lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
crates/mun_codegen/src/ir/function.rs
tdejager/mun
769bfe5a3a921bcc5289217e692f7f8cf19648ab
use super::try_convert_any_to_basic; use crate::ir::dispatch_table::DispatchTable; use crate::values::{ BasicValueEnum, CallSiteValue, FloatValue, FunctionValue, InstructionOpcode, IntValue, }; use crate::{IrDatabase, Module, OptimizationLevel}; use inkwell::builder::Builder; use inkwell::passes::{PassManager, PassManagerBuilder}; use inkwell::types::{AnyTypeEnum, BasicTypeEnum}; use inkwell::{FloatPredicate, IntPredicate}; use mun_hir::{ self as hir, ArithOp, BinaryOp, Body, CmpOp, Expr, ExprId, HirDisplay, InferenceResult, Literal, Ordering, Pat, PatId, Path, Resolution, Resolver, Statement, TypeCtor, }; use std::collections::HashMap; use std::mem; use std::sync::Arc; pub(crate) fn create_pass_manager( module: &Module, optimization_lvl: OptimizationLevel, ) -> PassManager<FunctionValue> { let pass_builder = PassManagerBuilder::create(); pass_builder.set_optimization_level(optimization_lvl); let function_pass_manager = PassManager::create(module); pass_builder.populate_function_pass_manager(&function_pass_manager); function_pass_manager.initialize(); function_pass_manager } pub(crate) fn gen_signature( db: &impl IrDatabase, f: hir::Function, module: &Module, ) -> FunctionValue { let name = f.name(db).to_string(); if let AnyTypeEnum::FunctionType(ty) = db.type_ir(f.ty(db)) { module.add_function(&name, ty, None) } else { panic!("not a function type") } } pub(crate) fn gen_body<'a, 'b, D: IrDatabase>( db: &'a D, hir_function: hir::Function, llvm_function: FunctionValue, module: &'a Module, llvm_functions: &'a HashMap<mun_hir::Function, FunctionValue>, dispatch_table: &'b DispatchTable, ) -> FunctionValue { let context = db.context(); let builder = context.create_builder(); let body_ir = context.append_basic_block(&llvm_function, "body"); builder.position_at_end(&body_ir); let mut code_gen = BodyIrGenerator::new( db, module, hir_function, llvm_function, llvm_functions, builder, dispatch_table, ); code_gen.gen_fn_body(); llvm_function } struct BodyIrGenerator<'a, 'b, D: IrDatabase> { db: &'a D, module: &'a Module, body: Arc<Body>, infer: Arc<InferenceResult>, builder: Builder, fn_value: FunctionValue, pat_to_param: HashMap<PatId, inkwell::values::BasicValueEnum>, pat_to_local: HashMap<PatId, inkwell::values::PointerValue>, pat_to_name: HashMap<PatId, String>, function_map: &'a HashMap<mun_hir::Function, FunctionValue>, dispatch_table: &'b DispatchTable, } impl<'a, 'b, D: IrDatabase> BodyIrGenerator<'a, 'b, D> { fn new( db: &'a D, module: &'a Module, f: hir::Function, fn_value: FunctionValue, function_map: &'a HashMap<mun_hir::Function, FunctionValue>, builder: Builder, dispatch_table: &'b DispatchTable, ) -> Self { let body = f.body(db); let infer = f.infer(db); BodyIrGenerator { db, module, body, infer, builder, fn_value, pat_to_param: HashMap::default(), pat_to_local: HashMap::default(), pat_to_name: HashMap::default(), function_map, dispatch_table, } } fn gen_fn_body(&mut self) { for (i, (pat, _ty)) in self.body.params().iter().enumerate() { let body = self.body.clone(); match &body[*pat] { Pat::Bind { name } => { let name = name.to_string(); let param = self.fn_value.get_nth_param(i as u32).unwrap(); param.set_name(&name); self.pat_to_param.insert(*pat, param); self.pat_to_name.insert(*pat, name); } Pat::Wild => {} Pat::Missing | Pat::Path(_) => unreachable!(), } } let ret_value = self.gen_expr(self.body.body_expr()); if let Some(value) = ret_value { self.builder.build_return(Some(&value)); } else { self.builder.build_return(None); } } fn gen_expr(&mut self, expr: ExprId) -> Option<inkwell::values::BasicValueEnum> { let body = self.body.clone(); let mut value = match &body[expr] { &Expr::Block { ref statements, tail, } => { for statement in statements.iter() { match statement { Statement::Let { pat, initializer, .. } => { self.gen_let_statement(*pat, *initializer); } Statement::Expr(expr) => { self.gen_expr(*expr); } }; } tail.and_then(|expr| self.gen_expr(expr)) } Expr::Path(ref p) => { let resolver = mun_hir::resolver_for_expr(self.body.clone(), self.db, expr); Some(self.gen_path_expr(p, expr, &resolver)) } Expr::Literal(lit) => match lit { Literal::Int(v) => Some( self.module .get_context() .i64_type() .const_int(unsafe { mem::transmute::<i64, u64>(*v) }, true) .into(), ), Literal::Float(v) => Some( self.module .get_context() .f64_type() .const_float(*v as f64) .into(), ), Literal::String(_) | Literal::Bool(_) => unreachable!(), }, &Expr::BinaryOp { lhs, rhs, op } => { Some(self.gen_binary_op(lhs, rhs, op.expect("missing op"))) } Expr::Call { ref callee, ref args, } => self.gen_call(*callee, &args).try_as_basic_value().left(), _ => unreachable!("unimplemented expr type"), }; value = value.map(|value| { match ( value.get_type(), try_convert_any_to_basic(self.db.type_ir(self.infer[expr].clone())), ) { (BasicTypeEnum::IntType(_), Some(target @ BasicTypeEnum::FloatType(_))) => self .builder .build_cast(InstructionOpcode::SIToFP, value, target, "implicit_cast"), (a, Some(b)) if a == b => value, _ => unreachable!("could not perform implicit cast"), } }); value } fn new_alloca_builder(&self) -> Builder { let temp_builder = Builder::create(); let block = self .builder .get_insert_block() .expect("at this stage there must be a block"); if let Some(first_instruction) = block.get_first_instruction() { temp_builder.position_before(&first_instruction); } else { temp_builder.position_at_end(&block); } temp_builder } fn gen_let_statement(&mut self, pat: PatId, initializer: Option<ExprId>) { let initializer = initializer.and_then(|expr| self.gen_expr(expr)); match &self.body[pat] { Pat::Bind { name } => { let builder = self.new_alloca_builder(); let ty = try_convert_any_to_basic(self.db.type_ir(self.infer[pat].clone())) .expect("expected basic type"); let ptr = builder.build_alloca(ty, &name.to_string()); self.pat_to_local.insert(pat, ptr); self.pat_to_name.insert(pat, name.to_string()); if let Some(value) = initializer { self.builder.build_store(ptr, value); }; } Pat::Wild => {} Pat::Missing | Pat::Path(_) => unreachable!(), } } fn gen_path_expr( &self, path: &Path, _expr: ExprId, resolver: &Resolver, ) -> inkwell::values::BasicValueEnum { let resolution = resolver .resolve_path_without_assoc_items(self.db, path) .take_values() .expect("unknown path"); match resolution { Resolution::LocalBinding(pat) => { if let Some(param) = self.pat_to_param.get(&pat) { *param } else if let Some(ptr) = self.pat_to_local.get(&pat) { let name = self.pat_to_name.get(&pat).expect("could not find pat name"); self.builder.build_load(*ptr, &name) } else { unreachable!("could not find the pattern.."); } } Resolution::Def(_) => panic!("no support for module definitions"), } } fn gen_binary_op(&mut self, lhs: ExprId, rhs: ExprId, op: BinaryOp) -> BasicValueEnum { let lhs_value = self.gen_expr(lhs).expect("no lhs value"); let rhs_value = self.gen_expr(rhs).expect("no rhs value"); let lhs_type = self.infer[lhs].clone(); let rhs_type = self.infer[rhs].clone(); match lhs_type.as_simple() { Some(TypeCtor::Float) => self.gen_binary_op_float( *lhs_value.as_float_value(), *rhs_value.as_float_value(), op, ), Some(TypeCtor::Int) => { self.gen_binary_op_int(*lhs_value.as_int_value(), *rhs_value.as_int_value(), op) } _ => unreachable!( "Unsupported operation {0}op{1}", lhs_type.display(self.db), rhs_type.display(self.db) ), } } fn gen_binary_op_float( &mut self, lhs: FloatValue, rhs: FloatValue, op: BinaryOp, ) -> BasicValueEnum { match op { BinaryOp::ArithOp(ArithOp::Add) => self.builder.build_float_add(lhs, rhs, "add").into(), BinaryOp::ArithOp(ArithOp::Subtract) => { self.builder.build_float_sub(lhs, rhs, "sub").into() } BinaryOp::ArithOp(ArithOp::Divide) => { self.builder.build_float_div(lhs, rhs, "div").into() } BinaryOp::ArithOp(ArithOp::Multiply) => { self.builder.build_float_mul(lhs, rhs, "mul").into() } BinaryOp::CmpOp(op) => { let (name, predicate) = match op { CmpOp::Eq { negated: false } => ("eq", FloatPredicate::OEQ), CmpOp::Eq { negated: true } => ("neq", FloatPredicate::ONE), CmpOp::Ord { ordering: Ordering::Less, strict: false, } => ("lesseq", FloatPredicate::OLE), CmpOp::Ord { ordering: Ordering::Less, strict: true, } => ("less", FloatPredicate::OLT), CmpOp::Ord { ordering: Ordering::Greater, strict: false, } => ("greatereq", FloatPredicate::OGE), CmpOp::Ord { ordering: Ordering::Greater, strict: true, } => ("greater", FloatPredicate::OGT), }; self.builder .build_float_compare(predicate, lhs, rhs, name) .into() } _ => unreachable!(), } } fn gen_binary_op_int(&mut self, lhs: IntValue, rhs: IntValue, op: BinaryOp) -> BasicValueEnum { match op { BinaryOp::ArithOp(ArithOp::Add) => self.builder.build_int_add(lhs, rhs, "add").into(), BinaryOp::ArithOp(ArithOp::Subtract) => { self.builder.build_int_sub(lhs, rhs, "sub").into() } BinaryOp::ArithOp(ArithOp::Divide) => { self.builder.build_int_signed_div(lhs, rhs, "div").into() } BinaryOp::ArithOp(ArithOp::Multiply) => { self.builder.build_int_mul(lhs, rhs, "mul").into() } BinaryOp::CmpOp(op) => { let (name, predicate) = match op { CmpOp::Eq { negated: false } => ("eq", IntPredicate::EQ), CmpOp::Eq { negated: true } => ("neq", IntPredicate::NE), CmpOp::Ord { ordering: Ordering::Less, strict: false, } => ("lesseq", IntPredicate::SLE), CmpOp::Ord { ordering: Ordering::Less, strict: true, } => ("less", IntPredicate::SLT), CmpOp::Ord { ordering: Ordering::Greater, strict: false, } => ("greatereq", IntPredicate::SGE), CmpOp::Ord { ordering: Ordering::Greater, strict: true, } => ("greater", IntPredicate::SGT), }; self.builder .build_int_compare(predicate, lhs, rhs, name) .into() } _ => unreachable!(), } } fn should_use_dispatch_table(&self) -> bool { true } fn gen_call(&mut self, callee: ExprId, args: &[ExprId]) -> CallSiteValue { let function = self.infer[callee] .as_function_def() .expect("expected a function expression"); let args: Vec<BasicValueEnum> = args .iter() .map(|expr| self.gen_expr(*expr).expect("expected a value")) .collect(); if self.should_use_dispatch_table() { let ptr_value = self.dispatch_table .gen_function_lookup(self.db, &self.builder, function); self.builder .build_call(ptr_value, &args, &function.name(self.db).to_string()) } else { let llvm_function = self .function_map .get(&function) .expect("missing function value for hir function"); self.builder .build_call(*llvm_function, &args, &function.name(self.db).to_string()) } } } trait OptName { fn get_name(&self) -> Option<&str>; fn set_name<T: AsRef<str>>(&self, name: T); } impl OptName for BasicValueEnum { fn get_name(&self) -> Option<&str> { match self { BasicValueEnum::ArrayValue(v) => v.get_name().to_str().ok(), BasicValueEnum::IntValue(v) => v.get_name().to_str().ok(), BasicValueEnum::FloatValue(v) => v.get_name().to_str().ok(), BasicValueEnum::PointerValue(v) => v.get_name().to_str().ok(), BasicValueEnum::StructValue(v) => v.get_name().to_str().ok(), BasicValueEnum::VectorValue(v) => v.get_name().to_str().ok(), } } fn set_name<T: AsRef<str>>(&self, name: T) { match self { BasicValueEnum::ArrayValue(v) => v.set_name(name.as_ref()), BasicValueEnum::IntValue(v) => v.set_name(name.as_ref()), BasicValueEnum::FloatValue(v) => v.set_name(name.as_ref()), BasicValueEnum::PointerValue(v) => v.set_name(name.as_ref()), BasicValueEnum::StructValue(v) => v.set_name(name.as_ref()), BasicValueEnum::VectorValue(v) => v.set_name(name.as_ref()), }; } }
use super::try_convert_any_to_basic; use crate::ir::dispatch_table::DispatchTable; use crate::values::{ BasicValueEnum, CallSiteValue, FloatValue, FunctionValue, InstructionOpcode, IntValue, }; use crate::{IrDatabase, Module, OptimizationLevel}; use inkwell::builder::Builder; use inkwell::passes::{PassManager, PassManagerBuilder}; use inkwell::types::{AnyTypeEnum, BasicTypeEnum}; use inkwell::{FloatPredicate, IntPredicate}; use mun_hir::{ self as hir, ArithOp, BinaryOp, Body, CmpOp, Expr, ExprId, HirDisplay, InferenceResult, Literal, Ordering, Pat, PatId, Path, Resolution, Resolver, Statement, TypeCtor, }; use std::collections::HashMap; use std::mem; use std::sync::Arc; pub(crate) fn create_pass_manager( module: &Module, optimization_lvl: OptimizationLevel, ) -> PassManager<FunctionValue> { let pass_builder = PassManagerBuilder::create(); pass_builder.set_optimization_level(optimization_lvl); let function_pass_manager = PassManager::create(module); pass_builder.populate_function_pass_manager(&function_pass_manager); function_pass_manager.initialize(); function_pass_manager } pub(crate) fn gen_signature( db: &impl IrDatabase, f: hir::Function, module: &Module, ) -> FunctionValue { let name = f.name(db).to_string(); if let AnyTypeEnum::FunctionType(ty) = db.type_ir(f.ty(db)) { module.add_function(&name, ty, None) } else { panic!("not a function type") } } pub(crate) fn gen_body<'a, 'b, D: IrDatabase>( db: &'a D, hir_function: hir::Function, llvm_function: FunctionValue, module: &'a Module, llvm_functions: &'a HashMap<mun_hir::Function, FunctionValue>, dispatch_table: &'b DispatchTable, ) -> FunctionValue { let context = db.context(); let builder = context.create_builder(); let body_ir = context.append_basic_block(&llvm_function, "body"); builder.position_at_end(&body_ir); let mut code_gen = BodyIrGenerator::new( db, module, hir_function, llvm_function, llvm_functions, builder, dispatch_table, ); code_gen.gen_fn_body(); llvm_function } struct BodyIrGenerator<'a, 'b, D: IrDatabase> { db: &'a D, module: &'a Module, body: Arc<Body>, infer: Arc<InferenceResult>, builder: Builder, fn_value: FunctionValue, pat_to_param: HashMap<PatId, inkwell::values::BasicValueEnum>, pat_to_local: HashMap<PatId, inkwell::values::PointerValue>, pat_to_name: HashMap<PatId, String>, function_map: &'a HashMap<mun_hir::Function, FunctionValue>, dispatch_table: &'b DispatchTable, } impl<'a, 'b, D: IrDatabase> BodyIrGenerator<'a, 'b, D> { fn new( db: &'a D, module: &'a Module, f: hir::Function, fn_value: FunctionValue, function_map: &'a HashMap<mun_hir::Function, FunctionValue>, builder: Builder, dispatch_table: &'b DispatchTable, ) -> Self { let body = f.body(db); let infer = f.infer(db); BodyIrGenerator { db, module, body, infer, builder, fn_value, pat_to_param: HashMap::default(), pat_to_local: HashMap::default(), pat_to_name: HashMap::default(), function_map, dispatch_table, } } fn gen_fn_body(&mut self) { for (i, (pat, _ty)) in self.body.params().iter().enumerate() { let body = self.body.clone(); match &body[*pat] { Pat::Bind { name } => { let name = name.to_string(); let param = self.fn_value.get_nth_param(i as u32).unwrap(); param.set_name(&name); self.pat_to_param.insert(*pat, param); self.pat_to_name.insert(*pat, name); } Pat::Wild => {} Pat::Missing | Pat::Path(_) => unreachable!(), } } let ret_value = self.gen_expr(self.body.body_expr()); if let Some(value) = ret_value { self.builder.build_return(Some(&value)); } else { self.builder.build_return(None); } } fn gen_expr(&mut self, expr: ExprId) -> Option<inkwell::values::BasicValueEnum> { let body = self.body.clone(); let mut value = match &body[expr] { &Expr::Block { ref statements, tail, } => { for statement in statements.iter() { match statement { Statement::Let { pat, initializer, .. } => { self.gen_let_statement(*pat, *initializer); } Statement::Expr(expr) => { self.gen_expr(*expr); } }; } tail.and_then(|expr| self.gen_expr(expr)) } Expr::Path(ref p) => { let resolver = mun_hir::resolver_for_expr(self.body.clone(), self.db, expr); Some(self.gen_path_expr(p, expr, &resolver)) } Expr::Literal(lit) => match lit { Literal::Int(v) => Some( self.module .get_context() .i64_type() .const_int(unsafe { mem::transmute::<i64, u64>(*v) }, true) .into(), ), Literal::Float(v) => Some( self.module .get_context() .f64_type() .const_float(*v as f64) .into(), ), Literal::String(_) | Literal::Bool(_) => unreachable!(), }, &Expr::BinaryOp { lhs, rhs, op } => { Some(self.gen_binary_op(lhs, rhs, op.expect("missing op"))) } Expr::Call { ref callee, ref args, } => self.gen_call(*callee, &args).try_as_basic_value().left(), _ => unreachable!("unimplemented expr type"), }; value = value.map(|value| { match ( value.get_type(), try_convert_any_to_basic(self.db.type_ir(self.infer[expr].clone())), ) { (BasicTypeEnum::IntType(_), Some(target @ BasicTypeEnum::FloatType(_))) => self .builder .build_cast(InstructionOpcode::SIToFP, value, target, "implicit_cast"), (a, Some(b)) if a == b => value, _ => unreachable!("could not perform implicit cast"), } }); value } fn new_alloca_builder(&self) -> Builder { let temp_builder = Builder::create(); let block = self .builder .get_insert_blo
Resolution::Def(_) => panic!("no support for module definitions"), } } fn gen_binary_op(&mut self, lhs: ExprId, rhs: ExprId, op: BinaryOp) -> BasicValueEnum { let lhs_value = self.gen_expr(lhs).expect("no lhs value"); let rhs_value = self.gen_expr(rhs).expect("no rhs value"); let lhs_type = self.infer[lhs].clone(); let rhs_type = self.infer[rhs].clone(); match lhs_type.as_simple() { Some(TypeCtor::Float) => self.gen_binary_op_float( *lhs_value.as_float_value(), *rhs_value.as_float_value(), op, ), Some(TypeCtor::Int) => { self.gen_binary_op_int(*lhs_value.as_int_value(), *rhs_value.as_int_value(), op) } _ => unreachable!( "Unsupported operation {0}op{1}", lhs_type.display(self.db), rhs_type.display(self.db) ), } } fn gen_binary_op_float( &mut self, lhs: FloatValue, rhs: FloatValue, op: BinaryOp, ) -> BasicValueEnum { match op { BinaryOp::ArithOp(ArithOp::Add) => self.builder.build_float_add(lhs, rhs, "add").into(), BinaryOp::ArithOp(ArithOp::Subtract) => { self.builder.build_float_sub(lhs, rhs, "sub").into() } BinaryOp::ArithOp(ArithOp::Divide) => { self.builder.build_float_div(lhs, rhs, "div").into() } BinaryOp::ArithOp(ArithOp::Multiply) => { self.builder.build_float_mul(lhs, rhs, "mul").into() } BinaryOp::CmpOp(op) => { let (name, predicate) = match op { CmpOp::Eq { negated: false } => ("eq", FloatPredicate::OEQ), CmpOp::Eq { negated: true } => ("neq", FloatPredicate::ONE), CmpOp::Ord { ordering: Ordering::Less, strict: false, } => ("lesseq", FloatPredicate::OLE), CmpOp::Ord { ordering: Ordering::Less, strict: true, } => ("less", FloatPredicate::OLT), CmpOp::Ord { ordering: Ordering::Greater, strict: false, } => ("greatereq", FloatPredicate::OGE), CmpOp::Ord { ordering: Ordering::Greater, strict: true, } => ("greater", FloatPredicate::OGT), }; self.builder .build_float_compare(predicate, lhs, rhs, name) .into() } _ => unreachable!(), } } fn gen_binary_op_int(&mut self, lhs: IntValue, rhs: IntValue, op: BinaryOp) -> BasicValueEnum { match op { BinaryOp::ArithOp(ArithOp::Add) => self.builder.build_int_add(lhs, rhs, "add").into(), BinaryOp::ArithOp(ArithOp::Subtract) => { self.builder.build_int_sub(lhs, rhs, "sub").into() } BinaryOp::ArithOp(ArithOp::Divide) => { self.builder.build_int_signed_div(lhs, rhs, "div").into() } BinaryOp::ArithOp(ArithOp::Multiply) => { self.builder.build_int_mul(lhs, rhs, "mul").into() } BinaryOp::CmpOp(op) => { let (name, predicate) = match op { CmpOp::Eq { negated: false } => ("eq", IntPredicate::EQ), CmpOp::Eq { negated: true } => ("neq", IntPredicate::NE), CmpOp::Ord { ordering: Ordering::Less, strict: false, } => ("lesseq", IntPredicate::SLE), CmpOp::Ord { ordering: Ordering::Less, strict: true, } => ("less", IntPredicate::SLT), CmpOp::Ord { ordering: Ordering::Greater, strict: false, } => ("greatereq", IntPredicate::SGE), CmpOp::Ord { ordering: Ordering::Greater, strict: true, } => ("greater", IntPredicate::SGT), }; self.builder .build_int_compare(predicate, lhs, rhs, name) .into() } _ => unreachable!(), } } fn should_use_dispatch_table(&self) -> bool { true } fn gen_call(&mut self, callee: ExprId, args: &[ExprId]) -> CallSiteValue { let function = self.infer[callee] .as_function_def() .expect("expected a function expression"); let args: Vec<BasicValueEnum> = args .iter() .map(|expr| self.gen_expr(*expr).expect("expected a value")) .collect(); if self.should_use_dispatch_table() { let ptr_value = self.dispatch_table .gen_function_lookup(self.db, &self.builder, function); self.builder .build_call(ptr_value, &args, &function.name(self.db).to_string()) } else { let llvm_function = self .function_map .get(&function) .expect("missing function value for hir function"); self.builder .build_call(*llvm_function, &args, &function.name(self.db).to_string()) } } } trait OptName { fn get_name(&self) -> Option<&str>; fn set_name<T: AsRef<str>>(&self, name: T); } impl OptName for BasicValueEnum { fn get_name(&self) -> Option<&str> { match self { BasicValueEnum::ArrayValue(v) => v.get_name().to_str().ok(), BasicValueEnum::IntValue(v) => v.get_name().to_str().ok(), BasicValueEnum::FloatValue(v) => v.get_name().to_str().ok(), BasicValueEnum::PointerValue(v) => v.get_name().to_str().ok(), BasicValueEnum::StructValue(v) => v.get_name().to_str().ok(), BasicValueEnum::VectorValue(v) => v.get_name().to_str().ok(), } } fn set_name<T: AsRef<str>>(&self, name: T) { match self { BasicValueEnum::ArrayValue(v) => v.set_name(name.as_ref()), BasicValueEnum::IntValue(v) => v.set_name(name.as_ref()), BasicValueEnum::FloatValue(v) => v.set_name(name.as_ref()), BasicValueEnum::PointerValue(v) => v.set_name(name.as_ref()), BasicValueEnum::StructValue(v) => v.set_name(name.as_ref()), BasicValueEnum::VectorValue(v) => v.set_name(name.as_ref()), }; } }
ck() .expect("at this stage there must be a block"); if let Some(first_instruction) = block.get_first_instruction() { temp_builder.position_before(&first_instruction); } else { temp_builder.position_at_end(&block); } temp_builder } fn gen_let_statement(&mut self, pat: PatId, initializer: Option<ExprId>) { let initializer = initializer.and_then(|expr| self.gen_expr(expr)); match &self.body[pat] { Pat::Bind { name } => { let builder = self.new_alloca_builder(); let ty = try_convert_any_to_basic(self.db.type_ir(self.infer[pat].clone())) .expect("expected basic type"); let ptr = builder.build_alloca(ty, &name.to_string()); self.pat_to_local.insert(pat, ptr); self.pat_to_name.insert(pat, name.to_string()); if let Some(value) = initializer { self.builder.build_store(ptr, value); }; } Pat::Wild => {} Pat::Missing | Pat::Path(_) => unreachable!(), } } fn gen_path_expr( &self, path: &Path, _expr: ExprId, resolver: &Resolver, ) -> inkwell::values::BasicValueEnum { let resolution = resolver .resolve_path_without_assoc_items(self.db, path) .take_values() .expect("unknown path"); match resolution { Resolution::LocalBinding(pat) => { if let Some(param) = self.pat_to_param.get(&pat) { *param } else if let Some(ptr) = self.pat_to_local.get(&pat) { let name = self.pat_to_name.get(&pat).expect("could not find pat name"); self.builder.build_load(*ptr, &name) } else { unreachable!("could not find the pattern.."); } }
random
[ { "content": "/// Build the declared type of a function. This should not need to look at the\n\n/// function body.\n\nfn type_for_fn(_db: &impl HirDatabase, def: Function) -> Ty {\n\n Ty::simple(TypeCtor::FnDef(def))\n\n}\n\n\n", "file_path": "crates/mun_hir/src/ty/lower.rs", "rank": 0, "score": ...
Rust
src/algebra.rs
doxxx/raytracer
21c92437ffd07d0434f8e095ce787fe23f42658c
/* Transcribed from http://cosinekitty.com/raytrace/rtsource.zip. Original written by Don Cross. Adapted to Rust by Gordon Tyler. */ #![allow(non_snake_case)] use num_complex::Complex; use std::f64::consts::PI; const TOLERANCE: f64 = 1.0e-8; const TWO_PI: f64 = 2.0 * PI; fn complex(re: f64) -> Complex<f64> { Complex { re, im: 0.0 } } fn complex2(re: f64, im: f64) -> Complex<f64> { Complex { re, im } } fn is_zero(c: Complex<f64>) -> bool { c.re.abs() < TOLERANCE && c.im.abs() < TOLERANCE } fn filter_real(c: Vec<Complex<f64>>) -> Vec<f64> { c.into_iter().filter(|c| c.im.abs() < TOLERANCE).map(|c| c.re).collect() } fn cbrt(c: Complex<f64>, n: isize) -> Complex<f64> { let rho = c.norm().powf(1.0 / 3.0); let theta = ((TWO_PI * n as f64) + c.arg()) / 3.0; complex2( rho * theta.cos(), rho * theta.sin(), ) } pub fn solve_quadratic(a: Complex<f64>, b: Complex<f64>, c: Complex<f64>) -> Vec<Complex<f64>> { if is_zero(a) { if is_zero(b) { Vec::with_capacity(0) } else { vec![-c / b] } } else { let radicand = b * b - 4.0 * a * c; if is_zero(radicand) { vec![-b / (2.0 * a)] } else { let r = radicand.sqrt(); let d = 2.0 * a; vec![(-b + r) / d, (-b - r) / d] } } } pub fn solve_cubic(a: Complex<f64>, b: Complex<f64>, c: Complex<f64>, d: Complex<f64>) -> Vec<Complex<f64>> { if is_zero(a) { solve_quadratic(b, c, d) } else { let b = b / a; let c = c / a; let d = d / a; let S = b / 3.0; let D = c / 3.0 - S * S; let E = S * S * S + (d - S * c) / 2.0; let F_root = (E * E + D * D * D).sqrt(); let mut F = -F_root - E; if is_zero(F) { F = F_root - E; } (0..3).into_iter().map(|i| { let G = cbrt(F, i); G - D / G - S }).collect() } } pub fn solve_quartic( a: Complex<f64>, b: Complex<f64>, c: Complex<f64>, d: Complex<f64>, e: Complex<f64>, ) -> Vec<Complex<f64>> { if is_zero(a) { solve_cubic(b, c, d, e) } else { let b = b / a; let c = c / a; let d = d / a; let e = e / a; let b2 = b * b; let b3 = b * b2; let b4 = b * b3; let alpha = (-3.0 / 8.0) * b2 + c; let beta = b3 / 8.0 - b * c / 2.0 + d; let gamma = (-3.0 / 256.0) * b4 + b2 * c / 16.0 - b * d / 4.0 + e; let alpha2 = alpha * alpha; let t = -b / 4.0; if is_zero(beta) { let rad = (alpha2 - 4.0 * gamma).sqrt(); let r1 = ((-alpha + rad) / 2.0).sqrt(); let r2 = ((-alpha - rad) / 2.0).sqrt(); vec![t + r1, t - r1, t + r2, t - r2] } else { let alpha3 = alpha * alpha2; let P = -(alpha2 / 12.0 + gamma); let Q = -alpha3 / 108.0 + alpha * gamma / 3.0 - beta * beta / 8.0; let R = -Q / 2.0 + (Q * Q / 4.0 + P * P * P / 27.0).sqrt(); let U = cbrt(R, 0); let mut y = (-5.0 / 6.0) * alpha + U; if is_zero(U) { y -= cbrt(Q, 0); } else { y -= P / (3.0 * U); } let W = (alpha + 2.0 * y).sqrt(); let r1 = (-(3.0 * alpha + 2.0 * y + 2.0 * beta / W)).sqrt(); let r2 = (-(3.0 * alpha + 2.0 * y - 2.0 * beta / W)).sqrt(); vec![ t + (W - r1) / 2.0, t + (W + r1) / 2.0, t + (-W - r2) / 2.0, t + (-W + r2) / 2.0, ] } } } pub fn solve_quartic_f64(a: f64, b: f64, c: f64, d: f64, e: f64) -> Vec<f64> { filter_real(solve_quartic( complex(a), complex(b), complex(c), complex(d), complex(e), )) } #[cfg(test)] mod tests { use super::*; fn check_roots(known: &[Complex<f64>], found: &[Complex<f64>]) { const MAX_ROOTS: usize = 4; assert!(found.len() <= MAX_ROOTS, "num roots out of bounds: {}", found.len()); let mut used = [false, false, false, false]; for k in 0..found.len() { let mut ok = false; for f in 0..found.len() { if !used[f] && is_zero(known[k] - found[f]) { ok = true; used[f] = true; break; } } if !ok { panic!( "Solver produced incorrect root value(s)\n\ Known correct roots: {:?}\n\ Found roots: {:?}", known, found ); } } } fn validate_polynomial(order: usize, poly: &[Complex<f64>], root: Complex<f64>) { let mut power = complex2(1.0, 0.0); let mut sum = complex2(0.0, 0.0); for i in 0..order { sum += poly[i] * power; power *= root; } assert!(is_zero(sum), "invalid polynomial"); } fn test_known_quadratic_roots(M: Complex<f64>, K: Complex<f64>, L: Complex<f64>) { let a = M; let b = -M * (K + L); let c = M * K * L; let poly = [c, b, a]; validate_polynomial(3, &poly, K); validate_polynomial(3, &poly, L); let found = solve_quadratic(a, b, c); let expected_roots = if is_zero(K - L) { 1 } else { 2 }; assert_eq!(expected_roots, found.len()); let known = [K, L]; check_roots(&known, &found); } fn test_known_cubic_roots(M: Complex<f64>, K: Complex<f64>, L: Complex<f64>, N: Complex<f64>) { let a = M; let b = -M*(K+L+N); let c = M*(K*L + N*K + N*L); let d = -M*K*L*N; let poly = [d, c, b, a]; validate_polynomial(4, &poly, K); validate_polynomial(4, &poly, L); validate_polynomial(4, &poly, N); let found = solve_cubic(a, b, c, d); let expected_roots = 3; assert_eq!(expected_roots, found.len()); let known = [K, L, N]; check_roots(&known, &found); } fn test_known_quartic_roots(m: Complex<f64>, a: Complex<f64>, b: Complex<f64>, c: Complex<f64>, d: Complex<f64>) { let A = m; let B = -m*(a + b + c + d); let C = m*(a*b + c*d + (a + b)*(c + d)); let D = -m*(c*d*(a + b) + a*b*(c + d)); let E = m*a*b*c*d; let poly = [E, D, C, B, A]; validate_polynomial(5, &poly, a); validate_polynomial(5, &poly, b); validate_polynomial(5, &poly, c); validate_polynomial(5, &poly, d); let found = solve_quartic(A, B, C, D, E); let expected_roots = 4; assert_eq!(expected_roots, found.len()); let known = [a, b, c, d]; check_roots(&known, &found); } #[test] pub fn quadratic() { test_known_quadratic_roots(complex2(-2.3,4.8), complex2(3.2,-4.1), complex2(-2.5,7.7)); test_known_quadratic_roots(complex2(5.5,4.4), complex2(8.2,-2.1), complex2(8.2,-2.1)); } #[test] pub fn cubic() { test_known_cubic_roots(complex(1.0), complex(2.0), complex(3.0), complex(4.0)); test_known_cubic_roots(complex2(-2.3,4.8), complex2(3.2,-4.1), complex2(-2.5,7.7), complex2(53.0,-23.9)); } #[test] pub fn quartic() { test_known_quartic_roots(complex(1.0), complex(2.0), complex(3.0), complex(4.0), complex(5.0)); test_known_quartic_roots(complex(1.0), complex(3.2), complex(2.5), complex(53.0), complex(-8.7)); test_known_quartic_roots(complex2(-2.3,4.8), complex2(3.2,-4.1), complex2(-2.5,7.7), complex2(53.0,-23.9), complex2(-9.2,-8.7)); } }
/* Transcribed from http://cosinekitty.com/raytrace/rtsource.zip. Original written by Don Cross. Adapted to Rust by Gordon Tyler. */ #![allow(non_snake_case)] use num_complex::Complex; use std::f64::consts::PI; const TOLERANCE: f64 = 1.0e-8; const TWO_PI: f64 = 2.0 * PI; fn complex(re: f64) -> Complex<f64> { Complex { re, im: 0.0 } } fn complex2(re: f64, im: f64) -> Complex<f64> { Complex { re, im } } fn is_zero(c: Complex<f64>) -> bool { c.re.abs() < TOLERANCE && c.im.abs() < TOLERANCE } fn filter_real(c: Vec<Complex<f64>>) -> Vec<f64> { c.into_iter().filter(|c| c.im.abs() < TOLERANCE).map(|c| c.re).collect() } fn cbrt(c: Complex<f64>, n: isize) -> Complex<f64> { let rho = c.norm().powf(1.0 / 3.0); let theta = ((TWO_PI * n as f64) + c.arg()) / 3.0; complex2( rho * theta.cos(), rho * theta.sin(), ) } pub fn solve_quadratic(a: Complex<f64>, b: Complex<f64>, c: Complex<f64>) -> Vec<Complex<f64>> { if is_zero(a) { if is_zero(b) { Vec::with_capacity(0) } else { vec![-c / b] } } else { let radicand = b * b - 4.0 * a * c; if is_zero(radicand) { vec![-b / (2.0 * a)] } else { let r = radicand.sqrt(); let d = 2.0 * a; vec![(-b + r) / d, (-b - r) / d] } } } pub fn solve_cubic(a: Complex<f64>, b: Complex<f64>, c: Complex<f64>, d: Complex<f64>) -> Vec<Complex<f64>> { if is_zero(a) { solve_quadratic(b, c, d) } else { let b = b / a; let c = c / a; let d = d / a; let S = b / 3.0; let D = c / 3.0 - S * S; let E = S * S * S + (d - S * c) / 2.0; let F_root = (E * E + D * D * D).sqrt(); let mut F = -F_root - E; if is_zero(F) { F = F_root - E; } (0..3).into_iter().map(|i| { let G = cbrt(F, i); G - D / G - S }).collect() } } pub fn solve_quartic( a: Complex<f64>, b: Complex<f64>, c: Complex<f64>, d: Complex<f64>, e: Complex<f64>, ) -> Vec<Complex<f64>> { if is_zero(a) { solve_cubic(b, c, d, e) } else { let b = b / a; let c = c / a; let d = d / a; let e = e / a; let b2 = b * b; let b3 = b * b2; let b4 = b * b3; let alpha = (-3.0 / 8.0) * b2 + c; let beta = b3 / 8.0 - b * c / 2.0 + d; let gamma = (-3.0 / 256.0) * b4 + b2 * c / 16.0 - b * d / 4.0 + e; let alpha2 = alpha * alpha; let t = -b / 4.0; if is_zero(beta) { let rad = (alpha2 - 4.0 * gamma).sqrt(); let r1 = ((-alpha + rad) / 2.0).sqrt(); let r2 = ((-alpha - rad) / 2.0).sqrt(); vec![t + r1, t - r1, t + r2, t - r2] } else { let alpha3 = alpha * alpha2; let P = -(alpha2 / 12.0 + gamma); let Q = -alpha3 / 108.0 + alpha * gamma / 3.0 - beta * beta / 8.0; let R = -Q / 2.0 + (Q * Q / 4.0 + P * P * P / 27.0).sqrt(); let U = cbrt(R, 0); let mut y = (-5.0 / 6.0) * alpha + U; if is_zero(U) { y -= cbrt(Q, 0); } else { y -= P / (3.0 * U); } let W = (alpha + 2.0 * y).sqrt(); let r1 = (-(3.0 * alpha + 2.0 * y + 2.0 * beta / W)).sqrt(); let r2 = (-(3.0 * alpha + 2.0 * y - 2.0 * beta / W)).sqrt(); vec![ t + (W - r1) / 2.0, t + (W + r1) / 2.0, t + (-W - r2) / 2.0, t + (-W + r2) / 2.0, ] } } } pub fn solve_quartic_f64(a: f64, b: f64, c: f64, d: f64, e: f64) -> Vec<f64> { filter_real(solve_quartic( complex(a), complex(b), complex(c), complex(d), complex(e), )) } #[cfg(test)] mod tests { use super::*; fn check_roots(known: &[Complex<f64>], found: &[Complex<f64>]) { const MAX_ROOTS: usize = 4; assert!(found.len() <= MAX_ROOTS, "num roots out of bounds: {}", found.len()); let mut used = [false, false, false, false]; for k in 0..found.len() { let mut ok = false; for f in 0..found.len() { if !used[f] && is_zero(known[k] - found[f]) { ok = true; used[f] = true; break; } } if !ok { panic!( "Solver produced incorrect root value(s)\n\ Known correct roots: {:?}\n\ Found roots: {:?}", known, found ); } } } fn validate_polynomial(order: usize, poly: &[Complex<f64>], root: Complex<f64>) { let mut power = complex2(1.0, 0.0); let mut sum = complex2(0.0, 0.0); for i in 0..order { sum += poly[i] * power; power *= root; } assert!(is_zero(sum), "invalid polynomial"); } fn test_known_quadratic_roots(M: Complex<f64>, K: Complex<f64>, L: Complex<f64>) { let a = M; let b = -M * (K + L); let c = M * K * L; let poly = [c, b, a]; validate_polynomial(3, &poly, K); validate_polynomial(3, &poly, L); let found = solve_quadratic(a, b, c); let expected_roots = if is_zero(K - L) { 1 } else { 2 }; assert_eq!(expected_roots, found.len()); let known = [K, L]; check_roots(&known, &found); } fn test_known_cubic_roots(M: Complex<f64>, K: Complex<f64>, L: Complex<f64>, N: Complex<f64>) { let a = M; let b = -M*(K+L+N); let c = M*(K*L + N*K + N*L); let d = -M*K*L*N; let poly = [d, c, b, a]; validate_polynomial(4, &poly, K); validate_polynomial(4, &poly, L); validate_polynomial(4, &poly, N); let found = solve_cubic(a, b, c, d); let expected_roots = 3; assert_eq!(expected_roots, found.len()); let known = [K, L, N]; check_roots(&known, &found); } fn test_known_quartic_roots(m: Complex<f64>, a: Complex<f64>, b: Complex<f64>, c: Complex<f64>, d: Complex<f64>) { let A = m; let B = -m*(a + b + c + d); let C = m*(a*b + c*d + (a + b)*(c + d)); let D = -m*(c*d*(a + b) + a*b*(c + d)); let E = m*a*b*c*d; let poly = [E, D, C, B, A]; validate_polynomial(5, &poly, a); validate_polynomial(5, &poly, b); validate_polynomial(5, &poly, c); validate_polynomial(5, &poly, d); let found = solve_quartic(A, B, C, D, E); let expected_roots = 4; assert_eq!(expected_roots, found.len()); let known = [a, b, c, d]; check_roots(&known, &found); } #[test] pub fn quadratic() { test_known_quadratic_roots(complex2(-2.3,4.8), complex2(3.2,-4.1), complex2(-2.5,7.7)); test_known_quadratic_roots(complex2(5.5,4.4), complex2(8.2,-2.1), complex2(8.2,-2.1)); } #[test] pub fn cubic() { test_known_cubic_roots(complex(1.0), complex(2.0), complex(3.
complex(5.0)); test_known_quartic_roots(complex(1.0), complex(3.2), complex(2.5), complex(53.0), complex(-8.7)); test_known_quartic_roots(complex2(-2.3,4.8), complex2(3.2,-4.1), complex2(-2.5,7.7), complex2(53.0,-23.9), complex2(-9.2,-8.7)); } }
0), complex(4.0)); test_known_cubic_roots(complex2(-2.3,4.8), complex2(3.2,-4.1), complex2(-2.5,7.7), complex2(53.0,-23.9)); } #[test] pub fn quartic() { test_known_quartic_roots(complex(1.0), complex(2.0), complex(3.0), complex(4.0),
random
[ { "content": "fn solve_quadratic(a: f64, b: f64, c: f64) -> Option<(f64, f64)> {\n\n let discr = b * b - 4.0 * a * c;\n\n if discr < 0.0 {\n\n return None;\n\n } else if discr == 0.0 {\n\n let x = -0.5 * b / a;\n\n return Some((x, x));\n\n } else {\n\n let q = if b > 0.0 ...
Rust
src/tables/parts.rs
jaredwolff/eagle-plm
aae5fd8f0ca6d30d295af99eed038b2195fa073b
extern crate diesel; use prettytable::{row, Table}; use serde::Deserialize; use crate::{models::*, *}; use diesel::prelude::*; use std::fs::File; use std::io::BufReader; #[derive(Debug, Deserialize)] struct Record { pn: String, mpn: String, desc: String, } pub fn create(app: &mut crate::Application) { let pn = app.prompt.ask_text_entry("Part Number: "); let mpn = app.prompt.ask_text_entry("Manufacturer Part Number: "); let desc = app.prompt.ask_text_entry("Description: "); let ver = app.prompt.ask_text_entry("Version: "); let ver: i32 = ver.trim().parse().expect("Invalid version number!"); let part = NewUpdatePart { pn: &pn, mpn: &mpn, descr: &desc, ver: &ver, mqty: &1, }; let found = find_part_by_pn(&app.conn, &pn); if let Ok(found) = found { let question = format!("{} already exists! Would you like to update it?", pn); let update = app.prompt.ask_yes_no_question(&question); if update { update_part(&app.conn, &found.id, &part).expect("Unable to update part!"); println!("{} updated!", pn); } } else { create_part(&app.conn, &part).expect("Unable to create part!"); } } pub fn rename(app: &mut crate::Application) { let pn = app.prompt.ask_text_entry("Part Number: "); let newpn = app.prompt.ask_text_entry("New Part Number: "); rename_part(&app.conn, &pn, &newpn).expect("Unable to change pn"); } pub fn create_by_csv(app: &mut crate::Application, filename: &str) { let file = File::open(filename).unwrap(); let file = BufReader::new(file); let mut records: Vec<Record> = Vec::new(); let mut rdr = csv::Reader::from_reader(file); for result in rdr.deserialize() { let record: Record = result.expect("Unable to deserialize."); println!("Processing: {:?}", record); records.push(record); } for record in records { let part = models::NewUpdatePart { pn: &record.pn, mpn: &record.mpn, descr: &record.desc, ver: &1, mqty: &1, }; let found = find_part_by_pn(&app.conn, &part.pn); if let Ok(found) = found { if found.mpn != part.mpn || found.descr != part.descr || found.ver != *part.ver { let question = format!("{} already exists! Would you like to update it?", part.pn); let mut table = Table::new(); table.add_row(row![ "Current:", found.pn, found.mpn, found.descr, found.ver ]); table.add_row(row!["Change to:", part.pn, part.mpn, part.descr, part.ver]); table.printstd(); let update = app.prompt.ask_yes_no_question(&question); if update { update_part(&app.conn, &found.id, &part).expect("Unable to update part!"); println!("{} updated!", part.pn); } } } else { println!("Creating: {:?}", part); create_part(&app.conn, &part).expect("Unable to create part!"); } } } pub fn delete(app: &mut crate::Application) { let part = app.prompt.ask_text_entry("Part Number: "); let part = find_part_by_pn(&app.conn, &part).expect("Unable to find part!"); let question = format!("Would you like to delete {}?", part.pn); let delete = app.prompt.ask_yes_no_question(&question); if delete { let res = delete_part(&app.conn, &part.id); if res.is_err() { panic!("Error deleting part {}.", part.pn); } else { println!("Deleted {}", part.pn); } } } pub fn show(app: &mut crate::Application) { use crate::schema::*; let mut table = Table::new(); let results = parts::dsl::parts .load::<models::Part>(&app.conn) .expect("Error loading parts"); println!("Displaying {} parts", results.len()); table.add_row(row!["PN", "MPN", "Desc", "Mqty", "Ver"]); for part in results { table.add_row(row![part.pn, part.mpn, part.descr, part.mqty, part.ver]); } table.printstd(); }
extern crate diesel; use prettytable::{row, Table}; use serde::Deserialize; use crate::{models::*, *}; use diesel::prelude::*; use std::fs::File; use std::io::BufReader; #[derive(Debug, Deserialize)] struct Record { pn: String, mpn: String, desc: String, } pub fn create(app: &mut crate::Application) { let pn = app.prompt.ask_text_entry("Part Number: "); let mpn = app.prompt.ask_text_entry("Manufacturer Part Number: "); let desc = app.prompt.ask_text_entry("Description: "); let ver = app.prompt.ask_text_entry("Version: "); let ver: i32 = ver.trim().parse().expect("Invalid version number!"); let part = NewUpdatePart { pn: &pn, mpn: &mpn, descr: &desc, ver: &ver, mqty: &1, }; let found = find_part_by_pn(&app.conn, &pn); if let Ok(found) = found { let question = format!("{} already exists! Would you like to update it?", pn); let update = app.prompt.ask_yes_no_question(&question); if update { update_part(&app.conn, &found.id, &part).expect("Unable to update part!"); println!("{} updated!", pn); } } else { create_part(&app.conn, &part).expect("Unable to create part!"); } } pub fn rename(app: &mut crate::Application) { let pn = app.prompt.ask_text_entry("Part Number: "); let newpn = app.prompt.ask_text_entry("New Part Number: "); rename_part(&app.conn, &pn, &newpn).expect("Unable to change pn"); } pub fn create_by_csv(app: &mut crate::Application, filename: &str) { let file = File::open(filename).unwrap(); let file = BufReader::new(file); let mut records: Vec<Record> = Vec::new(); let mut rdr = csv::Reader::from_reader(file); for result in rdr.deserialize() { let record: Record = result.expect("Unable to deserialize."); println!("Processing: {:?}", record); records.push(record); } for record in records { let part = models::NewUpdatePart { pn: &record.pn, mpn: &record.mpn, descr: &record.desc, ver: &1, mqty: &1, }; let found = find_part_by_pn(&app.conn, &part.pn); if let Ok(found) = found { if found.mpn != part.mpn || found.descr != part.descr || found.ver != *part.ver { let question = format!("{} already exists! Would you like to update it?", part.pn); let mut table = Table::new(); table.add_row(row![ "Current:", found.pn, found.mpn, found.descr, found.ver ]); table.add_row(row!["Change to:", part.pn, part.mpn, part.descr, part.ver]); table.printstd(); let update = app.prompt.ask_yes_no_question(&question); if update {
pub fn delete(app: &mut crate::Application) { let part = app.prompt.ask_text_entry("Part Number: "); let part = find_part_by_pn(&app.conn, &part).expect("Unable to find part!"); let question = format!("Would you like to delete {}?", part.pn); let delete = app.prompt.ask_yes_no_question(&question); if delete { let res = delete_part(&app.conn, &part.id); if res.is_err() { panic!("Error deleting part {}.", part.pn); } else { println!("Deleted {}", part.pn); } } } pub fn show(app: &mut crate::Application) { use crate::schema::*; let mut table = Table::new(); let results = parts::dsl::parts .load::<models::Part>(&app.conn) .expect("Error loading parts"); println!("Displaying {} parts", results.len()); table.add_row(row!["PN", "MPN", "Desc", "Mqty", "Ver"]); for part in results { table.add_row(row![part.pn, part.mpn, part.descr, part.mqty, part.ver]); } table.printstd(); }
update_part(&app.conn, &found.id, &part).expect("Unable to update part!"); println!("{} updated!", part.pn); } } } else { println!("Creating: {:?}", part); create_part(&app.conn, &part).expect("Unable to create part!"); } } }
function_block-function_prefix_line
[ { "content": "/// Function used to show parts in BOM\n\npub fn show(app: &mut crate::Application, part_number: &str, version: &Option<i32>) {\n\n use crate::schema::*;\n\n\n\n // Find the part\n\n let part = find_part_by_pn(&app.conn, &part_number);\n\n\n\n if part.is_err() {\n\n println!(\"{...
Rust
2018/dec03/rs/src/main.rs
henrywallace/advent-of-code
f50d00b47603117e25c18d4f645fadd451fb6be2
extern crate clap; #[macro_use] extern crate lazy_static; extern crate regex; use std::error::Error; use std::fs::File; use std::io::{BufReader, BufRead}; use clap::{Arg, App}; use std::collections::{HashMap, HashSet}; use std::str::FromStr; use regex::Regex; #[derive(Debug)] struct Claim { id: u32, offset: (u32, u32), size: (u32, u32), } impl FromStr for Claim { type Err = Box<Error>; fn from_str(s: &str) -> Result<Self, Self::Err> { lazy_static! { static ref RE: Regex = Regex::new(r"(?x) \#(?P<id>\d+)\s+@\s+ (?P<x>\d+),(?P<y>\d+):\s+ (?P<w>\d+)x(?P<h>\d+) ").unwrap(); } match RE.captures(s) { Some(caps) => { Ok(Claim{ id: caps["id"].parse()?, offset: (caps["x"].parse()?, caps["y"].parse()?), size: (caps["w"].parse()?, caps["h"].parse()?), }) }, None => Err(Box::<Error>::from(format!("failed to create claim from: {:?}", s))), } } } impl Claim { fn update_fabric(&self, fabric: &mut Fabric) { for i in self.offset.0..(self.offset.0+self.size.0) { for j in self.offset.1..(self.offset.1+self.size.1) { fabric.entry((i, j)) .or_insert(vec![]) .push(self.id); } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_fabric_one_simple() { let claim: Claim = "#1 @ 1,2: 1x2".parse().unwrap(); let mut actual = Fabric::new(); claim.update_fabric(&mut actual); let expect: Fabric = [ ((1, 2), vec![1]), ((1, 3), vec![1]), ].iter().cloned().collect(); assert_eq!(expect, actual); } #[test] fn test_fabric_two_overlap() { let claim1: Claim = "#1 @ 0,0: 2x1".parse().unwrap(); let claim2: Claim = "#2 @ 1,0: 2x1".parse().unwrap(); let mut actual = Fabric::new(); claim1.update_fabric(&mut actual); claim2.update_fabric(&mut actual); let expect: Fabric = [ ((0, 0), vec![1]), ((1, 0), vec![1, 2]), ((2, 0), vec![2]), ].iter().cloned().collect(); assert_eq!(expect, actual); } } type Fabric = HashMap<(u32, u32), Vec<u32>>; fn part1(input: &str) -> Result<(), Box<Error>> { let mut fabric = Fabric::new(); let f = File::open(input)?; let buf = BufReader::new(f); for line in buf.lines() { let claim: Claim = line?.parse()?; claim.update_fabric(&mut fabric); } let mut total = 0; for v in fabric.values() { if v.len() > 1 { total += 1; } } println!("{}", total); Ok(()) } fn part2(input: &str) -> Result<(), Box<Error>> { let mut fabric = Fabric::new(); let f = File::open(input)?; let buf = BufReader::new(f); for line in buf.lines() { let claim: Claim = line?.parse()?; claim.update_fabric(&mut fabric); } let mut alone: HashSet<u32> = HashSet::new(); let mut not_alone: HashSet<u32> = HashSet::new(); for v in fabric.values() { if v.len() == 1 { alone.insert(v[0]); } else { for id in v.iter() { not_alone.insert(*id); } } } println!("{:?}", alone.difference(&not_alone)); Ok(()) } fn main() { let matches = App::new("dec01") .arg(Arg::with_name("input").required(true)) .arg(Arg::with_name("part").long("part").required(true) .takes_value(true) .possible_values(&["1", "2"])) .get_matches(); let input = matches.value_of("input").unwrap(); match matches.value_of("part").unwrap() { "1" => part1(input).unwrap(), "2" => part2(input).unwrap(), _ => unreachable!(), } }
extern crate clap; #[macro_use] extern crate lazy_static; extern crate regex; use std::error::Error; use std::fs::File; use std::io::{BufReader, BufRead}; use clap::{Arg, App}; use std::collections::{HashMap, HashSet}; use std::str::FromStr; use regex::Regex; #[derive(Debug)] struct Claim { id: u32, offset: (u32, u32), size: (u32, u32), } impl FromStr for Claim { type Err = Box<Error>; fn from_str(s: &str) -> Result<Self, Self::Err> { lazy_static! { static ref RE: Regex = Regex::new(r"(?x) \#(?P<id>\d+)\s+@\s+ (?P<x>\d+),(?P<y>\d+):\s+ (?P<w>\d+)x(?P<h>\d+) ").unwrap(); } match RE.captures(s) { Some(caps) => { Ok(Claim{ id: caps["id"].parse()?, offset: (caps["x"].parse()?, caps["y"].parse()?), size: (caps["w"].parse()?, caps["h"].parse()?), }) }, None => Err(Box::<Error>::from(format!("failed to create claim from: {:?}", s))), } } } impl Claim { fn update_fabric(&self, fabric: &mut Fabric) { for i in self.offset.0..(self.offset.0+self.size.0) { for j in self.offset.1..(self.offset.1+self.size.1) { fabric.entry((i, j)) .or_insert(vec![]) .push(self.id); } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_fabric_one_simple() { let claim: Claim = "#1 @ 1,2: 1x2".parse().unwrap(); let mut actual = Fabric::new(); claim.update_fabric(&mut actual); let expect: Fabric = [ ((1, 2), vec![1]), ((1, 3), vec![1]), ].iter().cloned().collect(); assert_eq!(expect, actual); } #[test] fn test_fabric_two_overlap() { let claim1: Claim = "#1 @ 0,0: 2x1".parse().unwrap(); let claim2: Claim = "#2 @ 1,0: 2x1".parse().unwrap(); let mut actual = Fabric::new(); claim1.update_fabric(&mut actual); claim2.update_fabric(&mut actual); let expect: Fabric = [ ((0, 0), vec![1]), ((1, 0), vec![1, 2]), ((2, 0), vec![2]), ].iter().cloned().collect(); assert_eq!(expect, actual); } } type Fabric = HashMap<(u32, u32), Vec<u32>>; fn part1(input: &str) -> Result<(), Box<Error>> { let mut fabric = Fabric::new(); let f = File::open(input)?; let buf = BufReader::new(f); for line in buf.lines() { let claim: Claim = line?.parse()?; claim.update_fabric(&mut fabric); } let mut total = 0; for v in fabric.values() { if v.len() > 1 { total += 1; } } println!("{}", total); Ok(()) } fn part2(input: &str) -> Result<(), Box<Error>> { let mut fabric = Fabric::new(); let f = File::open(input)?; let buf = BufReader::new(f); for line in buf.lines() { let claim: Claim = line?.parse()?; claim.update_fabric(&mut fabric); } let mut alone: HashSet<u32> = HashSet::new(); let mut
} println!("{:?}", alone.difference(&not_alone)); Ok(()) } fn main() { let matches = App::new("dec01") .arg(Arg::with_name("input").required(true)) .arg(Arg::with_name("part").long("part").required(true) .takes_value(true) .possible_values(&["1", "2"])) .get_matches(); let input = matches.value_of("input").unwrap(); match matches.value_of("part").unwrap() { "1" => part1(input).unwrap(), "2" => part2(input).unwrap(), _ => unreachable!(), } }
not_alone: HashSet<u32> = HashSet::new(); for v in fabric.values() { if v.len() == 1 { alone.insert(v[0]); } else { for id in v.iter() { not_alone.insert(*id); } }
function_block-random_span
[ { "content": "type GuardID = u32;\n\n\n", "file_path": "2018/dec04/rs/src/main.rs", "rank": 1, "score": 92777.30177134293 }, { "content": "fn part1(input: &str) -> Result<(), Box<Error>> {\n\n let f = File::open(input)?;\n\n let buf = BufReader::new(f);\n\n let mut records = vec![];...
Rust
src/post.rs
Lonami/pagong
bb5b24c733c435e8c041e5a91112e3ae5ad8cacc
use crate::config::{ Config, DATE_FMT, META_KEY_CATEGORY, META_KEY_CREATION_DATE, META_KEY_MODIFIED_DATE, META_KEY_TAGS, META_KEY_TEMPLATE, META_KEY_TITLE, META_TAG_SEPARATOR, META_VALUE_SEPARATOR, SOURCE_META_KEY, }; use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag}; use std::collections::HashMap; use std::fs; use std::io; use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; use chrono::offset::Local; use chrono::{Date, NaiveDate, NaiveDateTime, TimeZone}; const ZWNBSP: &str = "\u{FEFF}"; #[derive(Debug, Clone)] pub struct Post { pub path: PathBuf, pub markdown: String, pub meta: HashMap<String, String>, pub title: String, pub date: Date<Local>, pub updated: Date<Local>, pub category: String, pub tags: Vec<String>, pub template: Option<PathBuf>, pub uri: String, pub toc: Vec<(String, u8)>, } impl Post { pub fn new(config: &Config, root: &Path, path: PathBuf) -> io::Result<Self> { let mut markdown = fs::read_to_string(&path)?.replace(ZWNBSP, ""); let mut meta = HashMap::new(); if let Some((Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(lang))), start_range)) = Parser::new(&markdown).into_offset_iter().next() { if lang.as_ref() == SOURCE_META_KEY { meta.extend(markdown[start_range.clone()].lines().filter_map(|line| { let mut kv = line.splitn(2, META_VALUE_SEPARATOR); kv.next() .zip(kv.next()) .map(|(k, v)| (k.trim().to_owned(), v.trim().to_owned())) })); markdown.replace_range(start_range, ""); } } let title = meta .get(META_KEY_TITLE) .cloned() .or_else(|| { let mut wait_title = false; Parser::new(&markdown).find_map(|event| { match event { Event::Start(Tag::Heading(1)) => wait_title = true, Event::Text(s) if wait_title => { return Some(s.to_string()); } _ => {} } None }) }) .unwrap_or_else(|| { path.file_name() .unwrap() .to_str() .expect("bad md file name") .to_owned() }); let metadata = fs::metadata(&path)?; let date = meta .get(META_KEY_CREATION_DATE) .and_then(|date| NaiveDate::parse_from_str(date, DATE_FMT).ok()) .or_else(|| { metadata .created() .ok() .and_then(|date| date.duration_since(UNIX_EPOCH).ok()) .map(|duration| { NaiveDateTime::from_timestamp( duration.as_secs() as i64, duration.subsec_nanos(), ) .date() }) }) .and_then(|date| Local.from_local_date(&date).latest()) .unwrap_or_else(|| Local::now().date()); let updated = meta .get(META_KEY_MODIFIED_DATE) .and_then(|date| NaiveDate::parse_from_str(date, DATE_FMT).ok()) .or_else(|| { metadata .modified() .ok() .and_then(|date| date.duration_since(UNIX_EPOCH).ok()) .map(|duration| { NaiveDateTime::from_timestamp( duration.as_secs() as i64, duration.subsec_nanos(), ) .date() }) }) .and_then(|date| Local.from_local_date(&date).latest()) .unwrap_or(date); let category = meta.get(META_KEY_CATEGORY).cloned().unwrap_or_else(|| { path.parent() .expect("post file had no parent") .file_name() .expect("post parent had no name") .to_str() .expect("post parent had non-utf8 name") .to_owned() }); let tags = meta .get(META_KEY_TAGS) .map(|tags| { tags.split(META_TAG_SEPARATOR) .map(|s| s.trim().to_owned()) .collect() }) .unwrap_or_else(Vec::new); let template = meta .get(META_KEY_TEMPLATE) .map(|s| crate::utils::get_abs_path(root, &path, s)); let uri = crate::utils::path_to_uri(root, &path.with_extension(&config.dist_ext)); let toc = { let mut toc_depth = None; Parser::new(&markdown) .filter_map(|event| { match event { Event::Start(Tag::Heading(depth)) => toc_depth = Some(depth as u8), Event::Text(s) if toc_depth.is_some() => { return Some((s.to_string(), toc_depth.take().unwrap())); } _ => {} } None }) .collect() }; Ok(Self { path, markdown, meta, title, date, updated, category, tags, template, uri, toc, }) } }
use crate::config::{ Config, DATE_FMT, META_KEY_CATEGORY, META_KEY_CREATION_DATE, META_KEY_MODIFIED_DATE, META_KEY_TAGS, META_KEY_TEMPLATE, META_KEY_TITLE, META_TAG_SEPARATOR, META_VALUE_SEPARATOR, SOURCE_META_KEY, }; use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag}; use std::collections::HashMap; use std::fs; use std::io; use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; use chrono::offset::Local; use chrono::{Date, NaiveDate, NaiveDateTime, TimeZone}; const ZWNBSP: &str = "\u{FEFF}"; #[derive(Debug, Clone)] pub struct Post { pub path: PathBuf, pub markdown: String, pub meta: HashMap<String, String>, pub title: String, pub date: Date<Local>, pub updated: Date<Local>, pub category: String, pub tags: Vec<String>, pub template: Option<PathBuf>, pub uri: String, pub toc: Vec<(String, u8)>, } impl Post {
}
pub fn new(config: &Config, root: &Path, path: PathBuf) -> io::Result<Self> { let mut markdown = fs::read_to_string(&path)?.replace(ZWNBSP, ""); let mut meta = HashMap::new(); if let Some((Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(lang))), start_range)) = Parser::new(&markdown).into_offset_iter().next() { if lang.as_ref() == SOURCE_META_KEY { meta.extend(markdown[start_range.clone()].lines().filter_map(|line| { let mut kv = line.splitn(2, META_VALUE_SEPARATOR); kv.next() .zip(kv.next()) .map(|(k, v)| (k.trim().to_owned(), v.trim().to_owned())) })); markdown.replace_range(start_range, ""); } } let title = meta .get(META_KEY_TITLE) .cloned() .or_else(|| { let mut wait_title = false; Parser::new(&markdown).find_map(|event| { match event { Event::Start(Tag::Heading(1)) => wait_title = true, Event::Text(s) if wait_title => { return Some(s.to_string()); } _ => {} } None }) }) .unwrap_or_else(|| { path.file_name() .unwrap() .to_str() .expect("bad md file name") .to_owned() }); let metadata = fs::metadata(&path)?; let date = meta .get(META_KEY_CREATION_DATE) .and_then(|date| NaiveDate::parse_from_str(date, DATE_FMT).ok()) .or_else(|| { metadata .created() .ok() .and_then(|date| date.duration_since(UNIX_EPOCH).ok()) .map(|duration| { NaiveDateTime::from_timestamp( duration.as_secs() as i64, duration.subsec_nanos(), ) .date() }) }) .and_then(|date| Local.from_local_date(&date).latest()) .unwrap_or_else(|| Local::now().date()); let updated = meta .get(META_KEY_MODIFIED_DATE) .and_then(|date| NaiveDate::parse_from_str(date, DATE_FMT).ok()) .or_else(|| { metadata .modified() .ok() .and_then(|date| date.duration_since(UNIX_EPOCH).ok()) .map(|duration| { NaiveDateTime::from_timestamp( duration.as_secs() as i64, duration.subsec_nanos(), ) .date() }) }) .and_then(|date| Local.from_local_date(&date).latest()) .unwrap_or(date); let category = meta.get(META_KEY_CATEGORY).cloned().unwrap_or_else(|| { path.parent() .expect("post file had no parent") .file_name() .expect("post parent had no name") .to_str() .expect("post parent had non-utf8 name") .to_owned() }); let tags = meta .get(META_KEY_TAGS) .map(|tags| { tags.split(META_TAG_SEPARATOR) .map(|s| s.trim().to_owned()) .collect() }) .unwrap_or_else(Vec::new); let template = meta .get(META_KEY_TEMPLATE) .map(|s| crate::utils::get_abs_path(root, &path, s)); let uri = crate::utils::path_to_uri(root, &path.with_extension(&config.dist_ext)); let toc = { let mut toc_depth = None; Parser::new(&markdown) .filter_map(|event| { match event { Event::Start(Tag::Heading(depth)) => toc_depth = Some(depth as u8), Event::Text(s) if toc_depth.is_some() => { return Some((s.to_string(), toc_depth.take().unwrap())); } _ => {} } None }) .collect() }; Ok(Self { path, markdown, meta, title, date, updated, category, tags, template, uri, toc, }) }
function_block-full_function
[ { "content": "pub fn get_relative_uri(relative_to: &str, uri: &str) -> String {\n\n let relative_to = relative_to.as_bytes();\n\n let uri = uri.as_bytes();\n\n\n\n let mut count_after = relative_to.len();\n\n let mut last_shared_slash = 0;\n\n for i in 0..relative_to.len().max(uri.len()) {\n\n ...
Rust
src/args/arg_builder/flag.rs
Nemo157/clap-rs
01994467d5808903907012c26953ebde72594137
use std::convert::From; use std::fmt::{Display, Formatter, Result}; use std::rc::Rc; use std::result::Result as StdResult; use vec_map::VecMap; use Arg; use args::{AnyArg, DispOrder}; use args::settings::{ArgFlags, ArgSettings}; #[derive(Debug)] #[doc(hidden)] pub struct FlagBuilder<'n, 'e> { pub name: &'n str, pub long: Option<&'e str>, pub aliases: Option<Vec<(&'e str, bool)>>, pub help: Option<&'e str>, pub blacklist: Option<Vec<&'e str>>, pub requires: Option<Vec<&'e str>>, pub short: Option<char>, pub overrides: Option<Vec<&'e str>>, pub settings: ArgFlags, pub disp_ord: usize, } impl<'n, 'e> Default for FlagBuilder<'n, 'e> { fn default() -> Self { FlagBuilder { name: "", long: None, aliases: None, help: None, blacklist: None, requires: None, short: None, overrides: None, settings: ArgFlags::new(), disp_ord: 999, } } } impl<'n, 'e> FlagBuilder<'n, 'e> { pub fn new(name: &'n str) -> Self { FlagBuilder { name: name, ..Default::default() } } } impl<'a, 'b, 'z> From<&'z Arg<'a, 'b>> for FlagBuilder<'a, 'b> { fn from(a: &'z Arg<'a, 'b>) -> Self { assert!(a.validator.is_none(), format!("The argument '{}' has a validator set, yet was parsed as a flag. Ensure \ .takes_value(true) or .index(u64) is set.", a.name)); assert!(a.possible_vals.is_none(), format!("The argument '{}' cannot have a specific value set because it doesn't \ have takes_value(true) set", a.name)); assert!(!a.is_set(ArgSettings::Required), format!("The argument '{}' cannot be required because it's a flag, perhaps you \ forgot takes_value(true)?", a.name)); FlagBuilder { name: a.name, short: a.short, long: a.long, aliases: a.aliases.clone(), help: a.help, blacklist: a.blacklist.clone(), overrides: a.overrides.clone(), requires: a.requires.clone(), settings: a.settings, disp_ord: a.disp_ord, } } } impl<'n, 'e> Display for FlagBuilder<'n, 'e> { fn fmt(&self, f: &mut Formatter) -> Result { if let Some(l) = self.long { try!(write!(f, "--{}", l)); } else { try!(write!(f, "-{}", self.short.unwrap())); } Ok(()) } } impl<'n, 'e> Clone for FlagBuilder<'n, 'e> { fn clone(&self) -> Self { FlagBuilder { name: self.name, short: self.short, long: self.long, aliases: self.aliases.clone(), help: self.help, blacklist: self.blacklist.clone(), overrides: self.overrides.clone(), requires: self.requires.clone(), settings: self.settings, disp_ord: self.disp_ord, } } } impl<'n, 'e> AnyArg<'n, 'e> for FlagBuilder<'n, 'e> { fn name(&self) -> &'n str { self.name } fn overrides(&self) -> Option<&[&'e str]> { self.overrides.as_ref().map(|o| &o[..]) } fn requires(&self) -> Option<&[&'e str]> { self.requires.as_ref().map(|o| &o[..]) } fn blacklist(&self) -> Option<&[&'e str]> { self.blacklist.as_ref().map(|o| &o[..]) } fn required_unless(&self) -> Option<&[&'e str]> { None } fn is_set(&self, s: ArgSettings) -> bool { self.settings.is_set(s) } fn has_switch(&self) -> bool { true } fn takes_value(&self) -> bool { false } fn set(&mut self, s: ArgSettings) { self.settings.set(s) } fn max_vals(&self) -> Option<u64> { None } fn val_names(&self) -> Option<&VecMap<&'e str>> { None } fn num_vals(&self) -> Option<u64> { None } fn possible_vals(&self) -> Option<&[&'e str]> { None } fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> { None } fn min_vals(&self) -> Option<u64> { None } fn short(&self) -> Option<char> { self.short } fn long(&self) -> Option<&'e str> { self.long } fn val_delim(&self) -> Option<char> { None } fn help(&self) -> Option<&'e str> { self.help } fn default_val(&self) -> Option<&'n str> { None } fn longest_filter(&self) -> bool { self.long.is_some() } fn aliases(&self) -> Option<Vec<&'e str>> { if let Some(ref aliases) = self.aliases { let vis_aliases: Vec<_> = aliases.iter() .filter_map(|&(n, v)| if v { Some(n) } else { None }) .collect(); if vis_aliases.is_empty() { None } else { Some(vis_aliases) } } else { None } } } impl<'n, 'e> DispOrder for FlagBuilder<'n, 'e> { fn disp_ord(&self) -> usize { self.disp_ord } } #[cfg(test)] mod test { use args::settings::ArgSettings; use super::FlagBuilder; #[test] fn flagbuilder_display() { let mut f = FlagBuilder::new("flg"); f.settings.set(ArgSettings::Multiple); f.long = Some("flag"); assert_eq!(&*format!("{}", f), "--flag"); let mut f2 = FlagBuilder::new("flg"); f2.short = Some('f'); assert_eq!(&*format!("{}", f2), "-f"); } #[test] fn flagbuilder_display_single_alias() { let mut f = FlagBuilder::new("flg"); f.long = Some("flag"); f.aliases = Some(vec![("als", true)]); assert_eq!(&*format!("{}", f), "--flag"); } #[test] fn flagbuilder_display_multiple_aliases() { let mut f = FlagBuilder::new("flg"); f.short = Some('f'); f.aliases = Some(vec![ ("alias_not_visible", false), ("f2", true), ("f3", true), ("f4", true) ]); assert_eq!(&*format!("{}", f), "-f"); } }
use std::convert::From; use std::fmt::{Display, Formatter, Result}; use std::rc::Rc; use std::result::Result as StdResult; use vec_map::VecMap; use Arg; use args::{AnyArg, DispOrder}; use args::settings::{ArgFlags, ArgSettings}; #[derive(Debug)] #[doc(hidden)] pub struct FlagBuilder<'n, 'e> { pub name: &'n str, pub long: Option<&'e str>, pub aliases: Option<Vec<(&'e str, bool)>>, pub help: Option<&'e str>, pub blacklist: Option<Vec<&'e str>>, pub requires: Option<Vec<&'e str>>, pub short: Option<char>, pub overrides: Option<Vec<&'e str>>, pub settings: ArgFlags, pub disp_ord: usize, } impl<'n, 'e> Default for FlagBuilder<'n, 'e> { fn default() -> Self { FlagBuilder { name: "", long: None, aliases: None, help: None, blacklist: None, requires: None, short: None, overrides: None, settings: ArgFlags::new(), disp_ord: 999, } } } impl<'n, 'e> FlagBuilder<'n, 'e> { pub fn new(name: &'n str) -> Self { FlagBuilder { name: name, ..Default::default() } } } impl<'a, 'b, 'z> From<&'z Arg<'a, 'b>> for FlagBuilder<'a, 'b> { fn from(a: &'z Arg<'a, 'b>) -> Self { assert!(a.validator.is_none(), format!("The argument '{}' has a validator set, yet was parsed as a flag. Ensure \ .takes_value(true) or .index(u64) is set.", a.name)); assert!(a.possible_vals.is_none(), format!("The argument '{}' cannot have a specific value set because it doesn't \ have takes_value(true) set", a.name)); assert!(!a.is_set(ArgSettings::Required), format!("The argument '{}' cannot be required because it's a flag, perhaps you \ forgot takes_value(true)?", a.name)); FlagBuilder { name: a.name, short: a.short, long: a.long, aliases: a.aliases.clone(), help: a.help, blacklist: a.blacklist.clone(), overrides: a.overrides.clone(), requires: a.requires.clone(), settings: a.settings, disp_ord: a.disp_ord, } } } impl<'n, 'e> Display for FlagBuilder<'n, 'e> { fn fmt(&self, f: &mut Formatter) -> Result { if let Some(l) = self.long { try!(write!(f, "--{}", l)); } else { try!(write!(f, "-{}", self.short.unwrap())); } Ok(()) } } impl<'n, 'e> Clone for FlagBuilder<'n, 'e> { fn clone(&self) -> Self { FlagBuilder { name: self.name, short: self.short, long: self.long, aliases: self.aliases.clone(), help: self.help, blacklist: self.blacklist.clone(), overrides: self.overrides.clone(), requires: self.requires.clone(), settings: self.settings, disp_ord: self.disp_ord, } } } impl<'n, 'e> AnyArg<'n, 'e> for FlagBuilder<'n, 'e> { fn name(&self) -> &'n str { self.name } fn overrides(&self) -> Option<&[&'e str]> { self.overrides.as_ref().map(|o| &o[..]) } fn requires(&self) -> Option<&[&'e str]> { self.requires.as_ref().map(|o| &o[..]) } fn blacklist(&self) -> Option<&[&'e str]> { self.blacklist.as_ref().map(|o| &o[..]) } fn required_unless(&self) -> Option<&[&'e str]> { None } fn is_set(&self, s: ArgSettings) -> bool { self.settings.is_set(s) } fn has_switch(&self) -> bool { true } fn takes_value(&self) -> bool { false } fn set(&mut self, s: ArgSettings) { self.settings.set(s) } fn max_vals(&self) -> Option<u64> { None } fn val_names(&self) -> Option<&VecMap<&'e str>> { None } fn num_vals(&self) -> Option<u64> { None } fn possible_vals(&self) -> Option<&[&'e str]> { None } fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> { None } fn min_vals(&self) -> Option<u64> { None } fn short(&self) -> Option<char> { self.short } fn long(&self) -> Option<&'e str> { self.long } fn val_delim(&self) -> Option<char> { None } fn help(&self) -> Option<&'e str> { self.help } fn default_val(&self) -> Option<&'n str> { None } fn longest_filter(&self) -> bool { self.long.is_some() } fn aliases(&self) -> Option<Vec<&'e str>> { if let Some(ref aliases) = self.aliases { let vis_aliases: Vec<_> = aliases.iter() .filter_map(|&(n, v)| if v { Some(n) } else { None }) .collect(); if vis_aliases.is_empty() { None } else { Some(vis_aliases) } } else { None } } } impl<'n, 'e> DispOrder for FlagBuilder<'n, 'e> { fn disp_ord(&self) -> usize { self.disp_ord } } #[cfg(test)] mod test { use args::settings::ArgSettings; use super::FlagBuilder; #[test] fn flagbuilder_display() { let mut f = FlagBuilder::new("flg"); f.settings.set(ArgSettings::Multiple); f.long = Some("flag"); assert_eq!(&*format!("{}", f), "--flag"); let mut f2 = FlagBuilder::new("flg"); f2.short = Some('f'); assert_eq!(&*format!("{}", f2), "-f"); } #[test] fn flagbuilder_display_single_alias() { let mut f = FlagBuilder::new("flg"); f.long = Some("flag"); f.aliases = Some(vec![("als", true)]); assert_eq!(&*format!("{}", f), "--flag"); } #[test] fn flagbuilder_display_multiple_aliases() { let mut f = FlagBuilder::new("flg"); f.short = Some('f'); f.aliases =
; assert_eq!(&*format!("{}", f), "-f"); } }
Some(vec![ ("alias_not_visible", false), ("f2", true), ("f3", true), ("f4", true) ])
call_expression
[ { "content": "fn compare_app_str(l: &App, right: &str) -> bool {\n\n let left = build_new_help(&l);\n\n // Strip out any mismatching \\r character on windows that might sneak in on either side\n\n let b = left.trim().replace(\"\\r\", \"\") == right.replace(\"\\r\", \"\");\n\n if !b {\n\n prin...
Rust
src/rest_api/routes/consortium.rs
arsulegai/splinter-admin-ops-daemon
8511d0ce2505eb9bfe4bfa973a31bbf87b1f4bf4
use std::collections::HashMap; use actix_web::{client::Client, error, http::StatusCode, web, Error, HttpResponse}; use futures::{Future, IntoFuture}; use openssl::hash::{hash, MessageDigest}; use protobuf::Message; use splinter::admin::messages::{ AuthorizationType, CreateCircuit, DurabilityType, PersistenceType, RouteType, SplinterNode, SplinterService, }; use splinter::node_registry::Node; use splinter::protos::admin::{ CircuitManagementPayload, CircuitManagementPayload_Action as Action, CircuitManagementPayload_Header as Header, }; use uuid::Uuid; use crate::application_metadata::ApplicationMetadata; use crate::rest_api::{ConsortiumData, RestApiResponseError}; use super::{ get_response_paging_info, validate_limit, ErrorResponse, SuccessResponse, DEFAULT_LIMIT, DEFAULT_OFFSET, }; use db_models::models::Consortium; #[derive(Debug, Serialize, Deserialize)] pub struct CreateConsortiumForm { alias: String, members: Vec<String>, } pub fn propose_consortium( create_consortium: web::Json<CreateConsortiumForm>, node_info: web::Data<Node>, client: web::Data<Client>, splinterd_url: web::Data<String>, consortium_data: web::Data<ConsortiumData>, ) -> impl Future<Item = HttpResponse, Error = Error> { fetch_node_information(&create_consortium.members, &splinterd_url, client).then(move |resp| { let nodes = match resp { Ok(nodes) => nodes, Err(err) => match err { RestApiResponseError::BadRequest(message) => { return HttpResponse::BadRequest() .json(ErrorResponse::bad_request(&message.to_string())) .into_future(); } _ => { debug!("Failed to fetch node information: {}", err); return HttpResponse::InternalServerError() .json(ErrorResponse::internal_error()) .into_future(); } }, }; let mut members = nodes .iter() .map(|node| SplinterNode { node_id: node.identity.to_string(), endpoint: node .metadata .get("endpoint") .unwrap_or(&"".to_string()) .to_string(), }) .collect::<Vec<SplinterNode>>(); members.push(SplinterNode { node_id: node_info.identity.to_string(), endpoint: node_info .metadata .get("endpoint") .unwrap_or(&"".to_string()) .to_string(), }); let partial_circuit_id = members.iter().fold(String::new(), |mut acc, member| { acc.push_str(&format!("::{}", member.node_id)); acc }); let scabbard_admin_keys = vec![consortium_data.get_ref().public_key.clone()]; let mut scabbard_args = vec![]; scabbard_args.push(( "admin_keys".into(), match serde_json::to_string(&scabbard_admin_keys) { Ok(s) => s, Err(err) => { debug!("Failed to serialize scabbard admin keys: {}", err); return HttpResponse::InternalServerError() .json(ErrorResponse::internal_error()) .into_future(); } }, )); let mut roster = vec![]; for node in members.iter() { let peer_services = match serde_json::to_string( &members .iter() .filter_map(|other_node| { if other_node.node_id != node.node_id { Some(format!("consortium_{}", other_node.node_id)) } else { None } }) .collect::<Vec<_>>(), ) { Ok(s) => s, Err(err) => { debug!("Failed to serialize peer services: {}", err); return HttpResponse::InternalServerError() .json(ErrorResponse::internal_error()) .into_future(); } }; let mut service_args = scabbard_args.clone(); service_args.push(("peer_services".into(), peer_services)); roster.push(SplinterService { service_id: format!("consortium_{}", node.node_id), service_type: "scabbard".to_string(), allowed_nodes: vec![node.node_id.to_string()], arguments: service_args, }); } let application_metadata = match ApplicationMetadata::new(&create_consortium.alias, &scabbard_admin_keys) .to_bytes() { Ok(bytes) => bytes, Err(err) => { debug!("Failed to serialize application metadata: {}", err); return HttpResponse::InternalServerError() .json(ErrorResponse::internal_error()) .into_future(); } }; let create_request = CreateCircuit { circuit_id: format!( "consortium{}::{}", partial_circuit_id, Uuid::new_v4().to_string() ), roster, members, authorization_type: AuthorizationType::Trust, persistence: PersistenceType::Any, durability: DurabilityType::NoDurability, routes: RouteType::Any, circuit_management_type: "consortium".to_string(), application_metadata, }; let payload_bytes = match make_payload(create_request, node_info.identity.to_string()) { Ok(bytes) => bytes, Err(err) => { debug!("Failed to make circuit management payload: {}", err); return HttpResponse::InternalServerError() .json(ErrorResponse::internal_error()) .into_future(); } }; HttpResponse::Ok() .json(SuccessResponse::new(json!({ "payload_bytes": payload_bytes }))) .into_future() }) } fn fetch_node_information( node_ids: &[String], splinterd_url: &str, client: web::Data<Client>, ) -> Box<dyn Future<Item = Vec<Node>, Error = RestApiResponseError>> { let node_ids = node_ids.to_owned(); Box::new( client .get(&format!("{}/nodes?limit={}", splinterd_url, std::i64::MAX)) .send() .map_err(|err| { RestApiResponseError::InternalError(format!("Failed to send request {}", err)) }) .and_then(move |mut resp| { let body = resp.body().wait().map_err(|err| { RestApiResponseError::InternalError(format!( "Failed to receive response body {}", err )) })?; match resp.status() { StatusCode::OK => { let list_reponse: SuccessResponse<Vec<Node>> = serde_json::from_slice(&body).map_err(|err| { RestApiResponseError::InternalError(format!( "Failed to parse response body {}", err )) })?; let nodes = node_ids.into_iter().try_fold(vec![], |mut acc, node_id| { if let Some(node) = list_reponse .data .iter() .find(|node| node.identity == node_id) { acc.push(node.clone()); Ok(acc) } else { Err(RestApiResponseError::BadRequest(format!( "Could not find node with id {}", node_id ))) } })?; Ok(nodes) } StatusCode::BAD_REQUEST => { let message: String = serde_json::from_slice(&body).map_err(|err| { RestApiResponseError::InternalError(format!( "Failed to parse response body {}", err )) })?; Err(RestApiResponseError::BadRequest(message)) } _ => { let message: String = serde_json::from_slice(&body).map_err(|err| { RestApiResponseError::InternalError(format!( "Failed to parse response body {}", err )) })?; Err(RestApiResponseError::InternalError(message)) } } }), ) } fn make_payload( create_request: CreateCircuit, local_node: String, ) -> Result<Vec<u8>, RestApiResponseError> { let circuit_proto = create_request.into_proto()?; let circuit_bytes = circuit_proto.write_to_bytes()?; let hashed_bytes = hash(MessageDigest::sha512(), &circuit_bytes)?; let mut header = Header::new(); header.set_action(Action::CIRCUIT_CREATE_REQUEST); header.set_payload_sha512(hashed_bytes.to_vec()); header.set_requester_node_id(local_node); let header_bytes = header.write_to_bytes()?; let mut circuit_management_payload = CircuitManagementPayload::new(); circuit_management_payload.set_header(header_bytes); circuit_management_payload.set_circuit_create_request(circuit_proto); let payload_bytes = circuit_management_payload.write_to_bytes()?; Ok(payload_bytes) }
use std::collections::HashMap; use actix_web::{client::Client, error, http::StatusCode, web, Error, HttpResponse}; use futures::{Future, IntoFuture}; use openssl::hash::{hash, MessageDigest}; use protobuf::Message; use splinter::admin::messages::{ AuthorizationType, CreateCircuit, DurabilityType, PersistenceType, RouteType, SplinterNode, SplinterService, }; use splinter::node_registry::Node; use splinter::protos::admin::{ CircuitManagementPayload, CircuitManagementPayload_Action as Action, CircuitManagementPayload_Header as Header, }; use uuid::Uuid; use crate::application_metadata::ApplicationMetadata; use crate::rest_api::{ConsortiumData, RestApiResponseError}; use super::{ get_response_paging_info, validate_limit, ErrorResponse, SuccessResponse, DEFAULT_LIMIT, DEFAULT_OFFSET, }; use db_models::models::Consortium; #[derive(Debug, Serialize, Deserialize)] pub struct CreateConsortiumForm { alias: String, members: Vec<String>, } pub fn propose_consortium( create_consortium: web::Json<CreateConsortiumForm>, node_info: web::Data<Node>, client: web::Data<Client>, splinterd_url: web::Data<String>, consortium_data: web::Data<ConsortiumData>, ) -> impl Future<Item = HttpResponse, Error = Error> { fetch_node_information(&create_consortium.members, &splinterd_url, client).then(move |resp| { let nodes = match resp { Ok(nodes) => nodes, Err(err) => match err { RestApiResponseError::BadRequest(message) => { return HttpResponse::BadRequest() .json(ErrorResponse::bad_request(&message.to_string())) .into_future(); } _ => { debug!("Failed to fetch node information: {}", err); return HttpResponse::InternalServerError() .json(ErrorResponse::internal_error()) .into_future(); } }, }; let mut members = nodes .iter() .map(|node| SplinterNode { node_id: node.identity.to_string(), endpoint: node .metadata .get("endpoint") .unwrap_or(&"".to_string()) .to_string(), }) .collect::<Vec<SplinterNode>>(); members.push(SplinterNode { node_id: node_info.identity.to_string(), endpoint: node_info .metadata .get("endpoint") .unwrap_or(&"".to_string()) .to_string(), }); let partial_circuit_id = members.iter().fold(String::new(), |mut acc, member| { acc.push_str(&format!("::{}", member.node_id)); acc }); let scabbard_admin_keys = vec![consortium_data.get_ref().public_key.clone()]; let mut scabbard_args = vec![]; scabbard_args.push(( "admin_keys".into(), match serde_json::to_string(&scabbard_admin_keys) { Ok(s) => s, Err(err) => { debug!("Failed to serialize scabbard admin keys: {}", err); return HttpResponse::InternalServerError() .json(ErrorResponse::internal_error()) .into_future(); } }, )); let mut roster = vec![]; for node in members.iter() { let peer_services = match serde_json::to_string( &members .iter() .filter_map(|other_node| { if other_node.node_id != node.node_id { Some(format!("consortium_{}", other_node.node_id)) } else { None } }) .collect::<Vec<_>>(), ) { Ok(s) => s, Err(err) => { debug!("Failed to serialize peer services: {}", err); return HttpResponse::InternalServerError() .json(ErrorResponse::internal_error()) .into_future(); } }; let mut service_args = scabbard_args.clone(); service_args.push(("peer_services".into(), peer_services)); roster.push(SplinterService { service_id: format!("consortium_{}", node.node_id), service_type: "scabbard".to_string(), allowed_nodes: vec![node.node_id.to_string()], arguments: service_args, }); } let application_metadata = match ApplicationMetadata::new(&create_consortium.alias, &scabbard_admin_keys) .to_bytes() { Ok(bytes) => bytes, Err(err) => { debug!("Failed to serialize application metadata: {}", err); return HttpResponse::InternalServerError() .json(ErrorResponse::internal_error()) .into_future(); } }; let create_request = CreateCircuit { circuit_id: format!( "consortium{}::{}", partial_circuit_
fn fetch_node_information( node_ids: &[String], splinterd_url: &str, client: web::Data<Client>, ) -> Box<dyn Future<Item = Vec<Node>, Error = RestApiResponseError>> { let node_ids = node_ids.to_owned(); Box::new( client .get(&format!("{}/nodes?limit={}", splinterd_url, std::i64::MAX)) .send() .map_err(|err| { RestApiResponseError::InternalError(format!("Failed to send request {}", err)) }) .and_then(move |mut resp| { let body = resp.body().wait().map_err(|err| { RestApiResponseError::InternalError(format!( "Failed to receive response body {}", err )) })?; match resp.status() { StatusCode::OK => { let list_reponse: SuccessResponse<Vec<Node>> = serde_json::from_slice(&body).map_err(|err| { RestApiResponseError::InternalError(format!( "Failed to parse response body {}", err )) })?; let nodes = node_ids.into_iter().try_fold(vec![], |mut acc, node_id| { if let Some(node) = list_reponse .data .iter() .find(|node| node.identity == node_id) { acc.push(node.clone()); Ok(acc) } else { Err(RestApiResponseError::BadRequest(format!( "Could not find node with id {}", node_id ))) } })?; Ok(nodes) } StatusCode::BAD_REQUEST => { let message: String = serde_json::from_slice(&body).map_err(|err| { RestApiResponseError::InternalError(format!( "Failed to parse response body {}", err )) })?; Err(RestApiResponseError::BadRequest(message)) } _ => { let message: String = serde_json::from_slice(&body).map_err(|err| { RestApiResponseError::InternalError(format!( "Failed to parse response body {}", err )) })?; Err(RestApiResponseError::InternalError(message)) } } }), ) } fn make_payload( create_request: CreateCircuit, local_node: String, ) -> Result<Vec<u8>, RestApiResponseError> { let circuit_proto = create_request.into_proto()?; let circuit_bytes = circuit_proto.write_to_bytes()?; let hashed_bytes = hash(MessageDigest::sha512(), &circuit_bytes)?; let mut header = Header::new(); header.set_action(Action::CIRCUIT_CREATE_REQUEST); header.set_payload_sha512(hashed_bytes.to_vec()); header.set_requester_node_id(local_node); let header_bytes = header.write_to_bytes()?; let mut circuit_management_payload = CircuitManagementPayload::new(); circuit_management_payload.set_header(header_bytes); circuit_management_payload.set_circuit_create_request(circuit_proto); let payload_bytes = circuit_management_payload.write_to_bytes()?; Ok(payload_bytes) }
id, Uuid::new_v4().to_string() ), roster, members, authorization_type: AuthorizationType::Trust, persistence: PersistenceType::Any, durability: DurabilityType::NoDurability, routes: RouteType::Any, circuit_management_type: "consortium".to_string(), application_metadata, }; let payload_bytes = match make_payload(create_request, node_info.identity.to_string()) { Ok(bytes) => bytes, Err(err) => { debug!("Failed to make circuit management payload: {}", err); return HttpResponse::InternalServerError() .json(ErrorResponse::internal_error()) .into_future(); } }; HttpResponse::Ok() .json(SuccessResponse::new(json!({ "payload_bytes": payload_bytes }))) .into_future() }) }
function_block-function_prefixed
[ { "content": "pub fn fetch_node(\n\n identity: web::Path<String>,\n\n client: web::Data<Client>,\n\n splinterd_url: web::Data<String>,\n\n) -> impl Future<Item = HttpResponse, Error = Error> {\n\n client\n\n .get(&format!(\"{}/nodes/{}\", splinterd_url.get_ref(), identity))\n\n .send()...
Rust
src/lib.rs
pudnax/chonker
dff08090f23322631ea60fe13d5dd3789f926577
#![feature(get_mut_unchecked)] use std::{ path::{Path, PathBuf}, time::Instant, }; pub mod camera; pub mod context; mod utils; mod watcher; pub use camera::{Camera, CameraBinding}; pub use context::{ Context, GlobalUniformBinding, HdrBackBuffer, PipelineHandle, Uniform, VolumeTexture, }; pub use utils::{dispatch_optimal, shader_compiler, NonZeroSized}; pub use watcher::{ReloadablePipeline, Watcher}; use color_eyre::eyre::Result; use pollster::FutureExt; use utils::{frame_counter::FrameCounter, input::Input, recorder::RecordEvent}; use winit::{ dpi::{PhysicalPosition, PhysicalSize}, event::{ DeviceEvent, ElementState, Event, KeyboardInput, MouseScrollDelta, VirtualKeyCode, WindowEvent, }, event_loop::{ControlFlow, EventLoop}, window::Window, }; const SHADER_FOLDER: &str = "shaders"; const SCREENSHOTS_FOLDER: &str = "screenshots"; const VIDEO_FOLDER: &str = "recordings"; pub trait Demo: 'static + Sized { fn init(ctx: &mut Context) -> Self; fn resize(&mut self, _: &wgpu::Device, _: &wgpu::Queue, _: &wgpu::SurfaceConfiguration) {} fn update(&mut self, _: &mut Context) {} fn update_input(&mut self, _: WindowEvent) {} fn render(&mut self, _: &Context) {} } pub fn run<D: Demo>( event_loop: EventLoop<(PathBuf, wgpu::ShaderModule)>, window: Window, camera: Option<Camera>, ) -> Result<()> { color_eyre::install()?; env_logger::init(); let mut context = Context::new(&window, &event_loop, camera).block_on()?; let mut recording_status = false; let recorder = utils::recorder::Recorder::new(); print_help(context.get_info(), &recorder.ffmpeg_version); let mut frame_counter = FrameCounter::new(); let mut input = Input::new(); let mut mouse_dragged = false; let rotate_speed = 0.0025; let zoom_speed = 0.002; let mut demo = D::init(&mut context); let mut main_window_focused = false; event_loop.run(move |event, _, control_flow| { *control_flow = ControlFlow::Wait; match event { Event::MainEventsCleared => { context.update(&frame_counter, &input); demo.update(&mut context); window.request_redraw(); } Event::WindowEvent { event, window_id, .. } if window.id() == window_id => { input.update(&event, &window); match event { WindowEvent::Focused(focused) => main_window_focused = focused, WindowEvent::CloseRequested | WindowEvent::KeyboardInput { input: KeyboardInput { virtual_keycode: Some(VirtualKeyCode::Escape), state: ElementState::Pressed, .. }, .. } => *control_flow = ControlFlow::Exit, WindowEvent::Resized(PhysicalSize { width, height }) | WindowEvent::ScaleFactorChanged { new_inner_size: &mut PhysicalSize { width, height }, .. } => { if width != 0 && height != 0 { context.resize(width, height); demo.resize(&context.device, &context.queue, &context.surface_config); } if recording_status { println!("Stop recording. Resolution has been changed.",); recording_status = false; recorder.send(RecordEvent::Finish); } } WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(keycode), .. }, .. } => { if VirtualKeyCode::F11 == keycode { let now = Instant::now(); let frame = context.capture_frame(); eprintln!("Capture image: {:#.2?}", now.elapsed()); recorder.send(RecordEvent::Screenshot(frame)); } if recorder.ffmpeg_installed() && VirtualKeyCode::F12 == keycode { if !recording_status { recorder .send(RecordEvent::Start(context.capture_image_dimentions())); } else { recorder.send(RecordEvent::Finish); } recording_status = !recording_status; } } _ => {} } demo.update_input(event); } Event::DeviceEvent { ref event, .. } if main_window_focused => match event { DeviceEvent::Button { #[cfg(target_os = "macos")] button: 0, #[cfg(not(target_os = "macos"))] button: 1, state: statee, } => { let is_pressed = *statee == ElementState::Pressed; mouse_dragged = is_pressed; } DeviceEvent::MouseWheel { delta, .. } => { let scroll_amount = -match delta { MouseScrollDelta::LineDelta(_, scroll) => scroll * 1.0, MouseScrollDelta::PixelDelta(PhysicalPosition { y: scroll, .. }) => { *scroll as f32 } }; context.camera.add_zoom(scroll_amount * zoom_speed); } DeviceEvent::MouseMotion { delta } => { if mouse_dragged { context.camera.add_yaw(-delta.0 as f32 * rotate_speed); context.camera.add_pitch(delta.1 as f32 * rotate_speed); } } _ => (), }, Event::RedrawRequested(_) => { frame_counter.record(); demo.render(&context); match context.render() { Ok(_) => {} Err(wgpu::SurfaceError::Lost) => { context.resize(context.width, context.height); window.request_redraw(); } Err(wgpu::SurfaceError::OutOfMemory) => *control_flow = ControlFlow::Exit, Err(e) => { eprintln!("{:?}", e); window.request_redraw(); } } if recording_status { let (frame, _) = context.capture_frame(); recorder.send(RecordEvent::Record(frame)); } } Event::UserEvent((path, shader)) => context.register_shader_change(path, shader), Event::LoopDestroyed => { println!("\n// End from the loop. Bye bye~⏎ "); } _ => {} } }) } pub fn print_help(info: impl std::fmt::Display, ffmpeg_version: &str) { println!("{}", info); println!("{}", ffmpeg_version); println!( "Default shader path:\n\t{}\n", Path::new(SHADER_FOLDER).canonicalize().unwrap().display() ); println!("- `F11`: Take Screenshot"); println!("- `F12`: Start/Stop record video"); println!("- `ESC`: Exit the application"); println!(); println!("// Set up our new world⏎ "); println!("// And let's begin the⏎ "); println!("\tSIMULATION⏎ \n"); }
#![feature(get_mut_unchecked)] use std::{ path::{Path, PathBuf}, time::Instant, }; pub mod camera; pub mod context; mod utils; mod watcher; pub use camera::{Camera, CameraBinding}; pub use context::{ Context, GlobalUniformBinding, HdrBackBuffer, PipelineHandle, Uniform, VolumeTexture, }; pub use utils::{dispatch_optimal, shader_compiler, NonZeroSized}; pub use watcher::{ReloadablePipeline, Watcher}; use color_eyre::eyre::Result; use pollster::FutureExt; use utils::{frame_counter::FrameCounter, input::Input, recorder::RecordEvent}; use winit::{ dpi::{PhysicalPosition, PhysicalSize}, event::{ DeviceEvent, ElementState, Event, KeyboardInput, MouseScrollDelta, VirtualKeyCode, WindowEvent, }, event_loop::{ControlFlow, EventLoop}, window::Window, }; const SHADER_FOLDER: &str = "shaders"; const SCREENSHOTS_FOLDER: &str = "screenshots"; const VIDEO_FOLDER: &str = "recordings"; pub trait Demo: 'static + Sized { fn init(ctx: &mut Context) -> Self; fn resize(&mut self, _: &wgpu::Device, _: &wgpu::Queue, _: &wgpu::SurfaceConfiguration) {} fn update(&mut self, _: &mut Context) {} fn update_input(&mut self, _: WindowEvent) {} fn render(&mut self, _: &Context) {} } pub fn run<D: Demo>( event_loop: EventLoop<(PathBuf, wgpu::ShaderModule)>, window: Window, camera: Option<Camera>, ) -> Result<()> { color_eyre::install()?; env_logger::init(); let mut context = Context::new(&window, &event_loop, camera).block_on()?; let mut recording_status = false; let recorder = utils::recorder::Recorder::new(); print_help(context.get_info(), &recorder.ffmpeg_version); let mut frame_counter = FrameCounter::new(); let mut input = Input::new(); let mut mouse_dragged = false; let rotate_speed = 0.0025; let zoom_speed = 0.002; let mut demo = D::init(&mut context); let mut main_window_focused = false; event_loop.run(move |event, _, control_flow| { *control_flow = ControlFlow::Wait; match event { Event::MainEventsCleared => { context.update(&frame_counter, &input); demo.update(&mut context); window.request_redraw(); } Event::WindowEvent { event, window_id, .. } if window.id() == window_id => { input.update(&event, &window); match event { WindowEvent::Focused(focused) => main_window_focused = focused, WindowEvent::CloseRequested | WindowEvent::KeyboardInput { input: KeyboardInput { virtual_keycode: Some(VirtualKeyCode::Escape), state: ElementState::Pressed, .. }, .. } => *control_flow = ControlFlow::Exit, WindowEvent::Resized(PhysicalSize { width, height }) | WindowEvent::ScaleFactorChanged { new_inner_size: &mut PhysicalSize { width, height }, .. } => { if width != 0 && height != 0 { context.resize(width, height); demo.resize(&context.device, &context.queue, &context.surface_config); } if recording_status { println!("Stop recording. Resolution has been changed.",); recording_status = false; recorder.send(RecordEvent::Finish); } } WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(keycode), .. }, .. } => { if VirtualKeyCode::F11 == keycode { let now = Instant::now(); let frame = context.capture_frame(); eprintln!("Capture image: {:#.2?}", now.elapsed()); recorder.send(RecordEvent::Screenshot(frame)); } if recorder.ffmpeg_installed() && VirtualKeyCode::F12 == keycode { if !recording_status { recorder .send(RecordEvent::Start(context.capture_image_dimentions())); } else { recorder.send(RecordEvent::Finish); } recording_status = !recording_status; } } _ => {} } demo.update_input(event); } Event::DeviceEvent { ref event, .. } if main_window_focused => match event { DeviceEvent::Button { #[cfg(target_os = "macos")] button: 0, #[cfg(not(target_os = "macos"))] button: 1, state: statee, } => { let is_pressed = *statee == ElementState::Pressed; mouse_dragged = is_pressed; } DeviceEvent::MouseWheel { delta, .. } => { let scroll_amount = -match delta { MouseScrollDelta::LineDelta(_, scroll) => scroll * 1.0, MouseScrollDelta::PixelDelta(PhysicalPosition { y: scroll, .. }) => { *scroll as f32 } }; context.camera.add_zoom(scroll_amount * zoom_speed); } DeviceEvent::MouseMotion { delta } => { if mouse_dragged { context.camera.add_yaw(-delta.0 as f32 * rotate_speed); context.camera.add_pitch(delta.1 as f32 * rotate_speed); } } _ => (), }, Event::RedrawRequested(_) => { frame_counter.record(); demo.render(&context); match context.render() { Ok(_) => {} Err(wgpu::SurfaceError::Lost) => { context.resize(context.width, context.height); window.request_redraw(); } Err(wgpu::SurfaceError::OutOfMemory) => *control_flow = ControlFlow::Exit, Err(e) => { eprintln!("{:?}", e); window.request_redraw(); } } if recording_status { let (frame, _) = context.capture_frame(); recorder.send(RecordEvent::Record(frame)); } } Event::UserEvent((path, shader)) => context.register_shader_change(path, shader), Event::LoopDestroyed => { println!("\n// End from the loop. Bye bye~⏎ "); } _ => {} } }) }
pub fn print_help(info: impl std::fmt::Display, ffmpeg_version: &str) { println!("{}", info); println!("{}", ffmpeg_version); println!( "Default shader path:\n\t{}\n", Path::new(SHADER_FOLDER).canonicalize().unwrap().display() ); println!("- `F11`: Take Screenshot"); println!("- `F12`: Start/Stop record video"); println!("- `ESC`: Exit the application"); println!(); println!("// Set up our new world⏎ "); println!("// And let's begin the⏎ "); println!("\tSIMULATION⏎ \n"); }
function_block-full_function
[ { "content": "pub fn save_screenshot(frame: Vec<u8>, image_dimentions: ImageDimentions) -> Result<()> {\n\n let now = Instant::now();\n\n let screenshots_folder = Path::new(SCREENSHOTS_FOLDER);\n\n create_folder(screenshots_folder)?;\n\n let path = screenshots_folder.join(format!(\n\n \"scree...
Rust
benches/crit_bench.rs
arthurprs/lz4_flex
4953936f618dc7b644b2f30a612149d466005718
extern crate criterion; use self::criterion::*; use lz4::block::compress as lz4_linked_block_compress; use lz_fear::raw::compress2; use lz_fear::raw::decompress_raw; use lz_fear::raw::U16Table; use lz_fear::raw::U32Table; const COMPRESSION1K: &'static [u8] = include_bytes!("compression_1k.txt"); const COMPRESSION34K: &'static [u8] = include_bytes!("compression_34k.txt"); const COMPRESSION65K: &'static [u8] = include_bytes!("compression_65k.txt"); const COMPRESSION66K: &'static [u8] = include_bytes!("compression_66k_JSON.txt"); const COMPRESSION95K_VERY_GOOD_LOGO: &'static [u8] = include_bytes!("../logo.jpg"); const ALL: &[&[u8]] = &[ COMPRESSION1K as &[u8], COMPRESSION34K as &[u8], ]; fn compress_lz4_fear(input: &[u8]) -> Vec<u8> { let mut buf = Vec::new(); if input.len() <= 0xFFFF { compress2(input, 0, &mut U16Table::default(), &mut buf).unwrap(); } else { compress2(input, 0, &mut U32Table::default(), &mut buf).unwrap(); } buf } fn bench_compression_throughput(c: &mut Criterion) { let plot_config = PlotConfiguration::default().summary_scale(AxisScale::Linear); let mut group = c.benchmark_group("Compress"); group.plot_config(plot_config); for input in ALL.iter() { let input_bytes = input.len() as u64; group.throughput(Throughput::Bytes(input_bytes)); group.bench_with_input( BenchmarkId::new("lz4_flexx_rust", input_bytes), &input, |b, i| b.iter(|| lz4_flex::compress(&i)), ); } group.finish(); } pub fn decompress_fear(input: &[u8]) -> Vec<u8> { let mut vec = Vec::new(); decompress_raw(input, &[], &mut vec, std::usize::MAX).unwrap(); vec } fn bench_decompression_throughput(c: &mut Criterion) { let plot_config = PlotConfiguration::default().summary_scale(AxisScale::Linear); let mut group = c.benchmark_group("Decompress"); group.plot_config(plot_config); for input in ALL.iter() { let input_bytes = input.len() as u64; group.throughput(Throughput::Bytes(input_bytes)); let comp_lz4 = lz4::block::compress(&input, None, false).unwrap(); group.bench_with_input( BenchmarkId::new("lz4_flexx_rust", input_bytes), &comp_lz4, |b, i| b.iter(|| lz4_flex::decompress(&i, input.len())), ); } group.finish(); } criterion_group!( benches, bench_decompression_throughput, bench_compression_throughput ); criterion_main!(benches);
extern crate criterion; use self::criterion::*; use lz4::block::compress as lz4_linked_block_compress; use lz_fear::raw::compress2; use lz_fear::raw::decompress_raw; use lz_fear::raw::U16Table; use lz_f
g = PlotConfiguration::default().summary_scale(AxisScale::Linear); let mut group = c.benchmark_group("Decompress"); group.plot_config(plot_config); for input in ALL.iter() { let input_bytes = input.len() as u64; group.throughput(Throughput::Bytes(input_bytes)); let comp_lz4 = lz4::block::compress(&input, None, false).unwrap(); group.bench_with_input( BenchmarkId::new("lz4_flexx_rust", input_bytes), &comp_lz4, |b, i| b.iter(|| lz4_flex::decompress(&i, input.len())), ); } group.finish(); } criterion_group!( benches, bench_decompression_throughput, bench_compression_throughput ); criterion_main!(benches);
ear::raw::U32Table; const COMPRESSION1K: &'static [u8] = include_bytes!("compression_1k.txt"); const COMPRESSION34K: &'static [u8] = include_bytes!("compression_34k.txt"); const COMPRESSION65K: &'static [u8] = include_bytes!("compression_65k.txt"); const COMPRESSION66K: &'static [u8] = include_bytes!("compression_66k_JSON.txt"); const COMPRESSION95K_VERY_GOOD_LOGO: &'static [u8] = include_bytes!("../logo.jpg"); const ALL: &[&[u8]] = &[ COMPRESSION1K as &[u8], COMPRESSION34K as &[u8], ]; fn compress_lz4_fear(input: &[u8]) -> Vec<u8> { let mut buf = Vec::new(); if input.len() <= 0xFFFF { compress2(input, 0, &mut U16Table::default(), &mut buf).unwrap(); } else { compress2(input, 0, &mut U32Table::default(), &mut buf).unwrap(); } buf } fn bench_compression_throughput(c: &mut Criterion) { let plot_config = PlotConfiguration::default().summary_scale(AxisScale::Linear); let mut group = c.benchmark_group("Compress"); group.plot_config(plot_config); for input in ALL.iter() { let input_bytes = input.len() as u64; group.throughput(Throughput::Bytes(input_bytes)); group.bench_with_input( BenchmarkId::new("lz4_flexx_rust", input_bytes), &input, |b, i| b.iter(|| lz4_flex::compress(&i)), ); } group.finish(); } pub fn decompress_fear(input: &[u8]) -> Vec<u8> { let mut vec = Vec::new(); decompress_raw(input, &[], &mut vec, std::usize::MAX).unwrap(); vec } fn bench_decompression_throughput(c: &mut Criterion) { let plot_confi
random
[ { "content": "use lz4_flex::block::DecompressError;\n\nuse tokio::fs::File;\n\nuse tokio::prelude::*; // for write_all()\n\nuse argh::FromArgs;\n\n\n\n#[macro_use]\n\nextern crate quick_error;\n\n\n\n#[derive(FromArgs, Debug)]\n\n/// Reach new heights.\n", "file_path": "lz4_bin/src/main.rs", "rank": 2, ...
Rust
src/record.rs
phip1611/beat-detector
ad00de5348bb0325298abd5a1e31d59d5f34845e
/* MIT License Copyright (c) 2021 Philipp Schuster Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use crate::{BeatInfo, StrategyKind}; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use cpal::{BufferSize, Device, Host, InputCallbackInfo, SampleFormat, StreamConfig, StreamError}; use std::collections::{BTreeMap, HashMap}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread::{spawn, JoinHandle}; use std::time::Instant; pub fn start_listening( on_beat_cb: impl Fn(BeatInfo) + Send + 'static, input_dev: Option<Device>, strategy: StrategyKind, keep_recording: Arc<AtomicBool>, ) -> Result<JoinHandle<()>, String> { if !keep_recording.load(Ordering::SeqCst) { return Err("Variable keep_recording is false from the beginning!?".to_string()); } let in_dev = input_dev.map(Ok).unwrap_or_else(|| { let host = cpal::default_host(); host.default_input_device() .ok_or_else(|| "Must have input device!".to_string()) })?; let in_dev_cfg = in_dev.default_input_config().unwrap(); let sampling_rate = in_dev_cfg.sample_rate(); let sample_format = in_dev_cfg.sample_format(); eprintln!("Using input device: {:?}", in_dev.name().unwrap()); eprintln!(" sampling_rate: {}", sampling_rate.0); eprintln!(" sample_format: {:?}", sample_format); let err_cb = |err: StreamError| { eprintln!("Record error occurred: {:#?}", err); }; #[cfg(not(target_os = "linux"))] let preferred_window_length = 1024; let in_stream_cfg = StreamConfig { channels: 1, sample_rate: sampling_rate, #[cfg(not(target_os = "linux"))] buffer_size: BufferSize::Fixed(preferred_window_length), #[cfg(target_os = "linux")] buffer_size: BufferSize::Default, }; let detector = strategy.detector(sampling_rate.0); let handle = spawn(move || { let stream = match sample_format { SampleFormat::F32 => in_dev.build_input_stream( &in_stream_cfg, move |data: &[f32], _info: &InputCallbackInfo| { let now = Instant::now(); if let Some(info) = detector.is_beat(&f32_data_to_i16(data)) { on_beat_cb(info); } let millis = now.elapsed().as_millis(); if millis > 20 { eprintln!("calculation took {}ms", millis); } }, err_cb, ), SampleFormat::I16 => in_dev.build_input_stream( &in_stream_cfg, move |data: &[i16], _info: &InputCallbackInfo| { let now = Instant::now(); if let Some(info) = detector.is_beat(data) { on_beat_cb(info); } let millis = now.elapsed().as_millis(); if millis > 20 { eprintln!("calculation took {}ms", millis); } }, err_cb, ), SampleFormat::U16 => in_dev.build_input_stream( &in_stream_cfg, move |data: &[u16], _info: &InputCallbackInfo| { let now = Instant::now(); if let Some(info) = detector.is_beat(&u16_data_to_i16(data)) { on_beat_cb(info); } let millis = now.elapsed().as_millis(); if millis > 20 { eprintln!("calculation took {}ms", millis); } }, err_cb, ), } .map_err(|err| format!("Can't open stream: {:?}", err)) .unwrap(); stream.play().unwrap(); loop { if !keep_recording.load(Ordering::SeqCst) { break; } } }); Ok(handle) } #[inline(always)] fn u16_data_to_i16(data: &[u16]) -> Vec<i16> { data.iter() .map(|x| *x as i32) .map(|x| x - i16::MAX as i32 / 2) .map(|x| x as i16) .collect() } #[inline(always)] fn f32_data_to_i16(data: &[f32]) -> Vec<i16> { data.iter() .map(|x| x * i16::MAX as f32) .map(|x| x as i16) .collect() } pub fn audio_input_device_list() -> BTreeMap<String, Device> { let host = cpal::default_host(); let mut map = BTreeMap::new(); for (i, dev) in host.input_devices().unwrap().enumerate() { map.insert(dev.name().unwrap_or(format!("Unknown device #{}", i)), dev); } map } pub fn print_audio_input_device_configs() { let host = cpal::default_host(); for (i, dev) in host.input_devices().unwrap().enumerate() { eprintln!("--------"); let name = dev.name().unwrap_or(format!("Unknown device #{}", i)); eprintln!("[{}] default config:", name); eprintln!("{:#?}", dev.default_input_config().unwrap()); } } pub fn get_backends() -> HashMap<String, Host> { cpal::available_hosts() .into_iter() .map(|id| (format!("{:?}", id), cpal::host_from_id(id).unwrap())) .collect::<HashMap<_, _>>() } #[cfg(test)] mod tests { use super::*; }
/* MIT License Copyright (c) 2021 Philipp Schuster Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use crate::{BeatInfo, StrategyKind}; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use cpal::{BufferSize, Device, Host, InputCallbackInfo, SampleFormat, StreamConfig, StreamError}; use std::collections::{BTreeMap, HashMap}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread::{spawn, JoinHandle}; use std::time::Instant; pub fn start_listening( on_beat_cb: impl Fn(BeatInfo) + Send + 'static, input_dev: Option<Device>, strategy: StrategyKind, keep_recording: Arc<AtomicBool>, ) -> Result<JoinHandle<()>, String> { if !keep_recording.load(Ordering::SeqCst) { return Err("Variable keep_recording is false from the beginning!?".to_string()); } let in_dev = input_dev.map(Ok).unwrap_or_else(|| { let host = cpal::default_host(); host.default_input_device() .ok_or_else(|| "Must have input device!".to_string()) })?; let in_dev_cfg = in_dev.default_input_config().unwrap(); let sampling_rate = in_dev_cfg.sample_rate(); let sample_format = in_dev_cfg.sample_format(); eprintln!("Using input device: {:?}", in_dev.name().unwrap()); eprintln!(" sampling_rate: {}", sampling_rate.0); eprintln!(" sample_format: {:?}", sample_format); let err_cb = |err: StreamError| { eprintln!("Record error occurred: {:#?}", err); }; #[cfg(not(target_os = "linux"))] let preferred_window_length = 1024; let in_stream_cfg = StreamConfig { channels: 1, sample_rate: sampling_rate, #[cfg(not(target_os = "linux"))] buffer_size: BufferSize::Fixed(preferred_window_length), #[cfg(target_os = "linux")] buffer_size: BufferSize::Default, }; let detector = strategy.detector(sampling_rate.0); let handle = spawn(move || { let stream = match sample_format { SampleFormat::F32 => in_dev.build_input_stream( &in_stream_cfg, move |data: &[f32], _info: &InputCallbackInfo| { let now = Instant::now(); if let Some(info) = detector.is_beat(&f32_data_to_i16(data)) { on_beat_cb(info); } let millis = now.elapsed().as_millis(); if millis > 20 { eprintln!("calculation took {}ms", millis); } }, err_cb, ), SampleFormat::I16 => in_dev.build_input_stream( &in_stream_cfg, move |data: &[i16], _info: &InputCallbackInfo| { let now = Instant::now(); if let Some(info) = detector.is_beat(data) { on_beat_cb(info); } let millis = now.elapsed().as_millis(); if millis > 20 { eprintln!("calculation took {}ms", millis); } }, err_cb, ), SampleFormat::U16 => in_dev.build_input_stream( &in_stream_cfg, move |data: &[u16], _info: &InputCallbackInfo| { let now = Instant::now(); if let Some(info) = detector.is_beat(&u16_data_to_i16(data)) { on_beat_cb(info); } let millis = now.elapsed().as_millis(); if millis > 20 { eprintln!("calculation took {}ms", millis); } }, err_cb, ), } .map_err(|err| format!("Can't open stream: {:?}", err)) .unwrap();
#[inline(always)] fn u16_data_to_i16(data: &[u16]) -> Vec<i16> { data.iter() .map(|x| *x as i32) .map(|x| x - i16::MAX as i32 / 2) .map(|x| x as i16) .collect() } #[inline(always)] fn f32_data_to_i16(data: &[f32]) -> Vec<i16> { data.iter() .map(|x| x * i16::MAX as f32) .map(|x| x as i16) .collect() } pub fn audio_input_device_list() -> BTreeMap<String, Device> { let host = cpal::default_host(); let mut map = BTreeMap::new(); for (i, dev) in host.input_devices().unwrap().enumerate() { map.insert(dev.name().unwrap_or(format!("Unknown device #{}", i)), dev); } map } pub fn print_audio_input_device_configs() { let host = cpal::default_host(); for (i, dev) in host.input_devices().unwrap().enumerate() { eprintln!("--------"); let name = dev.name().unwrap_or(format!("Unknown device #{}", i)); eprintln!("[{}] default config:", name); eprintln!("{:#?}", dev.default_input_config().unwrap()); } } pub fn get_backends() -> HashMap<String, Host> { cpal::available_hosts() .into_iter() .map(|id| (format!("{:?}", id), cpal::host_from_id(id).unwrap())) .collect::<HashMap<_, _>>() } #[cfg(test)] mod tests { use super::*; }
stream.play().unwrap(); loop { if !keep_recording.load(Ordering::SeqCst) { break; } } }); Ok(handle) }
function_block-function_prefix_line
[ { "content": "fn select_strategy() -> StrategyKind {\n\n println!(\"Available beat detection strategies:\");\n\n StrategyKind::values()\n\n .into_iter()\n\n .enumerate()\n\n .for_each(|(i, s)| {\n\n println!(\" [{}] {} - {}\", i, s.name(), s.description());\n\n });\...
Rust
tests/defaults_encode_decode.rs
OragonEfreet/sage_mqtt
092cf0494e5c602d712591a4fb87e5cd713b7282
use sage_mqtt::{ Auth, ConnAck, Connect, Disconnect, Error, Packet, PubAck, PubComp, PubRec, PubRel, Publish, ReasonCode, SubAck, Subscribe, UnSubAck, UnSubscribe, }; use std::io::Cursor; #[tokio::test] async fn default_connect() { let mut encoded = Vec::new(); let send_packet: Packet = Connect::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode Connect packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode Connect"); if let Packet::Connect(receive_packet) = receive_result { assert_eq!(receive_packet, Connect::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn connect_with_default_auth() { let mut encoded = Vec::new(); let send_packet: Packet = Connect { authentication: Some(Default::default()), ..Default::default() } .into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode Connect packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode Connect"); if let Packet::Connect(receive_packet) = receive_result { assert_eq!( receive_packet, Connect { authentication: Some(Default::default()), ..Default::default() } ); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_connack() { let mut encoded = Vec::new(); let send_packet: Packet = ConnAck::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode ConnAck packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode ConnAck"); if let Packet::ConnAck(receive_packet) = receive_result { assert_eq!(receive_packet, ConnAck::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_publish() { let mut encoded = Vec::new(); let send_packet: Packet = Publish::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode Publish packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode Publish"); if let Packet::Publish(receive_packet) = receive_result { assert_eq!(receive_packet, Publish::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_puback() { let mut encoded = Vec::new(); let send_packet: Packet = PubAck::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode PubAck packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode PubAck"); if let Packet::PubAck(receive_packet) = receive_result { assert_eq!(receive_packet, PubAck::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_pubrec() { let mut encoded = Vec::new(); let send_packet: Packet = PubRec::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode PubRec packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode PubRec"); if let Packet::PubRec(receive_packet) = receive_result { assert_eq!(receive_packet, PubRec::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_pubrel() { let mut encoded = Vec::new(); let send_packet: Packet = PubRel::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode PubRel packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode PubRel"); if let Packet::PubRel(receive_packet) = receive_result { assert_eq!(receive_packet, PubRel::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_pubcomp() { let mut encoded = Vec::new(); let send_packet: Packet = PubComp::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode PubComp packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode PubComp"); if let Packet::PubComp(receive_packet) = receive_result { assert_eq!(receive_packet, PubComp::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_subscribe() { let mut encoded = Vec::new(); let send_packet: Packet = Subscribe::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode Subscribe packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor).await; assert!(matches!( receive_result, Err(Error::Reason(ReasonCode::ProtocolError)) )); } #[tokio::test] async fn default_suback() { let mut encoded = Vec::new(); let send_packet: Packet = SubAck::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode SubAck packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode SubAck"); if let Packet::SubAck(receive_packet) = receive_result { assert_eq!(receive_packet, SubAck::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_unsubscribe() { let mut encoded = Vec::new(); let send_packet: Packet = UnSubscribe::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode UnSubscribe packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor).await; assert!(matches!( receive_result, Err(Error::Reason(ReasonCode::ProtocolError)) )); } #[tokio::test] async fn default_unsuback() { let mut encoded = Vec::new(); let send_packet: Packet = UnSubAck::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode UnSubAck packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode UnSubAck"); if let Packet::UnSubAck(receive_packet) = receive_result { assert_eq!(receive_packet, UnSubAck::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_pingreq() { let mut encoded = Vec::new(); let send_size = Packet::PingReq .encode(&mut encoded) .await .expect("Cannot encode PingReq packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode PingReq"); assert!(matches!(receive_result, Packet::PingReq)); } #[tokio::test] async fn default_pingresp() { let mut encoded = Vec::new(); let send_size = Packet::PingResp .encode(&mut encoded) .await .expect("Cannot encode PingResp packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode PingResp"); assert!(matches!(receive_result, Packet::PingResp)); } #[tokio::test] async fn default_disconnect() { let mut encoded = Vec::new(); let send_packet: Packet = Disconnect::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode Disconnect packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode Disconnect"); if let Packet::Disconnect(receive_packet) = receive_result { assert_eq!(receive_packet, Disconnect::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_auth() { let mut encoded = Vec::new(); let send_packet: Packet = Auth::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode Auth packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode Auth"); if let Packet::Auth(receive_packet) = receive_result { assert_eq!(receive_packet, Auth::default()); } else { panic!("Incorrect packet type"); } }
use sage_mqtt::{ Auth, ConnAck, Connect, Disconnect, Error, Packet, PubAck, PubComp, PubRec, PubRel, Publish, ReasonCode, SubAck, Subscribe, UnSubAck, UnSubscribe, }; use std::io::Cursor; #[tokio::test] async fn default_connect() { let mut encoded = Vec::new(); let send_packet: Packet = Connect::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode Connect packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode Connect"); if let Packet::Connect(receive_packet) = receive_result { assert_eq!(receive_packet, Connect::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn connect_with_default_auth() { let mut encoded = Vec::new(); let send_packet: Packet = Connect { authentication: Some(Default::default()), ..Default::default() } .into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode Connect packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode Connect");
} #[tokio::test] async fn default_connack() { let mut encoded = Vec::new(); let send_packet: Packet = ConnAck::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode ConnAck packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode ConnAck"); if let Packet::ConnAck(receive_packet) = receive_result { assert_eq!(receive_packet, ConnAck::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_publish() { let mut encoded = Vec::new(); let send_packet: Packet = Publish::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode Publish packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode Publish"); if let Packet::Publish(receive_packet) = receive_result { assert_eq!(receive_packet, Publish::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_puback() { let mut encoded = Vec::new(); let send_packet: Packet = PubAck::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode PubAck packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode PubAck"); if let Packet::PubAck(receive_packet) = receive_result { assert_eq!(receive_packet, PubAck::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_pubrec() { let mut encoded = Vec::new(); let send_packet: Packet = PubRec::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode PubRec packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode PubRec"); if let Packet::PubRec(receive_packet) = receive_result { assert_eq!(receive_packet, PubRec::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_pubrel() { let mut encoded = Vec::new(); let send_packet: Packet = PubRel::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode PubRel packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode PubRel"); if let Packet::PubRel(receive_packet) = receive_result { assert_eq!(receive_packet, PubRel::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_pubcomp() { let mut encoded = Vec::new(); let send_packet: Packet = PubComp::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode PubComp packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode PubComp"); if let Packet::PubComp(receive_packet) = receive_result { assert_eq!(receive_packet, PubComp::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_subscribe() { let mut encoded = Vec::new(); let send_packet: Packet = Subscribe::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode Subscribe packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor).await; assert!(matches!( receive_result, Err(Error::Reason(ReasonCode::ProtocolError)) )); } #[tokio::test] async fn default_suback() { let mut encoded = Vec::new(); let send_packet: Packet = SubAck::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode SubAck packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode SubAck"); if let Packet::SubAck(receive_packet) = receive_result { assert_eq!(receive_packet, SubAck::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_unsubscribe() { let mut encoded = Vec::new(); let send_packet: Packet = UnSubscribe::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode UnSubscribe packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor).await; assert!(matches!( receive_result, Err(Error::Reason(ReasonCode::ProtocolError)) )); } #[tokio::test] async fn default_unsuback() { let mut encoded = Vec::new(); let send_packet: Packet = UnSubAck::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode UnSubAck packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode UnSubAck"); if let Packet::UnSubAck(receive_packet) = receive_result { assert_eq!(receive_packet, UnSubAck::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_pingreq() { let mut encoded = Vec::new(); let send_size = Packet::PingReq .encode(&mut encoded) .await .expect("Cannot encode PingReq packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode PingReq"); assert!(matches!(receive_result, Packet::PingReq)); } #[tokio::test] async fn default_pingresp() { let mut encoded = Vec::new(); let send_size = Packet::PingResp .encode(&mut encoded) .await .expect("Cannot encode PingResp packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode PingResp"); assert!(matches!(receive_result, Packet::PingResp)); } #[tokio::test] async fn default_disconnect() { let mut encoded = Vec::new(); let send_packet: Packet = Disconnect::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode Disconnect packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode Disconnect"); if let Packet::Disconnect(receive_packet) = receive_result { assert_eq!(receive_packet, Disconnect::default()); } else { panic!("Incorrect packet type"); } } #[tokio::test] async fn default_auth() { let mut encoded = Vec::new(); let send_packet: Packet = Auth::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode Auth packet"); assert!(send_size > 0); let mut cursor = Cursor::new(encoded); let receive_result = Packet::decode(&mut cursor) .await .expect("Cannot decode Auth"); if let Packet::Auth(receive_packet) = receive_result { assert_eq!(receive_packet, Auth::default()); } else { panic!("Incorrect packet type"); } }
if let Packet::Connect(receive_packet) = receive_result { assert_eq!( receive_packet, Connect { authentication: Some(Default::default()), ..Default::default() } ); } else { panic!("Incorrect packet type"); }
if_condition
[ { "content": "use crate::QoS;\n\n\n\n/// The control packet type is present as the first element of the fixed header\n\n/// in an MQTT paquet. It is encoded in a 8bit flag set where the 4 most\n\n/// significant bits represent the type of the paquet and the 4 least are flags\n\n/// where values depend on the ty...
Rust
exchanges/binance/src/exchange.rs
rcjmurillo/crypto-portfolio
3032bb100159875b5730da440b008d1e46df7539
use chrono::{DateTime, Utc}; use std::collections::HashSet; use anyhow::Result; use async_trait::async_trait; use futures::future::join_all; use crate::{ api_model::{Deposit, FiatOrder, MarginLoan, MarginRepay, Trade, Withdraw}, client::{BinanceFetcher, EndpointsGlobal, EndpointsUs, RegionGlobal, RegionUs}, }; use exchange::{self, AssetPair, AssetsInfo, ExchangeDataFetcher, ExchangeClient, Candle}; impl From<FiatOrder> for exchange::Deposit { fn from(d: FiatOrder) -> Self { Self { source_id: d.id, source: "binance".to_string(), asset: d.fiat_currency, amount: d.amount, fee: Some(d.platform_fee), time: d.create_time, is_fiat: true, } } } impl From<FiatOrder> for exchange::Withdraw { fn from(d: FiatOrder) -> Self { Self { source_id: d.id, source: "binance".to_string(), asset: d.fiat_currency, amount: d.amount, fee: d.transaction_fee + d.platform_fee, time: d.create_time, } } } impl From<Deposit> for exchange::Deposit { fn from(d: Deposit) -> Self { Self { source_id: d.id, source: "binance".to_string(), asset: d.coin, amount: d.amount, fee: None, time: d.insert_time, is_fiat: false, } } } impl From<Withdraw> for exchange::Withdraw { fn from(w: Withdraw) -> Self { Self { source_id: w.id, source: "binance".to_string(), asset: w.coin, amount: w.amount, time: w.apply_time, fee: w.transaction_fee, } } } impl From<Trade> for exchange::Trade { fn from(t: Trade) -> Self { Self { source_id: t.id.to_string(), source: "binance".to_string(), symbol: t.symbol, base_asset: t.base_asset, quote_asset: t.quote_asset, price: t.price, amount: t.qty, fee: t.commission, fee_asset: t.commission_asset, time: t.time, side: if t.is_buyer { exchange::TradeSide::Buy } else { exchange::TradeSide::Sell }, } } } impl From<MarginLoan> for exchange::Loan { fn from(m: MarginLoan) -> Self { Self { source_id: m.tx_id.to_string(), source: "binance".to_string(), asset: m.asset, amount: m.principal, time: m.timestamp, status: match m.status.as_str() { "CONFIRMED" => exchange::Status::Success, _ => exchange::Status::Failure, }, } } } impl From<MarginRepay> for exchange::Repay { fn from(r: MarginRepay) -> Self { Self { source_id: r.tx_id.to_string(), source: "binance".to_string(), asset: r.asset, amount: r.principal, interest: r.interest, time: r.timestamp, status: match r.status.as_str() { "CONFIRMED" => exchange::Status::Success, _ => exchange::Status::Failure, }, } } } #[async_trait] impl ExchangeDataFetcher for BinanceFetcher<RegionGlobal> { async fn trades(&self) -> Result<Vec<exchange::Trade>> { let all_symbols: Vec<String> = self .fetch_exchange_symbols(&EndpointsGlobal::ExchangeInfo.to_string()) .await? .into_iter() .map(|x| x.symbol) .collect(); let mut trades: Vec<Result<Vec<Trade>>> = Vec::new(); let endpoint = EndpointsGlobal::Trades.to_string(); let mut handles = Vec::new(); for symbol in self.symbols().iter() { if all_symbols.contains(&symbol.join("")) { handles.push(self.fetch_trades(&endpoint, symbol)); if handles.len() >= 10 { trades.extend(join_all(handles).await); handles = Vec::new(); } } } if handles.len() > 0 { trades.extend(join_all(handles).await); } flatten_results(trades) } async fn margin_trades(&self) -> Result<Vec<exchange::Trade>> { let all_symbols: Vec<String> = self .fetch_exchange_symbols(&EndpointsGlobal::ExchangeInfo.to_string()) .await? .into_iter() .map(|x| x.symbol) .collect(); let mut handles = Vec::new(); for symbol in self.symbols().iter() { if all_symbols.contains(&symbol.join("")) { handles.push(self.fetch_margin_trades(symbol)); } } flatten_results(join_all(handles).await) } async fn loans(&self) -> Result<Vec<exchange::Loan>> { let mut handles = Vec::new(); let exchange_symbols = self .fetch_exchange_symbols(&EndpointsGlobal::ExchangeInfo.to_string()) .await?; let all_symbols: Vec<String> = exchange_symbols.iter().map(|x| x.symbol.clone()).collect(); let mut processed_assets = HashSet::new(); for symbol in self.symbols().iter() { if all_symbols.contains(&symbol.join("")) { if !processed_assets.contains(&symbol.base) { handles.push(self.fetch_margin_loans(&symbol.base, None)); processed_assets.insert(&symbol.base); } handles.push(self.fetch_margin_loans(&symbol.base, Some(symbol))); } } flatten_results(join_all(handles).await) } async fn repays(&self) -> Result<Vec<exchange::Repay>> { let mut handles = Vec::new(); let exchange_symbols = self .fetch_exchange_symbols(&EndpointsGlobal::ExchangeInfo.to_string()) .await?; let all_symbols: Vec<String> = exchange_symbols.iter().map(|x| x.symbol.clone()).collect(); let mut processed_assets = HashSet::new(); for symbol in self.symbols().iter() { if all_symbols.contains(&symbol.join("")) { if !processed_assets.contains(&symbol.base) { handles.push(self.fetch_margin_repays(&symbol.base, None)); processed_assets.insert(symbol.base.clone()); } handles.push(self.fetch_margin_repays(&symbol.base, Some(symbol))); } } flatten_results(join_all(handles).await) } async fn deposits(&self) -> Result<Vec<exchange::Deposit>> { let mut deposits = Vec::new(); deposits.extend( self.fetch_fiat_deposits() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Deposit>>(), ); deposits.extend( self.fetch_deposits() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Deposit>>(), ); Ok(deposits) } async fn withdraws(&self) -> Result<Vec<exchange::Withdraw>> { let mut withdraws = Vec::new(); withdraws.extend( self.fetch_fiat_withdraws() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Withdraw>>(), ); withdraws.extend( self.fetch_withdraws() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Withdraw>>(), ); Ok(withdraws) } } #[async_trait] impl ExchangeClient for BinanceFetcher<RegionGlobal> { async fn prices( &self, asset_pair: &AssetPair, start: DateTime<Utc>, end: DateTime<Utc>, ) -> Result<Vec<Candle>> { self.fetch_prices_in_range( &EndpointsGlobal::Klines.to_string(), &asset_pair.join(""), start.timestamp_millis().try_into()?, end.timestamp_millis().try_into()?, ).await } } #[async_trait] impl ExchangeDataFetcher for BinanceFetcher<RegionUs> { async fn trades(&self) -> Result<Vec<exchange::Trade>> { let all_symbols: Vec<String> = self .fetch_exchange_symbols(&EndpointsUs::ExchangeInfo.to_string()) .await? .into_iter() .map(|x| x.symbol) .collect(); let endpoint = EndpointsUs::Trades.to_string(); let mut handles = Vec::new(); for symbol in self.symbols().iter() { if all_symbols.contains(&symbol.join("")) { handles.push(self.fetch_trades(&endpoint, &symbol)); } } flatten_results(join_all(handles).await) } async fn margin_trades(&self) -> Result<Vec<exchange::Trade>> { Ok(Vec::new()) } async fn loans(&self) -> Result<Vec<exchange::Loan>> { Ok(Vec::new()) } async fn repays(&self) -> Result<Vec<exchange::Repay>> { Ok(Vec::new()) } async fn deposits(&self) -> Result<Vec<exchange::Deposit>> { let mut deposits = Vec::new(); deposits.extend( self.fetch_fiat_deposits() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Deposit>>(), ); deposits.extend( self.fetch_deposits() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Deposit>>(), ); Ok(deposits) } async fn withdraws(&self) -> Result<Vec<exchange::Withdraw>> { let mut withdraws = Vec::new(); withdraws.extend( self.fetch_fiat_withdraws() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Withdraw>>(), ); withdraws.extend( self.fetch_withdraws() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Withdraw>>(), ); Ok(withdraws) } } #[async_trait] impl AssetsInfo for BinanceFetcher<RegionGlobal> { async fn price_at(&self, asset_pair: &AssetPair, time: &DateTime<Utc>) -> Result<f64> { self.fetch_price_at( &EndpointsGlobal::Prices.to_string(), &asset_pair.join(""), time, ) .await } } fn flatten_results<T, U>(results: Vec<Result<Vec<T>>>) -> Result<Vec<U>> where T: Into<U>, { Ok(results .into_iter() .collect::<Result<Vec<Vec<T>>>>()? .into_iter() .flatten() .map(|x| x.into()) .collect()) }
use chrono::{DateTime, Utc}; use std::collections::HashSet; use anyhow::Result; use async_trait::async_trait; use futures::future::join_all; use crate::{ api_model::{Deposit, FiatOrder, MarginLoan, MarginRepay, Trade, Withdraw}, client::{BinanceFetcher, EndpointsGlobal, EndpointsUs, RegionGlobal, RegionUs}, }; use exchange::{self, AssetPair, AssetsInfo, ExchangeDataFetcher, ExchangeClient, Candle}; impl From<FiatOrder> for exchange::Deposit { fn from(d: FiatOrder) -> Self { Self { source_id: d.id, source: "binance".to_string(), as
ance".to_string(), asset: r.asset, amount: r.principal, interest: r.interest, time: r.timestamp, status: match r.status.as_str() { "CONFIRMED" => exchange::Status::Success, _ => exchange::Status::Failure, }, } } } #[async_trait] impl ExchangeDataFetcher for BinanceFetcher<RegionGlobal> { async fn trades(&self) -> Result<Vec<exchange::Trade>> { let all_symbols: Vec<String> = self .fetch_exchange_symbols(&EndpointsGlobal::ExchangeInfo.to_string()) .await? .into_iter() .map(|x| x.symbol) .collect(); let mut trades: Vec<Result<Vec<Trade>>> = Vec::new(); let endpoint = EndpointsGlobal::Trades.to_string(); let mut handles = Vec::new(); for symbol in self.symbols().iter() { if all_symbols.contains(&symbol.join("")) { handles.push(self.fetch_trades(&endpoint, symbol)); if handles.len() >= 10 { trades.extend(join_all(handles).await); handles = Vec::new(); } } } if handles.len() > 0 { trades.extend(join_all(handles).await); } flatten_results(trades) } async fn margin_trades(&self) -> Result<Vec<exchange::Trade>> { let all_symbols: Vec<String> = self .fetch_exchange_symbols(&EndpointsGlobal::ExchangeInfo.to_string()) .await? .into_iter() .map(|x| x.symbol) .collect(); let mut handles = Vec::new(); for symbol in self.symbols().iter() { if all_symbols.contains(&symbol.join("")) { handles.push(self.fetch_margin_trades(symbol)); } } flatten_results(join_all(handles).await) } async fn loans(&self) -> Result<Vec<exchange::Loan>> { let mut handles = Vec::new(); let exchange_symbols = self .fetch_exchange_symbols(&EndpointsGlobal::ExchangeInfo.to_string()) .await?; let all_symbols: Vec<String> = exchange_symbols.iter().map(|x| x.symbol.clone()).collect(); let mut processed_assets = HashSet::new(); for symbol in self.symbols().iter() { if all_symbols.contains(&symbol.join("")) { if !processed_assets.contains(&symbol.base) { handles.push(self.fetch_margin_loans(&symbol.base, None)); processed_assets.insert(&symbol.base); } handles.push(self.fetch_margin_loans(&symbol.base, Some(symbol))); } } flatten_results(join_all(handles).await) } async fn repays(&self) -> Result<Vec<exchange::Repay>> { let mut handles = Vec::new(); let exchange_symbols = self .fetch_exchange_symbols(&EndpointsGlobal::ExchangeInfo.to_string()) .await?; let all_symbols: Vec<String> = exchange_symbols.iter().map(|x| x.symbol.clone()).collect(); let mut processed_assets = HashSet::new(); for symbol in self.symbols().iter() { if all_symbols.contains(&symbol.join("")) { if !processed_assets.contains(&symbol.base) { handles.push(self.fetch_margin_repays(&symbol.base, None)); processed_assets.insert(symbol.base.clone()); } handles.push(self.fetch_margin_repays(&symbol.base, Some(symbol))); } } flatten_results(join_all(handles).await) } async fn deposits(&self) -> Result<Vec<exchange::Deposit>> { let mut deposits = Vec::new(); deposits.extend( self.fetch_fiat_deposits() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Deposit>>(), ); deposits.extend( self.fetch_deposits() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Deposit>>(), ); Ok(deposits) } async fn withdraws(&self) -> Result<Vec<exchange::Withdraw>> { let mut withdraws = Vec::new(); withdraws.extend( self.fetch_fiat_withdraws() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Withdraw>>(), ); withdraws.extend( self.fetch_withdraws() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Withdraw>>(), ); Ok(withdraws) } } #[async_trait] impl ExchangeClient for BinanceFetcher<RegionGlobal> { async fn prices( &self, asset_pair: &AssetPair, start: DateTime<Utc>, end: DateTime<Utc>, ) -> Result<Vec<Candle>> { self.fetch_prices_in_range( &EndpointsGlobal::Klines.to_string(), &asset_pair.join(""), start.timestamp_millis().try_into()?, end.timestamp_millis().try_into()?, ).await } } #[async_trait] impl ExchangeDataFetcher for BinanceFetcher<RegionUs> { async fn trades(&self) -> Result<Vec<exchange::Trade>> { let all_symbols: Vec<String> = self .fetch_exchange_symbols(&EndpointsUs::ExchangeInfo.to_string()) .await? .into_iter() .map(|x| x.symbol) .collect(); let endpoint = EndpointsUs::Trades.to_string(); let mut handles = Vec::new(); for symbol in self.symbols().iter() { if all_symbols.contains(&symbol.join("")) { handles.push(self.fetch_trades(&endpoint, &symbol)); } } flatten_results(join_all(handles).await) } async fn margin_trades(&self) -> Result<Vec<exchange::Trade>> { Ok(Vec::new()) } async fn loans(&self) -> Result<Vec<exchange::Loan>> { Ok(Vec::new()) } async fn repays(&self) -> Result<Vec<exchange::Repay>> { Ok(Vec::new()) } async fn deposits(&self) -> Result<Vec<exchange::Deposit>> { let mut deposits = Vec::new(); deposits.extend( self.fetch_fiat_deposits() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Deposit>>(), ); deposits.extend( self.fetch_deposits() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Deposit>>(), ); Ok(deposits) } async fn withdraws(&self) -> Result<Vec<exchange::Withdraw>> { let mut withdraws = Vec::new(); withdraws.extend( self.fetch_fiat_withdraws() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Withdraw>>(), ); withdraws.extend( self.fetch_withdraws() .await? .into_iter() .map(|x| x.into()) .collect::<Vec<exchange::Withdraw>>(), ); Ok(withdraws) } } #[async_trait] impl AssetsInfo for BinanceFetcher<RegionGlobal> { async fn price_at(&self, asset_pair: &AssetPair, time: &DateTime<Utc>) -> Result<f64> { self.fetch_price_at( &EndpointsGlobal::Prices.to_string(), &asset_pair.join(""), time, ) .await } } fn flatten_results<T, U>(results: Vec<Result<Vec<T>>>) -> Result<Vec<U>> where T: Into<U>, { Ok(results .into_iter() .collect::<Result<Vec<Vec<T>>>>()? .into_iter() .flatten() .map(|x| x.into()) .collect()) }
set: d.fiat_currency, amount: d.amount, fee: Some(d.platform_fee), time: d.create_time, is_fiat: true, } } } impl From<FiatOrder> for exchange::Withdraw { fn from(d: FiatOrder) -> Self { Self { source_id: d.id, source: "binance".to_string(), asset: d.fiat_currency, amount: d.amount, fee: d.transaction_fee + d.platform_fee, time: d.create_time, } } } impl From<Deposit> for exchange::Deposit { fn from(d: Deposit) -> Self { Self { source_id: d.id, source: "binance".to_string(), asset: d.coin, amount: d.amount, fee: None, time: d.insert_time, is_fiat: false, } } } impl From<Withdraw> for exchange::Withdraw { fn from(w: Withdraw) -> Self { Self { source_id: w.id, source: "binance".to_string(), asset: w.coin, amount: w.amount, time: w.apply_time, fee: w.transaction_fee, } } } impl From<Trade> for exchange::Trade { fn from(t: Trade) -> Self { Self { source_id: t.id.to_string(), source: "binance".to_string(), symbol: t.symbol, base_asset: t.base_asset, quote_asset: t.quote_asset, price: t.price, amount: t.qty, fee: t.commission, fee_asset: t.commission_asset, time: t.time, side: if t.is_buyer { exchange::TradeSide::Buy } else { exchange::TradeSide::Sell }, } } } impl From<MarginLoan> for exchange::Loan { fn from(m: MarginLoan) -> Self { Self { source_id: m.tx_id.to_string(), source: "binance".to_string(), asset: m.asset, amount: m.principal, time: m.timestamp, status: match m.status.as_str() { "CONFIRMED" => exchange::Status::Success, _ => exchange::Status::Failure, }, } } } impl From<MarginRepay> for exchange::Repay { fn from(r: MarginRepay) -> Self { Self { source_id: r.tx_id.to_string(), source: "bin
random
[ { "content": "pub fn get_asset_price_bucket(bucket: u16, asset: &AssetPair) -> Result<Option<Vec<Candle>>> {\n\n let conn = Connection::open(DB_NAME)?;\n\n\n\n let mut stmt =\n\n conn.prepare(\"SELECT prices FROM asset_price_buckets WHERE bucket = ?1 AND asset = ?2\")?;\n\n let mut iter = stmt.q...
Rust
deps/stb-image/image.rs
tomaka/declmagic
df3abdcd89cd1515f93c369401ac93581c3d4382
use stb_image::bindgen::*; use std::any::Any; use libc; use libc::{c_void, c_int}; use std::slice::raw::buf_as_slice; pub struct Image<T> { pub width : uint, pub height : uint, pub depth : uint, pub data : Vec<T>, } pub fn new_image<T>(width: uint, height: uint, depth: uint, data: Vec<T>) -> Image<T> { Image::<T> { width : width, height : height, depth : depth, data : data, } } pub enum LoadResult { Error(String), ImageU8(Image<u8>), ImageF32(Image<f32>), } impl LoadResult { pub fn from_result(res: Result<LoadResult,Box<Any>>)-> LoadResult { match res { Ok(res) => res, Err(e) => Error(e.to_string()), } } } pub fn load(path: &Path) -> LoadResult { let force_depth = 0; load_with_depth(path, force_depth, false) } fn load_internal<T: Clone>(buf : *const T, w : c_int, h : c_int, d : c_int) -> Image<T> { unsafe { let data = buf_as_slice(buf, (w * h * d) as uint, |s| { Vec::from_slice(s) }); libc::free(buf as *mut c_void); Image::<T>{ width : w as uint, height : h as uint, depth : d as uint, data : data} } } pub fn load_with_depth(path: &Path, force_depth: uint, convert_hdr: bool) -> LoadResult { unsafe { let mut width = 0 as c_int; let mut height = 0 as c_int; let mut depth = 0 as c_int; let path_as_str = match path.as_str() { Some(s) => s, None => return Error("path is not valid utf8".to_string()), }; path_as_str.with_c_str(|bytes| { if !convert_hdr && stbi_is_hdr(bytes)!=0 { let buffer = stbi_loadf(bytes, &mut width, &mut height, &mut depth, force_depth as c_int); if buffer.is_null() { Error("stbi_loadf failed".to_string()) } else { ImageF32(load_internal(buffer, width, height, depth)) } } else { let buffer = stbi_load(bytes, &mut width, &mut height, &mut depth, force_depth as c_int); if buffer.is_null() { Error("stbi_load failed".to_string()) } else { ImageU8(load_internal(buffer, width, height, depth)) } } }) } } pub fn load_from_memory(buffer: &[u8]) -> LoadResult { let force_depth = 0; load_from_memory_with_depth(buffer, force_depth, false) } pub fn load_from_memory_with_depth(buffer: &[u8], force_depth: uint, convert_hdr:bool) -> LoadResult { unsafe { let mut width = 0 as c_int; let mut height = 0 as c_int; let mut depth = 0 as c_int; if !convert_hdr && stbi_is_hdr_from_memory(buffer.as_ptr(), buffer.len() as c_int) != 0 { let buffer = stbi_loadf_from_memory(buffer.as_ptr(), buffer.len() as c_int, &mut width, &mut height, &mut depth, force_depth as c_int); if buffer.is_null() { Error("stbi_loadf_from_memory failed".to_string()) } else { let actual_depth = if force_depth != 0 { force_depth as c_int } else { depth }; ImageF32(load_internal(buffer, width, height, actual_depth)) } } else { let buffer = stbi_load_from_memory(buffer.as_ptr(), buffer.len() as c_int, &mut width, &mut height, &mut depth, force_depth as c_int); if buffer.is_null() { Error("stbi_load_from_memory failed".to_string()) } else { let actual_depth = if force_depth != 0 { force_depth as c_int } else { depth }; ImageU8(load_internal(buffer, width, height, actual_depth)) } } } }
use stb_image::bindgen::*; use std::any::Any; use libc; use libc::{c_void, c_int}; use std::slice::raw::buf_as_slice; pub struct Image<T> { pub width : uint, pub height : uint, pub depth : uint, pub data : Vec<T>, } pub fn new_image<T>(width: uint, height: uint, depth: uint, data: Vec<T>) -> Image<T> { Image::<T> { width : width, height : height, depth : depth, data : data, } } pub enum LoadResult { Error(String), ImageU8(Image<u8>), ImageF32(Image<f32>), } impl LoadResult { pub fn from_result(res: Result<LoadResult,Box<Any>>)-> LoadResult { match res { Ok(res) => res, Err(e) => Error(e.to_string()), } } } pub fn load(path: &Path) -> LoadResult { let force_depth = 0; load_with_depth(path, force_depth, false) } fn load_internal<T: Clone>(buf : *const T, w : c_int, h : c_int, d : c_int) -> Image<T> { unsafe { let data = buf_as_slice(buf, (w * h * d) as uint, |s| { Vec::from_slice(s) });
pub fn load_with_depth(path: &Path, force_depth: uint, convert_hdr: bool) -> LoadResult { unsafe { let mut width = 0 as c_int; let mut height = 0 as c_int; let mut depth = 0 as c_int; let path_as_str = match path.as_str() { Some(s) => s, None => return Error("path is not valid utf8".to_string()), }; path_as_str.with_c_str(|bytes| { if !convert_hdr && stbi_is_hdr(bytes)!=0 { let buffer = stbi_loadf(bytes, &mut width, &mut height, &mut depth, force_depth as c_int); if buffer.is_null() { Error("stbi_loadf failed".to_string()) } else { ImageF32(load_internal(buffer, width, height, depth)) } } else { let buffer = stbi_load(bytes, &mut width, &mut height, &mut depth, force_depth as c_int); if buffer.is_null() { Error("stbi_load failed".to_string()) } else { ImageU8(load_internal(buffer, width, height, depth)) } } }) } } pub fn load_from_memory(buffer: &[u8]) -> LoadResult { let force_depth = 0; load_from_memory_with_depth(buffer, force_depth, false) } pub fn load_from_memory_with_depth(buffer: &[u8], force_depth: uint, convert_hdr:bool) -> LoadResult { unsafe { let mut width = 0 as c_int; let mut height = 0 as c_int; let mut depth = 0 as c_int; if !convert_hdr && stbi_is_hdr_from_memory(buffer.as_ptr(), buffer.len() as c_int) != 0 { let buffer = stbi_loadf_from_memory(buffer.as_ptr(), buffer.len() as c_int, &mut width, &mut height, &mut depth, force_depth as c_int); if buffer.is_null() { Error("stbi_loadf_from_memory failed".to_string()) } else { let actual_depth = if force_depth != 0 { force_depth as c_int } else { depth }; ImageF32(load_internal(buffer, width, height, actual_depth)) } } else { let buffer = stbi_load_from_memory(buffer.as_ptr(), buffer.len() as c_int, &mut width, &mut height, &mut depth, force_depth as c_int); if buffer.is_null() { Error("stbi_load_from_memory failed".to_string()) } else { let actual_depth = if force_depth != 0 { force_depth as c_int } else { depth }; ImageU8(load_internal(buffer, width, height, actual_depth)) } } } }
libc::free(buf as *mut c_void); Image::<T>{ width : w as uint, height : h as uint, depth : d as uint, data : data} } }
function_block-function_prefixed
[ { "content": "/// Load each OpenGL symbol using a custom load function. This allows for the\n\n/// use of functions like `glfwGetProcAddress` or `SDL_GL_GetProcAddress`.\n\n///\n\n/// ~~~\n\n/// let gl = gl::load_with(glfw::get_proc_address);\n\n/// ~~~\n\npub fn load_with(loadfn: |symbol: &str| -> *const libc:...
Rust
keyvalues-parser/src/text/parse.rs
LovecraftianHorror/vdf-pest
a9f3966b7ec7b389a18351d6469749ce8c93253d
#![allow(renamed_and_removed_lints)] #![allow(clippy::unknown_clippy_lints)] #![allow(clippy::upper_case_acronyms)] use pest::{iterators::Pair as PestPair, Parser}; use pest_derive::Parser; use std::borrow::Cow; use crate::{error::Result, Obj, PartialVdf as Vdf, Value}; macro_rules! common_parsing { ($parser:ty, $rule:ty, $parse_escaped:expr) => { pub fn parse<'a>(s: &'a str) -> Result<Vdf<'a>> { let mut full_grammar = <$parser>::parse(<$rule>::vdf, s)?; let mut bases = Vec::new(); loop { let pair = full_grammar.next().unwrap(); if let <$rule>::base_macro = pair.as_rule() { let base_path_string = pair.into_inner().next().unwrap(); let base_path = match base_path_string.as_rule() { <$rule>::quoted_raw_string => base_path_string.into_inner().next().unwrap(), <$rule>::unquoted_string => base_path_string, _ => unreachable!("Prevented by grammar"), } .as_str(); bases.push(Cow::from(base_path)); } else { let (key, value) = parse_pair(pair); return Ok(Vdf { key, value, bases }); } } } fn parse_pair(grammar_pair: PestPair<'_, $rule>) -> (Cow<'_, str>, Value<'_>) { if let <$rule>::pair = grammar_pair.as_rule() { let mut grammar_pair_innards = grammar_pair.into_inner(); let grammar_string = grammar_pair_innards.next().unwrap(); let key = parse_string(grammar_string); let grammar_value = grammar_pair_innards.next().unwrap(); let value = Value::from(grammar_value); (key, value) } else { unreachable!("Prevented by grammar"); } } fn parse_string(grammar_string: PestPair<'_, $rule>) -> Cow<'_, str> { match grammar_string.as_rule() { <$rule>::quoted_string => { let quoted_inner = grammar_string.into_inner().next().unwrap(); if $parse_escaped { parse_escaped_string(quoted_inner) } else { Cow::from(quoted_inner.as_str()) } } <$rule>::unquoted_string => { let s = grammar_string.as_str(); Cow::from(s) } _ => unreachable!("Prevented by grammar"), } } fn parse_escaped_string(inner: PestPair<'_, $rule>) -> Cow<'_, str> { let s = inner.as_str(); if s.contains('\\') { let mut escaped = String::with_capacity(s.len()); let mut it = s.chars(); while let Some(ch) = it.next() { if ch == '\\' { match it.next() { Some('n') => escaped.push('\n'), Some('r') => escaped.push('\r'), Some('t') => escaped.push('\t'), Some('\\') => escaped.push('\\'), Some('\"') => escaped.push('\"'), _ => unreachable!("Prevented by grammar"), } } else { escaped.push(ch) } } Cow::from(escaped) } else { Cow::from(s) } } impl<'a> From<PestPair<'a, $rule>> for Value<'a> { fn from(grammar_value: PestPair<'a, $rule>) -> Self { match grammar_value.as_rule() { <$rule>::quoted_string | <$rule>::unquoted_string => { Self::Str(parse_string(grammar_value)) } <$rule>::obj => { let mut obj = Obj::new(); for grammar_pair in grammar_value.into_inner() { let (key, value) = parse_pair(grammar_pair); let entry = obj.entry(key).or_default(); (*entry).push(value); } Self::Obj(obj) } _ => unreachable!("Prevented by grammar"), } } } }; } pub use escaped::{parse as escaped_parse, PestError as EscapedPestError}; pub use raw::{parse as raw_parse, PestError as RawPestError}; impl<'a> Vdf<'a> { pub fn parse(s: &'a str) -> Result<Self> { escaped_parse(s) } pub fn parse_raw(s: &'a str) -> Result<Self> { raw_parse(s) } } impl<'a> crate::Vdf<'a> { pub fn parse(s: &'a str) -> Result<Self> { Ok(crate::Vdf::from(Vdf::parse(s)?)) } pub fn parse_raw(s: &'a str) -> Result<Self> { Ok(crate::Vdf::from(Vdf::parse_raw(s)?)) } } mod escaped { use super::*; #[derive(Parser)] #[grammar = "grammars/escaped.pest"] struct EscapedParser; pub type PestError = pest::error::Error<Rule>; common_parsing!(EscapedParser, Rule, true); } mod raw { use super::*; #[derive(Parser)] #[grammar = "grammars/raw.pest"] struct RawParser; pub type PestError = pest::error::Error<Rule>; common_parsing!(RawParser, Rule, false); }
#![allow(renamed_and_removed_lints)] #![allow(clippy::unknown_clippy_lints)] #![allow(clippy::upper_case_acronyms)] use pest::{iterators::Pair as PestPair, Parser}; use pest_derive::Parser; use std::borrow::Cow; use crate::{error::Result, Obj, PartialVdf as Vdf, Value}; macro_rules! common_parsing { ($parser:ty, $rule:ty, $parse_escaped:expr) => { pub fn parse<'a>(s: &'a str) -> Result<Vdf<'a>> { let mut full_grammar = <$parser>::parse(<$rule>::vdf, s)?; let mut bases = Vec::new(); loop { let pair = full_grammar.next().unwrap(); if let <$rule>::base_macro = pair.as_rule() { let base_path_string = pair.into_inner().next().unwrap(); let base_path = match base_path_string.as_rule() { <$rule>::quoted_raw_string => base_path_string.into_inner().next().unwrap(), <$rule>::unquoted_string => base_path_string, _ => unreachable!("Prevented by grammar"), } .as_str(); bases.push(Cow::from(base_path)); } else { let (key, value) = parse_pair(pair); return Ok(Vdf { key, value, bases }); } } } fn parse_pair(grammar_pair: PestPair<'_, $rule>) -> (Cow<'_, str>, Value<'_>) { if let <$rule>::pair = grammar_pair.as_rule() { let mut grammar_pair_innards = grammar_pair.into_inner(); let grammar_string = grammar_pair_innards.next().unwrap(); let key = parse_string(grammar_string); let grammar_value = grammar_pair_innards.next().unwrap(); let value = Value::from(grammar_value); (key, value) } else { unreachable!("Prevented by grammar"); } } fn parse_string(grammar_string: PestPair<'_, $rule>) -> Cow<'_, str> { match grammar_string.as_rule() { <$rule>::quoted_string => { let quoted_inner = grammar_string.into_inner().next().unwrap(); if $parse_escaped { parse_escaped_string(quoted_inner) } else { Cow::from(quoted_inner.as_str()) } } <$rule>::unquoted_string => { let s = grammar_string.as_str(); Cow::from(s) } _ => unreachable!("Prevented by grammar"), } } fn parse_escaped_string(inner: PestPair<'_, $rule>) -> Cow<'_, str> { let s = inner.as_str(); if s.contains('\\') { let mut escaped = String::with_capacity(s.len()); let mut it = s.chars(); while let Some(ch) = it.next() { if ch == '\\' { match it.next() { Some('n') => escaped.push('\n'), Some('r') => escaped.
rser)] #[grammar = "grammars/escaped.pest"] struct EscapedParser; pub type PestError = pest::error::Error<Rule>; common_parsing!(EscapedParser, Rule, true); } mod raw { use super::*; #[derive(Parser)] #[grammar = "grammars/raw.pest"] struct RawParser; pub type PestError = pest::error::Error<Rule>; common_parsing!(RawParser, Rule, false); }
push('\r'), Some('t') => escaped.push('\t'), Some('\\') => escaped.push('\\'), Some('\"') => escaped.push('\"'), _ => unreachable!("Prevented by grammar"), } } else { escaped.push(ch) } } Cow::from(escaped) } else { Cow::from(s) } } impl<'a> From<PestPair<'a, $rule>> for Value<'a> { fn from(grammar_value: PestPair<'a, $rule>) -> Self { match grammar_value.as_rule() { <$rule>::quoted_string | <$rule>::unquoted_string => { Self::Str(parse_string(grammar_value)) } <$rule>::obj => { let mut obj = Obj::new(); for grammar_pair in grammar_value.into_inner() { let (key, value) = parse_pair(grammar_pair); let entry = obj.entry(key).or_default(); (*entry).push(value); } Self::Obj(obj) } _ => unreachable!("Prevented by grammar"), } } } }; } pub use escaped::{parse as escaped_parse, PestError as EscapedPestError}; pub use raw::{parse as raw_parse, PestError as RawPestError}; impl<'a> Vdf<'a> { pub fn parse(s: &'a str) -> Result<Self> { escaped_parse(s) } pub fn parse_raw(s: &'a str) -> Result<Self> { raw_parse(s) } } impl<'a> crate::Vdf<'a> { pub fn parse(s: &'a str) -> Result<Self> { Ok(crate::Vdf::from(Vdf::parse(s)?)) } pub fn parse_raw(s: &'a str) -> Result<Self> { Ok(crate::Vdf::from(Vdf::parse_raw(s)?)) } } mod escaped { use super::*; #[derive(Pa
random
[ { "content": "/// Serialize the `value` into an IO stream of VDF text with a custom top level VDF key\n\n///\n\n/// # Errors\n\n///\n\n/// This will return an error if the input can't be represented with valid VDF\n\npub fn to_writer_with_key<W, T>(writer: &mut W, value: &T, key: &str) -> Result<()>\n\nwhere\n\...
Rust
agent/test-agent/tests/mock.rs
webern/bottlerocket-test-system
6b523be719c79449784ae75b7bc18056d857aa89
/*! The purpose of this test is to demonstrate the mocking of a [`Client`] and a [`Bootstrap`] in order to test a [`Runner`] with the [`TestAgent`]. !*/ use async_trait::async_trait; use model::{Configuration, Outcome}; use serde::{Deserialize, Serialize}; use std::fmt::{Debug, Display}; use std::path::PathBuf; use tempfile::{tempdir, TempDir}; use test_agent::{BootstrapData, Client, Runner}; use test_agent::{Spec, TestResults}; use tokio::time::{sleep, Duration}; struct MyRunner { _spec: Spec<MyConfig>, } #[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)] struct MyConfig {} impl Configuration for MyConfig {} #[async_trait] impl Runner for MyRunner { type C = MyConfig; type E = String; async fn new(spec: Spec<Self::C>) -> Result<Self, Self::E> { Ok(Self { _spec: spec }) } async fn run(&mut self) -> Result<TestResults, Self::E> { println!("MyRunner::run"); for i in 1..=5 { println!("Hello {}", i); sleep(Duration::from_millis(50)).await; } Ok(TestResults { outcome: Outcome::Pass, ..TestResults::default() }) } async fn terminate(&mut self) -> Result<(), Self::E> { println!("MyRunner::terminate"); Ok(()) } } struct MockClient { results_dir: TempDir, results_file: TempDir, } #[async_trait] impl Client for MockClient { type E = String; async fn new(_: BootstrapData) -> Result<Self, Self::E> { Ok(Self { results_dir: tempdir().unwrap(), results_file: tempdir().unwrap(), }) } async fn spec<C>(&self) -> Result<Spec<C>, Self::E> where C: Configuration, { println!("MockClient::get"); Ok(Spec { name: "mock-test".into(), configuration: C::default(), secrets: Default::default(), results_dir: Default::default(), }) } async fn send_test_starting(&self) -> Result<(), Self::E> { println!("MockClient::send_test_starting"); Ok(()) } async fn send_test_done(&self, results: TestResults) -> Result<(), Self::E> { println!("MockClient::send_test_done: {:?}", results); Ok(()) } async fn send_test_results(&self, results: TestResults) -> Result<(), Self::E> { println!("MockClient::send_test_results: {:?}", results); Ok(()) } async fn send_error<E>(&self, error: E) -> Result<(), Self::E> where E: Debug + Display + Send + Sync, { println!("MockClient::send_error {}", error); Ok(()) } async fn keep_running(&self) -> Result<bool, Self::E> { Ok(false) } async fn results_directory(&self) -> Result<PathBuf, Self::E> { Ok(self.results_dir.path().to_path_buf()) } async fn results_file(&self) -> Result<PathBuf, Self::E> { Ok(self.results_file.path().join("result.tar.gz")) } async fn retries(&self) -> Result<u32, Self::E> { Ok(0) } } #[tokio::test] async fn mock_test() -> std::io::Result<()> { let mut agent_main = test_agent::TestAgent::<MockClient, MyRunner>::new(BootstrapData { test_name: String::from("hello-test"), }) .await .unwrap(); agent_main.run().await.unwrap(); assert!(std::path::Path::new(&agent_main.results_file().await.unwrap()).is_file()); Ok(()) }
/*! The purpose of this test is to demonstrate the mocking of a [`Client`] and a [`Bootstrap`] in order to test a [`Runner`] with the [`TestAgent`]. !*/ use async_trait::async_trait; use model::{Configuration, Outcome}; use serde::{Deserialize, Serialize}; use std::fmt::{Debug, Display}; use std::path::PathBuf; use tempfile::{tempdir, TempDir}; use test_agent::{BootstrapData, Client, Runner}; use test_agent::{Spec, TestResults}; use tokio::time::{sleep, Duration}; struct MyRunner { _spec: Spec<MyConfig>, } #[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)] struct MyConfig {} impl Configuration for MyConfig {} #[async_trait] impl Runner for MyRunner { type C = MyConfig; type E = String; async fn new(spec: Spec<Self::C>) -> Result<Self, Self::E> { Ok(Self { _spec: spec }) } async fn run(&mut self) -> Result<Tes
_main.run().await.unwrap(); assert!(std::path::Path::new(&agent_main.results_file().await.unwrap()).is_file()); Ok(()) }
tResults, Self::E> { println!("MyRunner::run"); for i in 1..=5 { println!("Hello {}", i); sleep(Duration::from_millis(50)).await; } Ok(TestResults { outcome: Outcome::Pass, ..TestResults::default() }) } async fn terminate(&mut self) -> Result<(), Self::E> { println!("MyRunner::terminate"); Ok(()) } } struct MockClient { results_dir: TempDir, results_file: TempDir, } #[async_trait] impl Client for MockClient { type E = String; async fn new(_: BootstrapData) -> Result<Self, Self::E> { Ok(Self { results_dir: tempdir().unwrap(), results_file: tempdir().unwrap(), }) } async fn spec<C>(&self) -> Result<Spec<C>, Self::E> where C: Configuration, { println!("MockClient::get"); Ok(Spec { name: "mock-test".into(), configuration: C::default(), secrets: Default::default(), results_dir: Default::default(), }) } async fn send_test_starting(&self) -> Result<(), Self::E> { println!("MockClient::send_test_starting"); Ok(()) } async fn send_test_done(&self, results: TestResults) -> Result<(), Self::E> { println!("MockClient::send_test_done: {:?}", results); Ok(()) } async fn send_test_results(&self, results: TestResults) -> Result<(), Self::E> { println!("MockClient::send_test_results: {:?}", results); Ok(()) } async fn send_error<E>(&self, error: E) -> Result<(), Self::E> where E: Debug + Display + Send + Sync, { println!("MockClient::send_error {}", error); Ok(()) } async fn keep_running(&self) -> Result<bool, Self::E> { Ok(false) } async fn results_directory(&self) -> Result<PathBuf, Self::E> { Ok(self.results_dir.path().to_path_buf()) } async fn results_file(&self) -> Result<PathBuf, Self::E> { Ok(self.results_file.path().join("result.tar.gz")) } async fn retries(&self) -> Result<u32, Self::E> { Ok(0) } } #[tokio::test] async fn mock_test() -> std::io::Result<()> { let mut agent_main = test_agent::TestAgent::<MockClient, MyRunner>::new(BootstrapData { test_name: String::from("hello-test"), }) .await .unwrap(); agent
random
[ { "content": "/// Print a value using `serde_json` `to_string_pretty` for types that implement Serialize.\n\npub fn json_display<T: Serialize>(object: T) -> String {\n\n serde_json::to_string_pretty(&object).unwrap_or_else(|e| format!(\"Serialization failed: {}\", e))\n\n}\n\n\n\n/// Implement `Display` usin...
Rust
demo/src/features/mesh/jobs/write.rs
jlowry/rafx
515aeeae3e57e1c520e320316197326294fc099e
use rafx::render_feature_write_job_prelude::*; use rafx::api::RafxPrimitiveTopology; use rafx::framework::{VertexDataLayout, VertexDataSetLayout}; use serde::{Deserialize, Serialize}; #[derive(Copy, Clone, Debug, Serialize, Deserialize, Default)] #[repr(C)] pub struct MeshVertex { pub position: [f32; 3], pub normal: [f32; 3], pub tangent: [f32; 4], pub tex_coord: [f32; 2], } lazy_static::lazy_static! { pub static ref MESH_VERTEX_LAYOUT : VertexDataSetLayout = { use rafx::api::RafxFormat; VertexDataLayout::build_vertex_layout(&MeshVertex::default(), |builder, vertex| { builder.add_member(&vertex.position, "POSITION", RafxFormat::R32G32B32_SFLOAT); builder.add_member(&vertex.normal, "NORMAL", RafxFormat::R32G32B32_SFLOAT); builder.add_member(&vertex.tangent, "TANGENT", RafxFormat::R32G32B32A32_SFLOAT); builder.add_member(&vertex.tex_coord, "TEXCOORD", RafxFormat::R32G32_SFLOAT); }).into_set(RafxPrimitiveTopology::TriangleList) }; } use super::ExtractedFrameNodeMeshData; use rafx::api::{RafxIndexBufferBinding, RafxIndexType, RafxVertexBufferBinding}; use rafx::framework::{DescriptorSetArc, MaterialPassResource, ResourceArc}; use rafx::nodes::{FrameNodeIndex, PerViewNode}; struct PreparedSubmitNodeMeshData { material_pass_resource: ResourceArc<MaterialPassResource>, per_view_descriptor_set: DescriptorSetArc, per_material_descriptor_set: Option<DescriptorSetArc>, per_instance_descriptor_set: DescriptorSetArc, frame_node_index: FrameNodeIndex, mesh_part_index: usize, } impl std::fmt::Debug for PreparedSubmitNodeMeshData { fn fmt( &self, f: &mut std::fmt::Formatter<'_>, ) -> std::fmt::Result { f.debug_struct("PreparedSubmitNodeMeshData") .field("frame_node_index", &self.frame_node_index) .field("mesh_part_index", &self.mesh_part_index) .finish() } } pub struct MeshWriteJob { extracted_frame_node_mesh_data: Vec<Option<ExtractedFrameNodeMeshData>>, prepared_submit_node_mesh_data: Vec<PreparedSubmitNodeMeshData>, } impl MeshWriteJob { pub fn new() -> Self { MeshWriteJob { extracted_frame_node_mesh_data: Default::default(), prepared_submit_node_mesh_data: Default::default(), } } pub fn push_submit_node( &mut self, view_node: &PerViewNode, per_view_descriptor_set: DescriptorSetArc, per_material_descriptor_set: Option<DescriptorSetArc>, per_instance_descriptor_set: DescriptorSetArc, mesh_part_index: usize, material_pass_resource: ResourceArc<MaterialPassResource>, ) -> usize { let submit_node_index = self.prepared_submit_node_mesh_data.len(); self.prepared_submit_node_mesh_data .push(PreparedSubmitNodeMeshData { material_pass_resource: material_pass_resource.clone(), per_view_descriptor_set, per_material_descriptor_set, per_instance_descriptor_set, frame_node_index: view_node.frame_node_index(), mesh_part_index, }); submit_node_index } pub fn set_extracted_frame_node_mesh_data( &mut self, extracted_frame_node_mesh_data: Vec<Option<ExtractedFrameNodeMeshData>>, ) { self.extracted_frame_node_mesh_data = extracted_frame_node_mesh_data; } } impl WriteJob for MeshWriteJob { fn render_element( &self, write_context: &mut RenderJobWriteContext, _view: &RenderView, render_phase_index: RenderPhaseIndex, index: SubmitNodeId, ) -> RafxResult<()> { profiling::scope!(super::RENDER_ELEMENT_SCOPE_NAME); let command_buffer = &write_context.command_buffer; let render_node_data = &self.prepared_submit_node_mesh_data[index as usize]; let frame_node_data: &ExtractedFrameNodeMeshData = self.extracted_frame_node_mesh_data [render_node_data.frame_node_index as usize] .as_ref() .unwrap(); let mesh_part = &frame_node_data.mesh_asset.inner.mesh_parts [render_node_data.mesh_part_index] .as_ref() .unwrap(); let pipeline = write_context .resource_context .graphics_pipeline_cache() .get_or_create_graphics_pipeline( render_phase_index, &render_node_data.material_pass_resource, &write_context.render_target_meta, &*MESH_VERTEX_LAYOUT, )?; command_buffer.cmd_bind_pipeline(&pipeline.get_raw().pipeline)?; render_node_data .per_view_descriptor_set .bind(command_buffer)?; if let Some(per_material_descriptor_set) = &render_node_data.per_material_descriptor_set { per_material_descriptor_set.bind(command_buffer).unwrap(); } render_node_data .per_instance_descriptor_set .bind(command_buffer)?; command_buffer.cmd_bind_vertex_buffers( 0, &[RafxVertexBufferBinding { buffer: &frame_node_data .mesh_asset .inner .vertex_buffer .get_raw() .buffer, byte_offset: mesh_part.vertex_buffer_offset_in_bytes as u64, }], )?; command_buffer.cmd_bind_index_buffer(&RafxIndexBufferBinding { buffer: &frame_node_data .mesh_asset .inner .index_buffer .get_raw() .buffer, byte_offset: mesh_part.index_buffer_offset_in_bytes as u64, index_type: RafxIndexType::Uint16, })?; command_buffer.cmd_draw_indexed( mesh_part.index_buffer_size_in_bytes / 2, 0, 0, )?; Ok(()) } fn feature_debug_name(&self) -> &'static str { super::render_feature_debug_name() } fn feature_index(&self) -> RenderFeatureIndex { super::render_feature_index() } }
use rafx::render_feature_write_job_prelude::*; use rafx::api::RafxPrimitiveTopology; use rafx::framework::{VertexDataLayout, VertexDataSetLayout}; use serde::{Deserialize, Serialize}; #[derive(Copy, Clone, Debug, Serialize, Deserialize, Default)] #[repr(C)] pub struct MeshVertex { pub position: [f32; 3], pub normal: [f32; 3], pub tangent: [f32; 4], pub tex_coord: [f32; 2], } lazy_static::lazy_static! { pub static ref MESH_VERTEX_LAYOUT : VertexDataSetLayout = { use rafx::api::RafxFormat; VertexDataLayout::build_vertex_layout(&MeshVertex::default(), |builder, vertex| { builder.add_member(&vertex.position, "POSITION", RafxFormat::R32G32B32_SFLOAT); builder.add_member(&vertex.normal, "NORMAL", RafxFormat::R32G32B32_SFLOAT); builder.add_member(&vertex.tangent, "TANGENT", RafxFormat::R32G32B32A32_SFLOAT); builder.add_member(&vertex.tex_coord, "TEXCOORD", RafxFormat::R32G32_SFLOAT); }).into_set(RafxPrimitiveTopology::TriangleList) }; } use super::ExtractedFrameNodeMeshData; use rafx::api::{RafxIndexBufferBinding, RafxIndexType, RafxVertexBufferBinding}; use rafx::framework::{DescriptorSetArc, MaterialPassResource, ResourceArc}; use rafx::nodes::{FrameNodeIndex, PerViewNode}; struct PreparedSubmitNodeMeshData { material_pass_resource: ResourceArc<MaterialPassResource>, per_view_descriptor_set: DescriptorSetArc, per_material_descriptor_set: Option<DescriptorSetArc>, per_instance_descriptor_set: DescriptorSetArc, frame_node_index: FrameNodeIndex, mesh_part_index: usize, } impl std::fmt::Debug for PreparedSubmitNodeMeshData { fn fmt( &self, f: &mut std::fmt::Formatter<'_>, ) -> std::fmt::Result { f.debug_struct("PreparedSubmitNodeMeshData") .field("frame_node_index", &self.frame_node_index) .field("mesh_part_index", &self.mesh_part_index) .finish() } } pub struct MeshWriteJob { extracted_frame_node_mesh_data: Vec<Option<ExtractedFrameNodeMeshData>>, prepared_submit_node_mesh_data: Vec<PreparedSubmitNodeMeshData>, } impl MeshWriteJob { pub fn new() -> Self { MeshWriteJob { extracted_frame_node_mesh_data: Default::default(), prepared_submit_node_mesh_data: Default::default(), } } pub fn push_submit_node( &mut self, view_node: &PerViewNode, per_view_descriptor_set: DescriptorSetArc, per_material_descriptor_set: Option<DescriptorSetArc>, per_instance_descriptor_set: DescriptorSetArc, mesh_part_index: usize, material_pass_resource: ResourceArc<MaterialPassResource>, ) -> usize { let submit_node_index = self.prepared_submit_node_mesh_data.len(); self.prepared_submit_node_mesh_data .push(PreparedSubmitNodeMeshData { material_pass_resource: material_pass_resource.clone(), per_view_descriptor_set, per_material_descriptor_set, per_instance_descriptor_set, frame_node_index: view_node.frame_node_index(), mesh_part_index, }); submit_node_index }
} impl WriteJob for MeshWriteJob { fn render_element( &self, write_context: &mut RenderJobWriteContext, _view: &RenderView, render_phase_index: RenderPhaseIndex, index: SubmitNodeId, ) -> RafxResult<()> { profiling::scope!(super::RENDER_ELEMENT_SCOPE_NAME); let command_buffer = &write_context.command_buffer; let render_node_data = &self.prepared_submit_node_mesh_data[index as usize]; let frame_node_data: &ExtractedFrameNodeMeshData = self.extracted_frame_node_mesh_data [render_node_data.frame_node_index as usize] .as_ref() .unwrap(); let mesh_part = &frame_node_data.mesh_asset.inner.mesh_parts [render_node_data.mesh_part_index] .as_ref() .unwrap(); let pipeline = write_context .resource_context .graphics_pipeline_cache() .get_or_create_graphics_pipeline( render_phase_index, &render_node_data.material_pass_resource, &write_context.render_target_meta, &*MESH_VERTEX_LAYOUT, )?; command_buffer.cmd_bind_pipeline(&pipeline.get_raw().pipeline)?; render_node_data .per_view_descriptor_set .bind(command_buffer)?; if let Some(per_material_descriptor_set) = &render_node_data.per_material_descriptor_set { per_material_descriptor_set.bind(command_buffer).unwrap(); } render_node_data .per_instance_descriptor_set .bind(command_buffer)?; command_buffer.cmd_bind_vertex_buffers( 0, &[RafxVertexBufferBinding { buffer: &frame_node_data .mesh_asset .inner .vertex_buffer .get_raw() .buffer, byte_offset: mesh_part.vertex_buffer_offset_in_bytes as u64, }], )?; command_buffer.cmd_bind_index_buffer(&RafxIndexBufferBinding { buffer: &frame_node_data .mesh_asset .inner .index_buffer .get_raw() .buffer, byte_offset: mesh_part.index_buffer_offset_in_bytes as u64, index_type: RafxIndexType::Uint16, })?; command_buffer.cmd_draw_indexed( mesh_part.index_buffer_size_in_bytes / 2, 0, 0, )?; Ok(()) } fn feature_debug_name(&self) -> &'static str { super::render_feature_debug_name() } fn feature_index(&self) -> RenderFeatureIndex { super::render_feature_index() } }
pub fn set_extracted_frame_node_mesh_data( &mut self, extracted_frame_node_mesh_data: Vec<Option<ExtractedFrameNodeMeshData>>, ) { self.extracted_frame_node_mesh_data = extracted_frame_node_mesh_data; }
function_block-full_function
[ { "content": "pub fn default_daemon() -> distill::daemon::AssetDaemon {\n\n use crate::assets::*;\n\n\n\n distill::daemon::AssetDaemon::default()\n\n .with_importer(\"sampler\", SamplerImporter)\n\n .with_importer(\"material\", MaterialImporter)\n\n .with_importer(\"materialinstance\"...
Rust
src/transforms/rename_fields.rs
zcapper/vector
560fd106fc9a60c12ddf2c32e31ad4f2031ff1f5
use super::Transform; use crate::{ event::Event, topology::config::{DataType, TransformConfig, TransformContext, TransformDescription}, }; use indexmap::map::IndexMap; use serde::{Deserialize, Serialize}; use snafu::Snafu; use string_cache::DefaultAtom as Atom; use toml::value::Value as TomlValue; #[derive(Deserialize, Serialize, Debug)] #[serde(deny_unknown_fields)] pub struct RenameFieldsConfig { pub fields: IndexMap<String, TomlValue>, } pub struct RenameFields { fields: IndexMap<Atom, Atom>, } inventory::submit! { TransformDescription::new_without_default::<RenameFieldsConfig>("rename_fields") } #[typetag::serde(name = "rename_fields")] impl TransformConfig for RenameFieldsConfig { fn build(&self, _exec: TransformContext) -> crate::Result<Box<dyn Transform>> { Ok(Box::new(RenameFields::new(self.fields.clone())?)) } fn input_type(&self) -> DataType { DataType::Log } fn output_type(&self) -> DataType { DataType::Log } fn transform_type(&self) -> &'static str { "rename_fields" } } impl RenameFields { pub fn new(fields: IndexMap<String, TomlValue>) -> crate::Result<Self> { Ok(RenameFields { fields: fields .into_iter() .map(|kv| flatten(kv, None)) .collect::<crate::Result<_>>()?, }) } } #[derive(Debug, Eq, PartialEq, Snafu)] enum FlattenError { #[snafu(display( "The key {:?} cannot be flattened. Is it a plain string or a `a.b.c` style map?", key ))] CannotFlatten { key: String }, } fn flatten(kv: (String, TomlValue), prequel: Option<String>) -> crate::Result<(Atom, Atom)> { let (k, v) = kv; match v { TomlValue::String(s) => match prequel { Some(prequel) => Ok((format!("{}.{}", prequel, k).into(), s.into())), None => Ok((k.into(), s.into())), }, TomlValue::Table(map) => { if map.len() > 1 { Err(Box::new(FlattenError::CannotFlatten { key: k })) } else { let sub_kv = map.into_iter().next().expect("Map of len 1 has no values"); let key = match prequel { Some(prequel) => format!("{}.{}", prequel, k), None => k, }; flatten(sub_kv, Some(key)) } } TomlValue::Integer(_) | TomlValue::Float(_) | TomlValue::Boolean(_) | TomlValue::Datetime(_) | TomlValue::Array(_) => Err(Box::new(FlattenError::CannotFlatten { key: k })), } } impl Transform for RenameFields { fn transform(&mut self, mut event: Event) -> Option<Event> { for (old_key, new_key) in &self.fields { let log = event.as_mut_log(); if let Some(v) = log.remove(&old_key) { log.insert(new_key.clone(), v) } } Some(event) } } #[cfg(test)] mod tests { use super::RenameFields; use crate::{event::Event, transforms::Transform}; use indexmap::map::IndexMap; #[test] fn rename_fields() { let mut event = Event::from("message"); event.as_mut_log().insert("to_move", "some value"); event.as_mut_log().insert("do_not_move", "not moved"); let mut fields = IndexMap::new(); fields.insert("to_move".into(), "moved".into()); fields.insert("not_present".into(), "should_not_exist".into()); let mut transform = RenameFields::new(fields).unwrap(); let new_event = transform.transform(event).unwrap(); assert!(new_event.as_log().get(&"to_move".into()).is_none()); assert_eq!(new_event.as_log()[&"moved".into()], "some value".into()); assert!(new_event.as_log().get(&"not_present".into()).is_none()); assert!(new_event.as_log().get(&"should_not_exist".into()).is_none()); assert_eq!( new_event.as_log()[&"do_not_move".into()], "not moved".into() ); } }
use super::Transform; use crate::{ event::Event, topology::config::{DataType, TransformConfig, TransformContext, TransformDescription}, }; use indexmap::map::IndexMap; use serde::{Deserialize, Serialize}; use snafu::Snafu; use string_cache::DefaultAtom as Atom; use toml::value::Value as TomlValue; #[derive(Deserialize, Serialize, Debug)] #[serde(deny_unknown_fields)] pub struct RenameFieldsConfig { pub fields: IndexMap<String, TomlValue>, } pub struct RenameFields { fields: IndexMap<Atom, Atom>, } inventory::submit! { TransformDescription::new_without_default::<RenameFieldsConfig>("rename_fields") } #[typetag::serde(name = "rename_fields")] impl TransformConfig for RenameFieldsConfig { fn build(&self, _exec: TransformContext) -> crate::Result<Box<dyn Transform>> { Ok(Box::new(RenameFields::new(self.fields.clone())?)) } fn input_type(&self) -> DataType { DataType::Log } fn output_type(&self) -> DataType { DataType::Log } fn transform_type(&self) -> &'static str { "rename_fields" } } impl RenameFields { pub fn new(fields: IndexMap<String, TomlValue>) -> crate::Result<Self> {
} } #[derive(Debug, Eq, PartialEq, Snafu)] enum FlattenError { #[snafu(display( "The key {:?} cannot be flattened. Is it a plain string or a `a.b.c` style map?", key ))] CannotFlatten { key: String }, } fn flatten(kv: (String, TomlValue), prequel: Option<String>) -> crate::Result<(Atom, Atom)> { let (k, v) = kv; match v { TomlValue::String(s) => match prequel { Some(prequel) => Ok((format!("{}.{}", prequel, k).into(), s.into())), None => Ok((k.into(), s.into())), }, TomlValue::Table(map) => { if map.len() > 1 { Err(Box::new(FlattenError::CannotFlatten { key: k })) } else { let sub_kv = map.into_iter().next().expect("Map of len 1 has no values"); let key = match prequel { Some(prequel) => format!("{}.{}", prequel, k), None => k, }; flatten(sub_kv, Some(key)) } } TomlValue::Integer(_) | TomlValue::Float(_) | TomlValue::Boolean(_) | TomlValue::Datetime(_) | TomlValue::Array(_) => Err(Box::new(FlattenError::CannotFlatten { key: k })), } } impl Transform for RenameFields { fn transform(&mut self, mut event: Event) -> Option<Event> { for (old_key, new_key) in &self.fields { let log = event.as_mut_log(); if let Some(v) = log.remove(&old_key) { log.insert(new_key.clone(), v) } } Some(event) } } #[cfg(test)] mod tests { use super::RenameFields; use crate::{event::Event, transforms::Transform}; use indexmap::map::IndexMap; #[test] fn rename_fields() { let mut event = Event::from("message"); event.as_mut_log().insert("to_move", "some value"); event.as_mut_log().insert("do_not_move", "not moved"); let mut fields = IndexMap::new(); fields.insert("to_move".into(), "moved".into()); fields.insert("not_present".into(), "should_not_exist".into()); let mut transform = RenameFields::new(fields).unwrap(); let new_event = transform.transform(event).unwrap(); assert!(new_event.as_log().get(&"to_move".into()).is_none()); assert_eq!(new_event.as_log()[&"moved".into()], "some value".into()); assert!(new_event.as_log().get(&"not_present".into()).is_none()); assert!(new_event.as_log().get(&"should_not_exist".into()).is_none()); assert_eq!( new_event.as_log()[&"do_not_move".into()], "not moved".into() ); } }
Ok(RenameFields { fields: fields .into_iter() .map(|kv| flatten(kv, None)) .collect::<crate::Result<_>>()?, })
call_expression
[ { "content": "/// Iterates over all paths in form \"a.b[0].c[1]\" in alphabetical order.\n\n/// It is implemented as a wrapper around `all_fields` to reduce code\n\n/// duplication.\n\npub fn keys<'a>(fields: &'a BTreeMap<Atom, Value>) -> impl Iterator<Item = Atom> + 'a {\n\n all_fields(fields).map(|(k, _)| ...
Rust
src/netlink-generic/message.rs
qinqon/nispor
86e8a54cba6ad8161bfa78fa683bd114a3ed7799
use anyhow::Context; use netlink_packet_core::{ DecodeError, NetlinkDeserializable, NetlinkHeader, NetlinkPayload, NetlinkSerializable, }; use netlink_packet_utils::{ nla::{DefaultNla, NlasIterator}, Emitable, Parseable, ParseableParametrized, }; use crate::{ buffer::GENL_ID_CTRL, CtrlAttr, GenericNetlinkHeader, GenericNetlinkMessageBuffer, }; #[derive(Debug, PartialEq, Eq, Clone)] pub enum GenericNetlinkAttr { Ctrl(Vec<CtrlAttr>), Other(Vec<DefaultNla>), } #[derive(Debug, PartialEq, Eq, Clone)] pub struct GenericNetlinkMessage { pub message_type: u16, pub header: GenericNetlinkHeader, pub nlas: GenericNetlinkAttr, } impl Emitable for GenericNetlinkMessage { fn buffer_len(&self) -> usize { self.header.buffer_len() + match &self.nlas { GenericNetlinkAttr::Ctrl(nlas) => nlas.as_slice().buffer_len(), GenericNetlinkAttr::Other(nlas) => nlas.as_slice().buffer_len(), } } fn emit(&self, buffer: &mut [u8]) { self.header.emit(buffer); match &self.nlas { GenericNetlinkAttr::Ctrl(nlas) => nlas .as_slice() .emit(&mut buffer[self.header.buffer_len()..]), GenericNetlinkAttr::Other(nlas) => nlas .as_slice() .emit(&mut buffer[self.header.buffer_len()..]), } } } impl NetlinkSerializable<GenericNetlinkMessage> for GenericNetlinkMessage { fn message_type(&self) -> u16 { self.message_type } fn buffer_len(&self) -> usize { <Self as Emitable>::buffer_len(self) } fn serialize(&self, buffer: &mut [u8]) { self.emit(buffer) } } impl NetlinkDeserializable<GenericNetlinkMessage> for GenericNetlinkMessage { type Error = DecodeError; fn deserialize( header: &NetlinkHeader, payload: &[u8], ) -> Result<Self, Self::Error> { let buf = GenericNetlinkMessageBuffer::new(payload); GenericNetlinkMessage::parse_with_param(&buf, header.message_type) } } impl<'a, T: AsRef<[u8]> + ?Sized> ParseableParametrized<GenericNetlinkMessageBuffer<&'a T>, u16> for GenericNetlinkMessage { fn parse_with_param( buf: &GenericNetlinkMessageBuffer<&'a T>, message_type: u16, ) -> Result<Self, DecodeError> { let header = GenericNetlinkHeader::parse(buf) .context("failed to parse generic netlink message header")?; match message_type { GENL_ID_CTRL => { match GenericNetlinkMessageBuffer::new_checked(&buf.inner()) { Ok(buf) => Ok(GenericNetlinkMessage { message_type, header, nlas: { let mut nlas = Vec::new(); let error_msg = "failed to parse control message attributes"; for nla in NlasIterator::new(buf.payload()) { let nla = &nla.context(error_msg)?; let parsed = CtrlAttr::parse(nla).context(error_msg)?; nlas.push(parsed); } GenericNetlinkAttr::Ctrl(nlas) }, }), Err(e) => Err(e), } } _ => Err(format!("Unknown message type: {}", message_type).into()), } } } impl From<GenericNetlinkMessage> for NetlinkPayload<GenericNetlinkMessage> { fn from(message: GenericNetlinkMessage) -> Self { NetlinkPayload::InnerMessage(message) } }
use anyhow::Context; use netlink_packet_core::{ DecodeError, NetlinkDeserializable, NetlinkHeader, NetlinkPayload, NetlinkSerializable, }; use netlink_packet_utils::{ nla::{DefaultNla, NlasIterator}, Emitable, Parseable, ParseableParametrized, }; use crate::{ buffer::GENL_ID_CTRL, CtrlAttr, GenericNetlinkHeader, GenericNetlinkMessageBuffer, }; #[derive(Debug, PartialEq, Eq, Clone)] pub enum GenericNetlinkAttr { Ctrl(Vec<CtrlAttr>), Other(Vec<DefaultNla>), } #[derive(Debug, PartialEq, Eq, Clone)] pub struct GenericNetlinkMessage { pub message_type: u16, pub header: GenericNetlinkHeader, pub nlas: GenericNetlinkAttr, } impl Emitable for GenericNetlinkMessage { fn buffer_len(&self) -> usize { self.header.buffer_len() + match &self.nlas { GenericNetlinkAttr::Ctrl(nlas) => nlas.as_slice().buffer_len(), GenericNetlinkAttr::Other(nlas) => nlas.as_slice().buffer_len(), } } fn emit(&self, buffer: &mut [u8]) { self.header.emit(b
} } } impl NetlinkSerializable<GenericNetlinkMessage> for GenericNetlinkMessage { fn message_type(&self) -> u16 { self.message_type } fn buffer_len(&self) -> usize { <Self as Emitable>::buffer_len(self) } fn serialize(&self, buffer: &mut [u8]) { self.emit(buffer) } } impl NetlinkDeserializable<GenericNetlinkMessage> for GenericNetlinkMessage { type Error = DecodeError; fn deserialize( header: &NetlinkHeader, payload: &[u8], ) -> Result<Self, Self::Error> { let buf = GenericNetlinkMessageBuffer::new(payload); GenericNetlinkMessage::parse_with_param(&buf, header.message_type) } } impl<'a, T: AsRef<[u8]> + ?Sized> ParseableParametrized<GenericNetlinkMessageBuffer<&'a T>, u16> for GenericNetlinkMessage { fn parse_with_param( buf: &GenericNetlinkMessageBuffer<&'a T>, message_type: u16, ) -> Result<Self, DecodeError> { let header = GenericNetlinkHeader::parse(buf) .context("failed to parse generic netlink message header")?; match message_type { GENL_ID_CTRL => { match GenericNetlinkMessageBuffer::new_checked(&buf.inner()) { Ok(buf) => Ok(GenericNetlinkMessage { message_type, header, nlas: { let mut nlas = Vec::new(); let error_msg = "failed to parse control message attributes"; for nla in NlasIterator::new(buf.payload()) { let nla = &nla.context(error_msg)?; let parsed = CtrlAttr::parse(nla).context(error_msg)?; nlas.push(parsed); } GenericNetlinkAttr::Ctrl(nlas) }, }), Err(e) => Err(e), } } _ => Err(format!("Unknown message type: {}", message_type).into()), } } } impl From<GenericNetlinkMessage> for NetlinkPayload<GenericNetlinkMessage> { fn from(message: GenericNetlinkMessage) -> Self { NetlinkPayload::InnerMessage(message) } }
uffer); match &self.nlas { GenericNetlinkAttr::Ctrl(nlas) => nlas .as_slice() .emit(&mut buffer[self.header.buffer_len()..]), GenericNetlinkAttr::Other(nlas) => nlas .as_slice() .emit(&mut buffer[self.header.buffer_len()..]),
function_block-random_span
[ { "content": "fn feature_bits_emit(_feature_bits: &[FeatureBit], _buffer: &mut [u8]) {\n\n todo!(\"Does not support changing ethtool feature yet\")\n\n}\n\n\n\n#[derive(Debug, PartialEq, Eq, Clone)]\n\npub enum FeatureAttr {\n\n Header(Vec<EthtoolHeader>),\n\n Hw(Vec<FeatureBit>),\n\n Wanted(Vec<Fea...
Rust
src/response/mod.rs
ferrum-rs/ferrum
2bda0743d84632e95925d687d8cc03ef15e0ecc4
use std::fmt::{self, Debug}; use std::mem::replace; use mime::Mime; use typemap::{TypeMap, TypeMapInner}; use plugin::Extensible; use hyper::{Body, HttpVersion}; use hyper::header::{ContentLength, ContentType, Location, Raw}; use {Plugin, Header, Headers, StatusCode}; pub use hyper::Response as HyperResponse; pub mod content; pub use self::content::*; pub struct Response { pub status: StatusCode, pub headers: Headers, pub body: Option<Body>, pub extensions: TypeMap<TypeMapInner>, } impl Response { #[inline] pub fn new() -> Response { Response { status: Default::default(), headers: Headers::new(), body: None, extensions: TypeMap::custom() } } #[inline] pub fn new_redirect<R: Into<Raw>>(location: R) -> Response { let mut headers = Headers::new(); headers.set(Location::parse_header(&location.into()).unwrap()); Response { status: StatusCode::Found, headers, body: None, extensions: TypeMap::custom() } } #[inline] pub fn with_status(mut self, status: StatusCode) -> Self { self.status = status; self } #[inline] pub fn with_header<H: Header>(mut self, header: H) -> Self { self.headers.set(header); self } #[inline] pub fn with_headers(mut self, headers: Headers) -> Self { self.headers = headers; self } #[inline] pub fn with_body<T: Into<Body>>(mut self, body: T) -> Self { self.body = Some(body.into()); self } #[inline] pub fn with_content<C: Into<Content>>(mut self, content: C, mime: Mime) -> Self { self.set_content(content, mime); self } #[inline] pub fn set_content<C: Into<Content>>(&mut self, content: C, mime: Mime) { let content = content.into(); self.headers.set(ContentType(mime)); self.headers.set(ContentLength(content.len() as u64)); self.body = Some(content.into()); self.status = StatusCode::Ok; } #[inline] pub fn with_mime(mut self, mime: Mime) -> Self { self.set_mime(mime); self } #[inline] pub fn set_mime(&mut self, mime: Mime) { self.headers.set(ContentType(mime)); } } impl From<HyperResponse> for Response { fn from(mut from_response: HyperResponse) -> Response { Response { status: from_response.status(), headers: replace(from_response.headers_mut(), Headers::new()), body: if from_response.body_ref().is_some() { Some(from_response.body()) } else { None }, extensions: TypeMap::custom() } } } impl From<Response> for HyperResponse { fn from(from_response: Response) -> HyperResponse { HyperResponse::new() .with_status(from_response.status) .with_headers(from_response.headers) .with_body(from_response.body.unwrap_or_default()) } } impl Debug for Response { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { writeln!(formatter, "{} {}\n{}", HttpVersion::default(), self.status, self.headers ) } } impl fmt::Display for Response { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { Debug::fmt(self, formatter) } } impl Extensible<TypeMapInner> for Response { fn extensions(&self) -> &TypeMap<TypeMapInner> { &self.extensions } fn extensions_mut(&mut self) -> &mut TypeMap<TypeMapInner> { &mut self.extensions } } impl Plugin for Response {} #[cfg(test)] mod test { use super::*; use hyper::header::{ContentType}; use futures::stream::Stream; use futures::{future, Future}; use mime; use std::str::from_utf8; #[test] fn test_create_response() { let response = Response::new(); assert_eq!(response.status, StatusCode::Ok); assert_eq!(response.headers, Headers::new()); assert!(response.body.is_none()); } #[test] fn test_response_from_hyper_response() { let mut headers = Headers::new(); headers.set(ContentType(mime::TEXT_HTML)); let response = Response::from( HyperResponse::new() .with_status(StatusCode::NotFound) .with_headers(headers.clone()) .with_body("Error") ); assert_eq!(response.status, StatusCode::NotFound); assert_eq!(response.headers, headers); assert!(response.body.is_some()); let body = response.body.unwrap() .concat2() .and_then(|chunk| { future::ok(String::from(from_utf8(&chunk).unwrap())) }) .wait().unwrap(); assert_eq!(body, "Error"); } #[test] fn test_hyper_response_from_response() { let mut headers = Headers::new(); headers.set(ContentType(mime::TEXT_HTML)); let response = HyperResponse::from( Response { status: StatusCode::NotFound, headers: headers.clone(), body: Some("Error".into()), extensions: TypeMap::custom() } ); assert_eq!(response.status(), StatusCode::NotFound); assert_eq!(response.headers(), &headers); assert!(response.body_ref().is_some()); let body = response.body() .concat2() .and_then(|chunk| { future::ok(String::from(from_utf8(&chunk).unwrap())) }) .wait().unwrap(); assert_eq!(body, "Error"); } }
use std::fmt::{self, Debug}; use std::mem::replace; use mime::Mime; use typemap::{TypeMap, TypeMapInner}; use plugin::Extensible; use hyper::{Body, HttpVersion}; use hyper::header::{ContentLength, ContentType, Location, Raw}; use {Plugin, Header, Headers, StatusCode}; pub use hyper::Response as HyperResponse; pub mod content; pub use self::content::*; pub struct Response { pub status: StatusCode, pub headers: Headers, pub body: Option<Body>, pub extensions: TypeMap<TypeMapInner>, } impl Response { #[inline] pub fn new() -> Response { Response { status: Default::default(), headers: Headers::new(), body: None, extensions: TypeMap::custom() } } #[inline] pub fn new_redirect<R: Into<Raw>>(location: R) -> Response { let mut headers = Headers::new(); headers.set(Location::parse_header(&location.into()).unwrap()); Response { status: StatusCode::Found, headers, body: None, extensions: TypeMap::custom() } } #[inline] pub fn with_status(mut self, status: StatusCode) -> Self { self.status = status; self } #[inline] pub fn with_header<H: Header>(mut self, header: H) -> Self { self.headers.set(header); self } #[inline] pub fn with_headers(mut self, headers: Headers) -> Self { self.headers = headers; self } #[inline] pub fn with_body<T: Into<Body>>(mut self, body: T) -> Self { self.body = Some(body.into()); self } #[inline] pub fn with_content<C: Into<Content>>(mut self, content: C, mime: Mime) -> Self { self.set_content(content, mime); self } #[inline]
#[inline] pub fn with_mime(mut self, mime: Mime) -> Self { self.set_mime(mime); self } #[inline] pub fn set_mime(&mut self, mime: Mime) { self.headers.set(ContentType(mime)); } } impl From<HyperResponse> for Response { fn from(mut from_response: HyperResponse) -> Response { Response { status: from_response.status(), headers: replace(from_response.headers_mut(), Headers::new()), body: if from_response.body_ref().is_some() { Some(from_response.body()) } else { None }, extensions: TypeMap::custom() } } } impl From<Response> for HyperResponse { fn from(from_response: Response) -> HyperResponse { HyperResponse::new() .with_status(from_response.status) .with_headers(from_response.headers) .with_body(from_response.body.unwrap_or_default()) } } impl Debug for Response { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { writeln!(formatter, "{} {}\n{}", HttpVersion::default(), self.status, self.headers ) } } impl fmt::Display for Response { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { Debug::fmt(self, formatter) } } impl Extensible<TypeMapInner> for Response { fn extensions(&self) -> &TypeMap<TypeMapInner> { &self.extensions } fn extensions_mut(&mut self) -> &mut TypeMap<TypeMapInner> { &mut self.extensions } } impl Plugin for Response {} #[cfg(test)] mod test { use super::*; use hyper::header::{ContentType}; use futures::stream::Stream; use futures::{future, Future}; use mime; use std::str::from_utf8; #[test] fn test_create_response() { let response = Response::new(); assert_eq!(response.status, StatusCode::Ok); assert_eq!(response.headers, Headers::new()); assert!(response.body.is_none()); } #[test] fn test_response_from_hyper_response() { let mut headers = Headers::new(); headers.set(ContentType(mime::TEXT_HTML)); let response = Response::from( HyperResponse::new() .with_status(StatusCode::NotFound) .with_headers(headers.clone()) .with_body("Error") ); assert_eq!(response.status, StatusCode::NotFound); assert_eq!(response.headers, headers); assert!(response.body.is_some()); let body = response.body.unwrap() .concat2() .and_then(|chunk| { future::ok(String::from(from_utf8(&chunk).unwrap())) }) .wait().unwrap(); assert_eq!(body, "Error"); } #[test] fn test_hyper_response_from_response() { let mut headers = Headers::new(); headers.set(ContentType(mime::TEXT_HTML)); let response = HyperResponse::from( Response { status: StatusCode::NotFound, headers: headers.clone(), body: Some("Error".into()), extensions: TypeMap::custom() } ); assert_eq!(response.status(), StatusCode::NotFound); assert_eq!(response.headers(), &headers); assert!(response.body_ref().is_some()); let body = response.body() .concat2() .and_then(|chunk| { future::ok(String::from(from_utf8(&chunk).unwrap())) }) .wait().unwrap(); assert_eq!(body, "Error"); } }
pub fn set_content<C: Into<Content>>(&mut self, content: C, mime: Mime) { let content = content.into(); self.headers.set(ContentType(mime)); self.headers.set(ContentLength(content.len() as u64)); self.body = Some(content.into()); self.status = StatusCode::Ok; }
function_block-full_function
[ { "content": "struct DefaultContentType;\n\n\n\nimpl AfterMiddleware for DefaultContentType {\n\n // This is run for every requests, AFTER all handlers have been executed\n\n fn after(&self, _: &mut Request, mut response: Response) -> FerrumResult<Response> {\n\n if response.headers.get::<ContentTy...
Rust
src/scu_reset/prclr1.rs
austinglaser/xmc4700
12e1d2b638af5ff0e7088605a4299590a2cd60eb
#[doc = "Writer for register PRCLR1"] pub type W = crate::W<u32, super::PRCLR1>; #[doc = "Register PRCLR1 `reset()`'s with value 0"] impl crate::ResetValue for super::PRCLR1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "CCU43 Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CCU43RS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<CCU43RS_AW> for bool { #[inline(always)] fn from(variant: CCU43RS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `CCU43RS`"] pub struct CCU43RS_W<'a> { w: &'a mut W, } impl<'a> CCU43RS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CCU43RS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(CCU43RS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(CCU43RS_AW::VALUE2) } #[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 = "LEDTS Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LEDTSCU0RS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<LEDTSCU0RS_AW> for bool { #[inline(always)] fn from(variant: LEDTSCU0RS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `LEDTSCU0RS`"] pub struct LEDTSCU0RS_W<'a> { w: &'a mut W, } impl<'a> LEDTSCU0RS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LEDTSCU0RS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(LEDTSCU0RS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(LEDTSCU0RS_AW::VALUE2) } #[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 = "MultiCAN Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MCAN0RS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<MCAN0RS_AW> for bool { #[inline(always)] fn from(variant: MCAN0RS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `MCAN0RS`"] pub struct MCAN0RS_W<'a> { w: &'a mut W, } impl<'a> MCAN0RS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MCAN0RS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(MCAN0RS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(MCAN0RS_AW::VALUE2) } #[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 = "DAC Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DACRS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<DACRS_AW> for bool { #[inline(always)] fn from(variant: DACRS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `DACRS`"] pub struct DACRS_W<'a> { w: &'a mut W, } impl<'a> DACRS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DACRS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(DACRS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(DACRS_AW::VALUE2) } #[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 = "MMC Interface Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MMCIRS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<MMCIRS_AW> for bool { #[inline(always)] fn from(variant: MMCIRS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `MMCIRS`"] pub struct MMCIRS_W<'a> { w: &'a mut W, } impl<'a> MMCIRS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MMCIRS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(MMCIRS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(MMCIRS_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "USIC1 Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USIC1RS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<USIC1RS_AW> for bool { #[inline(always)] fn from(variant: USIC1RS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `USIC1RS`"] pub struct USIC1RS_W<'a> { w: &'a mut W, } impl<'a> USIC1RS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USIC1RS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(USIC1RS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(USIC1RS_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "USIC2 Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USIC2RS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<USIC2RS_AW> for bool { #[inline(always)] fn from(variant: USIC2RS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `USIC2RS`"] pub struct USIC2RS_W<'a> { w: &'a mut W, } impl<'a> USIC2RS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USIC2RS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(USIC2RS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(USIC2RS_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "PORTS Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPORTSRS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<PPORTSRS_AW> for bool { #[inline(always)] fn from(variant: PPORTSRS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `PPORTSRS`"] pub struct PPORTSRS_W<'a> { w: &'a mut W, } impl<'a> PPORTSRS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPORTSRS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPORTSRS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPORTSRS_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } impl W { #[doc = "Bit 0 - CCU43 Reset Clear"] #[inline(always)] pub fn ccu43rs(&mut self) -> CCU43RS_W { CCU43RS_W { w: self } } #[doc = "Bit 3 - LEDTS Reset Clear"] #[inline(always)] pub fn ledtscu0rs(&mut self) -> LEDTSCU0RS_W { LEDTSCU0RS_W { w: self } } #[doc = "Bit 4 - MultiCAN Reset Clear"] #[inline(always)] pub fn mcan0rs(&mut self) -> MCAN0RS_W { MCAN0RS_W { w: self } } #[doc = "Bit 5 - DAC Reset Clear"] #[inline(always)] pub fn dacrs(&mut self) -> DACRS_W { DACRS_W { w: self } } #[doc = "Bit 6 - MMC Interface Reset Clear"] #[inline(always)] pub fn mmcirs(&mut self) -> MMCIRS_W { MMCIRS_W { w: self } } #[doc = "Bit 7 - USIC1 Reset Clear"] #[inline(always)] pub fn usic1rs(&mut self) -> USIC1RS_W { USIC1RS_W { w: self } } #[doc = "Bit 8 - USIC2 Reset Clear"] #[inline(always)] pub fn usic2rs(&mut self) -> USIC2RS_W { USIC2RS_W { w: self } } #[doc = "Bit 9 - PORTS Reset Clear"] #[inline(always)] pub fn pportsrs(&mut self) -> PPORTSRS_W { PPORTSRS_W { w: self } } }
#[doc = "Writer for register PRCLR1"] pub type W = crate::W<u32, super::PRCLR1>; #[doc = "Register PRCLR1 `reset()`'s with value 0"] impl crate::ResetValue for super::PRCLR1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "CCU43 Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CCU43RS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<CCU43RS_AW> for bool { #[inline(always)] fn from(variant: CCU43RS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `CCU43RS`"] pub struct CCU43RS_W<'a> { w: &'a mut W, } impl<'a> CCU43RS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CCU43RS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(CCU43RS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(CCU43RS_AW::VALUE2) } #[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 = "LEDTS Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LEDTSCU0RS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<LEDTSCU0RS_AW> for bool { #[inline(always)] fn from(variant: LEDTSCU0RS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `LEDTSCU0RS`"] pub struct LEDTSCU0RS_W<'a> { w: &'a mut W, } impl<'a> LEDTSCU0RS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LEDTSCU0RS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(LEDTSCU0RS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(LEDTSCU0RS_AW::VALUE2) } #[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 <<
"USIC1 Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USIC1RS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<USIC1RS_AW> for bool { #[inline(always)] fn from(variant: USIC1RS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `USIC1RS`"] pub struct USIC1RS_W<'a> { w: &'a mut W, } impl<'a> USIC1RS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USIC1RS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(USIC1RS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(USIC1RS_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "USIC2 Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USIC2RS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<USIC2RS_AW> for bool { #[inline(always)] fn from(variant: USIC2RS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `USIC2RS`"] pub struct USIC2RS_W<'a> { w: &'a mut W, } impl<'a> USIC2RS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USIC2RS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(USIC2RS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(USIC2RS_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "PORTS Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPORTSRS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<PPORTSRS_AW> for bool { #[inline(always)] fn from(variant: PPORTSRS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `PPORTSRS`"] pub struct PPORTSRS_W<'a> { w: &'a mut W, } impl<'a> PPORTSRS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPORTSRS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPORTSRS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPORTSRS_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } impl W { #[doc = "Bit 0 - CCU43 Reset Clear"] #[inline(always)] pub fn ccu43rs(&mut self) -> CCU43RS_W { CCU43RS_W { w: self } } #[doc = "Bit 3 - LEDTS Reset Clear"] #[inline(always)] pub fn ledtscu0rs(&mut self) -> LEDTSCU0RS_W { LEDTSCU0RS_W { w: self } } #[doc = "Bit 4 - MultiCAN Reset Clear"] #[inline(always)] pub fn mcan0rs(&mut self) -> MCAN0RS_W { MCAN0RS_W { w: self } } #[doc = "Bit 5 - DAC Reset Clear"] #[inline(always)] pub fn dacrs(&mut self) -> DACRS_W { DACRS_W { w: self } } #[doc = "Bit 6 - MMC Interface Reset Clear"] #[inline(always)] pub fn mmcirs(&mut self) -> MMCIRS_W { MMCIRS_W { w: self } } #[doc = "Bit 7 - USIC1 Reset Clear"] #[inline(always)] pub fn usic1rs(&mut self) -> USIC1RS_W { USIC1RS_W { w: self } } #[doc = "Bit 8 - USIC2 Reset Clear"] #[inline(always)] pub fn usic2rs(&mut self) -> USIC2RS_W { USIC2RS_W { w: self } } #[doc = "Bit 9 - PORTS Reset Clear"] #[inline(always)] pub fn pportsrs(&mut self) -> PPORTSRS_W { PPORTSRS_W { w: self } } }
3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "MultiCAN Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MCAN0RS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<MCAN0RS_AW> for bool { #[inline(always)] fn from(variant: MCAN0RS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `MCAN0RS`"] pub struct MCAN0RS_W<'a> { w: &'a mut W, } impl<'a> MCAN0RS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MCAN0RS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(MCAN0RS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(MCAN0RS_AW::VALUE2) } #[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 = "DAC Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DACRS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<DACRS_AW> for bool { #[inline(always)] fn from(variant: DACRS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `DACRS`"] pub struct DACRS_W<'a> { w: &'a mut W, } impl<'a> DACRS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DACRS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(DACRS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(DACRS_AW::VALUE2) } #[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 = "MMC Interface Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MMCIRS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<MMCIRS_AW> for bool { #[inline(always)] fn from(variant: MMCIRS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `MMCIRS`"] pub struct MMCIRS_W<'a> { w: &'a mut W, } impl<'a> MMCIRS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MMCIRS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(MMCIRS_AW::VALUE1) } #[doc = "De-assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(MMCIRS_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc =
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/main.rs
0x4c37373230/BDumper
fac8b161d544bccdc26f9f3607ebcafcf3c53f39
#![windows_subsystem = "windows"] extern crate native_windows_derive as nwd; extern crate native_windows_gui as nwg; use { bedrock_dumper::*, nwd::NwgUi, nwg::{CheckBoxState, NativeUi}, }; #[derive(Default, NwgUi)] pub struct BedrockDumper { #[nwg_control(size: (590, 225), position: (300, 300), title: "BDumper", flags: "WINDOW|VISIBLE")] #[nwg_events( OnWindowClose: [BedrockDumper::exit_program] )] window: nwg::Window, #[nwg_control(text: "BDumper is a .pdb file dumper made in Rust by Luke7720 designed to extract \ function prototypes and RVAs (Relative Virtual Addresses) and export them into either text \ or C++ header files. It can also find specific functions within the pdb\n\ -----------------------------------------------------------------------\ ----------------------------------------------------------------------- ", size: (580, 70), position: (10, 10))] label: nwg::Label, #[nwg_control(text: "Input your .pdb file path here", size: (280, 25), position: (10, 80))] label2: nwg::Label, #[nwg_control(text: "", size: (280, 25), position: (10, 100))] pdb_path: nwg::TextInput, #[nwg_control(text: "Input your file type (.hpp or .txt) here", size: (280, 25), position: (300, 80))] label3: nwg::Label, #[nwg_control(text: "", size: (280, 25), position: (300, 100))] file_type: nwg::TextInput, #[nwg_control(text: "Input a function's name here", size: (280, 25), position: (10, 130))] label4: nwg::Label, #[nwg_control(text: "", size: (280, 25), position: (10, 150))] func_name: nwg::TextInput, #[nwg_control(text: "Include demangled function prototypes", size: (280, 25), position: (300, 150))] should_demangle: nwg::CheckBox, #[nwg_control(text: "Dump Data", size: (185, 30), position: (10, 180))] #[nwg_events( OnButtonClick: [BedrockDumper::dump] )] dump: nwg::Button, #[nwg_control(text: "Find Function", size: (185, 30), position: (200, 180))] #[nwg_events( OnButtonClick: [BedrockDumper::find] )] find: nwg::Button, #[nwg_control(text: "Filtered Dump", size: (185, 30), position: (390, 180))] #[nwg_events( OnButtonClick: [BedrockDumper::filtered_dump] )] find_filtered: nwg::Button, } impl BedrockDumper { fn dump(&self) { let pdb_path: &str = &self.pdb_path.text(); let file_type: &str = &self.file_type.text(); let demangle = if &self.should_demangle.check_state() == &CheckBoxState::Checked { true } else { false }; match setup::dump_init(pdb_path, file_type) { Ok(dump_file) => pdb::pdb_dump(pdb_path, file_type, dump_file, demangle) .expect("ERROR: Failed to dump pdb contents"), Err(str) => { nwg::simple_message("Error", &str); return; } } } fn find(&self) { match pdb::find_function(&self.pdb_path.text(), &self.func_name.text()) { Ok(bds_func) => nwg::simple_message( "Found a match", &format!( "Function name: {}\nSymbol: {}\nRVA: {}", bds_func.name, bds_func.symbol, bds_func.rva ), ), Err(str) => nwg::simple_message("Error", &str), }; } fn filtered_dump(&self) { let pdb_path: &str = &self.pdb_path.text(); let file_type: &str = &self.file_type.text(); match setup::dump_init(pdb_path, file_type) { Ok(dump_file) => match pdb::find_functions(pdb_path, file_type, dump_file) { Err(str) => { nwg::simple_message("Error", &str); } _ => {} }, Err(str) => { nwg::simple_message("Error", &str); } } } fn exit_program(&self) { nwg::stop_thread_dispatch(); } } fn main() { nwg::init().expect("Failed to init Native Windows GUI"); setup::filter_manager(); let _app = BedrockDumper::build_ui(Default::default()).expect("Failed to build UI"); nwg::dispatch_thread_events(); }
#![windows_subsystem = "windows"] extern crate native_windows_derive as nwd; extern crate native_windows_gui as nwg; use { bedrock_dumper::*, nwd::NwgUi, nwg::{CheckBoxState, NativeUi}, }; #[derive(Default, NwgUi)] pub struct BedrockDumper { #[nwg_control(size: (590, 225), position: (300, 300), title: "BDumper", flags: "WINDOW|VISIBLE")] #[nwg_events( OnWindowClose: [BedrockDumper::exit_program] )] window: nwg::Window, #[nwg_control(text: "BDumper is a .pdb file dumper made in Rust by Luke7720 designed to extract \ function prototypes and RVAs (Relative Virtual Addresses) and export them into either text \ or C++ header files. It can also find specific functions within the pdb\n\ -----------------------------------------------------------------------\ ----------------------------------------------------------------------- ", size: (580, 70), position: (10, 10))] label: nwg::Label, #[nwg_control(text: "Input your .pdb file path here", size: (280, 25), position: (10, 80))] label2: nwg::Label, #[nwg_control(text: "", size: (280, 25), position: (10, 100))] pdb_path: nwg::TextInput, #[nwg_control(text: "Input your file type (.hpp or .txt) here", size: (280, 25), position: (300, 80))] label3: nwg::Label, #[nwg_control(text: "", size: (280, 25), position: (300, 100))] file_type: nwg::TextInput, #[nwg_control(text: "Input a function's name here", size: (280, 25), position: (10, 130))] label4: nwg::Label, #[nwg_control(text: "", size: (280, 25), position: (10, 150))] func_name: nwg::TextInput, #[nwg_control(text: "Include demangled function prototypes", size: (280, 25), position: (300, 150))] should_demangle: nwg::CheckBox, #[nwg_control(text: "Dump Data", size: (185, 30), position: (10, 180))] #[nwg_events( OnButtonClick: [BedrockDumper::dump] )] dump: nwg::Button, #[nwg_control(text: "Find Function", size: (185, 30), position: (200, 180))] #[nwg_events( OnButtonClick: [BedrockDumper::find] )] find: nwg::Button, #[nwg_control(text: "Filtered Dump", size: (185, 30), position: (390, 180))] #[nwg_events( OnButtonClick: [BedrockDumper::filtered_dump] )] find_filtered: nwg::Button,
ath, file_type, dump_file) { Err(str) => { nwg::simple_message("Error", &str); } _ => {} }, Err(str) => { nwg::simple_message("Error", &str); } } } fn exit_program(&self) { nwg::stop_thread_dispatch(); } } fn main() { nwg::init().expect("Failed to init Native Windows GUI"); setup::filter_manager(); let _app = BedrockDumper::build_ui(Default::default()).expect("Failed to build UI"); nwg::dispatch_thread_events(); }
} impl BedrockDumper { fn dump(&self) { let pdb_path: &str = &self.pdb_path.text(); let file_type: &str = &self.file_type.text(); let demangle = if &self.should_demangle.check_state() == &CheckBoxState::Checked { true } else { false }; match setup::dump_init(pdb_path, file_type) { Ok(dump_file) => pdb::pdb_dump(pdb_path, file_type, dump_file, demangle) .expect("ERROR: Failed to dump pdb contents"), Err(str) => { nwg::simple_message("Error", &str); return; } } } fn find(&self) { match pdb::find_function(&self.pdb_path.text(), &self.func_name.text()) { Ok(bds_func) => nwg::simple_message( "Found a match", &format!( "Function name: {}\nSymbol: {}\nRVA: {}", bds_func.name, bds_func.symbol, bds_func.rva ), ), Err(str) => nwg::simple_message("Error", &str), }; } fn filtered_dump(&self) { let pdb_path: &str = &self.pdb_path.text(); let file_type: &str = &self.file_type.text(); match setup::dump_init(pdb_path, file_type) { Ok(dump_file) => match pdb::find_functions(pdb_p
random
[ { "content": "# BDumper\n\nA windows BDS .pdb dumper written in rust which dumps symbols, reconstructed function prototypes from demangled symbols and RVAs (Relative Virtual Addresses) into either a C++ header (.hpp) or a text file (.txt) and can also find data corresponding to specific functions. This project ...
Rust
kosem-gui/src/work_on_procedure.rs
idanarye/kosem
c72198c1f78855cfd49d1d0fa1bc848ac0c8f9cc
use actix::prelude::*; use gtk::prelude::*; use kosem_webapi::Uuid; use kosem_webapi::pairing_messages; use kosem_webapi::phase_control_messages; use crate::internal_messages::gui_control::{ ProcedureScreenAttach, UserClickedButton, ShowJoinMenu, }; #[derive(woab::Factories)] pub struct WorkOnProcedureFactories { pub app_work_on_procedure_window: woab::BuilderFactory, row_phase: woab::BuilderFactory, cld_caption: woab::BuilderFactory, cld_button: woab::BuilderFactory, } #[derive(typed_builder::TypedBuilder)] pub struct WorkOnProcedureActor { factories: crate::Factories, widgets: WorkOnProcedureWidgets, join_menu: Addr<crate::join_menu::JoinMenuActor>, gui_client: Addr<crate::client::GuiClientActor>, server_idx: usize, procedure: pairing_messages::AvailableProcedure, #[builder(default, setter(skip))] phases: std::collections::HashMap<Uuid, PhaseRow>, } impl Actor for WorkOnProcedureActor { type Context = Context<Self>; fn started(&mut self, ctx: &mut Self::Context) { self.widgets.lbl_title.set_text(&self.procedure.name); self.widgets.app_work_on_procedure_window.show_all(); self.gui_client.do_send(ProcedureScreenAttach { server_idx: self.server_idx, request_uid: self.procedure.uid, addr: ctx.address(), }); } } #[derive(woab::WidgetsFromBuilder)] pub struct WorkOnProcedureWidgets { app_work_on_procedure_window: gtk::ApplicationWindow, lst_phases: gtk::ListBox, lbl_title: gtk::Label, } impl actix::Handler<woab::Signal> for WorkOnProcedureActor { type Result = woab::SignalResult; fn handle(&mut self, msg: woab::Signal, _ctx: &mut Self::Context) -> Self::Result { Ok(match msg.name() { "close" => { self.join_menu.do_send(ShowJoinMenu); None } _ => msg.cant_handle()?, }) } } impl Handler<phase_control_messages::PhasePushed> for WorkOnProcedureActor { type Result = (); fn handle(&mut self, msg: phase_control_messages::PhasePushed, ctx: &mut Self::Context) -> Self::Result { let phase_widgets: PhaseWidgets = self.factories.work_on_procedure.row_phase.instantiate().widgets().unwrap(); self.widgets.lst_phases.add(&phase_widgets.row_phase); for (i, component) in msg.components.iter().enumerate() { match &component.params { phase_control_messages::ComponentParams::Caption { text } => { let widgets: ComponentCaptionWidgets = self.factories.work_on_procedure.cld_caption.instantiate().widgets().unwrap(); widgets.lbl_caption.set_text(&text); phase_widgets.box_components.add(&widgets.cld_caption); } phase_control_messages::ComponentParams::Button { text } => { let widgets: ComponentButtonWidgets = self.factories.work_on_procedure.cld_button.instantiate() .connect_to(((msg.phase_uid, i), ctx.address())) .widgets().unwrap(); widgets.btn_button.set_label(&text); phase_widgets.box_components.add(&widgets.cld_button); } } } self.phases.insert(msg.phase_uid, PhaseRow { widgets: phase_widgets, msg, }); } } impl Handler<phase_control_messages::PhasePopped> for WorkOnProcedureActor { type Result = (); fn handle(&mut self, msg: phase_control_messages::PhasePopped, _ctx: &mut Self::Context) -> Self::Result { let phase_row = if let Some(p) = self.phases.get(&msg.phase_uid) { p } else { log::warn!("Unknown phase {}", msg.phase_uid); return; }; self.widgets.lst_phases.remove(&phase_row.widgets.row_phase); } } impl Handler<pairing_messages::ProcedureFinished> for WorkOnProcedureActor { type Result = (); fn handle(&mut self, _msg: pairing_messages::ProcedureFinished, _ctx: &mut Self::Context) -> Self::Result { self.widgets.app_work_on_procedure_window.close(); } } struct PhaseRow { widgets: PhaseWidgets, msg: phase_control_messages::PhasePushed, } #[derive(woab::WidgetsFromBuilder)] struct PhaseWidgets { row_phase: gtk::ListBoxRow, box_components: gtk::FlowBox, } #[derive(woab::WidgetsFromBuilder)] struct ComponentCaptionWidgets { cld_caption: gtk::FlowBoxChild, lbl_caption: gtk::Label, } #[derive(woab::WidgetsFromBuilder)] struct ComponentButtonWidgets { cld_button: gtk::FlowBoxChild, btn_button: gtk::Button, } impl actix::Handler<woab::Signal<(Uuid, usize)>> for WorkOnProcedureActor { type Result = woab::SignalResult; fn handle(&mut self, msg: woab::Signal<(Uuid, usize)>, _ctx: &mut Self::Context) -> Self::Result { let (phase_uid, component_ordinal) = *msg.tag(); let phase_row = if let Some(p) = self.phases.get(&phase_uid) { p } else { log::warn!("Unknown phase {}", phase_uid); return Ok(None); }; let component = if let Some(c) = phase_row.msg.components.get(component_ordinal) { c } else { log::warn!("Phase {} only has {} components - cannot access component {}", phase_uid, phase_row.msg.components.len(), component_ordinal); return Ok(None); }; Ok(match msg.name() { "button_clicked" => { self.gui_client.do_send(UserClickedButton { server_idx: self.server_idx, request_uid: self.procedure.uid, phase_uid, button_name: component.name.clone(), }); None } _ => msg.cant_handle()?, }) } }
use actix::prelude::*; use gtk::prelude::*; use kosem_webapi::Uuid; use kosem_webapi::pairing_messages; use kosem_webapi::phase_control_messages; use crate::internal_messages::gui_control::{ ProcedureScreenAttach, UserClickedButton, ShowJoinMenu, }; #[derive(woab::Factories)] pub struct WorkOnProcedureFactories { pub app_work_on_procedure_window: woab::BuilderFactory, row_phase: woab::BuilderFactory, cld_caption: woab::BuilderFactory, cld_button: woab::BuilderFactory, } #[derive(typed_builder::TypedBuilder)] pub struct WorkOnProcedureActor { factories: crate::Factories, widgets: WorkOnProcedureWidgets, join_menu: Addr<crate::join_menu::JoinMenuActor>, gui_client: Addr<crate::client::GuiClientActor>, server_idx: usize, procedure: pairing_messages::AvailableProcedure, #[builder(default, setter(skip))] phases: std::collections::HashMap<Uuid, PhaseRow>, } impl Actor for WorkOnProcedureActor { type Context = Context<Self>; fn started(&mut self, ctx: &mut Self::Context) { self.widgets.lbl_title.set_text(&self.procedure.name); self.widgets.app_work_on_procedure_window.show_all(); self.gui_client.do_send(ProcedureScreenAttach { server_idx: self.server_idx, request_uid: self.procedure.uid, addr: ctx.address(), }); } } #[derive(woab::WidgetsFromBuilder)] pub struct WorkOnProcedureWidgets { app_work_on_procedure_window: gtk::ApplicationWindow, lst_phases: gtk::ListBox, lbl_title: gtk::Label, } impl actix::Handler<woab::Signal> for WorkOnProcedureActor { type Result = woab::SignalResult; fn handle(&mut self, msg: woab::Signal, _ctx: &mut Self::Context) -> Self::Result { Ok(match msg.name() { "close" => { self.join_menu.do_send(ShowJoinMenu); None } _ => msg.cant_handle()?, }) } } impl Handler<phase_control_messages::PhasePushed> for WorkOnProcedureActor { type Result = (); fn handle(&mut self, msg: phase_control_messages::PhasePushed, ctx: &mut Self::Context) -> Self::Result { let phase_widgets: PhaseWidgets = self.factories.work_on_procedure.row_phase.instantiate().widgets().unwrap(); self.widgets.lst_phases.add(&phase_widgets.row_phase); for (i, component) in msg.components.iter().enumerate() { match &component.params { phase_control_messages::ComponentParams::Caption { text } => { let widgets: ComponentCaptionWidgets = self.factories.work_on_procedure.cld_caption.instantiate().widgets().unwrap(); widgets.lbl_caption.set_text(&text); phase_widgets.box_components.add(&widgets.cld_caption); } phase_control_messages::ComponentParams::Button { text } => { let widgets: ComponentButtonWidgets = self.factories.work_on_procedure.cld_button.instantiate() .connect_to(((msg.phase_uid, i), ctx.address())) .widgets().unwrap(); widgets.btn_button.set_label(&text); phase_widgets.box_components.add(&widgets.cld_button); } } } self.phases.insert(msg.phase_uid, PhaseRow { widgets: phase_widgets, msg, }); } } impl Handler<phase_control_messages::PhasePopped> for WorkOnProcedureActor { type Result = (); fn handle(&mut self, msg: phase_control_messages::PhasePopped, _ctx: &mut Self::Context) -> Self::Result { let phase_row = if let Some(p) = self.phases.get(&msg.phase_uid) { p } else { log::warn!("Unknown phase {}", msg.phase_uid); return; }; self.widgets.lst_phases.remove(&phase_row.widgets.row_phase); } } impl Handler<pairing_messages::ProcedureFinished> for WorkOnProcedureActor { type Result = (); fn handle(&mut self, _msg: pairing_messages::ProcedureFinished, _ctx: &mut Self::Context) -> Self::Result { self.widgets.app_work_on_procedure_window.close(); } } struct PhaseRow { widgets: PhaseWidgets, msg: phase_control_messages::PhasePushed, } #[derive(woab::WidgetsFromBuilder)] struct PhaseWidgets { row_phase: gtk::ListBoxRow, box_components: gtk::FlowBox, } #[derive(woab::WidgetsFromBuilder)] struct ComponentCaptionWidgets { cld_caption: gtk::FlowBoxChild, lbl_caption: gtk::Label, } #[derive(woab::WidgetsFromBuilder)] struct ComponentButtonWidgets { cld_button: gtk::FlowBoxChild, btn_button: gtk::Button, } impl actix::Handler<woab::Signal<(Uuid, usize)>> for WorkOnProcedureActor { type Result = woab::SignalResult; fn handle(&mut self, msg: woab::Signal<(Uuid, usize)>, _ctx: &mut Self::Context) -> Self::Result { let (phase_uid, component_
}
ordinal) = *msg.tag(); let phase_row = if let Some(p) = self.phases.get(&phase_uid) { p } else { log::warn!("Unknown phase {}", phase_uid); return Ok(None); }; let component = if let Some(c) = phase_row.msg.components.get(component_ordinal) { c } else { log::warn!("Phase {} only has {} components - cannot access component {}", phase_uid, phase_row.msg.components.len(), component_ordinal); return Ok(None); }; Ok(match msg.name() { "button_clicked" => { self.gui_client.do_send(UserClickedButton { server_idx: self.server_idx, request_uid: self.procedure.uid, phase_uid, button_name: component.name.clone(), }); None } _ => msg.cant_handle()?, }) }
function_block-function_prefixed
[ { "content": "pub fn start_gtk(settings: client_config::ClientConfig) -> anyhow::Result<()> {\n\n let factories = Factories::new(FactoriesInner {\n\n join_menu: join_menu::JoinMenuFactories::read(&*Asset::get(\"join_menu.glade\").unwrap())?,\n\n work_on_procedure: work_on_procedure::WorkOnProce...
Rust
src/main.rs
codahale/veil-rs
45e3a32ad522b4ce68425442a39ccc76d92bf43c
use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::{fs, result}; use anyhow::Result; use clap::{App, IntoApp, Parser}; use clap::{AppSettings, Subcommand, ValueHint}; use clap_complete::generate_to; use clap_complete::Shell; use clio::{Input, Output}; use mimalloc::MiMalloc; use veil::{PublicKey, PublicKeyError, SecretKey, Signature}; #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; fn main() -> Result<()> { let opts: Opts = Opts::parse(); match opts.cmd { Command::SecretKey(cmd) => cmd.run(), Command::PublicKey(cmd) => cmd.run(), Command::DeriveKey(cmd) => cmd.run(), Command::Encrypt(cmd) => cmd.run(), Command::Decrypt(cmd) => cmd.run(), Command::Sign(cmd) => cmd.run(), Command::Verify(cmd) => cmd.run(), Command::Complete(cmd) => cmd.run(), } } #[derive(Debug, Parser)] #[clap(author, version, about)] #[clap(setting = AppSettings::SubcommandRequired)] struct Opts { #[clap(subcommand)] cmd: Command, } trait Cmd { fn run(self) -> Result<()>; } #[derive(Debug, Subcommand)] #[clap(setting = AppSettings::DeriveDisplayOrder)] enum Command { SecretKey(SecretKeyArgs), PublicKey(PublicKeyArgs), DeriveKey(DeriveKeyArgs), Encrypt(EncryptArgs), Decrypt(DecryptArgs), Sign(SignArgs), Verify(VerifyArgs), Complete(CompleteArgs), } #[derive(Debug, Parser)] struct SecretKeyArgs { #[clap(value_hint = ValueHint::FilePath)] output: PathBuf, #[clap(long, default_value = "128")] time: u32, #[clap(long, default_value = "1024")] space: u32, #[clap(long, value_hint = ValueHint::FilePath)] passphrase_file: Option<PathBuf>, } impl Cmd for SecretKeyArgs { fn run(self) -> Result<()> { let passphrase = prompt_passphrase(&self.passphrase_file)?; let secret_key = SecretKey::new(); let ciphertext = secret_key.encrypt(&passphrase, self.time, self.space); fs::write(self.output, ciphertext)?; Ok(()) } } #[derive(Debug, Parser)] struct PublicKeyArgs { #[clap(value_hint = ValueHint::FilePath)] secret_key: PathBuf, key_id: OsString, #[clap(parse(try_from_os_str = output_from_os_str), value_hint = ValueHint::FilePath, default_value="-")] output: Output, #[clap(long, value_hint = ValueHint::FilePath)] passphrase_file: Option<PathBuf>, } impl Cmd for PublicKeyArgs { fn run(mut self) -> Result<()> { let secret_key = decrypt_secret_key(&self.passphrase_file, &self.secret_key)?; let public_key = secret_key.public_key(self.key_id.to_string_lossy().as_ref()); write!(self.output.lock(), "{}", public_key)?; Ok(()) } } #[derive(Debug, Parser)] struct DeriveKeyArgs { public_key: OsString, sub_key_id: OsString, #[clap(parse(try_from_os_str = output_from_os_str), value_hint = ValueHint::FilePath, default_value="-")] output: Output, } impl Cmd for DeriveKeyArgs { fn run(mut self) -> Result<()> { let root = self.public_key.to_string_lossy().as_ref().parse::<PublicKey>()?; let public_key = root.derive(self.sub_key_id.to_string_lossy().as_ref()); write!(self.output.lock(), "{}", public_key)?; Ok(()) } } #[derive(Debug, Parser)] struct EncryptArgs { #[clap(value_hint = ValueHint::FilePath)] secret_key: PathBuf, key_id: OsString, #[clap(parse(try_from_os_str = input_from_os_str), value_hint = ValueHint::FilePath)] plaintext: Input, #[clap(parse(try_from_os_str = output_from_os_str), value_hint = ValueHint::FilePath)] ciphertext: Output, #[clap(required = true)] recipients: Vec<OsString>, #[clap(long, default_value = "0")] fakes: usize, #[clap(long, default_value = "0")] padding: u64, #[clap(long, value_hint = ValueHint::FilePath)] passphrase_file: Option<PathBuf>, } impl Cmd for EncryptArgs { fn run(mut self) -> Result<()> { let secret_key = decrypt_secret_key(&self.passphrase_file, &self.secret_key)?; let private_key = secret_key.private_key(self.key_id.to_string_lossy().as_ref()); let pks = self .recipients .iter() .map(|s| s.to_string_lossy().as_ref().parse::<PublicKey>()) .collect::<result::Result<Vec<PublicKey>, PublicKeyError>>()?; private_key.encrypt( &mut self.plaintext.lock(), &mut self.ciphertext.lock(), pks, self.fakes, self.padding, )?; Ok(()) } } #[derive(Debug, Parser)] struct DecryptArgs { #[clap(value_hint = ValueHint::FilePath)] secret_key: PathBuf, key_id: OsString, #[clap(parse(try_from_os_str = input_from_os_str), value_hint = ValueHint::FilePath)] ciphertext: Input, #[clap(parse(try_from_os_str = output_from_os_str), value_hint = ValueHint::FilePath)] plaintext: Output, sender: OsString, #[clap(long, value_hint = ValueHint::FilePath)] passphrase_file: Option<PathBuf>, } impl Cmd for DecryptArgs { fn run(mut self) -> Result<()> { let secret_key = decrypt_secret_key(&self.passphrase_file, &self.secret_key)?; let private_key = secret_key.private_key(self.key_id.to_string_lossy().as_ref()); let sender = self.sender.to_string_lossy().parse()?; private_key.decrypt(&mut self.ciphertext.lock(), &mut self.plaintext.lock(), &sender)?; Ok(()) } } #[derive(Debug, Parser)] struct SignArgs { #[clap(value_hint = ValueHint::FilePath)] secret_key: PathBuf, key_id: OsString, #[clap(parse(try_from_os_str = input_from_os_str), value_hint = ValueHint::FilePath)] message: Input, #[clap(parse(try_from_os_str = output_from_os_str), value_hint = ValueHint::FilePath, default_value="-")] output: Output, #[clap(long, value_hint = ValueHint::FilePath)] passphrase_file: Option<PathBuf>, } impl Cmd for SignArgs { fn run(mut self) -> Result<()> { let secret_key = decrypt_secret_key(&self.passphrase_file, &self.secret_key)?; let private_key = secret_key.private_key(self.key_id.to_string_lossy().as_ref()); let sig = private_key.sign(&mut self.message.lock())?; write!(self.output.lock(), "{}", sig)?; Ok(()) } } #[derive(Debug, Parser)] struct VerifyArgs { public_key: OsString, #[clap(parse(try_from_os_str = input_from_os_str), value_hint = ValueHint::FilePath)] message: Input, signature: OsString, } impl Cmd for VerifyArgs { fn run(mut self) -> Result<()> { let signer = self.public_key.to_string_lossy().as_ref().parse::<PublicKey>()?; let sig = self.signature.to_string_lossy().as_ref().parse::<Signature>()?; signer.verify(&mut self.message.lock(), &sig)?; Ok(()) } } #[derive(Debug, Parser)] #[clap(setting = AppSettings::Hidden)] struct CompleteArgs { shell: Shell, #[clap(value_hint = ValueHint::DirPath)] output: OsString, } impl Cmd for CompleteArgs { fn run(self) -> Result<()> { let mut app: App = Opts::into_app(); generate_to(self.shell, &mut app, "veil", &self.output)?; Ok(()) } } fn decrypt_secret_key(passphrase_file: &Option<PathBuf>, path: &Path) -> Result<SecretKey> { let passphrase = prompt_passphrase(passphrase_file)?; let ciphertext = fs::read(path)?; let sk = SecretKey::decrypt(&passphrase, &ciphertext)?; Ok(sk) } fn prompt_passphrase(passphrase_file: &Option<PathBuf>) -> Result<String> { match passphrase_file { Some(p) => Ok(fs::read_to_string(p)?), None => Ok(rpassword::read_password_from_tty(Some("Enter passphrase: "))?), } } fn input_from_os_str(path: &OsStr) -> Result<Input, String> { Input::new(path).map_err(|e| e.to_string()) } fn output_from_os_str(path: &OsStr) -> Result<Output, String> { Output::new(path).map_err(|e| e.to_string()) }
use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::{fs, result}; use anyhow::Result; use clap::{App, IntoApp, Parser}; use clap::{AppSettings, Subcommand, ValueHint}; use clap_complete::generate_to; use clap_complete::Shell; use clio::{Input, Output}; use mimalloc::MiMalloc; use veil::{PublicKey, PublicKeyError, SecretKey, Signature}; #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; fn main() -> Result<()> { let opts: Opts = Opts::parse(); match opts.cmd { Command::SecretKey(cmd) => cmd.run(), Command::PublicKey(cmd) => cmd.run(), Command::DeriveKey(cmd) => cmd.run(), Command::Encrypt(cmd) => cmd.run(), Command::Decrypt(cmd) => cmd.run(), Command::Sign(cmd) => cmd.run(), Command::Verify(cmd) => cmd.run(), Command::Complete(cmd) => cmd.run(), } } #[derive(Debug, Parser)] #[clap(author, version, about)] #[clap(setting = AppSettings::SubcommandRequired)] struct Opts { #[clap(subcommand)] cmd: Command, } trait Cmd { fn run(self) -> Result<()>; } #[derive(Debug, Subcommand)] #[clap(setting = AppSettings::DeriveDisplayOrder)] enum Command { SecretKey(SecretKeyArgs), PublicKey(PublicKeyArgs), DeriveKey(DeriveKeyArgs), Encrypt(EncryptArgs), Decrypt(DecryptArgs), Sign(SignArgs), Verify(VerifyArgs), Complete(CompleteArgs), } #[derive(Debug, Parser)] struct SecretKeyArgs { #[clap(value_hint = ValueHint::FilePath)] output: PathBuf, #[clap(long, default_value = "128")] time: u32, #[clap(long, default_value = "1024")] space: u32, #[clap(long, value_hint = ValueHint::FilePath)] passphrase_file: Option<PathBuf>, } impl Cmd for SecretKeyArgs {
} #[derive(Debug, Parser)] struct PublicKeyArgs { #[clap(value_hint = ValueHint::FilePath)] secret_key: PathBuf, key_id: OsString, #[clap(parse(try_from_os_str = output_from_os_str), value_hint = ValueHint::FilePath, default_value="-")] output: Output, #[clap(long, value_hint = ValueHint::FilePath)] passphrase_file: Option<PathBuf>, } impl Cmd for PublicKeyArgs { fn run(mut self) -> Result<()> { let secret_key = decrypt_secret_key(&self.passphrase_file, &self.secret_key)?; let public_key = secret_key.public_key(self.key_id.to_string_lossy().as_ref()); write!(self.output.lock(), "{}", public_key)?; Ok(()) } } #[derive(Debug, Parser)] struct DeriveKeyArgs { public_key: OsString, sub_key_id: OsString, #[clap(parse(try_from_os_str = output_from_os_str), value_hint = ValueHint::FilePath, default_value="-")] output: Output, } impl Cmd for DeriveKeyArgs { fn run(mut self) -> Result<()> { let root = self.public_key.to_string_lossy().as_ref().parse::<PublicKey>()?; let public_key = root.derive(self.sub_key_id.to_string_lossy().as_ref()); write!(self.output.lock(), "{}", public_key)?; Ok(()) } } #[derive(Debug, Parser)] struct EncryptArgs { #[clap(value_hint = ValueHint::FilePath)] secret_key: PathBuf, key_id: OsString, #[clap(parse(try_from_os_str = input_from_os_str), value_hint = ValueHint::FilePath)] plaintext: Input, #[clap(parse(try_from_os_str = output_from_os_str), value_hint = ValueHint::FilePath)] ciphertext: Output, #[clap(required = true)] recipients: Vec<OsString>, #[clap(long, default_value = "0")] fakes: usize, #[clap(long, default_value = "0")] padding: u64, #[clap(long, value_hint = ValueHint::FilePath)] passphrase_file: Option<PathBuf>, } impl Cmd for EncryptArgs { fn run(mut self) -> Result<()> { let secret_key = decrypt_secret_key(&self.passphrase_file, &self.secret_key)?; let private_key = secret_key.private_key(self.key_id.to_string_lossy().as_ref()); let pks = self .recipients .iter() .map(|s| s.to_string_lossy().as_ref().parse::<PublicKey>()) .collect::<result::Result<Vec<PublicKey>, PublicKeyError>>()?; private_key.encrypt( &mut self.plaintext.lock(), &mut self.ciphertext.lock(), pks, self.fakes, self.padding, )?; Ok(()) } } #[derive(Debug, Parser)] struct DecryptArgs { #[clap(value_hint = ValueHint::FilePath)] secret_key: PathBuf, key_id: OsString, #[clap(parse(try_from_os_str = input_from_os_str), value_hint = ValueHint::FilePath)] ciphertext: Input, #[clap(parse(try_from_os_str = output_from_os_str), value_hint = ValueHint::FilePath)] plaintext: Output, sender: OsString, #[clap(long, value_hint = ValueHint::FilePath)] passphrase_file: Option<PathBuf>, } impl Cmd for DecryptArgs { fn run(mut self) -> Result<()> { let secret_key = decrypt_secret_key(&self.passphrase_file, &self.secret_key)?; let private_key = secret_key.private_key(self.key_id.to_string_lossy().as_ref()); let sender = self.sender.to_string_lossy().parse()?; private_key.decrypt(&mut self.ciphertext.lock(), &mut self.plaintext.lock(), &sender)?; Ok(()) } } #[derive(Debug, Parser)] struct SignArgs { #[clap(value_hint = ValueHint::FilePath)] secret_key: PathBuf, key_id: OsString, #[clap(parse(try_from_os_str = input_from_os_str), value_hint = ValueHint::FilePath)] message: Input, #[clap(parse(try_from_os_str = output_from_os_str), value_hint = ValueHint::FilePath, default_value="-")] output: Output, #[clap(long, value_hint = ValueHint::FilePath)] passphrase_file: Option<PathBuf>, } impl Cmd for SignArgs { fn run(mut self) -> Result<()> { let secret_key = decrypt_secret_key(&self.passphrase_file, &self.secret_key)?; let private_key = secret_key.private_key(self.key_id.to_string_lossy().as_ref()); let sig = private_key.sign(&mut self.message.lock())?; write!(self.output.lock(), "{}", sig)?; Ok(()) } } #[derive(Debug, Parser)] struct VerifyArgs { public_key: OsString, #[clap(parse(try_from_os_str = input_from_os_str), value_hint = ValueHint::FilePath)] message: Input, signature: OsString, } impl Cmd for VerifyArgs { fn run(mut self) -> Result<()> { let signer = self.public_key.to_string_lossy().as_ref().parse::<PublicKey>()?; let sig = self.signature.to_string_lossy().as_ref().parse::<Signature>()?; signer.verify(&mut self.message.lock(), &sig)?; Ok(()) } } #[derive(Debug, Parser)] #[clap(setting = AppSettings::Hidden)] struct CompleteArgs { shell: Shell, #[clap(value_hint = ValueHint::DirPath)] output: OsString, } impl Cmd for CompleteArgs { fn run(self) -> Result<()> { let mut app: App = Opts::into_app(); generate_to(self.shell, &mut app, "veil", &self.output)?; Ok(()) } } fn decrypt_secret_key(passphrase_file: &Option<PathBuf>, path: &Path) -> Result<SecretKey> { let passphrase = prompt_passphrase(passphrase_file)?; let ciphertext = fs::read(path)?; let sk = SecretKey::decrypt(&passphrase, &ciphertext)?; Ok(sk) } fn prompt_passphrase(passphrase_file: &Option<PathBuf>) -> Result<String> { match passphrase_file { Some(p) => Ok(fs::read_to_string(p)?), None => Ok(rpassword::read_password_from_tty(Some("Enter passphrase: "))?), } } fn input_from_os_str(path: &OsStr) -> Result<Input, String> { Input::new(path).map_err(|e| e.to_string()) } fn output_from_os_str(path: &OsStr) -> Result<Output, String> { Output::new(path).map_err(|e| e.to_string()) }
fn run(self) -> Result<()> { let passphrase = prompt_passphrase(&self.passphrase_file)?; let secret_key = SecretKey::new(); let ciphertext = secret_key.encrypt(&passphrase, self.time, self.space); fs::write(self.output, ciphertext)?; Ok(()) }
function_block-function_prefix_line
[ { "content": "fn init(passphrase: &[u8], salt: &[u8], time: u32, space: u32) -> Strobe {\n\n let mut pbenc = Strobe::new(b\"veil.pbenc\", SecParam::B128);\n\n\n\n // Initialize protocol with metadata.\n\n pbenc.meta_ad_u32(DELTA as u32);\n\n pbenc.meta_ad_u32(N as u32);\n\n pbenc.meta_ad_u32(MAC_...
Rust
src/lib.rs
phaylon/resorb
4b36e3da17b66c97e28b86ee23f7db9d77d8a38d
use std::rc; use std::sync; use std::error; use std::fmt; macro_rules! assert_parse_ok { ($parser:expr, $input:expr, $expected:expr $(,)*) => {{ let input: String = ($input).into(); assert_eq!( ::apply(&input, ::Options::default(), $parser), Ok($expected) ); drop(input); }} } macro_rules! assert_parse_no_match { ($parser:expr, $input:expr $(,)*) => {{ let input: String = ($input).into(); assert_eq!( ::apply(&input, ::Options::default(), $parser), Err(::ApplyError::NoMatch) ); drop(input); }} } macro_rules! assert_parse_fail { ($parser:expr, $input:expr, $value:expr, ($($l:tt)+) $(,)*) => {{ let input: String = ($input).into(); assert_eq!( ::apply(&input, ::Options::default(), $parser), Err(::ApplyError::Fail(::Error::new(::Location::new($($l)+), $value))) ); drop(input); }} } macro_rules! assert_parse_partial { ($parser:expr, $input:expr, $value:expr, $rest:expr, ($($l:tt)+) $(,)*) => {{ let input: String = ($input).into(); assert_eq!( ::apply(&input, ::Options::default(), $parser), Err(::ApplyError::Unparsed($value, ::Location::new($($l)+), $rest)) ); drop(input); }} } pub mod util; pub mod parse; pub fn apply<'src, P>(input: &'src str, options: Options, parser: P) -> Result<P::Output, ApplyError<'src, P::Output, P::Error>> where P: Parser<'src> { let depth_limit = options.depth_limit; let ctx = Context { options: options, depth: 1, }; let input = Input { rest: input, location: Location { line: 1, column: 1, offset: 0, }, }; match parser.parse(input, ctx) { Ok((value, input)) => match input.unpack_if_nonempty() { None => Ok(value), Some((location, rest)) => Err(ApplyError::Unparsed(value, location, rest)), }, Err(Fail::NoMatch) => Err(ApplyError::NoMatch), Err(Fail::DepthLimit(location)) => Err(ApplyError::DepthLimit(location, depth_limit.unwrap())), Err(Fail::Error(error)) => Err(ApplyError::Fail(error)), Err(Fail::ZeroLengthRepeat(location)) => Err(ApplyError::ZeroLengthRepeat(location)), } } #[derive( Debug, Clone )] pub struct Context { options: Options, depth: usize, } impl Context { pub fn descend<'src, E>(&self, input: &Input<'src>) -> Result<Context, Fail<E>> { let new_depth = self.depth + 1; if let Some(limit) = self.options.depth_limit { if new_depth > limit { return Err(Fail::DepthLimit(input.location)); } } Ok(Context { options: self.options.clone(), depth: new_depth, }) } } #[derive( Debug, Clone )] pub struct Options { pub depth_limit: Option<usize>, } impl Default for Options { fn default() -> Options { Options { depth_limit: Some(64), } } } #[derive( Debug, Clone, PartialEq, Eq )] pub enum ApplyError<'src, T, E> { NoMatch, Fail(Error<E>), DepthLimit(Location, usize), Unparsed(T, Location, &'src str), ZeroLengthRepeat(Location), } pub type Outcome<'src, O, E> = Result<(O, Input<'src>), Fail<E>>; pub trait Parser<'src> { type Output; type Error; fn parse(&self, input: Input<'src>, ctx: Context) -> Outcome<'src, Self::Output, Self::Error>; } impl<'src, P> Parser<'src> for sync::Arc<P> where P: Parser<'src> { type Output = P::Output; type Error = P::Error; fn parse(&self, input: Input<'src>, ctx: Context) -> Outcome<'src, Self::Output, Self::Error> { (**self).parse(input, ctx) } } impl<'src, P> Parser<'src> for rc::Rc<P> where P: Parser<'src> { type Output = P::Output; type Error = P::Error; fn parse(&self, input: Input<'src>, ctx: Context) -> Outcome<'src, Self::Output, Self::Error> { (**self).parse(input, ctx) } } impl<'src, P> Parser<'src> for Box<P> where P: Parser<'src> { type Output = P::Output; type Error = P::Error; fn parse(&self, input: Input<'src>, ctx: Context) -> Outcome<'src, Self::Output, Self::Error> { (**self).parse(input, ctx) } } impl<'src, 'p, P> Parser<'src> for &'p P where P: Parser<'src> { type Output = P::Output; type Error = P::Error; fn parse(&self, input: Input<'src>, ctx: Context) -> Outcome<'src, Self::Output, Self::Error> { (**self).parse(input, ctx) } } #[derive( Debug, Clone, PartialEq, Eq )] pub enum Fail<E> { NoMatch, Error(Error<E>), DepthLimit(Location), ZeroLengthRepeat(Location), } #[derive( Debug, Clone, Copy, PartialEq, Eq )] pub struct Location { line: usize, column: usize, offset: usize, } impl Location { pub fn new(line: usize, column: usize, offset: usize) -> Location { Location { line: line, column: column, offset: offset, } } pub fn line(&self) -> usize { self.line } pub fn column(&self) -> usize { self.column } pub fn offset(&self) -> usize { self.offset } fn advance(&self, parsed: &str) -> Location { let nl_count = parsed .chars() .filter(|c| *c == '\n') .count(); let last_line = parsed .rfind('\n') .map(|nl_pos| &parsed[(nl_pos+1)..]) .unwrap_or(&parsed); let last_line_chars = last_line .chars() .count(); Location { offset: self.offset + parsed.len(), line: self.line + nl_count, column: last_line_chars + if nl_count > 0 { 1 } else { self.column }, } } } #[derive( Debug, Clone )] pub struct Input<'src> { rest: &'src str, location: Location, } impl<'src> Input<'src> { pub fn location(&self) -> Location { self.location } pub fn consume_len_via<F>(self, find_len: F) -> Option<(&'src str, Input<'src>)> where F: FnOnce(&'src str) -> Option<usize> { let len = match find_len(self.rest) { None => return None, Some(len) => len, }; let consumed = &self.rest[..len]; Some((consumed, self.advance(len))) } pub fn consume_char(self) -> Option<(char, Input<'src>)> { let chr = match self.rest.chars().nth(0) { None => return None, Some(chr) => chr, }; Some((chr, self.advance(chr.len_utf8()))) } fn advance(self, len: usize) -> Input<'src> { let consumed = &self.rest[..len]; let new_rest = &self.rest[len..]; let new_location = self.location.advance(consumed); Input { rest: new_rest, location: new_location, } } fn unpack_if_nonempty(self) -> Option<(Location, &'src str)> { if self.rest.len() > 0 { Some((self.location, self.rest)) } else { None } } } #[derive( Debug, Clone, PartialEq, Eq )] pub struct Error<E> { location: Location, value: E, cause: Option<Box<Error<E>>>, } impl<E> Error<E> { pub fn new(location: Location, value: E) -> Error<E> { Error { location: location, value: value, cause: None, } } pub fn new_with_cause(location: Location, value: E, cause: Error<E>) -> Error<E> { Error { location: location, value: value, cause: Some(Box::new(cause)), } } pub fn location(&self) -> Location { self.location } pub fn value(&self) -> &E { &self.value } pub fn cause(&self) -> Option<&Error<E>> { match self.cause { Some(ref error) => Some(&*error), None => None, } } } impl<E> fmt::Display for Error<E> where E: fmt::Display { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.value, fmt) } } impl<E> error::Error for Error<E> where E: error::Error { fn description(&self) -> &str { self.value.description() } fn cause(&self) -> Option<&error::Error> { match self.cause { Some(ref error) => Some(&*error), None => None, } } } #[cfg(test)] mod tests { use parse; #[test] fn apply() { #[derive( Debug, Clone, PartialEq, Eq )] struct ErrMarker; let parser = parse::pair( parse::exact_str("foo"), parse::require(parse::exact_str("bar"), || ErrMarker), ); assert_parse_ok!(&parser, "foobar", ("foo", "bar")); assert_parse_no_match!(&parser, "qux"); assert_parse_fail!(&parser, "fooqux", ErrMarker, (1, 4, 3)); } #[test] fn pointers() { use std::rc::Rc; use std::sync::Arc; let plain = parse::no_custom_error(parse::exact_str("foo")); assert_eq!(::apply("foo", ::Options::default(), &plain), Ok("foo")); let boxed = Box::new(parse::no_custom_error(parse::exact_str("foo"))); assert_eq!(::apply("foo", ::Options::default(), boxed), Ok("foo")); let rced = Rc::new(parse::no_custom_error(parse::exact_str("foo"))); assert_eq!(::apply("foo", ::Options::default(), rced), Ok("foo")); let arced = Arc::new(parse::no_custom_error(parse::exact_str("foo"))); assert_eq!(::apply("foo", ::Options::default(), arced), Ok("foo")); } #[test] fn location() { use super::Location as L; let loc = L::new(1, 1, 0).advance("foo"); assert_eq!(loc, L::new(1, 4, 3)); let loc = loc.advance(" \t"); assert_eq!(loc, L::new(1, 6, 5)); let loc = loc.advance("\n"); assert_eq!(loc, L::new(2, 1, 6)); let loc = loc.advance("a\nb\nc"); assert_eq!(loc, L::new(4, 2, 11)); } }
use std::rc; use std::sync; use std::error; use std::fmt; macro_rules! assert_parse_ok { ($parser:expr, $input:expr, $expected:expr $(,)*) => {{ let input: String = ($input).into(); assert_eq!( ::apply(&input, ::Options::default(), $parser), Ok($expected) ); drop(input); }} } macro_rules! assert_parse_no_match { ($parser:expr, $input:expr $(,)*) => {{ let input: String = ($input).into(); assert_eq!( ::apply(&input, ::Options::default(), $parser), Err(::ApplyError::NoMatch) ); drop(input); }} } macro_rules! assert_parse_fail { ($parser:expr, $input:expr, $value:expr, ($($l:tt)+) $(,)*) => {{ let input: String = ($input).into(); assert_eq!( ::apply(&input, ::Options::default(), $parser), Err(::ApplyError::Fail(::Error::new(::Location::new($($l)+), $value))) ); drop(input); }} } macro_rules! assert_parse_partial { ($parser:expr, $input:expr, $value:expr, $rest:expr, ($($l:tt)+) $(,)*) => {{ let input: String = ($input).into(); assert_eq!( ::apply(&input, ::Options::default(), $parser), Err(::ApplyError::Unparsed($value, ::Location::new($($l)+), $rest)) ); drop(input); }} } pub mod util; pub mod parse; pub fn apply<'src, P>(input: &'src str, options: Options, parser: P) -> Result<P::Output, ApplyError<'src, P::Output, P::Error>> where P: Parser<'src> { let depth_limit = options.depth_limit; let ctx = Context { options: options, depth: 1, }; let input = Input { rest: input, location: Location { line: 1, column: 1, offset: 0, }, }; match parser.parse(input, ctx) { Ok((value, input)) => match input.unpack_if_nonempty() { None => Ok(value), Some((location, rest)) => Err(ApplyError::Unparsed(value, location, rest)), }, Err(Fail::NoMatch) => Err(ApplyError::NoMatch), Err(Fail::DepthLimit(location)) => Err(ApplyError::DepthLimit(location, depth_limit.unwrap())), Err(Fail::Error(error)) => Err(ApplyError::Fail(error)), Err(Fail::ZeroLengthRepeat(location)) => Err(ApplyError::ZeroLengthRepeat(location)), } } #[derive( Debug, Clone )] pub struct Context { options: Options, depth: usize, } impl Context { pub fn descend<'src, E>(&self, input: &Input<'src>) -> Result<Context, Fail<E>> { let new_depth = self.depth + 1; if let Some(limit) = self.options.depth_limit { if new_depth > limit { return Err(Fail::DepthLimit(input.location)); } } Ok(Context { options: self.options.clone(), depth: new_depth, }) } } #[derive( Debug, Clone )] pub struct Options { pub depth_limit: Option<usize>, } impl Default for Options { fn default() -> Options { Options { depth_limit: Some(64), } } } #[derive( Debug, Clone, PartialEq, Eq )] pub enum ApplyError<'src, T, E> { NoMatch, Fail(Error<E>), DepthLimit(Location, usize), Unparsed(T, Location, &'src str), ZeroLengthRepeat(Location), } pub type Outcome<'src, O, E> = Result<(O, Input<'src>), Fail<E>>; pub trait Parser<'src> { type Output; type Error; fn parse(&self, input: Input<'src>, ctx: Context) -> Outcome<'src, Self::Output, Self::Error>; } impl<'src, P> Parser<'src> for sync::Arc<P> where P: Parser<'src> { type Output = P::Output; type Error = P::Error; fn parse(&self, input: Input<'src>, ctx: Context) -> Outcome<'src, Self::Output, Self::Error> { (**self).parse(input, ctx) } } impl<'src, P> Parser<'src> for rc::Rc<P> where P: Parser<'src> { type Output = P::Output; type Error = P::Error; fn parse(&self, input: Input<'src>, ctx: Context) -> Outcome<'src, Self::Output, Self::Error> { (**self).parse(input, ctx) } } impl<'src, P> Parser<'src> for Box<P> where P: Parser<'src> { type Output = P::Output; type Error = P::Error; fn parse(&self, input: Input<'src>, ctx: Context) -> Outcome<'src, Self::Output, Self::Error> { (**self).parse(input, ctx) } } impl<'src, 'p, P> Parser<'src> for &'p P where P: Parser<'src> { type Output = P::Output; type Error = P::Error; fn parse(&self, input: Input<'src>, ctx: Context) -> Outcome<'src, Self::Output, Self::Error> { (**self).parse(input, ctx) } } #[derive( Debug, Clone, PartialEq, Eq )] pub enum Fail<E> { NoMatch, Error(Error<E>), DepthLimit(Location), ZeroLengthRepeat(Location), } #[derive( Debug, Clone, Copy, PartialEq, Eq )] pub struct Location { line: usize, column: usize, offset: usize, } impl Location {
pub fn line(&self) -> usize { self.line } pub fn column(&self) -> usize { self.column } pub fn offset(&self) -> usize { self.offset } fn advance(&self, parsed: &str) -> Location { let nl_count = parsed .chars() .filter(|c| *c == '\n') .count(); let last_line = parsed .rfind('\n') .map(|nl_pos| &parsed[(nl_pos+1)..]) .unwrap_or(&parsed); let last_line_chars = last_line .chars() .count(); Location { offset: self.offset + parsed.len(), line: self.line + nl_count, column: last_line_chars + if nl_count > 0 { 1 } else { self.column }, } } } #[derive( Debug, Clone )] pub struct Input<'src> { rest: &'src str, location: Location, } impl<'src> Input<'src> { pub fn location(&self) -> Location { self.location } pub fn consume_len_via<F>(self, find_len: F) -> Option<(&'src str, Input<'src>)> where F: FnOnce(&'src str) -> Option<usize> { let len = match find_len(self.rest) { None => return None, Some(len) => len, }; let consumed = &self.rest[..len]; Some((consumed, self.advance(len))) } pub fn consume_char(self) -> Option<(char, Input<'src>)> { let chr = match self.rest.chars().nth(0) { None => return None, Some(chr) => chr, }; Some((chr, self.advance(chr.len_utf8()))) } fn advance(self, len: usize) -> Input<'src> { let consumed = &self.rest[..len]; let new_rest = &self.rest[len..]; let new_location = self.location.advance(consumed); Input { rest: new_rest, location: new_location, } } fn unpack_if_nonempty(self) -> Option<(Location, &'src str)> { if self.rest.len() > 0 { Some((self.location, self.rest)) } else { None } } } #[derive( Debug, Clone, PartialEq, Eq )] pub struct Error<E> { location: Location, value: E, cause: Option<Box<Error<E>>>, } impl<E> Error<E> { pub fn new(location: Location, value: E) -> Error<E> { Error { location: location, value: value, cause: None, } } pub fn new_with_cause(location: Location, value: E, cause: Error<E>) -> Error<E> { Error { location: location, value: value, cause: Some(Box::new(cause)), } } pub fn location(&self) -> Location { self.location } pub fn value(&self) -> &E { &self.value } pub fn cause(&self) -> Option<&Error<E>> { match self.cause { Some(ref error) => Some(&*error), None => None, } } } impl<E> fmt::Display for Error<E> where E: fmt::Display { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.value, fmt) } } impl<E> error::Error for Error<E> where E: error::Error { fn description(&self) -> &str { self.value.description() } fn cause(&self) -> Option<&error::Error> { match self.cause { Some(ref error) => Some(&*error), None => None, } } } #[cfg(test)] mod tests { use parse; #[test] fn apply() { #[derive( Debug, Clone, PartialEq, Eq )] struct ErrMarker; let parser = parse::pair( parse::exact_str("foo"), parse::require(parse::exact_str("bar"), || ErrMarker), ); assert_parse_ok!(&parser, "foobar", ("foo", "bar")); assert_parse_no_match!(&parser, "qux"); assert_parse_fail!(&parser, "fooqux", ErrMarker, (1, 4, 3)); } #[test] fn pointers() { use std::rc::Rc; use std::sync::Arc; let plain = parse::no_custom_error(parse::exact_str("foo")); assert_eq!(::apply("foo", ::Options::default(), &plain), Ok("foo")); let boxed = Box::new(parse::no_custom_error(parse::exact_str("foo"))); assert_eq!(::apply("foo", ::Options::default(), boxed), Ok("foo")); let rced = Rc::new(parse::no_custom_error(parse::exact_str("foo"))); assert_eq!(::apply("foo", ::Options::default(), rced), Ok("foo")); let arced = Arc::new(parse::no_custom_error(parse::exact_str("foo"))); assert_eq!(::apply("foo", ::Options::default(), arced), Ok("foo")); } #[test] fn location() { use super::Location as L; let loc = L::new(1, 1, 0).advance("foo"); assert_eq!(loc, L::new(1, 4, 3)); let loc = loc.advance(" \t"); assert_eq!(loc, L::new(1, 6, 5)); let loc = loc.advance("\n"); assert_eq!(loc, L::new(2, 1, 6)); let loc = loc.advance("a\nb\nc"); assert_eq!(loc, L::new(4, 2, 11)); } }
pub fn new(line: usize, column: usize, offset: usize) -> Location { Location { line: line, column: column, offset: offset, } }
function_block-full_function
[ { "content": "pub fn fail<E>(location: ::Location, error: E) -> ::Fail<E> {\n\n ::Fail::Error(::Error::new(location, error))\n\n}\n", "file_path": "src/util.rs", "rank": 0, "score": 211455.97158554505 }, { "content": "pub fn no_custom_error<'src, P>(parser: P) -> P where P: ::Parser<'src,...
Rust
src/config.rs
drogue-iot/drogue-event-source
6f96f14d95de0bd914f523c6cb2b284bd24cf57b
use anyhow::Result; use reqwest::Method; use serde::Deserialize; use serde_with::serde_as; use std::collections::HashMap; use std::time::Duration; pub trait ConfigFromEnv<'de>: Sized + Deserialize<'de> { fn from_env() -> Result<Self, config::ConfigError> { Self::from(config::Environment::default()) } fn from_env_source(source: HashMap<String, String>) -> Result<Self, config::ConfigError> { Self::from(config::Environment::default().source(Some(source))) } fn from_env_prefix<S: AsRef<str>>(prefix: S) -> Result<Self, config::ConfigError> { Self::from(config::Environment::with_prefix(prefix.as_ref())) } fn from(env: config::Environment) -> Result<Self, config::ConfigError>; } impl<'de, T: Deserialize<'de> + Sized> ConfigFromEnv<'de> for T { fn from(env: config::Environment) -> Result<T, config::ConfigError> { let cfg = config::Config::builder() .add_source(env.separator("__")) .build()?; cfg.try_deserialize() } } #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] #[serde(tag = "mode")] #[serde(rename_all = "lowercase")] pub enum Mode { Kafka(KafkaConfig), #[serde(alias = "ws")] Websocket(WebsocketConfig), } #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] pub struct KafkaConfig { pub topic: String, pub bootstrap_servers: String, #[serde(default)] pub properties: HashMap<String, String>, } #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] pub struct WebsocketConfig { pub drogue_endpoint: String, pub drogue_app: String, pub drogue_user: String, pub drogue_token: String, } #[derive(Clone, Debug, Deserialize)] pub struct Config { #[serde(default)] pub endpoint: EndpointConfig, pub k_sink: String, #[serde(flatten)] pub mode: Mode, } #[serde_as] #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] pub struct EndpointConfig { #[serde(default = "default_method")] #[serde_as(as = "serde_with::DisplayFromStr")] pub method: Method, #[serde(default)] pub username: Option<String>, #[serde(default)] pub password: Option<String>, #[serde(default)] pub token: Option<String>, #[serde(default)] pub tls_insecure: bool, #[serde(default)] pub tls_certificate: Option<String>, #[serde(default)] pub headers: HashMap<String, String>, #[serde(default, with = "humantime_serde")] pub timeout: Option<Duration>, #[serde(default = "default_error_delay", with = "humantime_serde")] pub error_delay: Duration, #[serde(default = "default_retries")] pub retries: usize, } impl Default for EndpointConfig { fn default() -> Self { Self { method: default_method(), username: None, password: None, token: None, tls_insecure: false, tls_certificate: None, headers: Default::default(), timeout: None, error_delay: default_error_delay(), retries: default_retries(), } } } const fn default_error_delay() -> Duration { Duration::from_secs(1) } const fn default_retries() -> usize { 5 } const fn default_method() -> Method { Method::POST } #[cfg(test)] mod test { use super::*; use maplit::*; #[test] fn test_cfg_kafka() { let env = convert_args!(hashmap!( "MODE" => "kafka", "BOOTSTRAP_SERVERS" => "bootstrap:9091", "TOPIC" => "topic", "PROPERTIES__FOO_BAR" => "baz", "K_SINK" => "http://localhost", )); let cfg = Config::from_env_source(env).unwrap(); assert_eq!( cfg.mode, Mode::Kafka(KafkaConfig { topic: "topic".to_string(), bootstrap_servers: "bootstrap:9091".into(), properties: convert_args!(hashmap!( "foo_bar" => "baz", )) }) ); } #[test] fn test_cfg_ws() { let env = convert_args!(hashmap!( "MODE" => "ws", "DROGUE_APP" => "app", "DROGUE_ENDPOINT" => "endpoint", "DROGUE_USER" => "user", "DROGUE_TOKEN" => "token", "K_SINK" => "http://localhost", )); let cfg = Config::from_env_source(env).unwrap(); assert_eq!( cfg.mode, Mode::Websocket(WebsocketConfig { drogue_app: "app".into(), drogue_endpoint: "endpoint".into(), drogue_user: "user".into(), drogue_token: "token".into(), }) ); } #[test] fn test_cfg_endpoint() { let env = convert_args!(hashmap!( "MODE" => "ws", "DROGUE_APP" => "app", "DROGUE_ENDPOINT" => "endpoint", "DROGUE_USER" => "user", "DROGUE_TOKEN" => "token", "K_SINK" => "http://localhost", "ENDPOINT__METHOD" => "GET", "ENDPOINT__HEADERS__foo" => "bar", )); let cfg = Config::from_env_source(env).unwrap(); assert_eq!( cfg.endpoint, EndpointConfig { method: Method::GET, username: None, password: None, token: None, tls_insecure: false, tls_certificate: None, headers: convert_args!(hashmap!( "foo" => "bar" )), timeout: None, error_delay: default_error_delay(), retries: 5 } ); } }
use anyhow::Result; use reqwest::Method; use serde::Deserialize; use serde_with::serde_as; use std::collections::HashMap; use std::time::Duration; pub trait ConfigFromEnv<'de>: Sized + Deserialize<'de> { fn from_env() -> Result<Self, config::ConfigError> { Self::from(config::Environment::default()) } fn from_env_source(source: HashMap<String, String>) -> Result<Self, config::ConfigError> { Self::from(config::Environment::default().source(Some(source))) } fn from_env_prefix<S: AsRef<str>>(prefix: S) -> Result<Self, config::ConfigError> { Self::from(config::Environment::with_prefix(prefix.as_ref())) } fn from(env: config::Environment) -> Result<Self, config::ConfigError>; } impl<'de, T: Deserialize<'de> + Sized> ConfigFromEnv<'de> for T { fn from(env: config::Environment) -> Result<T, config::ConfigError> {
} #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] #[serde(tag = "mode")] #[serde(rename_all = "lowercase")] pub enum Mode { Kafka(KafkaConfig), #[serde(alias = "ws")] Websocket(WebsocketConfig), } #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] pub struct KafkaConfig { pub topic: String, pub bootstrap_servers: String, #[serde(default)] pub properties: HashMap<String, String>, } #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] pub struct WebsocketConfig { pub drogue_endpoint: String, pub drogue_app: String, pub drogue_user: String, pub drogue_token: String, } #[derive(Clone, Debug, Deserialize)] pub struct Config { #[serde(default)] pub endpoint: EndpointConfig, pub k_sink: String, #[serde(flatten)] pub mode: Mode, } #[serde_as] #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] pub struct EndpointConfig { #[serde(default = "default_method")] #[serde_as(as = "serde_with::DisplayFromStr")] pub method: Method, #[serde(default)] pub username: Option<String>, #[serde(default)] pub password: Option<String>, #[serde(default)] pub token: Option<String>, #[serde(default)] pub tls_insecure: bool, #[serde(default)] pub tls_certificate: Option<String>, #[serde(default)] pub headers: HashMap<String, String>, #[serde(default, with = "humantime_serde")] pub timeout: Option<Duration>, #[serde(default = "default_error_delay", with = "humantime_serde")] pub error_delay: Duration, #[serde(default = "default_retries")] pub retries: usize, } impl Default for EndpointConfig { fn default() -> Self { Self { method: default_method(), username: None, password: None, token: None, tls_insecure: false, tls_certificate: None, headers: Default::default(), timeout: None, error_delay: default_error_delay(), retries: default_retries(), } } } const fn default_error_delay() -> Duration { Duration::from_secs(1) } const fn default_retries() -> usize { 5 } const fn default_method() -> Method { Method::POST } #[cfg(test)] mod test { use super::*; use maplit::*; #[test] fn test_cfg_kafka() { let env = convert_args!(hashmap!( "MODE" => "kafka", "BOOTSTRAP_SERVERS" => "bootstrap:9091", "TOPIC" => "topic", "PROPERTIES__FOO_BAR" => "baz", "K_SINK" => "http://localhost", )); let cfg = Config::from_env_source(env).unwrap(); assert_eq!( cfg.mode, Mode::Kafka(KafkaConfig { topic: "topic".to_string(), bootstrap_servers: "bootstrap:9091".into(), properties: convert_args!(hashmap!( "foo_bar" => "baz", )) }) ); } #[test] fn test_cfg_ws() { let env = convert_args!(hashmap!( "MODE" => "ws", "DROGUE_APP" => "app", "DROGUE_ENDPOINT" => "endpoint", "DROGUE_USER" => "user", "DROGUE_TOKEN" => "token", "K_SINK" => "http://localhost", )); let cfg = Config::from_env_source(env).unwrap(); assert_eq!( cfg.mode, Mode::Websocket(WebsocketConfig { drogue_app: "app".into(), drogue_endpoint: "endpoint".into(), drogue_user: "user".into(), drogue_token: "token".into(), }) ); } #[test] fn test_cfg_endpoint() { let env = convert_args!(hashmap!( "MODE" => "ws", "DROGUE_APP" => "app", "DROGUE_ENDPOINT" => "endpoint", "DROGUE_USER" => "user", "DROGUE_TOKEN" => "token", "K_SINK" => "http://localhost", "ENDPOINT__METHOD" => "GET", "ENDPOINT__HEADERS__foo" => "bar", )); let cfg = Config::from_env_source(env).unwrap(); assert_eq!( cfg.endpoint, EndpointConfig { method: Method::GET, username: None, password: None, token: None, tls_insecure: false, tls_certificate: None, headers: convert_args!(hashmap!( "foo" => "bar" )), timeout: None, error_delay: default_error_delay(), retries: 5 } ); } }
let cfg = config::Config::builder() .add_source(env.separator("__")) .build()?; cfg.try_deserialize() }
function_block-function_prefix_line
[ { "content": "use crate::EndpointConfig;\n\nuse anyhow::bail;\n\nuse cloudevents::binding::reqwest::RequestBuilderExt;\n\nuse reqwest::{Certificate, Url};\n\nuse std::time::Duration;\n\nuse thiserror::Error;\n\n\n\npub struct Sender {\n\n config: EndpointConfig,\n\n url: Url,\n\n client: reqwest::Clien...
Rust
src/lib.rs
DomWilliams0/panik-rs
493ac556522b245c54e070bc44119fc1c99a488c
use backtrace::Backtrace; use std::borrow::Cow; use std::fmt::Debug; use std::panic::{PanicInfo, UnwindSafe}; use std::thread::ThreadId; use std::cmp::Ordering; use std::ops::DerefMut; #[cfg(feature = "use-parking-lot")] use parking_lot::Mutex; #[cfg(not(feature = "use-parking-lot"))] use std::sync::Mutex; const DEFAULT_BACKTRACE_RESOLUTION_LIMIT: usize = 8; lazy_static::lazy_static! { static ref STATE: Mutex<State> = Mutex::new(State::default()); } macro_rules! log_warn { ($state:expr, $($arg:tt)+) => { #[cfg(feature = "use-slog")] slog::warn!(&$state.slogger, $($arg)+); #[cfg(feature = "use-log")] log::warn!($($arg)+); #[cfg(feature = "use-stderr")] eprintln!($($arg)+); } } macro_rules! log_error { ($state:expr, $($arg:tt)+) => { #[cfg(feature = "use-slog")] slog::error!(&$state.slogger, $($arg)+); #[cfg(feature = "use-log")] log::error!($($arg)+); #[cfg(feature = "use-stderr")] eprintln!($($arg)+); } } macro_rules! log_crit { ($state:expr, $($arg:tt)+) => { #[cfg(feature = "use-slog")] slog::crit!(&$state.slogger, $($arg)+); #[cfg(feature = "use-log")] log::error!($($arg)+); #[cfg(feature = "use-stderr")] eprintln!($($arg)+); } } struct State { panics: Vec<Panic>, backtrace_resolution_limit: usize, is_running: bool, #[cfg(feature = "use-slog")] slogger: slog::Logger, } #[derive(Debug, Clone)] pub struct Panic { message: String, thread_id: ThreadId, thread: String, backtrace: Backtrace, backtrace_resolved: bool, } #[derive(Clone)] pub struct Builder { #[cfg(feature = "use-slog")] slogger: Option<slog::Logger>, backtrace_resolution_limit: usize, } struct GlobalStateGuard; impl Builder { pub fn new() -> Self { Builder { #[cfg(feature = "use-slog")] slogger: None, backtrace_resolution_limit: DEFAULT_BACKTRACE_RESOLUTION_LIMIT, } } #[cfg(feature = "use-slog")] pub fn slogger(mut self, slogger: impl Into<slog::Logger>) -> Self { self.slogger = Some(slogger.into()); self } pub fn backtrace_resolution_limit(mut self, n: usize) -> Self { self.backtrace_resolution_limit = n; self } fn apply_settings(&mut self) { let mut state = state_mutex(); #[cfg(feature = "use-slog")] { state.slogger = self.slogger.take().unwrap_or_else(default_slogger); } state.backtrace_resolution_limit = self.backtrace_resolution_limit; } pub fn run_and_handle_panics<R: Debug>( mut self, do_me: impl FnOnce() -> R + UnwindSafe, ) -> Option<R> { self.apply_settings(); run_and_handle_panics(do_me) } pub fn run_and_handle_panics_no_debug<R>( mut self, do_me: impl FnOnce() -> R + UnwindSafe, ) -> Option<R> { self.apply_settings(); run_and_handle_panics_no_debug(do_me) } } impl Default for Builder { fn default() -> Self { Self::new() } } fn register_panic(panic: &PanicInfo) { let (thread, tid) = { let t = std::thread::current(); let name = t.name().unwrap_or("<unnamed>"); (format!("{:?} ({})", t.id(), name), t.id()) }; let message = panic .payload() .downcast_ref::<&str>() .map(|s| Cow::Borrowed(*s)) .unwrap_or_else(|| Cow::from(format!("{}", panic))); let backtrace = Backtrace::new_unresolved(); let mut state = state_mutex(); log_error!(&state, "handling panic on thread {}: '{}'", thread, message); state.panics.push(Panic { message: message.into_owned(), thread_id: tid, thread, backtrace, backtrace_resolved: false, }); } fn state_mutex() -> impl DerefMut<Target = State> { #[cfg(feature = "use-parking-lot")] return STATE.lock(); #[cfg(not(feature = "use-parking-lot"))] STATE.lock().unwrap() } pub fn run_and_handle_panics_no_debug<R>(do_me: impl FnOnce() -> R + UnwindSafe) -> Option<R> { run_and_handle_panics_with_maybe_debug(do_me, |_| Cow::Borrowed("<unprintable>")) } pub fn run_and_handle_panics<R: Debug>(do_me: impl FnOnce() -> R + UnwindSafe) -> Option<R> { run_and_handle_panics_with_maybe_debug(do_me, |res| Cow::Owned(format!("{:?}", res))) } fn run_and_handle_panics_with_maybe_debug<R>( do_me: impl FnOnce() -> R + UnwindSafe, format_swallowed: impl FnOnce(R) -> Cow<'static, str>, ) -> Option<R> { let _guard = GlobalStateGuard::init(); let result = std::panic::catch_unwind(|| do_me()); let mut state = state_mutex(); match (result, state.panics.is_empty()) { (Ok(res), true) => { return Some(res); } (Ok(res), false) => { let swallowed = format_swallowed(res); log_warn!( &state, "panic occurred in another thread, swallowing unpanicked result: {}", swallowed ); } (Err(_), false) => {} (Err(_), true) => unreachable!(), }; log_error!( &state, "{count} threads panicked", count = state.panics.len() ); let backtrace_resolution_limit = state.backtrace_resolution_limit; let mut panics = std::mem::take(&mut state.panics); debug_assert!(!panics.is_empty(), "panics vec should not be empty"); for ( i, Panic { message, thread, ref mut backtrace, backtrace_resolved, .. }, ) in panics.iter_mut().enumerate() { match i.cmp(&backtrace_resolution_limit) { Ordering::Less => { backtrace.resolve(); *backtrace_resolved = true; } Ordering::Equal => { #[cfg(feature = "use-log")] log::warn!( "handling more than {limit} panics, no longer resolving backtraces", limit = backtrace_resolution_limit ); #[cfg(feature = "use-stderr")] eprintln!( "handling more than {limit} panics, no longer resolving backtraces", limit = backtrace_resolution_limit ); } _ => {} }; if *backtrace_resolved { log_crit!( &state, "panic on thread {:?}: {:?}\n{:?}", thread, message, backtrace ); } else { log_crit!(&state, "panic on thread {:?}: {:?}", thread, message,); } } let empty = std::mem::replace(&mut state.panics, panics); debug_assert!(empty.is_empty()); std::mem::forget(empty); None } pub fn panics() -> Vec<Panic> { let state = state_mutex(); state.panics.clone() } pub fn has_panicked() -> bool { !state_mutex().panics.is_empty() } impl Panic { pub fn is_backtrace_resolved(&self) -> bool { self.backtrace_resolved } pub fn message(&self) -> &str { &self.message } pub fn thread_id(&self) -> ThreadId { self.thread_id } pub fn thread_name(&self) -> &str { &self.thread } pub fn backtrace(&self) -> &Backtrace { &self.backtrace } } impl GlobalStateGuard { fn init() -> Self { let mut state = state_mutex(); if state.is_running { drop(state); panic!("nested calls to panik::run_and_handle_panics are not supported") } state.panics.clear(); state.is_running = true; std::panic::set_hook(Box::new(|panic| { register_panic(panic); })); Self } } impl Drop for GlobalStateGuard { fn drop(&mut self) { let _ = std::panic::take_hook(); let mut state = state_mutex(); state.backtrace_resolution_limit = DEFAULT_BACKTRACE_RESOLUTION_LIMIT; state.is_running = false; #[cfg(feature = "use-slog")] { state.slogger = default_slogger(); } } } impl Default for State { fn default() -> Self { State { panics: Vec::new(), backtrace_resolution_limit: DEFAULT_BACKTRACE_RESOLUTION_LIMIT, is_running: false, #[cfg(feature = "use-slog")] slogger: default_slogger(), } } } #[cfg(feature = "use-slog")] fn default_slogger() -> slog::Logger { use slog::Drain; slog::Logger::root(slog_stdlog::StdLog.fuse(), slog::o!()) }
use backtrace::Backtrace; use std::borrow::Cow; use std::fmt::Debug; use std::panic::{PanicInfo, UnwindSafe}; use std::thread::ThreadId; use std::cmp::Ordering; use std::ops::DerefMut; #[cfg(feature = "use-parking-lot")] use parking_lot::Mutex; #[cfg(not(feature = "use-parking-lot"))] use std::sync::Mutex; const DEFAULT_BACKTRACE_RESOLUTION_LIMIT: usize = 8; lazy_static::lazy_static! { static ref STATE: Mutex<State> = Mutex::new(State::default()); } macro_rules! log_warn { ($state:expr, $($arg:tt)+) => { #[cfg(feature = "use-slog")] slog::warn!(&$state.slogger, $($arg)+); #[cfg(feature = "use-log")] log::warn!($($arg)+); #[cfg(feature = "use-stderr")] eprintln!($($arg)+); } } macro_rules! log_error { ($state:expr, $($arg:tt)+) => { #[cfg(feature = "use-slog")] slog::error!(&$state.slogger, $($arg)+); #[cfg(feature = "use-log")] log::error!($($arg)+); #[cfg(feature = "use-stderr")] eprintln!($($arg)+); } } macro_rules! log_crit { ($state:expr, $($arg:tt)+) => { #[cfg(feature = "use-slog")] slog::crit!(&$state.slogger, $($arg)+); #[cfg(feature = "use-log")] log::error!($($arg)+); #[cfg(feature = "use-stderr")] eprintln!($($arg)+); } } struct State { panics: Vec<Panic>, backtrace_resolution_limit: usize, is_running: bool, #[cfg(feature = "use-slog")] slogger: slog::Logger, } #[derive(Debug, Clone)] pub struct Panic { message: String, thread_id: ThreadId, thread: String, backtrace: Backtrace, backtrace_resolved: bool, } #[derive(Clone)] pub struct Builder { #[cfg(feature = "use-slog")] slogger: Option<slog::Logger>, backtrace_resolution_limit: usize, } struct GlobalStateGuard; impl Builder { pub fn new() -> Self { Builder { #[cfg(feature = "use-slog")] slogger: None, backtrace_resolution_limit: DEFAULT_BACKTRACE_RESOLUTION_LIMIT, } } #[cfg(feature = "use-slog")] pub fn slogger(mut self, slogger: impl Into<slog::Logger>) -> Self { self.slogger = Some(slogger.into()); self } pub fn backtrace_resolution_limit(mut self, n: usize) -> Self { self.backtrace_resolution_limit = n; self } fn apply_settings(&mut self) { let mut state = state_mutex(); #[cfg(feature = "use-slog")] { state.slogger = self.slogger.take().unwrap_or_else(default_slogger); } state.backtrace_resolution_limit = self.backtrace_resolution_limit; } pub fn run_and_handle_panics<R: Debug>( mut self, do_me: impl FnOnce() -> R + UnwindSafe, ) -> Option<R> { self.apply_settings(); run_and_handle_panics(do_me) } pub fn run_and_handle_panics_no_debug<R>( mut self, do_me: impl FnOnce() -> R + UnwindSafe, ) -> Option<R> { self.apply_settings(); run_and_handle_panics_no_debug(do_me) } } impl Default for Builder { fn default() -> Self { Self::new() } } fn register_panic(panic: &PanicInfo) { let (thread, tid) = { let t = std::thread::current(); let name = t.name().unwrap_or("<unnamed>"); (format!("{:?} ({})", t.id(), name), t.id()) }; let message = panic .payload() .downcast_ref::<&str>() .map(|s| Cow::Borrowed(*s)) .unwrap_or_else(|| Cow::from(format!("{}", panic))); let backtrace = Backtrace::new_unresolved(); let mut state = state_mutex(); log_error!(&state, "handling panic on thread {}: '{}'", thread, message); state.panics.push(Panic { message: message.into_owned(), thread_id: tid, thread, backtrace, backtrace_resolved: false, }); } fn state_mutex() -> impl DerefMut<Target = State> { #[cfg(feature = "use-parking-lot")] return STATE.lock(); #[cfg(not(feature = "use-parking-lot"))] STATE.lock().unwrap() } pub fn run_and_handle_panics_no_debug<R>(do_me: impl FnOnce() -> R + UnwindSafe) -> Option<R> { run_and_handle_panics_with_maybe_debug(do_me, |_| Cow::Borrowed("<unprintable>")) } pub fn run_and_handle_panics<R: Debug>(do_me: impl FnOnce() -> R + UnwindSafe) -> Option<R> { run_and_handle_panics_with_maybe_debug(do_me, |res| Cow::Owned(format!("{:?}", res))) } fn run_and_handle_panics_with_maybe_debug<R>( do_me: impl FnOnce() -> R + UnwindSafe, format_swallowed: impl FnOnce(R) -> Cow<'static, str>, ) -> Option<R> { let _guard = GlobalStateGuard::init(); let result = std::panic::catch_unwind(|| do_me()); let mut state = state_mutex(); match (result, state.panics.is_empty()) { (Ok(res), true) => { return Some(res); } (Ok(res), false) => { let swallowed = format_swallowed(res); log_warn!( &state, "panic occurred in another thread, swallowing unpanicked result: {}", swallowed ); } (Err(_), false) => {} (Err(_), true) => unreachable!(), }; log_error!( &state, "{count} threads panicked", count = state.panics.len() ); let backtrace_resolution_limit = state.backtrace_resolution_limit; let mut panics = std::mem::take(&mut state.panics); debug_assert!(!panics.is_empty(), "panics vec should not be empty"); for ( i, Panic { message, thread, ref mut backtrace, backtrace_resolved, .. }, ) in panics.iter_mut().enumerate() {
; if *backtrace_resolved { log_crit!( &state, "panic on thread {:?}: {:?}\n{:?}", thread, message, backtrace ); } else { log_crit!(&state, "panic on thread {:?}: {:?}", thread, message,); } } let empty = std::mem::replace(&mut state.panics, panics); debug_assert!(empty.is_empty()); std::mem::forget(empty); None } pub fn panics() -> Vec<Panic> { let state = state_mutex(); state.panics.clone() } pub fn has_panicked() -> bool { !state_mutex().panics.is_empty() } impl Panic { pub fn is_backtrace_resolved(&self) -> bool { self.backtrace_resolved } pub fn message(&self) -> &str { &self.message } pub fn thread_id(&self) -> ThreadId { self.thread_id } pub fn thread_name(&self) -> &str { &self.thread } pub fn backtrace(&self) -> &Backtrace { &self.backtrace } } impl GlobalStateGuard { fn init() -> Self { let mut state = state_mutex(); if state.is_running { drop(state); panic!("nested calls to panik::run_and_handle_panics are not supported") } state.panics.clear(); state.is_running = true; std::panic::set_hook(Box::new(|panic| { register_panic(panic); })); Self } } impl Drop for GlobalStateGuard { fn drop(&mut self) { let _ = std::panic::take_hook(); let mut state = state_mutex(); state.backtrace_resolution_limit = DEFAULT_BACKTRACE_RESOLUTION_LIMIT; state.is_running = false; #[cfg(feature = "use-slog")] { state.slogger = default_slogger(); } } } impl Default for State { fn default() -> Self { State { panics: Vec::new(), backtrace_resolution_limit: DEFAULT_BACKTRACE_RESOLUTION_LIMIT, is_running: false, #[cfg(feature = "use-slog")] slogger: default_slogger(), } } } #[cfg(feature = "use-slog")] fn default_slogger() -> slog::Logger { use slog::Drain; slog::Logger::root(slog_stdlog::StdLog.fuse(), slog::o!()) }
match i.cmp(&backtrace_resolution_limit) { Ordering::Less => { backtrace.resolve(); *backtrace_resolved = true; } Ordering::Equal => { #[cfg(feature = "use-log")] log::warn!( "handling more than {limit} panics, no longer resolving backtraces", limit = backtrace_resolution_limit ); #[cfg(feature = "use-stderr")] eprintln!( "handling more than {limit} panics, no longer resolving backtraces", limit = backtrace_resolution_limit ); } _ => {} }
if_condition
[ { "content": "pub fn panik_builder() -> panik::Builder {\n\n #[cfg(feature = \"use-log\")]\n\n env_logger::builder()\n\n .is_test(true)\n\n .filter_level(log::LevelFilter::Debug)\n\n .init();\n\n\n\n #[cfg(feature = \"use-slog\")]\n\n {\n\n use slog::{slog_o, Drain};\n\n\...
Rust
2021/src/day19.rs
shrugalic/advent_of_code
8d18a3dbdcf847a667ab553f5441676003b9362a
use std::collections::{HashMap, HashSet, VecDeque}; const INPUT: &str = include_str!("../input/day19.txt"); pub(crate) fn day19_part1() -> usize { System::from(INPUT).beacon_count() } pub(crate) fn day19_part2() -> usize { System::from(INPUT).max_manhattan_distance() } type Coordinate = isize; type Vector = [Coordinate; 3]; #[derive(Debug)] struct System { scanners: Vec<Scanner>, } impl From<&str> for System { fn from(input: &str) -> Self { let scanners = input.trim().split("\n\n").map(Scanner::from).collect(); System { scanners } } } impl System { fn beacon_count(self) -> usize { self.align_beacons().0 } fn max_manhattan_distance(self) -> usize { self.align_beacons().1 } fn align_beacons(mut self) -> (usize, usize) { let mut distances_to_ref = vec![[0, 0, 0]; self.scanners.len()]; let reference = self.scanners.remove(0); let mut unique_beacons: HashSet<Vector> = reference.beacons.iter().cloned().collect(); let mut aligned = VecDeque::new(); aligned.push_back(reference); let mut unaligned: Vec<Scanner> = self.scanners.drain(..).collect(); while let Some(reference) = aligned.pop_front() { let mut still_unaligned = vec![]; while let Some(mut scanner) = unaligned.pop() { if let Some(offset) = scanner.align_with(&reference.beacons) { unique_beacons.extend(scanner.beacons.clone()); distances_to_ref[scanner.id] = offset; aligned.push_back(scanner); } else { still_unaligned.push(scanner); } } unaligned.append(&mut still_unaligned); aligned.push_back(reference); if unaligned.is_empty() { break; } } let distances_between_scanners = Scanner::offsets_between(&distances_to_ref) .into_iter() .map(|(d, _)| d); let max_manhattan_distance = distances_between_scanners .map(|[a, b, c]| (a.abs() + b.abs() + c.abs()) as usize) .max() .unwrap(); (unique_beacons.len(), max_manhattan_distance) } } #[derive(Debug)] struct Scanner { id: usize, beacons: Vec<Vector>, } impl From<&str> for Scanner { fn from(lines: &str) -> Self { let to_position = |line: &str| { let pos: Vec<Coordinate> = line.split(',').map(|n| n.parse().unwrap()).collect(); [pos[0], pos[1], pos[2]] }; let mut lines = lines.trim().lines(); let header = lines.next().unwrap(); let id = header .trim_start_matches("--- scanner ") .trim_end_matches(" ---") .parse() .unwrap(); let beacons: Vec<_> = lines.map(to_position).collect(); Scanner { id, beacons } } } impl Scanner { fn align_with(&mut self, ref_beacons: &[Vector]) -> Option<Vector> { for orientation in Orientation::all() { let mut offset_frequencies: HashMap<Vector, usize> = HashMap::new(); let aligned_beacons = self.aligned_beacons(&orientation); for own_beacon in &aligned_beacons { for ref_beacon in ref_beacons { let offset = Scanner::offset_between(ref_beacon, own_beacon); *offset_frequencies.entry(offset).or_default() += 1; } } if let Some((offset, _)) = offset_frequencies .into_iter() .find(|(_, count)| *count >= 12) { self.beacons = Scanner::translate_beacons(&aligned_beacons, offset); return Some(offset); } } None } fn aligned_beacons(&self, orientation: &Orientation) -> Vec<Vector> { self.beacons .iter() .map(|pos| orientation.align(*pos)) .collect() } fn translate_beacons(beacons: &[Vector], offset: Vector) -> Vec<Vector> { beacons .iter() .map(|pos| [pos[0] + offset[0], pos[1] + offset[1], pos[2] + offset[2]]) .collect() } fn offset_between(a: &Vector, b: &Vector) -> Vector { [a[0] - b[0], a[1] - b[1], a[2] - b[2]] } fn offsets_between(beacons: &[Vector]) -> HashMap<Vector, Vec<Vector>> { let mut distances: HashMap<Vector, Vec<Vector>> = HashMap::new(); for (i, a) in beacons.iter().enumerate().take(beacons.len() - 1) { for b in beacons.iter().skip(i + 1) { let diff = Scanner::offset_between(a, b); let positions = distances.entry(diff).or_default(); positions.push(*a); positions.push(*b); } } assert_eq!(distances.len(), beacons.len() * (beacons.len() - 1) / 2); distances } } #[derive(Debug, Copy, Clone)] struct Orientation { index: [usize; 3], multi: [isize; 3], } impl Orientation { fn new(index: [usize; 3], multi: [isize; 3]) -> Self { Orientation { index, multi } } fn all() -> Vec<Orientation> { vec![ Orientation::new([0, 1, 2], [1, 1, 1]), Orientation::new([0, 2, 1], [1, 1, -1]), Orientation::new([0, 1, 2], [1, -1, -1]), Orientation::new([0, 2, 1], [1, -1, 1]), Orientation::new([0, 2, 1], [-1, 1, 1]), Orientation::new([0, 1, 2], [-1, 1, -1]), Orientation::new([0, 2, 1], [-1, -1, -1]), Orientation::new([0, 1, 2], [-1, -1, 1]), Orientation::new([1, 2, 0], [1, 1, 1]), Orientation::new([1, 0, 2], [1, 1, -1]), Orientation::new([1, 2, 0], [1, -1, -1]), Orientation::new([1, 0, 2], [1, -1, 1]), Orientation::new([1, 0, 2], [-1, 1, 1]), Orientation::new([1, 2, 0], [-1, 1, -1]), Orientation::new([1, 0, 2], [-1, -1, -1]), Orientation::new([1, 2, 0], [-1, -1, 1]), Orientation::new([2, 0, 1], [1, 1, 1]), Orientation::new([2, 1, 0], [1, 1, -1]), Orientation::new([2, 0, 1], [1, -1, -1]), Orientation::new([2, 1, 0], [1, -1, 1]), Orientation::new([2, 1, 0], [-1, 1, 1]), Orientation::new([2, 0, 1], [-1, 1, -1]), Orientation::new([2, 1, 0], [-1, -1, -1]), Orientation::new([2, 0, 1], [-1, -1, 1]), ] } fn align(&self, mut pos: Vector) -> Vector { pos = [pos[self.index[0]], pos[self.index[1]], pos[self.index[2]]]; (0..3).for_each(|i| pos[i] *= self.multi[i]); pos } } #[cfg(test)] mod tests { use super::*; #[test] fn test_orientations() { let pos = [5, 6, -4]; let mut orientations: Vec<_> = Orientation::all() .into_iter() .map(|o| o.align(pos)) .collect(); orientations.sort_unstable(); assert_eq!( 24, orientations .iter() .cloned() .collect::<HashSet<Vector>>() .len() ); assert!(orientations.contains(&[5, 6, -4])); assert!(orientations.contains(&[-5, 4, -6])); assert!(orientations.contains(&[4, 6, 5])); assert!(orientations.contains(&[-4, -6, 5])); assert!(orientations.contains(&[-6, -4, -5])); let expected = vec![ [-6, -5, 4], [-6, -4, -5], [-6, 4, 5], [-6, 5, -4], [-5, -6, -4], [-5, -4, 6], [-5, 4, -6], [-5, 6, 4], [-4, -6, 5], [-4, -5, -6], [-4, 5, 6], [-4, 6, -5], [4, -6, -5], [4, -5, 6], [4, 5, -6], [4, 6, 5], [5, -6, 4], [5, -4, -6], [5, 4, 6], [5, 6, -4], [6, -5, -4], [6, -4, 5], [6, 4, -5], [6, 5, 4], ]; assert_eq!(expected, orientations); } #[test] fn part1_example() { let system = System::from(EXAMPLE); assert_eq!(79, system.beacon_count()); } #[test] fn part1() { assert_eq!(398, day19_part1()); } #[test] fn part2_example() { assert_eq!(3621, System::from(EXAMPLE).max_manhattan_distance()); } #[test] fn part2() { assert_eq!(10965, day19_part2()); } const EXAMPLE: &str = "\ --- scanner 0 --- 404,-588,-901 528,-643,409 -838,591,734 390,-675,-793 -537,-823,-458 -485,-357,347 -345,-311,381 -661,-816,-575 -876,649,763 -618,-824,-621 553,345,-567 474,580,667 -447,-329,318 -584,868,-557 544,-627,-890 564,392,-477 455,729,728 -892,524,684 -689,845,-530 423,-701,434 7,-33,-71 630,319,-379 443,580,662 -789,900,-551 459,-707,401 --- scanner 1 --- 686,422,578 605,423,415 515,917,-361 -336,658,858 95,138,22 -476,619,847 -340,-569,-846 567,-361,727 -460,603,-452 669,-402,600 729,430,532 -500,-761,534 -322,571,750 -466,-666,-811 -429,-592,574 -355,545,-477 703,-491,-529 -328,-685,520 413,935,-424 -391,539,-444 586,-435,557 -364,-763,-893 807,-499,-711 755,-354,-619 553,889,-390 --- scanner 2 --- 649,640,665 682,-795,504 -784,533,-524 -644,584,-595 -588,-843,648 -30,6,44 -674,560,763 500,723,-460 609,671,-379 -555,-800,653 -675,-892,-343 697,-426,-610 578,704,681 493,664,-388 -671,-858,530 -667,343,800 571,-461,-707 -138,-166,112 -889,563,-600 646,-828,498 640,759,510 -630,509,768 -681,-892,-333 673,-379,-804 -742,-814,-386 577,-820,562 --- scanner 3 --- -589,542,597 605,-692,669 -500,565,-823 -660,373,557 -458,-679,-417 -488,449,543 -626,468,-788 338,-750,-386 528,-832,-391 562,-778,733 -938,-730,414 543,643,-506 -524,371,-870 407,773,750 -104,29,83 378,-903,-323 -778,-728,485 426,699,580 -438,-605,-362 -469,-447,-387 509,732,623 647,635,-688 -868,-804,481 614,-800,639 595,780,-596 --- scanner 4 --- 727,592,562 -293,-554,779 441,611,-461 -714,465,-776 -743,427,-804 -660,-479,-426 832,-632,460 927,-485,-438 408,393,-506 466,436,-512 110,16,151 -258,-428,682 -393,719,612 -211,-452,876 808,-476,-593 -575,615,604 -485,667,467 -680,325,-822 -627,-443,-432 872,-547,-609 833,512,582 807,604,487 839,-516,451 891,-625,532 -652,-548,-490 30,-46,-14 "; }
use std::collections::{HashMap, HashSet, VecDeque}; const INPUT: &str = include_str!("../input/day19.txt"); pub(crate) fn day19_part1() -> usize { System::from(INPUT).beacon_count() } pub(crate) fn day19_part2() -> usize { System::from(INPUT).max_manhattan_distance() } type Coordinate = isize; type Vector = [Coordinate; 3]; #[derive(Debug)] struct System { scanners: Vec<Scanner>, } impl From<&str> for System { fn from(input: &str) -> Self { let scanners = input.trim().split("\n\n").map(Scanner::from).collect(); System { scanners } } } impl System { fn beacon_count(self) -> usize { self.align_beacons().0 } fn max_manhattan_distance(self) -> usize { self.align_beacons().1 } fn align_beacons(mut self) -> (usize, usize) { let mut distances_to_ref = vec![[0, 0, 0]; self.scanners.len()]; let reference = self.scanners.remove(0); let mut unique_beacons: HashSet<Vector> = reference.beacons.iter().cloned().collect(); let mut aligned = VecDeque::new(); aligned.push_back(reference); let mut unaligned: Vec<Scanner> = self.scanners.drain(..).collect(); while let Some(reference) = aligned.pop_front() { let mut still_unaligned = vec![]; while let Some(mut scanner) = unaligned.pop() { if let Some(offset) = scanner.align_with(&reference.beacons) { unique_beacons.extend(scanner.beacons.clone()); distances_to_ref[scanner.id] = offset; aligned.push_back(scanner); } else { still_unaligned.push(scanner); } } unaligned.append(&mut still_unaligned); aligned.push_back(reference); if unaligned.is_empty() { break; } } let distances_between_scanners = Scanner::offsets_between(&distances_to_ref) .into_iter() .map(|(d, _)| d); let max_manhattan_distance = distances_between_scanners .map(|[a, b, c]| (a.abs() + b.abs() + c.abs()) as usize) .max() .unwrap(); (unique_beacons.len(), max_manhattan_distance) } } #[derive(Debug)] struct Scanner { id: usize, beacons: Vec<Vector>, } impl From<&str> for Scanner {
} impl Scanner { fn align_with(&mut self, ref_beacons: &[Vector]) -> Option<Vector> { for orientation in Orientation::all() { let mut offset_frequencies: HashMap<Vector, usize> = HashMap::new(); let aligned_beacons = self.aligned_beacons(&orientation); for own_beacon in &aligned_beacons { for ref_beacon in ref_beacons { let offset = Scanner::offset_between(ref_beacon, own_beacon); *offset_frequencies.entry(offset).or_default() += 1; } } if let Some((offset, _)) = offset_frequencies .into_iter() .find(|(_, count)| *count >= 12) { self.beacons = Scanner::translate_beacons(&aligned_beacons, offset); return Some(offset); } } None } fn aligned_beacons(&self, orientation: &Orientation) -> Vec<Vector> { self.beacons .iter() .map(|pos| orientation.align(*pos)) .collect() } fn translate_beacons(beacons: &[Vector], offset: Vector) -> Vec<Vector> { beacons .iter() .map(|pos| [pos[0] + offset[0], pos[1] + offset[1], pos[2] + offset[2]]) .collect() } fn offset_between(a: &Vector, b: &Vector) -> Vector { [a[0] - b[0], a[1] - b[1], a[2] - b[2]] } fn offsets_between(beacons: &[Vector]) -> HashMap<Vector, Vec<Vector>> { let mut distances: HashMap<Vector, Vec<Vector>> = HashMap::new(); for (i, a) in beacons.iter().enumerate().take(beacons.len() - 1) { for b in beacons.iter().skip(i + 1) { let diff = Scanner::offset_between(a, b); let positions = distances.entry(diff).or_default(); positions.push(*a); positions.push(*b); } } assert_eq!(distances.len(), beacons.len() * (beacons.len() - 1) / 2); distances } } #[derive(Debug, Copy, Clone)] struct Orientation { index: [usize; 3], multi: [isize; 3], } impl Orientation { fn new(index: [usize; 3], multi: [isize; 3]) -> Self { Orientation { index, multi } } fn all() -> Vec<Orientation> { vec![ Orientation::new([0, 1, 2], [1, 1, 1]), Orientation::new([0, 2, 1], [1, 1, -1]), Orientation::new([0, 1, 2], [1, -1, -1]), Orientation::new([0, 2, 1], [1, -1, 1]), Orientation::new([0, 2, 1], [-1, 1, 1]), Orientation::new([0, 1, 2], [-1, 1, -1]), Orientation::new([0, 2, 1], [-1, -1, -1]), Orientation::new([0, 1, 2], [-1, -1, 1]), Orientation::new([1, 2, 0], [1, 1, 1]), Orientation::new([1, 0, 2], [1, 1, -1]), Orientation::new([1, 2, 0], [1, -1, -1]), Orientation::new([1, 0, 2], [1, -1, 1]), Orientation::new([1, 0, 2], [-1, 1, 1]), Orientation::new([1, 2, 0], [-1, 1, -1]), Orientation::new([1, 0, 2], [-1, -1, -1]), Orientation::new([1, 2, 0], [-1, -1, 1]), Orientation::new([2, 0, 1], [1, 1, 1]), Orientation::new([2, 1, 0], [1, 1, -1]), Orientation::new([2, 0, 1], [1, -1, -1]), Orientation::new([2, 1, 0], [1, -1, 1]), Orientation::new([2, 1, 0], [-1, 1, 1]), Orientation::new([2, 0, 1], [-1, 1, -1]), Orientation::new([2, 1, 0], [-1, -1, -1]), Orientation::new([2, 0, 1], [-1, -1, 1]), ] } fn align(&self, mut pos: Vector) -> Vector { pos = [pos[self.index[0]], pos[self.index[1]], pos[self.index[2]]]; (0..3).for_each(|i| pos[i] *= self.multi[i]); pos } } #[cfg(test)] mod tests { use super::*; #[test] fn test_orientations() { let pos = [5, 6, -4]; let mut orientations: Vec<_> = Orientation::all() .into_iter() .map(|o| o.align(pos)) .collect(); orientations.sort_unstable(); assert_eq!( 24, orientations .iter() .cloned() .collect::<HashSet<Vector>>() .len() ); assert!(orientations.contains(&[5, 6, -4])); assert!(orientations.contains(&[-5, 4, -6])); assert!(orientations.contains(&[4, 6, 5])); assert!(orientations.contains(&[-4, -6, 5])); assert!(orientations.contains(&[-6, -4, -5])); let expected = vec![ [-6, -5, 4], [-6, -4, -5], [-6, 4, 5], [-6, 5, -4], [-5, -6, -4], [-5, -4, 6], [-5, 4, -6], [-5, 6, 4], [-4, -6, 5], [-4, -5, -6], [-4, 5, 6], [-4, 6, -5], [4, -6, -5], [4, -5, 6], [4, 5, -6], [4, 6, 5], [5, -6, 4], [5, -4, -6], [5, 4, 6], [5, 6, -4], [6, -5, -4], [6, -4, 5], [6, 4, -5], [6, 5, 4], ]; assert_eq!(expected, orientations); } #[test] fn part1_example() { let system = System::from(EXAMPLE); assert_eq!(79, system.beacon_count()); } #[test] fn part1() { assert_eq!(398, day19_part1()); } #[test] fn part2_example() { assert_eq!(3621, System::from(EXAMPLE).max_manhattan_distance()); } #[test] fn part2() { assert_eq!(10965, day19_part2()); } const EXAMPLE: &str = "\ --- scanner 0 --- 404,-588,-901 528,-643,409 -838,591,734 390,-675,-793 -537,-823,-458 -485,-357,347 -345,-311,381 -661,-816,-575 -876,649,763 -618,-824,-621 553,345,-567 474,580,667 -447,-329,318 -584,868,-557 544,-627,-890 564,392,-477 455,729,728 -892,524,684 -689,845,-530 423,-701,434 7,-33,-71 630,319,-379 443,580,662 -789,900,-551 459,-707,401 --- scanner 1 --- 686,422,578 605,423,415 515,917,-361 -336,658,858 95,138,22 -476,619,847 -340,-569,-846 567,-361,727 -460,603,-452 669,-402,600 729,430,532 -500,-761,534 -322,571,750 -466,-666,-811 -429,-592,574 -355,545,-477 703,-491,-529 -328,-685,520 413,935,-424 -391,539,-444 586,-435,557 -364,-763,-893 807,-499,-711 755,-354,-619 553,889,-390 --- scanner 2 --- 649,640,665 682,-795,504 -784,533,-524 -644,584,-595 -588,-843,648 -30,6,44 -674,560,763 500,723,-460 609,671,-379 -555,-800,653 -675,-892,-343 697,-426,-610 578,704,681 493,664,-388 -671,-858,530 -667,343,800 571,-461,-707 -138,-166,112 -889,563,-600 646,-828,498 640,759,510 -630,509,768 -681,-892,-333 673,-379,-804 -742,-814,-386 577,-820,562 --- scanner 3 --- -589,542,597 605,-692,669 -500,565,-823 -660,373,557 -458,-679,-417 -488,449,543 -626,468,-788 338,-750,-386 528,-832,-391 562,-778,733 -938,-730,414 543,643,-506 -524,371,-870 407,773,750 -104,29,83 378,-903,-323 -778,-728,485 426,699,580 -438,-605,-362 -469,-447,-387 509,732,623 647,635,-688 -868,-804,481 614,-800,639 595,780,-596 --- scanner 4 --- 727,592,562 -293,-554,779 441,611,-461 -714,465,-776 -743,427,-804 -660,-479,-426 832,-632,460 927,-485,-438 408,393,-506 466,436,-512 110,16,151 -258,-428,682 -393,719,612 -211,-452,876 808,-476,-593 -575,615,604 -485,667,467 -680,325,-822 -627,-443,-432 872,-547,-609 833,512,582 807,604,487 839,-516,451 891,-625,532 -652,-548,-490 30,-46,-14 "; }
fn from(lines: &str) -> Self { let to_position = |line: &str| { let pos: Vec<Coordinate> = line.split(',').map(|n| n.parse().unwrap()).collect(); [pos[0], pos[1], pos[2]] }; let mut lines = lines.trim().lines(); let header = lines.next().unwrap(); let id = header .trim_start_matches("--- scanner ") .trim_end_matches(" ---") .parse() .unwrap(); let beacons: Vec<_> = lines.map(to_position).collect(); Scanner { id, beacons } }
function_block-full_function
[ { "content": "fn max_distance_to_origin(input: Vec<&str>) -> usize {\n\n curr_and_max_distances_to_origin(input).1\n\n}\n\n\n", "file_path": "2017/src/day11.rs", "rank": 0, "score": 388208.4410849393 }, { "content": "fn sum_of_valid_sector_ids(input: Vec<&str>) -> usize {\n\n input\n\n...
Rust
src/update_status.rs
FutureTVGroup/update-broker
2d8468473b5b72a228a5bdae95f50789e0bbf3b4
use futures::Future; use futures::Stream; use inotify::wrapper::Event; use slog::Logger; use std::ffi::OsString; use std::io::Result; use std::io::{Error, ErrorKind}; use std::ops::Deref; use std::path::Path; use std::process::Command; use std::rc::Rc; use std::time::{SystemTime, UNIX_EPOCH}; use tokio_core::reactor::Handle; use tokio_inotify::AsyncINotify; use tokio_inotify::{IN_CREATE, IN_DELETE}; static VERSION_ZERO: &'static str = "0.0.0"; #[derive(Debug, PartialEq, Eq)] #[allow(dead_code)] pub enum UpdateStatus { Idle, CheckingForUpdate, UpdateAvailable, Downloading, Verifying, Finalizing, UpdatedNeedReboot, ReportingErrorEvent, } impl Deref for UpdateStatus { type Target = str; fn deref(&self) -> &'static str { match *self { UpdateStatus::Idle => &"UPDATE_STATUS_IDLE", UpdateStatus::CheckingForUpdate => &"UPDATE_STATUS_CHECKING_FOR_UPDATE", UpdateStatus::UpdateAvailable => &"UPDATE_STATUS_UPDATE_AVAILABLE", UpdateStatus::Downloading => &"UPDATE_STATUS_DOWNLOADING", UpdateStatus::Verifying => &"UPDATE_STATUS_VERIFYING", UpdateStatus::Finalizing => &"UPDATE_STATUS_FINALIZING", UpdateStatus::UpdatedNeedReboot => &"UPDATE_STATUS_UPDATED_NEED_REBOOT", UpdateStatus::ReportingErrorEvent => &"UPDATE_STATUS_REPORTING_ERROR_EVENT", } } } #[derive(Debug)] pub struct UpdateStatusIndication { pub last_checked_time: SystemTime, pub progress: f64, pub current_operation: UpdateStatus, pub new_version: String, pub new_size: i64, } impl UpdateStatusIndication { fn new(current_operation: UpdateStatus) -> UpdateStatusIndication { UpdateStatusIndication { last_checked_time: SystemTime::now(), progress: 0.0, current_operation: current_operation, new_version: UpdateStatusIndication::version(), new_size: 0, } } fn version() -> String { Command::new("lsb_release") .arg("-r") .arg("-s") .output() .and_then(|o| { String::from_utf8(o.stdout) .map(|mut s| { let len = s.trim_right().len(); s.truncate(len); s }).map_err(|_| Error::new(ErrorKind::InvalidData, "Invalid version string")) }).unwrap_or_else(|_| String::from(VERSION_ZERO)) } pub fn last_checked_time_millis(&self) -> i64 { let duration = self.last_checked_time.duration_since(UNIX_EPOCH).unwrap(); let nanos = duration.subsec_nanos() as u64; return ((1000 * 1000 * 1000 * duration.as_secs() + nanos) / (1000 * 1000)) as i64; } pub fn from_inotify_event(event: &Event) -> Option<UpdateStatusIndication> { let status: Option<UpdateStatus>; if event.is_create() { status = Option::Some(UpdateStatus::UpdatedNeedReboot); } else if event.is_delete() { status = Option::Some(UpdateStatus::Idle); } else { status = Option::None; } status.map(|s| UpdateStatusIndication::new(s)) } pub fn from_path(path: &Path) -> UpdateStatusIndication { let status: UpdateStatus; if path.exists() { status = UpdateStatus::UpdatedNeedReboot; } else { status = UpdateStatus::Idle; } UpdateStatusIndication::new(status) } } #[derive(Debug)] pub struct UpdateStatusNotifier(); pub trait UpdateStatusIndicationConsumer { fn status_changed(&self, status: UpdateStatusIndication) -> (); } impl UpdateStatusNotifier { fn add_watch(inotify: AsyncINotify, path: &Path) -> Result<AsyncINotify> { path.parent().map_or( Err(Error::new( ErrorKind::NotFound, "Invalid path to reboot sentinel file", )), |dir| { inotify .add_watch(dir, IN_CREATE | IN_DELETE) .map(|_| inotify) }, ) } fn get_file_name_os_string(path: &Path) -> Option<OsString> { path.file_name().map(|f| f.to_os_string()) } pub fn new_with_path_and_consumer( handle: &Handle, path: &Path, consumer: Box<UpdateStatusIndicationConsumer>, logger: Rc<Logger>, ) -> Result<Box<Future<Item = (), Error = Error>>> { if let Some(sentinel_file) = UpdateStatusNotifier::get_file_name_os_string(path) { AsyncINotify::init(handle) .and_then(|stream| UpdateStatusNotifier::add_watch(stream, path)) .map(|stream| { stream.filter(move |event: &Event| event.name.as_os_str() == sentinel_file) }).map(|stream| { stream .map(|ev| UpdateStatusIndication::from_inotify_event(&ev)) .map_err(move |e| { warn!(&logger, "Error handling watch. {:?}", e); e }) }).map(|stream| { return Box::new(stream.for_each(move |v| { if let Some(indication) = v { consumer.status_changed(indication) } Ok(()) })) as Box<Future<Item = (), Error = Error>>; }) } else { Err(Error::new( ErrorKind::NotFound, "Invalid path to reboot sentinel file", )) } } }
use futures::Future; use futures::Stream; use inotify::wrapper::Event; use slog::Logger; use std::ffi::OsString; use std::io::Result; use std::io::{Error, ErrorKind}; use std::ops::Deref; use std::path::Path; use std::process::Command; use std::rc::Rc; use std::time::{SystemTime, UNIX_EPOCH}; use tokio_core::reactor::Handle; use tokio_inotify::AsyncINotify; use tokio_inotify::{IN_CREATE, IN_DELETE}; static VERSION_ZERO: &'static str = "0.0.0"; #[derive(Debug, PartialEq, Eq)] #[allow(dead_code)] pub enum UpdateStatus { Idle, CheckingForUpdate, UpdateAvailable, Downloading, Verifying, Finalizing, UpdatedNeedReboot, ReportingErrorEvent, } impl Deref for UpdateStatus { type Target = str; fn deref(&self) -> &'static str { match *self { UpdateStatus::Idle => &"UPDATE_STATUS_IDLE", UpdateStatus::CheckingForUpdate => &"UPDATE_STATUS_CHECKING_FOR_UPDATE", UpdateStatus::UpdateAvailable => &"UPDATE_STATUS_UPDATE_AVAILABLE", UpdateStatus::Downloading => &"UPDATE_STATUS_DOWNLOADING", UpdateStatus::Verifying => &"UPDATE_STATUS_VERIFYING", UpdateStatus::Finalizing => &"UPDATE_STATUS_FINALIZING", UpdateStatus::UpdatedNeedReboot => &"UPDATE_STATUS_UPDATED_NEED_REBOOT", UpdateStatus::ReportingErrorEvent => &"UPDATE_STATUS_REPORTING_ERROR_EVENT", } } } #[derive(Debug)] pub struct UpdateStatusIndication { pub last_checked_time: SystemTime, pub progress: f64, pub current_operation: UpdateStatus, pub new_version: String, pub new_size: i64, } impl UpdateStatusIndication { fn new(current_operation: UpdateStatus) -> UpdateStatusIndication { UpdateStatusIndication { last_checked_time: SystemTime::now(), progress: 0.0, current_operation: current_operation, new_version: UpdateStatusIndication::version(), new_size: 0, } } fn version() -> String { Command::new("lsb_release") .arg("-r") .arg("-s") .output() .and_then(|o| { String::from_utf8(o.stdout) .map(|mut s| { let len = s.trim_right().len(); s.truncate(len); s }).map_err(|_| Error::new(ErrorKind::InvalidData, "Invalid version string")) }).unwrap_or_else(|_| String::from(VERSION_ZERO)) } pub fn last_checked_time_millis(&self) -> i64 { let duration = self.last_checked_time.duration_since(UNIX_EPOCH).unwrap(); let nanos = duration.subsec_nanos() as u64; return ((1000 * 1000 * 1000 * duration.as_secs() + nanos) / (1000 * 1000)) as i64; } pub fn from_inotify_event(event: &Event) -> Option<UpdateStatusIndication> { let status: Option<UpdateStatus>; if event.is_create() { status = Option::Some(UpdateStatus::UpdatedNeedReboot); } else if event.is_delete() { status = Option::Some(UpdateStatus::Idle); } else { status = Option::None; } status.map(|s| UpdateStatusIndication::new(s)) } pub fn from_path(path: &Path) -> UpdateStatusIndication { let status: UpdateStatus; if path.exists() { status = UpdateStatus::UpdatedNeedReboot; } else { status = UpdateStatus::Idle; } UpdateStatusIndication::new(status) } } #[derive(Debug)] pub struct UpdateStatusNotifier(); pub trait UpdateStatusIndicationConsumer { fn status_changed(&self, status: UpdateStatusIndication) -> (); } impl UpdateStatusNotifier { fn add_watch(inotify: AsyncINotify, path: &Path) -> Result<AsyncINotify> { path.parent().map_or( Err(Error::new( ErrorKind::NotFound, "Invalid path to reboot sentinel file", )), |dir| { inotify .add_watch(dir, IN_CREATE | IN_DELETE) .map(|_| inotify) }, ) } fn get_file_name_os_string(path: &Path) -> Option<OsString> { path.file_name().map(|f| f.to_os_string()) } pub fn new_with_path_and_consumer( handle: &Handle, path: &Path, consumer: Box<UpdateStatusIndicationConsumer
cINotify::init(handle) .and_then(|stream| UpdateStatusNotifier::add_watch(stream, path)) .map(|stream| { stream.filter(move |event: &Event| event.name.as_os_str() == sentinel_file) }).map(|stream| { stream .map(|ev| UpdateStatusIndication::from_inotify_event(&ev)) .map_err(move |e| { warn!(&logger, "Error handling watch. {:?}", e); e }) }).map(|stream| { return Box::new(stream.for_each(move |v| { if let Some(indication) = v { consumer.status_changed(indication) } Ok(()) })) as Box<Future<Item = (), Error = Error>>; }) } else { Err(Error::new( ErrorKind::NotFound, "Invalid path to reboot sentinel file", )) } } }
>, logger: Rc<Logger>, ) -> Result<Box<Future<Item = (), Error = Error>>> { if let Some(sentinel_file) = UpdateStatusNotifier::get_file_name_os_string(path) { Asyn
random
[ { "content": "pub fn engine(path: &Path, logger: Rc<Logger>) -> Result<(), IoError> {\n\n let owned_path = path.to_owned();\n\n let connection_r = Connection::get_private(BusType::System);\n\n if connection_r.is_err() {\n\n return connection_r.map(|_| ()).map_err(|e| {\n\n IoError::ne...
Rust
src/pwasm.rs
jakelang/libeci
a4add3d49ec631dbb9c7f65f50655f6ec3ca5f2e
/* * libeci: Ethereum WebAssembly ABI compliance library * * Copyright (c) 2018 Jake Lang * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ use parity_wasm::elements::{External, FunctionType, Internal, Module, Type}; pub fn func_type_by_index(module: &Module, index: usize) -> FunctionType { let function_section = module .function_section() .expect("No function section found"); let type_section = module.type_section().expect("No type section found"); let import_section_len: usize = match module.import_section() { Some(import) => import .entries() .iter() .filter(|entry| match entry.external() { &External::Function(_) => true, _ => false, }) .count(), None => 0, }; let function_index_in_section = index - import_section_len; let func_type_ref: usize = function_section.entries()[function_index_in_section].type_ref() as usize; match type_section.types()[func_type_ref] { Type::Function(ref func_type) => func_type.clone(), } } pub fn imported_func_type_by_index(module: &Module, index: usize) -> FunctionType { let import_section = module.import_section().expect("No function section found"); let type_section = module.type_section().expect("No type section found"); let func_type_ref: usize = match import_section.entries()[index].external() { &External::Function(idx) => idx as usize, _ => usize::max_value(), }; match type_section.types()[func_type_ref] { Type::Function(ref func_type) => func_type.clone(), } } pub fn resolve_export_by_name(module: &Module, name: &str) -> Option<(u32, Internal)> { if !has_export_section(module) { None } else { let idx: Option<(u32, Internal)> = match module .export_section() .unwrap() .entries() .iter() .find(|export| if export.field() == name { true } else { false }) { Some(export) => match *export.internal() { Internal::Function(index) => Some((index, Internal::Function(index))), Internal::Memory(index) => Some((index, Internal::Memory(index))), Internal::Global(index) => Some((index, Internal::Global(index))), Internal::Table(index) => Some((index, Internal::Table(index))), }, None => None, }; idx } } pub fn get_imports(module: &Module) -> Option<Vec<(&str, &str)>> { if !has_import_section(module) { return None; } else { let imports_list: Option<Vec<(&str, &str)>> = Some( module .import_section() .unwrap() .entries() .iter() .map(|x| (x.module(), x.field())) .collect(), ); imports_list } } pub fn has_export_section(module: &Module) -> bool { match module.export_section() { Some(_thing) => true, None => false, } } pub fn has_import_section(module: &Module) -> bool { match module.import_section() { Some(_thing) => true, None => false, } }
/* * libeci: Ethereum WebAssembly ABI compliance library * * Copyright (c) 2018 Jake Lang * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ use parity_wasm::elements::{External, FunctionType, Internal, Module, Type}; pub fn func_type_by_index(module: &Module, index: usize) -> FunctionType { let function_section = module .function_section() .expect("No function section found"); let type_section = module.type_section().expect("No type section found"); let import_section_len: usize = match module.import_section() { Some(import) => import .entries() .iter() .filter(|entry| match entry.external() { &External::Function(_) => true, _ => false, }) .count(), None => 0, }; let function_index_in_section = index - import_section_len; let func_type_ref: usize = function_section.entries()[function_index_in_section].type_ref() as usize; match type_section.types()[func_type_ref] { Type::Function(ref func_type) => func_type.clone(), } } pub fn imported_func_type_by_index(module: &Module, index: usize) -> FunctionType { let import_section = module.import_section().expect("No function section found"); let type_section = module.type_section().expect("No type section found"); let func_type_ref: usize = match import_section.entries()[index].external() { &External::Function(idx) => idx as usize, _ => usize::max_value(), }; match type_section.types()[func_type_ref] { Type::Function(ref func_type) => func_type.clone(), } }
pub fn get_imports(module: &Module) -> Option<Vec<(&str, &str)>> { if !has_import_section(module) { return None; } else { let imports_list: Option<Vec<(&str, &str)>> = Some( module .import_section() .unwrap() .entries() .iter() .map(|x| (x.module(), x.field())) .collect(), ); imports_list } } pub fn has_export_section(module: &Module) -> bool { match module.export_section() { Some(_thing) => true, None => false, } } pub fn has_import_section(module: &Module) -> bool { match module.import_section() { Some(_thing) => true, None => false, } }
pub fn resolve_export_by_name(module: &Module, name: &str) -> Option<(u32, Internal)> { if !has_export_section(module) { None } else { let idx: Option<(u32, Internal)> = match module .export_section() .unwrap() .entries() .iter() .find(|export| if export.field() == name { true } else { false }) { Some(export) => match *export.internal() { Internal::Function(index) => Some((index, Internal::Function(index))), Internal::Memory(index) => Some((index, Internal::Memory(index))), Internal::Global(index) => Some((index, Internal::Global(index))), Internal::Table(index) => Some((index, Internal::Table(index))), }, None => None, }; idx } }
function_block-full_function
[ { "content": "/// Utility function checking that a module has an exported function with a given signature.\n\npub fn has_func_export(module: &Module, name: &str, sig: FunctionType) -> CheckStatus {\n\n match resolve_export_by_name(module, name) {\n\n Some((index, reference)) => if reference == Interna...
Rust
contracts/farms/spectrum_pylon_farm/src/compound.rs
spectrumprotocol/contract
eee411acc13ed999a9718c096aef93b586941c02
use cosmwasm_std::{attr, to_binary, Attribute, CanonicalAddr, Coin, CosmosMsg, DepsMut, Env, MessageInfo, Response, StdError, StdResult, Uint128, WasmMsg, QueryRequest, WasmQuery}; use crate::{ bond::deposit_farm_share, state::{read_config, state_store}, }; use crate::querier::query_pylon_reward_info; use cw20::Cw20ExecuteMsg; use crate::state::{pool_info_read, pool_info_store, read_state, Config, PoolInfo}; use pylon_token::staking::{ Cw20HookMsg as PylonStakingCw20HookMsg, ExecuteMsg as PylonStakingExecuteMsg, }; use spectrum_protocol::gov::{ExecuteMsg as GovExecuteMsg}; use spectrum_protocol::pylon_farm::ExecuteMsg; use terraswap::asset::{Asset, AssetInfo}; use terraswap::pair::{Cw20HookMsg as TerraswapCw20HookMsg, ExecuteMsg as TerraswapExecuteMsg, QueryMsg as TerraswapQueryMsg, PoolResponse}; use terraswap::querier::{query_token_balance, simulate}; use spectrum_protocol::farm_helper::{compute_provide_after_swap, deduct_tax}; use moneymarket::market::{ExecuteMsg as MoneyMarketExecuteMsg}; pub fn compound(deps: DepsMut, env: Env, info: MessageInfo) -> StdResult<Response> { let config = read_config(deps.storage)?; if config.controller != deps.api.addr_canonicalize(info.sender.as_str())? { return Err(StdError::generic_err("unauthorized")); } let pair_contract = deps.api.addr_humanize(&config.pair_contract)?; let pylon_staking = deps.api.addr_humanize(&config.pylon_staking)?; let pylon_token = deps.api.addr_humanize(&config.pylon_token)?; let pylon_reward_info = query_pylon_reward_info( deps.as_ref(), &config.pylon_staking, &env.contract.address, Some(env.block.height), )?; let mut total_mine_swap_amount = Uint128::zero(); let mut total_mine_stake_amount = Uint128::zero(); let mut total_mine_commission = Uint128::zero(); let mut compound_amount = Uint128::zero(); let mut attributes: Vec<Attribute> = vec![]; let community_fee = config.community_fee; let platform_fee = config.platform_fee; let controller_fee = config.controller_fee; let total_fee = community_fee + platform_fee + controller_fee; let mut pool_info = pool_info_read(deps.storage).load(config.pylon_token.as_slice())?; let reward = pylon_reward_info.pending_reward; if !reward.is_zero() && !pylon_reward_info.bond_amount.is_zero() { let commission = reward * total_fee; let pylon_amount = reward.checked_sub(commission)?; total_mine_commission += commission; total_mine_swap_amount += commission; let auto_bond_amount = pylon_reward_info .bond_amount .checked_sub(pool_info.total_stake_bond_amount)?; compound_amount = pylon_amount.multiply_ratio(auto_bond_amount, pylon_reward_info.bond_amount); let stake_amount = pylon_amount.checked_sub(compound_amount)?; attributes.push(attr("commission", commission)); attributes.push(attr("compound_amount", compound_amount)); attributes.push(attr("stake_amount", stake_amount)); total_mine_stake_amount += stake_amount; } let mut state = read_state(deps.storage)?; let reinvest_allowance = query_token_balance(&deps.querier, pylon_token.clone(), env.contract.address.clone())? .checked_sub(state.total_farm_amount)?; deposit_farm_share( &mut state, &mut pool_info, total_mine_stake_amount, )?; state_store(deps.storage).save(&state)?; pool_info_store(deps.storage).save(config.pylon_token.as_slice(), &pool_info)?; let reinvest_amount = reinvest_allowance + compound_amount; let swap_amount = reinvest_amount.multiply_ratio(1u128, 2u128); total_mine_swap_amount += swap_amount; let mine = Asset { info: AssetInfo::Token { contract_addr: pylon_token.to_string(), }, amount: total_mine_swap_amount, }; let mine_swap_rate = simulate( &deps.querier, pair_contract.clone(), &mine, )?; let total_ust_return_amount = deduct_tax(&deps.querier, mine_swap_rate.return_amount, config.base_denom.clone())?; attributes.push(attr("total_ust_return_amount", total_ust_return_amount)); let total_ust_commission_amount = if total_mine_swap_amount != Uint128::zero() { total_ust_return_amount.multiply_ratio(total_mine_commission, total_mine_swap_amount) } else { Uint128::zero() }; let total_ust_reinvest_amount = total_ust_return_amount.checked_sub(total_ust_commission_amount)?; let net_reinvest_ust = deduct_tax( &deps.querier, total_ust_reinvest_amount, config.base_denom.clone(), )?; let pool: PoolResponse = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr: pair_contract.to_string(), msg: to_binary(&TerraswapQueryMsg::Pool {})?, }))?; let provide_mine = compute_provide_after_swap( &pool, &mine, mine_swap_rate.return_amount, net_reinvest_ust )?; let mut messages: Vec<CosmosMsg> = vec![]; let withdraw_all_mine: CosmosMsg = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: pylon_staking.to_string(), funds: vec![], msg: to_binary(&PylonStakingExecuteMsg::Withdraw {})?, }); messages.push(withdraw_all_mine); if !total_mine_swap_amount.is_zero() { let swap_mine: CosmosMsg = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: pylon_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::Send { contract: pair_contract.to_string(), amount: total_mine_swap_amount, msg: to_binary(&TerraswapCw20HookMsg::Swap { max_spread: None, belief_price: None, to: None, })?, })?, funds: vec![], }); messages.push(swap_mine); } if !total_ust_commission_amount.is_zero() { let net_commission_amount = deduct_tax(&deps.querier, total_ust_commission_amount, config.base_denom.clone())?; let mut state = read_state(deps.storage)?; state.earning += net_commission_amount; state_store(deps.storage).save(&state)?; attributes.push(attr("net_commission", net_commission_amount)); messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps.api.addr_humanize(&config.anchor_market)?.to_string(), msg: to_binary(&MoneyMarketExecuteMsg::DepositStable {})?, funds: vec![Coin { denom: config.base_denom.clone(), amount: net_commission_amount, }], })); messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps.api.addr_humanize(&config.spectrum_gov)?.to_string(), msg: to_binary(&GovExecuteMsg::mint {})?, funds: vec![], })); messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: env.contract.address.to_string(), msg: to_binary(&ExecuteMsg::send_fee {})?, funds: vec![], })); } if !provide_mine.is_zero() { let increase_allowance = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: pylon_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::IncreaseAllowance { spender: pair_contract.to_string(), amount: provide_mine, expires: None, })?, funds: vec![], }); messages.push(increase_allowance); let provide_liquidity = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: pair_contract.to_string(), msg: to_binary(&TerraswapExecuteMsg::ProvideLiquidity { assets: [ Asset { info: AssetInfo::Token { contract_addr: pylon_token.to_string(), }, amount: provide_mine, }, Asset { info: AssetInfo::NativeToken { denom: config.base_denom.clone(), }, amount: net_reinvest_ust, }, ], slippage_tolerance: None, receiver: None, })?, funds: vec![Coin { denom: config.base_denom, amount: net_reinvest_ust, }], }); messages.push(provide_liquidity); let stake = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: env.contract.address.to_string(), msg: to_binary(&ExecuteMsg::stake { asset_token: pylon_token.to_string(), })?, funds: vec![], }); messages.push(stake); } attributes.push(attr("action", "compound")); attributes.push(attr("asset_token", pylon_token)); attributes.push(attr("reinvest_amount", reinvest_amount)); attributes.push(attr("provide_token_amount", provide_mine)); attributes.push(attr("provide_ust_amount", net_reinvest_ust)); Ok(Response::new() .add_messages(messages) .add_attributes(attributes)) } pub fn stake( deps: DepsMut, env: Env, info: MessageInfo, asset_token: String, ) -> StdResult<Response> { if info.sender != env.contract.address { return Err(StdError::generic_err("unauthorized")); } let config: Config = read_config(deps.storage)?; let pylon_staking = deps.api.addr_humanize(&config.pylon_staking)?; let asset_token_raw: CanonicalAddr = deps.api.addr_canonicalize(&asset_token)?; let pool_info: PoolInfo = pool_info_read(deps.storage).load(asset_token_raw.as_slice())?; let staking_token = deps.api.addr_humanize(&pool_info.staking_token)?; let amount = query_token_balance(&deps.querier, staking_token.clone(), env.contract.address)?; Ok(Response::new() .add_messages(vec![CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: staking_token.to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Send { contract: pylon_staking.to_string(), amount, msg: to_binary(&PylonStakingCw20HookMsg::Bond {})?, })?, })]) .add_attributes(vec![ attr("action", "stake"), attr("asset_token", asset_token), attr("staking_token", staking_token), attr("amount", amount), ])) } pub fn send_fee( deps: DepsMut, env: Env, info: MessageInfo, ) -> StdResult<Response> { if info.sender != env.contract.address { return Err(StdError::generic_err("unauthorized")); } let config = read_config(deps.storage)?; let aust_token = deps.api.addr_humanize(&config.aust_token)?; let spectrum_gov = deps.api.addr_humanize(&config.spectrum_gov)?; let aust_balance = query_token_balance(&deps.querier, aust_token.clone(), env.contract.address)?; let mut messages: Vec<CosmosMsg> = vec![]; let thousand = Uint128::from(1000u64); let total_fee = config.community_fee + config.controller_fee + config.platform_fee; let community_amount = aust_balance.multiply_ratio(thousand * config.community_fee, thousand * total_fee); if !community_amount.is_zero() { let transfer_community_fee = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: aust_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient: spectrum_gov.to_string(), amount: community_amount, })?, funds: vec![], }); messages.push(transfer_community_fee); } let platform_amount = aust_balance.multiply_ratio(thousand * config.platform_fee, thousand * total_fee); if !platform_amount.is_zero() { let stake_platform_fee = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: aust_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient: deps.api.addr_humanize(&config.platform)?.to_string(), amount: platform_amount, })?, funds: vec![], }); messages.push(stake_platform_fee); } let controller_amount = aust_balance.checked_sub(community_amount + platform_amount)?; if !controller_amount.is_zero() { let stake_controller_fee = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: aust_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient: deps.api.addr_humanize(&config.controller)?.to_string(), amount: controller_amount, })?, funds: vec![], }); messages.push(stake_controller_fee); } Ok(Response::new() .add_messages(messages)) }
use cosmwasm_std::{attr, to_binary, Attribute, CanonicalAddr, Coin, CosmosMsg, DepsMut, Env, MessageInfo, Response, StdError, StdResult, Uint128, WasmMsg, QueryRequest, WasmQuery}; use crate::{ bond::deposit_farm_share, state::{read_config, state_store}, }; use crate::querier::query_pylon_reward_info; use cw20::Cw20ExecuteMsg; use crate::state::{pool_info_read, pool_info_store, read_state, Config, PoolInfo}; use pylon_token::staking::{ Cw20HookMsg as PylonStakingCw20HookMsg, ExecuteMsg as PylonStakingExecuteMsg, }; use spectrum_protocol::gov::{ExecuteMsg as GovExecuteMsg}; use spectrum_protocol::pylon_farm::ExecuteMsg; use terraswap::asset::{Asset, AssetInfo}; use terraswap::pair::{Cw20HookMsg as TerraswapCw20HookMsg, ExecuteMsg as TerraswapExecuteMsg, QueryMsg as TerraswapQueryMsg, PoolResponse}; use terraswap::querier::{query_token_balance, simulate}; use spectrum_protocol::farm_helper::{compute_provide_after_swap, deduct_tax}; use moneymarket::market::{ExecuteMsg as MoneyMarketExecuteMsg}; pub fn compound(deps: DepsMut, env: Env, info: MessageInfo) -> StdResult<Response> { let config = read_config(deps.storage)?; if config.controller != deps.api.addr_canonicalize(info.sender.as_str())? { return Err(StdError::generic_err("unauthorized")); } let pair_contract = deps.api.addr_humanize(&config.pair_contract)?; let pylon_staking = deps.api.addr_humanize(&config.pylon_staking)?; let pylon_token = deps.api.addr_humanize(&config.pylon_token)?; let pylon_reward_info = query_pylon_reward_info( deps.as_ref(), &config.pylon_staking, &env.contract.address, Some(env.block.height), )?; let mut total_mine_swap_amount = Uint128::zero(); let mut total_mine_stake_amount = Uint128::zero(); let mut total_mine_commission = Uint128::zero(); let mut compound_amount = Uint128::zero(); let mut attributes: Vec<Attribute> = vec![]; let community_fee = config.community_fee; let platform_fee = config.platform_fee; let controller_fee = config.controller_fee; let total_fee = community_fee + platform_fee + controller_fee; let mut pool_info = pool_info_read(deps.storage).load(config.pylon_token.as_slice())?; let reward = pylon_reward_info.pending_reward; if !reward.is_zero() && !pylon_reward_info.bond_amount.is_zero() { let commission = reward * total_fee; let pylon_amount = reward.checked_sub(commission)?; total_mine_commission += commission; total_mine_swap_amount += commission; let auto_bond_amount = pylon_reward_info .bond_amount .checked_sub(pool_info.total_stake_bond_amount)?; compound_amount = pylon_amount.multiply_ratio(auto_bond_amount, pylon_reward_info.bond_amount); let stake_amount = pylon_amount.checked_sub(compound_amount)?; attributes.push(attr("commission", commission)); attributes.push(attr("compound_amount", compound_amount)); attributes.push(attr("stake_amount", stake_amount)); total_mine_stake_amount += stake_amount; } let mut state = read_state(deps.storage)?; let reinvest_allowance = query_token_balance(&deps.querier, pylon_token.clone(), env.contract.address.clone())? .checked_sub(state.total_farm_amount)?; deposit_farm_share( &mut state, &mut pool_info, total_mine_stake_amount, )?; state_store(deps.storage).save(&state)?; pool_info_store(deps.storage).save(config.pylon_token.as_slice(), &pool_info)?; let reinvest_amount = reinvest_allowance + compound_amount; let swap_amount = reinvest_amount.multiply_ratio(1u128, 2u128); total_mine_swap_amount += swap_amount; let mine = Asset { info: AssetInfo::Token { contract_addr: pylon_token.to_string(), }, amount: total_mine_swap_amount, }; let mine_swap_rate = simulate( &deps.querier, pair_contract.clone(), &mine, )?; let total_ust_return_amount = deduct_tax(&deps.querier, mine_swap_rate.return_amount, config.base_denom.clone())?; attributes.push(attr("total_ust_return_amount", total_ust_return_amount)); let total_ust_commission_amount = if total_mine_swap_amount != Uint128::zero() { total_ust_return_amount.multiply_ratio(total_mine_commission, total_mine_swap_amount) } else { Uint128::zero() }; let total_ust_reinvest_amount = total_ust_return_amount.checked_sub(total_ust_commission_amount)?; let net_reinvest_ust = deduct_tax( &deps.querier, total_ust_reinvest_amount, config.base_denom.clone(), )?; let pool: PoolResponse = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr: pair_contract.to_string(), msg: to_binary(&TerraswapQueryMsg::Pool {})?, }))?; let provide_mine = compute_provide_after_swap( &pool, &mine, mine_swap_rate.return_amount, net_reinvest_ust )?; let mut messages: Vec<CosmosMsg> = vec![]; let withdraw_all_mine: CosmosMsg = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: pylon_staking.to_string(), funds: vec![], msg: to_binary(&PylonStakingExecuteMsg::Withdraw {})?, }); messages.push(withdraw_all_mine); if !total_mine_swap_amount.is_zero() { let swap_mine: CosmosMsg = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: pylon_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::Send { contract: pair_contract.to_string(), amount: total_mine_swap_amount, msg: to_binary(&TerraswapCw20HookMsg::Swap { max_spread: None, belief_price: None, to: None, })?, })?, funds: vec![], }); messages.push(swap_mine); } if !total_ust_commission_amount.is_zero() { let net_commission_amount = deduct_tax(&deps.querier, total_ust_commission_amount, config.base_denom.clone())?; let mut state = read_state(deps.storage)?; state.earning += net_commission_amount; state
], slippage_tolerance: None, receiver: None, })?, funds: vec![Coin { denom: config.base_denom, amount: net_reinvest_ust, }], }); messages.push(provide_liquidity); let stake = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: env.contract.address.to_string(), msg: to_binary(&ExecuteMsg::stake { asset_token: pylon_token.to_string(), })?, funds: vec![], }); messages.push(stake); } attributes.push(attr("action", "compound")); attributes.push(attr("asset_token", pylon_token)); attributes.push(attr("reinvest_amount", reinvest_amount)); attributes.push(attr("provide_token_amount", provide_mine)); attributes.push(attr("provide_ust_amount", net_reinvest_ust)); Ok(Response::new() .add_messages(messages) .add_attributes(attributes)) } pub fn stake( deps: DepsMut, env: Env, info: MessageInfo, asset_token: String, ) -> StdResult<Response> { if info.sender != env.contract.address { return Err(StdError::generic_err("unauthorized")); } let config: Config = read_config(deps.storage)?; let pylon_staking = deps.api.addr_humanize(&config.pylon_staking)?; let asset_token_raw: CanonicalAddr = deps.api.addr_canonicalize(&asset_token)?; let pool_info: PoolInfo = pool_info_read(deps.storage).load(asset_token_raw.as_slice())?; let staking_token = deps.api.addr_humanize(&pool_info.staking_token)?; let amount = query_token_balance(&deps.querier, staking_token.clone(), env.contract.address)?; Ok(Response::new() .add_messages(vec![CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: staking_token.to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Send { contract: pylon_staking.to_string(), amount, msg: to_binary(&PylonStakingCw20HookMsg::Bond {})?, })?, })]) .add_attributes(vec![ attr("action", "stake"), attr("asset_token", asset_token), attr("staking_token", staking_token), attr("amount", amount), ])) } pub fn send_fee( deps: DepsMut, env: Env, info: MessageInfo, ) -> StdResult<Response> { if info.sender != env.contract.address { return Err(StdError::generic_err("unauthorized")); } let config = read_config(deps.storage)?; let aust_token = deps.api.addr_humanize(&config.aust_token)?; let spectrum_gov = deps.api.addr_humanize(&config.spectrum_gov)?; let aust_balance = query_token_balance(&deps.querier, aust_token.clone(), env.contract.address)?; let mut messages: Vec<CosmosMsg> = vec![]; let thousand = Uint128::from(1000u64); let total_fee = config.community_fee + config.controller_fee + config.platform_fee; let community_amount = aust_balance.multiply_ratio(thousand * config.community_fee, thousand * total_fee); if !community_amount.is_zero() { let transfer_community_fee = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: aust_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient: spectrum_gov.to_string(), amount: community_amount, })?, funds: vec![], }); messages.push(transfer_community_fee); } let platform_amount = aust_balance.multiply_ratio(thousand * config.platform_fee, thousand * total_fee); if !platform_amount.is_zero() { let stake_platform_fee = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: aust_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient: deps.api.addr_humanize(&config.platform)?.to_string(), amount: platform_amount, })?, funds: vec![], }); messages.push(stake_platform_fee); } let controller_amount = aust_balance.checked_sub(community_amount + platform_amount)?; if !controller_amount.is_zero() { let stake_controller_fee = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: aust_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient: deps.api.addr_humanize(&config.controller)?.to_string(), amount: controller_amount, })?, funds: vec![], }); messages.push(stake_controller_fee); } Ok(Response::new() .add_messages(messages)) }
_store(deps.storage).save(&state)?; attributes.push(attr("net_commission", net_commission_amount)); messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps.api.addr_humanize(&config.anchor_market)?.to_string(), msg: to_binary(&MoneyMarketExecuteMsg::DepositStable {})?, funds: vec![Coin { denom: config.base_denom.clone(), amount: net_commission_amount, }], })); messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps.api.addr_humanize(&config.spectrum_gov)?.to_string(), msg: to_binary(&GovExecuteMsg::mint {})?, funds: vec![], })); messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: env.contract.address.to_string(), msg: to_binary(&ExecuteMsg::send_fee {})?, funds: vec![], })); } if !provide_mine.is_zero() { let increase_allowance = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: pylon_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::IncreaseAllowance { spender: pair_contract.to_string(), amount: provide_mine, expires: None, })?, funds: vec![], }); messages.push(increase_allowance); let provide_liquidity = CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: pair_contract.to_string(), msg: to_binary(&TerraswapExecuteMsg::ProvideLiquidity { assets: [ Asset { info: AssetInfo::Token { contract_addr: pylon_token.to_string(), }, amount: provide_mine, }, Asset { info: AssetInfo::NativeToken { denom: config.base_denom.clone(), }, amount: net_reinvest_ust, },
random
[ { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> StdResult<Response> {\n\n match msg {\n\n ExecuteMsg::zap_to_bond {\n\n contract,\n\n provide_asset,\n\n swap_operations...
Rust
query-engine/core/src/metrics/formatters.rs
prisma-korea/prisma-engines
99ac5a5c95ba2f5308d84fc30a7110f606182d92
use super::common::{Histogram, Metric, MetricValue, Snapshot}; use metrics_exporter_prometheus::formatting::{ sanitize_description, sanitize_label_key, sanitize_label_value, write_help_line, write_metric_line, write_type_line, }; use serde_json::Value; use std::collections::HashMap; fn create_label_string(labels: &HashMap<String, String>) -> Vec<String> { let mut label_string = labels .iter() .map(|(k, v)| format!("{}=\"{}\"", sanitize_label_key(k), sanitize_label_value(v))) .collect::<Vec<String>>(); label_string.sort(); label_string } pub(crate) fn metrics_to_json(snapshot: Snapshot) -> Value { let Snapshot { counters, histograms, gauges, } = snapshot; let mut normalised_histograms = Vec::new(); for histogram in histograms { if let MetricValue::Histogram(histogram_value) = histogram.value { let mut prev = 0; let buckets = histogram_value .buckets .iter() .cloned() .map(|(le, count)| { let new_count = count - prev; prev = count; (le, new_count) }) .collect(); let new_histogram = Histogram { buckets, sum: histogram_value.sum, count: histogram_value.count, }; normalised_histograms.push(Metric { key: histogram.key.clone(), labels: histogram.labels.clone(), description: histogram.description.clone(), value: MetricValue::Histogram(new_histogram), }); } } let snapshot = Snapshot { counters, histograms: normalised_histograms, gauges, }; serde_json::to_value(snapshot).unwrap() } pub(crate) fn metrics_to_prometheus(snapshot: Snapshot) -> String { let Snapshot { counters, histograms, gauges, } = snapshot; let mut output = String::new(); for counter in counters { let desc = sanitize_description(counter.description.as_str()); write_help_line(&mut output, counter.key.as_str(), desc.as_str()); write_type_line(&mut output, counter.key.as_str(), "counter"); let labels = create_label_string(&counter.labels); if let MetricValue::Counter(value) = counter.value { write_metric_line::<&str, u64>(&mut output, &counter.key.as_str(), None, &labels, None, value); } output.push('\n'); } for gauge in gauges { let desc = sanitize_description(gauge.description.as_str()); write_help_line(&mut output, gauge.key.as_str(), desc.as_str()); write_type_line(&mut output, gauge.key.as_str(), "gauge"); let labels = create_label_string(&gauge.labels); if let MetricValue::Gauge(value) = gauge.value { write_metric_line::<&str, f64>(&mut output, &gauge.key.as_str(), None, &labels, None, value); } output.push('\n'); } for histogram in histograms { let desc = sanitize_description(histogram.description.as_str()); write_help_line(&mut output, histogram.key.as_str(), desc.as_str()); write_type_line(&mut output, histogram.key.as_str(), "histogram"); let labels = create_label_string(&histogram.labels); if let MetricValue::Histogram(histogram_values) = histogram.value { for (le, count) in histogram_values.buckets { write_metric_line( &mut output, histogram.key.as_str(), Some("bucket"), &labels, Some(("le", le)), count, ); } write_metric_line( &mut output, histogram.key.as_str(), Some("bucket"), &labels, Some(("le", "+Inf")), histogram_values.count, ); write_metric_line::<&str, f64>( &mut output, histogram.key.as_str(), Some("sum"), &labels, None, histogram_values.sum, ); write_metric_line::<&str, u64>( &mut output, histogram.key.as_str(), Some("count"), &labels, None, histogram_values.count, ); } output.push('\n'); } output }
use super::common::{Histogram, Metric, MetricValue, Snapshot}; use metrics_exporter_prometheus::formatting::{ sanitize_description, sanitize_label_key, sanitize_label_value, write_help_line, write_metric_line, write_type_line, }; use serde_json::Value; use std::collections::HashMap; fn create_label_string(labels: &HashMap<String, String>) -> Vec<String> { let mut label_string = labels .iter() .map(|(k, v)| format!("{}=\"{}\"", sanitize_label_key(k), sanitize_label_value(v))) .collect::<Vec<String>>(); label_string.sort(); label_string } pub(crate) fn metrics_to_json(snapshot: Snapshot) -> Value { let Snapshot { counters, histograms, gauges, } = snapshot; let mut normalised_histograms = Vec::new(); for histogram in histograms { if let MetricValue::Histogram(histogram_value) = histogram.value { let mut prev = 0; let buckets = histogram_value .buckets .iter() .cloned() .map(|(le, count)| { let new_count = count - prev; prev = count; (le, new_count) }) .collect(); let new_histogram = His
pub(crate) fn metrics_to_prometheus(snapshot: Snapshot) -> String { let Snapshot { counters, histograms, gauges, } = snapshot; let mut output = String::new(); for counter in counters { let desc = sanitize_description(counter.description.as_str()); write_help_line(&mut output, counter.key.as_str(), desc.as_str()); write_type_line(&mut output, counter.key.as_str(), "counter"); let labels = create_label_string(&counter.labels); if let MetricValue::Counter(value) = counter.value { write_metric_line::<&str, u64>(&mut output, &counter.key.as_str(), None, &labels, None, value); } output.push('\n'); } for gauge in gauges { let desc = sanitize_description(gauge.description.as_str()); write_help_line(&mut output, gauge.key.as_str(), desc.as_str()); write_type_line(&mut output, gauge.key.as_str(), "gauge"); let labels = create_label_string(&gauge.labels); if let MetricValue::Gauge(value) = gauge.value { write_metric_line::<&str, f64>(&mut output, &gauge.key.as_str(), None, &labels, None, value); } output.push('\n'); } for histogram in histograms { let desc = sanitize_description(histogram.description.as_str()); write_help_line(&mut output, histogram.key.as_str(), desc.as_str()); write_type_line(&mut output, histogram.key.as_str(), "histogram"); let labels = create_label_string(&histogram.labels); if let MetricValue::Histogram(histogram_values) = histogram.value { for (le, count) in histogram_values.buckets { write_metric_line( &mut output, histogram.key.as_str(), Some("bucket"), &labels, Some(("le", le)), count, ); } write_metric_line( &mut output, histogram.key.as_str(), Some("bucket"), &labels, Some(("le", "+Inf")), histogram_values.count, ); write_metric_line::<&str, f64>( &mut output, histogram.key.as_str(), Some("sum"), &labels, None, histogram_values.sum, ); write_metric_line::<&str, u64>( &mut output, histogram.key.as_str(), Some("count"), &labels, None, histogram_values.count, ); } output.push('\n'); } output }
togram { buckets, sum: histogram_value.sum, count: histogram_value.count, }; normalised_histograms.push(Metric { key: histogram.key.clone(), labels: histogram.labels.clone(), description: histogram.description.clone(), value: MetricValue::Histogram(new_histogram), }); } } let snapshot = Snapshot { counters, histograms: normalised_histograms, gauges, }; serde_json::to_value(snapshot).unwrap() }
function_block-function_prefixed
[ { "content": "// Todo: Sanitizing might need to be adjusted to also change the fields in the RelationInfo\n\nfn sanitize_models(ctx: &mut Context) -> HashMap<String, (String, Option<String>)> {\n\n let mut enum_renames = HashMap::new();\n\n let sql_family = ctx.sql_family();\n\n\n\n for model in ctx.da...
Rust
sdk/tests/t_nft_contract.rs
fgfm999/trampoline
e7c2f0172087973f8fc0b4884e459fdd5855c235
use std::path::Path; use ckb_hash::blake2b_256; use trampoline_sdk::ckb_types::packed::{CellInput, CellOutput}; use ckb_jsonrpc_types::JsonBytes; use trampoline_sdk::chain::{MockChain, MockChainTxProvider as ChainRpc}; use trampoline_sdk::ckb_types::{ self, bytes::Bytes, core::{TransactionBuilder, TransactionView}, error::Error, packed::*, prelude::*, H256, }; use trampoline_sdk::contract::*; use trampoline_sdk::contract::{builtins::t_nft::*, generator::*}; use trampoline_sdk::contract::{schema::*, ContractSource}; fn _assert_script_error(err: Error, err_code: i8) { let error_string = err.to_string(); assert!( error_string.contains(format!("error code {} ", err_code).as_str()), "error_string: {}, expected_error_code: {}", error_string, err_code ); } fn _generate_always_success_lock( args: Option<ckb_types::packed::Bytes>, ) -> ckb_types::packed::Script { let data: Bytes = ckb_always_success_script::ALWAYS_SUCCESS.to_vec().into(); let data_hash = H256::from(blake2b_256(data.to_vec().as_slice())); ckb_types::packed::Script::default() .as_builder() .args(args.unwrap_or([0u8].pack())) .code_hash(data_hash.pack()) .hash_type(ckb_types::core::ScriptHashType::Data1.into()) .build() } fn gen_nft_contract() -> TrampolineNFTContract { let out_dir = std::env::var_os("OUT_DIR").unwrap(); let path_to_nft_bin = Path::new(&out_dir).join("trampoline-nft"); let bin = ContractSource::load_from_path(path_to_nft_bin).unwrap(); let mut contract = TrampolineNFTContract::default(); contract.code = Some(JsonBytes::from_bytes(bin)); contract } fn _gen_tnft_cell_output(contract: &TrampolineNFTContract) -> CellOutput { let lock = contract .lock .clone() .unwrap_or(_generate_always_success_lock(None).into()); CellOutput::new_builder() .capacity(200_u64.pack()) .type_( Some(ckb_types::packed::Script::from( contract.as_script().unwrap(), )) .pack(), ) .lock(lock.into()) .build() } fn _generate_mock_tx( inputs: Vec<CellInput>, outputs: Vec<CellOutput>, outputs_data: Vec<ckb_types::packed::Bytes>, ) -> TransactionView { TransactionBuilder::default() .inputs(inputs) .outputs(outputs) .outputs_data(outputs_data) .build() } fn genesis_id_from(input: OutPoint) -> GenesisId { let seed_tx_hash = input.tx_hash(); let seed_idx = input.index(); let mut seed = Vec::with_capacity(36); seed.extend_from_slice(seed_tx_hash.as_slice()); seed.extend_from_slice(seed_idx.as_slice()); let hash = blake2b_256(&seed); GenesisId::from_mol(hash.pack()) } type NftArgs = SchemaPrimitiveType<Bytes, ckb_types::packed::Bytes>; type NftField = ContractCellField<NftArgs, TrampolineNFT>; #[test] fn test_success_deploy() { let mut tnft_contract = gen_nft_contract(); let mut chain = MockChain::default(); let minter_lock_cell = chain.get_default_script_outpoint(); let minter_lock_script = chain.build_script(&minter_lock_cell, vec![1_u8].into()); let tx_input_cell = chain.deploy_random_cell_with_default_lock(2000, Some(vec![1_u8].into())); let tnft_code_cell = tnft_contract.as_code_cell(); let tnft_code_cell_outpoint = chain.create_cell(tnft_code_cell.0, tnft_code_cell.1); tnft_contract.source = Some(ContractSource::Chain(tnft_code_cell_outpoint.into())); let genesis_seed = genesis_id_from(tx_input_cell); tnft_contract.add_input_rule(move |_tx| -> CellQuery { CellQuery { _query: QueryStatement::Single(CellQueryAttribute::LockHash( minter_lock_script .clone() .unwrap() .calc_script_hash() .into(), )), _limit: 1, } }); tnft_contract.add_output_rule(ContractField::Data, move |ctx| -> NftField { let nft: NftField = ctx.load(ContractField::Data); if let ContractCellField::Data(nft_data) = nft { let mut t_nft_data = nft_data; t_nft_data.genesis_id = genesis_seed.clone(); NftField::Data(t_nft_data) } else { nft } }); let chain_rpc = ChainRpc::new(chain); let generator = Generator::new() .chain_service(&chain_rpc) .query_service(&chain_rpc) .pipeline(vec![&tnft_contract]); let new_mint_tx = generator.generate(); let is_valid = chain_rpc.verify_tx(new_mint_tx.tx.into()); assert!(is_valid); } #[test] fn test_invalid_mismatched_genesis_id() { let mut tnft_contract = gen_nft_contract(); let mut chain = MockChain::default(); let minter_lock_cell = chain.get_default_script_outpoint(); let minter_lock_script = chain.build_script(&minter_lock_cell, vec![1_u8].into()); let _tx_input_cell = chain.deploy_random_cell_with_default_lock(2000, Some(vec![1_u8].into())); let genesis_id_seed_cell = chain.deploy_random_cell_with_default_lock(2000, Some(vec![2_u8].into())); let tnft_code_cell = tnft_contract.as_code_cell(); let tnft_code_cell_outpoint = chain.create_cell(tnft_code_cell.0, tnft_code_cell.1); tnft_contract.source = Some(ContractSource::Chain(tnft_code_cell_outpoint.into())); let genesis_seed = genesis_id_from(genesis_id_seed_cell); tnft_contract.add_input_rule(move |_tx| -> CellQuery { CellQuery { _query: QueryStatement::Single(CellQueryAttribute::LockHash( minter_lock_script .clone() .unwrap() .calc_script_hash() .into(), )), _limit: 1, } }); tnft_contract.add_output_rule(ContractField::Data, move |ctx| -> NftField { let nft: NftField = ctx.load(ContractField::Data); if let ContractCellField::Data(nft_data) = nft { let mut t_nft_data = nft_data; t_nft_data.genesis_id = genesis_seed.clone(); NftField::Data(t_nft_data) } else { nft } }); let chain_rpc = ChainRpc::new(chain); let generator = Generator::new() .chain_service(&chain_rpc) .query_service(&chain_rpc) .pipeline(vec![&tnft_contract]); let new_mint_tx = generator.generate(); let is_valid = chain_rpc.verify_tx(new_mint_tx.tx.into()); assert!(!is_valid); } #[test] fn test_invalid_mint_of_pre_existing_tnft() { let mut tnft_contract = gen_nft_contract(); let mut chain = MockChain::default(); let minter_lock_cell = chain.get_default_script_outpoint(); let minter_lock_script = chain.build_script(&minter_lock_cell, vec![1_u8].into()); let _tx_input_cell = chain.deploy_random_cell_with_default_lock(2000, Some(vec![1_u8].into())); let input_tnft_seed = chain.deploy_random_cell_with_default_lock(2000, Some(vec![2_u8].into())); let tnft_code_cell = tnft_contract.as_code_cell(); let tnft_code_cell_outpoint = chain.create_cell(tnft_code_cell.0, tnft_code_cell.1); tnft_contract.source = Some(ContractSource::Chain(tnft_code_cell_outpoint.into())); let tnft_input_cell = CellOutput::new_builder() .lock(minter_lock_script.clone().unwrap()) .capacity(150_u64.pack()) .type_(Some(Script::from(tnft_contract.as_script().unwrap())).pack()) .build(); let tnft_input_cell_data = TrampolineNFT { genesis_id: genesis_id_from(input_tnft_seed), cid: Default::default(), }; let _tnft_input_outpoint = chain.deploy_cell_output(tnft_input_cell_data.to_bytes(), tnft_input_cell); tnft_contract.add_input_rule(move |_tx| -> CellQuery { CellQuery { _query: QueryStatement::Single(CellQueryAttribute::LockHash( minter_lock_script .clone() .unwrap() .calc_script_hash() .into(), )), _limit: 1, } }); tnft_contract.add_output_rule(ContractField::Data, move |ctx| -> NftField { let nft: NftField = ctx.load(ContractField::Data); if let NftField::ResolvedInputs(inputs) = ctx.load(TransactionField::ResolvedInputs) { if let ContractCellField::Data(nft_data) = nft { let mut t_nft_data = nft_data; let genesis_id = genesis_id_from(inputs.first().unwrap().out_point.clone()); t_nft_data.genesis_id = genesis_id; NftField::Data(t_nft_data) } else { nft } } else { nft } }); let chain_rpc = ChainRpc::new(chain); let generator = Generator::new() .chain_service(&chain_rpc) .query_service(&chain_rpc) .pipeline(vec![&tnft_contract]); let new_mint_tx = generator.generate(); let is_valid = chain_rpc.verify_tx(new_mint_tx.tx.into()); assert!(is_valid); }
use std::path::Path; use ckb_hash::blake2b_256; use trampoline_sdk::ckb_types::packed::{CellInput, CellOutput}; use ckb_jsonrpc_types::JsonBytes; use trampoline_sdk::chain::{MockChain, MockChainTxProvider as ChainRpc}; use trampoline_sdk::ckb_types::{ self, bytes::Bytes, core::{TransactionBuilder, TransactionView}, error::Error, packed::*, prelude::*, H256, }; use trampoline_sdk::contract::*; use trampoline_sdk::contract::{builtins::t_nft::*, generator::*}; use trampoline_sdk::contract::{schema::*, ContractSource}; fn _assert_script_error(err: Error, err_code: i8) { let error_string = err.to_string(); assert!( error_string.contains(format!("error code {} ", err_code).as_str()), "error_string: {}, expected_error_code: {}", error_string, err_code ); } fn _generate_always_success_lock( args: Option<ckb_types::packed::Bytes>, ) -> ckb_types::packed::Script { let data: Bytes = ckb_always_success_script::ALWAYS_SUCCESS.to_vec().into(); let data_hash = H256::from(blake2b_256(data.to_vec().as_slice())); ckb_types::packed::Script::default() .as_builder() .args(args.unwrap_or([0u8].pack())) .code_hash(data_hash.pack()) .hash_type(ckb_types::core::ScriptHashType::Data1.into()) .build() } fn gen_nft_contract() -> TrampolineNFTContract { let out_dir = std::env::var_os("OUT_DIR").unwrap(); let path_to_nft_bin = Path::new(&out_dir).join("trampoline-nft"); let bin = ContractSource::load_from_path(path_to_nft_bin).unwrap(); let mut contract = TrampolineNFTContract::default(); contract.code = Some(JsonBytes::from_bytes(bin)); contract } fn _gen_tnft_cell_output(contract: &TrampolineNFTContract) -> CellOutput { let lock = contract .lock .clone() .unwrap_or(_generate_always_success_lock(None).into()); CellOutput::new_builder() .capacity(200_u64.pack()) .type_( Some(ckb_types::packed::Script::from( contract.as_script().unwrap(), )) .pack(), ) .lock(lock.into()) .build() } fn _generate_mock_tx( inputs: Vec<CellInput>, outputs: Vec<CellOutput>, outputs_data: Vec<ckb_types::packed::Byte
fn genesis_id_from(input: OutPoint) -> GenesisId { let seed_tx_hash = input.tx_hash(); let seed_idx = input.index(); let mut seed = Vec::with_capacity(36); seed.extend_from_slice(seed_tx_hash.as_slice()); seed.extend_from_slice(seed_idx.as_slice()); let hash = blake2b_256(&seed); GenesisId::from_mol(hash.pack()) } type NftArgs = SchemaPrimitiveType<Bytes, ckb_types::packed::Bytes>; type NftField = ContractCellField<NftArgs, TrampolineNFT>; #[test] fn test_success_deploy() { let mut tnft_contract = gen_nft_contract(); let mut chain = MockChain::default(); let minter_lock_cell = chain.get_default_script_outpoint(); let minter_lock_script = chain.build_script(&minter_lock_cell, vec![1_u8].into()); let tx_input_cell = chain.deploy_random_cell_with_default_lock(2000, Some(vec![1_u8].into())); let tnft_code_cell = tnft_contract.as_code_cell(); let tnft_code_cell_outpoint = chain.create_cell(tnft_code_cell.0, tnft_code_cell.1); tnft_contract.source = Some(ContractSource::Chain(tnft_code_cell_outpoint.into())); let genesis_seed = genesis_id_from(tx_input_cell); tnft_contract.add_input_rule(move |_tx| -> CellQuery { CellQuery { _query: QueryStatement::Single(CellQueryAttribute::LockHash( minter_lock_script .clone() .unwrap() .calc_script_hash() .into(), )), _limit: 1, } }); tnft_contract.add_output_rule(ContractField::Data, move |ctx| -> NftField { let nft: NftField = ctx.load(ContractField::Data); if let ContractCellField::Data(nft_data) = nft { let mut t_nft_data = nft_data; t_nft_data.genesis_id = genesis_seed.clone(); NftField::Data(t_nft_data) } else { nft } }); let chain_rpc = ChainRpc::new(chain); let generator = Generator::new() .chain_service(&chain_rpc) .query_service(&chain_rpc) .pipeline(vec![&tnft_contract]); let new_mint_tx = generator.generate(); let is_valid = chain_rpc.verify_tx(new_mint_tx.tx.into()); assert!(is_valid); } #[test] fn test_invalid_mismatched_genesis_id() { let mut tnft_contract = gen_nft_contract(); let mut chain = MockChain::default(); let minter_lock_cell = chain.get_default_script_outpoint(); let minter_lock_script = chain.build_script(&minter_lock_cell, vec![1_u8].into()); let _tx_input_cell = chain.deploy_random_cell_with_default_lock(2000, Some(vec![1_u8].into())); let genesis_id_seed_cell = chain.deploy_random_cell_with_default_lock(2000, Some(vec![2_u8].into())); let tnft_code_cell = tnft_contract.as_code_cell(); let tnft_code_cell_outpoint = chain.create_cell(tnft_code_cell.0, tnft_code_cell.1); tnft_contract.source = Some(ContractSource::Chain(tnft_code_cell_outpoint.into())); let genesis_seed = genesis_id_from(genesis_id_seed_cell); tnft_contract.add_input_rule(move |_tx| -> CellQuery { CellQuery { _query: QueryStatement::Single(CellQueryAttribute::LockHash( minter_lock_script .clone() .unwrap() .calc_script_hash() .into(), )), _limit: 1, } }); tnft_contract.add_output_rule(ContractField::Data, move |ctx| -> NftField { let nft: NftField = ctx.load(ContractField::Data); if let ContractCellField::Data(nft_data) = nft { let mut t_nft_data = nft_data; t_nft_data.genesis_id = genesis_seed.clone(); NftField::Data(t_nft_data) } else { nft } }); let chain_rpc = ChainRpc::new(chain); let generator = Generator::new() .chain_service(&chain_rpc) .query_service(&chain_rpc) .pipeline(vec![&tnft_contract]); let new_mint_tx = generator.generate(); let is_valid = chain_rpc.verify_tx(new_mint_tx.tx.into()); assert!(!is_valid); } #[test] fn test_invalid_mint_of_pre_existing_tnft() { let mut tnft_contract = gen_nft_contract(); let mut chain = MockChain::default(); let minter_lock_cell = chain.get_default_script_outpoint(); let minter_lock_script = chain.build_script(&minter_lock_cell, vec![1_u8].into()); let _tx_input_cell = chain.deploy_random_cell_with_default_lock(2000, Some(vec![1_u8].into())); let input_tnft_seed = chain.deploy_random_cell_with_default_lock(2000, Some(vec![2_u8].into())); let tnft_code_cell = tnft_contract.as_code_cell(); let tnft_code_cell_outpoint = chain.create_cell(tnft_code_cell.0, tnft_code_cell.1); tnft_contract.source = Some(ContractSource::Chain(tnft_code_cell_outpoint.into())); let tnft_input_cell = CellOutput::new_builder() .lock(minter_lock_script.clone().unwrap()) .capacity(150_u64.pack()) .type_(Some(Script::from(tnft_contract.as_script().unwrap())).pack()) .build(); let tnft_input_cell_data = TrampolineNFT { genesis_id: genesis_id_from(input_tnft_seed), cid: Default::default(), }; let _tnft_input_outpoint = chain.deploy_cell_output(tnft_input_cell_data.to_bytes(), tnft_input_cell); tnft_contract.add_input_rule(move |_tx| -> CellQuery { CellQuery { _query: QueryStatement::Single(CellQueryAttribute::LockHash( minter_lock_script .clone() .unwrap() .calc_script_hash() .into(), )), _limit: 1, } }); tnft_contract.add_output_rule(ContractField::Data, move |ctx| -> NftField { let nft: NftField = ctx.load(ContractField::Data); if let NftField::ResolvedInputs(inputs) = ctx.load(TransactionField::ResolvedInputs) { if let ContractCellField::Data(nft_data) = nft { let mut t_nft_data = nft_data; let genesis_id = genesis_id_from(inputs.first().unwrap().out_point.clone()); t_nft_data.genesis_id = genesis_id; NftField::Data(t_nft_data) } else { nft } } else { nft } }); let chain_rpc = ChainRpc::new(chain); let generator = Generator::new() .chain_service(&chain_rpc) .query_service(&chain_rpc) .pipeline(vec![&tnft_contract]); let new_mint_tx = generator.generate(); let is_valid = chain_rpc.verify_tx(new_mint_tx.tx.into()); assert!(is_valid); }
s>, ) -> TransactionView { TransactionBuilder::default() .inputs(inputs) .outputs(outputs) .outputs_data(outputs_data) .build() }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn test_contract_pack_and_unpack_data() {\n\n let mut sudt_contract = gen_sudt_contract(None, None);\n\n\n\n sudt_contract.set_args(OwnerLockHash::from_mol(Byte32::default()));\n\n sudt_contract.set_data(SudtAmount::from_mol(1200_u128.pack()));\n\n\n\n let uint128_data: u128...
Rust
libs/editor/libs/paths/src/paths.rs
Ryan1729IsParanoidAboutWriteAccess/rote
fbe20e4627c1b63d2af7141dcffd424563b8fe9f
use std::path::{Path, PathBuf}; pub fn find_in<'path, I: Iterator<Item = &'path Path>>( paths: I, needle: &str, ) -> Vec<PathBuf> { if needle.is_empty() { return Vec::new(); } let len = { if let (_, Some(l)) = paths.size_hint() { l } else { 128 } }; let mut output: Vec<PathBuf> = Vec::with_capacity(len); for path in paths { let mut contains_needle = false; macro_rules! cmp_match_indices { ($p1: expr, $p2: expr, $path_cmp: expr) => {{ use std::cmp::Ordering::*; let mut p1_iter = $p1.match_indices(needle); let mut p2_iter = $p2.match_indices(needle); let mut backup_ordering = Equal; let mut p1_needle_count = 0; let mut p2_needle_count = 0; loop { match (p1_iter.next(), p2_iter.next()) { (Some((p1_i, _)), Some((p2_i, _))) => { contains_needle = true; backup_ordering = p1_i.cmp(&p2_i); p1_needle_count += 1; p2_needle_count += 1; } (Some(_), None) => { contains_needle = true; p1_needle_count += 1; break; } (None, Some(_)) => { p2_needle_count += 1; break; } (None, None) => { break; } } } p1_needle_count .cmp(&p2_needle_count) .then_with(|| backup_ordering) .then_with(|| $path_cmp) }}; } let i = if output.is_empty() { contains_needle = if let Some(s) = path.to_str() { s.match_indices(needle).count() > 0 } else { let s = path.to_string_lossy(); s.match_indices(needle).count() > 0 }; 0 } else { output .binary_search_by(|p| { match (path.to_str(), p.to_str()) { (Some(s1), Some(s2)) => cmp_match_indices!(s1, s2, p.as_path().cmp(path)), (Some(s1), None) => { let s2 = p.to_string_lossy(); cmp_match_indices!(s1, s2, p.as_path().cmp(path)) } (None, Some(s2)) => { let s1 = path.to_string_lossy(); cmp_match_indices!(s1, s2, p.as_path().cmp(path)) } (None, None) => { let s1 = path.to_string_lossy(); let s2 = p.to_string_lossy(); cmp_match_indices!(s1, s2, p.as_path().cmp(path)) } } }) .unwrap_or_else(|i| i) }; if contains_needle { output.insert(i, path.to_path_buf()); } } output } #[cfg(test)] mod tests { use super::*; #[test] fn find_in_paths_works_on_this_small_example() { let needle = "b"; let searched_paths = vec![ PathBuf::from("C:\\Users\\ryan1729\\Documents\\bartog.txt"), PathBuf::from("C:\\Users\\ryan1729\\Documents\\beans.txt"), PathBuf::from("C:\\Users\\ryan1729\\Documents\\unrelated.txt"), ]; let expected = vec![ PathBuf::from("C:\\Users\\ryan1729\\Documents\\bartog.txt"), PathBuf::from("C:\\Users\\ryan1729\\Documents\\beans.txt"), ]; assert_eq!( find_in(searched_paths.iter().map(|p| p.as_path()), needle), expected ); } #[test] fn find_in_paths_sorts_things_with_multiple_needles_higher() { let needle = "b"; let searched_paths = vec![ PathBuf::from("C:\\Users\\ryan1729\\Documents\\basketball.txt"), PathBuf::from("C:\\Users\\ryan1729\\Documents\\beans.txt"), PathBuf::from("C:\\Users\\ryan1729\\Documents\\beebasketball.txt"), ]; let expected = vec![ PathBuf::from("C:\\Users\\ryan1729\\Documents\\beebasketball.txt"), PathBuf::from("C:\\Users\\ryan1729\\Documents\\basketball.txt"), PathBuf::from("C:\\Users\\ryan1729\\Documents\\beans.txt"), ]; assert_eq!( find_in(searched_paths.iter().map(|p| p.as_path()), needle), expected ); } }
use std::path::{Path, PathBuf}; pub fn find_in<'path, I: Iterator<Item = &'path Path>>( paths: I, needle: &str, ) -> Vec<PathBuf> { if needle.is_empty() { return Vec::new(); } let len = { if let (_, Some(l)) = paths.size_hint() { l } else { 128 } }; let mut output: Vec<PathBuf> = Vec::with_capacity(len); for path in paths { let mut contains_needle = false; macro_rules! cmp_match_indices { ($p1: expr, $p2: expr, $path_cmp: expr) => {{ use std::cmp::Ordering::*; let mut p1_iter = $p1.match_indices(needle); let mut p2_iter = $p2.match_indices(needle); let mut backup_ordering = Equal; let mut p1_needle_count = 0; let mut p2_needle_count = 0; loop { match (p1_iter.next(), p2_iter.next()) { (Some((p1_i, _)), Some((p2_i, _))) => { contains_needle = true; backup_ordering = p1_i.cmp(&p2_i); p1_needle_count += 1; p2_needle_count += 1; } (Some(_), None) => { contains_needle = true; p1_needle_count += 1; break; } (None, Some(_)) => { p2_needle_count += 1; break; } (None, None) => { break; } } } p1_needle_count .cmp(&p2_needle_count) .then_with(|| backup_ordering) .then_with(|| $path_cmp) }}; } let i = if output.is_empty() { contains_needle = if let Some(s) = path.to_str() { s.match_indices(needle).count() > 0 } else { let s = path.to_string_lossy(); s.match_indices(needle).count() > 0 }; 0 } else { output .binary_search_by(|p| { match (path.to_str(), p.to_str()) { (Some(s1), Some(s2)) => cmp_match_indices!(s1, s2, p.as_path().cmp(path)), (Some(s1), None) => { let s2 = p.to_string_lossy(); cmp_match_indices!(s1, s2, p.as_path().cmp(path)) } (None, Some(s2)) => { let s1 = path.to_string_lossy(); cmp_match_indices!(s1, s2, p.as_path().cmp(path)) } (None, None) => { let s1 = path.to_string_lossy(); let s2 = p.to_string_lossy(); cmp_match_indices!(s1, s2, p.as_path().cmp(path)) } } }) .unwrap_or_else(|i| i) }; if contains_needle { output.insert(i, path.to_path_buf()); } } output } #[cfg(test)] mod tests { use super::*; #[test] fn find_in_paths_works_on_this_small_example() { let needle = "b"; let searched_paths = vec![ PathBuf::from("C:\\Users\\rya
rom("C:\\Users\\ryan1729\\Documents\\beans.txt"), ]; assert_eq!( find_in(searched_paths.iter().map(|p| p.as_path()), needle), expected ); } #[test] fn find_in_paths_sorts_things_with_multiple_needles_higher() { let needle = "b"; let searched_paths = vec![ PathBuf::from("C:\\Users\\ryan1729\\Documents\\basketball.txt"), PathBuf::from("C:\\Users\\ryan1729\\Documents\\beans.txt"), PathBuf::from("C:\\Users\\ryan1729\\Documents\\beebasketball.txt"), ]; let expected = vec![ PathBuf::from("C:\\Users\\ryan1729\\Documents\\beebasketball.txt"), PathBuf::from("C:\\Users\\ryan1729\\Documents\\basketball.txt"), PathBuf::from("C:\\Users\\ryan1729\\Documents\\beans.txt"), ]; assert_eq!( find_in(searched_paths.iter().map(|p| p.as_path()), needle), expected ); } }
n1729\\Documents\\bartog.txt"), PathBuf::from("C:\\Users\\ryan1729\\Documents\\beans.txt"), PathBuf::from("C:\\Users\\ryan1729\\Documents\\unrelated.txt"), ]; let expected = vec![ PathBuf::from("C:\\Users\\ryan1729\\Documents\\bartog.txt"), PathBuf::f
function_block-random_span
[]
Rust
src/mesh.rs
ArvinSKushwaha/dynamics_engine
a1189653d3dc5c9b4dfd4eee3eee75b7b6f3b9ed
use crate::object::{Ray, RayCollision}; use crate::{Float, Mat3, Point3, UnitVec3, Vec3, EPSILON}; use na::{point, vector}; use nalgebra as na; use std::io::{BufRead, BufReader}; #[derive(Debug, Clone)] pub struct MeshOptions { pub smooth_normals: bool, } #[derive(Debug, Clone)] pub struct PolygonMesh { pub vertex_list: Vec<Point3>, pub vertices_to_faces: Vec<Vec<usize>>, pub faces_to_vertices: Vec<Vec<usize>>, pub face_normals: Vec<UnitVec3>, pub vertex_normals: Vec<UnitVec3>, pub mesh_options: MeshOptions, pub smooth_transform_matrices: Option<Vec<Mat3>>, } impl PolygonMesh { pub fn get_mesh(&self) -> &PolygonMesh { self } pub fn get_vertex_count(&self) -> usize { self.vertex_list.len() } pub fn get_face_count(&self) -> usize { self.face_normals.len() } pub fn from_many(x: &[PolygonMesh]) -> PolygonMesh { x.iter() .fold( PolygonMesh { vertex_list: vec![], vertices_to_faces: vec![], faces_to_vertices: vec![], face_normals: vec![], vertex_normals: vec![], mesh_options: MeshOptions { smooth_normals: false, }, smooth_transform_matrices: None, }, |a: PolygonMesh, b: &PolygonMesh| { let mut a = a.clone(); let vertex_count = a.get_vertex_count(); let face_count = a.get_face_count(); a.vertex_list.extend(b.vertex_list.iter()); a.face_normals.extend(b.face_normals.iter()); a.vertex_normals.extend(b.vertex_normals.iter()); a.faces_to_vertices.extend(b.faces_to_vertices.clone()); a.vertices_to_faces.extend(b.faces_to_vertices.clone()); for i in face_count..a.faces_to_vertices.len() { a.faces_to_vertices[i] = a.faces_to_vertices[i] .iter() .map(|v| *v + vertex_count) .collect(); } for i in vertex_count..a.vertices_to_faces.len() { a.vertices_to_faces[i] = a.vertices_to_faces[i] .iter() .map(|v| *v + face_count) .collect(); } a }, ) .clone() } } pub fn read_obj(path: &str, smoothing: bool) -> Result<PolygonMesh, &str> { let f = match std::fs::File::open(path) { Ok(t) => t, Err(_) => return Err("OBJ File opening failed"), }; let mut smooth_transform_matrices = vec![]; let mut mesh = PolygonMesh { vertex_list: vec![], vertices_to_faces: vec![], faces_to_vertices: vec![], face_normals: vec![], vertex_normals: vec![], mesh_options: MeshOptions { smooth_normals: smoothing, }, smooth_transform_matrices: None, }; for line in BufReader::new(f).lines() { let data: String = match line { Ok(t) => t.trim().to_string(), Err(_) => return Err("OBJ File reading failed"), }; if data.len() == 0 || data.starts_with("#") { continue; } let mut iter = data.split_whitespace(); match iter.next() { Some("v") => { mesh.vertex_list.push(point![ iter.next().unwrap_or("0").parse::<Float>().unwrap_or(0.), iter.next().unwrap_or("0").parse::<Float>().unwrap_or(0.), iter.next().unwrap_or("0").parse::<Float>().unwrap_or(0.) ]); mesh.vertices_to_faces.push(vec![]); } Some("f") => { let mut face_vertices: Vec<usize> = Vec::with_capacity(3); loop { if let Some(t) = iter.next() { match t.split('/').collect::<Vec<&str>>()[0].parse::<usize>() { Ok(v_num) => { face_vertices.push(v_num - 1); } Err(_) => { return Err("Integer parsing failed in face generation"); } } } else { break; } } assert!(face_vertices.len() >= 3); let pts = [ mesh.vertex_list[face_vertices[2]], mesh.vertex_list[face_vertices[1]], mesh.vertex_list[face_vertices[0]], ]; let norm: Vec3 = (pts[1] - pts[0]).cross(&(pts[2] - pts[1])); let unit_normal; if let Some(unit_norm) = na::Unit::try_new(norm, 1.0e-7) { unit_normal = unit_norm; } else { std::panic::panic_any("Yikes, the normals didn't compute right?!"); } for i in 0..face_vertices.len() - 2 { mesh.vertices_to_faces[face_vertices[0]].push(mesh.faces_to_vertices.len()); mesh.vertices_to_faces[face_vertices[i + 1]].push(mesh.faces_to_vertices.len()); mesh.vertices_to_faces[face_vertices[i + 2]].push(mesh.faces_to_vertices.len()); if smoothing { smooth_transform_matrices.push( match na::Matrix3::from_columns(&[ mesh.vertex_list[face_vertices[0]] .coords .add_scalar(EPSILON), mesh.vertex_list[face_vertices[i + 1]] .coords .add_scalar(EPSILON), mesh.vertex_list[face_vertices[i + 2]] .coords .add_scalar(EPSILON), ]) .try_inverse() { Some(m) => m, None => return Err("Found a non-invertible matrix. Yikes."), }, ); } mesh.faces_to_vertices.push(vec![ face_vertices[0], face_vertices[i + 1], face_vertices[i + 2], ]); mesh.face_normals.push(unit_normal); } } Some("vt") => continue, Some("vn") => { mesh.vertex_normals.push( na::Unit::try_new( vector![ iter.next().unwrap_or("0").parse::<Float>().unwrap_or(0.), iter.next().unwrap_or("0").parse::<Float>().unwrap_or(0.), iter.next().unwrap_or("0").parse::<Float>().unwrap_or(0.) ], 1e-7, ) .unwrap(), ); } _ => continue, }; } if mesh.vertex_normals.len() != mesh.vertex_list.len() { mesh.vertex_normals.resize( mesh.vertex_list.len(), na::UnitVector3::new_unchecked(vector![1., 0., 0.]), ); for (i, faces) in mesh.vertices_to_faces.iter().enumerate() { let current_vertex = mesh.vertex_list[i]; let mut normal = vector![0., 0., 0.]; for face in faces { let vertex_index = mesh.faces_to_vertices[*face] .iter() .position(|&r| r == i) .unwrap(); let prev_vertex = mesh.vertex_list[mesh.faces_to_vertices[*face][(vertex_index as isize - 1) .rem_euclid(mesh.faces_to_vertices[*face].len() as isize) as usize]]; let next_vertex = mesh.vertex_list[mesh.faces_to_vertices[*face][(vertex_index as isize + 1) .rem_euclid(mesh.faces_to_vertices[*face].len() as isize) as usize]]; let angle = (std::f64::consts::PI as Float) - (current_vertex - prev_vertex) .angle(&(next_vertex - current_vertex)) .abs(); normal += mesh.face_normals[*face].into_inner() * angle / (2. * (std::f64::consts::PI as Float)); } mesh.vertex_normals[i] = na::Unit::new_normalize(normal); } } for i in 0..mesh.get_face_count() { assert_eq!(mesh.faces_to_vertices[i].len(), 3); } mesh.smooth_transform_matrices = Some(smooth_transform_matrices); assert_eq!(mesh.face_normals.len(), mesh.faces_to_vertices.len()); assert_eq!(mesh.vertex_list.len(), mesh.vertices_to_faces.len()); assert_eq!(mesh.vertex_list.len(), mesh.vertex_normals.len()); return Result::Ok(mesh); } pub fn get_potential_collisions(mesh: &PolygonMesh, ray: &Ray) -> Vec<RayCollision> { let mut probable_faces = vec![]; for i in 0..mesh.get_face_count() { let vertices = ( mesh.vertex_list[mesh.faces_to_vertices[i][0]], mesh.vertex_list[mesh.faces_to_vertices[i][1]], mesh.vertex_list[mesh.faces_to_vertices[i][2]], ); let normals = ( mesh.vertex_normals[mesh.faces_to_vertices[i][0]], mesh.vertex_normals[mesh.faces_to_vertices[i][1]], mesh.vertex_normals[mesh.faces_to_vertices[i][2]], ); let (edge1, edge2, h, s, q); let (a, f, u, v); edge1 = vertices.1 - vertices.0; edge2 = vertices.2 - vertices.0; h = ray.direction.cross(&edge2); a = edge1.dot(&h); if a > -EPSILON && a < EPSILON { continue; } f = 1.0 / a; s = ray.origin - vertices.0; u = f * s.dot(&h); if u < 0. || u > 1. { continue; } q = s.cross(&edge1); v = f * ray.direction.dot(&q); if v < 0. || u + v > 1. { continue; } let t = f * edge2.dot(&q); if t > 0. { assert!(!t.is_nan()); let pos = ray.origin + ray.direction.scale(t); probable_faces.push(RayCollision { mesh: unsafe { std::mem::transmute(mesh) }, distance: t, face_normal: mesh.face_normals[i], position: pos, smooth_normal: if mesh.mesh_options.smooth_normals { let matrices = mesh.smooth_transform_matrices.as_ref().unwrap(); let components = matrices[i] * pos.coords.add_scalar(EPSILON); Some(UnitVec3::new_normalize( normals.0.scale(components.x) + normals.1.scale(components.y) + normals.2.scale(components.z), )) } else { None }, }); } } probable_faces.sort_unstable_by(|a, b| a.distance.partial_cmp(&b.distance).unwrap()); probable_faces }
use crate::object::{Ray, RayCollision}; use crate::{Float, Mat3, Point3, UnitVec3, Vec3, EPSILON}; use na::{point, vector}; use nalgebra as na; use std::io::{BufRead, BufReader}; #[derive(Debug, Clone)] pub struct MeshOptions { pub smooth_normals: bool, } #[derive(Debug, Clone)] pub struct PolygonMesh { pub vertex_list: Vec<Point3>, pub vertices_to_faces: Vec<Vec<usize>>, pub faces_to_vertices: Vec<Vec<usize>>, pub face_normals: Vec<UnitVec3>, pub vertex_normals: Vec<UnitVec3>, pub mesh_options: MeshOptions, pub smooth_transform_matrices: Option<Vec<Mat3>>, } impl PolygonMesh { pub fn get_mesh(&self) -> &PolygonMesh { self } pub fn get_vertex_count(&self) -> usize { self.vertex_list.len() } pub fn get_face_count(&self) -> usize { self.face_normals.len() } pub fn from_many(x: &[PolygonMesh]) -> PolygonMesh { x.iter() .fold( PolygonMesh { vertex_list: vec![], vertices_to_faces: vec![], faces_to_vertices: vec![], face_normals: vec![], vertex_normals: vec![], mesh_options: MeshOptions { smooth_normals: false, }, smooth_transform_matrices: None, }, |a: PolygonMesh, b: &PolygonMesh| { let mut a = a.clone(); let vertex_count = a.get_vertex_count(); let face_count = a.get_face_count(); a.vertex_list.extend(b.vertex_list.iter()); a.face_normals.extend(b.face_normals.iter()); a.vertex_normals.extend(b.vertex_normals.iter()); a.faces_to_vertices.extend(b.faces_to_vertices.clone()); a.vertices_to_faces.extend(b.faces_to_vertices.clone()); for i in face_count..a.faces_to_vertices.len() { a.faces_to_vertices[i] = a.faces_to_vertices[i] .iter() .map(|v| *v + vertex_count) .collect(); } for i in vertex_count..a.vertices_to_faces.len() { a.vertices_to_faces[i] = a.vertices_to_faces[i] .iter() .map(|v| *v + face_count) .collect(); } a }, ) .clone() } } pub fn read_obj(path: &str, smoothing: bool) -> Result<PolygonMesh, &str> { let f = match std::fs::File::open(path) { Ok(t) => t, Err(_) => return Err("OBJ File opening failed"), }; let mut smooth_transform_matrices = vec![]; let mut mesh = PolygonMesh { vertex_list: vec![], vertices_to_faces: vec![], faces_to_vertices: vec![], face_normals: vec![], vertex_normals: vec![], mesh_options: MeshOptions { smooth_normals: smoothing, }, smooth_transform_matrices: None, }; for line in BufReader::new(f).lines() { let data: String = match line { Ok(t) => t.trim().to_string(), Err(_) => return Err("OBJ File reading failed"), }; if data.len() == 0 || data.starts_with("#") { continue; } let mut iter = data.split_whitespace(); match iter.next() { Some("v") => { mesh.vertex_list.push(point![ iter.next().unwrap_or("0").parse::<Float>().unwrap_or(0.), iter.next().unwrap_or("0").parse::<Float>().unwrap_or(0.), iter.next().unwrap_or("0").parse::<Float>().unwrap_or(0.) ]); mesh.vertices_to_faces.push(vec![]); } Some("f") => { let mut face_vertices: Vec<usize> = Vec::with_capacity(3); loop { if let Some(t) = iter.next() { match t.split('/').collect::<Vec<&str>>()[0].parse::<usize>() { Ok(v_num) => { face_vertices.push(v_num - 1); } Err(_) => { return Err("Integer parsing failed in face generation"); } } } else { break; } } assert!(face_vertices.len() >= 3); let pts = [ mesh.vertex_list[face_vertices[2]], mesh.vertex_list[face_vertices[1]], mesh.vertex_list[face_vertices[0]], ]; let norm: Vec3 = (pts[1] - pts[0]).cross(&(pts[2] - pts[1])); let unit_normal; if let Some(unit_norm) = na::Unit::try_new(norm, 1.0e-7) { unit_normal = unit_norm; } else {
* (std::f64::consts::PI as Float)); } mesh.vertex_normals[i] = na::Unit::new_normalize(normal); } } for i in 0..mesh.get_face_count() { assert_eq!(mesh.faces_to_vertices[i].len(), 3); } mesh.smooth_transform_matrices = Some(smooth_transform_matrices); assert_eq!(mesh.face_normals.len(), mesh.faces_to_vertices.len()); assert_eq!(mesh.vertex_list.len(), mesh.vertices_to_faces.len()); assert_eq!(mesh.vertex_list.len(), mesh.vertex_normals.len()); return Result::Ok(mesh); } pub fn get_potential_collisions(mesh: &PolygonMesh, ray: &Ray) -> Vec<RayCollision> { let mut probable_faces = vec![]; for i in 0..mesh.get_face_count() { let vertices = ( mesh.vertex_list[mesh.faces_to_vertices[i][0]], mesh.vertex_list[mesh.faces_to_vertices[i][1]], mesh.vertex_list[mesh.faces_to_vertices[i][2]], ); let normals = ( mesh.vertex_normals[mesh.faces_to_vertices[i][0]], mesh.vertex_normals[mesh.faces_to_vertices[i][1]], mesh.vertex_normals[mesh.faces_to_vertices[i][2]], ); let (edge1, edge2, h, s, q); let (a, f, u, v); edge1 = vertices.1 - vertices.0; edge2 = vertices.2 - vertices.0; h = ray.direction.cross(&edge2); a = edge1.dot(&h); if a > -EPSILON && a < EPSILON { continue; } f = 1.0 / a; s = ray.origin - vertices.0; u = f * s.dot(&h); if u < 0. || u > 1. { continue; } q = s.cross(&edge1); v = f * ray.direction.dot(&q); if v < 0. || u + v > 1. { continue; } let t = f * edge2.dot(&q); if t > 0. { assert!(!t.is_nan()); let pos = ray.origin + ray.direction.scale(t); probable_faces.push(RayCollision { mesh: unsafe { std::mem::transmute(mesh) }, distance: t, face_normal: mesh.face_normals[i], position: pos, smooth_normal: if mesh.mesh_options.smooth_normals { let matrices = mesh.smooth_transform_matrices.as_ref().unwrap(); let components = matrices[i] * pos.coords.add_scalar(EPSILON); Some(UnitVec3::new_normalize( normals.0.scale(components.x) + normals.1.scale(components.y) + normals.2.scale(components.z), )) } else { None }, }); } } probable_faces.sort_unstable_by(|a, b| a.distance.partial_cmp(&b.distance).unwrap()); probable_faces }
std::panic::panic_any("Yikes, the normals didn't compute right?!"); } for i in 0..face_vertices.len() - 2 { mesh.vertices_to_faces[face_vertices[0]].push(mesh.faces_to_vertices.len()); mesh.vertices_to_faces[face_vertices[i + 1]].push(mesh.faces_to_vertices.len()); mesh.vertices_to_faces[face_vertices[i + 2]].push(mesh.faces_to_vertices.len()); if smoothing { smooth_transform_matrices.push( match na::Matrix3::from_columns(&[ mesh.vertex_list[face_vertices[0]] .coords .add_scalar(EPSILON), mesh.vertex_list[face_vertices[i + 1]] .coords .add_scalar(EPSILON), mesh.vertex_list[face_vertices[i + 2]] .coords .add_scalar(EPSILON), ]) .try_inverse() { Some(m) => m, None => return Err("Found a non-invertible matrix. Yikes."), }, ); } mesh.faces_to_vertices.push(vec![ face_vertices[0], face_vertices[i + 1], face_vertices[i + 2], ]); mesh.face_normals.push(unit_normal); } } Some("vt") => continue, Some("vn") => { mesh.vertex_normals.push( na::Unit::try_new( vector![ iter.next().unwrap_or("0").parse::<Float>().unwrap_or(0.), iter.next().unwrap_or("0").parse::<Float>().unwrap_or(0.), iter.next().unwrap_or("0").parse::<Float>().unwrap_or(0.) ], 1e-7, ) .unwrap(), ); } _ => continue, }; } if mesh.vertex_normals.len() != mesh.vertex_list.len() { mesh.vertex_normals.resize( mesh.vertex_list.len(), na::UnitVector3::new_unchecked(vector![1., 0., 0.]), ); for (i, faces) in mesh.vertices_to_faces.iter().enumerate() { let current_vertex = mesh.vertex_list[i]; let mut normal = vector![0., 0., 0.]; for face in faces { let vertex_index = mesh.faces_to_vertices[*face] .iter() .position(|&r| r == i) .unwrap(); let prev_vertex = mesh.vertex_list[mesh.faces_to_vertices[*face][(vertex_index as isize - 1) .rem_euclid(mesh.faces_to_vertices[*face].len() as isize) as usize]]; let next_vertex = mesh.vertex_list[mesh.faces_to_vertices[*face][(vertex_index as isize + 1) .rem_euclid(mesh.faces_to_vertices[*face].len() as isize) as usize]]; let angle = (std::f64::consts::PI as Float) - (current_vertex - prev_vertex) .angle(&(next_vertex - current_vertex)) .abs(); normal += mesh.face_normals[*face].into_inner() * angle / (2.
random
[]
Rust
pallets/root-of-trust/src/lib.rs
NodleCode/PKI
748aaddb8ce3ab7c90cfa3fd2610275f00f5cb7b
#![cfg_attr(not(feature = "std"), no_std)] #[cfg(test)] mod tests; use codec::{Decode, Encode}; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, dispatch::DispatchResult, ensure, traits::{ChangeMembers, Currency, ExistenceRequirement, Get, OnUnbalanced, WithdrawReasons}, Parameter, }; use frame_system::{self as system, ensure_signed}; use sp_runtime::traits::{MaybeDisplay, MaybeSerializeDeserialize, Member}; use sp_std::{fmt::Debug, prelude::Vec}; type BalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance; type NegativeImbalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance; #[derive(Encode, Decode, Default, Clone, PartialEq)] pub struct RootCertificate<AccountId, CertificateId, BlockNumber> { owner: AccountId, key: CertificateId, created: BlockNumber, renewed: BlockNumber, revoked: bool, validity: BlockNumber, child_revocations: Vec<CertificateId>, } pub trait Trait: system::Trait { type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>; type Currency: Currency<Self::AccountId>; type CertificateId: Member + Parameter + MaybeSerializeDeserialize + Debug + MaybeDisplay + Ord + Default; type SlotBookingCost: Get<BalanceOf<Self>>; type SlotRenewingCost: Get<BalanceOf<Self>>; type SlotValidity: Get<Self::BlockNumber>; type FundsCollector: OnUnbalanced<NegativeImbalanceOf<Self>>; } decl_event!( pub enum Event<T> where AccountId = <T as system::Trait>::AccountId, CertificateId = <T as Trait>::CertificateId, { SlotTaken(AccountId, CertificateId), SlotRenewed(CertificateId), SlotRevoked(CertificateId), ChildSlotRevoked(CertificateId, CertificateId), } ); decl_error! { pub enum Error for Module<T: Trait> { NotAMember, SlotTaken, NotEnoughFunds, NoLongerValid, NotTheOwner, } } decl_storage! { trait Store for Module<T: Trait> as RootOfTrustModule { Members get(members): Vec<T::AccountId>; Slots get(slots): map hasher(blake2_256) T::CertificateId => RootCertificate<T::AccountId, T::CertificateId, T::BlockNumber>; } } decl_module! { pub struct Module<T: Trait> for enum Call where origin: T::Origin { fn deposit_event() = default; fn book_slot(origin, certificate_id: T::CertificateId) -> DispatchResult { let sender = ensure_signed(origin)?; ensure!(Self::is_member(&sender), Error::<T>::NotAMember); ensure!(!<Slots<T>>::contains_key(&certificate_id), Error::<T>::SlotTaken); match T::Currency::withdraw(&sender, T::SlotBookingCost::get(), WithdrawReasons::all(), ExistenceRequirement::AllowDeath) { Ok(imbalance) => T::FundsCollector::on_unbalanced(imbalance), Err(_) => Err(Error::<T>::NotEnoughFunds)?, }; let now = <system::Module<T>>::block_number(); <Slots<T>>::insert(&certificate_id, RootCertificate { owner: sender.clone(), key: certificate_id.clone(), created: now, renewed: now, revoked: false, validity: T::SlotValidity::get(), child_revocations: Vec::new(), }); Self::deposit_event(RawEvent::SlotTaken(sender, certificate_id)); Ok(()) } fn renew_slot(origin, certificate: T::CertificateId) -> DispatchResult { let sender = ensure_signed(origin)?; let mut slot = <Slots<T>>::get(&certificate); ensure!(Self::is_slot_valid(&slot), Error::<T>::NoLongerValid); ensure!(slot.owner == sender, Error::<T>::NotTheOwner); match T::Currency::withdraw(&sender, T::SlotRenewingCost::get(), WithdrawReasons::all(), ExistenceRequirement::AllowDeath) { Ok(imbalance) => T::FundsCollector::on_unbalanced(imbalance), Err(_) => Err(Error::<T>::NotEnoughFunds)?, }; slot.renewed = <system::Module<T>>::block_number(); <Slots<T>>::insert(&certificate, slot); Self::deposit_event(RawEvent::SlotRenewed(certificate)); Ok(()) } fn revoke_slot(origin, certificate: T::CertificateId) -> DispatchResult { let sender = ensure_signed(origin)?; let mut slot = <Slots<T>>::get(&certificate); ensure!(Self::is_slot_valid(&slot), Error::<T>::NoLongerValid); ensure!(slot.owner == sender, Error::<T>::NotTheOwner); slot.revoked = true; <Slots<T>>::insert(&certificate, slot); Self::deposit_event(RawEvent::SlotRevoked(certificate)); Ok(()) } fn revoke_child(origin, root: T::CertificateId, child: T::CertificateId) -> DispatchResult { let sender = ensure_signed(origin)?; let mut slot = <Slots<T>>::get(&root); ensure!(Self::is_slot_valid(&slot), Error::<T>::NoLongerValid); ensure!(slot.owner == sender, Error::<T>::NotTheOwner); ensure!(!slot.child_revocations.contains(&child), Error::<T>::NoLongerValid); slot.child_revocations.push(child.clone()); <Slots<T>>::insert(&root, slot); Self::deposit_event(RawEvent::ChildSlotRevoked(root, child)); Ok(()) } } } impl<T: Trait> Module<T> { fn is_member(who: &T::AccountId) -> bool { Self::members().contains(who) } fn is_slot_valid( slot: &RootCertificate<T::AccountId, T::CertificateId, T::BlockNumber>, ) -> bool { let owner_is_member = Self::is_member(&slot.owner); let revoked = slot.revoked; let expired = slot.renewed + slot.validity <= <system::Module<T>>::block_number(); owner_is_member && !revoked && !expired } #[allow(dead_code)] pub fn is_root_certificate_valid(cert: &T::CertificateId) -> bool { let exists = <Slots<T>>::contains_key(cert); let slot = <Slots<T>>::get(cert); exists && Self::is_slot_valid(&slot) } #[allow(dead_code)] pub fn is_child_certificate_valid(root: &T::CertificateId, child: &T::CertificateId) -> bool { let equals = root == child; let root_valid = Self::is_root_certificate_valid(root); let revoked = <Slots<T>>::get(root).child_revocations.contains(child); !equals && root_valid && !revoked } } impl<T: Trait> ChangeMembers<T::AccountId> for Module<T> { fn change_members_sorted( _incoming: &[T::AccountId], _outgoing: &[T::AccountId], new: &[T::AccountId], ) { <Members<T>>::put(new); } }
#![cfg_attr(not(feature = "std"), no_std)] #[cfg(test)] mod tests; use codec::{Decode, Encode}; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, dispatch::DispatchResult, ensure, traits::{ChangeMembers, Currency, ExistenceRequirement, Get, OnUnbalanced, WithdrawReasons}, Parameter, }; use frame_system::{self as system, ensure_signed}; use sp_runtime::traits::{MaybeDisplay, MaybeSerializeDeserialize, Member}; use sp_std::{fmt::Debug, prelude::Vec}; type BalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance; type NegativeImbalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance; #[derive(Encode, Decode, Default, Clone, PartialEq)] pub struct RootCertificate<AccountId, CertificateId, BlockNumber> { owner: AccountId, key: CertificateId, created: BlockNumber, renewed: BlockNumber, revoked: bool, validity: BlockNumber, child_revocations: Vec<CertificateId>, } pub trait Trait: system::Trait { type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>; type Currency: Currency<Self::AccountId>; type CertificateId: Member + Parameter + MaybeSerializeDeserialize + Debug + MaybeDisplay + Ord + Default; type SlotBookingCost: Get<BalanceOf<Self>>; type SlotRenewingCost: Get<BalanceOf<Self>>; type SlotValidity: Get<Self::BlockNumber>; type FundsCollector: OnUnbalanced<NegativeImbalanceOf<Self>>; } decl_event!( pub enum Event<T> where AccountId = <T as system::Trait>::AccountId, CertificateId = <T as Trait>::CertificateId, { SlotTaken(AccountId, CertificateId), SlotRenewed(CertificateId), SlotRevoked(CertificateId), ChildSlotRevoked(CertificateId, CertificateId), } ); decl_error! { pub enum Error for Module<T: Trait> { NotAMember, SlotTaken, NotEnoughFunds, NoLongerValid, NotTheOwner, } } decl_storage! { trait Store for Module<T: Trait> as RootOfTrustModule { Members get(members): Vec<T::AccountId>; Slots get(slots): map hasher(blake2_256) T::CertificateId => RootCertificate<T::AccountId, T::CertificateId, T::BlockNumber>; } } decl_module! { pub struct Module<T: Trait> for enum Call where origin: T::Origin { fn deposit_event() = default; fn book_slot(origin, certificate_id: T::CertificateId) -> DispatchResult { let sender = ensure_signed(origin)?; ensure!(Self::is_member(&sender), Error::<T>::NotAMember); ensure!(!<Slots<T>>::contains_key(&certificate_id), Error::<T>::SlotTaken); match T::Currency::withdraw(&sender, T::SlotBookingCost::get(), WithdrawReasons::all(), ExistenceRequirement::AllowDeath) { Ok(imbalance) => T::FundsCollector::on_unbalanced(imbalance), Err(_) => Err(Error::<T>::NotEnoughFunds)?, }; let now = <system::Module<T>>::block_number(); <Slots<T>>::insert(&certificate_id, RootCertificate { owner: sender.clone(), key: certificate_id.clone(), created: now, renewed: now, revoked: false, validity: T::SlotValidity::get(), child_revocations: Vec::new(), }); Self::deposit_event(RawEvent::SlotTaken(sender, certificate_id)); Ok(()) } fn renew_slot(origin, certificate: T::CertificateId) -> DispatchResult { let sender = ensure_signed(origin)?; let mut slot = <Slots<T>>::get(&certificate); ensure!(Self::is_slot_valid(&slot), Error::<T>::NoLongerValid); ensure!(slot.owner == sender, Error::<T>::NotTheOwner); match T::Currency::withdraw(&sender, T::SlotRenewingCost::get(), WithdrawReasons::all(), ExistenceRequirement::AllowDeath) { Ok(imbalance) => T::FundsCollector::on_unbalanced(imbalance), Err(_) => Err(Error::<T>::NotEnoughFunds)?, }; slot.renewed = <system::Module<T>>::block_number(); <Slots<T>>::insert(&certificate, slot); Self::deposit_event(RawEvent::SlotRenewed(certificate)); Ok(()) } fn revoke_slot(origin, certificate: T::CertificateId) -> DispatchResult { let sender = ensure_signed(origin)?; let mut slot = <Slots<T>>::get(&certificate); ensure!(Self::is_slot_valid(&slot), Error::<T>::NoLongerValid); ensure!(slot.owner == sender, Error::<T>::NotTheOwner); slot.revoked = true; <Slots<T>>::insert(&certificate, slot); Self::deposit_event(RawEvent::SlotRevoked(certificate)); Ok(()) } fn revoke_child(origin, root: T::CertificateId, child: T::CertificateId) -> DispatchResult { let sender = ensure_signed(origin)?; let mut slot = <Slots<T>>::get(&root); ensure!(Self::is_slot_valid(&slot), Error::<T>::NoLongerValid); ensure!(slot.owner == sender, Error::<T>::NotTheOwner); ensure!(!slot.child_revocations.contains(&child), Error::<T>::NoLongerValid); slot.child_revocations.push(child.clone()); <Slots<T>>::insert(&root, slot); Self::deposit_event(RawEvent::ChildSlotRevoked(root, child)); Ok(()) } } } impl<T: Trait> Module<T> { fn is_member(who: &T::AccountId) -> bool { Self::members().contains(who) } fn is_slot_valid( slot: &RootCertificate<T::AccountId, T::CertificateId, T::BlockNumber>, ) -> bool { let owner_is_member = Self::is_member(&slot.owner); let revoked = slot.revoked; let expired = slot.renewed + slot.validity <= <system::Module<T>>::block_number(); owner_is_member && !revoked && !expired } #[allow(dead_code)] pub fn is_root_certificate_valid(cert: &T::CertificateId) -> bool { let exists = <Slots<T>>::contains_key(cert); let slot = <Slots<T>>::get(cert); exists && Self::is_slot_valid(&slot) } #[allow(dead_code)]
} impl<T: Trait> ChangeMembers<T::AccountId> for Module<T> { fn change_members_sorted( _incoming: &[T::AccountId], _outgoing: &[T::AccountId], new: &[T::AccountId], ) { <Members<T>>::put(new); } }
pub fn is_child_certificate_valid(root: &T::CertificateId, child: &T::CertificateId) -> bool { let equals = root == child; let root_valid = Self::is_root_certificate_valid(root); let revoked = <Slots<T>>::get(root).child_revocations.contains(child); !equals && root_valid && !revoked }
function_block-full_function
[ { "content": "#[test]\n\nfn child_certificate_not_valid_if_revoked_in_root_certificate() {\n\n new_test_ext().execute_with(|| {\n\n allocate_balances();\n\n do_register();\n\n\n\n let now = <system::Module<Test>>::block_number();\n\n <Slots<Test>>::insert(\n\n &OFFCHAIN...
Rust
src/particle.rs
n3f4s/particule_generator
731ee8d834f5a458b3ee78b7849b60ccb81d659b
use vec3d::Vec3; use point3d::Point3; use drawable::Drawable; use sdl2::render::Canvas; use sdl2::video::Window; use sdl2::surface::Surface; use sdl2::gfx::primitives::DrawRenderer; static PARTICLE_DENSITY : f64 = 1.0; #[derive(Debug, Default, PartialEq, Copy, Clone)] pub struct Particle { position: Point3<i16>, direction: Vec3<i16>, alive: bool, lifetime: u64, max_lifetime: u64, radius: i16, mass: f64 } impl Particle { pub fn new(p: Point3<i16>, d: Vec3<i16>) -> Particle { Particle { position: p, direction: d, alive: true, lifetime: 250, max_lifetime: 250, radius: 5, mass: 5.0 * PARTICLE_DENSITY } } pub fn set_position(&mut self, pos: Point3<i16>) { self.position = pos; } pub fn is_alive(&self) -> bool { self.alive } pub fn get_position(&self) -> Point3<i16> { self.position } pub fn get_direction(&self) -> Vec3<i16> { self.direction } pub fn get_lifetime(&self) -> u64 { self.lifetime } pub fn get_radius(&self) -> i16 { self.radius } pub fn get_mass(&self) -> f64 { self.mass } pub fn copy(&self) -> Particle { Particle { position: self.position, direction: self.direction, alive: self.alive, lifetime: self.lifetime, max_lifetime: self.max_lifetime, radius: self.radius, mass: self.mass } } pub fn update(&mut self) { if self.alive { self.position.apply_vec(self.direction/10.0); self.lifetime -= 1; if self.lifetime == 0 { self.alive = false; } } } pub fn apply_force(&mut self, f: Vec3<i16>) { self.direction += f } pub fn kill(&mut self) { self.alive = false; } fn compute_alpha(&self) -> u8 { ((self.lifetime as f64) / (self.max_lifetime as f64) * (self.lifetime as f64) / (self.max_lifetime as f64) * 255.0) as u8 } fn compute_green(&self) -> u8 { ( ( 1.0 - (((self.lifetime as f64) / (self.max_lifetime as f64) ) * ( (self.lifetime as f64) / (self.max_lifetime as f64))) ) * 255.0 ) as u8 } fn change_radius(&mut self, rad: i16) { self.radius = rad; self.mass = (rad as f64) * PARTICLE_DENSITY; } } impl Drawable for Particle { fn draw_surface(&self, c: &mut Canvas<Surface>) { c.filled_circle(self.position.x as i16, self.position.y as i16, self.radius, (255, self.compute_green(), 0, self.compute_alpha())).unwrap(); } fn draw_window(&self, c: &mut Canvas<Window>) { c.filled_circle(self.position.x as i16, self.position.y as i16, self.radius, (255, self.compute_green(), 0, self.compute_alpha())).unwrap(); } } pub struct ParticleBuilder { template: Particle } impl<'a> ParticleBuilder { pub fn new(start_pos: Point3<i16>, start_dir: Vec3<i16>) -> ParticleBuilder { ParticleBuilder { template: Particle::new(start_pos, start_dir) } } pub fn with_radius(&'a mut self, radius: i16) -> &'a mut ParticleBuilder { self.template.change_radius(radius); self } pub fn with_lifetime(&'a mut self, lifetime: u64) -> &'a mut ParticleBuilder { self.template.max_lifetime = lifetime; self.template.lifetime = lifetime; self } pub fn create(&self) -> Particle { self.template.clone() } }
use vec3d::Vec3; use point3d::Point3; use drawable::Drawable; use sdl2::render::Canvas; use sdl2::video::Window; use sdl2::surface::Surface; use sdl2::gfx::primitives::DrawRenderer; static PARTICLE_DENSITY : f64 = 1.0; #[derive(Debug, Default, PartialEq, Copy, Clone)] pub struct Particle { position: Point3<i16>, direction: Vec3<i16>, alive: bool, lifetime: u64, max_lifetime: u64, radius: i16, mass: f64 } impl Particle { pub fn new(p: Point3<i16>, d: Vec3<i16>) -> Particle { Particle { position: p, direction: d, alive: true, li
pub fn set_position(&mut self, pos: Point3<i16>) { self.position = pos; } pub fn is_alive(&self) -> bool { self.alive } pub fn get_position(&self) -> Point3<i16> { self.position } pub fn get_direction(&self) -> Vec3<i16> { self.direction } pub fn get_lifetime(&self) -> u64 { self.lifetime } pub fn get_radius(&self) -> i16 { self.radius } pub fn get_mass(&self) -> f64 { self.mass } pub fn copy(&self) -> Particle { Particle { position: self.position, direction: self.direction, alive: self.alive, lifetime: self.lifetime, max_lifetime: self.max_lifetime, radius: self.radius, mass: self.mass } } pub fn update(&mut self) { if self.alive { self.position.apply_vec(self.direction/10.0); self.lifetime -= 1; if self.lifetime == 0 { self.alive = false; } } } pub fn apply_force(&mut self, f: Vec3<i16>) { self.direction += f } pub fn kill(&mut self) { self.alive = false; } fn compute_alpha(&self) -> u8 { ((self.lifetime as f64) / (self.max_lifetime as f64) * (self.lifetime as f64) / (self.max_lifetime as f64) * 255.0) as u8 } fn compute_green(&self) -> u8 { ( ( 1.0 - (((self.lifetime as f64) / (self.max_lifetime as f64) ) * ( (self.lifetime as f64) / (self.max_lifetime as f64))) ) * 255.0 ) as u8 } fn change_radius(&mut self, rad: i16) { self.radius = rad; self.mass = (rad as f64) * PARTICLE_DENSITY; } } impl Drawable for Particle { fn draw_surface(&self, c: &mut Canvas<Surface>) { c.filled_circle(self.position.x as i16, self.position.y as i16, self.radius, (255, self.compute_green(), 0, self.compute_alpha())).unwrap(); } fn draw_window(&self, c: &mut Canvas<Window>) { c.filled_circle(self.position.x as i16, self.position.y as i16, self.radius, (255, self.compute_green(), 0, self.compute_alpha())).unwrap(); } } pub struct ParticleBuilder { template: Particle } impl<'a> ParticleBuilder { pub fn new(start_pos: Point3<i16>, start_dir: Vec3<i16>) -> ParticleBuilder { ParticleBuilder { template: Particle::new(start_pos, start_dir) } } pub fn with_radius(&'a mut self, radius: i16) -> &'a mut ParticleBuilder { self.template.change_radius(radius); self } pub fn with_lifetime(&'a mut self, lifetime: u64) -> &'a mut ParticleBuilder { self.template.max_lifetime = lifetime; self.template.lifetime = lifetime; self } pub fn create(&self) -> Particle { self.template.clone() } }
fetime: 250, max_lifetime: 250, radius: 5, mass: 5.0 * PARTICLE_DENSITY } }
function_block-function_prefixed
[ { "content": "pub fn dot(v1: &Vec3, v2: &Vec3) -> f64 {\n\n v1.x * v2.x + v1.y * v2.y + v1.z * v2.z\n\n}\n\n\n", "file_path": "src/vec3.rs", "rank": 0, "score": 83669.11190807322 }, { "content": "pub fn unit_vector(v: Vec3) -> Vec3 {\n\n let mut tmp = v;\n\n tmp.make_unit();\n\n ...
Rust
src/keychain/mod.rs
mikelodder7/keychain-services.rs
6c68371b199d9d450d185681d80720ed4561b8d0
pub mod item; pub mod key; use self::item::MatchLimit; pub use self::{item::Item, key::Key}; use crate::dictionary::*; use crate::error::Error; use crate::ffi::*; use core_foundation::base::{CFTypeRef, TCFType}; use std::{ffi::CString, os::raw::c_char, os::unix::ffi::OsStrExt, path::Path, ptr}; declare_TCFType! { Keychain, KeychainRef } impl_TCFType!(Keychain, KeychainRef, SecKeychainGetTypeID); impl Keychain { pub fn find_default() -> Result<Keychain, Error> { let mut result: KeychainRef = ptr::null_mut(); let status = unsafe { SecKeychainCopyDefault(&mut result) }; if let Some(e) = Error::maybe_from_OSStatus(status) { Err(e) } else { Ok(unsafe { Keychain::wrap_under_create_rule(result) }) } } pub fn create(path: &Path, password: Option<&str>) -> Result<Keychain, Error> { let path_cstring = CString::new(path.as_os_str().as_bytes()).unwrap(); let mut result: KeychainRef = ptr::null_mut(); let status = match password { Some(pw) => unsafe { SecKeychainCreate( path_cstring.as_ptr() as *const c_char, pw.len() as u32, pw.as_bytes().as_ptr() as *const c_char, false, ptr::null(), &mut result, ) }, None => unsafe { SecKeychainCreate( path_cstring.as_ptr() as *const c_char, 0, ptr::null(), true, ptr::null(), &mut result, ) }, }; if let Some(e) = Error::maybe_from_OSStatus(status) { Err(e) } else { Ok(unsafe { Keychain::wrap_under_create_rule(result) }) } } pub fn delete(self) -> Result<(), Error> { let status = unsafe { SecKeychainDelete(self.as_concrete_TypeRef()) }; if let Some(e) = Error::maybe_from_OSStatus(status) { Err(e) } else { Ok(()) } } fn find_item(&self, mut attrs: DictionaryBuilder) -> Result<Item, Error> { attrs.add(unsafe { kSecMatchLimit }, &MatchLimit::One.as_CFType()); attrs.add_boolean(unsafe { kSecReturnRef }, true); let mut result: ItemRef = ptr::null_mut(); let status = unsafe { SecItemCopyMatching( Dictionary::from(attrs).as_concrete_TypeRef(), &mut result as &mut CFTypeRef, ) }; if let Some(e) = Error::maybe_from_OSStatus(status) { return Err(e); } Ok(unsafe { Item::wrap_under_create_rule(result) }) } fn add_item(&self, mut attrs: DictionaryBuilder) -> Result<Item, Error> { attrs.add(unsafe { kSecUseKeychain }, self); attrs.add_boolean(unsafe { kSecReturnRef }, true); let mut result: ItemRef = ptr::null_mut(); let status = unsafe { SecItemAdd(Dictionary::from(attrs).as_concrete_TypeRef(), &mut result) }; if let Some(e) = Error::maybe_from_OSStatus(status) { Err(e) } else { Ok(unsafe { Item::wrap_under_create_rule(result) }) } } } impl Default for Keychain { fn default() -> Keychain { Self::find_default().expect("no default keychain available") } }
pub mod item; pub mod key; use self::item::MatchLimit; pub use self::{item::Item, key::Key}; use crate::dictionary::*; use crate::error::Error; use crate::ffi::*; use core_foundation::base::{CFTypeRef, TCFType}; use std::{ffi::CString, os::raw::c_char, os::unix::ffi::OsStrExt, path::Path, ptr}; declare_TCFType! { Keychain, KeychainRef } impl_TCFType!(Keychain, KeychainRef, SecKeychainGetTypeID); impl Keychain { pub fn find_default() -> Result<Keychain, Error> { let mut result: KeychainRef = ptr::null_mut(); let status = unsafe { SecKeychainCopyDefault(&mut result) }; if let Some(e) = Error::maybe_from_OSStatus(status) { Err(e) } else { Ok(unsafe { Keychain::wrap_under_create_rule(result) }) } } pub fn create(path: &Path, password: Option<&str>) -> Result<Keychain, Error> { let path_cstring = CString::new(path.as_os_str().as_bytes()).unwrap(); let mut result: KeychainRef = ptr::null_mut(); let status = match password { Some(pw) => unsafe { SecKeychainCreate( path_cstring.as_ptr() as *const c_char, pw.len() as u32, pw.as_bytes().as_ptr() as *const c_char, false, ptr::null(), &mut result, ) }, None => unsafe { SecKeychainCreate( path_cstring.as_ptr() as *const c_char, 0, ptr::null(), true, ptr::null(), &mut result, ) }, }; if let Some(e) = Error::maybe_from_OSStatus(status) { Err(e) } else { Ok(unsafe { Keychain::wrap_under_create_rule(result) }) } } pub fn delete(self) -> Result<(), Error> { let status = unsafe { SecKeychainDelete(self.as_concrete_TypeRef()) }; if let Some(e) = Error::maybe_from_OSStatus(status) { Err(e) } else { Ok(()) } } fn find_item(&self, mut attrs: DictionaryBuilder) -> Result<Item, Error> { attrs.add(unsafe { kSecMatchLimit }, &MatchLimit::One.as_CFType()); attrs.add_boolean(unsafe { kSecReturnRef }, true); let mut result: ItemRef = ptr::null_mut(); let status = unsafe { SecItemCopyMatching( Dictionary::from(attrs).as_concrete_TypeRef(), &mut result as &mut CFTypeRef,
unsafe { SecItemAdd(Dictionary::from(attrs).as_concrete_TypeRef(), &mut result) }; if let Some(e) = Error::maybe_from_OSStatus(status) { Err(e) } else { Ok(unsafe { Item::wrap_under_create_rule(result) }) } } } impl Default for Keychain { fn default() -> Keychain { Self::find_default().expect("no default keychain available") } }
) }; if let Some(e) = Error::maybe_from_OSStatus(status) { return Err(e); } Ok(unsafe { Item::wrap_under_create_rule(result) }) } fn add_item(&self, mut attrs: DictionaryBuilder) -> Result<Item, Error> { attrs.add(unsafe { kSecUseKeychain }, self); attrs.add_boolean(unsafe { kSecReturnRef }, true); let mut result: ItemRef = ptr::null_mut(); let status =
random
[ { "content": "#[test]\n\nfn generate_and_use_rsa_keys() {\n\n let acl =\n\n AccessControl::create_with_flags(AttrAccessible::WhenUnlocked, Default::default()).unwrap();\n\n\n\n let generate_params = KeyPairGenerateParams::new(AttrKeyType::Rsa, 2048).access_control(&acl);\n\n\n\n let keypair = Ke...
Rust
kailua_types/src/ty/tag.rs
nxgtri/kailua
17eb0750ff8bbe4237d75f31f9b8aa23170c3c28
use std::fmt; use kailua_env::Spanned; use kailua_diag::{Result, Reporter}; use kailua_syntax::ast::{Attr, AttrValue}; use super::{Display, DisplayState, TypeResolver, ClassSystemId}; use message as m; #[derive(Copy, Clone, PartialEq, Eq)] pub enum Tag { #[doc(hidden)] _Subtype, #[doc(hidden)] _NoSubtype, #[doc(hidden)] _NoSubtype2, Require, Type, Assert, AssertNot, AssertType, GenericPairs, GlobalEnv, GlobalEval, BecomeModule, PackagePath, PackageCpath, StringMeta, MakeClass(ClassSystemId), KailuaGenTvar, KailuaAssertTvar, } impl Tag { pub fn from(attr: &Attr, resolv: &mut TypeResolver) -> Result<Option<Tag>> { let no_values = |resolv: &mut TypeResolver, tag| { if let Some(ref values) = attr.values { resolv.error(values, m::AttrCannotHaveAnyValues { name: &attr.name }).done()?; } Ok(Some(tag)) }; let values = |resolv: &mut TypeResolver, count| { if let Some(ref values) = attr.values { if values.len() != count { resolv.error(values, m::AttrRequiresFixedNumOfValues { name: &attr.name, count: count }) .done()?; } Ok(&values[..]) } else { resolv.error(&attr.name, m::AttrRequiresFixedNumOfValues { name: &attr.name, count: count }) .done()?; const EMPTY: &'static [Spanned<AttrValue>] = &[]; Ok(EMPTY) } }; match &attr.name.base[..] { b"internal subtype" => no_values(resolv, Tag::_Subtype), b"internal no_subtype" => no_values(resolv, Tag::_NoSubtype), b"internal no_subtype2" => no_values(resolv, Tag::_NoSubtype2), b"require" => no_values(resolv, Tag::Require), b"type" => no_values(resolv, Tag::Type), b"assert" => no_values(resolv, Tag::Assert), b"assert_not" => no_values(resolv, Tag::AssertNot), b"assert_type" => no_values(resolv, Tag::AssertType), b"generic_pairs" => no_values(resolv, Tag::GenericPairs), b"genv" => no_values(resolv, Tag::GlobalEnv), b"geval" => no_values(resolv, Tag::GlobalEval), b"become_module" => no_values(resolv, Tag::BecomeModule), b"package_path" => no_values(resolv, Tag::PackagePath), b"package_cpath" => no_values(resolv, Tag::PackageCpath), b"string_meta" => no_values(resolv, Tag::StringMeta), b"make_class" => { let values = values(resolv, 1)?; if let Some(&AttrValue::Name(ref system)) = values.get(0).map(|v| &v.base) { if let Some(system) = resolv.class_system_from_name(system)? { return Ok(Some(Tag::MakeClass(system))); } } Ok(None) }, b"internal kailua_gen_tvar" => no_values(resolv, Tag::KailuaGenTvar), b"internal kailua_assert_tvar" => no_values(resolv, Tag::KailuaAssertTvar), _ => { resolv.warn(&attr.name, m::UnknownAttrName { name: &attr.name.base }).done()?; Ok(None) } } } pub fn name(&self) -> &'static str { match *self { Tag::Require => "require", Tag::Type => "type", Tag::Assert => "assert", Tag::AssertNot => "assert_not", Tag::AssertType => "assert_type", Tag::GenericPairs => "generic_pairs", Tag::GlobalEnv => "genv", Tag::GlobalEval => "geval", Tag::BecomeModule => "become_module", Tag::PackagePath => "package_path", Tag::PackageCpath => "package_cpath", Tag::StringMeta => "string_meta", Tag::MakeClass(_) => "make_class", Tag::_Subtype => "internal subtype", Tag::_NoSubtype => "internal no_subtype", Tag::_NoSubtype2 => "internal no_subtype2", Tag::KailuaGenTvar => "internal kailua_gen_tvar", Tag::KailuaAssertTvar => "internal kailua_assert_tvar", } } pub fn scope_local(&self) -> bool { match *self { Tag::Type | Tag::Assert | Tag::AssertNot | Tag::AssertType | Tag::GenericPairs | Tag::MakeClass(_) | Tag::KailuaGenTvar | Tag::KailuaAssertTvar => true, _ => false, } } pub fn needs_subtype(&self) -> bool { match *self { Tag::_Subtype => true, Tag::_NoSubtype => false, Tag::_NoSubtype2 => false, Tag::PackagePath | Tag::PackageCpath => false, _ => true, } } } impl fmt::Debug for Tag { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.name())?; match *self { Tag::MakeClass(csid) => { write!(f, "({:?})", csid)?; } _ => {} } Ok(()) } } impl Display for Tag { fn fmt_displayed(&self, f: &mut fmt::Formatter, st: &DisplayState) -> fmt::Result { write!(f, "{}", self.name())?; match *self { Tag::MakeClass(csid) => { write!(f, "(")?; st.context.fmt_class_system_name(csid, f, st)?; write!(f, ")")?; } _ => {} } Ok(()) } }
use std::fmt; use kailua_env::Spanned; use kailua_diag::{Result, Reporter}; use kailua_syntax::ast::{Attr, AttrValue}; use super::{Display, DisplayState, TypeResolver, ClassSystemId}; use message as m; #[derive(Copy, Clone, PartialEq, Eq)] pub enum Tag { #[doc(hidden)] _Subtype, #[doc(hidden)] _NoSubtype, #[doc(hidden)] _NoSubtype2, Require, Type, Assert, AssertNot, AssertType, GenericPairs, GlobalEnv, GlobalEval, BecomeModule, PackagePath, PackageCpath, StringMeta, MakeClass(ClassSystemId), KailuaGenTvar, KailuaAssertTvar, } impl Tag { pub fn from(attr: &Attr, resolv: &mut TypeResolver) -> Result<Option<Tag>> { let no_values = |resolv: &mut TypeResolver, tag| { if let Some(ref values) = attr.values { resolv.error(values, m::AttrCannotHaveAnyValues { name: &attr.name }).done()?; } Ok(Some(tag)) }; let values = |resolv: &mut TypeResolver, count| { if let Some(ref values) = attr.values { if values.len() != count { resolv.error(values, m::AttrRequiresFixedNumOfValues { name: &attr.name, count: count }) .done()?; } Ok(&values[..]) } else { resolv.error(&attr.name, m::AttrRequiresFixedNumOfValues { name: &attr.name, count: count }) .done()?; const EMPTY: &'static [Spanned<AttrValue>] = &[]; Ok(EMPTY) } }; match &attr.name.base[..] { b"internal subtype" => no_values(resolv, Tag::_Subtype), b"internal no_subtype" => no_values(resolv, Tag::_NoSubtype), b"internal no_subtype2" => no_values(resolv, Tag::_NoSubtype2), b"require" => no_values(resolv, Tag::Require), b"type" => no_values(resolv, Tag::Type), b"assert" => no_values(resolv, Tag::Assert), b"assert_not" => no_values(resolv, Tag::AssertNot), b"assert_type" => no_values(resolv, Tag::AssertType), b"generic_pairs" => no_values(resolv, Tag::GenericPairs), b"genv" => no_values(resolv, Tag::GlobalEnv), b"geval" => no_values(resolv, Tag::GlobalEval), b"become_module" => no_values(resolv, Tag::BecomeModule), b"package_path" => no_values(resolv, Tag::PackagePath), b"package_cpath" => no_values(resolv, Tag::PackageCpath), b"string_meta" => no_values(resolv, Tag::StringMeta), b"make_class" => { let values = values(resolv, 1)?; if let Some(&AttrValue::Name(ref system)) = values.get(0).map(|v| &v.base) { if let Some(system) = resolv.class_system_from_name(system)? { return Ok(Some(Tag::MakeClass(system))); } } Ok(None) }, b"internal kailua_gen_tvar" => no_values(resolv, Tag::KailuaGenTvar), b"internal kailua_assert_tvar" => no_values(resolv, Tag::KailuaAssertTvar), _ => { resolv.warn(&attr.name, m::UnknownAttrName { name: &attr.name.base }).done()?; Ok(None) } } } pub fn name(&self) -> &'static str { match *self { Tag::Require => "require", Tag::Type => "type", Tag::Assert => "assert", Tag::AssertNot => "assert_not", Tag::AssertType => "assert_type", Tag::GenericPairs => "generic_pairs", Tag::GlobalEnv => "genv", Tag::GlobalEval => "geval", Tag::BecomeModule => "become_module", Tag::PackagePath => "package_path", Tag::PackageCpath => "package_cpath", Tag::StringMeta => "string_meta", Tag::MakeClass(_) => "make_class", Tag::_Subtype => "internal subtype", Tag::_NoSubtype => "internal no_subtype", Tag::_NoSubtype2 => "internal no_subtype2", Tag::KailuaGenTvar => "internal kailua_gen_tvar", Tag::KailuaAssertTvar => "internal kailua_assert_tvar", } }
pub fn needs_subtype(&self) -> bool { match *self { Tag::_Subtype => true, Tag::_NoSubtype => false, Tag::_NoSubtype2 => false, Tag::PackagePath | Tag::PackageCpath => false, _ => true, } } } impl fmt::Debug for Tag { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.name())?; match *self { Tag::MakeClass(csid) => { write!(f, "({:?})", csid)?; } _ => {} } Ok(()) } } impl Display for Tag { fn fmt_displayed(&self, f: &mut fmt::Formatter, st: &DisplayState) -> fmt::Result { write!(f, "{}", self.name())?; match *self { Tag::MakeClass(csid) => { write!(f, "(")?; st.context.fmt_class_system_name(csid, f, st)?; write!(f, ")")?; } _ => {} } Ok(()) } }
pub fn scope_local(&self) -> bool { match *self { Tag::Type | Tag::Assert | Tag::AssertNot | Tag::AssertType | Tag::GenericPairs | Tag::MakeClass(_) | Tag::KailuaGenTvar | Tag::KailuaAssertTvar => true, _ => false, } }
function_block-full_function
[ { "content": "pub fn get_defs(name: &str) -> Option<&'static [Def]> {\n\n match name {\n\n \"lua51\" => Some(LUA51_DEFS),\n\n \"lua51_base\" => Some(LUA51_BASE_DEFS),\n\n \"lua51_package\" => Some(LUA51_PACKAGE_DEFS),\n\n \"lua51_string\" => Some(LUA51_STRING_DEFS),\n\...
Rust
src/api/reddit/repository.rs
tigorlazuardi/ridit-rs
bae8b50db3237df03e925048bf5c5eb6d575b2af
use std::{convert::TryInto, path::PathBuf, sync::Arc, time::Duration, usize}; use anyhow::{bail, Context, Error, Result}; use imagesize::blob_size; use reqwest::{header::RANGE, Client, Response}; use tokio::{ fs::{self, File}, io::AsyncWriteExt, sync::{mpsc::UnboundedSender, Semaphore}, }; use tokio_retry::{ strategy::{jitter, FixedInterval}, Retry, }; use super::models::{download_meta::DownloadMeta, download_status::DownloadStatus}; use crate::api::{ config::{config::Config, configuration::Subreddit}, reddit::models::{error::RedditError, listing::Listing}, }; #[derive(Clone, Debug)] pub struct Repository { client: Arc<Client>, config: Arc<Config>, semaphore: Arc<Semaphore>, } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum PrintOut { Bar, Text, None, } static APP_USER_AGENT: &str = concat!( "id.web.tigor.", env!("CARGO_PKG_NAME"), "/v", env!("CARGO_PKG_VERSION"), " (by /u/CrowFX)" ); impl Repository { pub fn new(config: Arc<Config>) -> Self { let os = std::env::consts::OS; let user_agent = os.to_string() + ":" + APP_USER_AGENT; let client = reqwest::Client::builder() .user_agent(user_agent) .connect_timeout(Duration::from_secs(config.timeout.into())) .build() .context("failed to create request client") .unwrap(); let semaphore = Arc::new(Semaphore::new(config.download_threads)); Self { client: Arc::new(client), config, semaphore, } } pub async fn download( &self, display: PrintOut, progress: UnboundedSender<DownloadStatus>, ) -> Vec<(DownloadMeta, Result<(), Error>)> { let mut handlers = Vec::new(); for (_, subreddit) in &self.config.subreddits { let this = self.clone(); let subreddit = subreddit.clone(); let progress = progress.clone(); let handle = tokio::spawn(async move { Ok::<_, Error>(this.exec_download(subreddit, display, progress).await?) }); handlers.push(handle); } let mut v = Vec::new(); for handle in handlers { match handle.await.unwrap() { Ok(vec) => v.extend(vec), Err(err) => println!("{:?}", err), } } v } async fn exec_download( &self, subreddit: Subreddit, display: PrintOut, progress: UnboundedSender<DownloadStatus>, ) -> Result<Vec<(DownloadMeta, Result<(), Error>)>> { let print = || { println!("{} downloading listing", subreddit.padded_proper_name()); }; match display { PrintOut::None => {} _ => print(), } let downloads = self.download_listing(&subreddit).await?; Ok(self.download_images(downloads, subreddit, progress).await) } async fn download_images( &self, downloads: Vec<DownloadMeta>, subreddit: Subreddit, progress: UnboundedSender<DownloadStatus>, ) -> Vec<(DownloadMeta, Result<(), Error>)> { let mut handlers = Vec::new(); 'meta: for mut meta in downloads.into_iter() { for profile in &meta.profile { if self.file_exists(profile, &meta).await { continue 'meta; } } let this = self.clone(); let sem = self.semaphore.clone(); let subreddit = subreddit.clone(); let progress = progress.clone(); let handle = tokio::spawn(async move { let _x = sem.acquire().await.unwrap(); let op = this.download_image(&mut meta, subreddit, progress).await; (meta, op) }); handlers.push(handle); } let mut v = Vec::new(); for handle in handlers { v.push(handle.await.unwrap()); } v } async fn download_listing(&self, subreddit: &Subreddit) -> Result<Vec<DownloadMeta>> { let listing_url = format!( "https://reddit.com/r/{}/{}.json?limit=100", subreddit.proper_name, subreddit.sort ); let retry_strategy = FixedInterval::from_millis(100).map(jitter).take(3); let resp: Response = Retry::spawn(retry_strategy, || async { let res = self.client.get(&listing_url).send().await?; Ok::<Response, Error>(res) }) .await .with_context(|| { format!( "failed to open connection to download listing from: {}", listing_url ) })?; if !resp.status().is_success() { let err = resp.json::<RedditError>().await.with_context(|| { format!("failed to deserialize json body from: {}", listing_url) })?; bail!( "downloading listing from [{}] give error: {}", subreddit.proper_name, err ); } let listing: Listing = resp .json() .await .with_context(|| format!("failed to deserialize json body from: {}", listing_url))?; Ok(listing.into_download_metas(&self.config)) } async fn download_image( &self, meta: &mut DownloadMeta, subreddit: Subreddit, progress: UnboundedSender<DownloadStatus>, ) -> Result<()> { if subreddit.download_first { self.poke_image_size(meta).await?; let mut should_continue = false; for (profile, setting) in self.config.iter() { if !meta.passed_checks(setting) { continue; } if self.file_exists(profile, meta).await { continue; } should_continue = true; meta.profile.push(profile.to_owned()); } if !should_continue { return Ok(()); } } let retry_strategy = FixedInterval::from_millis(100).map(jitter).take(3); let response: Response = Retry::spawn(retry_strategy, || async { let res = self.client.get(&meta.url).send().await?; Ok::<Response, Error>(res) }) .await .with_context(|| { format!( "failed to open connection to download image from: {}", meta.url ) })?; let status = response.status(); if !status.is_success() { bail!(format!( "download from {} gives [{}: {}] status code", meta.url, status.as_u16(), status.canonical_reason().unwrap_or("Unknown Reason"), )); } self.ensure_download_dir(meta).await?; let temp_file = self.store_to_temp(response, meta, progress).await?; for profile in &meta.profile { let download_location = self.download_location(profile, meta); fs::copy(&temp_file, &download_location) .await .with_context(|| { format!( "failed to copy file from tmp dir to {}", download_location.display() ) })?; let dir_path = std::env::temp_dir() .join("ridit") .join(&meta.subreddit_name) .join(&meta.filename); fs::remove_file(&dir_path).await.with_context(|| { format!( "failed to remove temp downloaded file {}", download_location.display() ) })?; } Ok(()) } async fn ensure_download_dir(&self, meta: &DownloadMeta) -> Result<()> { for profile in &meta.profile { let download_dir = self.config.path.join(profile).join(&meta.subreddit_name); fs::create_dir_all(&download_dir).await.with_context(|| { format!( "failed to create download directory on: {}", download_dir.display() ) })?; } Ok(()) } async fn poke_image_size(&self, meta: &mut DownloadMeta) -> Result<()> { const LIMIT: usize = 1024 * 2 * 10; let retry_strategy = FixedInterval::from_millis(100).map(jitter).take(3); let mut resp = Retry::spawn(retry_strategy, || async { let res = self .client .get(&meta.url) .header(RANGE, LIMIT) .send() .await?; Ok::<Response, Error>(res) }) .await .with_context(|| { format!( "failed to partial download an image to get image size from: {}", meta.url ) })?; let mut data: Vec<u8> = Vec::new(); while let Some(chunk) = resp.chunk().await? { data.append(&mut chunk.to_vec()); if data.len() >= LIMIT { break; } } let size = blob_size(&data) .with_context(|| format!("error getting image dimension from: {}", meta.url))?; meta.image_height = size .height .try_into() .with_context(|| "image height is too big to process")?; meta.image_width = size .width .try_into() .with_context(|| "image width is too big to process")?; Ok(()) } fn download_dir(&self, profile: &str, meta: &DownloadMeta) -> PathBuf { self.config.path.join(profile).join(&meta.subreddit_name) } fn download_location(&self, profile: &str, meta: &DownloadMeta) -> PathBuf { self.download_dir(profile, meta).join(&meta.filename) } async fn file_exists(&self, profile: &str, meta: &DownloadMeta) -> bool { fs::metadata(self.download_location(profile, meta)) .await .is_ok() } async fn store_to_temp( &self, mut resp: Response, meta: &DownloadMeta, progress: UnboundedSender<DownloadStatus>, ) -> Result<PathBuf> { let dir_path = std::env::temp_dir() .join("ridit") .join(&meta.subreddit_name); fs::create_dir_all(&dir_path).await?; let file_path = dir_path.join(&meta.filename); let mut file = File::create(&file_path) .await .context("cannot create file on tmp dir")?; let download_length = resp.content_length().unwrap_or(0); progress .send(meta.as_download_status(download_length, 0)) .unwrap(); while let Some(chunk) = resp.chunk().await? { progress .send(meta.as_download_status(download_length, chunk.len().try_into().unwrap())) .unwrap(); if let Err(err) = file.write(&chunk).await { progress .send( meta.as_download_status(download_length, chunk.len().try_into().unwrap()) .with_error(err.to_string()), ) .unwrap(); bail!("failed to save image from {}. cause: {}", meta.url, err) } } progress .send(meta.as_download_status(download_length, 0).set_finished()) .unwrap(); Ok(file_path) } pub async fn subreddit_exist(subreddit: &mut String) -> Result<bool> { let url = format!("https://reddit.com/r/{}.json", subreddit); let retry_strategy = FixedInterval::from_millis(100).map(jitter).take(3); let resp: Response = Retry::spawn(retry_strategy, || async { let res = reqwest::get(&url).await?; Ok::<Response, Error>(res) }) .await .with_context(|| format!("failed to check subreddit {}", subreddit))?; let listing: Listing = resp .json() .await .with_context(|| format!("failed to deserialize json body from: {}", url))?; match listing.data.children.get(0) { Some(v) => { subreddit.clear(); subreddit.push_str(&v.data.subreddit); Ok(true) } None => Ok(false), } } }
use std::{convert::TryInto, path::PathBuf, sync::Arc, time::Duration, usize}; use anyhow::{bail, Context, Error, Result}; use imagesize::blob_size; use reqwest::{header::RANGE, Client, Response}; use tokio::{ fs::{self, File}, io::AsyncWriteExt, sync::{mpsc::UnboundedSender, Semaphore}, }; use tokio_retry::{ strategy::{jitter, FixedInterval}, Retry, }; use super::models::{download_meta::DownloadMeta, download_status::DownloadStatus}; use crate::api::{ config::{config::Config, configuration::Subreddit}, reddit::models::{error::RedditError, listing::Listing}, }; #[derive(Clone, Debug)] pub struct Repository { client: Arc<Client>, config: Arc<Config>, semaphore: Arc<Semaphore>, } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum PrintOut { Bar, Text, None, } static APP_USER_AGENT: &str = concat!( "id.web.tigor.", env!("CARGO_PKG_NAME"), "/v", env!("CARGO_PKG_VERSION"), " (by /u/CrowFX)" ); impl Repository { pub fn new(config: Arc<Config>) -> Self { let os = std::env::consts::OS; let user_agent = os.to_string() + ":" + APP_USER_AGENT; let client = reqwest::Client::builder() .user_agent(user_agent) .connect_timeout(Duration::from_secs(config.timeout.into())) .build() .context("failed to create request client") .unwrap(); let semaphore = Arc::new(Semaphore::new(config.download_threads)); Self { client: Arc::new(client), config, semaphore, } } pub async fn download( &self, display: PrintOut, progress: UnboundedSender<DownloadStatus>, ) -> Vec<(DownloadMeta, Result<(), Error>)> { let mut handlers = Vec::new(); for (_, subreddit) in &self.config.subreddits { let this = self.clone(); let subreddit = subreddit.clone(); let progress = progress.clone(); let handle = tokio::spawn(async move { Ok::<_, Error>(this.exec_download(subreddit, display, progress).await?) }); handlers.push(handle); } let mut v = Vec::new(); for handle in handlers { match handle.await.unwrap() { Ok(vec) => v.extend(vec), Err(err) => println!("{:?}", err), } } v } async fn exec_download( &self, subreddit: Subreddit, display: PrintOut, progress: UnboundedSender<DownloadStatus>, ) -> Result<Vec<(DownloadMeta, Result<(), Error>)>> { let print = || { println!("{} downloading listing", subreddit.padded_proper_name()); }; match display { PrintOut::None => {} _ => print(), } let downloads = self.download_listing(&subreddit).await?; Ok(self.download_images(downloads, subreddit, progress).await) } async fn download_images( &self, downloads: Vec<DownloadMeta>, subreddit: Subreddit, progress: UnboundedSender<DownloadStatus>, ) -> Vec<(DownloadMeta, Result<(), Error>)> { let mut handlers = Vec::new(); 'meta: for mut meta in downloads.into_iter() { for profile in &meta.profile { if self.file_exists(profile, &meta).await { continue 'meta; } } let this = self.clone(); let sem = self.semaphore.clone(); let subreddit = subreddit.clone(); let progress = progress.clone(); let handle = tokio::spawn(async move { let _x = sem.acquire().await.unwrap(); let op = this.download_image(&mut meta, subreddit, progress).await; (meta, op) }); handlers.push(handle); } let mut v = Vec::new(); for handle in handlers { v.push(handle.await.unwrap()); } v } async fn download_listing(&self, subreddit: &Subreddit) -> Result<Vec<DownloadMeta>> { let listing_url = format!( "https://reddit.com/r/{}/{}.json?limit=100", subreddit.proper_name, subreddit.sort ); let retry_strategy = FixedInterval::from_millis(100).map(jitter).take(3); let resp: Response = Retry::spawn(retry_strategy, || async { let res = self.client.get(&listing_url).send().await?; Ok::<Response, Error>(res) }) .await .with_context(|| { format!( "failed to open connection to download listing from: {}", listing_url ) })?; if !resp.status().is_success() { let err = resp.json::<RedditError>().await.with_context(|| { format!("failed to deserialize json body from: {}", listing_url) })?; bail!( "downloading listing from [{}] give error: {}", subreddit.proper_name, err ); } let listing: Listing = resp .json() .await .with_context(|| format!("failed to deserialize json body from: {}", listing_url))?; Ok(listing.into_download_metas(&self.config)) } async fn download_image( &self, meta: &mut DownloadMeta, subreddit: Subreddit, progress: UnboundedSender<DownloadStatus>, ) -> Result<()> { if subreddit.download_first { self.poke_image_size(meta).await?; let mut should_continue = false; for (profile, setting) in self.config.iter() { if !meta.passed_checks(setting) { continue; } if self.file_exists(profile, meta).await { continue; } should_continue = true; meta.profile.push(profile.to_owned()); } if !should_continue { return Ok(()); } } let retry_strategy = FixedInterval::from_millis(100).map(jitter).take(3); let response: Response = Retry::spawn(retry_strategy, || async { let res = self.client.get(&meta.url).send().await?; Ok::<Response, Error>(res) }) .await .with_context(|| { format!( "failed to open connection to download image from: {}", meta.url ) })?; let status = response.status(); if !status.is_success() { bail!(format!( "download from {} gives [{}: {}] status code", meta.url, status.as_u16(), status.canonical_reason().unwrap_or("Unknown Reason"), )); } self.ensure_download_dir(meta).await?; let temp_file = self.store_to_temp(response, meta, progress).await?; for profile in &meta.profile { let download_location = self.download_location(profile, meta); fs::copy(&temp_file, &download_location) .await .with_context(|| { format!( "failed to copy file from tmp dir to {}", download_location.display() ) })?; let dir_path = std::env::temp_dir() .join("ridit") .join(&meta.subreddit_name) .join(&meta.filename); fs::remove_file(&dir_path).await.with_context(|| { format!( "failed to remove temp downloaded file {}", download_location.display() ) })?; } Ok(()) }
async fn poke_image_size(&self, meta: &mut DownloadMeta) -> Result<()> { const LIMIT: usize = 1024 * 2 * 10; let retry_strategy = FixedInterval::from_millis(100).map(jitter).take(3); let mut resp = Retry::spawn(retry_strategy, || async { let res = self .client .get(&meta.url) .header(RANGE, LIMIT) .send() .await?; Ok::<Response, Error>(res) }) .await .with_context(|| { format!( "failed to partial download an image to get image size from: {}", meta.url ) })?; let mut data: Vec<u8> = Vec::new(); while let Some(chunk) = resp.chunk().await? { data.append(&mut chunk.to_vec()); if data.len() >= LIMIT { break; } } let size = blob_size(&data) .with_context(|| format!("error getting image dimension from: {}", meta.url))?; meta.image_height = size .height .try_into() .with_context(|| "image height is too big to process")?; meta.image_width = size .width .try_into() .with_context(|| "image width is too big to process")?; Ok(()) } fn download_dir(&self, profile: &str, meta: &DownloadMeta) -> PathBuf { self.config.path.join(profile).join(&meta.subreddit_name) } fn download_location(&self, profile: &str, meta: &DownloadMeta) -> PathBuf { self.download_dir(profile, meta).join(&meta.filename) } async fn file_exists(&self, profile: &str, meta: &DownloadMeta) -> bool { fs::metadata(self.download_location(profile, meta)) .await .is_ok() } async fn store_to_temp( &self, mut resp: Response, meta: &DownloadMeta, progress: UnboundedSender<DownloadStatus>, ) -> Result<PathBuf> { let dir_path = std::env::temp_dir() .join("ridit") .join(&meta.subreddit_name); fs::create_dir_all(&dir_path).await?; let file_path = dir_path.join(&meta.filename); let mut file = File::create(&file_path) .await .context("cannot create file on tmp dir")?; let download_length = resp.content_length().unwrap_or(0); progress .send(meta.as_download_status(download_length, 0)) .unwrap(); while let Some(chunk) = resp.chunk().await? { progress .send(meta.as_download_status(download_length, chunk.len().try_into().unwrap())) .unwrap(); if let Err(err) = file.write(&chunk).await { progress .send( meta.as_download_status(download_length, chunk.len().try_into().unwrap()) .with_error(err.to_string()), ) .unwrap(); bail!("failed to save image from {}. cause: {}", meta.url, err) } } progress .send(meta.as_download_status(download_length, 0).set_finished()) .unwrap(); Ok(file_path) } pub async fn subreddit_exist(subreddit: &mut String) -> Result<bool> { let url = format!("https://reddit.com/r/{}.json", subreddit); let retry_strategy = FixedInterval::from_millis(100).map(jitter).take(3); let resp: Response = Retry::spawn(retry_strategy, || async { let res = reqwest::get(&url).await?; Ok::<Response, Error>(res) }) .await .with_context(|| format!("failed to check subreddit {}", subreddit))?; let listing: Listing = resp .json() .await .with_context(|| format!("failed to deserialize json body from: {}", url))?; match listing.data.children.get(0) { Some(v) => { subreddit.clear(); subreddit.push_str(&v.data.subreddit); Ok(true) } None => Ok(false), } } }
async fn ensure_download_dir(&self, meta: &DownloadMeta) -> Result<()> { for profile in &meta.profile { let download_dir = self.config.path.join(profile).join(&meta.subreddit_name); fs::create_dir_all(&download_dir).await.with_context(|| { format!( "failed to create download directory on: {}", download_dir.display() ) })?; } Ok(()) }
function_block-full_function
[ { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n\ttonic_build::compile_protos(\"proto/server.proto\")?;\n\n\tOk(())\n\n}\n", "file_path": "src/build.rs", "rank": 0, "score": 114218.0222370955 }, { "content": "fn project_dir() -> ProjectDirs {\n\n\tProjectDirs::from(\"i...
Rust
src/ed25519/mod.rs
acw/simple_crypto
82bb499be36f17957e7f5e14755f5e67a2931fb4
mod constants; mod fe; mod loads; mod point; mod scalars; use rand::Rng; use sha::{Hash,SHA512}; use self::scalars::{curve25519_scalar_mask,x25519_sc_muladd,x25519_sc_reduce}; use self::point::{Point,Point2}; #[cfg(test)] use testing::run_test; #[cfg(test)] use std::collections::HashMap; use super::KeyPair; #[derive(Debug,PartialEq)] pub struct ED25519KeyPair { pub public: ED25519Public, pub private: ED25519Private } impl KeyPair for ED25519KeyPair { type Public = ED25519Public; type Private = ED25519Private; fn new(pbl: ED25519Public, prv: ED25519Private) -> ED25519KeyPair { ED25519KeyPair { public: pbl, private: prv } } } impl ED25519KeyPair { pub fn generate<G: Rng>(rng: &mut G) -> ED25519KeyPair { let mut seed = [0; 32]; rng.fill_bytes(&mut seed); let private = ED25519Private::from_seed(&seed); let public = ED25519Public::from(&private); ED25519KeyPair::new(public, private) } pub fn from_seed(seed: &[u8]) -> ED25519KeyPair { let private = ED25519Private::from_seed(seed); let public = ED25519Public::from(&private); ED25519KeyPair{ public, private } } } #[derive(Debug,PartialEq)] pub struct ED25519Private { seed: [u8; 32], private: [u8; 32], prefix: [u8; 32], public: [u8; 32] } impl ED25519Private { pub fn from_seed(seed: &[u8]) -> ED25519Private { let mut result = ED25519Private { seed: [0; 32], private: [0; 32], prefix: [0; 32], public: [0; 32] }; result.seed.copy_from_slice(seed); let mut expanded = SHA512::hash(seed); let (private, prefix) = expanded.split_at_mut(32); result.private.copy_from_slice(private); result.prefix.copy_from_slice(prefix); curve25519_scalar_mask(&mut result.private); let a = Point::scalarmult_base(&result.private); result.public.copy_from_slice(&a.encode()); result } pub fn sign(&self, msg: &[u8]) -> Vec<u8> { let mut signature_s = [0u8; 32]; let mut ctx = SHA512::new(); ctx.update(&self.prefix); ctx.update(&msg); let nonce = digest_scalar(&ctx.finalize()); let r = Point::scalarmult_base(&nonce); let signature_r = r.encode(); let hram_digest = eddsa_digest(&signature_r, &self.public, &msg); let hram = digest_scalar(&hram_digest); x25519_sc_muladd(&mut signature_s, &hram, &self.private, &nonce); let mut result = Vec::with_capacity(64); result.extend_from_slice(&signature_r); result.extend_from_slice(&signature_s); result } pub fn to_bytes(&self) -> Vec<u8> { self.seed.to_vec() } } #[derive(Debug,PartialEq)] pub struct ED25519Public { bytes: [u8; 32], point: Point } impl<'a> From<&'a ED25519Private> for ED25519Public { fn from(x: &ED25519Private) -> ED25519Public { ED25519Public::new(&x.public).expect("Broke converting private ED25519 to public. (?!)") } } #[derive(Debug)] pub enum ED25519PublicImportError { WrongNumberOfBytes(usize), InvalidPublicPoint } impl ED25519Public { pub fn new(bytes: &[u8]) -> Result<ED25519Public,ED25519PublicImportError> { if bytes.len() != 32 { return Err(ED25519PublicImportError::WrongNumberOfBytes(bytes.len())); } match Point::from_bytes(&bytes) { None => Err(ED25519PublicImportError::InvalidPublicPoint), Some(a) => { let mut res = ED25519Public{ bytes: [0; 32], point: a }; res.bytes.copy_from_slice(&bytes); Ok(res) } } } pub fn verify(&self, msg: &[u8], sig: &[u8]) -> bool { assert_eq!(sig.len(), 64); let signature_r = &sig[..32]; let signature_s = &sig[32..]; if signature_s[31] & 0b11100000 != 0 { return false; } let ainv = self.point.invert(); let h_digest = eddsa_digest(signature_r, &self.bytes, msg); let h = digest_scalar(&h_digest); let r = Point2::double_scalarmult_vartime(&h, &ainv, &signature_s); let r_check = r.encode(); signature_r.to_vec() == r_check } pub fn to_bytes(&self) -> Vec<u8> { self.bytes.to_vec() } } fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> Vec<u8> { let mut ctx = SHA512::new(); ctx.update(signature_r); ctx.update(public_key); ctx.update(msg); ctx.finalize() } fn digest_scalar(digest: &[u8]) -> Vec<u8> { assert_eq!(digest.len(), 512/8); let mut copy = [0; 512/8]; copy.copy_from_slice(digest); x25519_sc_reduce(&mut copy); copy[..32].to_vec() } #[cfg(test)] fn run_signing_testcase(case: HashMap<String,(bool,Vec<u8>)>) { let (negr, rbytes) = case.get("r").unwrap(); let (negu, ubytes) = case.get("u").unwrap(); let (negm, mbytes) = case.get("m").unwrap(); let (negs, sbytes) = case.get("s").unwrap(); assert!(!negr && !negu && !negm && !negs); let keypair = ED25519KeyPair::from_seed(rbytes); assert_eq!(ubytes, &keypair.public.bytes.to_vec()); let mut privpub = Vec::new(); privpub.append(&mut rbytes.clone()); privpub.append(&mut ubytes.clone()); let sig = keypair.private.sign(&mbytes); assert_eq!(sig.len(), sbytes.len()); assert!(sig.iter().eq(sbytes.iter())); assert!(keypair.public.verify(&mbytes, &sig)); } #[cfg(test)] #[test] fn rfc8072() { let fname = "testdata/ed25519/rfc8032.test"; run_test(fname.to_string(), 4, run_signing_testcase); } #[cfg(test)] #[test] fn signing() { let fname = "testdata/ed25519/sign.test"; run_test(fname.to_string(), 4, run_signing_testcase); }
mod constants; mod fe; mod loads; mod point; mod scalars; use rand::Rng; use sha::{Hash,SHA512}; use self::scalars::{curve25519_scalar_mask,x25519_sc_muladd,x25519_sc_reduce}; use self::point::{Point,Point2}; #[cfg(test)] use testing::run_test; #[cfg(test)] use std::collections::HashMap; use super::KeyPair; #[derive(Debug,PartialEq)] pub struct ED25519KeyPair { pub public: ED25519Public, pub private: ED25519Private } impl KeyPair for ED25519KeyPair { type Public = ED25519Public; type Private = ED25519Private; fn new(pbl: ED25519Public, prv: ED25519Private) -> ED25519KeyPair { ED25519KeyPair { public: pbl, private: prv } } } impl ED25519KeyPair { pub fn generate<G: Rng>(rng: &mut G) -> ED25519KeyPair { let mut seed = [0; 32]; rng.fill_bytes(&mut seed); let private = ED25519Private::from_seed(&seed); let public = ED25519Public::from(&private); ED25519KeyPair::new(public, private) } pub fn from_seed(seed: &[u8]) -> ED25519KeyPair { let private = ED25519Private::from_seed(seed); let public = ED25519Public::from(&private); ED25519KeyPair{ public, private } } } #[derive(Debug,PartialEq)] pub struct ED25519Private { seed: [u8; 32], private: [u8; 32], prefix: [u8; 32], public: [u8; 32] } impl ED25519Private { pub fn from_seed(seed: &[u8]) -> ED25519Private { let mut result = ED25519Private { seed: [0; 32], private: [0; 32], prefix: [0; 32], public: [0; 32] }; result.seed.copy_from_slice(seed); let mut expanded = SHA512::hash(seed); let (private, prefix) = expanded.split_at_mut(32); result.private.copy_from_slice(private); result.prefix.copy_from_slice(prefix); curve25519_scalar_mask(&mut result.private); let a = Point::scalarmult_base(&result.private); result.public.copy_from_slice(&a.encode()); result } pub fn sign(&self, msg: &[u8]) -> Vec<u8> { let mut signature_s = [0u8; 32]; let mut ctx = SHA512::new(); ctx.update(&self.prefix); ctx.update(&msg); let nonce = digest_scalar(&ctx.finalize()); let r = Point::scalarmult_base(&nonce); let signature_r = r.encode(); let hram_digest = eddsa_digest(&signature_r, &self.public, &msg); let hram = digest_scalar(&hram_digest); x25519_sc_muladd(&mut signature_s, &hram, &self.private, &nonce); let mut result = Vec::with_capacity(64); result.extend_from_slice(&signature_r); result.extend_from_slice(&signature_s); result } pub fn to_bytes(&self) -> Vec<u8> { self.seed.to_vec() } } #[derive(Debug,PartialEq)] pub struct ED25519Public { bytes: [u8; 32], point: Point } impl<'a> From<&'a ED25519Private> for ED25519Public { fn from(x: &ED25519Private) -> ED25519Public { ED25519Public::new(&x.public).expect("Broke converting private ED25519 to public. (?!)") } } #[derive(Debug)] pub enum ED25519PublicImportError { WrongNumberOfBytes(usize), InvalidPublicPoint } impl ED25519Public { pub fn new(bytes: &[u8]) -> Result<ED25519Public,ED25519PublicImportError> { if bytes.len() != 32 { return Err(ED25519PublicImportError::WrongNumberOfBytes(bytes.len())); } match Point::from_bytes(&bytes) { None => Err(ED25519PublicImportError::InvalidPublicPoint), Some(a) => { let mut res = ED25519Public{ bytes: [0; 32], point: a }; res.bytes.copy_from_slice(&bytes); Ok(res) } } } pub fn verify(&self, msg: &[u8], sig: &[u8]) -> bool { assert_eq!(sig.len(), 64); let signature_r = &sig[..32]; let signature_s = &sig[32..]; if signature_s[31] & 0b11100000 != 0 { return false; } let ainv = self.point.invert(); let h_digest = eddsa_digest(signature_r, &self.bytes, msg); let h = digest_scalar(&h_digest); let r = Point2::double_scalarmult_vartime(&h, &ainv, &signature_s); let r_check = r.encode(); signature_r.to_vec() == r_check } pub fn to_bytes(&self) -> Vec<u8> { self.bytes.to_vec() } }
fn digest_scalar(digest: &[u8]) -> Vec<u8> { assert_eq!(digest.len(), 512/8); let mut copy = [0; 512/8]; copy.copy_from_slice(digest); x25519_sc_reduce(&mut copy); copy[..32].to_vec() } #[cfg(test)] fn run_signing_testcase(case: HashMap<String,(bool,Vec<u8>)>) { let (negr, rbytes) = case.get("r").unwrap(); let (negu, ubytes) = case.get("u").unwrap(); let (negm, mbytes) = case.get("m").unwrap(); let (negs, sbytes) = case.get("s").unwrap(); assert!(!negr && !negu && !negm && !negs); let keypair = ED25519KeyPair::from_seed(rbytes); assert_eq!(ubytes, &keypair.public.bytes.to_vec()); let mut privpub = Vec::new(); privpub.append(&mut rbytes.clone()); privpub.append(&mut ubytes.clone()); let sig = keypair.private.sign(&mbytes); assert_eq!(sig.len(), sbytes.len()); assert!(sig.iter().eq(sbytes.iter())); assert!(keypair.public.verify(&mbytes, &sig)); } #[cfg(test)] #[test] fn rfc8072() { let fname = "testdata/ed25519/rfc8032.test"; run_test(fname.to_string(), 4, run_signing_testcase); } #[cfg(test)] #[test] fn signing() { let fname = "testdata/ed25519/sign.test"; run_test(fname.to_string(), 4, run_signing_testcase); }
fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> Vec<u8> { let mut ctx = SHA512::new(); ctx.update(signature_r); ctx.update(public_key); ctx.update(msg); ctx.finalize() }
function_block-full_function
[ { "content": "pub fn curve25519_scalar_mask(a: &mut [u8])\n\n{\n\n assert_eq!(a.len(), 32);\n\n a[0] &= 248;\n\n a[31] &= 127;\n\n a[31] |= 64;\n\n}\n\n\n", "file_path": "src/ed25519/scalars.rs", "rank": 0, "score": 295214.22511977865 }, { "content": "pub fn x25519_sc_reduce(s: &...
Rust
src/parallelhash.rs
quininer/sp800-185
04472c21e6b92956983fff9178452ee38a9d9c80
use tiny_keccak::{ Keccak, XofReader }; use rayon::prelude::*; use ::cshake::CShake; use ::utils::{ left_encode, right_encode }; #[derive(Clone)] pub struct ParallelHash { inner: CShake, buf: Vec<u8>, n: u64, rate: usize, blocksize: usize } impl ParallelHash { #[inline] pub fn new_parallelhash128(custom: &[u8], blocksize: usize) -> Self { let mut hasher = ParallelHash { inner: CShake::new_cshake128(b"ParallelHash", custom), buf: Vec::new(), n: 0, rate: 128, blocksize }; hasher.init(); hasher } #[inline] pub fn new_parallelhash256(custom: &[u8], blocksize: usize) -> Self { let mut hasher = ParallelHash { inner: CShake::new_cshake256(b"ParallelHash", custom), buf: Vec::new(), n: 0, rate: 256, blocksize }; hasher.init(); hasher } fn init(&mut self) { let mut encbuf = [0; 9]; let pos = left_encode(&mut encbuf, self.blocksize as u64); self.inner.update(&encbuf[pos..]); } pub fn update(&mut self, buf: &[u8]) { let rate = self.rate; let pos = if !self.buf.is_empty() { let len = self.blocksize - self.buf.len(); if buf.len() < len { self.buf.extend_from_slice(buf); return; } else { let mut encbuf = vec![0; rate / 4]; let mut shake = Keccak::new(200 - rate / 4, 0x1f); shake.update(&self.buf); shake.update(&buf[..len]); shake.finalize(&mut encbuf); self.inner.update(&encbuf); self.buf.clear(); self.n += 1; } len } else { 0 }; let bufs = buf[pos..].par_chunks(self.blocksize) .map(|chunk| if chunk.len() < self.blocksize { (false, chunk.into()) } else { let mut encbuf = vec![0; rate / 4]; let mut shake = Keccak::new(200 - rate / 4, 0x1f); shake.update(chunk); shake.finalize(&mut encbuf); (true, encbuf) }) .collect::<Vec<_>>(); for (is_hashed, mut buf) in bufs { if is_hashed { self.inner.update(&buf); self.n += 1; } else { self.buf.append(&mut buf); } } } #[inline] pub fn finalize(mut self, buf: &mut [u8]) { self.with_bitlength(buf.len() as u64 * 8); self.inner.finalize(buf) } #[inline] pub fn xof(mut self) -> XofReader { self.with_bitlength(0); self.inner.xof() } #[inline] fn with_bitlength(&mut self, bitlength: u64) { if !self.buf.is_empty() { let mut encbuf = vec![0; self.rate / 4]; let mut shake = Keccak::new(200 - self.rate / 4, 0x1f); shake.update(&self.buf); shake.finalize(&mut encbuf); self.inner.update(&encbuf); self.buf.clear(); self.n += 1; } let mut encbuf = [0; 9]; let pos = right_encode(&mut encbuf, self.n); self.inner.update(&encbuf[pos..]); let pos = right_encode(&mut encbuf, bitlength); self.inner.update(&encbuf[pos..]); } }
use tiny_keccak::{ Keccak, XofReader }; use rayon::prelude::*; use ::cshake::CShake; use ::utils::{ left_encode, right_encode }; #[derive(Clone)] pub struct ParallelHash { inner: CShake, buf: Vec<u8>, n: u64, rate: usize, blocksize: usize } impl ParallelHash { #[inline] pub fn new_parallelhash128(custom: &[u8], blocksize: usize) -> Self { let mut hasher = ParallelHash { inner: CShake::new_cshake128(b"ParallelHash", custom), buf: Vec::new(), n: 0, rate: 128, blocksize }; hasher.init(); hasher } #[inline] pub fn new_parallelhash256(custom: &[u8], blocksize: usize) -> Self { let mut hasher = ParallelHash { inner: CShake::new_cshake256(b"ParallelHash", custom), buf: Vec::new(), n: 0, rate: 256, blocksize }; hasher.init(); hasher } fn init(&mut self) { let mut encbuf = [0; 9]; let pos = left_encode(&mut encbuf, self.blocksize as u64); self.inner.update(&encbuf[pos..]); } pub fn update(&mut self, buf: &[u8]) { let rate = self.rate; let pos = if !self.buf.is_empty() { let len = self.blocksize - self.buf.len(); if buf.len() < len { self.buf.extend_from_slice(buf); return; } else { let mut encbuf = vec![0; rate / 4]; let mut shake = Keccak::new(200 - rate / 4, 0x1f); shake.update(&self.buf); shake.update(&buf[..len]); shak
let mut encbuf = [0; 9]; let pos = right_encode(&mut encbuf, self.n); self.inner.update(&encbuf[pos..]); let pos = right_encode(&mut encbuf, bitlength); self.inner.update(&encbuf[pos..]); } }
e.finalize(&mut encbuf); self.inner.update(&encbuf); self.buf.clear(); self.n += 1; } len } else { 0 }; let bufs = buf[pos..].par_chunks(self.blocksize) .map(|chunk| if chunk.len() < self.blocksize { (false, chunk.into()) } else { let mut encbuf = vec![0; rate / 4]; let mut shake = Keccak::new(200 - rate / 4, 0x1f); shake.update(chunk); shake.finalize(&mut encbuf); (true, encbuf) }) .collect::<Vec<_>>(); for (is_hashed, mut buf) in bufs { if is_hashed { self.inner.update(&buf); self.n += 1; } else { self.buf.append(&mut buf); } } } #[inline] pub fn finalize(mut self, buf: &mut [u8]) { self.with_bitlength(buf.len() as u64 * 8); self.inner.finalize(buf) } #[inline] pub fn xof(mut self) -> XofReader { self.with_bitlength(0); self.inner.xof() } #[inline] fn with_bitlength(&mut self, bitlength: u64) { if !self.buf.is_empty() { let mut encbuf = vec![0; self.rate / 4]; let mut shake = Keccak::new(200 - self.rate / 4, 0x1f); shake.update(&self.buf); shake.finalize(&mut encbuf); self.inner.update(&encbuf); self.buf.clear(); self.n += 1; }
random
[ { "content": "/// `left_encode(x)` encodes the integer x as a byte string in a way that can be unambiguously parsed\n\n/// from the beginning of the string by inserting the length of the byte string before the byte string\n\n/// representation of x.\n\npub fn left_encode(buf: &mut [u8; 9], value: u64) -> usize ...
Rust
src/mesh/model.rs
OllieBerzs/tegne-rs
be614c6b5091ffe476ffbe44ef4ea5b62d998078
use std::collections::HashSet; use std::slice::Iter; use super::Mesh; use crate::math::Mat4; use crate::pipeline::Descriptor; use crate::pipeline::Material; use crate::resources::Handle; pub struct Model { pub nodes: Vec<ModelNode>, } #[derive(Clone)] pub struct ModelNode { pub meshes: Vec<Handle<Mesh>>, pub materials: Vec<Handle<Material>>, pub matrix: Mat4, pub children: Vec<Self>, } struct ChildIter<'a> { stack: Vec<Iter<'a, ModelNode>>, } impl Model { pub fn fix_color_space(&mut self) { let mut fixed = HashSet::new(); self.nodes .iter_mut() .for_each(|n| n.fix_color_space(&mut fixed)); } pub fn meshes(&self) -> impl Iterator<Item = &Handle<Mesh>> { self.nodes.iter().map(|node| node.meshes()).flatten() } pub fn materials(&self) -> impl Iterator<Item = &Handle<Material>> { self.nodes.iter().map(|node| node.materials()).flatten() } } impl ModelNode { pub(crate) fn orders(&self) -> impl Iterator<Item = (&Handle<Mesh>, &Handle<Material>)> { self.meshes.iter().zip(self.materials.iter()) } fn fix_color_space(&mut self, fixed: &mut HashSet<Descriptor>) { for mat in &mut self.materials { let mut m = mat.write(); if !fixed.contains(&m.descriptor()) { m.a[0] = to_linear(m.a[0]); m.a[1] = to_linear(m.a[1]); m.a[2] = to_linear(m.a[2]); fixed.insert(m.descriptor()); } } self.children .iter_mut() .for_each(|c| c.fix_color_space(fixed)); } fn meshes(&self) -> impl Iterator<Item = &Handle<Mesh>> { self.meshes .iter() .chain(self.child_iter().map(|node| node.meshes.iter()).flatten()) } fn materials(&self) -> impl Iterator<Item = &Handle<Material>> { self.materials.iter().chain( self.child_iter() .map(|node| node.materials.iter()) .flatten(), ) } fn child_iter(&self) -> ChildIter<'_> { ChildIter { stack: vec![self.children.iter()], } } } impl<'a> Iterator for ChildIter<'a> { type Item = &'a ModelNode; fn next(&mut self) -> Option<Self::Item> { loop { if let Some(mut top_iter) = self.stack.pop() { if let Some(node) = top_iter.next() { self.stack.push(top_iter); self.stack.push(node.children.iter()); return Some(&node); } } else { return None; } } } } fn to_linear(value: f32) -> f32 { let s = clamp(value, 0.0, 1.0); let cutoff = 0.04045; let gamma = 2.2; if s <= cutoff { s / 12.92 } else { ((s + 0.055) / 1.055).powf(gamma) } } fn clamp(value: f32, min: f32, max: f32) -> f32 { if value < min { min } else if value > max { max } else { value } }
use std::collections::HashSet; use std::slice::Iter; use super::Mesh; use crate::math::Mat4; use crate::pipeline::Descriptor; use crate::pipeline::Material; use crate::resources::Handle; pub struct Model { pub nodes: Vec<ModelNode>, } #[derive(Clone)] pub struct ModelNode { pub meshes: Vec<Handle<Mesh>>, pub materials: Vec<Handle<Material>>, pub matrix: Mat4, pub children: Vec<Self>, } struct ChildIter<'a> { stack: Vec<Iter<'a, ModelNode>>, } impl Model {
pub fn meshes(&self) -> impl Iterator<Item = &Handle<Mesh>> { self.nodes.iter().map(|node| node.meshes()).flatten() } pub fn materials(&self) -> impl Iterator<Item = &Handle<Material>> { self.nodes.iter().map(|node| node.materials()).flatten() } } impl ModelNode { pub(crate) fn orders(&self) -> impl Iterator<Item = (&Handle<Mesh>, &Handle<Material>)> { self.meshes.iter().zip(self.materials.iter()) } fn fix_color_space(&mut self, fixed: &mut HashSet<Descriptor>) { for mat in &mut self.materials { let mut m = mat.write(); if !fixed.contains(&m.descriptor()) { m.a[0] = to_linear(m.a[0]); m.a[1] = to_linear(m.a[1]); m.a[2] = to_linear(m.a[2]); fixed.insert(m.descriptor()); } } self.children .iter_mut() .for_each(|c| c.fix_color_space(fixed)); } fn meshes(&self) -> impl Iterator<Item = &Handle<Mesh>> { self.meshes .iter() .chain(self.child_iter().map(|node| node.meshes.iter()).flatten()) } fn materials(&self) -> impl Iterator<Item = &Handle<Material>> { self.materials.iter().chain( self.child_iter() .map(|node| node.materials.iter()) .flatten(), ) } fn child_iter(&self) -> ChildIter<'_> { ChildIter { stack: vec![self.children.iter()], } } } impl<'a> Iterator for ChildIter<'a> { type Item = &'a ModelNode; fn next(&mut self) -> Option<Self::Item> { loop { if let Some(mut top_iter) = self.stack.pop() { if let Some(node) = top_iter.next() { self.stack.push(top_iter); self.stack.push(node.children.iter()); return Some(&node); } } else { return None; } } } } fn to_linear(value: f32) -> f32 { let s = clamp(value, 0.0, 1.0); let cutoff = 0.04045; let gamma = 2.2; if s <= cutoff { s / 12.92 } else { ((s + 0.055) / 1.055).powf(gamma) } } fn clamp(value: f32, min: f32, max: f32) -> f32 { if value < min { min } else if value > max { max } else { value } }
pub fn fix_color_space(&mut self) { let mut fixed = HashSet::new(); self.nodes .iter_mut() .for_each(|n| n.fix_color_space(&mut fixed)); }
function_block-full_function
[ { "content": "struct Cache {\n\n shader: Option<Handle<Shader>>,\n\n material: Option<Handle<Material>>,\n\n font: Option<Handle<Font>>,\n\n\n\n // colors\n\n background: Rgb,\n\n fill: Rgb,\n\n stroke: Rgb,\n\n tint: Rgb,\n\n\n\n // shadows\n\n shadows: bool,\n\n\n\n // other\n...
Rust
src/socket.rs
caizixian/streamdeck-rs
3848d18fa4bf48b95ccb77c6cf689d422145509e
use super::{Message, MessageOut}; use failure::Fail; use futures::prelude::*; use serde::{de, ser}; use serde_derive::Serialize; use std::marker::PhantomData; use std::pin::Pin; use std::task::{Context, Poll}; use tokio::net::TcpStream; use tokio_tungstenite::{self, WebSocketStream, MaybeTlsStream}; use url::Url; pub struct StreamDeckSocket<G, S, MI, MO> { inner: WebSocketStream<MaybeTlsStream<TcpStream>>, _g: PhantomData<G>, _s: PhantomData<S>, _mi: PhantomData<MI>, _mo: PhantomData<MO>, } impl<G, S, MI, MO> StreamDeckSocket<G, S, MI, MO> { pub async fn connect<A: Into<Address>>( address: A, event: String, uuid: String, ) -> Result<Self, ConnectError> { let address = address.into(); let (mut stream, _) = tokio_tungstenite::connect_async(address.url) .await .map_err(ConnectError::ConnectionError)?; let message = serde_json::to_string(&Registration { event: &event, uuid: &uuid, }) .unwrap(); stream .send(tungstenite::Message::Text(message)) .await .map_err(ConnectError::SendError)?; Ok(StreamDeckSocket { inner: stream, _g: PhantomData, _s: PhantomData, _mi: PhantomData, _mo: PhantomData, }) } fn pin_get_inner(self: Pin<&mut Self>) -> Pin<&mut WebSocketStream<MaybeTlsStream<TcpStream>>> { unsafe { self.map_unchecked_mut(|s| &mut s.inner) } } } #[derive(Debug, Fail)] pub enum StreamDeckSocketError { #[fail(display = "WebSocket error")] WebSocketError(#[fail(cause)] tungstenite::error::Error), #[fail(display = "Bad message")] BadMessage(#[fail(cause)] serde_json::Error), } impl<G, S, MI, MO> Stream for StreamDeckSocket<G, S, MI, MO> where G: de::DeserializeOwned, S: de::DeserializeOwned, MI: de::DeserializeOwned, { type Item = Result<Message<G, S, MI>, StreamDeckSocketError>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { let mut inner = self.pin_get_inner(); loop { match inner.as_mut().poll_next(cx) { Poll::Ready(Some(Ok(tungstenite::Message::Text(message)))) => { break match serde_json::from_str(&message) { Ok(message) => Poll::Ready(Some(Ok(message))), Err(error) => { Poll::Ready(Some(Err(StreamDeckSocketError::BadMessage(error)))) } }; } Poll::Ready(Some(Ok(_))) => {} Poll::Ready(Some(Err(error))) => { break Poll::Ready(Some(Err(StreamDeckSocketError::WebSocketError(error)))) } Poll::Ready(None) => break Poll::Ready(None), Poll::Pending => break Poll::Pending, } } } } impl<G, S, MI, MO> Sink<MessageOut<G, S, MO>> for StreamDeckSocket<G, S, MI, MO> where G: ser::Serialize, S: ser::Serialize, MO: ser::Serialize, { type Error = StreamDeckSocketError; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { self.pin_get_inner() .poll_ready(cx) .map_err(StreamDeckSocketError::WebSocketError) } fn start_send(self: Pin<&mut Self>, item: MessageOut<G, S, MO>) -> Result<(), Self::Error> { let message = serde_json::to_string(&item).map_err(StreamDeckSocketError::BadMessage)?; self.pin_get_inner() .start_send(tungstenite::Message::Text(message)) .map_err(StreamDeckSocketError::WebSocketError) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { self.pin_get_inner() .poll_flush(cx) .map_err(StreamDeckSocketError::WebSocketError) } fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { self.pin_get_inner() .poll_close(cx) .map_err(StreamDeckSocketError::WebSocketError) } } pub struct Address { pub url: Url, } impl From<Url> for Address { fn from(value: Url) -> Self { Address { url: value } } } impl From<u16> for Address { fn from(value: u16) -> Self { let mut url = Url::parse("ws://localhost").unwrap(); url.set_port(Some(value)).unwrap(); Address { url } } } #[derive(Debug, Fail)] pub enum ConnectError { #[fail(display = "Websocket connection error")] ConnectionError(#[fail(cause)] tungstenite::error::Error), #[fail(display = "Send error")] SendError(#[fail(cause)] tungstenite::error::Error), } #[derive(Serialize)] struct Registration<'a> { event: &'a str, uuid: &'a str, }
use super::{Message, MessageOut}; use failure::Fail; use futures::prelude::*; use serde::{de, ser}; use serde_derive::Serialize; use std::marker::PhantomData; use std::pin::Pin; use std::task::{Context, Poll}; use tokio::net::TcpStream; use tokio_tungstenite::{self, WebSocketStream, MaybeTlsStream}; use url::Url; pub struct StreamDeckSocket<G, S, MI, MO> { inner: WebSocketStream<MaybeTlsStream<TcpStream>>, _g: PhantomData<G>, _s: PhantomData<S>, _mi: PhantomData<MI>, _mo: PhantomData<MO>, } impl<G, S, MI, MO> StreamDeckSocket<G, S, MI, MO> { pub async fn connect<A: Into<Address>>( address: A, event: String, uuid: String, ) -> Result<Self, ConnectError> { let address = address.into(); let (mut stream, _) = tokio_tungstenite::connect_async(address.url) .await .map_err(ConnectError::ConnectionError)?; let message = serde_json::to_string(&Registration { event: &event, uuid: &uuid, }) .unwrap(); stream .send(tungstenite::Message::Text(message)) .await .map_err(ConnectError::SendError)?; Ok(StreamDeckSocket { inner: stream, _g: PhantomData, _s: PhantomData, _mi: PhantomData, _mo: PhantomData, }) } fn pin_get_inner(self: Pin<&mut Self>) -> Pin<&mut WebSocketStream<MaybeTlsStream<TcpStream>>> { unsafe { self.map_unchecked_mut(|s| &mut s.inner) } } } #[derive(Debug, Fail)] pub enum StreamDeckSocketError { #[fail(display = "WebSocket error")] WebSocketError(#[fail(cause)] tungstenite::error::Error), #[fail(display = "Bad message")] BadMessage(#[fail(cause)] serde_json::Error), } impl<G, S, MI, MO> Stream for StreamDeckSocket<G, S, MI, MO> where G: de::DeserializeOwned, S: de::DeserializeOwned, MI: de::DeserializeOwned, { type Item = Result<Message<G, S, MI>, StreamDeckSocketError>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { let mut inner = self.pin_get_inner(); loop { match inner.as_mut().poll_next(cx) { Poll::Ready(Some(Ok(tungstenite::Message::Text(message)))) => { break match serde_json::from_str(&message) { Ok(message) => Poll::Ready(Some(Ok(message))), Err(error) => { Poll::Ready(Some(Err(StreamDeckSocketError::BadMessage(error)))) } }; } Poll::Ready(Some(Ok(_))) => {} Poll::Ready(Some(Err
} Poll::Ready(None) => break Poll::Ready(None), Poll::Pending => break Poll::Pending, } } } } impl<G, S, MI, MO> Sink<MessageOut<G, S, MO>> for StreamDeckSocket<G, S, MI, MO> where G: ser::Serialize, S: ser::Serialize, MO: ser::Serialize, { type Error = StreamDeckSocketError; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { self.pin_get_inner() .poll_ready(cx) .map_err(StreamDeckSocketError::WebSocketError) } fn start_send(self: Pin<&mut Self>, item: MessageOut<G, S, MO>) -> Result<(), Self::Error> { let message = serde_json::to_string(&item).map_err(StreamDeckSocketError::BadMessage)?; self.pin_get_inner() .start_send(tungstenite::Message::Text(message)) .map_err(StreamDeckSocketError::WebSocketError) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { self.pin_get_inner() .poll_flush(cx) .map_err(StreamDeckSocketError::WebSocketError) } fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { self.pin_get_inner() .poll_close(cx) .map_err(StreamDeckSocketError::WebSocketError) } } pub struct Address { pub url: Url, } impl From<Url> for Address { fn from(value: Url) -> Self { Address { url: value } } } impl From<u16> for Address { fn from(value: u16) -> Self { let mut url = Url::parse("ws://localhost").unwrap(); url.set_port(Some(value)).unwrap(); Address { url } } } #[derive(Debug, Fail)] pub enum ConnectError { #[fail(display = "Websocket connection error")] ConnectionError(#[fail(cause)] tungstenite::error::Error), #[fail(display = "Send error")] SendError(#[fail(cause)] tungstenite::error::Error), } #[derive(Serialize)] struct Registration<'a> { event: &'a str, uuid: &'a str, }
(error))) => { break Poll::Ready(Some(Err(StreamDeckSocketError::WebSocketError(error))))
function_block-random_span
[ { "content": "struct Serializer {\n\n stack: Vec<String>,\n\n}\n\n\n\nimpl slog::Serializer for Serializer {\n\n fn emit_none(&mut self, key: Key) -> slog::Result {\n\n self.stack.push(format!(\"{}: None\", key));\n\n Ok(())\n\n }\n\n fn emit_unit(&mut self, key: Key) -> slog::Result {...
Rust
src/commands/install.rs
RyosukeNAKATA/mamimi
347583f657f0f8a4df2d91df86e05d6113251f44
use crate::alias::create_alias; use crate::archive::{self, extract::Error as ExtractError, extract::Extract}; use crate::config::MamimiConfig; use crate::current_python_version::current_python_version; use crate::input_version::InputVersion; use crate::outln; use crate::python_version::PythonVersion; use crate::version_files::get_user_version_for_directory; use anyhow::Result; use colored::Colorize; use dirs::config_dir; use log::debug; use num_cpus; use reqwest::Url; use std::env::current_dir; use std::error; use std::io::prelude::*; use std::path::{Path, PathBuf}; use tempfile; use thiserror::Error; #[derive(Error, Debug)] pub enum MamimiError { #[error(transparent)] HttpError(#[from] reqwest::Error), #[error(transparent)] IoError(#[from] std::io::Error), #[error("Can't find the number of cores")] FromUtf8Error(#[from] std::string::FromUtf8Error), #[error("Can't extract the file: {source:?}")] ExtractError { source: ExtractError }, #[error("The downloaded archive is empty")] TarIsEmpty, #[error("Can't find version")] VersionNotFound { version: InputVersion }, #[error("Can't list the remote versions: {source:?}")] CannotListRemoteVersions { source: reqwest::Error }, #[error("Version already installed at {path:?}")] VersionAlreadyInstalled { path: PathBuf }, #[error( "Cannnot find the version in dotfiles. Please provide a version manually to the command." )] CannotInferVersion, #[error("The requested version is not installable: {version}")] NotInstallableVerison { version: PythonVersion }, #[error("Cannot build Python: {stderr}")] CannotBuildPython { stderr: String }, } #[derive(clap::Parser, Debug, Default)] pub struct Install { pub version: Option<InputVersion>, pub configure_opts: Vec<String>, } impl super::command::Command for Install { type Error = MamimiError; fn apply(&self, config: &MamimiConfig) -> Result<(), Self::Error> { let current_version = self .version .clone() .or_else(|| get_user_version_for_directory(std::env::current_dir().unwrap())) .ok_or(MamimiError::CannotInferVersion)?; let version = match current_version.clone() { InputVersion::Full(PythonVersion::Semver(v)) => PythonVersion::Semver(v), InputVersion::Full(PythonVersion::System) => { return Err(MamimiError::NotInstallableVerison { version: PythonVersion::System, }) } current_version => { let avalable_versions = crate::remote_python_index::list() .map_err(|source| MamimiError::CannotListRemoteVersions { source })? .drain(..) .map(|x| x.python_version) .collect::<Vec<_>>(); current_version .to_version(&avalable_versions) .ok_or(MamimiError::VersionNotFound { version: current_version, })? .clone() } }; let installations_dir = config.python_versions_dir(); let installation_dir = PathBuf::from(&installations_dir).join(version.to_string()); if installation_dir.exists() { return Err(MamimiError::VersionAlreadyInstalled { path: installation_dir, }); } let url = package_url(&version); outln!( config, Error, "{} Downloading {}", "==>".green(), format!("{}", url).green() ); let response = reqwest::blocking::get(url)?; if response.status() == 404 { return Err(MamimiError::VersionNotFound { version: current_version, }); } outln!( config, Error, "{} Extracting {}", "==>".green(), format!("{}", url).green() ); let tmp_installations_dir = installations_dir.join(".downloads"); std::fs::create_dir_all(&tmp_installations_dir).map_err(MamimiError::IoError)?; let tmp_dir = tempfile::TempDir::new_in(&tmp_installations_dir) .expect("Cannot generate a temp directory"); extract_archive_into(&tmp_dir, response)?; outln!( config, Error, "{} Building {}", "==>".green(), format!("Python {}", current_version).green() ); let installed_directory = std::fs::read_dir(&tmp_dir) .map_err(MamimiError::IoError)? .next() .ok_or(MamimiError::TarIsEmpty)? .map_err(MamimiError::IoError)?; let installed_directory = installed_directory.path(); build_package( &installed_directory, &installation_dir, &self.configure_opts, )?; if !config.default_python_version_dir().exists() { debug!("Use {} as the default Python version", current_version); create_alias(&config, "default", &version).map_err(MamimiError::IoError)?; } Ok(()) } } fn extract_archive_into<P: AsRef<Path>>( path: P, response: reqwest::blocking::Response, ) -> Result<(), MamimiError> { #[cfg(unix)] let extractor = archive::tar_xz::TarXz::new(response); #[cfg(windows)] let extractor = archive::tar_xz::TarXz::new(response); extractor .extract_into(path) .map_err(|source| MamimiError::ExtractError { source })?; Ok(()) } fn package_url(version: &PythonVersion) -> Url { debug!("package url"); Url::parse(&format!( "https://www.python.org/ftp/python/{}/Python-{}.tar.xz", version, version )) .unwrap() } #[cfg(unix)] fn archive(version: &PythonVersion) -> String { format!("python-{}.tar.xz", version) } #[cfg(windows)] fn archive(version: &PythonVersion) -> String { format!("python-{}.zip", version) } #[allow(clippy::unnecessary_wraps)] fn openssl_dir() -> Result<String, MamimiError> { #[cfg(target_os = "macos")] return Ok(String::from_utf8_lossy( &super::command::Command::new("brew") .arg("--prefix") .arg("openssl@1.1") .output() .map_err(MamimiError::IoError)? .stdout, ) .trim() .to_string()); #[cfg(not(target_os = "macos"))] return Ok("/url/local".to_string()); } fn build_package( current_dir: &Path, installed_dir: &Path, configure_opts: &[String], ) -> Result<(), MamimiError> { debug!("./configure {}", configure_opts.join(" ")); let mut command = super::command::Command::new("sh"); command .arg("configure") .arg(format!("--prefix={}", installed_dir.to_str().unwrap())) .args(configure_opts); if !configure_opts .iter() .any(|opt| opt.starts_with("--with-openssl-dir")) { command.arg(format!("--with-openssl-dir={}", openssl_dir()?)); } let configure = command .current_dir(&current_dir) .output() .map_err(MamimiError::IoError)?; if !configure.status.success() { return Err(MamimiError::CannotBuildPython { stderr: format!( "configure failed: {}", String::from_utf8_lossy(&configure.stderr).to_string() ), }); }; debug!("make -j {}", num_cpus::get().to_string()); let make = super::command::Command::new("make") .arg("-j") .arg(num_cpus::get().to_string()) .current_dir(&current_dir) .output() .map_err(MamimiError::IoError)?; if !make.status.success() { return Err(MamimiError::CannotBuildPython { stderr: format!( "make failed: {}", String::from_utf8_lossy(&make.stderr).to_string() ), }); }; Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::commands::command::Command; use crate::config::MamimiConfig; use crate::python_version::PythonVersion; use itertools::Itertools; use tempfile::tempdir; #[test] fn test_install_second_version() { let config = MamimiConfig { base_dir: Some(tempdir().unwrap().path().to_path_buf()), ..Default::default() }; Install { version: Some(InputVersion::Full(PythonVersion::Semver("3.8.7").unwrap())), configure_opts: vec![], } .apply(&config) .expect("Can't install Python3.8.7"); assert_eq!( std::fs::read_link(&config.default_python_version_dir()) .unwrap() .components() .last(), Some(std::path::Component::Normal(std::ffi::OsStr::new("3.9.6"))) ); } #[test] fn test_install_default_python_version() { let config = MamimiConfig { base_dir: Some(tempdir().unwrap().path().to_path_buf()), ..Default::default() }; Install { version: Some(InputVersion::Full(PythonVersion::Semver( semver::Version::parse("3.8.7").unwrap(), ))), configure_opts: vec![], } .apply(&config) .expect("Can't insatll"); assert!(config.installations_dir().join("3.8.7").exists()); assert!(config .installations_dir() .join("3.8.7") .join("bin") .join("python3") .exists()); assert!(config.default_python_version_dir().exists()); } }
use crate::alias::create_alias; use crate::archive::{self, extract::Error as ExtractError, extract::Extract}; use crate::config::MamimiConfig; use crate::current_python_version::current_python_version; use crate::input_version::InputVersion; use crate::outln; use crate::python_version::PythonVersion; use crate::version_files::get_user_version_for_directory; use anyhow::Result; use colored::Colorize; use dirs::config_dir; use log::debug; use num_cpus; use reqwest::Url; use std::env::current_dir; use std::error; use std::io::prelude::*; use std::path::{Path, PathBuf}; use tempfile; use thiserror::Error; #[derive(Error, Debug)] pub enum MamimiError { #[error(transparent)] HttpError(#[from] reqwest::Error), #[error(transparent)] IoError(#[from] std::io::Error), #[error("Can't find the number of cores")] FromUtf8Error(#[from] std::string::FromUtf8Error), #[error("Can't extract the file: {source:?}")] ExtractError { source: ExtractError }, #[error("The downloaded archive is empty")] TarIsEmpty, #[error("Can't find version")] VersionNotFound { version: InputVersion }, #[error("Can't list the remote versions: {source:?}")] CannotListRemoteVersions { source: reqwest::Error }, #[error("Version already installed at {path:?}")] VersionAlreadyInstalled { path: PathBuf }, #[error( "Cannnot find the version in dotfiles. Please provide a version manually to the command." )] CannotInferVersion, #[error("The requested version is not installable: {version}")] NotInstallableVerison { version: PythonVersion }, #[error("Cannot build Python: {stderr}")] CannotBuildPython { stderr: String }, } #[derive(clap::Parser, Debug, Default)] pub struct Install { pub version: Option<InputVersion>, pub configure_opts: Vec<String>, } impl super::command::Command for Install { type Error = MamimiError; fn apply(&self, config: &MamimiConfig) -> Result<(), Self::Error> { let current_version = self .version .clone() .or_else(|| get_user_version_for_directory(std::env::current_dir().unwrap())) .ok_or(MamimiError::CannotInferVersion)?; let version = match current_version.clone() { InputVersion::Full(PythonVersion::Semver(v)) => PythonVersion::Semver(v), InputVersion::Full(PythonVersion::System) => { return Err(MamimiError::NotInstallableVerison { version: PythonVersion::System, }) } current_version => { let avalable_versions = crate::remote_python_index::list() .map_err(|source| MamimiError::CannotListRemoteVersions { source })? .drain(..) .map(|x| x.python_version) .collect::<Vec<_>>(); current_version .to_version(&avalable_versions)
.expect("Cannot generate a temp directory"); extract_archive_into(&tmp_dir, response)?; outln!( config, Error, "{} Building {}", "==>".green(), format!("Python {}", current_version).green() ); let installed_directory = std::fs::read_dir(&tmp_dir) .map_err(MamimiError::IoError)? .next() .ok_or(MamimiError::TarIsEmpty)? .map_err(MamimiError::IoError)?; let installed_directory = installed_directory.path(); build_package( &installed_directory, &installation_dir, &self.configure_opts, )?; if !config.default_python_version_dir().exists() { debug!("Use {} as the default Python version", current_version); create_alias(&config, "default", &version).map_err(MamimiError::IoError)?; } Ok(()) } } fn extract_archive_into<P: AsRef<Path>>( path: P, response: reqwest::blocking::Response, ) -> Result<(), MamimiError> { #[cfg(unix)] let extractor = archive::tar_xz::TarXz::new(response); #[cfg(windows)] let extractor = archive::tar_xz::TarXz::new(response); extractor .extract_into(path) .map_err(|source| MamimiError::ExtractError { source })?; Ok(()) } fn package_url(version: &PythonVersion) -> Url { debug!("package url"); Url::parse(&format!( "https://www.python.org/ftp/python/{}/Python-{}.tar.xz", version, version )) .unwrap() } #[cfg(unix)] fn archive(version: &PythonVersion) -> String { format!("python-{}.tar.xz", version) } #[cfg(windows)] fn archive(version: &PythonVersion) -> String { format!("python-{}.zip", version) } #[allow(clippy::unnecessary_wraps)] fn openssl_dir() -> Result<String, MamimiError> { #[cfg(target_os = "macos")] return Ok(String::from_utf8_lossy( &super::command::Command::new("brew") .arg("--prefix") .arg("openssl@1.1") .output() .map_err(MamimiError::IoError)? .stdout, ) .trim() .to_string()); #[cfg(not(target_os = "macos"))] return Ok("/url/local".to_string()); } fn build_package( current_dir: &Path, installed_dir: &Path, configure_opts: &[String], ) -> Result<(), MamimiError> { debug!("./configure {}", configure_opts.join(" ")); let mut command = super::command::Command::new("sh"); command .arg("configure") .arg(format!("--prefix={}", installed_dir.to_str().unwrap())) .args(configure_opts); if !configure_opts .iter() .any(|opt| opt.starts_with("--with-openssl-dir")) { command.arg(format!("--with-openssl-dir={}", openssl_dir()?)); } let configure = command .current_dir(&current_dir) .output() .map_err(MamimiError::IoError)?; if !configure.status.success() { return Err(MamimiError::CannotBuildPython { stderr: format!( "configure failed: {}", String::from_utf8_lossy(&configure.stderr).to_string() ), }); }; debug!("make -j {}", num_cpus::get().to_string()); let make = super::command::Command::new("make") .arg("-j") .arg(num_cpus::get().to_string()) .current_dir(&current_dir) .output() .map_err(MamimiError::IoError)?; if !make.status.success() { return Err(MamimiError::CannotBuildPython { stderr: format!( "make failed: {}", String::from_utf8_lossy(&make.stderr).to_string() ), }); }; Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::commands::command::Command; use crate::config::MamimiConfig; use crate::python_version::PythonVersion; use itertools::Itertools; use tempfile::tempdir; #[test] fn test_install_second_version() { let config = MamimiConfig { base_dir: Some(tempdir().unwrap().path().to_path_buf()), ..Default::default() }; Install { version: Some(InputVersion::Full(PythonVersion::Semver("3.8.7").unwrap())), configure_opts: vec![], } .apply(&config) .expect("Can't install Python3.8.7"); assert_eq!( std::fs::read_link(&config.default_python_version_dir()) .unwrap() .components() .last(), Some(std::path::Component::Normal(std::ffi::OsStr::new("3.9.6"))) ); } #[test] fn test_install_default_python_version() { let config = MamimiConfig { base_dir: Some(tempdir().unwrap().path().to_path_buf()), ..Default::default() }; Install { version: Some(InputVersion::Full(PythonVersion::Semver( semver::Version::parse("3.8.7").unwrap(), ))), configure_opts: vec![], } .apply(&config) .expect("Can't insatll"); assert!(config.installations_dir().join("3.8.7").exists()); assert!(config .installations_dir() .join("3.8.7") .join("bin") .join("python3") .exists()); assert!(config.default_python_version_dir().exists()); } }
.ok_or(MamimiError::VersionNotFound { version: current_version, })? .clone() } }; let installations_dir = config.python_versions_dir(); let installation_dir = PathBuf::from(&installations_dir).join(version.to_string()); if installation_dir.exists() { return Err(MamimiError::VersionAlreadyInstalled { path: installation_dir, }); } let url = package_url(&version); outln!( config, Error, "{} Downloading {}", "==>".green(), format!("{}", url).green() ); let response = reqwest::blocking::get(url)?; if response.status() == 404 { return Err(MamimiError::VersionNotFound { version: current_version, }); } outln!( config, Error, "{} Extracting {}", "==>".green(), format!("{}", url).green() ); let tmp_installations_dir = installations_dir.join(".downloads"); std::fs::create_dir_all(&tmp_installations_dir).map_err(MamimiError::IoError)?; let tmp_dir = tempfile::TempDir::new_in(&tmp_installations_dir)
random
[ { "content": "pub fn current_python_version(config: &MamimiConfig) -> Result<Option<PythonVersion>, Error> {\n\n let multishell_path = config.multishell_path().ok_or(Error::EnvNotApplied)?;\n\n\n\n if multishell_path.read_link().ok() == Some(system_version::path()) {\n\n return Ok(Some(PythonVersio...
Rust
src/tests/live_mocker.rs
w3f/polkadot-registrar-bot
3c5aa36cf5de8edae0ac434947eb585b7ca92c75
use crate::adapters::tests::MessageInjector; use crate::adapters::AdapterListener; use crate::database::Database; use crate::primitives::{ ExpectedMessage, ExternalMessage, ExternalMessageType, JudgementState, MessageId, Timestamp, }; use crate::tests::F; use crate::{config_session_notifier, DatabaseConfig, DisplayNameConfig, NotifierConfig, Result}; use rand::{thread_rng, Rng}; use tokio::time::{sleep, Duration}; #[actix::test] #[ignore] async fn run_mocker() -> Result<()> { tracing_subscriber::fmt() .with_max_level(tracing::Level::DEBUG) .with_env_filter("system") .init(); let mut rng = thread_rng(); let db_config = DatabaseConfig { uri: "mongodb://localhost:27017".to_string(), name: format!("registrar_test_{}", rng.gen_range(u32::MIN..u32::MAX)), }; let notifier_config = NotifierConfig { api_address: "localhost:8888".to_string(), display_name: DisplayNameConfig { enabled: true, limit: 0.85, }, }; info!("Starting mock adapter and session notifier instances"); let db = Database::new(&db_config.uri, &db_config.name).await?; config_session_notifier(db.clone(), notifier_config).await?; let injector = MessageInjector::new(); let listener = AdapterListener::new(db.clone()).await; listener.start_message_adapter(injector.clone(), 1).await; info!("Mocker setup completed"); let mut alice = JudgementState::alice(); *alice .get_field_mut(&F::ALICE_DISPLAY_NAME()) .expected_display_name_check_mut() .0 = true; info!("INSERTING IDENTITY: Alice (1a2YiGNu1UUhJtihq8961c7FZtWGQuWDVMWTNBKJdmpGhZP)"); db.add_judgement_request(&alice).await.unwrap(); let mut rng = thread_rng(); loop { let ty_msg: u32 = rng.gen_range(0..2); let ty_validity = rng.gen_range(0..1); let reset = rng.gen_range(0..5); if reset == 0 { warn!("Resetting Identity"); db.delete_judgement(&alice.context).await.unwrap(); alice = JudgementState::alice(); *alice .get_field_mut(&F::ALICE_DISPLAY_NAME()) .expected_display_name_check_mut() .0 = true; db.add_judgement_request(&alice).await.unwrap(); } let (origin, values) = match ty_msg { 0 => { (ExternalMessageType::Email("alice@email.com".to_string()), { match ty_validity { 0 => alice .get_field(&F::ALICE_EMAIL()) .expected_message() .to_message_parts(), 1 => ExpectedMessage::random().to_message_parts(), _ => panic!(), } }) } 1 => { (ExternalMessageType::Twitter("@alice".to_string()), { match ty_validity { 0 => alice .get_field(&F::ALICE_TWITTER()) .expected_message() .to_message_parts(), 1 => ExpectedMessage::random().to_message_parts(), _ => panic!(), } }) } 2 => { ( ExternalMessageType::Matrix("@alice:matrix.org".to_string()), { match ty_validity { 0 => alice .get_field(&F::ALICE_MATRIX()) .expected_message() .to_message_parts(), 1 => ExpectedMessage::random().to_message_parts(), _ => panic!(), } }, ) } _ => panic!(), }; injector .send(ExternalMessage { origin, id: MessageId::from(0u32), timestamp: Timestamp::now(), values, }) .await; sleep(Duration::from_secs(2)).await; } }
use crate::adapters::tests::MessageInjector; use crate::adapters::AdapterListener; use crate::database::Database; use crate::primitives::{ ExpectedMessage, ExternalMessage, ExternalMessageType, JudgementState, MessageId, Timestamp, }; use crate::tests::F; use crate::{config_session_notifier, DatabaseConfig, DisplayNameConfig, NotifierConfig, Result}; use rand::{thread_rng, Rng}; use tokio::time::{sleep, Duration}; #[actix::test] #[ignore] async fn run_mocker() -> Result<()> { tracing_subscriber::fmt() .with_max_level(tracing::Level::DEBUG) .with_env_filter("system") .init(); let mut rng = thread_rng(); let db_config = DatabaseConfig { uri: "mongodb://localhost:27017".to_string(), name: format!("registra
r_test_{}", rng.gen_range(u32::MIN..u32::MAX)), }; let notifier_config = NotifierConfig { api_address: "localhost:8888".to_string(), display_name: DisplayNameConfig { enabled: true, limit: 0.85, }, }; info!("Starting mock adapter and session notifier instances"); let db = Database::new(&db_config.uri, &db_config.name).await?; config_session_notifier(db.clone(), notifier_config).await?; let injector = MessageInjector::new(); let listener = AdapterListener::new(db.clone()).await; listener.start_message_adapter(injector.clone(), 1).await; info!("Mocker setup completed"); let mut alice = JudgementState::alice(); *alice .get_field_mut(&F::ALICE_DISPLAY_NAME()) .expected_display_name_check_mut() .0 = true; info!("INSERTING IDENTITY: Alice (1a2YiGNu1UUhJtihq8961c7FZtWGQuWDVMWTNBKJdmpGhZP)"); db.add_judgement_request(&alice).await.unwrap(); let mut rng = thread_rng(); loop { let ty_msg: u32 = rng.gen_range(0..2); let ty_validity = rng.gen_range(0..1); let reset = rng.gen_range(0..5); if reset == 0 { warn!("Resetting Identity"); db.delete_judgement(&alice.context).await.unwrap(); alice = JudgementState::alice(); *alice .get_field_mut(&F::ALICE_DISPLAY_NAME()) .expected_display_name_check_mut() .0 = true; db.add_judgement_request(&alice).await.unwrap(); } let (origin, values) = match ty_msg { 0 => { (ExternalMessageType::Email("alice@email.com".to_string()), { match ty_validity { 0 => alice .get_field(&F::ALICE_EMAIL()) .expected_message() .to_message_parts(), 1 => ExpectedMessage::random().to_message_parts(), _ => panic!(), } }) } 1 => { (ExternalMessageType::Twitter("@alice".to_string()), { match ty_validity { 0 => alice .get_field(&F::ALICE_TWITTER()) .expected_message() .to_message_parts(), 1 => ExpectedMessage::random().to_message_parts(), _ => panic!(), } }) } 2 => { ( ExternalMessageType::Matrix("@alice:matrix.org".to_string()), { match ty_validity { 0 => alice .get_field(&F::ALICE_MATRIX()) .expected_message() .to_message_parts(), 1 => ExpectedMessage::random().to_message_parts(), _ => panic!(), } }, ) } _ => panic!(), }; injector .send(ExternalMessage { origin, id: MessageId::from(0u32), timestamp: Timestamp::now(), values, }) .await; sleep(Duration::from_secs(2)).await; } }
function_block-function_prefixed
[ { "content": "fn try_decode_hex(display_name: &mut String) {\n\n if display_name.starts_with(\"0x\") {\n\n // Might be a false positive. Leave it as is if it cannot be decoded.\n\n if let Ok(name) = hex::decode(&display_name[2..]) {\n\n if let Ok(name) = String::from_utf8(name) {\n\n...
Rust
signature_benchmark/src/wots_aes.rs
qkniep/PQ-FIDO_sd-MSS
27c49bcb82d86057ae4b4c7a429fa55671735de0
use core::convert::TryInto; use core::hash::Hasher; use aes::cipher::{generic_array::GenericArray, BlockEncrypt, NewBlockCipher}; use aes::Aes128; use getrandom; use siphasher::sip128::{Hasher128, SipHasher}; pub const W: usize = 256; pub const X: usize = 1; pub const N: usize = 128 / 8; /*/// Message digest length in bytes. const M: usize = 512 / 8; /// Length of the base `W` representation of a message of length `M`. const L1: usize = 128; /// Length of the base `W` checksum of a base `W` message of length `L1`. const L2: usize = 3; /// Number of function chains const L: usize = L1 + L2;*/ #[derive(Debug, Clone, PartialEq, PartialOrd, Hash, Default)] pub struct Wots { pub pk: [u8; N], sk: Vec<[u8; N]>, } #[derive(Debug, Clone, PartialEq, PartialOrd, Hash, Default)] pub struct WotsSignature { pub pk: [u8; N], pub msg_hash: [u8; N], pub signature: Vec<[u8; N]>, } impl Wots { pub fn new() -> Self { let seed: [u8; N] = rand_digest().unwrap(); return Self::from_seed(seed); } pub fn from_seed(mut seed: [u8; N]) -> Self { let mut sk = Vec::<[u8; N]>::with_capacity(N * X); let mut pk = Vec::<[u8; N]>::with_capacity(N * X); for _ in 0..N * X { let secret = prng(&mut seed); sk.push(secret); let public = chain(&secret, W - 1); pk.push(public); } let mut hasher = SipHasher::new(); for p in &pk { hasher.write(p); } let h = hasher.finish128(); let hash_bytes = h.as_bytes(); return Self { pk: hash_bytes, sk }; } pub fn sign(&self, input: &str) -> WotsSignature { let mut hasher = SipHasher::new(); hasher.write(input.as_bytes()); let h = hasher.finish128(); let hash_bytes = h.as_bytes(); let mut signature: Vec<[u8; N]> = Vec::with_capacity(N * X); let mut sig_cycles: Vec<usize> = Vec::with_capacity(N * X); for i in 0..N { let symbols = base_w(hash_bytes[i]); for s in 0..X { sig_cycles.push(symbols[s] as usize); let index = i * X + s; let sig: [u8; N] = chain(&self.sk[index], sig_cycles[index]); signature.push(sig); } } return WotsSignature { pk: self.pk.clone(), msg_hash: hash_bytes.clone(), signature, }; } } impl WotsSignature { pub fn verify(&self) -> bool { let mut i = 0; let mut pk = Vec::<[u8; N]>::with_capacity(N * X); for b in &self.msg_hash { for s in base_w(*b) { let cycles = W - 1 - (s as usize); pk.push(chain(&self.signature[i], cycles)); i += 1; } } let mut hasher = SipHasher::new(); for p in &pk { hasher.write(p); } let h = hasher.finish128(); let hash_bytes = h.as_bytes(); assert_eq!(self.pk, hash_bytes); return true; } } pub fn chain(input: &[u8; N], c: usize) -> [u8; N] { let mut output = *GenericArray::from_slice(input); let iv = GenericArray::from([0u8; N]); let cipher = Aes128::new(&iv); for _ in 0..c { let i = u128::from_be_bytes(output.as_slice().try_into().expect("wrong length")); cipher.encrypt_block(&mut output); let o = u128::from_be_bytes(output.as_slice().try_into().expect("wrong length")); let r = i ^ o; output = GenericArray::from(r.to_be_bytes()); } return output.as_slice().try_into().expect("wrong length"); } pub fn base_w(byte: u8) -> [u8; X] { let mut b = byte as usize; let mut symbols = [0u8; X]; for s in 0..X { symbols[X - 1 - s] = (b % W) as u8; b /= W; } return symbols; } fn rand_digest() -> Result<[u8; N], getrandom::Error> { let mut buf = [0u8; N]; getrandom::getrandom(&mut buf)?; Ok(buf) } pub fn prng(seed: &mut [u8; N]) -> [u8; N] { let mut output = *GenericArray::from_slice(seed); let iv = GenericArray::from([0u8; N]); let cipher = Aes128::new(&iv); cipher.encrypt_block(&mut output); let s = u128::from_be_bytes(*seed); let o = u128::from_be_bytes(output.as_slice().try_into().expect("wrong length")); let r = s ^ o; let new_seed = r.wrapping_add(s).wrapping_add(1); *seed = new_seed.to_be_bytes(); return r.to_be_bytes(); } #[cfg(test)] mod tests { use super::*; #[test] fn chain_test() { let start = [0u8; N]; let mid = chain(&start, 3); let end1 = chain(&mid, 7); let end2 = chain(&start, 10); assert_eq!(end1, end2); } #[test] fn sign_and_verify() { let wots = Wots::new(); let sig = wots.sign("hello world"); assert_eq!(sig.verify(), true); } }
use core::convert::TryInto; use core::hash::Hasher; use aes::cipher::{generic_array::GenericArray, BlockEncrypt, NewBlockCipher}; use aes::Aes128; use getrandom; use siphasher::sip128::{Hasher128, SipHasher}; pub const W: usize = 256; pub const X: usize = 1; pub const N: usize = 128 / 8; /*/// Message digest length in bytes. const M: usize = 512 / 8; /// Length of the base `W` representation of a message of length `M`. const L1: usize = 128; /// Length of the base `W` checksum of a base `W` message of length `L1`. const L2: usize = 3; /// Number of function chains const L: usize = L1 + L2;*/ #[derive(Debug, Clone, PartialEq, PartialOrd, Hash, Default)] pub struct Wots { pub pk: [u8; N], sk: Vec<[u8; N]>, } #[derive(Debug, Clone, PartialEq, PartialOrd, Hash, Default)] pub struct WotsSignature { pub pk: [u8; N], pub msg_hash: [u8; N], pub signature: Vec<[u8; N]>, } impl Wots { pub fn new() -> Self { let seed: [u8; N] = rand_digest().unwrap(); return Self::from_seed(seed); } pub fn from_seed(mut seed: [u8; N]) -> Self { let mut sk = Vec::<[u8; N]>::with_capacity(N * X); let mut pk = Vec::<[u8; N]>::with_capacity(N * X); for _ in 0..N * X { let secret = prng(&mut seed); sk.push(secret); let public = chain(&secret, W - 1); pk.push(public); } let mut hasher = SipHasher::new(); for p in &pk { hasher.write(p); } let h = hasher.finish128(); let hash_bytes = h.as_bytes(); return Self { pk: hash_bytes, sk }; } pub fn sign(&self, input: &str) -> WotsSignature { let mut hasher = SipHasher::new(); hasher.write(input.as_bytes()); let h = hasher.finish128(); let hash_bytes = h.as_bytes(); let mut signature: Vec<[u8; N]> = Vec::with_capacity(N * X); let mut sig_cycles: Vec<usize> = Vec::with_capacity(N * X); for i in 0..N { let symbols = base_w(hash_bytes[i]); for s in 0..X { sig_cycles.push(symbols[s] as usize); let index = i * X + s; let sig: [u8; N] = chain(&self.sk[index], sig_cycles[index]); signature.push(sig); } } return WotsSignature { pk: self.pk.clone(), msg_hash: hash_bytes.clone(), signature, }; } } impl WotsSignature { pub fn verify(&se
)?; Ok(buf) } pub fn prng(seed: &mut [u8; N]) -> [u8; N] { let mut output = *GenericArray::from_slice(seed); let iv = GenericArray::from([0u8; N]); let cipher = Aes128::new(&iv); cipher.encrypt_block(&mut output); let s = u128::from_be_bytes(*seed); let o = u128::from_be_bytes(output.as_slice().try_into().expect("wrong length")); let r = s ^ o; let new_seed = r.wrapping_add(s).wrapping_add(1); *seed = new_seed.to_be_bytes(); return r.to_be_bytes(); } #[cfg(test)] mod tests { use super::*; #[test] fn chain_test() { let start = [0u8; N]; let mid = chain(&start, 3); let end1 = chain(&mid, 7); let end2 = chain(&start, 10); assert_eq!(end1, end2); } #[test] fn sign_and_verify() { let wots = Wots::new(); let sig = wots.sign("hello world"); assert_eq!(sig.verify(), true); } }
lf) -> bool { let mut i = 0; let mut pk = Vec::<[u8; N]>::with_capacity(N * X); for b in &self.msg_hash { for s in base_w(*b) { let cycles = W - 1 - (s as usize); pk.push(chain(&self.signature[i], cycles)); i += 1; } } let mut hasher = SipHasher::new(); for p in &pk { hasher.write(p); } let h = hasher.finish128(); let hash_bytes = h.as_bytes(); assert_eq!(self.pk, hash_bytes); return true; } } pub fn chain(input: &[u8; N], c: usize) -> [u8; N] { let mut output = *GenericArray::from_slice(input); let iv = GenericArray::from([0u8; N]); let cipher = Aes128::new(&iv); for _ in 0..c { let i = u128::from_be_bytes(output.as_slice().try_into().expect("wrong length")); cipher.encrypt_block(&mut output); let o = u128::from_be_bytes(output.as_slice().try_into().expect("wrong length")); let r = i ^ o; output = GenericArray::from(r.to_be_bytes()); } return output.as_slice().try_into().expect("wrong length"); } pub fn base_w(byte: u8) -> [u8; X] { let mut b = byte as usize; let mut symbols = [0u8; X]; for s in 0..X { symbols[X - 1 - s] = (b % W) as u8; b /= W; } return symbols; } fn rand_digest() -> Result<[u8; N], getrandom::Error> { let mut buf = [0u8; N]; getrandom::getrandom(&mut buf
random
[ { "content": "/// Applies c cycles of the SHA-256/8N hash function to the input.\n\npub fn chain(input: &[u8; N], c: usize, chain: usize, start: usize, pk_seed: &[u8; N]) -> [u8; N] {\n\n let mut output = input.clone();\n\n\n\n for i in 0..c {\n\n let (key, bitmask) = prf2(&pk_seed, ((chain << 8) +...
Rust
src/stations.rs
danielrs/pandora-rs
494ab0aef0ddb9959cdae6c6a6fb5a8ab161a7d0
use super::Pandora; use error::Result; use method::Method; use music::{ToMusicToken, MusicType}; use playlist::Playlist; use serde_json; pub struct Stations<'a> { pandora: &'a Pandora, } impl<'a> Stations<'a> { pub fn new(pandora: &'a Pandora) -> Stations<'a> { Stations { pandora: pandora } } pub fn list(&self) -> Result<Vec<Station>> { let stations = try!(self.pandora .post::<StationList>(Method::UserGetStationList, None)); Ok(stations.stations) } pub fn create<T>(&self, music_token: &T) -> Result<Station> where T: ToMusicToken { self.pandora .post(Method::StationCreateStation, Some(serde_json::to_value(CreateStationRequest { track_token: None, music_type: None, music_token: Some(music_token.to_music_token()), }))) } pub fn rename<T>(&self, station: &T, station_name: &str) -> Result<Station> where T: ToStationToken { self.pandora .post(Method::StationRenameStation, Some(serde_json::to_value(RenameStationRequest { station_token: station.to_station_token(), station_name: station_name.to_owned(), }))) } pub fn delete<T>(&self, station: &T) -> Result<()> where T: ToStationToken { self.pandora .post_noop(Method::StationDeleteStation, Some(serde_json::to_value(DeleteStationRequest { station_token: station.to_station_token(), }))) } pub fn add_seed<S, T>(&self, station: &S, music_token: &T) -> Result<Seed> where S: ToStationToken, T: ToMusicToken { self.pandora .post(Method::StationAddMusic, Some(serde_json::to_value(AddSeedRequest { station_token: station.to_station_token(), music_token: music_token.to_music_token(), }))) } pub fn remove_seed(&self, seed: &Seed) -> Result<()> { self.pandora .post(Method::StationDeleteMusic, Some(serde_json::to_value(RemoveSeedRequest { seed_id: seed.seed_id.clone() }))) } pub fn station<T>(&self, station: &T) -> Result<Station> where T: ToStationToken { self.pandora .post(Method::StationGetStation, Some(serde_json::to_value(GetStationRequest { station_token: station.to_station_token(), include_extended_attributes: true, }))) } pub fn checksum(&self) -> Result<StationListChecksum> { self.pandora.post(Method::UserGetStationListChecksum, None) } pub fn playlist<T>(&self, station: &T) -> Playlist where T: ToStationToken { Playlist::new(self.pandora, station) } } pub trait ToStationToken { fn to_station_token(&self) -> String; } #[derive(Debug, Clone, Deserialize)] pub struct Station { #[serde(rename="stationId")] pub station_id: String, #[serde(rename="stationName")] pub station_name: String, } impl ToStationToken for Station { fn to_station_token(&self) -> String { self.station_id.clone() } } #[derive(Debug, Deserialize)] struct StationList { pub stations: Vec<Station>, pub checksum: String, } #[derive(Deserialize)] pub struct StationListChecksum { pub checksum: String, } #[derive(Debug, Deserialize)] pub struct ExtendedStation { #[serde(rename="stationId")] pub station_id: String, #[serde(rename="stationName")] pub station_name: String, #[serde(rename="artUrl")] pub art_url: Option<String>, pub music: Option<StationMusic>, } #[derive(Debug, Deserialize)] pub struct StationMusic { pub songs: Vec<SongSeed>, pub artists: Vec<ArtistSeed>, pub genre: Option<Vec<GenreSeed>>, } #[derive(Debug, Deserialize)] pub struct Seed { #[serde(rename="seedId")] pub seed_id: String, } #[derive(Debug, Deserialize)] pub struct SongSeed { #[serde(rename="seedId")] pub seed_id: String, #[serde(rename="artistName")] pub artist_name: String, #[serde(rename="artUrl")] pub art_url: String, #[serde(rename="songName")] pub song_name: String, #[serde(rename="musicToken")] pub music_token: String, } #[derive(Debug, Deserialize)] pub struct ArtistSeed { #[serde(rename="seedId")] pub seed_id: String, #[serde(rename="artistName")] pub artist_name: String, #[serde(rename="artUrl")] pub art_url: String, #[serde(rename="musicToken")] pub music_token: String, } #[derive(Debug, Deserialize)] pub struct GenreSeed { #[serde(rename="seedId")] pub seed_id: String, #[serde(rename="artistName")] pub genre_name: String, #[serde(rename="musicToken")] pub music_token: String, } #[derive(Serialize)] struct CreateStationRequest { #[serde(rename="trackToken")] track_token: Option<String>, #[serde(rename="musicType")] music_type: Option<MusicType>, #[serde(rename="musicToken")] music_token: Option<String>, } #[derive(Serialize)] struct RenameStationRequest { #[serde(rename="stationToken")] station_token: String, #[serde(rename="stationName")] station_name: String, } #[derive(Serialize)] struct DeleteStationRequest { #[serde(rename="stationToken")] station_token: String, } #[derive(Serialize)] struct GetStationRequest { #[serde(rename="stationToken")] station_token: String, #[serde(rename="includeExtendedAttributes")] include_extended_attributes: bool, } #[derive(Serialize)] struct AddSeedRequest { #[serde(rename="stationToken")] station_token: String, #[serde(rename="musicToken")] music_token: String, } #[derive(Serialize)] struct RemoveSeedRequest { #[serde(rename="seedId")] seed_id: String, }
use super::Pandora; use error::Result; use method::Method; use music::{ToMusicToken, MusicType}; use playlist::Playlist; use serde_json; pub struct Stations<'a> { pandora: &'a Pandora, } impl<'a> Stations<'a> { pub fn new(pandora: &'a Pandora) -> Stations<'a> { Stations { pandora: pandora } } pub fn list(&self) -> Result<Vec<Station>> { let stations = try!(self.pandora .post::<StationList>(Method::UserGetStationList, None)); Ok(stations.stations) } pub fn create<T>(&self, music_token: &T) -> Result<Station> where T: ToMusicToken { self.pandora .post(Method::StationCreateStation, Some(serde_json::to_value(CreateStationRequest { track_token: None, music_type: None, music_token: Some(music_token.to_music_token()), }))) } pub fn rename<T>(&self, station: &T, station_name: &str) -> Result<Station> where T: ToStationToken { self.pandora .post(Method::StationRenameStation, Some(serde_json::to_value(RenameStationRequest { station_token: station.to_station_token(), station_name: station_name.to_owned(), }))) } pub fn delete<T>(&self, station: &T) -> Result<()>
pub fn add_seed<S, T>(&self, station: &S, music_token: &T) -> Result<Seed> where S: ToStationToken, T: ToMusicToken { self.pandora .post(Method::StationAddMusic, Some(serde_json::to_value(AddSeedRequest { station_token: station.to_station_token(), music_token: music_token.to_music_token(), }))) } pub fn remove_seed(&self, seed: &Seed) -> Result<()> { self.pandora .post(Method::StationDeleteMusic, Some(serde_json::to_value(RemoveSeedRequest { seed_id: seed.seed_id.clone() }))) } pub fn station<T>(&self, station: &T) -> Result<Station> where T: ToStationToken { self.pandora .post(Method::StationGetStation, Some(serde_json::to_value(GetStationRequest { station_token: station.to_station_token(), include_extended_attributes: true, }))) } pub fn checksum(&self) -> Result<StationListChecksum> { self.pandora.post(Method::UserGetStationListChecksum, None) } pub fn playlist<T>(&self, station: &T) -> Playlist where T: ToStationToken { Playlist::new(self.pandora, station) } } pub trait ToStationToken { fn to_station_token(&self) -> String; } #[derive(Debug, Clone, Deserialize)] pub struct Station { #[serde(rename="stationId")] pub station_id: String, #[serde(rename="stationName")] pub station_name: String, } impl ToStationToken for Station { fn to_station_token(&self) -> String { self.station_id.clone() } } #[derive(Debug, Deserialize)] struct StationList { pub stations: Vec<Station>, pub checksum: String, } #[derive(Deserialize)] pub struct StationListChecksum { pub checksum: String, } #[derive(Debug, Deserialize)] pub struct ExtendedStation { #[serde(rename="stationId")] pub station_id: String, #[serde(rename="stationName")] pub station_name: String, #[serde(rename="artUrl")] pub art_url: Option<String>, pub music: Option<StationMusic>, } #[derive(Debug, Deserialize)] pub struct StationMusic { pub songs: Vec<SongSeed>, pub artists: Vec<ArtistSeed>, pub genre: Option<Vec<GenreSeed>>, } #[derive(Debug, Deserialize)] pub struct Seed { #[serde(rename="seedId")] pub seed_id: String, } #[derive(Debug, Deserialize)] pub struct SongSeed { #[serde(rename="seedId")] pub seed_id: String, #[serde(rename="artistName")] pub artist_name: String, #[serde(rename="artUrl")] pub art_url: String, #[serde(rename="songName")] pub song_name: String, #[serde(rename="musicToken")] pub music_token: String, } #[derive(Debug, Deserialize)] pub struct ArtistSeed { #[serde(rename="seedId")] pub seed_id: String, #[serde(rename="artistName")] pub artist_name: String, #[serde(rename="artUrl")] pub art_url: String, #[serde(rename="musicToken")] pub music_token: String, } #[derive(Debug, Deserialize)] pub struct GenreSeed { #[serde(rename="seedId")] pub seed_id: String, #[serde(rename="artistName")] pub genre_name: String, #[serde(rename="musicToken")] pub music_token: String, } #[derive(Serialize)] struct CreateStationRequest { #[serde(rename="trackToken")] track_token: Option<String>, #[serde(rename="musicType")] music_type: Option<MusicType>, #[serde(rename="musicToken")] music_token: Option<String>, } #[derive(Serialize)] struct RenameStationRequest { #[serde(rename="stationToken")] station_token: String, #[serde(rename="stationName")] station_name: String, } #[derive(Serialize)] struct DeleteStationRequest { #[serde(rename="stationToken")] station_token: String, } #[derive(Serialize)] struct GetStationRequest { #[serde(rename="stationToken")] station_token: String, #[serde(rename="includeExtendedAttributes")] include_extended_attributes: bool, } #[derive(Serialize)] struct AddSeedRequest { #[serde(rename="stationToken")] station_token: String, #[serde(rename="musicToken")] music_token: String, } #[derive(Serialize)] struct RemoveSeedRequest { #[serde(rename="seedId")] seed_id: String, }
where T: ToStationToken { self.pandora .post_noop(Method::StationDeleteStation, Some(serde_json::to_value(DeleteStationRequest { station_token: station.to_station_token(), }))) }
function_block-function_prefix_line
[ { "content": "/// Returns the encrypted input using the given key.\n\n///\n\n/// The returned string is encoded in hexadecimal notation,\n\n/// which is a UTF-8 string, so it's fine to return it using\n\n/// the `String` type.\n\npub fn encrypt(key: &str, input: &str) -> String {\n\n let cipherbytes = cipher...
Rust
src/main.rs
cerrno/winnow
f172e648a9b69ac6dd0bc42ac753c173d89ad962
use std::collections::HashMap; use std::env; use std::io; use std::path::Path; use std::process::Command; use winnow::detector; use winnow::winnowing::{parse_patch, Fingerprint}; use colored::*; use indicatif::ProgressIterator; struct Repo { name: String, path: String, patches: Vec<String>, } impl Repo { fn new(repo: &str) -> io::Result<Self> { let repo_dir = Path::new(repo).file_name().unwrap(); let repo = Repo { name: repo_dir.to_str().unwrap().to_owned(), path: repo.to_owned(), patches: vec![], }; repo.git_clone()?; Ok(repo) } fn git_clone(&self) -> io::Result<()> { let clone_cmd = Command::new("git") .arg("clone") .arg("--bare") .arg(&self.path) .output()?; if clone_cmd.status.code().unwrap() == 128 { println!("{}", format!("repo {} already exists", self.path).yellow()); } else if !clone_cmd.status.success() { panic!("cannot clone repo {}", self.path); } Ok(()) } /* fn patches(&mut self) -> io::Result<()> { let start = empty_tree_hash()?; self.patches_since(&start) } */ fn make_patches_since(&mut self, start_hash: &str) -> io::Result<()> { let git_cmd = Command::new("git") .arg("format-patch") .arg("-k") .arg(start_hash) .current_dir(&self.name) .output()?; if !git_cmd.status.success() { println!("{}", String::from_utf8(git_cmd.stderr).unwrap()); panic!("cannot git format-patch"); } for l in String::from_utf8(git_cmd.stdout).unwrap().lines() { let mut s = self.name.clone(); s.push_str("/"); s.push_str(l); self.patches.push(s); } Ok(()) } fn parse_patches(&self) -> Vec<Fingerprint> { let mut out = vec![]; for p in self.patches.iter().progress() { out.append(&mut parse_patch(&p, &self.name)); } out } } fn empty_tree_hash() -> io::Result<String> { let hash = Command::new("git") .arg("hash-object") .arg("-t") .arg("tree") .arg("/dev/null") .output()?; if !hash.status.success() { panic!("cannot git hash-object"); } Ok(String::from_utf8(hash.stdout).unwrap().trim().to_owned()) } fn main() -> io::Result<()> { let args: Vec<String> = env::args().collect(); let (repo1, repo2, start_hash) = match args.len() { 3 => (args[1].clone(), args[2].clone(), empty_tree_hash()?), 4 => (args[1].clone(), args[2].clone(), args[3].clone()), _ => panic!("Invalid number of arguments"), }; let mut fingerprint_map: HashMap<String, Vec<Fingerprint>> = HashMap::new(); let mut repo = Repo::new(&repo1)?; repo.make_patches_since(&start_hash)?; let fingerprints = repo.parse_patches(); fingerprint_map.insert(repo.name, fingerprints); let mut repo = Repo::new(&repo2)?; repo.make_patches_since(&start_hash)?; let fingerprints = repo.parse_patches(); fingerprint_map.insert(repo.name, fingerprints); detector::run(fingerprint_map); Ok(()) }
use std::collections::HashMap; use std::env; use std::io; use std::path::Path; use std::process::Command; use winnow::detector; use winnow::winnowing::{parse_patch, Fingerprint}; use colored::*; use indicatif::ProgressIterator; struct Repo { name: String, path: String, patches: Vec<String>, } impl Repo { fn new(repo: &str) -> io::Result<Self> {
fn git_clone(&self) -> io::Result<()> { let clone_cmd = Command::new("git") .arg("clone") .arg("--bare") .arg(&self.path) .output()?; if clone_cmd.status.code().unwrap() == 128 { println!("{}", format!("repo {} already exists", self.path).yellow()); } else if !clone_cmd.status.success() { panic!("cannot clone repo {}", self.path); } Ok(()) } /* fn patches(&mut self) -> io::Result<()> { let start = empty_tree_hash()?; self.patches_since(&start) } */ fn make_patches_since(&mut self, start_hash: &str) -> io::Result<()> { let git_cmd = Command::new("git") .arg("format-patch") .arg("-k") .arg(start_hash) .current_dir(&self.name) .output()?; if !git_cmd.status.success() { println!("{}", String::from_utf8(git_cmd.stderr).unwrap()); panic!("cannot git format-patch"); } for l in String::from_utf8(git_cmd.stdout).unwrap().lines() { let mut s = self.name.clone(); s.push_str("/"); s.push_str(l); self.patches.push(s); } Ok(()) } fn parse_patches(&self) -> Vec<Fingerprint> { let mut out = vec![]; for p in self.patches.iter().progress() { out.append(&mut parse_patch(&p, &self.name)); } out } } fn empty_tree_hash() -> io::Result<String> { let hash = Command::new("git") .arg("hash-object") .arg("-t") .arg("tree") .arg("/dev/null") .output()?; if !hash.status.success() { panic!("cannot git hash-object"); } Ok(String::from_utf8(hash.stdout).unwrap().trim().to_owned()) } fn main() -> io::Result<()> { let args: Vec<String> = env::args().collect(); let (repo1, repo2, start_hash) = match args.len() { 3 => (args[1].clone(), args[2].clone(), empty_tree_hash()?), 4 => (args[1].clone(), args[2].clone(), args[3].clone()), _ => panic!("Invalid number of arguments"), }; let mut fingerprint_map: HashMap<String, Vec<Fingerprint>> = HashMap::new(); let mut repo = Repo::new(&repo1)?; repo.make_patches_since(&start_hash)?; let fingerprints = repo.parse_patches(); fingerprint_map.insert(repo.name, fingerprints); let mut repo = Repo::new(&repo2)?; repo.make_patches_since(&start_hash)?; let fingerprints = repo.parse_patches(); fingerprint_map.insert(repo.name, fingerprints); detector::run(fingerprint_map); Ok(()) }
let repo_dir = Path::new(repo).file_name().unwrap(); let repo = Repo { name: repo_dir.to_str().unwrap().to_owned(), path: repo.to_owned(), patches: vec![], }; repo.git_clone()?; Ok(repo) }
function_block-function_prefix_line
[ { "content": "pub fn parse_patch(path: &str, repo: &str) -> Vec<Fingerprint> {\n\n let patch = fs::read_to_string(path).unwrap();\n\n let mut patchset = PatchSet::new();\n\n if let Err(e) = patchset.parse(&patch) {\n\n println!(\"{:?}\", e);\n\n return vec![];\n\n }\n\n let commit_h...
Rust
bindings/src/event_bindings.rs
stumptownlabs/beeper-android-seshat
2de21b9002f72ac083a143629e0ad3d806fd63ce
extern crate jni; extern crate seshat; use jni::sys::{jlong, jboolean, jstring}; use jni::JNIEnv; use jni::objects::{JObject, JString, JValue}; use seshat::{Event, EventType}; use crate::utils::*; /* * EVENT BINDINGS */ #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1new_1event( env: JNIEnv, _: JObject, j_event_type: jlong, j_content_value: JString, j_has_msg_type: jboolean, j_msg_type: JString, j_event_id: JString, j_sender: JString, j_server_ts: jlong, j_room_id: JString, ) -> jlong { let event_type: EventType = match j_event_type { 1 => EventType::Name, 2 => EventType::Topic, _ => EventType::Message, }; let content_value = jstring_to_string(&env, j_content_value); let msg_type_string = jstring_to_string(&env, j_msg_type); let msg_type = match j_has_msg_type { 0 => None, _ => Some(msg_type_string.as_str()) }; let event_id = jstring_to_string(&env, j_event_id); let sender = jstring_to_string(&env, j_sender); let server_ts = j_server_ts; let room_id = jstring_to_string(&env, j_room_id); let proto_event = Event::new( event_type.clone(), content_value.as_str(), msg_type, event_id.as_str(), sender.as_str(), server_ts, room_id.as_str(), "", ); let event_source = event_to_json(proto_event).unwrap(); let event = Event::new( event_type, content_value.as_str(), msg_type, event_id.as_str(), sender.as_str(), server_ts, room_id.as_str(), event_source.as_str(), ); Box::into_raw(Box::new(event)) as jlong } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1free_1event( _: JNIEnv, _: JObject, event_ptr: jlong, ) { Box::from_raw(event_ptr as *mut Event); } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1event_1from_1json( env: JNIEnv, _: JObject, j_event_source: JString, j_result: JObject ) { let event_source = jstring_to_string(&env,j_event_source); let result = partial_event_from_json(&event_source.as_str()); match result { Ok(event) => { let event_pointer = Box::into_raw(Box::new(event)) as jlong; let jvm_long_field_id_type = "J"; let event_ptr_field_name = "resultPtr"; env.set_field( j_result, event_ptr_field_name, jvm_long_field_id_type, JValue::from(event_pointer), ) .unwrap(); } Err(err) => { let error_message = err.to_string(); let io_error = seshat::Error::IOError(err); let error_code = seshat_error_code(io_error); let jvm_int_field_id_type = "I"; let error_code_field_name = "errorCode"; env.set_field( j_result, error_code_field_name, jvm_int_field_id_type, JValue::from(error_code), ) .unwrap(); let jvm_int_field_id_type = "Ljava/lang/String;"; let error_message_field_name = "errorMessage"; let j_error_message = env.new_string(error_message).unwrap(); let jvalue = j_error_message.into_inner(); env.set_field( j_result, error_message_field_name, jvm_int_field_id_type, JValue::from(JObject::from(jvalue)), ) .unwrap(); } }; } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1get_1event_1type( _: JNIEnv, _: JObject, event_ptr: jlong, ) -> jlong { let event = Box::from_raw(event_ptr as *mut Event); let event_type = event.event_type.clone(); Box::leak(event); match event_type { EventType::Message => { 0 } EventType::Name => { 1 } EventType::Topic => { 2 } } } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1get_1event_1content_1value( env: JNIEnv, _: JObject, event_ptr: jlong, ) -> jstring { let event = Box::from_raw(event_ptr as *mut Event); let content_value = event.content_value.clone(); Box::leak(event); let output = env.new_string(content_value).unwrap(); output.into_inner() } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1get_1event_1id( env: JNIEnv, _: JObject, event_ptr: jlong, ) -> jstring { let event = Box::from_raw(event_ptr as *mut Event); let event_id = event.event_id.clone(); Box::leak(event); let output = env.new_string(event_id).unwrap(); output.into_inner() } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1get_1event_1sender( env: JNIEnv, _: JObject, event_ptr: jlong, ) -> jstring { let event = Box::from_raw(event_ptr as *mut Event); let sender = event.sender.clone(); Box::leak(event); let output = env.new_string(sender).unwrap(); output.into_inner() } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1get_1event_1server_1ts( _: JNIEnv, _: JObject, event_ptr: jlong, ) -> jlong { let event = Box::from_raw(event_ptr as *mut Event); let server_ts = event.server_ts.clone(); Box::leak(event); server_ts } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1get_1event_1room_1id( env: JNIEnv, _: JObject, event_ptr: jlong, ) -> jstring { let event = Box::from_raw(event_ptr as *mut Event); let room_id = event.room_id.clone(); Box::leak(event); let output = env.new_string(room_id).unwrap(); output.into_inner() } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1get_1event_1message_1type( env: JNIEnv, _: JObject, event_ptr: jlong, ) -> jstring { let event = Box::from_raw(event_ptr as *mut Event); let option = event.msgtype.clone(); let message_type = match option{ None => {String::from("")} Some(msgtype) => { msgtype } }; Box::leak(event); let output = env.new_string(message_type).unwrap(); output.into_inner() }
extern crate jni; extern crate seshat; use jni::sys::{jlong, jboolean, jstring}; use jni::JNIEnv; use jni::objects::{JObject, JString, JValue}; use seshat::{Event, EventType}; use crate::utils::*; /* * EVENT BINDINGS */ #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1new_1event( env: JNIEnv, _: JObject, j_event_type: jlong, j_content_value: JString, j_has_msg_type: jboolean, j_msg_type: JString, j_event_id: JString, j_sender: JString, j_server_ts: jlong, j_room_id: JString, ) -> jlong { let event_type: EventType = match j_event_type { 1 => EventType::Name, 2 => EventType::Topic, _ => EventType::Message, }; let content_value = jstring_to_string(&env, j_content_value); let msg_type_string = jstring_to_string(&env, j_msg_type); let msg_type = match j_has_msg_type { 0 => None, _ => Some(msg_type_string.as_str()) }; let event_id = jstring_to_string(&env, j_event_id); let sender = jstring_to_string(&env, j_sender); let server_ts = j_server_ts; let room_id = jstring_to_string(&env, j_room_id); let proto_event = Event::new( event_type.clone(), content_value.as_str(), msg_type, event_id.as_str(), sender.as_str(), server_ts, room_id.as_str(), "", ); let event_source = event_to_json(proto_event).unwrap(); let event = Event::new( event_type, content_value.as_str(), msg_type, event_id.as_str(), sender.as_str(), server_ts, room_id.as_str(), event_source.as_str(), ); Box::into_raw(Box::new(event)) as jlong } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1free_1event( _: JNIEnv, _: JObject, event_ptr: jlong, ) { Box::from_raw(event_ptr as *mut Event); } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1event_1from_1json( env: JNIEnv, _: JObject, j_event_source: JString, j_result: JObject ) { let event_source = jstring_to_string(&env,j_event_source); let result = partial_event_from_json(&event_source.as_str()); match result { Ok(event) => { let event_pointer = Box::into_raw(Box::new(event)) as jlong; let jvm_long_field_id_type = "J"; let event_ptr_field_name = "resultPtr"; env.set_field( j_result, event_ptr_field_name, jvm_long_field_id_type, JValue::from(event_pointer), ) .unwrap(); } Err(err) => { let error_message = err.to_string(); let io_error = seshat::Error::IOError(err); let error_code = seshat_error_code(io_error); let jvm_int_field_id_type = "I"; let error_code_field_name = "errorCode"; env.set_field( j_result, error_code_field_name, jvm_int_field_id_type, JValue::from(error_code), ) .unwrap(); let jvm_int_field_id_type = "Ljava/lang/String;"; let error_message_field_name = "errorMessage"; let j_error_message = env.new_string(error_message).unwrap(); let jvalue = j_error_message.into_inner(); env.set_field( j_result, error_message_field_name, jvm_int_field_id_type, JValue::from(JObject::from(jvalue)), ) .unwrap(); } }; } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1get_1event_1type( _: JNIEnv, _: JObject, event_ptr: jlong, ) -> jlong { let event = Box::from_raw(event_ptr as *mut Event); let event_type = event.event_type.clone(); Box::leak(event); match event_type { EventType::Message => { 0 } EventType::Name => { 1 } EventType::Topic => { 2 } } } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1get_1event_1content_1value( env: JNIEnv, _: JObject, event_ptr: jlong, ) -> jstring { let event = Box::from_raw(event_ptr as *mut Event); let content_value = event.content_value.clone(); Box::leak(event); let output = env.new_string(content_value).unwrap(); output.into_inner() } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1get_1event_1id( env: JNIEnv, _: JObject, event_ptr: jlong, ) -> jstring { let event = Box::from_raw(event_ptr as *mut Event); let event_id = event.event_id.clone(); Box::leak(event); let output = env.new_string(event_id).unwrap(); output.into_inner() } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1get_1event_1sender( env: JNIEnv, _: JObject, event_ptr: jlong, ) -> jstring { let event = Box::from_raw(event_ptr as *mut Event); let sender = event.sender.clone(); Box::leak(event); let output = env.new_string(sender).unwrap(); output.into_inner() } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1get_1event_1server_1ts( _: JNIEnv, _: JObject, event_ptr: jlong, ) -> jlong { let event = Box::from_raw(event_ptr as *mut Event); let server_ts = event.server_ts.clone(); Box::leak(event); server_ts } #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1get_1event_1room_1id( env: JNIEnv, _: JObject, event_ptr: jlong, ) -> jstring { let event = Box::from_raw(event_ptr as *mut Event); let room_id = event.room_id.clone(); Box::leak(event); let output = env.new_string(room_id).unwrap(); output.into_inner() } #[no_mangle] p
{ let event = Box::from_raw(event_ptr as *mut Event); let option = event.msgtype.clone(); let message_type = match option{ None => {String::from("")} Some(msgtype) => { msgtype } }; Box::leak(event); let output = env.new_string(message_type).unwrap(); output.into_inner() }
ub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1get_1event_1message_1type( env: JNIEnv, _: JObject, event_ptr: jlong, ) -> jstring
function_block-random_span
[ { "content": "pub fn event_to_json(event: Event) -> Result<String,serde_json::error::Error> {\n\n match serde_json::to_string(&event){\n\n Ok(json) => {\n\n Ok(json)\n\n }\n\n Err(error) => {\n\n Err(error)\n\n }\n\n }\n\n}\n\n\n", "file_path": "bindin...
Rust
src/traits.rs
dhylands/serial-framing-protocol-rs
2f8cee9611891e494023f797ecb847249dffca3f
use core::cmp::min; use core::fmt; use core::mem::size_of; use log::info; use pretty_hex::*; use crate::crc::{Crc, CrcAccum}; pub const SOF: u8 = 0x7e; pub const ESC: u8 = 0x7d; pub const ESC_FLIP: u8 = 0x20; pub trait PacketBuffer { fn capacity(&self) -> usize; fn len(&self) -> usize; fn set_len(&mut self, len: usize); fn data(&self) -> &[u8]; fn data_mut(&mut self) -> &mut [u8]; fn store_byte_at(&mut self, idx: usize, byte: u8) { self.data_mut()[idx] = byte; } fn store_data(&mut self, data: &[u8]) { let copy_len = min(data.len(), self.capacity()); self.data_mut()[..copy_len].copy_from_slice(&data[..copy_len]); self.set_len(copy_len); } fn is_empty(&self) -> bool { self.len() == 0 } fn reset(&mut self) { self.set_len(0); } fn append(&mut self, byte: u8) -> Result<(), ()> { let len = self.len(); if len < self.capacity() { self.set_len(len + 1); self.store_byte_at(len, byte); Ok(()) } else { Err(()) } } fn remove_crc(&mut self) -> CrcAccum { let mut len = self.len(); if len < size_of::<CrcAccum>() { return 0; } len -= 2; let data = self.data(); let crc = ((data[len + 1] as CrcAccum) << 8) | (data[len] as CrcAccum); self.set_len(len); crc } fn dump(&self) { info!("{:?}", self.data().hex_dump()); } } impl fmt::Debug for dyn PacketBuffer { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self.data().hex_dump()) } } pub trait PacketWriter { fn start_write(&mut self) {} fn write_byte(&mut self, byte: u8); fn end_write(&mut self) {} fn write_packet_data(&mut self, header: u8, bytes: &[u8]) { info!( "write_packet_data header: 0x{:02x} len: {}", header, bytes.len() ); let mut crc = Crc::new(); self.start_write(); self.write_byte(SOF); self.write_escaped_byte(&mut crc, header); self.write_escaped_bytes(&mut crc, bytes); self.write_crc(&mut crc); self.write_byte(SOF); self.end_write(); } fn write_crc(&mut self, crc: &mut Crc) { let crc_lsb = crc.lsb(); let crc_msb = crc.msb(); self.write_escaped_byte(crc, crc_lsb); self.write_escaped_byte(crc, crc_msb); } fn write_escaped_bytes(&mut self, crc: &mut Crc, bytes: &[u8]) { for byte in bytes { self.write_escaped_byte(crc, *byte); } } fn write_escaped_byte(&mut self, crc: &mut Crc, byte: u8) { crc.accum(byte); if byte == ESC || byte == SOF { self.write_byte(ESC); self.write_byte(byte ^ ESC_FLIP); } else { self.write_byte(byte); } } } pub trait PacketQueue { fn capacity(&self) -> usize; fn len(&self) -> usize; fn set_len(&mut self, len: usize); fn idx(&self) -> usize; fn set_idx(&mut self, len: usize); fn packet(&mut self, idx: usize) -> Option<&mut dyn PacketBuffer>; fn clear(&mut self) { self.set_len(0); self.set_idx(0); } fn next(&mut self) -> &mut dyn PacketBuffer { if self.len() < self.capacity() { self.set_len(self.len() + 1); } self.set_idx((self.idx() + 1) % self.capacity()); self.packet(self.idx()).unwrap() } fn get(&mut self, offset: usize) -> Option<&mut dyn PacketBuffer> { if offset < self.len() { let idx = if self.idx() < offset { self.idx() + self.capacity() - offset } else { self.idx() - offset }; self.packet(idx) } else { None } } } pub trait Storage { fn rx_buf(&mut self) -> &mut dyn PacketBuffer; fn tx_writer(&mut self) -> &mut dyn PacketWriter; fn tx_queue(&mut self) -> &mut dyn PacketQueue; }
use core::cmp::min; use core::fmt; use core::mem::size_of; use log::info; use pretty_hex::*; use crate::crc::{Crc, CrcAccum}; pub const SOF: u8 = 0x7e; pub const ESC: u8 = 0x7d; pub const ESC_FLIP: u8 = 0x20; pub trait PacketBuffer { fn capacity(&self) -> usize; fn len(&self) -> usize; fn set_len(&mut self, len: usize); fn data(&self) -> &[u8]; fn data_mut(&mut self) -> &mut [u8]; fn store_byte_at(&mut self, idx: usize, byte: u8) { self.data_mut()[idx] = byte; } fn store_data(&mut self, data: &[u8]) { let copy_len = min(data.len(), self.capacity()); self.data_mut()[..copy_len].copy_from_slice(&data[..copy_len]); self.set_len(copy_len); } fn is_empty(&self) -> bool { self.len() == 0 } fn reset(&mut self) { self.set_len(0); } fn append(&mut self, byte: u8) -> Result<(), ()> { let len = self.len(); if len < self.capacity() { self.set_len(len + 1); self.store_byte_at(len, byte); Ok(()) } else { Err(()) } } fn remove_crc(&mut self) -> CrcAccum { l
] as CrcAccum); self.set_len(len); crc } fn dump(&self) { info!("{:?}", self.data().hex_dump()); } } impl fmt::Debug for dyn PacketBuffer { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self.data().hex_dump()) } } pub trait PacketWriter { fn start_write(&mut self) {} fn write_byte(&mut self, byte: u8); fn end_write(&mut self) {} fn write_packet_data(&mut self, header: u8, bytes: &[u8]) { info!( "write_packet_data header: 0x{:02x} len: {}", header, bytes.len() ); let mut crc = Crc::new(); self.start_write(); self.write_byte(SOF); self.write_escaped_byte(&mut crc, header); self.write_escaped_bytes(&mut crc, bytes); self.write_crc(&mut crc); self.write_byte(SOF); self.end_write(); } fn write_crc(&mut self, crc: &mut Crc) { let crc_lsb = crc.lsb(); let crc_msb = crc.msb(); self.write_escaped_byte(crc, crc_lsb); self.write_escaped_byte(crc, crc_msb); } fn write_escaped_bytes(&mut self, crc: &mut Crc, bytes: &[u8]) { for byte in bytes { self.write_escaped_byte(crc, *byte); } } fn write_escaped_byte(&mut self, crc: &mut Crc, byte: u8) { crc.accum(byte); if byte == ESC || byte == SOF { self.write_byte(ESC); self.write_byte(byte ^ ESC_FLIP); } else { self.write_byte(byte); } } } pub trait PacketQueue { fn capacity(&self) -> usize; fn len(&self) -> usize; fn set_len(&mut self, len: usize); fn idx(&self) -> usize; fn set_idx(&mut self, len: usize); fn packet(&mut self, idx: usize) -> Option<&mut dyn PacketBuffer>; fn clear(&mut self) { self.set_len(0); self.set_idx(0); } fn next(&mut self) -> &mut dyn PacketBuffer { if self.len() < self.capacity() { self.set_len(self.len() + 1); } self.set_idx((self.idx() + 1) % self.capacity()); self.packet(self.idx()).unwrap() } fn get(&mut self, offset: usize) -> Option<&mut dyn PacketBuffer> { if offset < self.len() { let idx = if self.idx() < offset { self.idx() + self.capacity() - offset } else { self.idx() - offset }; self.packet(idx) } else { None } } } pub trait Storage { fn rx_buf(&mut self) -> &mut dyn PacketBuffer; fn tx_writer(&mut self) -> &mut dyn PacketWriter; fn tx_queue(&mut self) -> &mut dyn PacketQueue; }
et mut len = self.len(); if len < size_of::<CrcAccum>() { return 0; } len -= 2; let data = self.data(); let crc = ((data[len + 1] as CrcAccum) << 8) | (data[len
function_block-random_span
[ { "content": "// Parse a bunch of bytes and return the first return code that isn't\n\n// MoreDataNeeded. This means that this function will parse at most one\n\n// error or packet from the input stream, which is fine for testing.\n\npub fn parse_bytes(\n\n parser: &mut RawPacketParser,\n\n bytes: &[u8],\...
Rust
src/tokenizer/words.rs
naughie/kytea-tokenizer
8dd76fae807c2bd0d9f773cef2089b13b3ef7570
use super::Word; use crate::kytea::{DELIM, ESCAPE}; use std::num::NonZeroUsize; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub struct Words<'a> { inner: &'a str, } impl<'a> Iterator for Words<'a> { type Item = Word<'a>; fn next(&mut self) -> Option<Self::Item> { let pos = self.find_sow(); self.inner = &self.inner[pos..]; let pos = self.find_eow()?.get(); let inner = &self.inner[..pos]; self.inner = &self.inner[pos..]; Some(Word { inner }) } } impl<'a> DoubleEndedIterator for Words<'a> { fn next_back(&mut self) -> Option<Self::Item> { let pos = self.rfind_eow()?.get(); self.inner = &self.inner[..pos]; let pos = self.rfind_sow(); let inner = &self.inner[pos..]; self.inner = &self.inner[..pos]; Some(Word { inner }) } } impl<'a> From<&'a str> for Words<'a> { fn from(inner: &'a str) -> Self { Self { inner } } } impl Words<'_> { #[inline] fn len(self) -> usize { self.inner.len() } #[inline] fn is_empty(self) -> bool { self.inner.is_empty() } fn enumerate(&self) -> impl DoubleEndedIterator<Item = (usize, u8)> + '_ { self.inner.as_bytes().iter().copied().enumerate() } #[inline] fn renumerate(&self) -> impl Iterator<Item = (usize, u8)> + '_ { self.enumerate().rev() } fn find_sow(&self) -> usize { let mut it = self.enumerate().skip_while(|&(_, c)| c == DELIM); if let Some((i, _)) = it.next() { i } else { self.len() } } fn find_eow(&self) -> Option<NonZeroUsize> { if self.is_empty() { return None; } let mut prev_char = 0u8; for (i, c) in self.enumerate() { if c == DELIM && prev_char != ESCAPE { return unsafe { Some(NonZeroUsize::new_unchecked(i)) }; } prev_char = if c == ESCAPE && prev_char == ESCAPE { 0 } else { c }; } unsafe { Some(NonZeroUsize::new_unchecked(self.inner.len())) } } #[inline] fn iso_parity(i: usize, j: usize) -> bool { (i & 1) == (j & 1) } fn rfind_eow(&self) -> Option<NonZeroUsize> { let mut it = self.renumerate().skip_while(|&(_, c)| c == DELIM); if let Some((i, c)) = it.next() { if c == ESCAPE { let last = match it.filter(|&(_, c)| c == ESCAPE).last() { Some((j, _)) if !Self::iso_parity(i, j) => i + 1, _ => i + 2, }; unsafe { Some(NonZeroUsize::new_unchecked(last)) } } else { unsafe { Some(NonZeroUsize::new_unchecked(i + 1)) } } } else { None } } fn rfind_sow(&self) -> usize { let mut delim = 0; let mut delim_found = false; let mut broken = false; for (i, c) in self.renumerate() { if delim_found && c != ESCAPE { if Self::iso_parity(i, delim) { delim_found = false; } else { broken = true; break; } } if c == DELIM { delim_found = true; delim = i; } } if delim_found && (broken || Self::iso_parity(delim, 0)) { delim + 1 } else { 0 } } } #[cfg(test)] mod test { use super::*; #[test] fn test_words() { let s = ""; let mut words = Words::from(s); assert_eq!(words.next(), None); let s = "吾輩/名詞\tは/助詞\t\t猫/名詞\t /補助記号"; let mut words = Words::from(s); assert_eq!(words.next(), Some(Word::from("吾輩/名詞"))); assert_eq!(words.next(), Some(Word::from("は/助詞"))); assert_eq!(words.next(), Some(Word::from("猫/名詞"))); assert_eq!(words.next(), Some(Word::from(" /補助記号"))); assert_eq!(words.next(), None); let s = "ab\t\\\t/補助記号\t\\/\\\t\t\\\\\\\t/\\\\\t"; let mut words = Words::from(s); assert_eq!(words.next(), Some(Word::from("ab"))); assert_eq!(words.next(), Some(Word::from("\\\t/補助記号"))); assert_eq!(words.next(), Some(Word::from("\\/\\\t"))); assert_eq!(words.next(), Some(Word::from("\\\\\\\t/\\\\"))); assert_eq!(words.next(), None); } #[test] fn test_words_rev() { let s = ""; let mut words = Words::from(s).rev(); assert_eq!(words.next(), None); let s = "吾輩/名詞\tは/助詞\t\t猫/名詞\t /補助記号"; let mut words = Words::from(s).rev(); assert_eq!(words.next(), Some(Word::from(" /補助記号"))); assert_eq!(words.next(), Some(Word::from("猫/名詞"))); assert_eq!(words.next(), Some(Word::from("は/助詞"))); assert_eq!(words.next(), Some(Word::from("吾輩/名詞"))); assert_eq!(words.next(), None); let s = "\t\tab\t\\\t/補助記号\t\\/\\\t\t\\\\\\\t/\\\\\t"; let mut words = Words::from(s).rev(); assert_eq!(words.next(), Some(Word::from("\\\\\\\t/\\\\"))); assert_eq!(words.next(), Some(Word::from("\\/\\\t"))); assert_eq!(words.next(), Some(Word::from("\\\t/補助記号"))); assert_eq!(words.next(), Some(Word::from("ab"))); assert_eq!(words.next(), None); let s = "\ta"; let mut words = Words::from(s).rev(); assert_eq!(words.next(), Some(Word::from("a"))); assert_eq!(words.next(), None); let s = "\\\ta"; let mut words = Words::from(s).rev(); assert_eq!(words.next(), Some(Word::from("\\\ta"))); assert_eq!(words.next(), None); let s = "\\\\\ta"; let mut words = Words::from(s).rev(); assert_eq!(words.next(), Some(Word::from("a"))); assert_eq!(words.next(), Some(Word::from("\\\\"))); assert_eq!(words.next(), None); } #[test] fn test_words_mixed() { let s = "吾輩/名詞\tは/助詞\t\t猫/名詞\t /補助記号"; let mut words = Words::from(s); assert_eq!(words.next(), Some(Word::from("吾輩/名詞"))); assert_eq!(words.next_back(), Some(Word::from(" /補助記号"))); assert_eq!(words.next(), Some(Word::from("は/助詞"))); assert_eq!(words.next_back(), Some(Word::from("猫/名詞"))); assert_eq!(words.next(), None); assert_eq!(words.next_back(), None); } }
use super::Word; use crate::kytea::{DELIM, ESCAPE}; use std::num::NonZeroUsize; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub struct Words<'a> { inner: &'a str, } impl<'a> Iterator for Words<'a> { type Item = Word<'a>; fn next(&mut self) -> Option<Self::Item> { let pos = self.find_sow(); self.inner = &self.inner[pos..]; let pos = self.find_eow()?.get(); let inner = &self.inner[..pos]; self.inner = &self.inner[pos..]; Some(Word { inner }) } } impl<'a> DoubleEndedIterator for Words<'a> { fn next_back(&mut self) -> Option<Self::Item> { let pos = self.rfind_eow()?.get(); self.inner = &self.inner[..pos]; let pos = self.rfind_sow(); let inner = &self.inner[pos..]; self.inner = &self.inner[..pos]; Some(Word { inner }) } } impl<'a> From<&'a str> for Words<'a> { fn from(inner: &'a str) -> Self { Self { inner } } } impl Words<'_> { #[inline] fn len(self) -> usize { self.inner.len() } #[inline] fn is_empty(self) -> bool { self.inner.is_empty() } fn enumerate(&self) -> impl DoubleEndedIterator<Item = (usize, u8)> + '_ { self.inner.as_bytes().iter().copied().enumerate() } #[inline] fn renumerate(&self) -> impl Iterator<Item = (usize, u8)> + '_ { self.enumerate().rev() } fn find_sow(&self) -> usize { let mut it = self.enumerate().skip_while(|&(_, c)| c == DELIM); if let Some((i, _)) = it.next() { i } else { self.len() } } fn find_eow(&self) -> Option<NonZeroUsize> { if self.is_empty() { return None; } let mut prev_char = 0u8; for (i, c) in self.enumerate() { if c == DELIM && prev_char != ESCAPE { return unsafe { Some(NonZeroUsize::new_unchecked(i)) }; } prev_char = if c == ESCAPE && prev_char == ESCAPE { 0 } else { c }; } unsafe { Some(NonZeroUsize::new_unchecked(self.inner.len())) } } #[inline] fn iso_parity(i: usize, j: usize) -> bool { (i & 1) == (j & 1) } fn rfind_eow(&self) -> Option<NonZeroUsize> { let mut it = self.renumerate().skip_while(|&(_, c)| c == DELIM); if let Some((i, c)) = it.next() { if c == ESCAPE { let last = match it.filter(|&(_, c)| c == ESCAPE).last() { Some((j, _)) if !Self::iso_parity(i, j) => i + 1, _ => i + 2, }; unsafe { Some(NonZeroUsize::new_unchecked(last)) } } else { unsafe { Some(NonZeroUsize::new_unchecked(i + 1)) } } } else { None } } fn rfind_sow(&self) -> usize { let mut delim = 0; let mut delim_found = false; let mut broken = false; for (i, c) in self.renumerate() { if delim_found && c != ESCAPE { if Self::iso_parity(i, delim) { delim_found = false; } else { broken = true; break; } } if c == DELIM { delim_found = true; delim = i; } } if delim_found && (broken || Self::iso_parity(delim, 0)) { delim + 1 } else { 0 } } } #[cfg(test)] mod test { use super::*; #[test] fn test_words() { let s = ""; let mut words = Words::from(s); assert_eq!(words.next(), None); let s = "吾輩/名詞\tは/助詞\t\t猫/名詞\t /補助記号"; let mut words = Words::from(s); assert_eq!(words.next(), Some(Word::from("吾輩/名詞"))); assert_eq!(words.next(), Some(Word::from("は/助詞"))); assert_eq!(words.next(), Some(Word::from("猫/名詞"))); assert_eq!(words.next(), Some(Word::from(" /補助記号"))); assert_eq!(words.next(), None); let s = "ab\t\\\t/補助記号\t\\/\\\t\t\\\\\\\t/\\\\\t"; let mut words = Words::from(s); assert_eq!(words.next(), Some(Word::from("ab"))); assert_eq!(words.next(), Some(Word::from("\\\t/補助記号"))); assert_eq!(words.next(), Some(Word::from("\\/\\\t"))); assert_eq!(words.next(), Some(Word::from("\\\\\\\t/\\\\"))); assert_eq!(words.next(), None); } #[test] fn test_words_rev() { let s = ""; let mut words = Words::from(s).rev(); assert_eq!(words.next(), None); let s = "吾輩/名詞\tは/助詞\t\t猫/名詞\t /補助記号"; let mut words = Words::from(s).rev(); assert_eq!(words.next(), Some(Word::from(" /補助
Words::from(s).rev(); assert_eq!(words.next(), Some(Word::from("a"))); assert_eq!(words.next(), Some(Word::from("\\\\"))); assert_eq!(words.next(), None); } #[test] fn test_words_mixed() { let s = "吾輩/名詞\tは/助詞\t\t猫/名詞\t /補助記号"; let mut words = Words::from(s); assert_eq!(words.next(), Some(Word::from("吾輩/名詞"))); assert_eq!(words.next_back(), Some(Word::from(" /補助記号"))); assert_eq!(words.next(), Some(Word::from("は/助詞"))); assert_eq!(words.next_back(), Some(Word::from("猫/名詞"))); assert_eq!(words.next(), None); assert_eq!(words.next_back(), None); } }
記号"))); assert_eq!(words.next(), Some(Word::from("猫/名詞"))); assert_eq!(words.next(), Some(Word::from("は/助詞"))); assert_eq!(words.next(), Some(Word::from("吾輩/名詞"))); assert_eq!(words.next(), None); let s = "\t\tab\t\\\t/補助記号\t\\/\\\t\t\\\\\\\t/\\\\\t"; let mut words = Words::from(s).rev(); assert_eq!(words.next(), Some(Word::from("\\\\\\\t/\\\\"))); assert_eq!(words.next(), Some(Word::from("\\/\\\t"))); assert_eq!(words.next(), Some(Word::from("\\\t/補助記号"))); assert_eq!(words.next(), Some(Word::from("ab"))); assert_eq!(words.next(), None); let s = "\ta"; let mut words = Words::from(s).rev(); assert_eq!(words.next(), Some(Word::from("a"))); assert_eq!(words.next(), None); let s = "\\\ta"; let mut words = Words::from(s).rev(); assert_eq!(words.next(), Some(Word::from("\\\ta"))); assert_eq!(words.next(), None); let s = "\\\\\ta"; let mut words =
random
[ { "content": "type WordsFrom<'a> = fn(&'a str) -> Words<'a>;\n", "file_path": "src/tokenizer/mod.rs", "rank": 0, "score": 100778.44098460334 }, { "content": "pub fn strip(out: impl AsRef<str>) -> String {\n\n let mut stripped = String::new();\n\n\n\n for line in out.as_ref().lines() {\...
Rust
src/auth.rs
FamiizCEO/modio-rs
101460ef3ba1c197025ba80cd01568defbc2d7e9
use std::fmt; use futures::Future as StdFuture; use url::form_urlencoded; use crate::Future; use crate::Modio; use crate::ModioMessage; #[derive(Clone, Debug, PartialEq)] pub enum Credentials { ApiKey(String), Token(String), } impl fmt::Display for Credentials { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Credentials::ApiKey(key) => f.write_str(&key), Credentials::Token(token) => f.write_str(&token), } } } pub enum Service { Steam(u64), Gog(u64), } pub struct Auth { modio: Modio, } #[derive(Deserialize)] struct AccessToken { access_token: String, } impl Auth { pub(crate) fn new(modio: Modio) -> Self { Self { modio } } pub fn request_code(&self, email: &str) -> Future<()> { apikey_required!(self.modio); let data = form_urlencoded::Serializer::new(String::new()) .append_pair("email", email) .finish(); Box::new( self.modio .post::<ModioMessage, _>("/oauth/emailrequest", data) .map(|_| ()), ) } pub fn security_code(&self, code: &str) -> Future<Credentials> { apikey_required!(self.modio); let data = form_urlencoded::Serializer::new(String::new()) .append_pair("security_code", code) .finish(); Box::new( self.modio .post::<AccessToken, _>("/oauth/emailexchange", data) .map(|token| Credentials::Token(token.access_token)), ) } pub fn link(&self, email: &str, service: Service) -> Future<()> { token_required!(self.modio); let (service, id) = match service { Service::Steam(id) => ("steam", id.to_string()), Service::Gog(id) => ("gog", id.to_string()), }; let data = form_urlencoded::Serializer::new(String::new()) .append_pair("email", email) .append_pair("service", service) .append_pair("service_id", &id) .finish(); Box::new( self.modio .post::<ModioMessage, _>("/external/link", data) .map(|_| ()), ) } pub fn gog_auth(&self, ticket: &str) -> Future<Credentials> { apikey_required!(self.modio); let data = form_urlencoded::Serializer::new(String::new()) .append_pair("appdata", ticket) .finish(); Box::new( self.modio .post::<AccessToken, _>("/external/galaxyauth", data) .map(|token| Credentials::Token(token.access_token)), ) } pub fn steam_auth(&self, ticket: &str) -> Future<Credentials> { apikey_required!(self.modio); let data = form_urlencoded::Serializer::new(String::new()) .append_pair("appdata", ticket) .finish(); Box::new( self.modio .post::<AccessToken, _>("/external/steamauth", data) .map(|token| Credentials::Token(token.access_token)), ) } }
use std::fmt; use futures::Future as StdFuture; use url::form_urlencoded; use crate::Future; use crate::Modio; use crate::ModioMessage; #[derive(Clone, Debug, PartialEq)] pub enum Credentials { ApiKey(String), Token(String), } impl fmt::Display for Credentials { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Credentials::ApiKey(key) => f.write_str(&key), Credentials::Token(token) => f.write_str(&token), } } } pub enum Service { Steam(u64), Gog(u64), } pub struct Auth { modio: Modio, } #[derive(Deserialize)] struct AccessToken { access_token: String, } impl Auth { pub(crate) fn new(modio: Modio) -> Self { Self { modio } } pub fn request_code(&self, email: &str) -> Future<()> { apikey_required!(self.modio); let data = form_urlencoded::Serializer::new(String::new()) .append_pair("email", email) .finish(); Box::new( self.modio .post::<ModioMessage, _>("/oauth/emailrequest", data) .map(|_| ()), ) }
pub fn link(&self, email: &str, service: Service) -> Future<()> { token_required!(self.modio); let (service, id) = match service { Service::Steam(id) => ("steam", id.to_string()), Service::Gog(id) => ("gog", id.to_string()), }; let data = form_urlencoded::Serializer::new(String::new()) .append_pair("email", email) .append_pair("service", service) .append_pair("service_id", &id) .finish(); Box::new( self.modio .post::<ModioMessage, _>("/external/link", data) .map(|_| ()), ) } pub fn gog_auth(&self, ticket: &str) -> Future<Credentials> { apikey_required!(self.modio); let data = form_urlencoded::Serializer::new(String::new()) .append_pair("appdata", ticket) .finish(); Box::new( self.modio .post::<AccessToken, _>("/external/galaxyauth", data) .map(|token| Credentials::Token(token.access_token)), ) } pub fn steam_auth(&self, ticket: &str) -> Future<Credentials> { apikey_required!(self.modio); let data = form_urlencoded::Serializer::new(String::new()) .append_pair("appdata", ticket) .finish(); Box::new( self.modio .post::<AccessToken, _>("/external/steamauth", data) .map(|token| Credentials::Token(token.access_token)), ) } }
pub fn security_code(&self, code: &str) -> Future<Credentials> { apikey_required!(self.modio); let data = form_urlencoded::Serializer::new(String::new()) .append_pair("security_code", code) .finish(); Box::new( self.modio .post::<AccessToken, _>("/oauth/emailexchange", data) .map(|token| Credentials::Token(token.access_token)), ) }
function_block-full_function
[ { "content": "fn prompt(prompt: &str) -> io::Result<String> {\n\n print!(\"{}\", prompt);\n\n io::stdout().flush()?;\n\n let mut buffer = String::new();\n\n io::stdin().read_line(&mut buffer)?;\n\n Ok(buffer.trim().to_string())\n\n}\n\n\n", "file_path": "examples/auth.rs", "rank": 0, ...
Rust
kg-syntax/src/lexer/nfa.rs
kodegenix/kg-lang
baa79ac7fb8babe82b6b8eed2af34d869523d8f4
use super::*; #[derive(Debug, Clone)] pub struct Nfa { states: Vec<State>, } impl Nfa { pub fn from_program(prog: &Program) -> Nfa { Builder::new().build(prog) } pub fn states(&self) -> &[State] { &self.states } } impl std::fmt::Display for Nfa { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for (i, s) in self.states.iter().enumerate() { write!(f, "({:4}): {}", i, s)?; } Ok(()) } } #[derive(Debug, Clone)] pub struct State { edges: Vec<Edge>, accept: Option<Accept>, } impl State { fn from(state: StateEx) -> State { debug_assert!(state.accepts.len() <= 1); debug_assert!(state.edges.len() > 0 || state.accepts.len() == 1); State { edges: state.edges, accept: state.accepts.get(0).cloned(), } } pub fn edges(&self) -> &[Edge] { &self.edges } pub fn accept(&self) -> Option<Accept> { self.accept } } impl std::fmt::Display for State { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some(a) = self.accept { write!(f, "{}\n", a)?; } else { write!(f, "\n")?; } if self.edges.is_empty() { write!(f, " -\n")?; } else { for e in self.edges.iter() { write!(f, " {}\n", e)?; } } Ok(()) } } struct Builder { states: Vec<StateEx>, } impl Builder { fn new() -> Builder { Builder { states: Vec::new(), } } fn merge_epsilon_states(&mut self, prog: &Program) { fn resolve_edges(pc: u32, edges: &mut SparseSet<u32>, prog: &Program, level: usize) { debug_assert!(level < prog.code().len()); if let Opcode::Split(g1, g2) = *prog.opcode(pc) { resolve_edges(g1, edges, prog, level + 1); resolve_edges(g2, edges, prog, level + 1); } else { edges.insert(pc); } } fn add_code(state: &mut StateEx, pc: u32, edges: &HashMap<u32, SparseSet<u32>>, prog: &Program, nested: bool) { debug_assert!(!state.merged_states.contains(&pc)); match *prog.opcode(pc) { Opcode::Match(m) => { state.accepts.push(Accept::new(pc, m)); state.merged_states.insert(pc); } Opcode::Byte(g, b) => { state.edges.push(Edge::new(b, g)); state.merged_states.insert(pc); } Opcode::Range(g, a, b) => { for i in a..=b { state.edges.push(Edge::new(i, g)); } state.merged_states.insert(pc); } Opcode::Mask(g, m) => { let m = prog.mask(m); for i in m.iter() { state.edges.push(Edge::new(i, g)); } state.merged_states.insert(pc); } Opcode::Split(..) => { debug_assert!(!nested); for s in edges.get(&pc).unwrap().iter().cloned() { add_code(state, s, edges, prog, true); } } } } let mut edge_map: HashMap<u32, SparseSet<u32>> = HashMap::with_capacity(prog.code().len()); for pc in 0..prog.code().len() as u32 { if let Opcode::Split(..) = prog.opcode(pc) { let mut e = SparseSet::with_capacity(prog.code().len()); resolve_edges(pc, &mut e, prog, 0); edge_map.insert(pc, e); } } let mut state_map = vec![EMPTY_GOTO; prog.code().len()]; let mut states: Vec<StateEx> = Vec::with_capacity(prog.code().len()); let mut pc = 0; let mut done = false; while !done { let mut state = StateEx::new(prog.code().len()); add_code(&mut state, pc, &edge_map, prog, false); let mut found = false; for (i, s) in states.iter().enumerate() { if *s == state { state_map[pc as usize] = i as u32; found = true; break; } } if !found { state_map[pc as usize] = states.len() as u32; states.push(state); } done = true; 'search_loop: for s in states.iter() { for e in s.edges.iter().cloned() { if state_map[e.state() as usize] == EMPTY_GOTO { pc = e.state(); done = false; break 'search_loop; } } } } for s in states.iter_mut() { for e in s.edges.iter_mut() { let t = state_map[e.state() as usize]; debug_assert_ne!(t, EMPTY_GOTO); *e = Edge::new(e.value(), t); } } self.states = states; } fn build(mut self, prog: &Program) -> Nfa { self.merge_epsilon_states(prog); let mut states = Vec::with_capacity(self.states.len()); for state in self.states { debug_assert!(state.accepts.len() <= 1); states.push(State::from(state)); } Nfa { states } } } #[cfg(test)] mod tests { use super::*; #[test] fn test1() { let re = Regex::parse("aa*bb+|bb").unwrap(); let p = Program::from_regex(&re, 1); println!("{}", p); println!("{}", Nfa::from_program(&p)); } }
use super::*; #[derive(Debug, Clone)] pub struct Nfa { states: Vec<State>, } impl Nfa { pub fn from_program(prog: &Program) -> Nfa { Builder::new().build(prog) } pub fn states(&self) -> &[State] { &self.states } } impl std::fmt::Display for Nfa { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for (i, s) in self.states.iter().enumerate() { write!(f, "({:4}): {}", i, s)?; } Ok(()) } } #[derive(Debug, Clone)] pub struct State { edges: Vec<Edge>, accept: Option<Accept>, } impl State { fn from(state: StateEx) -> State { debug_assert!(state.accepts.len() <= 1); debug_assert!(state.edges.len() > 0 || state.accepts.len() == 1); State { edges: state.edges, accept: state.accepts.get(0).cloned(), } } pub fn edges(&self) -> &[Edge] { &self.edges } pub fn accept(&self) -> Option<Accept> { self.accept } } impl std::fmt::Display for State { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some(a) = self.accept { write!(f, "{}\n", a)?; } else { write!(f, "\n")?; } if self.edges.is_empty() { write!(f, " -\n")?; } else { for e in self.edges.iter() { write!(f, " {}\n", e)?; } } Ok(()) } } struct Builder { states: Vec<StateEx>, } impl Builder { fn new() -> Builder { Builder { states: Vec::new(), } } fn merge_epsilon_states(&mut self, prog: &Program) { fn resolve_edges(pc: u32, edges: &mut SparseSet<u32>, prog: &Program, level: usize) { debug_assert!(level < prog.code().len()); if let Opcode::Split(g1, g2) = *prog.opcode(pc) { resolve_edges(g1, edges, prog, level + 1); resolve_edges(g2, edges, prog, level + 1); } else { edges.insert(pc); } } fn add_code(state: &mut StateEx, pc: u32, edges: &HashMap<u32, SparseSet<u32>>, prog: &Program, nested:
ates.iter().enumerate() { if *s == state { state_map[pc as usize] = i as u32; found = true; break; } } if !found { state_map[pc as usize] = states.len() as u32; states.push(state); } done = true; 'search_loop: for s in states.iter() { for e in s.edges.iter().cloned() { if state_map[e.state() as usize] == EMPTY_GOTO { pc = e.state(); done = false; break 'search_loop; } } } } for s in states.iter_mut() { for e in s.edges.iter_mut() { let t = state_map[e.state() as usize]; debug_assert_ne!(t, EMPTY_GOTO); *e = Edge::new(e.value(), t); } } self.states = states; } fn build(mut self, prog: &Program) -> Nfa { self.merge_epsilon_states(prog); let mut states = Vec::with_capacity(self.states.len()); for state in self.states { debug_assert!(state.accepts.len() <= 1); states.push(State::from(state)); } Nfa { states } } } #[cfg(test)] mod tests { use super::*; #[test] fn test1() { let re = Regex::parse("aa*bb+|bb").unwrap(); let p = Program::from_regex(&re, 1); println!("{}", p); println!("{}", Nfa::from_program(&p)); } }
bool) { debug_assert!(!state.merged_states.contains(&pc)); match *prog.opcode(pc) { Opcode::Match(m) => { state.accepts.push(Accept::new(pc, m)); state.merged_states.insert(pc); } Opcode::Byte(g, b) => { state.edges.push(Edge::new(b, g)); state.merged_states.insert(pc); } Opcode::Range(g, a, b) => { for i in a..=b { state.edges.push(Edge::new(i, g)); } state.merged_states.insert(pc); } Opcode::Mask(g, m) => { let m = prog.mask(m); for i in m.iter() { state.edges.push(Edge::new(i, g)); } state.merged_states.insert(pc); } Opcode::Split(..) => { debug_assert!(!nested); for s in edges.get(&pc).unwrap().iter().cloned() { add_code(state, s, edges, prog, true); } } } } let mut edge_map: HashMap<u32, SparseSet<u32>> = HashMap::with_capacity(prog.code().len()); for pc in 0..prog.code().len() as u32 { if let Opcode::Split(..) = prog.opcode(pc) { let mut e = SparseSet::with_capacity(prog.code().len()); resolve_edges(pc, &mut e, prog, 0); edge_map.insert(pc, e); } } let mut state_map = vec![EMPTY_GOTO; prog.code().len()]; let mut states: Vec<StateEx> = Vec::with_capacity(prog.code().len()); let mut pc = 0; let mut done = false; while !done { let mut state = StateEx::new(prog.code().len()); add_code(&mut state, pc, &edge_map, prog, false); let mut found = false; for (i, s) in st
function_block-random_span
[ { "content": "#[derive(Debug, Clone, Copy)]\n\nstruct Proc(u32, u32);\n\n\n\nimpl Proc {\n\n fn is_empty(&self) -> bool {\n\n self.0 == EMPTY_GOTO\n\n }\n\n\n\n fn merge(&mut self, p: Proc) -> Proc {\n\n if self.is_empty() {\n\n *self = p;\n\n } else if !p.is_empty() {\n...
Rust
src/oneshot/timer_fd.rs
krircc/async-timer
c2cb75ab1d4624e8af280a1cdf8c3aa9f41f27bd
#[cfg(feature = "no_std")] core::compile_error!("no_std is not supported for timerfd implementation"); use crate::std::io; use core::future::Future; use core::pin::Pin; use core::{mem, ptr, task, time}; use libc::c_int; #[cfg(target_os = "android")] mod sys { #[repr(C)] pub struct itimerspec { pub it_interval: libc::timespec, pub it_value: libc::timespec, } extern "C" { pub fn timerfd_create(clockid: libc::clockid_t, flags: libc::c_int) -> libc::c_int; pub fn timerfd_settime(timerid: libc::c_int, flags: libc::c_int, new_value: *const itimerspec, old_value: *mut itimerspec) -> libc::c_int; } pub const TFD_NONBLOCK: libc::c_int = libc::O_NONBLOCK; } #[cfg(not(target_os = "android"))] use libc as sys; struct RawTimer(c_int); impl RawTimer { fn new() -> Self { let fd = unsafe { sys::timerfd_create(libc::CLOCK_MONOTONIC, sys::TFD_NONBLOCK) }; os_assert!(fd != -1); Self(fd) } fn set(&self, timer: sys::itimerspec) { let ret = unsafe { sys::timerfd_settime(self.0, 0, &timer, ptr::null_mut()) }; os_assert!(ret != -1); } fn read(&self) -> usize { let mut read_num = 0u64; match unsafe { libc::read(self.0, &mut read_num as *mut u64 as *mut _, 8) } { -1 => { let error = io::Error::last_os_error(); match error.kind() { io::ErrorKind::WouldBlock => 0, _ => panic!("Unexpected read error: {}", error), } } _ => read_num as usize, } } } impl mio::Evented for RawTimer { fn register(&self, poll: &mio::Poll, token: mio::Token, interest: mio::Ready, opts: mio::PollOpt) -> io::Result<()> { mio::unix::EventedFd(&self.0).register(poll, token, interest, opts) } fn reregister(&self, poll: &mio::Poll, token: mio::Token, interest: mio::Ready, opts: mio::PollOpt) -> io::Result<()> { mio::unix::EventedFd(&self.0).reregister(poll, token, interest, opts) } fn deregister(&self, poll: &mio::Poll) -> io::Result<()> { mio::unix::EventedFd(&self.0).deregister(poll) } } impl Drop for RawTimer { fn drop(&mut self) { unsafe { libc::close(self.0) }; } } enum State { Init(time::Duration), Running(bool), } fn set_timer_value(fd: &RawTimer, timeout: time::Duration) { #[cfg(not(target_pointer_width = "64"))] use core::convert::TryFrom; let it_value = libc::timespec { tv_sec: timeout.as_secs() as libc::time_t, #[cfg(target_pointer_width = "64")] tv_nsec: libc::suseconds_t::from(timeout.subsec_nanos()), #[cfg(not(target_pointer_width = "64"))] tv_nsec: libc::suseconds_t::try_from(timeout.subsec_nanos()).unwrap_or(libc::suseconds_t::max_value()), }; let new_value = sys::itimerspec { it_interval: unsafe { mem::zeroed() }, it_value, }; fd.set(new_value); } pub struct TimerFd { fd: tokio::io::PollEvented<RawTimer>, state: State, } impl super::Oneshot for TimerFd { fn new(timeout: time::Duration) -> Self { debug_assert!(!(timeout.as_secs() == 0 && timeout.subsec_nanos() == 0), "Zero timeout makes no sense"); Self { fd: tokio::io::PollEvented::new(RawTimer::new()).expect("To create PollEvented"), state: State::Init(timeout), } } fn is_ticking(&self) -> bool { match &self.state { State::Init(_) => false, State::Running(is_finished) => !*is_finished, } } fn is_expired(&self) -> bool { match &self.state { State::Init(_) => false, State::Running(is_finished) => *is_finished, } } fn cancel(&mut self) { self.fd.get_mut().set(unsafe { mem::zeroed() }); } fn restart(&mut self, new_value: time::Duration, _: &task::Waker) { debug_assert!(!(new_value.as_secs() == 0 && new_value.subsec_nanos() == 0), "Zero timeout makes no sense"); match &mut self.state { State::Init(ref mut timeout) => { *timeout = new_value; } State::Running(ref mut is_finished) => { *is_finished = false; set_timer_value(&self.fd.get_ref(), new_value); } } } } impl Future for TimerFd { type Output = (); fn poll(mut self: Pin<&mut Self>, ctx: &mut task::Context) -> task::Poll<Self::Output> { loop { self.state = match &self.state { State::Init(ref timeout) => { set_timer_value(self.fd.get_ref(), *timeout); State::Running(false) } State::Running(false) => { match Pin::new(&mut self.fd).poll_read_ready(ctx, mio::Ready::readable()) { task::Poll::Pending => return task::Poll::Pending, task::Poll::Ready(ready) => match ready.map(|ready| ready.is_readable()).expect("timerfd cannot be ready") { true => { let _ = Pin::new(&mut self.fd).clear_read_ready(ctx, mio::Ready::readable()); match self.fd.get_mut().read() { 0 => return task::Poll::Pending, _ => return task::Poll::Ready(()), } } false => return task::Poll::Pending, }, } } State::Running(true) => return task::Poll::Ready(()), } } } }
#[cfg(feature = "no_std")] core::compile_error!("no_std is not supported for timerfd implementation"); use crate::std::io; use core::future::Future; use core::pin::Pin; use core::{mem, ptr, task, time}; use libc::c_int; #[cfg(target_os = "android")] mod sys { #[repr(C)] pub struct itimerspec { pub it_interval: libc::timespec, pub it_value: libc::timespec, } extern "C" { pub fn timerfd_create(clockid: libc::clockid_t, flags: libc::c_int) -> libc::c_int; pub fn timerfd_settime(timerid: libc::c_int, flags: libc::c_int, new_value: *const itimerspec, old_value: *mut itimerspec) -> libc::c_int; } pub const TFD_NONBLOCK: libc::c_int = libc::O_NONBLOCK; } #[cfg(not(target_os = "android"))] use libc as sys; struct RawTimer(c_int); impl RawTimer { fn new() -> Self { let fd = unsafe { sys::timerfd_create(libc::CLOCK_MONOTONIC, sys::TFD_NONBLOCK) }; os_assert!(fd != -1); Self(fd) } fn set(&self, timer: sys::itimerspec) { let ret = unsafe { sys::timerfd_settime(self.0, 0, &timer, ptr::null_mut()) }; os_assert!(ret != -1); } fn read(&self) -> usize { let mut read_num = 0u64; match unsafe { libc::read(self.0, &mut read_num as *mut u64 as *mut _, 8) } { -1 => { let error = io::Error::last_os_error(); match error.kind() { io::ErrorKind::WouldBlock => 0, _ => panic!("Unexpected read error: {}", error), } } _ => read_num as usize, } } } impl mio::Evented for RawTimer { fn register(&self, poll: &mio::Poll, token: mio::Token, interest: mio::Ready, opts: mio::PollOpt) -> io::Result<()> { mio::unix::EventedFd(&self.0).register(poll, token, interest, opts) } fn reregister(&self, poll: &mio::Poll, token: mio::Token, interest: mio::Ready, opts: mio::PollOpt) -> io::Result<()> { mio::unix::EventedFd(&self.0).reregister(poll, token, interest, opts) } fn deregister(&self, poll: &mio::Poll) -> io::Result<()> { mio::unix::EventedFd(&self.0).deregister(poll) } } impl Drop for RawTimer { fn drop(&mut self) { unsafe { libc::close(self.0) }; } } enum State { Init(time::Duration), Running(bool), } fn set_timer_value(fd: &RawTimer, timeout: time::Duration) { #[cfg(not(target_pointer_width = "64"))] use core::convert::TryFrom; let it_value = libc::timespec { tv_sec: timeout.as_secs() as libc::time_t, #[cfg(target_pointer_width = "64")] tv_nsec: libc::suseconds_t::from(timeout.subsec_nanos()), #[cfg(not(target_pointer_width = "64"))] tv_nsec: libc::suseconds_t::try_from(timeout.subsec_nanos()).unwrap_or(libc::suseconds_t::max_value()), }; let new_value = sys::itimerspec { it_interval: unsafe { mem::zeroed() }, it_value, }; fd.set(new_value); } pub struct TimerFd { fd: tokio::io::PollEvented<RawTimer>, state: State, } impl super::Oneshot for TimerFd { fn new(timeout: time::Duration) -> Self { debug_assert!(!(timeout.as_secs() == 0 && timeout.subsec_nanos() == 0), "Zero timeout makes no sense"); Self { fd: tokio::io::PollEvented::new(RawTimer::new()).expect("To create PollEvented"), state: State::Init(timeout), } } fn is_ticking(&self) -> bool {
fn is_expired(&self) -> bool { match &self.state { State::Init(_) => false, State::Running(is_finished) => *is_finished, } } fn cancel(&mut self) { self.fd.get_mut().set(unsafe { mem::zeroed() }); } fn restart(&mut self, new_value: time::Duration, _: &task::Waker) { debug_assert!(!(new_value.as_secs() == 0 && new_value.subsec_nanos() == 0), "Zero timeout makes no sense"); match &mut self.state { State::Init(ref mut timeout) => { *timeout = new_value; } State::Running(ref mut is_finished) => { *is_finished = false; set_timer_value(&self.fd.get_ref(), new_value); } } } } impl Future for TimerFd { type Output = (); fn poll(mut self: Pin<&mut Self>, ctx: &mut task::Context) -> task::Poll<Self::Output> { loop { self.state = match &self.state { State::Init(ref timeout) => { set_timer_value(self.fd.get_ref(), *timeout); State::Running(false) } State::Running(false) => { match Pin::new(&mut self.fd).poll_read_ready(ctx, mio::Ready::readable()) { task::Poll::Pending => return task::Poll::Pending, task::Poll::Ready(ready) => match ready.map(|ready| ready.is_readable()).expect("timerfd cannot be ready") { true => { let _ = Pin::new(&mut self.fd).clear_read_ready(ctx, mio::Ready::readable()); match self.fd.get_mut().read() { 0 => return task::Poll::Pending, _ => return task::Poll::Ready(()), } } false => return task::Poll::Pending, }, } } State::Running(true) => return task::Poll::Ready(()), } } } }
match &self.state { State::Init(_) => false, State::Running(is_finished) => !*is_finished, } }
function_block-function_prefix_line
[ { "content": "fn time_create(timeout: time::Duration, state: *const TimerState) -> TimerHandle {\n\n let timeout = timeout.as_millis() as u32;\n\n\n\n let cb = wasm_bindgen::closure::Closure::once(move || unsafe {\n\n (*state).wake();\n\n });\n\n let handle = setTimeout(&cb, timeout);\n\n\n\n...
Rust
src/ingester/ingester.rs
pathivu/pathivu
09ac381630dceb578b8abc39a67030c521e404ce
/* * Copyright 2019 Balaji Jinnah and Contributors * * 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 crate::config::config::Config; use crate::partition::segment_writer::SegmentWriter; use crate::store::store::Store; use crate::types::types::*; use futures::channel::mpsc::{Receiver, Sender}; use futures::executor::block_on; use futures::sink::SinkExt; use futures::stream::StreamExt; use log::{debug, info, warn}; use retain_mut::RetainMut; use rmp_serde::Deserializer; use serde::Deserialize; use std::collections::HashMap; use tonic::Status; pub struct Ingester<S: Store> { receiver: Receiver<IngesterRequest>, id: u8, segment_writers: HashMap<String, SegmentWriter<S>>, cfg: Config, store: S, tailers: HashMap<String, Vec<Sender<Result<api::QueryResponse, Status>>>>, } impl<S: Store + Clone> Ingester<S> { pub fn new(receiver: Receiver<IngesterRequest>, cfg: Config, store: S) -> Ingester<S> { Ingester { receiver: receiver, id: 0, segment_writers: HashMap::new(), cfg: cfg, store: store, tailers: HashMap::default(), } } pub fn start(&mut self) { info!("ingester {} started", self.id); loop { let ingester_request = block_on(async { self.receiver.next().await }); info!("received yo"); if !ingester_request.is_some() { continue; } let ingester_request = ingester_request.unwrap(); match ingester_request { IngesterRequest::Push(req) => { self.handle_tailers(&req); let result = self.push(req.push_request); info!(" result {:?}", result); match req.complete_signal.send(result) { Err(e) => { warn!( "unable to complete the signal for the ingester {}: {:?}", self.id, e ); } _ => {} } } IngesterRequest::Flush(hint) => { let result = self.flush_if_necessary(hint.app, hint.start_ts, hint.end_ts); match hint.complete_signal.send(result) { Err(e) => warn!( "unable to send complete signal for ingester necessary flush {:?}", e ), _ => debug!("ingester necessary flush signal sent successfully"), } } IngesterRequest::RegisterTailer(req) => { self.register_tailer(req); } } } } fn flush_if_necessary( &mut self, partition: String, start_ts: u64, end_ts: u64, ) -> Result<(), failure::Error> { if let Some(writer) = self.segment_writers.get_mut(&partition) { let (segment_start_ts, segment_end_ts) = writer.segment_ts(); if (segment_start_ts >= start_ts && segment_start_ts <= end_ts) || (segment_end_ts >= start_ts && segment_end_ts <= start_ts) || (start_ts == 0 && end_ts == 0) { let segment_writer = self.segment_writers.remove(&partition).unwrap(); segment_writer.close()?; debug!("flushing writer {} for hint", partition); } } Ok(()) } fn push(&mut self, req: api::PushRequest) -> Result<(), failure::Error> { if req.lines.len() == 0 { return Ok(()); } debug!( "ingesting partition {}, with {} lines", req.source, req.lines.len() ); let ref mut segment_writer: SegmentWriter<S>; if let Some(writer) = self.segment_writers.get_mut(&req.source) { segment_writer = writer; info!("writer is thre"); } else { info!("writer not there"); let writer = self.create_segment_writer(&req.source, req.lines[0].ts)?; info!("inserting yo"); self.segment_writers.insert(req.source.clone(), writer); segment_writer = self.segment_writers.get_mut(&req.source).unwrap(); } segment_writer.push(req.lines)?; if self.cfg.max_segment_size <= segment_writer.size() { let segment_writer = self.segment_writers.remove(&req.source).unwrap(); segment_writer.close()?; } info!("segment writers {:}", &self.segment_writers.len()); Ok(()) } fn create_segment_writer( &self, partition: &String, start_ts: u64, ) -> Result<SegmentWriter<S>, failure::Error> { let segment_id: u64; let partition_registry = self .store .get(format!("{}_{}", PARTITION_PREFIX, partition).as_bytes())?; match partition_registry { Some(registry) => { let mut buf = Deserializer::new(&registry[..]); let registry: PartitionRegistry = Deserialize::deserialize(&mut buf)?; segment_id = registry.last_assigned + 1; } None => segment_id = 1, } SegmentWriter::new( self.cfg.clone(), partition.clone(), segment_id, self.store.clone(), start_ts, ) } fn register_tailer(&mut self, mut req: TailerRequest) { let mut push_tailer = |key: String, tailer: Sender<Result<api::QueryResponse, Status>>| match self .tailers .get_mut(&key) { Some(tailers) => tailers.push(tailer), None => { self.tailers.insert(key, vec![tailer]); } }; if req.partitions.len() == 0 { push_tailer(String::from("*"), req.sender); return; } for partition in req.partitions.drain(..) { push_tailer(partition, req.sender.clone()); } } fn handle_tailers(&mut self, req: &IngesterPush) { let send_logs = |tailers: Option<&mut Vec<Sender<Result<api::QueryResponse, Status>>>>| { if let Some(tailers) = tailers { tailers.retain_mut(|tailer| { let mut lines = Vec::new(); for log_line in req.push_request.lines.iter() { lines.push(api::LogLine { app: req.push_request.source.clone(), inner: String::from_utf8(log_line.raw_data.clone()).unwrap(), ts: log_line.ts, structured: log_line.structured, }); } match block_on(async { tailer .send(Ok(api::QueryResponse { lines: lines, json: String::from(""), })) .await }) { Ok(_) => true, Err(_) => { println!("removing tailer"); return false; } } }); } }; let tailers = self.tailers.get_mut("*"); send_logs(tailers); let tailers = self.tailers.get_mut(&req.push_request.source); send_logs(tailers); } }
/* * Copyright 2019 Balaji Jinnah and Contributors * * 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 crate::config::config::Config; use crate::partition::segment_writer::SegmentWriter; use crate::store::store::Store; use crate::types::types::*; use futures::channel::mpsc::{Receiver, Sender}; use futures::executor::block_on; use futures::sink::SinkExt; use futures::stream::StreamExt; use log::{debug, info, warn}; use retain_mut::RetainMut; use rmp_serde::Deserializer; use serde::Deserialize; use std::collections::HashMap; use tonic::Status; pub struct Ingester<S: Store> { receiver: Receiver<IngesterRequest>, id: u8, segment_writers: HashMap<String, SegmentWriter<S>>, cfg: Config, store: S, tailers: HashMap<String, Vec<Sender<Result<api::QueryResponse, Status>>>>, } impl<S: Store + Clone> Ingester<S> {
pub fn start(&mut self) { info!("ingester {} started", self.id); loop { let ingester_request = block_on(async { self.receiver.next().await }); info!("received yo"); if !ingester_request.is_some() { continue; } let ingester_request = ingester_request.unwrap(); match ingester_request { IngesterRequest::Push(req) => { self.handle_tailers(&req); let result = self.push(req.push_request); info!(" result {:?}", result); match req.complete_signal.send(result) { Err(e) => { warn!( "unable to complete the signal for the ingester {}: {:?}", self.id, e ); } _ => {} } } IngesterRequest::Flush(hint) => { let result = self.flush_if_necessary(hint.app, hint.start_ts, hint.end_ts); match hint.complete_signal.send(result) { Err(e) => warn!( "unable to send complete signal for ingester necessary flush {:?}", e ), _ => debug!("ingester necessary flush signal sent successfully"), } } IngesterRequest::RegisterTailer(req) => { self.register_tailer(req); } } } } fn flush_if_necessary( &mut self, partition: String, start_ts: u64, end_ts: u64, ) -> Result<(), failure::Error> { if let Some(writer) = self.segment_writers.get_mut(&partition) { let (segment_start_ts, segment_end_ts) = writer.segment_ts(); if (segment_start_ts >= start_ts && segment_start_ts <= end_ts) || (segment_end_ts >= start_ts && segment_end_ts <= start_ts) || (start_ts == 0 && end_ts == 0) { let segment_writer = self.segment_writers.remove(&partition).unwrap(); segment_writer.close()?; debug!("flushing writer {} for hint", partition); } } Ok(()) } fn push(&mut self, req: api::PushRequest) -> Result<(), failure::Error> { if req.lines.len() == 0 { return Ok(()); } debug!( "ingesting partition {}, with {} lines", req.source, req.lines.len() ); let ref mut segment_writer: SegmentWriter<S>; if let Some(writer) = self.segment_writers.get_mut(&req.source) { segment_writer = writer; info!("writer is thre"); } else { info!("writer not there"); let writer = self.create_segment_writer(&req.source, req.lines[0].ts)?; info!("inserting yo"); self.segment_writers.insert(req.source.clone(), writer); segment_writer = self.segment_writers.get_mut(&req.source).unwrap(); } segment_writer.push(req.lines)?; if self.cfg.max_segment_size <= segment_writer.size() { let segment_writer = self.segment_writers.remove(&req.source).unwrap(); segment_writer.close()?; } info!("segment writers {:}", &self.segment_writers.len()); Ok(()) } fn create_segment_writer( &self, partition: &String, start_ts: u64, ) -> Result<SegmentWriter<S>, failure::Error> { let segment_id: u64; let partition_registry = self .store .get(format!("{}_{}", PARTITION_PREFIX, partition).as_bytes())?; match partition_registry { Some(registry) => { let mut buf = Deserializer::new(&registry[..]); let registry: PartitionRegistry = Deserialize::deserialize(&mut buf)?; segment_id = registry.last_assigned + 1; } None => segment_id = 1, } SegmentWriter::new( self.cfg.clone(), partition.clone(), segment_id, self.store.clone(), start_ts, ) } fn register_tailer(&mut self, mut req: TailerRequest) { let mut push_tailer = |key: String, tailer: Sender<Result<api::QueryResponse, Status>>| match self .tailers .get_mut(&key) { Some(tailers) => tailers.push(tailer), None => { self.tailers.insert(key, vec![tailer]); } }; if req.partitions.len() == 0 { push_tailer(String::from("*"), req.sender); return; } for partition in req.partitions.drain(..) { push_tailer(partition, req.sender.clone()); } } fn handle_tailers(&mut self, req: &IngesterPush) { let send_logs = |tailers: Option<&mut Vec<Sender<Result<api::QueryResponse, Status>>>>| { if let Some(tailers) = tailers { tailers.retain_mut(|tailer| { let mut lines = Vec::new(); for log_line in req.push_request.lines.iter() { lines.push(api::LogLine { app: req.push_request.source.clone(), inner: String::from_utf8(log_line.raw_data.clone()).unwrap(), ts: log_line.ts, structured: log_line.structured, }); } match block_on(async { tailer .send(Ok(api::QueryResponse { lines: lines, json: String::from(""), })) .await }) { Ok(_) => true, Err(_) => { println!("removing tailer"); return false; } } }); } }; let tailers = self.tailers.get_mut("*"); send_logs(tailers); let tailers = self.tailers.get_mut(&req.push_request.source); send_logs(tailers); } }
pub fn new(receiver: Receiver<IngesterRequest>, cfg: Config, store: S) -> Ingester<S> { Ingester { receiver: receiver, id: 0, segment_writers: HashMap::new(), cfg: cfg, store: store, tailers: HashMap::default(), } }
function_block-full_function
[ { "content": "pub trait Store {\n\n fn merge(&mut self, key: &[u8], value: Vec<u8>);\n\n fn set(&mut self, key: &[u8], value: Vec<u8>);\n\n fn flush(&mut self) -> Result<usize, failure::Error>;\n\n fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, failure::Error>;\n\n fn flush_batch(&self, wb:...
Rust
src/bin/mv_files.rs
lukaspustina/clams-bin
14cf8732a4809b2003fbe255edffab448047b19a
use clams::prelude::*; use clams_bin::mv_files; use failure::{format_err, Error}; use std::path::{Path, PathBuf}; use structopt::StructOpt; use walkdir::WalkDir; #[derive(StructOpt, Debug)] #[structopt( name = "mv_files", about = "Move video files from a nested directory structure into another, flat directory", raw(setting = "structopt::clap::AppSettings::ColoredHelp") )] struct Args { #[structopt(short = "e", long = "extension", default_value = "avi,mkv,mp4")] extensions: String, #[structopt(short = "s", long = "size", default_value = "100M")] size: String, #[structopt(raw(required = "true", index = "1"))] sources: Vec<String>, #[structopt(raw(index = "2"))] destination: String, #[structopt(short = "d", long = "dry")] dry: bool, #[structopt(long = "no-color")] no_color: bool, #[structopt(short = "p", long = "progress-bar")] progress_bar: bool, #[structopt(long = "silent")] silent: bool, #[structopt(short = "v", long = "verbose", parse(from_occurrences))] verbosity: u64, } fn run(args: Args) -> Result<(), Error> { if args.dry { warn!( "{}", "Running in dry mode. No moves will be performed.".yellow() ); } let size = mv_files::human_size_to_bytes(&args.size)?; if !PathBuf::from(&args.destination).is_dir() { return Err(format_err!( "Destination directory '{}' does not exist.", args.destination )); } let extensions = mv_files::parse_extensions(&args.extensions)?; let source_directories: Vec<&str> = args.sources.iter().map(|s| s.as_ref()).collect(); let dir_entries: Vec<_> = source_directories .into_iter() .map(|d| WalkDir::new(d).into_iter()) .flat_map(|e| e) .collect::<Result<Vec<_>, _>>()?; let moves: Vec<(_, _)> = dir_entries .iter() .map(|e| e.path()) .filter(|p| !p.is_dir()) .filter(|p| { p.extension() .map_or(false, |x| extensions.contains(&x.to_str().unwrap())) }) .filter(|p| p.metadata().map(|m| m.len() >= size).unwrap_or(false)) .map(|p| { let dest_path = mv_files::destination_path(&args.destination, p).unwrap(); (p, dest_path) }) .collect(); debug!( "moving with progess bar = {} and dry mode = {} and moves = ({}) {:#?}", args.progress_bar, args.dry, moves.len(), moves ); if args.progress_bar { move_files_with_progress_bar(moves.as_slice(), args.dry) } else { move_files(moves.as_slice(), args.dry) } } fn move_files_with_progress_bar(moves: &[(&Path, PathBuf)], dry: bool) -> Result<(), Error> { let pb = ProgressBar::new(moves.len() as u64); let style = ProgressStyle::default_clams_bar(); pb.set_style(style); for &(from, ref to) in moves { pb.set_message(&format!( "Moving {} to {} ...", from.to_str().unwrap().yellow(), to.to_str().unwrap().yellow() )); if !dry { match std::fs::rename(from, to) { Ok(_) => {} Err(e) => eprintln!( "Failed to move {} because {}", from.to_str().unwrap().red(), e ), } } pb.inc(1); } pb.finish_with_message("done."); Ok(()) } fn move_files(moves: &[(&Path, PathBuf)], dry: bool) -> Result<(), Error> { for &(from, ref to) in moves { print!( "Moving {} to {} ...", from.to_str().unwrap().yellow(), to.to_str().unwrap().yellow() ); if dry { println!(" {}", "simulated.".blue()); } else { match std::fs::rename(from, to) { Ok(_) => println!(" {}.", "done".green()), Err(e) => eprintln!( "Failed to move {} because {}", from.to_str().unwrap().red(), e ), } } } Ok(()) } fn main() { let args = Args::from_args(); clams::console::set_color(!args.no_color); let name = Args::clap().get_name().to_owned(); let level: Level = args.verbosity.into(); if !args.silent { eprintln!( "{} version={}, log level={:?}", name, env!("CARGO_PKG_VERSION"), &level ); } let log_config = LogConfig::new( std::io::stderr(), !args.no_color, Level(log::LevelFilter::Error), vec![ModLevel { module: name.to_owned(), level, }], None, ); init_logging(log_config).expect("Failed to initialize logging"); match run(args) { Ok(_) => {} Err(e) => { println!("Failed:"); for c in e.iter_chain() { println!("{}", c); } } } }
use clams::prelude::*; use clams_bin::mv_files; use failure::{format_err, Error}; use std::path::{Path, PathBuf}; use structopt::StructOpt; use walkdir::WalkDir; #[derive(StructOpt, Debug)] #[structopt( name = "mv_files", about = "Move video files from a nested directory structure into another, flat directory", raw(setting = "structopt::clap::AppSettings::ColoredHelp") )] struct Args { #[structopt(short = "e", long = "extension", default_value = "avi,mkv,mp4")] extensions: String, #[structopt(short = "s", long = "size", default_value = "100M")] size: String, #[structopt(raw(required = "true", index = "1"))] sources: Vec<String>, #[structopt(raw(index = "2"))] destination: String, #[structopt(short = "d", long = "dry")] dry: bool, #[structopt(long = "no-color")] no_color: bool, #[structopt(short = "p", long = "progress-bar")] progress_bar: bool, #[structopt(long = "silent")] silent: bool, #[structopt(short = "v", long = "verbose", parse(from_occurrences))] verbosity: u64, } fn run(args: Args) -> Result<(), Error> { if args.dry { warn!( "{}", "Running in dry mode. No moves will be performed.".yellow() ); } let size = mv_files::human_size_to_bytes(&args.size)?; if !PathBuf::from(&args.destination).is_dir() { return Err(format_err!( "Destination directory '{}' does not exist.", args.destination )); } let extensions = mv_files::parse_extensions(&args.extensions)?; let source_directories: Vec<&str> = args.sources.iter().map(|s| s.as_ref()).collect(); let dir_entries: Vec<_> = source_directories .into_iter() .map(|d| WalkDir::new(d).into_iter()) .flat_map(|e| e) .collect::<Result<Vec<_>, _>>()?; let moves: Vec<(_, _)> = dir_entries .iter() .map(|e| e.path()) .filter(|p| !p.is_dir()) .filter(|p| { p.extension() .map_or(false, |x| extensions.contains(&x.to_str().unwrap())) }) .filter(|p| p.metadata().map(|m| m.len() >= size).unwrap_or(false)) .map(|p| { let dest_path = mv_files::destination_path(&args.destination, p).unwrap(); (p, dest_path) }) .collect(); debug!( "moving with progess bar = {} and dry mode = {} and moves = ({}) {:#?}", args.progress_bar, args.dry, moves.len(), moves ); if args.progress_bar { move_files_with_progress_bar(moves.as_slice(), args.dry) } else { move_files(moves.as_slice(), args.dry) } } fn move_files_with_progress_bar(moves: &[(&Path, PathBuf)], dry: bool) -> Result<(), Error> { let pb = ProgressBar::new(moves.len() as u64); let style = ProgressStyle::default_clams_bar(); pb.set_style(style); for &(from, ref to) in moves { pb.set_message(&format!( "Moving {} to {} ...", from.to_str().unwrap().yellow(), to.to_str().unwrap().yellow() )); if !dry { match std::fs::rename(from, to) { Ok(_) => {} Err(e) => eprintln!( "Failed to move {} because {}", from.to_str().unwrap().red(), e ), } } pb.inc(1); } pb.finish_with_message("done."); Ok(()) } fn move_files(moves: &[(&Path, PathBuf)], dry: bool) -> Result<(), Error> { for &(from, ref to) in moves { print!( "Moving {} to {} ...", from.to_str().unwrap().yellow(), to.to_str().unwrap().yellow() );
} Ok(()) } fn main() { let args = Args::from_args(); clams::console::set_color(!args.no_color); let name = Args::clap().get_name().to_owned(); let level: Level = args.verbosity.into(); if !args.silent { eprintln!( "{} version={}, log level={:?}", name, env!("CARGO_PKG_VERSION"), &level ); } let log_config = LogConfig::new( std::io::stderr(), !args.no_color, Level(log::LevelFilter::Error), vec![ModLevel { module: name.to_owned(), level, }], None, ); init_logging(log_config).expect("Failed to initialize logging"); match run(args) { Ok(_) => {} Err(e) => { println!("Failed:"); for c in e.iter_chain() { println!("{}", c); } } } }
if dry { println!(" {}", "simulated.".blue()); } else { match std::fs::rename(from, to) { Ok(_) => println!(" {}.", "done".green()), Err(e) => eprintln!( "Failed to move {} because {}", from.to_str().unwrap().red(), e ), } }
if_condition
[ { "content": " };\n\n\n\n let size = size.parse::<u64>().map_err(|_| MvFilesError::InvaildSize {\n\n arg: String::from(size),\n\n })?;\n\n\n\n let size = match scale {\n\n 'k' => size * 1024u64.pow(1),\n\n 'M' => size * 1024u64.pow(2),\n\n ...
Rust
benches/raid.rs
geky/gf256
57675335061b18e3614376981482fd7584454fd5
use criterion::criterion_group; use criterion::criterion_main; use criterion::Criterion; use criterion::BatchSize; use criterion::Throughput; use std::iter; use std::convert::TryFrom; #[allow(dead_code)] #[path = "../examples/raid.rs"] mod raid; fn bench_raid(c: &mut Criterion) { let mut group = c.benchmark_group("raid"); fn xorshift64(seed: u64) -> impl Iterator<Item=u64> { let mut x = seed; iter::repeat_with(move || { x ^= x << 13; x ^= x >> 7; x ^= x << 17; x }) } const SIZE: usize = 1024*1024; const COUNT: usize = 5; let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((COUNT*SIZE) as u64)); group.bench_function("raid5_format", |b| b.iter_batched_ref( || {( iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() )}, |(disks, p)| raid::raid5_format(disks, p), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); let mut disks = iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT) .collect::<Vec<_>>(); let mut p = (&mut xs).take(SIZE).collect::<Vec<u8>>(); raid::raid5_format(&disks, &mut p); group.throughput(Throughput::Bytes(SIZE as u64)); group.bench_function("raid5_update", |b| b.iter_batched_ref( || {( usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT).unwrap()), (&mut xs).take(SIZE).collect::<Vec<u8>>(), )}, |(i, data)| { raid::raid5_update(*i, &disks[*i], data, &mut p); disks[*i].copy_from_slice(data); }, BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((1*SIZE) as u64)); group.bench_function("raid5_repair", |b| b.iter_batched_ref( || {( usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT+1).unwrap()), iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() )}, |(i, disks, p)| raid::raid5_repair(disks, p, &[*i]), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((COUNT*SIZE) as u64)); group.bench_function("raid6_format", |b| b.iter_batched_ref( || {( iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() )}, |(disks, p, q)| raid::raid6_format(disks, p, q), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); let mut disks = iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT+2) .collect::<Vec<_>>(); let mut p = (&mut xs).take(SIZE).collect::<Vec<u8>>(); let mut q = (&mut xs).take(SIZE).collect::<Vec<u8>>(); raid::raid6_format(&mut disks, &mut p, &mut q); group.throughput(Throughput::Bytes(SIZE as u64)); group.bench_function("raid6_update", |b| b.iter_batched_ref( || {( usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT).unwrap()), (&mut xs).take(SIZE).collect::<Vec<u8>>(), )}, |(i, data)| { raid::raid6_update(*i, &disks[*i], data, &mut p, &mut q); disks[*i].copy_from_slice(data); }, BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((1*SIZE) as u64)); group.bench_function("raid6_repair_1", |b| b.iter_batched_ref( || {( usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT+2).unwrap()), iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT+2) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() )}, |(i, disks, p, q)| raid::raid6_repair(disks, p, q, &[*i]), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((2*SIZE) as u64)); group.bench_function("raid6_repair_2", |b| b.iter_batched_ref( || { let i = usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT+2).unwrap()); ( i, (i+1) % (COUNT+2), iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT+2) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() ) }, |(i, j, disks, p, q)| raid::raid6_repair(disks, p, q, &[*i, *j]), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((COUNT*SIZE) as u64)); group.bench_function("raid7_format", |b| b.iter_batched_ref( || {( iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() )}, |(disks, p, q, r)| raid::raid7_format(disks, p, q, r), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); let mut disks = iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT+2) .collect::<Vec<_>>(); let mut p = (&mut xs).take(SIZE).collect::<Vec<u8>>(); let mut q = (&mut xs).take(SIZE).collect::<Vec<u8>>(); let mut r = (&mut xs).take(SIZE).collect::<Vec<u8>>(); raid::raid6_format(&mut disks, &mut p, &mut q); group.throughput(Throughput::Bytes(SIZE as u64)); group.bench_function("raid7_update", |b| b.iter_batched_ref( || {( usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT).unwrap()), (&mut xs).take(SIZE).collect::<Vec<u8>>(), )}, |(i, data)| { raid::raid7_update(*i, &disks[*i], data, &mut p, &mut q, &mut r); disks[*i].copy_from_slice(data); }, BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((1*SIZE) as u64)); group.bench_function("raid7_repair_1", |b| b.iter_batched_ref( || {( usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT+3).unwrap()), iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT+2) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() )}, |(i, disks, p, q, r)| raid::raid7_repair(disks, p, q, r, &[*i]), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((2*SIZE) as u64)); group.bench_function("raid7_repair_2", |b| b.iter_batched_ref( || { let i = usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT+3).unwrap()); ( i, (i+1) % (COUNT+2), iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT+2) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() ) }, |(i, j, disks, p, q, r)| raid::raid7_repair(disks, p, q, r, &[*i, *j]), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((2*SIZE) as u64)); group.bench_function("raid7_repair_3", |b| b.iter_batched_ref( || { let i = usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT+3).unwrap()); ( i, (i+1) % (COUNT+3), (i+2) % (COUNT+3), iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT+2) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() ) }, |(i, j, k, disks, p, q, r)| raid::raid7_repair(disks, p, q, r, &[*i, *j, *k]), BatchSize::SmallInput )); } criterion_group!(benches, bench_raid); criterion_main!(benches);
use criterion::criterion_group; use criterion::criterion_main; use criterion::Criterion; use criterion::BatchSize; use criterion::Throughput; use std::iter; use std::convert::TryFrom; #[allow(dead_code)] #[path = "../examples/raid.rs"] mod raid; fn bench_raid(c: &mut Criterion) { let mut group = c.benchmark_group("raid");
const SIZE: usize = 1024*1024; const COUNT: usize = 5; let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((COUNT*SIZE) as u64)); group.bench_function("raid5_format", |b| b.iter_batched_ref( || {( iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() )}, |(disks, p)| raid::raid5_format(disks, p), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); let mut disks = iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT) .collect::<Vec<_>>(); let mut p = (&mut xs).take(SIZE).collect::<Vec<u8>>(); raid::raid5_format(&disks, &mut p); group.throughput(Throughput::Bytes(SIZE as u64)); group.bench_function("raid5_update", |b| b.iter_batched_ref( || {( usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT).unwrap()), (&mut xs).take(SIZE).collect::<Vec<u8>>(), )}, |(i, data)| { raid::raid5_update(*i, &disks[*i], data, &mut p); disks[*i].copy_from_slice(data); }, BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((1*SIZE) as u64)); group.bench_function("raid5_repair", |b| b.iter_batched_ref( || {( usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT+1).unwrap()), iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() )}, |(i, disks, p)| raid::raid5_repair(disks, p, &[*i]), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((COUNT*SIZE) as u64)); group.bench_function("raid6_format", |b| b.iter_batched_ref( || {( iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() )}, |(disks, p, q)| raid::raid6_format(disks, p, q), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); let mut disks = iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT+2) .collect::<Vec<_>>(); let mut p = (&mut xs).take(SIZE).collect::<Vec<u8>>(); let mut q = (&mut xs).take(SIZE).collect::<Vec<u8>>(); raid::raid6_format(&mut disks, &mut p, &mut q); group.throughput(Throughput::Bytes(SIZE as u64)); group.bench_function("raid6_update", |b| b.iter_batched_ref( || {( usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT).unwrap()), (&mut xs).take(SIZE).collect::<Vec<u8>>(), )}, |(i, data)| { raid::raid6_update(*i, &disks[*i], data, &mut p, &mut q); disks[*i].copy_from_slice(data); }, BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((1*SIZE) as u64)); group.bench_function("raid6_repair_1", |b| b.iter_batched_ref( || {( usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT+2).unwrap()), iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT+2) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() )}, |(i, disks, p, q)| raid::raid6_repair(disks, p, q, &[*i]), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((2*SIZE) as u64)); group.bench_function("raid6_repair_2", |b| b.iter_batched_ref( || { let i = usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT+2).unwrap()); ( i, (i+1) % (COUNT+2), iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT+2) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() ) }, |(i, j, disks, p, q)| raid::raid6_repair(disks, p, q, &[*i, *j]), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((COUNT*SIZE) as u64)); group.bench_function("raid7_format", |b| b.iter_batched_ref( || {( iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() )}, |(disks, p, q, r)| raid::raid7_format(disks, p, q, r), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); let mut disks = iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT+2) .collect::<Vec<_>>(); let mut p = (&mut xs).take(SIZE).collect::<Vec<u8>>(); let mut q = (&mut xs).take(SIZE).collect::<Vec<u8>>(); let mut r = (&mut xs).take(SIZE).collect::<Vec<u8>>(); raid::raid6_format(&mut disks, &mut p, &mut q); group.throughput(Throughput::Bytes(SIZE as u64)); group.bench_function("raid7_update", |b| b.iter_batched_ref( || {( usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT).unwrap()), (&mut xs).take(SIZE).collect::<Vec<u8>>(), )}, |(i, data)| { raid::raid7_update(*i, &disks[*i], data, &mut p, &mut q, &mut r); disks[*i].copy_from_slice(data); }, BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((1*SIZE) as u64)); group.bench_function("raid7_repair_1", |b| b.iter_batched_ref( || {( usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT+3).unwrap()), iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT+2) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() )}, |(i, disks, p, q, r)| raid::raid7_repair(disks, p, q, r, &[*i]), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((2*SIZE) as u64)); group.bench_function("raid7_repair_2", |b| b.iter_batched_ref( || { let i = usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT+3).unwrap()); ( i, (i+1) % (COUNT+2), iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT+2) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() ) }, |(i, j, disks, p, q, r)| raid::raid7_repair(disks, p, q, r, &[*i, *j]), BatchSize::SmallInput )); let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((2*SIZE) as u64)); group.bench_function("raid7_repair_3", |b| b.iter_batched_ref( || { let i = usize::from((&mut xs).next().unwrap() % u8::try_from(COUNT+3).unwrap()); ( i, (i+1) % (COUNT+3), (i+2) % (COUNT+3), iter::repeat_with(|| { (&mut xs).take(SIZE).collect::<Vec<u8>>() }) .take(COUNT+2) .collect::<Vec<_>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>(), (&mut xs).take(SIZE).collect::<Vec<u8>>() ) }, |(i, j, k, disks, p, q, r)| raid::raid7_repair(disks, p, q, r, &[*i, *j, *k]), BatchSize::SmallInput )); } criterion_group!(benches, bench_raid); criterion_main!(benches);
fn xorshift64(seed: u64) -> impl Iterator<Item=u64> { let mut x = seed; iter::repeat_with(move || { x ^= x << 13; x ^= x >> 7; x ^= x << 17; x }) }
function_block-full_function
[ { "content": "fn bench_gfmul(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"gfmul\");\n\n\n\n // gf256 mul/div\n\n bench_mul!(group, \"gf256_naive_mul\", gf256_naive);\n\n bench_mul!(group, \"gf256_table_mul\", gf256_table);\n\n bench_mul!(group, \"gf256_rem_ta...
Rust
src/types/option_value.rs
aCLr/telegram-tdlib
40262849d87608931f22d0bbfd5baa0b410461ce
use crate::errors::*; use crate::types::*; use uuid::Uuid; use std::fmt::Debug; pub trait TDOptionValue: Debug + RObject {} #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(tag = "@type")] pub enum OptionValue { #[doc(hidden)] _Default, #[serde(rename(serialize = "getOption", deserialize = "getOption"))] GetOption(GetOption), #[serde(rename(serialize = "optionValueBoolean", deserialize = "optionValueBoolean"))] Boolean(OptionValueBoolean), #[serde(rename(serialize = "optionValueEmpty", deserialize = "optionValueEmpty"))] Empty(OptionValueEmpty), #[serde(rename(serialize = "optionValueInteger", deserialize = "optionValueInteger"))] Integer(OptionValueInteger), #[serde(rename(serialize = "optionValueString", deserialize = "optionValueString"))] String(OptionValueString), } impl Default for OptionValue { fn default() -> Self { OptionValue::_Default } } impl RObject for OptionValue { #[doc(hidden)] fn extra(&self) -> Option<&str> { match self { OptionValue::GetOption(t) => t.extra(), OptionValue::Boolean(t) => t.extra(), OptionValue::Empty(t) => t.extra(), OptionValue::Integer(t) => t.extra(), OptionValue::String(t) => t.extra(), _ => None, } } #[doc(hidden)] fn client_id(&self) -> Option<i32> { match self { OptionValue::GetOption(t) => t.client_id(), OptionValue::Boolean(t) => t.client_id(), OptionValue::Empty(t) => t.client_id(), OptionValue::Integer(t) => t.client_id(), OptionValue::String(t) => t.client_id(), _ => None, } } } impl OptionValue { pub fn from_json<S: AsRef<str>>(json: S) -> RTDResult<Self> { Ok(serde_json::from_str(json.as_ref())?) } #[doc(hidden)] pub fn _is_default(&self) -> bool { matches!(self, OptionValue::_Default) } } impl AsRef<OptionValue> for OptionValue { fn as_ref(&self) -> &OptionValue { self } } #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct OptionValueBoolean { #[doc(hidden)] #[serde(rename(serialize = "@extra", deserialize = "@extra"))] extra: Option<String>, #[serde(rename(serialize = "@client_id", deserialize = "@client_id"))] client_id: Option<i32>, value: bool, } impl RObject for OptionValueBoolean { #[doc(hidden)] fn extra(&self) -> Option<&str> { self.extra.as_deref() } #[doc(hidden)] fn client_id(&self) -> Option<i32> { self.client_id } } impl TDOptionValue for OptionValueBoolean {} impl OptionValueBoolean { pub fn from_json<S: AsRef<str>>(json: S) -> RTDResult<Self> { Ok(serde_json::from_str(json.as_ref())?) } pub fn builder() -> RTDOptionValueBooleanBuilder { let mut inner = OptionValueBoolean::default(); inner.extra = Some(Uuid::new_v4().to_string()); RTDOptionValueBooleanBuilder { inner } } pub fn value(&self) -> bool { self.value } } #[doc(hidden)] pub struct RTDOptionValueBooleanBuilder { inner: OptionValueBoolean, } impl RTDOptionValueBooleanBuilder { pub fn build(&self) -> OptionValueBoolean { self.inner.clone() } pub fn value(&mut self, value: bool) -> &mut Self { self.inner.value = value; self } } impl AsRef<OptionValueBoolean> for OptionValueBoolean { fn as_ref(&self) -> &OptionValueBoolean { self } } impl AsRef<OptionValueBoolean> for RTDOptionValueBooleanBuilder { fn as_ref(&self) -> &OptionValueBoolean { &self.inner } } #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct OptionValueEmpty { #[doc(hidden)] #[serde(rename(serialize = "@extra", deserialize = "@extra"))] extra: Option<String>, #[serde(rename(serialize = "@client_id", deserialize = "@client_id"))] client_id: Option<i32>, } impl RObject for OptionValueEmpty { #[doc(hidden)] fn extra(&self) -> Option<&str> { self.extra.as_deref() } #[doc(hidden)] fn client_id(&self) -> Option<i32> { self.client_id } } impl TDOptionValue for OptionValueEmpty {} impl OptionValueEmpty { pub fn from_json<S: AsRef<str>>(json: S) -> RTDResult<Self> { Ok(serde_json::from_str(json.as_ref())?) } pub fn builder() -> RTDOptionValueEmptyBuilder { let mut inner = OptionValueEmpty::default(); inner.extra = Some(Uuid::new_v4().to_string()); RTDOptionValueEmptyBuilder { inner } } } #[doc(hidden)] pub struct RTDOptionValueEmptyBuilder { inner: OptionValueEmpty, } impl RTDOptionValueEmptyBuilder { pub fn build(&self) -> OptionValueEmpty { self.inner.clone() } } impl AsRef<OptionValueEmpty> for OptionValueEmpty { fn as_ref(&self) -> &OptionValueEmpty { self } } impl AsRef<OptionValueEmpty> for RTDOptionValueEmptyBuilder { fn as_ref(&self) -> &OptionValueEmpty { &self.inner } } #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct OptionValueInteger { #[doc(hidden)] #[serde(rename(serialize = "@extra", deserialize = "@extra"))] extra: Option<String>, #[serde(rename(serialize = "@client_id", deserialize = "@client_id"))] client_id: Option<i32>, #[serde(deserialize_with = "super::_common::number_from_string")] value: i64, } impl RObject for OptionValueInteger { #[doc(hidden)] fn extra(&self) -> Option<&str> { self.extra.as_deref() } #[doc(hidden)] fn client_id(&self) -> Option<i32> { self.client_id } } impl TDOptionValue for OptionValueInteger {} impl OptionValueInteger { pub fn from_json<S: AsRef<str>>(json: S) -> RTDResult<Self> { Ok(serde_json::from_str(json.as_ref())?) } pub fn builder() -> RTDOptionValueIntegerBuilder { let mut inner = OptionValueInteger::default(); inner.extra = Some(Uuid::new_v4().to_string()); RTDOptionValueIntegerBuilder { inner } } pub fn value(&self) -> i64 { self.value } } #[doc(hidden)] pub struct RTDOptionValueIntegerBuilder { inner: OptionValueInteger, } impl RTDOptionValueIntegerBuilder { pub fn build(&self) -> OptionValueInteger { self.inner.clone() } pub fn value(&mut self, value: i64) -> &mut Self { self.inner.value = value; self } } impl AsRef<OptionValueInteger> for OptionValueInteger { fn as_ref(&self) -> &OptionValueInteger { self } } impl AsRef<OptionValueInteger> for RTDOptionValueIntegerBuilder { fn as_ref(&self) -> &OptionValueInteger { &self.inner } } #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct OptionValueString { #[doc(hidden)] #[serde(rename(serialize = "@extra", deserialize = "@extra"))] extra: Option<String>, #[serde(rename(serialize = "@client_id", deserialize = "@client_id"))] client_id: Option<i32>, value: String, } impl RObject for OptionValueString { #[doc(hidden)] fn extra(&self) -> Option<&str> { self.extra.as_deref() } #[doc(hidden)] fn client_id(&self) -> Option<i32> { self.client_id } } impl TDOptionValue for OptionValueString {} impl OptionValueString { pub fn from_json<S: AsRef<str>>(json: S) -> RTDResult<Self> { Ok(serde_json::from_str(json.as_ref())?) } pub fn builder() -> RTDOptionValueStringBuilder { let mut inner = OptionValueString::default(); inner.extra = Some(Uuid::new_v4().to_string()); RTDOptionValueStringBuilder { inner } } pub fn value(&self) -> &String { &self.value } } #[doc(hidden)] pub struct RTDOptionValueStringBuilder { inner: OptionValueString, } impl RTDOptionValueStringBuilder { pub fn build(&self) -> OptionValueString { self.inner.clone() } pub fn value<T: AsRef<str>>(&mut self, value: T) -> &mut Self { self.inner.value = value.as_ref().to_string(); self } } impl AsRef<OptionValueString> for OptionValueString { fn as_ref(&self) -> &OptionValueString { self } } impl AsRef<OptionValueString> for RTDOptionValueStringBuilder { fn as_ref(&self) -> &OptionValueString { &self.inner } }
use crate::errors::*; use crate::types::*; use uuid::Uuid; use std::fmt::Debug; pub trait TDOptionValue: Debug + RObject {} #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(tag = "@type")] pub enum OptionValue { #[doc(hidden)] _Default, #[serde(rename(serialize = "getOption", deserialize = "getOption"))] GetOption(GetOption), #[serde(rename(serialize = "optionValueBoolean", deserialize = "optionValueBoolean"))] Boolean(OptionValueBoolean), #[serde(rename(serialize = "optionValueEmpty", deserialize = "optionValueEmpty"))] Empty(OptionValueEmpty), #[serde(rename(serialize = "optionValueInteger", deserialize = "optionValueInteger"))] Integer(OptionValueInteger), #[serde(rename(serialize = "optionValueString", deserialize = "optionValueString"))] String(OptionValueString), } impl Default for OptionValue { fn default() -> Self { OptionValue::_Default } } impl RObject for OptionValue { #[doc(hidden)] fn extra(&self) -> Option<&str> {
} #[doc(hidden)] fn client_id(&self) -> Option<i32> { match self { OptionValue::GetOption(t) => t.client_id(), OptionValue::Boolean(t) => t.client_id(), OptionValue::Empty(t) => t.client_id(), OptionValue::Integer(t) => t.client_id(), OptionValue::String(t) => t.client_id(), _ => None, } } } impl OptionValue { pub fn from_json<S: AsRef<str>>(json: S) -> RTDResult<Self> { Ok(serde_json::from_str(json.as_ref())?) } #[doc(hidden)] pub fn _is_default(&self) -> bool { matches!(self, OptionValue::_Default) } } impl AsRef<OptionValue> for OptionValue { fn as_ref(&self) -> &OptionValue { self } } #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct OptionValueBoolean { #[doc(hidden)] #[serde(rename(serialize = "@extra", deserialize = "@extra"))] extra: Option<String>, #[serde(rename(serialize = "@client_id", deserialize = "@client_id"))] client_id: Option<i32>, value: bool, } impl RObject for OptionValueBoolean { #[doc(hidden)] fn extra(&self) -> Option<&str> { self.extra.as_deref() } #[doc(hidden)] fn client_id(&self) -> Option<i32> { self.client_id } } impl TDOptionValue for OptionValueBoolean {} impl OptionValueBoolean { pub fn from_json<S: AsRef<str>>(json: S) -> RTDResult<Self> { Ok(serde_json::from_str(json.as_ref())?) } pub fn builder() -> RTDOptionValueBooleanBuilder { let mut inner = OptionValueBoolean::default(); inner.extra = Some(Uuid::new_v4().to_string()); RTDOptionValueBooleanBuilder { inner } } pub fn value(&self) -> bool { self.value } } #[doc(hidden)] pub struct RTDOptionValueBooleanBuilder { inner: OptionValueBoolean, } impl RTDOptionValueBooleanBuilder { pub fn build(&self) -> OptionValueBoolean { self.inner.clone() } pub fn value(&mut self, value: bool) -> &mut Self { self.inner.value = value; self } } impl AsRef<OptionValueBoolean> for OptionValueBoolean { fn as_ref(&self) -> &OptionValueBoolean { self } } impl AsRef<OptionValueBoolean> for RTDOptionValueBooleanBuilder { fn as_ref(&self) -> &OptionValueBoolean { &self.inner } } #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct OptionValueEmpty { #[doc(hidden)] #[serde(rename(serialize = "@extra", deserialize = "@extra"))] extra: Option<String>, #[serde(rename(serialize = "@client_id", deserialize = "@client_id"))] client_id: Option<i32>, } impl RObject for OptionValueEmpty { #[doc(hidden)] fn extra(&self) -> Option<&str> { self.extra.as_deref() } #[doc(hidden)] fn client_id(&self) -> Option<i32> { self.client_id } } impl TDOptionValue for OptionValueEmpty {} impl OptionValueEmpty { pub fn from_json<S: AsRef<str>>(json: S) -> RTDResult<Self> { Ok(serde_json::from_str(json.as_ref())?) } pub fn builder() -> RTDOptionValueEmptyBuilder { let mut inner = OptionValueEmpty::default(); inner.extra = Some(Uuid::new_v4().to_string()); RTDOptionValueEmptyBuilder { inner } } } #[doc(hidden)] pub struct RTDOptionValueEmptyBuilder { inner: OptionValueEmpty, } impl RTDOptionValueEmptyBuilder { pub fn build(&self) -> OptionValueEmpty { self.inner.clone() } } impl AsRef<OptionValueEmpty> for OptionValueEmpty { fn as_ref(&self) -> &OptionValueEmpty { self } } impl AsRef<OptionValueEmpty> for RTDOptionValueEmptyBuilder { fn as_ref(&self) -> &OptionValueEmpty { &self.inner } } #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct OptionValueInteger { #[doc(hidden)] #[serde(rename(serialize = "@extra", deserialize = "@extra"))] extra: Option<String>, #[serde(rename(serialize = "@client_id", deserialize = "@client_id"))] client_id: Option<i32>, #[serde(deserialize_with = "super::_common::number_from_string")] value: i64, } impl RObject for OptionValueInteger { #[doc(hidden)] fn extra(&self) -> Option<&str> { self.extra.as_deref() } #[doc(hidden)] fn client_id(&self) -> Option<i32> { self.client_id } } impl TDOptionValue for OptionValueInteger {} impl OptionValueInteger { pub fn from_json<S: AsRef<str>>(json: S) -> RTDResult<Self> { Ok(serde_json::from_str(json.as_ref())?) } pub fn builder() -> RTDOptionValueIntegerBuilder { let mut inner = OptionValueInteger::default(); inner.extra = Some(Uuid::new_v4().to_string()); RTDOptionValueIntegerBuilder { inner } } pub fn value(&self) -> i64 { self.value } } #[doc(hidden)] pub struct RTDOptionValueIntegerBuilder { inner: OptionValueInteger, } impl RTDOptionValueIntegerBuilder { pub fn build(&self) -> OptionValueInteger { self.inner.clone() } pub fn value(&mut self, value: i64) -> &mut Self { self.inner.value = value; self } } impl AsRef<OptionValueInteger> for OptionValueInteger { fn as_ref(&self) -> &OptionValueInteger { self } } impl AsRef<OptionValueInteger> for RTDOptionValueIntegerBuilder { fn as_ref(&self) -> &OptionValueInteger { &self.inner } } #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct OptionValueString { #[doc(hidden)] #[serde(rename(serialize = "@extra", deserialize = "@extra"))] extra: Option<String>, #[serde(rename(serialize = "@client_id", deserialize = "@client_id"))] client_id: Option<i32>, value: String, } impl RObject for OptionValueString { #[doc(hidden)] fn extra(&self) -> Option<&str> { self.extra.as_deref() } #[doc(hidden)] fn client_id(&self) -> Option<i32> { self.client_id } } impl TDOptionValue for OptionValueString {} impl OptionValueString { pub fn from_json<S: AsRef<str>>(json: S) -> RTDResult<Self> { Ok(serde_json::from_str(json.as_ref())?) } pub fn builder() -> RTDOptionValueStringBuilder { let mut inner = OptionValueString::default(); inner.extra = Some(Uuid::new_v4().to_string()); RTDOptionValueStringBuilder { inner } } pub fn value(&self) -> &String { &self.value } } #[doc(hidden)] pub struct RTDOptionValueStringBuilder { inner: OptionValueString, } impl RTDOptionValueStringBuilder { pub fn build(&self) -> OptionValueString { self.inner.clone() } pub fn value<T: AsRef<str>>(&mut self, value: T) -> &mut Self { self.inner.value = value.as_ref().to_string(); self } } impl AsRef<OptionValueString> for OptionValueString { fn as_ref(&self) -> &OptionValueString { self } } impl AsRef<OptionValueString> for RTDOptionValueStringBuilder { fn as_ref(&self) -> &OptionValueString { &self.inner } }
match self { OptionValue::GetOption(t) => t.extra(), OptionValue::Boolean(t) => t.extra(), OptionValue::Empty(t) => t.extra(), OptionValue::Integer(t) => t.extra(), OptionValue::String(t) => t.extra(), _ => None, }
if_condition
[ { "content": "pub trait RFunction: Debug + RObject + Serialize {\n\n fn to_json(&self) -> RTDResult<String> {\n\n Ok(serde_json::to_string(self)?)\n\n }\n\n}\n\n\n\nimpl<'a, RObj: RObject> RObject for &'a RObj {\n\n fn extra(&self) -> Option<&str> {\n\n (*self).extra()\n\n }\n\n fn ...
Rust
crates/vkfft-sys/build.rs
semio-ai/vkfft-rs
2ee35297bdfef4aece8877f7b1c1c5b1c584766c
extern crate bindgen; extern crate cc; use std::error::Error; use std::path::{Path, PathBuf}; use bindgen::Bindings; fn build_lib<O, LD, L, const N: usize, const M: usize>(out_dir: O, library_dirs: LD, libraries: L, defines: &[(&str, &str); N], include_dirs: &[String; M]) -> Result<(), Box<dyn Error>> where O: AsRef<Path>, LD: Iterator, LD::Item: AsRef<str>, L: Iterator, L::Item: AsRef<str> { let mut build = cc::Build::default(); build .cpp(true) .file("wrapper.cpp") .include(out_dir) .flag("-std=c++11") .flag("-w"); for library_dir in library_dirs { build.flag(format!("-L{}", library_dir.as_ref()).as_str()); } for library in libraries { build.flag(format!("-l{}", library.as_ref()).as_str()); } build .cargo_metadata(true) .static_flag(true); for (key, value) in defines.iter() { build.define(*key, Some(*value)); } for include_dir in include_dirs.iter() { build.include(include_dir); } build.compile("vkfft"); Ok(()) } fn gen_wrapper<F, const N: usize, const M: usize>(file: F, defines: &[(&str, &str); N], include_dirs: &[String; M]) -> Result<Bindings, Box<dyn Error>> where F: AsRef<Path>, { let base_args = [ "-std=c++11".to_string(), ]; let defines: Vec<String> = defines.iter().map(|(k, v)| { format!("-D{}={}", k, v) }).collect(); let include_dirs: Vec<String> = include_dirs.iter() .map(|s| format!("-I{}", s)) .collect(); let clang_args = base_args .iter() .chain(defines.iter()) .chain(include_dirs.iter()); println!("{:?}", clang_args); let res = bindgen::Builder::default() .clang_args(clang_args) .parse_callbacks(Box::new(bindgen::CargoCallbacks)) .header(file.as_ref().to_str().unwrap()) .allowlist_recursively(true) .allowlist_type("VkFFTConfiguration") .allowlist_type("VkFFTLaunchParams") .allowlist_type("VkFFTResult") .allowlist_type("VkFFTSpecializationConstantsLayout") .allowlist_type("VkFFTPushConstantsLayout") .allowlist_type("VkFFTAxis") .allowlist_type("VkFFTPlan") .allowlist_type("VkFFTApplication") .allowlist_function("VkFFTSync") .allowlist_function("VkFFTAppend") .allowlist_function("VkFFTPlanAxis") .allowlist_function("initializeVkFFT") .allowlist_function("deleteVkFFT") .allowlist_function("VkFFTGetVersion") .generate(); let bindings = match res { Ok(x) => x, Err(_) => { eprintln!("Failed to generate bindings."); std::process::exit(1); } }; Ok(bindings) } fn main() -> Result<(), Box<dyn Error>> { let vkfft_root = std::env::var("VKFFT_ROOT")?; let out_dir = std::env::var("OUT_DIR")?; let out_dir = PathBuf::from(out_dir); let library_dirs = [ format!("{}/build/glslang-master/glslang", vkfft_root), format!("{}/build/glslang-master/glslang/OSDependent/Unix", vkfft_root), format!("{}/build/glslang-master/glslang/OGLCompilersDLL", vkfft_root), format!("{}/build/glslang-master/glslang/SPIRV", vkfft_root), ]; let libraries = [ "glslang", "MachineIndependent", "OSDependent", "GenericCodeGen", "OGLCompiler", "vulkan", "SPIRV" ]; for library_dir in library_dirs.iter() { println!("cargo:rustc-link-search={}", library_dir); } for library in libraries.iter() { println!("cargo:rustc-link-lib={}", library); } println!("cargo:rerun-if-changed=wrapper.cpp"); println!("cargo:rerun-if-changed=build.rs"); let include_dirs = [ format!("{}/vkFFT", &vkfft_root), format!("{}/glslang-master/glslang/Include", vkfft_root) ]; let defines = [ ("VKFFT_BACKEND", "0"), ("VK_API_VERSION", "11") ]; let wrapper = std::fs::read_to_string(format!("{}/vkFFT/vkFFT.h", vkfft_root))? .replace("static inline", ""); let rw = out_dir.join("vkfft_rw.hpp"); std::fs::write(&rw, wrapper.as_str())?; build_lib(&out_dir, library_dirs.iter(), libraries.iter(), &defines, &include_dirs)?; let bindings = gen_wrapper(&rw, &defines, &include_dirs)?; bindings.write_to_file(out_dir.join("bindings.rs"))?; Ok(()) }
extern crate bindgen; extern crate cc; use std::error::Error; use std::path::{Path, PathBuf}; use bindgen::Bindings; fn build_lib<O, LD, L, const N: usize, const M: usize>(out_dir: O, library_dirs: LD, libraries: L, defines: &[(&str, &str); N], include_dirs: &[String; M]) -> Result<(), Box<dyn Error>> where O: AsRef<Path>, LD: Iterator, LD::Item: AsRef<str>, L: Iterator, L::Item: AsRef<str>
ings = gen_wrapper(&rw, &defines, &include_dirs)?; bindings.write_to_file(out_dir.join("bindings.rs"))?; Ok(()) }
{ let mut build = cc::Build::default(); build .cpp(true) .file("wrapper.cpp") .include(out_dir) .flag("-std=c++11") .flag("-w"); for library_dir in library_dirs { build.flag(format!("-L{}", library_dir.as_ref()).as_str()); } for library in libraries { build.flag(format!("-l{}", library.as_ref()).as_str()); } build .cargo_metadata(true) .static_flag(true); for (key, value) in defines.iter() { build.define(*key, Some(*value)); } for include_dir in include_dirs.iter() { build.include(include_dir); } build.compile("vkfft"); Ok(()) } fn gen_wrapper<F, const N: usize, const M: usize>(file: F, defines: &[(&str, &str); N], include_dirs: &[String; M]) -> Result<Bindings, Box<dyn Error>> where F: AsRef<Path>, { let base_args = [ "-std=c++11".to_string(), ]; let defines: Vec<String> = defines.iter().map(|(k, v)| { format!("-D{}={}", k, v) }).collect(); let include_dirs: Vec<String> = include_dirs.iter() .map(|s| format!("-I{}", s)) .collect(); let clang_args = base_args .iter() .chain(defines.iter()) .chain(include_dirs.iter()); println!("{:?}", clang_args); let res = bindgen::Builder::default() .clang_args(clang_args) .parse_callbacks(Box::new(bindgen::CargoCallbacks)) .header(file.as_ref().to_str().unwrap()) .allowlist_recursively(true) .allowlist_type("VkFFTConfiguration") .allowlist_type("VkFFTLaunchParams") .allowlist_type("VkFFTResult") .allowlist_type("VkFFTSpecializationConstantsLayout") .allowlist_type("VkFFTPushConstantsLayout") .allowlist_type("VkFFTAxis") .allowlist_type("VkFFTPlan") .allowlist_type("VkFFTApplication") .allowlist_function("VkFFTSync") .allowlist_function("VkFFTAppend") .allowlist_function("VkFFTPlanAxis") .allowlist_function("initializeVkFFT") .allowlist_function("deleteVkFFT") .allowlist_function("VkFFTGetVersion") .generate(); let bindings = match res { Ok(x) => x, Err(_) => { eprintln!("Failed to generate bindings."); std::process::exit(1); } }; Ok(bindings) } fn main() -> Result<(), Box<dyn Error>> { let vkfft_root = std::env::var("VKFFT_ROOT")?; let out_dir = std::env::var("OUT_DIR")?; let out_dir = PathBuf::from(out_dir); let library_dirs = [ format!("{}/build/glslang-master/glslang", vkfft_root), format!("{}/build/glslang-master/glslang/OSDependent/Unix", vkfft_root), format!("{}/build/glslang-master/glslang/OGLCompilersDLL", vkfft_root), format!("{}/build/glslang-master/glslang/SPIRV", vkfft_root), ]; let libraries = [ "glslang", "MachineIndependent", "OSDependent", "GenericCodeGen", "OGLCompiler", "vulkan", "SPIRV" ]; for library_dir in library_dirs.iter() { println!("cargo:rustc-link-search={}", library_dir); } for library in libraries.iter() { println!("cargo:rustc-link-lib={}", library); } println!("cargo:rerun-if-changed=wrapper.cpp"); println!("cargo:rerun-if-changed=build.rs"); let include_dirs = [ format!("{}/vkFFT", &vkfft_root), format!("{}/glslang-master/glslang/Include", vkfft_root) ]; let defines = [ ("VKFFT_BACKEND", "0"), ("VK_API_VERSION", "11") ]; let wrapper = std::fs::read_to_string(format!("{}/vkFFT/vkFFT.h", vkfft_root))? .replace("static inline", ""); let rw = out_dir.join("vkfft_rw.hpp"); std::fs::write(&rw, wrapper.as_str())?; build_lib(&out_dir, library_dirs.iter(), libraries.iter(), &defines, &include_dirs)?; let bind
random
[ { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n println!(\"VkFFT version: {}\", vkfft::version());\n\n\n\n let instance = Instance::new(\n\n None,\n\n &InstanceExtensions {\n\n ext_debug_utils: true,\n\n ..InstanceExtensions::none()\n\n },\n\n vec![\"VK_LAYER_KHRO...
Rust
examples/bgpdumper.rs
wladwm/zettabgp
85d8e21742e948907cf3fcc64552f40c9e852524
extern crate zettabgp; use std::env; use std::io::{Read, Write}; use std::net::{Shutdown, TcpStream}; use std::thread::{sleep, spawn}; use zettabgp::prelude::*; pub struct BgpDumper { pub params: BgpSessionParams, pub stream: TcpStream, } impl BgpDumper { pub fn new(bgp_params: BgpSessionParams, tcpstream: TcpStream) -> BgpDumper { BgpDumper { params: bgp_params, stream: tcpstream, } } fn recv_message_head(&mut self) -> Result<(BgpMessageType, usize), BgpError> { let mut buf = [0 as u8; 19]; self.stream.read_exact(&mut buf)?; self.params.decode_message_head(&buf) } pub fn start_active(&mut self) -> Result<(), BgpError> { let mut bom = self.params.open_message(); let mut buf = [255 as u8; 4096]; let messagelen = match bom.encode_to(&self.params, &mut buf[19..]) { Err(e) => { return Err(e); } Ok(sz) => sz, }; let blen = self .params .prepare_message_buf(&mut buf, BgpMessageType::Open, messagelen)?; self.stream.write_all(&buf[0..blen])?; let msg = match self.recv_message_head() { Err(e) => { return Err(e); } Ok(msg) => msg, }; if msg.0 != BgpMessageType::Open { return Err(BgpError::static_str("Invalid state to start_active")); } self.stream.read_exact(&mut buf[0..msg.1])?; bom.decode_from(&self.params, &buf[0..msg.1])?; self.params.hold_time = bom.hold_time; self.params.caps = bom.caps; self.params.check_caps(); Ok(()) } pub fn send_keepalive(stream: &mut TcpStream) -> Result<(), BgpError> { let mut buf = [255 as u8; 19]; buf[0..16].clone_from_slice(&[255 as u8; 16]); buf[16] = 0; buf[17] = 19; buf[18] = 4; match stream.write_all(&buf) { Ok(_) => Ok(()), Err(e) => Err(e.into()), } } pub fn start_keepalives(&self) -> Result<(), BgpError> { let mut ks = self.stream.try_clone()?; let slp = std::time::Duration::new((self.params.hold_time / 3) as u64, 0); spawn(move || loop { if BgpDumper::send_keepalive(&mut ks).is_err() { break; } sleep(slp); }); Ok(()) } pub fn lifecycle(&mut self) -> Result<(), BgpError> { self.start_keepalives()?; let mut buf = Box::new([0 as u8; 65536]); loop { let msg = match self.recv_message_head() { Ok(m) => m, Err(e) => { return Err(e); } }; if msg.0 == BgpMessageType::Keepalive { continue; } self.stream.read_exact(&mut buf[0..msg.1])?; match msg.0 { BgpMessageType::Open => { eprintln!("Incorrect open message!"); break; } BgpMessageType::Keepalive => {} BgpMessageType::Notification => { let mut msgnotification = BgpNotificationMessage::new(); match msgnotification.decode_from(&self.params, &buf[0..msg.1]) { Err(e) => { eprintln!("BGP notification decode error: {:?}", e); } Ok(_) => { println!( "BGP notification: {:?} - {:?}", msgnotification, msgnotification.error_text() ); } }; break; } BgpMessageType::Update => { let mut msgupdate = BgpUpdateMessage::new(); if let Err(e) = msgupdate.decode_from(&self.params, &buf[0..msg.1]) { eprintln!("BGP update decode error: {:?}", e); continue; } println!("{:?}", msgupdate); } } } Ok(()) } pub fn close(&mut self) { self.stream.shutdown(Shutdown::Both).unwrap_or_default(); } } fn main() { if env::args().len() != 3 { eprintln!("Usage: bgpdumper PEER AS"); return; } let vargs: Vec<String> = env::args().map(|x| x).collect(); let targetip: std::net::IpAddr = match vargs[1].parse() { Ok(x) => x, Err(_) => { eprintln!("Invalid peer IP - {}", vargs[1]); return; } }; let targetasn: u32 = match vargs[2].parse() { Ok(x) => x, Err(_) => { eprintln!("Invalid peer ASn - {}", vargs[2]); return; } }; let target = std::net::SocketAddr::new(targetip, 179); let stream = std::net::TcpStream::connect(target).expect("Unable to connect to bgp speaker"); let mut peer = BgpDumper::new( BgpSessionParams::new( targetasn, 180, BgpTransportMode::IPv4, std::net::Ipv4Addr::new(1, 0, 0, 0), vec![ BgpCapability::SafiIPv4u, BgpCapability::SafiIPv4m, BgpCapability::SafiIPv4lu, BgpCapability::SafiIPv6lu, BgpCapability::SafiVPNv4u, BgpCapability::SafiVPNv4m, BgpCapability::SafiVPNv6u, BgpCapability::SafiVPNv6m, BgpCapability::SafiIPv4mvpn, BgpCapability::SafiVPLS, BgpCapability::CapRR, BgpCapability::CapASN32(targetasn), ] .into_iter() .collect(), ), stream, ); match peer.start_active() { Err(e) => { eprintln!("failed to create BGP peer; err = {:?}", e); peer.close(); return; } Ok(_) => {} }; println!("Run lifecycle"); peer.lifecycle().unwrap(); println!("Done lifecycle"); peer.close(); }
extern crate zettabgp; use std::env; use std::io::{Read, Write}; use std::net::{Shutdown, TcpStream}; use std::thread::{sleep, spawn}; use zettabgp::prelude::*; pub struct BgpDumper { pub params: BgpSessionParams, pub stream: TcpStream, } impl BgpDumper { pub fn new(bgp_params: BgpSessionParams, tcpstream: TcpStream) -> BgpDumper { BgpDumper { params: bgp_params, stream: tcpstream, } } fn recv_message_head(&mut self) -> Result<(BgpMessageType, usize), BgpError> { let mut buf = [0 as u8; 19]; self.stream.read_exact(&mut buf)?; self.params.decode_message_head(&buf) } pub fn start_active(&mut self) -> Result<(), BgpError> { let mut bom = self.params.open_message(); let mut buf = [255 as u8; 4096]; let messagelen = match bom.encode_to(&self.params, &mut buf[19..]) { Err(e) => { return Err(e); } Ok(sz) => sz, }; let blen = self .params .prepare_message_buf(&mut buf, BgpMessageType::Open, messagelen)?; self.stream.write_all(&buf[0..blen])?; let msg = match self.recv_message_head() { Err(e) => { return Err(e); } Ok(msg) => msg, }; if msg.0 != BgpMessageType::Open { return Err(BgpError::static_str("Invalid state to start_active")); } self.stream.read_exact(&mut buf[0..msg.1])?; bom.decode_from(&self.params, &buf[0..msg.1])?; self.params.hold_time = bom.hold_time; self.params.caps = bom.caps; self.params.check_caps(); Ok(()) } pub fn send_keepalive(stream: &mut TcpStream) -> Result<(), BgpError> { let mut buf = [255 as u8; 19]; buf[0..16].clone_from_slice(&[255 as u8; 16]); buf[16] = 0; buf[17] = 19; buf[18] = 4; match stream.write_all(&buf) { Ok(_) => Ok(()), Err(e) => Err(e.into()), } } pub fn start_keepalives(&self) -> Result<(), BgpError> { let mut ks = self.stream.try_clone()?; let slp = std::time::Duration::new((self.params.hold_time / 3) as u64, 0); spawn(move || loop { if BgpDumper::send_keepalive(&mut ks).is_err() { break; } sleep(slp); }); Ok(()) } pub fn lifecycle(&mut self) -> Result<(), BgpError> { self.start_keepalives()?; let mut buf = Box::new([0 as u8; 65536]); loop { let msg = match self.recv_message_head() { Ok(m) => m, Err(e) => { return Err(e); } }; if msg.0 == BgpMessageType::Keepalive { continue; } self.stream.read_exact(&mut buf[0..msg.1])?; match msg.0 { BgpMessageType::Open => { eprintln!("Incorrect open message!"); break; } BgpMessageType::Keepalive => {} BgpMessageType::Notification => { let mut msgnotification = BgpNotificationMessage::new(); match msgnotification.decode_from(&self.params, &buf[0..msg.1]) { Err(e) => { eprintln!("BGP notification decode error: {:?}", e); } Ok(_) => { println!( "BGP notification: {:?} - {:?}", msgnotification, msgnotification.error_text() ); } }; break; } BgpMessageType::Update => { let mut msgupdate = BgpUpdateMessage::new(); if let Err(e) = msgupdate.decode_from(&self.params, &buf[0..msg.1]) { eprintln!("BGP update decode error: {:?}", e); continue; } println!("{:?}", msgupdate); } } } Ok(()) } pub fn close(&mut self) { self.stream.shutdown(Shutdown::Both).unwrap_or_default(); } }
fn main() { if env::args().len() != 3 { eprintln!("Usage: bgpdumper PEER AS"); return; } let vargs: Vec<String> = env::args().map(|x| x).collect(); let targetip: std::net::IpAddr = match vargs[1].parse() { Ok(x) => x, Err(_) => { eprintln!("Invalid peer IP - {}", vargs[1]); return; } }; let targetasn: u32 = match vargs[2].parse() { Ok(x) => x, Err(_) => { eprintln!("Invalid peer ASn - {}", vargs[2]); return; } }; let target = std::net::SocketAddr::new(targetip, 179); let stream = std::net::TcpStream::connect(target).expect("Unable to connect to bgp speaker"); let mut peer = BgpDumper::new( BgpSessionParams::new( targetasn, 180, BgpTransportMode::IPv4, std::net::Ipv4Addr::new(1, 0, 0, 0), vec![ BgpCapability::SafiIPv4u, BgpCapability::SafiIPv4m, BgpCapability::SafiIPv4lu, BgpCapability::SafiIPv6lu, BgpCapability::SafiVPNv4u, BgpCapability::SafiVPNv4m, BgpCapability::SafiVPNv6u, BgpCapability::SafiVPNv6m, BgpCapability::SafiIPv4mvpn, BgpCapability::SafiVPLS, BgpCapability::CapRR, BgpCapability::CapASN32(targetasn), ] .into_iter() .collect(), ), stream, ); match peer.start_active() { Err(e) => { eprintln!("failed to create BGP peer; err = {:?}", e); peer.close(); return; } Ok(_) => {} }; println!("Run lifecycle"); peer.lifecycle().unwrap(); println!("Done lifecycle"); peer.close(); }
function_block-full_function
[ { "content": "/// Stores ipv4 address into the buffer.\n\npub fn encode_addrv4_to(addr: &std::net::Ipv4Addr, buf: &mut [u8]) -> Result<usize, BgpError> {\n\n if buf.len() < 4 {\n\n return Err(BgpError::static_str(\"Invalid addrv4 length\"));\n\n }\n\n buf[0..4].clone_from_slice(&addr.octets());\...
Rust
embassy-stm32/src/pwm/mod.rs
Liamolucko/embassy
4f4b19d920c103453b2b0f9ce7994ca830ddb2d7
use crate::gpio; use crate::rcc::RccPeripheral; use crate::time::Hertz; use core::marker::PhantomData; use embassy::util::Unborrow; use embassy_hal_common::unborrow; use stm32_metapac::timer::vals::Ocm; pub struct Pwm<'d, T: Instance> { phantom: PhantomData<&'d mut T>, } pub struct Ch1 {} pub struct Ch2 {} pub struct Ch3 {} pub struct Ch4 {} #[derive(Clone, Copy)] pub enum Channel { Ch1, Ch2, Ch3, Ch4, } impl<'d, T: Instance> Pwm<'d, T> { pub fn new<F: Into<Hertz>>( _tim: impl Unborrow<Target = T> + 'd, ch1: impl Unborrow<Target = impl PwmPin<T, Ch1>> + 'd, ch2: impl Unborrow<Target = impl PwmPin<T, Ch2>> + 'd, ch3: impl Unborrow<Target = impl PwmPin<T, Ch3>> + 'd, ch4: impl Unborrow<Target = impl PwmPin<T, Ch4>> + 'd, freq: F, ) -> Self { unborrow!(ch1, ch2, ch3, ch4); T::enable(); T::reset(); let r = T::regs(); let mut this = Pwm { phantom: PhantomData, }; unsafe { ch1.configure(); ch2.configure(); ch3.configure(); ch4.configure(); } unsafe { use stm32_metapac::timer::vals::Dir; this.set_freq(freq); r.cr1().write(|w| { w.set_cen(true); w.set_dir(Dir::UP) }); this.set_ocm(Channel::Ch1, Ocm::PWMMODE1); this.set_ocm(Channel::Ch2, Ocm::PWMMODE1); this.set_ocm(Channel::Ch3, Ocm::PWMMODE1); this.set_ocm(Channel::Ch4, Ocm::PWMMODE1); } this } unsafe fn set_ocm(&mut self, channel: Channel, mode: Ocm) { let r = T::regs(); match channel { Channel::Ch1 => r.ccmr_output(0).modify(|w| w.set_ocm(0, mode)), Channel::Ch2 => r.ccmr_output(0).modify(|w| w.set_ocm(1, mode)), Channel::Ch3 => r.ccmr_output(1).modify(|w| w.set_ocm(0, mode)), Channel::Ch4 => r.ccmr_output(1).modify(|w| w.set_ocm(1, mode)), } } unsafe fn set_enable(&mut self, channel: Channel, enable: bool) { let r = T::regs(); match channel { Channel::Ch1 => r.ccer().modify(|w| w.set_cce(0, enable)), Channel::Ch2 => r.ccer().modify(|w| w.set_cce(1, enable)), Channel::Ch3 => r.ccer().modify(|w| w.set_cce(2, enable)), Channel::Ch4 => r.ccer().modify(|w| w.set_cce(3, enable)), } } pub fn enable(&mut self, channel: Channel) { unsafe { self.set_enable(channel, true) } } pub fn disable(&mut self, channel: Channel) { unsafe { self.set_enable(channel, false) } } pub fn set_freq<F: Into<Hertz>>(&mut self, freq: F) { use core::convert::TryInto; let clk = T::frequency(); let r = T::regs(); let freq: Hertz = freq.into(); let ticks: u32 = clk.0 / freq.0; let psc: u16 = (ticks / (1 << 16)).try_into().unwrap(); let arr: u16 = (ticks / (u32::from(psc) + 1)).try_into().unwrap(); unsafe { r.psc().write(|w| w.set_psc(psc)); r.arr().write(|w| w.set_arr(arr)); } } pub fn get_max_duty(&self) -> u32 { let r = T::regs(); unsafe { r.arr().read().arr() as u32 } } pub fn set_duty(&mut self, channel: Channel, duty: u32) { use core::convert::TryInto; assert!(duty < self.get_max_duty()); let duty: u16 = duty.try_into().unwrap(); let r = T::regs(); unsafe { match channel { Channel::Ch1 => r.ccr(0).modify(|w| w.set_ccr(duty)), Channel::Ch2 => r.ccr(1).modify(|w| w.set_ccr(duty)), Channel::Ch3 => r.ccr(2).modify(|w| w.set_ccr(duty)), Channel::Ch4 => r.ccr(3).modify(|w| w.set_ccr(duty)), } } } } pub(crate) mod sealed { pub trait Instance { fn regs() -> crate::pac::timer::TimGp16; } } pub trait Instance: sealed::Instance + Sized + RccPeripheral + 'static {} #[allow(unused)] macro_rules! impl_timer { ($inst:ident) => { impl crate::pwm::sealed::Instance for crate::peripherals::$inst { fn regs() -> crate::pac::timer::TimGp16 { crate::pac::timer::TimGp16(crate::pac::$inst.0) } } impl crate::pwm::Instance for crate::peripherals::$inst {} }; } pub trait PwmPin<Timer, Channel>: gpio::OptionalPin { unsafe fn configure(&mut self); } impl<Timer, Channel> PwmPin<Timer, Channel> for gpio::NoPin { unsafe fn configure(&mut self) {} } #[allow(unused)] macro_rules! impl_pwm_pin { ($timer:ident, $channel:ident, $pin:ident, $af:expr) => { impl crate::pwm::PwmPin<crate::peripherals::$timer, crate::pwm::$channel> for crate::peripherals::$pin { unsafe fn configure(&mut self) { use crate::gpio::sealed::{AFType, Pin}; use crate::gpio::Speed; self.set_low(); self.set_speed(Speed::VeryHigh); self.set_as_af($af, AFType::OutputPushPull); } } }; } crate::pac::peripherals!( (timer, $inst:ident) => { impl_timer!($inst); }; ); crate::pac::peripheral_pins!( ($inst:ident, timer,TIM_GP16, $pin:ident, CH1, $af:expr) => { impl_pwm_pin!($inst, Ch1, $pin, $af); }; ($inst:ident, timer,TIM_GP16, $pin:ident, CH2, $af:expr) => { impl_pwm_pin!($inst, Ch2, $pin, $af); }; ($inst:ident, timer,TIM_GP16, $pin:ident, CH3, $af:expr) => { impl_pwm_pin!($inst, Ch3, $pin, $af); }; ($inst:ident, timer,TIM_GP16, $pin:ident, CH4, $af:expr) => { impl_pwm_pin!($inst, Ch4, $pin, $af); }; );
use crate::gpio; use crate::rcc::RccPeripheral; use crate::time::Hertz; use core::marker::PhantomData; use embassy::util::Unborrow; use embassy_hal_common::unborrow; use stm32_metapac::timer::vals::Ocm; pub struct Pwm<'d, T: Instance> { phantom: PhantomData<&'d mut T>, } pub struct Ch1 {} pub struct Ch2 {} pub struct Ch3 {} pub struct Ch4 {} #[derive(Clone, Copy)] pub enum Channel { Ch1, Ch2, Ch3, Ch4, } impl<'d, T: Instance> Pwm<'d, T> { pub fn new<F: Into<Hertz>>( _tim: impl Unborrow<Target = T> + 'd, ch1: impl Unborrow<Target = impl PwmPin<T, Ch1>> + 'd, ch2: impl Unborrow<Target = impl PwmPin<T, Ch2>> + 'd, ch3: impl Unborrow<Target = impl PwmPin<T, Ch3>> + 'd, ch4: impl Unborrow<Target = impl PwmPin<T, Ch4>> + 'd, freq: F, ) -> Self { unborrow!(ch1, ch2, ch3, ch4); T::enable(); T::reset(); let r = T::regs(); let mut this = Pwm { phantom: PhantomData, }; unsafe { ch1.configure(); ch2.configure(); ch3.configure(); ch4.configure(); } unsafe { use stm32_metapac::timer::vals::Dir; this.set_freq(freq); r.cr1().write(|w| { w.set_cen(true); w.set_dir(Dir::UP) }); this.set_ocm(Channel::Ch1, Ocm::PWMMODE1); this.set_ocm(Channel::Ch2, Ocm::PWMMODE1); this.set_ocm(Channel::Ch3, Ocm::PWMMODE1); this.set_ocm(Channel::Ch4, Ocm::PWMMODE1); } this } unsafe fn set_ocm(&mut self, channel: Channel, mode: Ocm) { let r = T::regs(); match channel { Channel::Ch1 => r.ccmr_output(0).modify(|w| w.set_ocm(0, mode)), Channel::Ch2 => r.ccmr_output(0).modify(|w| w.set_ocm(1, mode)), Channel::Ch3 => r.ccmr_output(1).modify(|w| w.set_ocm(0, mode)), Channel::Ch4 => r.ccmr_output(1).modify(|w| w.set_ocm(1, mode)), } } unsafe fn set_enable(&mut self, channel: Channel, enable: bool) { let r = T::regs(); match channel { Channel::Ch1 => r.ccer().modify(|w| w.set_cce(0, enable)), Channel::Ch2 => r.ccer().modify(|w| w.set_cce(1, enable)), Channel::Ch3 => r.ccer().modify(|w| w.set_cce(2, enable)), Channel::Ch4 => r.ccer().modify(|w| w.set_cce(3, enable)), } } pub fn enable(&mut self, channel: Channel) { unsafe { self.set_enable(channel, true) } } pub fn disable(&mut self, channel: Channel) { unsafe { self.set_enable(channel, false) } }
pub fn get_max_duty(&self) -> u32 { let r = T::regs(); unsafe { r.arr().read().arr() as u32 } } pub fn set_duty(&mut self, channel: Channel, duty: u32) { use core::convert::TryInto; assert!(duty < self.get_max_duty()); let duty: u16 = duty.try_into().unwrap(); let r = T::regs(); unsafe { match channel { Channel::Ch1 => r.ccr(0).modify(|w| w.set_ccr(duty)), Channel::Ch2 => r.ccr(1).modify(|w| w.set_ccr(duty)), Channel::Ch3 => r.ccr(2).modify(|w| w.set_ccr(duty)), Channel::Ch4 => r.ccr(3).modify(|w| w.set_ccr(duty)), } } } } pub(crate) mod sealed { pub trait Instance { fn regs() -> crate::pac::timer::TimGp16; } } pub trait Instance: sealed::Instance + Sized + RccPeripheral + 'static {} #[allow(unused)] macro_rules! impl_timer { ($inst:ident) => { impl crate::pwm::sealed::Instance for crate::peripherals::$inst { fn regs() -> crate::pac::timer::TimGp16 { crate::pac::timer::TimGp16(crate::pac::$inst.0) } } impl crate::pwm::Instance for crate::peripherals::$inst {} }; } pub trait PwmPin<Timer, Channel>: gpio::OptionalPin { unsafe fn configure(&mut self); } impl<Timer, Channel> PwmPin<Timer, Channel> for gpio::NoPin { unsafe fn configure(&mut self) {} } #[allow(unused)] macro_rules! impl_pwm_pin { ($timer:ident, $channel:ident, $pin:ident, $af:expr) => { impl crate::pwm::PwmPin<crate::peripherals::$timer, crate::pwm::$channel> for crate::peripherals::$pin { unsafe fn configure(&mut self) { use crate::gpio::sealed::{AFType, Pin}; use crate::gpio::Speed; self.set_low(); self.set_speed(Speed::VeryHigh); self.set_as_af($af, AFType::OutputPushPull); } } }; } crate::pac::peripherals!( (timer, $inst:ident) => { impl_timer!($inst); }; ); crate::pac::peripheral_pins!( ($inst:ident, timer,TIM_GP16, $pin:ident, CH1, $af:expr) => { impl_pwm_pin!($inst, Ch1, $pin, $af); }; ($inst:ident, timer,TIM_GP16, $pin:ident, CH2, $af:expr) => { impl_pwm_pin!($inst, Ch2, $pin, $af); }; ($inst:ident, timer,TIM_GP16, $pin:ident, CH3, $af:expr) => { impl_pwm_pin!($inst, Ch3, $pin, $af); }; ($inst:ident, timer,TIM_GP16, $pin:ident, CH4, $af:expr) => { impl_pwm_pin!($inst, Ch4, $pin, $af); }; );
pub fn set_freq<F: Into<Hertz>>(&mut self, freq: F) { use core::convert::TryInto; let clk = T::frequency(); let r = T::regs(); let freq: Hertz = freq.into(); let ticks: u32 = clk.0 / freq.0; let psc: u16 = (ticks / (1 << 16)).try_into().unwrap(); let arr: u16 = (ticks / (u32::from(psc) + 1)).try_into().unwrap(); unsafe { r.psc().write(|w| w.set_psc(psc)); r.arr().write(|w| w.set_arr(arr)); } }
function_block-full_function
[ { "content": "/// Low power blocking wait loop using WFE/SEV.\n\npub fn low_power_wait_until(mut condition: impl FnMut() -> bool) {\n\n while !condition() {\n\n // WFE might \"eat\" an event that would have otherwise woken the executor.\n\n cortex_m::asm::wfe();\n\n }\n\n // Retrigger an ...
Rust
src/lib.rs
JerTH/elfy
2a761bcc4de002b72a538eae3e5ec1d5cc0f3ba8
#![warn(missing_docs)] use std::error::Error; use std::fmt::{ Display, Formatter }; use std::io::{ Read, Seek, SeekFrom }; use std::collections::HashMap; #[macro_use] mod macros; pub mod types; pub mod numeric; pub mod constants; use crate::types::*; pub type ParseElfResult<T> = std::result::Result<T, ParseElfError>; #[derive(Debug)] pub enum ParseElfError { IoError{ inner: std::io::Error }, #[allow(missing_docs)] InvalidSectionType(u32), #[allow(missing_docs)] InvalidProgramFlags(u32), #[allow(missing_docs)] InvalidProgramHeader(u32), #[allow(missing_docs)] InvalidVersion(u32), #[allow(missing_docs)] InvalidMachine(u16), #[allow(missing_docs)] InvalidElfType(u16), #[allow(missing_docs)] InvalidOsAbi(u8), #[allow(missing_docs)] InvalidIdentVersion(u8), #[allow(missing_docs)] InvalidDataFormat(u8), #[allow(missing_docs)] InvalidDataClass(u8), InvalidParsingDescriptor, } impl Error for ParseElfError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { ParseElfError::IoError{ inner } => Some(inner), _ => None, } } } impl Display for ParseElfError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "{:?}", self) } } impl From<std::io::Error> for ParseElfError { fn from(err: std::io::Error) -> ParseElfError { ParseElfError::IoError{ inner: err } } } trait Parslet { fn parse<R: Read + Seek>(reader: &mut R, descriptor: &mut Descriptor) -> ParseElfResult<Self> where Self: Sized; } enum Descriptor { None, Data{ format: DataFormat, class: DataClass }, } impl Descriptor { fn data_class(&self) -> ParseElfResult<DataClass> { match self { Descriptor::Data{ class, .. } => Ok(*class), Descriptor::None => Err(ParseElfError::InvalidParsingDescriptor), } } fn data_format(&self) -> ParseElfResult<DataFormat> { match self { Descriptor::Data{ format, .. } => Ok(*format), Descriptor::None => Err(ParseElfError::InvalidParsingDescriptor) } } } #[derive(Debug)] pub struct Elf { header: ElfHeader, sections: Vec<Section>, segments: Vec<Segment>, section_map: HashMap<String, usize>, } impl Elf { pub fn load<P: AsRef<std::path::Path>>(path: P) -> ParseElfResult<Elf> { let file = std::fs::File::open(path)?; let mut buf = std::io::BufReader::new(file); Ok(Elf::parse(&mut buf)?) } pub fn parse<R: Read + Seek>(reader: &mut R) -> ParseElfResult<Elf> { let mut descriptor = Descriptor::None; let header = ElfHeader::parse(reader, &mut descriptor)?; let sections = parse_sections(reader, &mut descriptor, &header)?; let segments = parse_segments(reader, &mut descriptor, &header)?; let mut section_map = HashMap::new(); associate_string_table(&mut section_map, &sections, &header); Ok(Elf{ header, sections, segments, section_map }) } pub fn try_get_section(&self, section_name: &str) -> Option<&Section> { self.sections.get(*self.section_map.get(section_name)?) } pub fn header(&self) -> &ElfHeader { &self.header } pub fn sections(&self) -> SectionIter { SectionIter { elf: &self, idx: 0 } } pub fn segments(&self) -> SegmentIter { SegmentIter { elf: &self, idx: 0 } } } fn parse_sections<R: Read + Seek>(reader: &mut R, descriptor: &mut Descriptor, header: &ElfHeader) -> ParseElfResult<Vec<Section>> { reader.seek(SeekFrom::Start(header.section_headers_offset()))?; let mut sections = Vec::new(); for _ in 0..header.section_header_count() { sections.push(Section::parse(reader, descriptor)?) } Ok(sections) } fn parse_segments<R: Read + Seek>(reader: &mut R, descriptor: &mut Descriptor, header: &ElfHeader) -> ParseElfResult<Vec<Segment>> { reader.seek(SeekFrom::Start(header.program_headers_offset()))?; let mut segments = Vec::new(); for _ in 0..header.program_header_count() { segments.push(Segment::parse(reader, descriptor)?) } Ok(segments) } fn associate_string_table(section_map: &mut HashMap<String, usize>, sections: &[Section], header: &ElfHeader) { if let Some(idx) = header.section_name_table_index() { if let SectionData::Strings(table) = &sections[idx].data() { for (i, _section) in sections.iter().enumerate() { let name = table[i].clone(); section_map.insert(name, i); } } } } pub struct SectionIter<'a> { elf: &'a Elf, idx: usize, } impl<'a> Iterator for SectionIter<'a> { type Item = &'a Section; fn next(&mut self) -> Option<Self::Item> { let item = self.elf.sections.get(self.idx)?; self.idx += 1; Some(item) } } pub struct SegmentIter<'a> { elf: &'a Elf, idx: usize, } impl<'a> Iterator for SegmentIter<'a> { type Item = &'a Segment; fn next(&mut self) -> Option<Self::Item> { let item = self.elf.segments.get(self.idx)?; self.idx += 1; Some(item) } } pub mod prelude { pub use crate::numeric::*; pub use crate::types::*; pub use crate::Elf; } #[cfg(test)] mod test { use super::*; fn _load_example_binary() -> Elf { let elf = Elf::load("examples/example-binary").unwrap(); elf } #[test] fn get_section_bytes() { let elf = _load_example_binary(); let text = elf.try_get_section(".text").unwrap(); if let SectionData::Bytes(_bytes) = text.data() { } } #[test] fn section_iters() { let elf = _load_example_binary(); for (i, s) in elf.sections().enumerate() { match i { 0 => assert_eq!(s.header().section_type(), SectionType::Null), 2 => assert_eq!(s.header().section_type(), SectionType::ProgramData), 5 => assert_eq!(s.header().section_type(), SectionType::SymbolTable), 6 => assert_eq!(s.header().section_type(), SectionType::StringTable), _ => continue } } } #[test] fn segment_iters() { let elf = _load_example_binary(); println!("{:#?}", elf); for (i, h) in elf.segments().enumerate() { match i { 0 => assert_eq!(h.header().program_header_type(), ProgramHeaderType::Phdr), 1 => assert_eq!(h.header().program_header_type(), ProgramHeaderType::Loadable), 2 => assert_eq!(h.header().program_header_type(), ProgramHeaderType::Loadable), 3 => assert_eq!(h.header().program_header_type(), ProgramHeaderType::GnuStack), 4 => assert_eq!(h.header().program_header_type(), ProgramHeaderType::ArmExidx), _ => continue } } } }
#![warn(missing_docs)] use std::error::Error; use std::fmt::{ Display, Formatter }; use std::io::{ Read, Seek, SeekFrom }; use std::collections::HashMap; #[macro_use] mod macros; pub mod types; pub mod numeric; pub mod constants; use crate::types::*; pub type ParseElfResult<T> = std::result::Result<T, ParseElfError>; #[derive(Debug)] pub enum ParseElfError { IoError{ inner: std::io::Error }, #[allow(missing_docs)] InvalidSectionType(u32), #[allow(missing_docs)] InvalidProgramFlags(u32), #[allow(missing_docs)] InvalidProgramHeader(u32), #[allow(missing_docs)] InvalidVersion(u32), #[allow(missing_docs)] InvalidMachine(u16), #[allow(missing_docs)] InvalidElfType(u16), #[allow(missing_docs)] InvalidOsAbi(u8), #[allow(missing_docs)] InvalidIdentVersion(u8), #[allow(missing_docs)] InvalidDataFormat(u8), #[allow(missing_docs)] InvalidDataClass(u8), InvalidParsingDescriptor, } impl Error for ParseElfError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { ParseElfError::IoError{ inner } => Some(inner), _ => None, } } } impl Display for ParseElfError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "{:?}", self) } } impl From<std::io::Error> for ParseElfError { fn from(err: std::io::Error) -> ParseElfError { ParseElfError::IoError{ inner: err } } } trait Parslet { fn parse<R: Read + Seek>(reader: &mut R, descriptor: &mut Descriptor) -> ParseElfResult<Self> where Self: Sized; } enum Descriptor { None, Data{ format: DataFormat, class: DataClass }, } impl Descriptor { fn data_class(&self) -> ParseElfResult<DataClass> { match self { Descriptor::Data{ class, .. } => Ok(*class), Descriptor::None => Err(ParseElfError::InvalidParsingDescriptor), } } fn data_format(&self) -> ParseElfResult<DataFormat> { match self { Descriptor::Data{ format, .. } => Ok(*format), Descriptor::None => Err(ParseElfError::InvalidParsingDescriptor) } } } #[derive(Debug)] pub struct Elf { header: ElfHeader, sections: Vec<Section>, segments: Vec<Segment>, section_map: HashMap<String, usize>, } impl Elf { pub fn load<P: AsRef<std::path::Path>>(path: P) -> ParseElfResult<Elf> { let file = std::fs::File::open(path)?; let mut buf = std::io::BufReader::new(file); Ok(Elf::parse(&mut buf)?) } pub fn parse<R: Read + Seek>(reader: &mut R) -> ParseElfResult<Elf> { let mut descriptor = Descriptor::None; let header = ElfHeader::parse(reader, &mut descriptor)?; let sections = parse_sections(reader, &mut descriptor, &header)?; let segments = parse_segments(reader, &mut descriptor, &header)?; let mut section_map = HashMap::new(); associate_string_table(&mut section_map, &sections, &header); Ok(Elf{ header, sections, segments, section_map }) } pub fn try_get_section(&self, section_name: &str) -> Option<&Section> { self.sections.get(*self.section_map.get(section_name)?) } pub fn header(&self) -> &ElfHeader { &self.header } pub fn sections(&self) -> SectionIter { SectionIter { elf: &self, idx: 0 } } pub fn segments(&self) -> SegmentIter { SegmentIter { elf: &self, idx: 0 } } } fn parse_sections<R: Read + Seek>(reader: &mut R, descriptor: &mut Descriptor, header: &ElfHeader) -> ParseElfResult<Vec<Section>> { reader.seek(SeekFrom::Start(header.section_headers_offset()))?; let mut sections = Vec::new(); for _ in 0..header.section_header_count() { sections.push(Section::pa
0 => assert_eq!(h.header().program_header_type(), ProgramHeaderType::Phdr), 1 => assert_eq!(h.header().program_header_type(), ProgramHeaderType::Loadable), 2 => assert_eq!(h.header().program_header_type(), ProgramHeaderType::Loadable), 3 => assert_eq!(h.header().program_header_type(), ProgramHeaderType::GnuStack), 4 => assert_eq!(h.header().program_header_type(), ProgramHeaderType::ArmExidx), _ => continue } } } }
rse(reader, descriptor)?) } Ok(sections) } fn parse_segments<R: Read + Seek>(reader: &mut R, descriptor: &mut Descriptor, header: &ElfHeader) -> ParseElfResult<Vec<Segment>> { reader.seek(SeekFrom::Start(header.program_headers_offset()))?; let mut segments = Vec::new(); for _ in 0..header.program_header_count() { segments.push(Segment::parse(reader, descriptor)?) } Ok(segments) } fn associate_string_table(section_map: &mut HashMap<String, usize>, sections: &[Section], header: &ElfHeader) { if let Some(idx) = header.section_name_table_index() { if let SectionData::Strings(table) = &sections[idx].data() { for (i, _section) in sections.iter().enumerate() { let name = table[i].clone(); section_map.insert(name, i); } } } } pub struct SectionIter<'a> { elf: &'a Elf, idx: usize, } impl<'a> Iterator for SectionIter<'a> { type Item = &'a Section; fn next(&mut self) -> Option<Self::Item> { let item = self.elf.sections.get(self.idx)?; self.idx += 1; Some(item) } } pub struct SegmentIter<'a> { elf: &'a Elf, idx: usize, } impl<'a> Iterator for SegmentIter<'a> { type Item = &'a Segment; fn next(&mut self) -> Option<Self::Item> { let item = self.elf.segments.get(self.idx)?; self.idx += 1; Some(item) } } pub mod prelude { pub use crate::numeric::*; pub use crate::types::*; pub use crate::Elf; } #[cfg(test)] mod test { use super::*; fn _load_example_binary() -> Elf { let elf = Elf::load("examples/example-binary").unwrap(); elf } #[test] fn get_section_bytes() { let elf = _load_example_binary(); let text = elf.try_get_section(".text").unwrap(); if let SectionData::Bytes(_bytes) = text.data() { } } #[test] fn section_iters() { let elf = _load_example_binary(); for (i, s) in elf.sections().enumerate() { match i { 0 => assert_eq!(s.header().section_type(), SectionType::Null), 2 => assert_eq!(s.header().section_type(), SectionType::ProgramData), 5 => assert_eq!(s.header().section_type(), SectionType::SymbolTable), 6 => assert_eq!(s.header().section_type(), SectionType::StringTable), _ => continue } } } #[test] fn segment_iters() { let elf = _load_example_binary(); println!("{:#?}", elf); for (i, h) in elf.segments().enumerate() { match i {
random
[ { "content": "}\n\n\n\nmacro_rules! read_u64 {\n\n ($reader:expr, $descriptor:expr) => {\n\n {\n\n let mut __bytes: [u8; 8] = [0; 8];\n\n let mut __temp: u64 = 0;\n\n $reader.read_exact(&mut __bytes)?;\n\n unsafe {\n\n __temp = std::mem::trans...
Rust
rs/2021/day20/src/main.rs
cs-cordero/advent-of-code
614b8f78b43c54ef180a7dc411a0d1366a62944f
use advent_of_code::read_input_as_string; use std::collections::HashSet; use std::fmt::{Display, Formatter}; type Point = (isize, isize); #[derive(Clone, Debug)] struct Rect { lo_row: isize, lo_col: isize, hi_row: isize, hi_col: isize, } impl Rect { fn contains(&self, point: &Point) -> bool { let (row, col) = *point; self.lo_row <= row && row <= self.hi_row && self.lo_col <= col && col <= self.hi_col } fn on_edge_or_outside(&self, point: &Point) -> bool { let (row, col) = *point; let on_horizontal_edge = (self.lo_col..=self.hi_col).contains(&col) && (row == self.lo_row || row == self.hi_row); let on_vertical_edge = (self.lo_row..=self.hi_row).contains(&row) && (col == self.lo_col || col == self.hi_col); on_horizontal_edge || on_vertical_edge || !self.contains(point) } fn expand(&self, increase: isize) -> Self { Self { lo_row: self.lo_row - increase, lo_col: self.lo_col - increase, hi_row: self.hi_row + increase, hi_col: self.hi_col + increase, } } fn iter(&self) -> impl Iterator<Item = (isize, isize)> { let lo_row = self.lo_row; let hi_row = self.hi_row; let lo_col = self.lo_col; let hi_col = self.hi_col; (lo_row..=hi_row).flat_map(move |row| (lo_col..=hi_col).map(move |col| (row, col))) } fn rows(&self) -> impl Iterator<Item = impl Iterator<Item = (isize, isize)>> { let lo_row = self.lo_row; let hi_row = self.hi_row; let lo_col = self.lo_col; let hi_col = self.hi_col; (lo_row..=hi_row).map(move |row| (lo_col..=hi_col).map(move |col| (row, col))) } } #[derive(Clone, Debug)] struct Image { pixels_on: HashSet<Point>, dimensions: Rect, enhance_iteration_toggle: bool, enhance_algorithm: Vec<char>, } impl Display for Image { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let s = self .dimensions .rows() .map(|row| { row.map(|point| { if self.pixels_on.contains(&point) { '#' } else { '.' } }) .collect::<String>() }) .collect::<Vec<_>>() .join("\n"); write!(f, "{}", s) } } impl Image { fn create_enhanced_image(self) -> Image { let enhanced_rect = self.dimensions.expand(1); let new_pixels = enhanced_rect .iter() .filter(|point| { let algorithm_index = self.get_encoded_enhanced_pixel(*point, &enhanced_rect); *self.enhance_algorithm.get(algorithm_index).unwrap() == '#' }) .collect::<HashSet<Point>>(); Image { pixels_on: new_pixels, dimensions: enhanced_rect, enhance_iteration_toggle: !self.enhance_iteration_toggle, enhance_algorithm: self.enhance_algorithm, } } #[inline] fn get_encoded_enhanced_pixel(&self, center: Point, enhanced_rect: &Rect) -> usize { let edge_or_beyond_value = if self.distance_points_will_toggle() { if self.enhance_iteration_toggle { 1 } else { 0 } } else { 0 }; let (row, col) = center; [ (row - 1, col - 1), (row - 1, col), (row - 1, col + 1), (row, col - 1), (row, col), (row, col + 1), (row + 1, col - 1), (row + 1, col), (row + 1, col + 1), ] .iter() .map(|point| { if enhanced_rect.on_edge_or_outside(point) { edge_or_beyond_value } else if self.pixels_on.contains(point) { 1 } else { 0 } }) .fold(0usize, |acc, bit| (acc << 1) + bit) } #[inline] fn distance_points_will_toggle(&self) -> bool { self.enhance_algorithm .first() .zip(self.enhance_algorithm.last()) .map(|(first, last)| *first == '#' && *last == '.') .unwrap_or(false) } } fn main() { let raw = read_input_as_string("2021/day20/src/input.txt"); let image = { let (raw_algorithm, raw_image) = raw.split_once("\n\n").unwrap(); let algorithm = raw_algorithm.chars().collect::<Vec<_>>(); let image = raw_image .lines() .enumerate() .flat_map(|(row, line)| { line.chars() .enumerate() .filter(|(_, pixel)| *pixel == '#') .map(move |(col, _)| (row as isize, col as isize)) }) .collect::<HashSet<Point>>(); let dimensions = Rect { lo_row: 0, lo_col: 0, hi_row: *image.iter().map(|(row, _)| row).max().unwrap(), hi_col: *image.iter().map(|(_, col)| col).max().unwrap(), }; Image { pixels_on: image, dimensions, enhance_iteration_toggle: false, enhance_algorithm: algorithm, } }; let answer1 = image .clone() .create_enhanced_image() .create_enhanced_image() .pixels_on .len(); let answer2 = (0..50) .fold(image, |acc, _| acc.create_enhanced_image()) .pixels_on .len(); println!("Part 1: {:?}", answer1); println!("Part 2: {:?}", answer2); }
use advent_of_code::read_input_as_string; use std::collections::HashSet; use std::fmt::{Display, Formatter}; type Point = (isize, isize); #[derive(Clone, Debug)] struct Rect { lo_row: isize, lo_col: isize, hi_row: isize, hi_col: isize, } impl Rect { fn contains(&self, point: &Point) -> bool { let (row, col) = *point; self.lo_row <= row && row <= self.hi_row && self.lo_col <= col && col <= self.hi_col } fn on_edge_or_outside(&self, point: &Point) -> bool { let (row, col) = *point; let on_horizontal_edge = (self.lo_col..=self.hi_col).contains(&col) && (row == self.lo_row || row == self.hi_row); let on_vertical_edge = (self.lo_row..=self.hi_row).contains(&row) && (col == self.lo_col || col == self.hi_col); on_horizontal_edge || on_vertical_edge || !self.contains(point) } fn expand(&self, increase: isize) -> Self { Self { lo_row: self.lo_row - increase, lo_col: self.lo_col - increase, hi_row: self.hi_row + increase, hi_col: self.hi_col + increase, } } fn iter(&self) -> impl Iterator<Item = (isize, isize)> { let lo_row = self.lo_row; let hi_row = self.hi_row; let lo_col = self.lo_col; let hi_col = self.hi_col; (lo_row..=hi_row).flat_map(move |row| (lo_col..=hi_col).map(move |col| (row, col))) } fn rows(&self) -> impl Iterator<Item = impl Iterator<Item = (isize, isize)>> { let lo_row = self.lo_row; let hi_row = self.hi_row; let lo_col = self.lo_col; let hi_col = self.hi_col; (lo_row..=hi_row).map(move |row| (lo_col..=hi_col).map(move |col| (row, col))) } } #[derive(Clone, Debug)] struct Image { pixels_on: HashSet<Point>, dimensions: Rect, enhance_iteration_toggle: bool, enhance_algorithm: Vec<char>, } impl Display for Image { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let s = self .dimensions .rows() .map(|row| { row.map(|point| { if self.pixels_on.contains(&point) { '#' } else { '.' } }) .collect::<String>() }) .collect::<Vec<_>>() .join("\n"); write!(f, "{}", s) } } impl Image { fn create_enhanced_image(self) -> Image { let enhanced_rect = self.dimensions.expand(1); let new_pixels = enhanced_rect .iter() .filter(|point| { let algorithm_index = self.get_encoded_enhanced_pixel(*point, &enhanced_rect); *self.enhance_algorithm.get(algorithm_index).unwrap() == '#' }) .collect::<HashSet<Point>>(); Image { pixels_on: new_pixels, dimensions: enhanced_rect, enhance_iteration_toggle: !self.enhance_iteration_toggle, enhance_algorithm: self.enhance_algorithm, } } #[inline] fn get_encoded_enhanced_pixel(&self, center: Point, enhanced_rect: &Rect) -> usize { let edge_or_beyond_value = if self.distance_points_will_toggle() { if self.enhance_iteration_toggle { 1 } else { 0 } } else { 0 }; let (row, col) = center; [ (row - 1, col - 1), (row - 1, col), (row - 1, col + 1), (row, col - 1), (row, col), (row, col + 1), (row + 1, col - 1), (row + 1, col), (row + 1, col + 1), ] .iter() .map(|point| { if enhanced_rect.on_edge_or_outside(point) { edge_or_beyond_value } else if self.pixels_on.contains(point) { 1 } else { 0 } }) .fold(0usize, |acc, bit| (acc << 1) + bit) } #[inline] fn distance_points_will_toggle(&self) -> bool { self.enhance_algorithm .first() .zip(self.enhance_algorithm.last()) .map(|(first, last)| *first == '#' && *last == '.') .unwrap_or(false) } }
fn main() { let raw = read_input_as_string("2021/day20/src/input.txt"); let image = { let (raw_algorithm, raw_image) = raw.split_once("\n\n").unwrap(); let algorithm = raw_algorithm.chars().collect::<Vec<_>>(); let image = raw_image .lines() .enumerate() .flat_map(|(row, line)| { line.chars() .enumerate() .filter(|(_, pixel)| *pixel == '#') .map(move |(col, _)| (row as isize, col as isize)) }) .collect::<HashSet<Point>>(); let dimensions = Rect { lo_row: 0, lo_col: 0, hi_row: *image.iter().map(|(row, _)| row).max().unwrap(), hi_col: *image.iter().map(|(_, col)| col).max().unwrap(), }; Image { pixels_on: image, dimensions, enhance_iteration_toggle: false, enhance_algorithm: algorithm, } }; let answer1 = image .clone() .create_enhanced_image() .create_enhanced_image() .pixels_on .len(); let answer2 = (0..50) .fold(image, |acc, _| acc.create_enhanced_image()) .pixels_on .len(); println!("Part 1: {:?}", answer1); println!("Part 2: {:?}", answer2); }
function_block-full_function
[ { "content": "fn find_monster(image: &[Vec<char>], row: usize, col: usize) -> bool {\n\n MONSTER_OFFSETS\n\n .iter()\n\n .copied()\n\n .all(|(offset_row, offset_col)| {\n\n let operator = match offset_row.cmp(&0) {\n\n Ordering::Less => usize::checked_sub,\n\n ...
Rust
rust/src/main.rs
tagadvance/chms_api_examples
b8335f5e5a9216afa357944b870edf29ad838243
#[macro_use] extern crate dotenv_codegen; extern crate dotenv; mod db; mod utils; use db::{TokenDatabase, TokenResponse}; use reqwest::Url; use serde::{Deserialize, Serialize}; use std::future::Future; use std::pin::Pin; use tide::http::url::ParseError; use tide::utils::After; use tide::{Body, Next, Redirect, Request, Response, Result}; use utils::{api, env}; #[derive(Deserialize)] struct AuthCodeParams { code: String, state: String, } #[derive(Deserialize, Serialize)] struct AuthCodeBody { grant_type: String, subdomain: String, redirect_uri: String, client_id: String, client_secret: String, code: String, } #[derive(Deserialize, Serialize)] struct RefreshTokenBody { refresh_token: String, grant_type: String, client_id: String, client_secret: String, } fn build_auth_code_redirect_url(return_url: String) -> std::result::Result<Url, ParseError> { let env = env::get_env(); Url::parse_with_params( api::AUTH_CODE_URL, &[ ("client_id", env.client_id), ("subdomain", env.subdomain), ("redirect_uri", api::REDIRECT_URL.into()), ("response_type", String::from("code")), ("state", return_url), ], ) } fn build_auth_code_body(code: String) -> AuthCodeBody { let env = env::get_env(); AuthCodeBody { grant_type: String::from("authorization_code"), redirect_uri: api::REDIRECT_URL.into(), subdomain: env.subdomain, client_id: env.client_id, client_secret: env.client_secret, code, } } fn build_refresh_token_body(refresh_token: String) -> RefreshTokenBody { let env = env::get_env(); RefreshTokenBody { refresh_token, grant_type: String::from("refresh_token"), client_id: env.client_id, client_secret: env.client_secret, } } fn perform_refresh(db: &TokenDatabase) -> Result<String> { let body = build_refresh_token_body(db.get_refresh_token().unwrap()); let response = api::post::<RefreshTokenBody, TokenResponse>(&api::make_api_url("oauth/token"), &body)?; db.handle_token_response(&response)?; println!("Tokens refreshed."); Ok(response.access_token) } fn access_token_middleware<'a>( mut request: Request<TokenDatabase>, next: Next<'a, TokenDatabase>, ) -> Pin<Box<dyn Future<Output = Result> + Send + 'a>> { Box::pin(async { if request.url().path() == "/auth" { return Ok(next.run(request).await); } match request.state().get_access_token() { Some(access_token) => { request.set_ext(access_token); Ok(next.run(request).await) } None => { println!("Missing auth tokens. Redirecting to auth url."); let url_path = request.url().path(); Ok(Redirect::new(build_auth_code_redirect_url(url_path.into())?).into()) } } }) } async fn auth_code_handler(req: Request<TokenDatabase>) -> tide::Result { let params: AuthCodeParams = req.query()?; let body = build_auth_code_body(params.code); let response = api::post::<AuthCodeBody, TokenResponse>(&api::make_api_url("oauth/token"), &body)?; req.state().handle_token_response(&response)?; println!("Auth code successfully exchanged for tokens."); Ok(Redirect::new(params.state).into()) } async fn api_passthrough_handler(request: Request<TokenDatabase>) -> tide::Result<Response> { let path = request.param("path")?; match request.ext() { None => Ok(Response::from("Token Missing")), Some(token) => { let url = &api::make_api_url(path); let response = api::get::<serde_json::Value>(url, token)?; let mut json = response.0; if response.1 == reqwest::StatusCode::UNAUTHORIZED { let refreshed_token = perform_refresh(request.state())?; json = api::get::<serde_json::Value>(url, &refreshed_token)?.0; } return Ok(Response::from(Body::from_json(&json)?)); } } } #[async_std::main] async fn main() -> tide::Result<()> { let mut app = tide::with_state(TokenDatabase::new()?); app.with(access_token_middleware); app.with(After(|mut res: Response| async { if let Some(err) = res.take_error() { let msg = format!("Error: {:?}", err); res.set_status(tide::StatusCode::InternalServerError); res.set_body(msg); }; Ok(res) })); app.at("/auth").get(auth_code_handler); app.at("api/*path").get(api_passthrough_handler); app.listen("127.0.0.1:3000").await?; Ok(()) }
#[macro_use] extern crate dotenv_codegen; extern crate dotenv; mod db; mod utils; use db::{TokenDatabase, TokenResponse}; use reqwest::Url; use serde::{Deserialize, Serialize}; use std::future::Future; use std::pin::Pin; use tide::http::url::ParseError; use tide::utils::After; use tide::{Body, Next, Redirect, Request, Response, Result}; use utils::{api, env}; #[derive(Deserialize)] struct AuthCodeParams { code: String, state: String, } #[derive(Deserialize, Serialize)] struct AuthCodeBody { grant_type: String, subdomain: String, re
rl("oauth/token"), &body)?; req.state().handle_token_response(&response)?; println!("Auth code successfully exchanged for tokens."); Ok(Redirect::new(params.state).into()) } async fn api_passthrough_handler(request: Request<TokenDatabase>) -> tide::Result<Response> { let path = request.param("path")?; match request.ext() { None => Ok(Response::from("Token Missing")), Some(token) => { let url = &api::make_api_url(path); let response = api::get::<serde_json::Value>(url, token)?; let mut json = response.0; if response.1 == reqwest::StatusCode::UNAUTHORIZED { let refreshed_token = perform_refresh(request.state())?; json = api::get::<serde_json::Value>(url, &refreshed_token)?.0; } return Ok(Response::from(Body::from_json(&json)?)); } } } #[async_std::main] async fn main() -> tide::Result<()> { let mut app = tide::with_state(TokenDatabase::new()?); app.with(access_token_middleware); app.with(After(|mut res: Response| async { if let Some(err) = res.take_error() { let msg = format!("Error: {:?}", err); res.set_status(tide::StatusCode::InternalServerError); res.set_body(msg); }; Ok(res) })); app.at("/auth").get(auth_code_handler); app.at("api/*path").get(api_passthrough_handler); app.listen("127.0.0.1:3000").await?; Ok(()) }
direct_uri: String, client_id: String, client_secret: String, code: String, } #[derive(Deserialize, Serialize)] struct RefreshTokenBody { refresh_token: String, grant_type: String, client_id: String, client_secret: String, } fn build_auth_code_redirect_url(return_url: String) -> std::result::Result<Url, ParseError> { let env = env::get_env(); Url::parse_with_params( api::AUTH_CODE_URL, &[ ("client_id", env.client_id), ("subdomain", env.subdomain), ("redirect_uri", api::REDIRECT_URL.into()), ("response_type", String::from("code")), ("state", return_url), ], ) } fn build_auth_code_body(code: String) -> AuthCodeBody { let env = env::get_env(); AuthCodeBody { grant_type: String::from("authorization_code"), redirect_uri: api::REDIRECT_URL.into(), subdomain: env.subdomain, client_id: env.client_id, client_secret: env.client_secret, code, } } fn build_refresh_token_body(refresh_token: String) -> RefreshTokenBody { let env = env::get_env(); RefreshTokenBody { refresh_token, grant_type: String::from("refresh_token"), client_id: env.client_id, client_secret: env.client_secret, } } fn perform_refresh(db: &TokenDatabase) -> Result<String> { let body = build_refresh_token_body(db.get_refresh_token().unwrap()); let response = api::post::<RefreshTokenBody, TokenResponse>(&api::make_api_url("oauth/token"), &body)?; db.handle_token_response(&response)?; println!("Tokens refreshed."); Ok(response.access_token) } fn access_token_middleware<'a>( mut request: Request<TokenDatabase>, next: Next<'a, TokenDatabase>, ) -> Pin<Box<dyn Future<Output = Result> + Send + 'a>> { Box::pin(async { if request.url().path() == "/auth" { return Ok(next.run(request).await); } match request.state().get_access_token() { Some(access_token) => { request.set_ext(access_token); Ok(next.run(request).await) } None => { println!("Missing auth tokens. Redirecting to auth url."); let url_path = request.url().path(); Ok(Redirect::new(build_auth_code_redirect_url(url_path.into())?).into()) } } }) } async fn auth_code_handler(req: Request<TokenDatabase>) -> tide::Result { let params: AuthCodeParams = req.query()?; let body = build_auth_code_body(params.code); let response = api::post::<AuthCodeBody, TokenResponse>(&api::make_api_u
random
[ { "content": "pub fn get<R: DeserializeOwned>(url: &String, token: &String) -> Result<(R, reqwest::StatusCode)> {\n\n let response = reqwest::blocking::Client::new()\n\n .get(url)\n\n .header(\"Content-Type\", \"application/json\")\n\n .header(\"Accept\", \"application/vnd.ccbchurch.v2+json\")\n\n ...
Rust
src/lib.rs
Gingeh/brainfrick
bd7fe1a2cc7dbee0b1c81e2b585c66d320facac5
use std::collections::VecDeque; pub struct BrainFuck { memory: Vec<Cell>, pointer: usize, input: VecDeque<u8>, counter: usize, max_steps: usize, } impl BrainFuck { #[must_use] pub fn new(size: usize, input: &str, max_steps: usize) -> Self { BrainFuck { memory: vec![Cell::from(0); size], pointer: 0, counter: 0, input: queue_from(input), max_steps, } } pub fn run(&mut self, program: &str) -> Result<String, String> { let mut output = String::new(); let program: Vec<char> = program.chars().collect(); let mut steps: usize = 0; while self.counter < program.len() { let ch = program[self.counter]; match ch { '+' => self.add(), '-' => self.sub(), '<' => self.left(), '>' => self.right(), '.' => output += &self.print(), ',' => self.read(), '[' => self.start(&program)?, ']' => self.end(&program)?, _ => {} } self.counter += 1; if steps == self.max_steps { return Err(format!( "Exceeded maximum steps ({}), the program may be stuck in a loop.", self.max_steps )); } steps += 1; } Ok(output) } fn add(&mut self) { self.memory[self.pointer].add(); } fn sub(&mut self) { self.memory[self.pointer].sub(); } fn left(&mut self) { self.pointer = if self.pointer == 0 { self.memory.len() - 1 } else { self.pointer - 1 } } fn right(&mut self) { self.pointer = if self.pointer == self.memory.len() - 1 { 0 } else { self.pointer + 1 } } fn print(&mut self) -> String { self.memory[self.pointer].to_string() } fn read(&mut self) { self.memory[self.pointer] = Cell::from(self.input.pop_front().unwrap_or(0)); } fn start(&mut self, program: &[char]) -> Result<(), String> { if self.memory[self.pointer] == Cell::from(0) { let mut level: usize = 1; while level > 0 { self.counter += 1; if self.counter == program.len() { return Err(String::from("A matching \"]\" could not be found.")); } if program[self.counter] == '[' { level += 1; } else if program[self.counter] == ']' { level -= 1; } } } Ok(()) } fn end(&mut self, program: &[char]) -> Result<(), String> { if self.memory[self.pointer] != Cell::from(0) { let mut level: usize = 1; while level > 0 { if self.counter == 0 { return Err(String::from("A matching \"[\" could not be found.")); } self.counter -= 1; if program[self.counter] == '[' { level -= 1; } else if program[self.counter] == ']' { level += 1; } } } Ok(()) } } #[derive(PartialEq, Clone, Copy)] struct Cell { value: u8, } impl Cell { fn add(&mut self) { self.value = if self.value == 255 { 0 } else { self.value + 1 } } fn sub(&mut self) { self.value = if self.value == 0 { 255 } else { self.value - 1 } } } impl ToString for Cell { fn to_string(&self) -> String { String::from(self.value as char) } } impl From<u8> for Cell { fn from(value: u8) -> Self { Self { value } } } fn queue_from(input: &str) -> VecDeque<u8> { VecDeque::from(input.as_bytes().to_vec()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_input() { let program = ",++.,-."; let mut engine = BrainFuck::new(256, "a", 10000); assert_eq!(engine.run(program), Ok(String::from("cÿ"))); } #[test] fn test_wraparound() { let program = "->>.<<."; let mut engine = BrainFuck::new(2, "", 10000); assert_eq!(engine.run(program), Ok(String::from("ÿÿ"))); } #[test] fn test_max_steps() { let program = "+[]"; let mut engine = BrainFuck::new(256, "", 100); assert_eq!( engine.run(program), Err(String::from( "Exceeded maximum steps (100), the program may be stuck in a loop." )) ); } #[test] fn test_invalid_character() { let program = "nothing lol"; let mut engine = BrainFuck::new(256, "", 10000); assert_eq!(engine.run(program), Ok(String::new())); } #[test] fn test_missing_bracket() { let program = "["; let mut engine = BrainFuck::new(256, "", 10000); assert_eq!( engine.run(program), Err(String::from("A matching \"]\" could not be found.")) ); let program = "+]"; let mut engine = BrainFuck::new(256, "", 10000); assert_eq!( engine.run(program), Err(String::from("A matching \"[\" could not be found.")) ); } #[test] fn test_loop() { let program = "[[-.+]]++[-]-."; let mut engine = BrainFuck::new(256, "", 10000); assert_eq!(engine.run(program), Ok(String::from("ÿ"))); } }
use std::collections::VecDeque; pub struct BrainFuck { memory: Vec<Cell>, pointer: usize, input: VecDeque<u8>, counter: usize, max_steps: usize, } impl BrainFuck { #[must_use] pub fn new(size: usize, input: &str, max_steps: usize) -> Self { BrainFuck { memory: vec![Cell::from(0); size], pointer: 0, counter: 0, input: queue_from(input), max_steps, } } pub fn run(&mut self, program: &str) -> Result<String, String> { let mut output = String::new(); let program: Vec<char> = program.chars().collect(); let mut steps: usize = 0; while self.counter < program.len() { let ch = program[self.counter]; match ch { '+
))); } #[test] fn test_max_steps() { let program = "+[]"; let mut engine = BrainFuck::new(256, "", 100); assert_eq!( engine.run(program), Err(String::from( "Exceeded maximum steps (100), the program may be stuck in a loop." )) ); } #[test] fn test_invalid_character() { let program = "nothing lol"; let mut engine = BrainFuck::new(256, "", 10000); assert_eq!(engine.run(program), Ok(String::new())); } #[test] fn test_missing_bracket() { let program = "["; let mut engine = BrainFuck::new(256, "", 10000); assert_eq!( engine.run(program), Err(String::from("A matching \"]\" could not be found.")) ); let program = "+]"; let mut engine = BrainFuck::new(256, "", 10000); assert_eq!( engine.run(program), Err(String::from("A matching \"[\" could not be found.")) ); } #[test] fn test_loop() { let program = "[[-.+]]++[-]-."; let mut engine = BrainFuck::new(256, "", 10000); assert_eq!(engine.run(program), Ok(String::from("ÿ"))); } }
' => self.add(), '-' => self.sub(), '<' => self.left(), '>' => self.right(), '.' => output += &self.print(), ',' => self.read(), '[' => self.start(&program)?, ']' => self.end(&program)?, _ => {} } self.counter += 1; if steps == self.max_steps { return Err(format!( "Exceeded maximum steps ({}), the program may be stuck in a loop.", self.max_steps )); } steps += 1; } Ok(output) } fn add(&mut self) { self.memory[self.pointer].add(); } fn sub(&mut self) { self.memory[self.pointer].sub(); } fn left(&mut self) { self.pointer = if self.pointer == 0 { self.memory.len() - 1 } else { self.pointer - 1 } } fn right(&mut self) { self.pointer = if self.pointer == self.memory.len() - 1 { 0 } else { self.pointer + 1 } } fn print(&mut self) -> String { self.memory[self.pointer].to_string() } fn read(&mut self) { self.memory[self.pointer] = Cell::from(self.input.pop_front().unwrap_or(0)); } fn start(&mut self, program: &[char]) -> Result<(), String> { if self.memory[self.pointer] == Cell::from(0) { let mut level: usize = 1; while level > 0 { self.counter += 1; if self.counter == program.len() { return Err(String::from("A matching \"]\" could not be found.")); } if program[self.counter] == '[' { level += 1; } else if program[self.counter] == ']' { level -= 1; } } } Ok(()) } fn end(&mut self, program: &[char]) -> Result<(), String> { if self.memory[self.pointer] != Cell::from(0) { let mut level: usize = 1; while level > 0 { if self.counter == 0 { return Err(String::from("A matching \"[\" could not be found.")); } self.counter -= 1; if program[self.counter] == '[' { level -= 1; } else if program[self.counter] == ']' { level += 1; } } } Ok(()) } } #[derive(PartialEq, Clone, Copy)] struct Cell { value: u8, } impl Cell { fn add(&mut self) { self.value = if self.value == 255 { 0 } else { self.value + 1 } } fn sub(&mut self) { self.value = if self.value == 0 { 255 } else { self.value - 1 } } } impl ToString for Cell { fn to_string(&self) -> String { String::from(self.value as char) } } impl From<u8> for Cell { fn from(value: u8) -> Self { Self { value } } } fn queue_from(input: &str) -> VecDeque<u8> { VecDeque::from(input.as_bytes().to_vec()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_input() { let program = ",++.,-."; let mut engine = BrainFuck::new(256, "a", 10000); assert_eq!(engine.run(program), Ok(String::from("cÿ"))); } #[test] fn test_wraparound() { let program = "->>.<<."; let mut engine = BrainFuck::new(2, "", 10000); assert_eq!(engine.run(program), Ok(String::from("ÿÿ"
random
[ { "content": "#[derive(StructOpt)]\n\n#[structopt(name = \"brainfrick\", about = \"Rust implementation of Brainfuck\")]\n\nstruct Opt {\n\n /// Path to program [optional: will use stdin instead]\n\n #[structopt()]\n\n path: Option<path::PathBuf>,\n\n\n\n /// Input given to program\n\n #[structopt...
Rust
src/service.rs
kfastov/moleculer-rs
c59695f4567a53d24cc9b9072d67a21f104059ff
use serde::{Deserialize, Serialize}; use serde_json::Value; use std::{collections::HashMap, marker::PhantomData}; use crate::{ channels::messages::incoming::{EventMessage, RequestMessage}, Error, ServiceBroker, }; pub type Callback<T> = fn(Context<T>) -> Result<(), Box<dyn std::error::Error>>; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Action { name: String, #[serde(default)] params: Option<Value>, #[serde(skip)] pub(crate) callback: Option<Callback<Action>>, } #[derive(Default, Debug)] pub struct EventBuilder { name: String, params: Option<Value>, callback: Option<Callback<Event>>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Event { name: String, #[serde(default)] params: Option<Value>, #[serde(skip)] pub(crate) callback: Option<Callback<Event>>, } impl EventBuilder { pub fn new<S: Into<String>>(name: S) -> Self { Self { name: name.into(), ..Self::default() } } pub fn add_params(mut self, params: Value) -> Self { self.params = Some(params); self } pub fn add_callback(mut self, callback: Callback<Event>) -> Self { self.callback = Some(callback); self } pub fn build(self) -> Event { Event { name: self.name, params: self.params, callback: self.callback, } } } #[derive(Default, Debug)] pub struct ActionBuilder { name: String, params: Option<Value>, callback: Option<Callback<Action>>, } impl ActionBuilder { pub fn new<S: Into<String>>(name: S) -> Self { Self { name: name.into(), ..Self::default() } } pub fn add_params(mut self, params: Value) -> Self { self.params = Some(params); self } pub fn add_callback(mut self, callback: Callback<Action>) -> Self { self.callback = Some(callback); self } pub fn build(self) -> Action { Action { name: self.name, params: self.params, callback: self.callback, } } } #[derive(Serialize, Deserialize, Debug, Default)] #[serde(rename_all = "camelCase")] pub struct Service { name: String, version: Option<i32>, #[serde(default)] #[serde(skip_deserializing)] settings: HashMap<String, String>, #[serde(default)] metadata: Option<Value>, pub(crate) actions: HashMap<String, Action>, pub(crate) events: HashMap<String, Event>, } impl Service { pub fn new<S: Into<String>>(name: S) -> Self { Self { name: name.into(), ..Default::default() } } pub fn set_version(mut self, version: i32) -> Self { self.version = Some(version); self } pub fn add_action(mut self, action: Action) -> Self { self.actions.insert(action.name.clone(), action); self } pub fn add_event(mut self, event: Event) -> Self { self.events.insert(event.name.clone(), event); self } } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "lowercase")] pub enum EventType { Emit, Broadcast, } pub struct Context<T> { phantom: PhantomData<T>, pub id: String, pub broker: ServiceBroker, pub node_id: String, pub action: Option<String>, pub event_name: Option<String>, pub event_type: Option<EventType>, pub event_groups: Vec<String>, pub caller: Option<String>, pub request_id: Option<String>, pub parent_id: Option<String>, pub params: Value, pub meta: Value, pub locals: Option<Value>, pub level: i32, } impl Context<Event> { pub(crate) fn new(event_message: EventMessage, service_broker: ServiceBroker) -> Self { let event_type = if event_message.broadcast.unwrap_or(false) { EventType::Broadcast } else { EventType::Emit }; Self { phantom: PhantomData, broker: service_broker, id: event_message.id, params: event_message.data, action: None, event_type: Some(event_type), event_name: Some(event_message.event), event_groups: vec![], node_id: event_message.sender, caller: event_message.caller, parent_id: event_message.parent_id, request_id: event_message.request_id, meta: event_message.meta, level: event_message.level, locals: None, } } } impl Context<Action> { pub(crate) fn new(request_message: RequestMessage, service_broker: ServiceBroker) -> Self { Self { phantom: PhantomData, broker: service_broker, id: request_message.request_id.clone(), params: request_message.params, action: Some(request_message.action), event_type: None, event_name: None, event_groups: vec![], node_id: request_message.sender, caller: request_message.caller, parent_id: request_message.parent_id, request_id: Some(request_message.request_id), meta: request_message.meta, level: 1, locals: None, } } pub fn reply(&self, params: Value) { act_zero::send!(self .broker .addr .reply(self.node_id.clone(), self.id.clone(), params)); } } impl<T> Context<T> { pub fn emit<S: Into<String>>(&self, event: S, params: Value) { self.broker.emit(event, params) } pub fn broadcast<S: Into<String>>(&self, event: S, params: Value) { self.broker.broadcast(event, params) } pub async fn call<S: Into<String>>(self, action: S, params: Value) -> Result<Value, Error> { self.broker.call(action, params).await } }
use serde::{Deserialize, Serialize}; use serde_json::Value; use std::{collections::HashMap, marker::PhantomData}; use crate::{ channels::messages::incoming::{EventMessage, RequestMessage}, Error, ServiceBroker, }; pub type Callback<T> = fn(Context<T>) -> Result<(), Box<dyn std::error::Error>>; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Action { name: String, #[serde(default)] params: Option<Value>, #[serde(skip)] pub(crate) callback: Option<Callback<Action>>, } #[derive(Default, Debug)] pub struct EventBuilder { name: String, params: Option<Value>, callback: Option<Callback<Event>>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Event { name: String, #[serde(default)] params: Option<Value>, #[serde(skip)] pub(crate) callback: Option<Callback<Event>>, } impl EventBuilder { pub fn new<S: Into<String>>(name: S) -> Self { Self { name: name.into(), ..Self::default() } } pub fn add_params(mut self, params: Value) -> Self { self.params = Some(params); self } pub fn add_callback(mut self, callback: Callback<Event>) -> Self { self.callback = Some(callback); self } pub fn build(self) -> Event { Event { name: self.name, params: self.params, callback: self.callback, } } } #[derive(Default, Debug)] pub struct ActionBuilder { name: String, params: Option<Value>, callback: Option<Callback<Action>>, } impl ActionBuilder { pub fn new<S: Into<String>>(name: S) -> Self { Self { name: name.into(), ..Self::default() } } pub fn add_params(mut self, params: Value) -> Self { self.params = Some(params); self } pub fn add_callback(mut self, callback: Callback<Action>) -> Self { self.callback = Some(callback); self } pub fn build(self) -> Action { Action { name: self.name, params: self.params, callback: self.callback, } } } #[derive(Serialize, Deserialize, Debug, Default)] #[serde(rename_all = "camelCase")] pub struct Service { name: String, version: Option<i32>, #[serde(default)] #[serde(skip_deserializing)] settings: HashMap<String, String>, #[serde(default)] metadata: Option<Value>, pub(crate) actions: HashMap<String, Action>, pub(crate) events: HashMap<String, Event>, } impl Service { pub fn new<S: Into<String>>(name: S) -> Self { Self { name: name.into(), ..Default::default() } } pub fn set_version(mut self, version: i32) -> Self { self.version = Some(version); self } pub fn add_action(mut self, action: Action) -> Self { self.actions.insert(action.name.clone(), action); self } pub fn add_event(mut self, event: Event) -> Self { self.events.insert(event.name.clone(), event); self } } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "lowercase")] pub enum EventType { Emit, Broadcast, } pub struct Context<T> { phantom: PhantomData<T>, pub id: String, pub broker: ServiceBroker, pub node_id: String, pub action: Option<String>, pub event_name: Option<String>, pub event_type: Option<EventType>, pub event_groups: Vec<String>, pub caller: Option<String>, pub request_id: Option<String>, pub parent_id: Option<String>, pub params: Value, pub meta: Value, pub locals: Option<Value>, pub level: i32, } impl Context<Event> { pub(crate) fn new(event_message: EventMessage, service_broker: ServiceBroker) -> Self {
Self { phantom: PhantomData, broker: service_broker, id: event_message.id, params: event_message.data, action: None, event_type: Some(event_type), event_name: Some(event_message.event), event_groups: vec![], node_id: event_message.sender, caller: event_message.caller, parent_id: event_message.parent_id, request_id: event_message.request_id, meta: event_message.meta, level: event_message.level, locals: None, } } } impl Context<Action> { pub(crate) fn new(request_message: RequestMessage, service_broker: ServiceBroker) -> Self { Self { phantom: PhantomData, broker: service_broker, id: request_message.request_id.clone(), params: request_message.params, action: Some(request_message.action), event_type: None, event_name: None, event_groups: vec![], node_id: request_message.sender, caller: request_message.caller, parent_id: request_message.parent_id, request_id: Some(request_message.request_id), meta: request_message.meta, level: 1, locals: None, } } pub fn reply(&self, params: Value) { act_zero::send!(self .broker .addr .reply(self.node_id.clone(), self.id.clone(), params)); } } impl<T> Context<T> { pub fn emit<S: Into<String>>(&self, event: S, params: Value) { self.broker.emit(event, params) } pub fn broadcast<S: Into<String>>(&self, event: S, params: Value) { self.broker.broadcast(event, params) } pub async fn call<S: Into<String>>(self, action: S, params: Value) -> Result<Value, Error> { self.broker.call(action, params).await } }
let event_type = if event_message.broadcast.unwrap_or(false) { EventType::Broadcast } else { EventType::Emit };
assignment_statement
[ { "content": "fn broadcast_name(ctx: Context<Event>) -> Result<(), Box<dyn Error>> {\n\n let msg: PrintNameMessage = serde_json::from_value(ctx.params)?;\n\n println!(\"Received broadcastName in rust\");\n\n ctx.broker\n\n .broadcast(\"testWithParam\", serde_json::to_value(&msg)?);\n\n\n\n Ok...
Rust
tools/butler/src/db/photos/patch.rs
hsfzxjy/omoyde
6cda092c1f895ac03e1aea2c32e315a9bad06202
use crate::prelude::*; use paste::paste; use std::borrow::Cow; use std::ptr::NonNull; #[derive(Clone, Debug)] pub struct Diff<'a, T: Clone> { old: Cow<'a, T>, new: Option<Cow<'a, T>>, } impl<'a, T: Clone> From<T> for Diff<'a, T> { fn from(v: T) -> Self { Self { old: Cow::Owned(v), new: None, } } } impl<'a, T: Clone> From<&'a T> for Diff<'a, T> { fn from(v: &'a T) -> Self { Self { old: Cow::Borrowed(v), new: None, } } } impl<'b, 'a: 'b, 'c: 'a, T: Clone> Diff<'a, T> { fn write(&self, slot: &mut T) { self.new.as_ref().map(|v| *slot = v.clone().into_owned()); } fn get_mut(&'b mut self) -> &'b mut T { if self.new.is_none() { self.new = Some(self.old.clone()); } self.new.as_mut().unwrap().to_mut() } pub fn set(&mut self, v: T) { *self.get_mut() = v; } fn current(&self) -> &T { self.new.as_ref().unwrap_or(&self.old) } fn to_owned(&'b self) -> Diff<'c, T> { Diff { old: Cow::Owned(self.old.clone().into_owned()), new: self .new .as_ref() .map(|x| Cow::Owned(x.clone().into_owned())), } } } impl<'a, T: Eq + Clone> Diff<'a, T> { fn changed(&self) -> bool { if matches!(self.old, Cow::Borrowed(_)) && matches!(self.new, None | Some(Cow::Borrowed(_))) { return false; } self.new .as_ref() .map(|new| new.ne(&self.old)) .unwrap_or(false) } fn run_if_changed<F>(&self, f: F) where F: FnOnce(&T, &T), { if self.changed() { f(&self.old, &self.new.as_ref().unwrap()) } } } macro_rules! fields { ($action: ident; $args: tt) => { fields!{@iter $action, $args, [ (metadata; PhotoMetadata), (file_hash; FileHash), (selected; bool), (status; PhotoRecordStatus), (commit_time; Option<DateTime<Utc>>) ]} }; (@iter define_struct, (), [ $(( $N: ident; $T: ty )),+ ]) => { #[derive(Debug)] pub struct PhotoRecordDiff<'a> { pub pid: PID, is_missing: bool, $( pub $N: Diff<'a, $T>, )+ } }; (@iter to_owned, ($self: ident), [ $(( $N: ident; $T: ty )),+ ]) => { PhotoRecordDiff { pid: $self.pid, is_missing: $self.is_missing, $( $N: $self.$N.to_owned(), )+ } }; (@iter new, ($arg: ident), [ $(( $N: ident; $T: ty )),+ ]) => { Self { pid: $arg.pid, is_missing: false, $( $N: (&$arg.$N).into(), )+ } }; (@iter $action: ident, $args: tt, [ $(( $N: ident; $T: ty )),+ ]) => { $( fields!(@call $action, $args, $N, $T); )+ }; (@call write, ($self: ident, $arg: ident, $changed: ident), $N: ident, $T: ty) => { if $self.$N.changed() { $self.$N.old.to_mut(); $self.$N.write(&mut $arg.$N); $changed = true; } }; (@call accessor, (), $N: ident, $T: ty) => { paste!{ pub fn $N(&self) -> &$T { self.rec_diff.$N.current() } pub fn [<set_ $N>](&mut self, v: $T) { *self.rec_diff.$N.get_mut() = v; } pub fn [<$N _mut>](&mut self) -> &mut $T { self.rec_diff.$N.get_mut() } pub fn [<with_ $N>](mut self, v: $T) -> Self { self.[<set_ $N>](v); self } pub fn [<set_ $N _with>]<F>(mut self, f: F) -> Self where F: FnOnce(&mut $T) { f(self.rec_diff.$N.get_mut()); self } } } } fields!(define_struct; ()); impl<'a> PhotoRecordDiff<'a> { fn write<'b, 'c>(&'b mut self, rec: &'c mut PhotoRecord) -> (&'c PhotoRecord, bool) { let mut changed = false; fields!(write; (self, rec, changed)); (rec, changed) } pub fn new(rec: &'a PhotoRecord) -> Self { fields!(new; (rec)) } fn is_dirty(&self) -> bool { self.file_hash.changed() || self.metadata.changed() } fn to_owned<'c: 'a>(&self) -> PhotoRecordDiff<'c> { fields!(to_owned; (self)) } } pub struct PhotoRecordPatch<'b, 'a: 'b> { commit_at_drop: bool, rec_diff: PhotoRecordDiff<'a>, rec: NonNull<PhotoRecord>, ptr: &'b TableRefMut<'a, PhotoTable>, } #[allow(dead_code)] impl<'b, 'a: 'b> PhotoRecordPatch<'b, 'a> { fields!(accessor; ()); pub(super) fn with_diff<'c: 'a>(mut self, diff: PhotoRecordDiff<'c>) -> Self { self.rec_diff = diff; self } pub fn mark_missing(&mut self) { self.rec_diff.is_missing = true } pub fn into_diff<'c>(mut self) -> PhotoRecordDiff<'c> { self.commit_at_drop = false; let ret = self.rec_diff.to_owned(); drop(self); ret } } impl<'b, 'a: 'b> Drop for PhotoRecordPatch<'b, 'a> { fn drop(&mut self) { if !self.commit_at_drop { return; } let ptr = unsafe { self.ptr.as_mut() }; if *self.selected() && self.rec_diff.is_missing { self.status_mut().handle_local_missing(); } else { let is_dirty = self.rec_diff.is_dirty(); self.status_mut().handle_dirty_mark(is_dirty); } { let status = &self.rec_diff.status; if status.changed() && *status.current() == Committed { self.set_commit_time(Some(Utc::now())) } } let (rec, changed) = self.rec_diff.write(unsafe { self.rec.as_mut() }); if changed { unsafe { self.ptr.as_mut() }.modified_flag().set(); } self.rec_diff.selected.run_if_changed(|_o, _n| { ptr.index.flip_selected(rec); }); self.rec_diff.status.run_if_changed(|o, n| { ptr.index.mutate_status(rec.pid, o.clone(), n.clone()); }); } } impl<'b, 'a: 'b> TableRecordPatch<'b, 'a> for PhotoRecordPatch<'b, 'a> { type Table = PhotoTable; fn new(rec: TableRecordMut<'a, Self::Table>, ptr: &'b TableRefMut<'a, Self::Table>) -> Self { let rec_ptr = unsafe { NonNull::new(std::mem::transmute(rec as *const _)).unwrap() }; Self { commit_at_drop: true, rec_diff: PhotoRecordDiff::new(rec), rec: rec_ptr, ptr, } } }
use crate::prelude::*; use paste::paste; use std::borrow::Cow; use std::ptr::NonNull; #[derive(Clone, Debug)] pub struct Diff<'a, T: Clone> { old: Cow<'a, T>, new: Option<Cow<'a, T>>, } impl<'a, T: Clone> From<T> for Diff<'a, T> { fn from(v: T) -> Self { Self { old: Cow::Owned(v), new: None, } } } impl<'a, T: Clone> From<&'a T> for Diff<'a, T> { fn from(v: &'a T) -> Self { Self { old: Cow::Borrowed(v), new: None, } } } impl<'b, 'a: 'b, 'c: 'a, T: Clone> Diff<'a, T> { fn write(&self, slot: &mut T) { self.new.as_ref().map(|v| *slot = v.clone().into_owned()); } fn get_mut(&'b mut self) -> &'b mut T { if self.new.is_none() { self.new = Some(self.old.clone()); } self.new.as_mut().unwrap().to_mut() } pub fn set(&mut self, v: T) { *self.get_mut() = v; } fn current(&self) -> &T { self.new.as_ref().unwrap_or(&self.old) } fn to_owned(&'b self) -> Diff<'c, T> { Diff { old: Cow::Owned(self.old.clone().into_owned()), new: s
td::mem::transmute(rec as *const _)).unwrap() }; Self { commit_at_drop: true, rec_diff: PhotoRecordDiff::new(rec), rec: rec_ptr, ptr, } } }
elf .new .as_ref() .map(|x| Cow::Owned(x.clone().into_owned())), } } } impl<'a, T: Eq + Clone> Diff<'a, T> { fn changed(&self) -> bool { if matches!(self.old, Cow::Borrowed(_)) && matches!(self.new, None | Some(Cow::Borrowed(_))) { return false; } self.new .as_ref() .map(|new| new.ne(&self.old)) .unwrap_or(false) } fn run_if_changed<F>(&self, f: F) where F: FnOnce(&T, &T), { if self.changed() { f(&self.old, &self.new.as_ref().unwrap()) } } } macro_rules! fields { ($action: ident; $args: tt) => { fields!{@iter $action, $args, [ (metadata; PhotoMetadata), (file_hash; FileHash), (selected; bool), (status; PhotoRecordStatus), (commit_time; Option<DateTime<Utc>>) ]} }; (@iter define_struct, (), [ $(( $N: ident; $T: ty )),+ ]) => { #[derive(Debug)] pub struct PhotoRecordDiff<'a> { pub pid: PID, is_missing: bool, $( pub $N: Diff<'a, $T>, )+ } }; (@iter to_owned, ($self: ident), [ $(( $N: ident; $T: ty )),+ ]) => { PhotoRecordDiff { pid: $self.pid, is_missing: $self.is_missing, $( $N: $self.$N.to_owned(), )+ } }; (@iter new, ($arg: ident), [ $(( $N: ident; $T: ty )),+ ]) => { Self { pid: $arg.pid, is_missing: false, $( $N: (&$arg.$N).into(), )+ } }; (@iter $action: ident, $args: tt, [ $(( $N: ident; $T: ty )),+ ]) => { $( fields!(@call $action, $args, $N, $T); )+ }; (@call write, ($self: ident, $arg: ident, $changed: ident), $N: ident, $T: ty) => { if $self.$N.changed() { $self.$N.old.to_mut(); $self.$N.write(&mut $arg.$N); $changed = true; } }; (@call accessor, (), $N: ident, $T: ty) => { paste!{ pub fn $N(&self) -> &$T { self.rec_diff.$N.current() } pub fn [<set_ $N>](&mut self, v: $T) { *self.rec_diff.$N.get_mut() = v; } pub fn [<$N _mut>](&mut self) -> &mut $T { self.rec_diff.$N.get_mut() } pub fn [<with_ $N>](mut self, v: $T) -> Self { self.[<set_ $N>](v); self } pub fn [<set_ $N _with>]<F>(mut self, f: F) -> Self where F: FnOnce(&mut $T) { f(self.rec_diff.$N.get_mut()); self } } } } fields!(define_struct; ()); impl<'a> PhotoRecordDiff<'a> { fn write<'b, 'c>(&'b mut self, rec: &'c mut PhotoRecord) -> (&'c PhotoRecord, bool) { let mut changed = false; fields!(write; (self, rec, changed)); (rec, changed) } pub fn new(rec: &'a PhotoRecord) -> Self { fields!(new; (rec)) } fn is_dirty(&self) -> bool { self.file_hash.changed() || self.metadata.changed() } fn to_owned<'c: 'a>(&self) -> PhotoRecordDiff<'c> { fields!(to_owned; (self)) } } pub struct PhotoRecordPatch<'b, 'a: 'b> { commit_at_drop: bool, rec_diff: PhotoRecordDiff<'a>, rec: NonNull<PhotoRecord>, ptr: &'b TableRefMut<'a, PhotoTable>, } #[allow(dead_code)] impl<'b, 'a: 'b> PhotoRecordPatch<'b, 'a> { fields!(accessor; ()); pub(super) fn with_diff<'c: 'a>(mut self, diff: PhotoRecordDiff<'c>) -> Self { self.rec_diff = diff; self } pub fn mark_missing(&mut self) { self.rec_diff.is_missing = true } pub fn into_diff<'c>(mut self) -> PhotoRecordDiff<'c> { self.commit_at_drop = false; let ret = self.rec_diff.to_owned(); drop(self); ret } } impl<'b, 'a: 'b> Drop for PhotoRecordPatch<'b, 'a> { fn drop(&mut self) { if !self.commit_at_drop { return; } let ptr = unsafe { self.ptr.as_mut() }; if *self.selected() && self.rec_diff.is_missing { self.status_mut().handle_local_missing(); } else { let is_dirty = self.rec_diff.is_dirty(); self.status_mut().handle_dirty_mark(is_dirty); } { let status = &self.rec_diff.status; if status.changed() && *status.current() == Committed { self.set_commit_time(Some(Utc::now())) } } let (rec, changed) = self.rec_diff.write(unsafe { self.rec.as_mut() }); if changed { unsafe { self.ptr.as_mut() }.modified_flag().set(); } self.rec_diff.selected.run_if_changed(|_o, _n| { ptr.index.flip_selected(rec); }); self.rec_diff.status.run_if_changed(|o, n| { ptr.index.mutate_status(rec.pid, o.clone(), n.clone()); }); } } impl<'b, 'a: 'b> TableRecordPatch<'b, 'a> for PhotoRecordPatch<'b, 'a> { type Table = PhotoTable; fn new(rec: TableRecordMut<'a, Self::Table>, ptr: &'b TableRefMut<'a, Self::Table>) -> Self { let rec_ptr = unsafe { NonNull::new(s
random
[ { "content": "pub fn pt_access_mut<'a>() -> TableAccessMut<'a, PhotoTable> {\n\n PHOTO_TABLE.lock().unwrap().access_mut()\n\n}\n\n\n\n#[allow(dead_code)]\n\npub type PhotoTableAccess<'a> = TableAccess<'a, PhotoTable>;\n\npub type PhotoTableAccessMut<'a> = TableAccessMut<'a, PhotoTable>;\n\n\n\nimpl<'b, 'a: '...
Rust
examples/truck_loading.rs
cuviper/RsGenetic
dfbf22008072920f21f1f7c07c1bc7af689bc1f4
extern crate rand; extern crate rsgenetic; use rsgenetic::sim::*; use rsgenetic::sim::seq::Simulator; use rsgenetic::sim::select::*; use rsgenetic::pheno::*; use rand::Rng; type TruckIndex = usize; type PackageSize = i32; type Scheme = Vec<(TruckIndex, PackageSize)>; type SchemeFitness = i32; const NUM_TRUCKS: usize = 5; const CAPACITY: i32 = 10; const PACKAGES: &[i32] = &[3, 8, 2, 7, 6, 1, 3]; struct LoadingScheme { scheme: Scheme, } impl Phenotype<SchemeFitness> for LoadingScheme { fn fitness(&self) -> SchemeFitness { let mut ret: i32 = 0; let mut trucks: Vec<PackageSize> = vec![0; NUM_TRUCKS]; for load in self.scheme.clone() { trucks[load.0] += load.1; } for load in trucks { let space_left = CAPACITY - load; if space_left < 0 { return i32::min_value(); } if space_left == CAPACITY { ret += 1000; } else { ret -= space_left; } } ret } fn crossover(&self, other: &LoadingScheme) -> LoadingScheme { let mut rng = ::rand::thread_rng(); let crossover_indices = ( rng.gen::<usize>() % PACKAGES.len(), rng.gen::<usize>() % PACKAGES.len(), ); let mut crossed_over: Scheme = vec![(0, 0); PACKAGES.len()]; for i in 0..crossover_indices.0 { crossed_over[i] = self.scheme[i]; } for i in crossover_indices.0..crossover_indices.1 { crossed_over[i] = other.scheme[i]; } for i in crossover_indices.1..PACKAGES.len() { crossed_over[i] = self.scheme[i]; } LoadingScheme { scheme: crossed_over, } } fn mutate(&self) -> LoadingScheme { let mut rng = ::rand::thread_rng(); LoadingScheme { scheme: self.scheme .iter() .map(|&(_, size)| (rng.gen::<usize>() % NUM_TRUCKS, size)) .collect(), } } } impl Clone for LoadingScheme { fn clone(&self) -> LoadingScheme { LoadingScheme { scheme: self.scheme.clone(), } } } fn main() { let mut population: Vec<LoadingScheme> = Vec::with_capacity(300); let mut rng = ::rand::thread_rng(); for _ in 0..300 { let mut pheno: Scheme = Vec::with_capacity(PACKAGES.len()); for package in PACKAGES { let index = rng.gen::<usize>() % NUM_TRUCKS; pheno.push((index, *package)); } population.push(LoadingScheme { scheme: pheno }); } #[allow(deprecated)] let mut s = Simulator::builder(&mut population) .set_selector(Box::new(MaximizeSelector::new(10))) .set_max_iters(100) .build(); s.run(); let result = s.get().unwrap(); let time = s.time(); println!("Execution time: {} ns.", time.unwrap()); println!( "Result: {:?} | Fitness: {}.", result.scheme, result.fitness() ); let mut trucks: Vec<_> = vec![0; NUM_TRUCKS]; for &(index, size) in &result.scheme { trucks[index] += size; } println!("Load per truck: {:?}.", trucks); }
extern crate rand; extern crate rsgenetic; use rsgenetic::sim::*; use rsgenetic::sim::seq::Simulator; use rsgenetic::sim::select::*; use rsgenetic::pheno::*; use rand::Rng; type TruckIndex = usize; type PackageSize = i32; type Scheme = Vec<(TruckIndex, PackageSize)>; type SchemeFitness = i32; const NUM_TRUCKS: usize = 5; const CAPACITY: i32 = 10; const PACKAGES: &[i32] = &[3, 8, 2, 7, 6, 1, 3]; struct LoadingScheme { scheme: Scheme, } impl Phenotype<SchemeFitness> for LoadingScheme { fn fitness(&self) -> SchemeFitness { let mut ret: i32 = 0; let mut trucks: Vec<PackageSize> = vec![0; NUM_TRUCKS]; for load in self.scheme.clone() { trucks[load.0] += load.1; } for load in trucks { let space_left = CAPACITY - load; if space_left < 0 { return i32::min_value(); } if space_left == CAPACITY { ret += 1000; } else { ret -= space_left; } } ret } fn crossover(&self, other: &LoadingScheme) -> LoadingScheme { let mut rng = ::rand::thread_rng(); let crossover_indices = ( rng.gen::<usize>() % PACKAGES.len(), rng.gen::<usize>() % PACKAGES.len(), ); let mut crossed_over: Scheme = vec![(0, 0); PACKAGES.len()];
fn mutate(&self) -> LoadingScheme { let mut rng = ::rand::thread_rng(); LoadingScheme { scheme: self.scheme .iter() .map(|&(_, size)| (rng.gen::<usize>() % NUM_TRUCKS, size)) .collect(), } } } impl Clone for LoadingScheme { fn clone(&self) -> LoadingScheme { LoadingScheme { scheme: self.scheme.clone(), } } } fn main() { let mut population: Vec<LoadingScheme> = Vec::with_capacity(300); let mut rng = ::rand::thread_rng(); for _ in 0..300 { let mut pheno: Scheme = Vec::with_capacity(PACKAGES.len()); for package in PACKAGES { let index = rng.gen::<usize>() % NUM_TRUCKS; pheno.push((index, *package)); } population.push(LoadingScheme { scheme: pheno }); } #[allow(deprecated)] let mut s = Simulator::builder(&mut population) .set_selector(Box::new(MaximizeSelector::new(10))) .set_max_iters(100) .build(); s.run(); let result = s.get().unwrap(); let time = s.time(); println!("Execution time: {} ns.", time.unwrap()); println!( "Result: {:?} | Fitness: {}.", result.scheme, result.fitness() ); let mut trucks: Vec<_> = vec![0; NUM_TRUCKS]; for &(index, size) in &result.scheme { trucks[index] += size; } println!("Load per truck: {:?}.", trucks); }
for i in 0..crossover_indices.0 { crossed_over[i] = self.scheme[i]; } for i in crossover_indices.0..crossover_indices.1 { crossed_over[i] = other.scheme[i]; } for i in crossover_indices.1..PACKAGES.len() { crossed_over[i] = self.scheme[i]; } LoadingScheme { scheme: crossed_over, } }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let mut population = (-300..300).map(|i| MyData { x: f64::from(i) }).collect();\n\n let mut s = Simulator::builder(&mut population)\n\n .set_selector(Box::new(StochasticSelector::new(10)))\n\n .set_max_iters(50)\n\n .build();\n\n s.run();\n\n let re...
Rust
src/bin/cmd/wallet_tests.rs
icook/grin
5915580ab372dd85c0cc615d9df1c9aa6329f0f0
#[cfg(test)] mod wallet_tests { use chrono; use clap; use grin_util as util; use grin_wallet; use serde; use grin_wallet::test_framework::{self, LocalWalletClient, WalletProxy}; use clap::{App, ArgMatches}; use grin_util::Mutex; use std::sync::Arc; use std::thread; use std::time::Duration; use std::{env, fs}; use grin_config::GlobalWalletConfig; use grin_core::global; use grin_core::global::ChainTypes; use grin_keychain::ExtKeychain; use grin_wallet::{LMDBBackend, WalletBackend, WalletConfig, WalletInst, WalletSeed}; use super::super::wallet_args; fn clean_output_dir(test_dir: &str) { let _ = fs::remove_dir_all(test_dir); } fn setup(test_dir: &str) { util::init_test_logger(); clean_output_dir(test_dir); global::set_mining_mode(ChainTypes::AutomatedTesting); } pub fn config_command_wallet( dir_name: &str, wallet_name: &str, ) -> Result<(), grin_wallet::Error> { let mut current_dir; let mut default_config = GlobalWalletConfig::default(); current_dir = env::current_dir().unwrap_or_else(|e| { panic!("Error creating config file: {}", e); }); current_dir.push(dir_name); current_dir.push(wallet_name); let _ = fs::create_dir_all(current_dir.clone()); let mut config_file_name = current_dir.clone(); config_file_name.push("grin-wallet.toml"); if config_file_name.exists() { return Err(grin_wallet::ErrorKind::ArgumentError( "grin-wallet.toml already exists in the target directory. Please remove it first" .to_owned(), ))?; } default_config.update_paths(&current_dir); default_config .write_to_file(config_file_name.to_str().unwrap()) .unwrap_or_else(|e| { panic!("Error creating config file: {}", e); }); println!( "File {} configured and created", config_file_name.to_str().unwrap(), ); Ok(()) } pub fn initial_setup_wallet(dir_name: &str, wallet_name: &str) -> WalletConfig { let mut current_dir; current_dir = env::current_dir().unwrap_or_else(|e| { panic!("Error creating config file: {}", e); }); current_dir.push(dir_name); current_dir.push(wallet_name); let _ = fs::create_dir_all(current_dir.clone()); let mut config_file_name = current_dir.clone(); config_file_name.push("grin-wallet.toml"); GlobalWalletConfig::new(config_file_name.to_str().unwrap()) .unwrap() .members .unwrap() .wallet } fn get_wallet_subcommand<'a>( wallet_dir: &str, wallet_name: &str, args: ArgMatches<'a>, ) -> ArgMatches<'a> { match args.subcommand() { ("wallet", Some(wallet_args)) => { if let ("init", Some(init_args)) = wallet_args.subcommand() { if init_args.is_present("here") { let _ = config_command_wallet(wallet_dir, wallet_name); } } wallet_args.to_owned() } _ => ArgMatches::new(), } } fn instantiate_wallet( mut wallet_config: WalletConfig, node_client: LocalWalletClient, passphrase: &str, account: &str, ) -> Result<Arc<Mutex<WalletInst<LocalWalletClient, ExtKeychain>>>, grin_wallet::Error> { wallet_config.chain_type = None; let _ = WalletSeed::from_file(&wallet_config, passphrase)?; let mut db_wallet = LMDBBackend::new(wallet_config.clone(), passphrase, node_client)?; db_wallet.set_parent_key_id_by_name(account)?; info!("Using LMDB Backend for wallet"); Ok(Arc::new(Mutex::new(db_wallet))) } fn execute_command( app: &App, test_dir: &str, wallet_name: &str, client: &LocalWalletClient, arg_vec: Vec<&str>, ) -> Result<String, grin_wallet::Error> { let args = app.clone().get_matches_from(arg_vec); let args = get_wallet_subcommand(test_dir, wallet_name, args.clone()); let mut config = initial_setup_wallet(test_dir, wallet_name); config.chain_type = None; wallet_args::wallet_command(&args, config.clone(), client.clone()) } fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet::Error> { setup(test_dir); let mut wallet_proxy: WalletProxy<LocalWalletClient, ExtKeychain> = WalletProxy::new(test_dir); let chain = wallet_proxy.chain.clone(); let yml = load_yaml!("../grin.yml"); let app = App::from_yaml(yml); let arg_vec = vec!["grin", "wallet", "-p", "password", "init", "-h"]; let client1 = LocalWalletClient::new("wallet1", wallet_proxy.tx.clone()); execute_command(&app, test_dir, "wallet1", &client1, arg_vec.clone())?; assert!(execute_command(&app, test_dir, "wallet1", &client1, arg_vec.clone()).is_err()); let client1 = LocalWalletClient::new("wallet1", wallet_proxy.tx.clone()); let config1 = initial_setup_wallet(test_dir, "wallet1"); let wallet1 = instantiate_wallet(config1.clone(), client1.clone(), "password", "default")?; wallet_proxy.add_wallet("wallet1", client1.get_send_instance(), wallet1.clone()); let client2 = LocalWalletClient::new("wallet2", wallet_proxy.tx.clone()); execute_command(&app, test_dir, "wallet2", &client2, arg_vec.clone())?; let config2 = initial_setup_wallet(test_dir, "wallet2"); let wallet2 = instantiate_wallet(config2.clone(), client2.clone(), "password", "default")?; wallet_proxy.add_wallet("wallet2", client2.get_send_instance(), wallet2.clone()); thread::spawn(move || { if let Err(e) = wallet_proxy.run() { error!("Wallet Proxy error: {}", e); } }); let arg_vec = vec![ "grin", "wallet", "-p", "password", "account", "-c", "mining", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "account", "-c", "account_1", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "account", "-c", "account_1", ]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec.clone())?; assert!(execute_command(&app, test_dir, "wallet2", &client2, arg_vec).is_err()); let arg_vec = vec![ "grin", "wallet", "-p", "password", "account", "-c", "account_2", ]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; let arg_vec = vec!["grin", "wallet", "-p", "password", "account"]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; let arg_vec = vec!["grin", "wallet", "-p", "password", "account"]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; let wallet1 = instantiate_wallet(config1.clone(), client1.clone(), "password", "default")?; grin_wallet::controller::owner_single_use(wallet1.clone(), |api| { api.set_active_account("mining")?; Ok(()) })?; let mut bh = 10u64; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), bh as usize); let arg_vec = vec!["grin", "wallet", "-p", "password", "-a", "mining", "info"]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let file_name = format!("{}/tx1.part_tx", test_dir); let response_file_name = format!("{}/tx1.part_tx.response", test_dir); let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "mining", "send", "-m", "file", "-d", &file_name, "-g", "Love, Yeast", "10", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "account_1", "receive", "-i", &file_name, "-g", "Thanks, Yeast!", ]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec.clone())?; assert!(execute_command(&app, test_dir, "wallet2", &client2, arg_vec).is_err()); let arg_vec = vec![ "grin", "wallet", "-p", "password", "finalize", "-i", &response_file_name, ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; bh += 1; let wallet1 = instantiate_wallet(config1.clone(), client1.clone(), "password", "default")?; grin_wallet::controller::owner_single_use(wallet1.clone(), |api| { api.set_active_account("mining")?; let (refreshed, txs) = api.retrieve_txs(true, None, None)?; assert!(refreshed); assert_eq!(txs.len(), bh as usize); Ok(()) })?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), 10); bh += 10; let arg_vec = vec!["grin", "wallet", "-p", "password", "-a", "mining", "info"]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "account_1", "info", ]; execute_command(&app, test_dir, "wallet2", &client1, arg_vec)?; let wallet2 = instantiate_wallet(config2.clone(), client2.clone(), "password", "default")?; grin_wallet::controller::owner_single_use(wallet2.clone(), |api| { api.set_active_account("account_1")?; let (_, wallet1_info) = api.retrieve_summary_info(true, 1)?; assert_eq!(wallet1_info.last_confirmed_height, bh); assert_eq!(wallet1_info.amount_currently_spendable, 10_000_000_000); Ok(()) })?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "mining", "send", "-m", "file", "-d", &file_name, "-g", "Love, Yeast, Smallest", "-s", "smallest", "10", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "mining", "receive", "-i", &file_name, "-g", "Thanks, Yeast!", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec.clone())?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "finalize", "-i", &response_file_name, ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; bh += 1; let wallet1 = instantiate_wallet(config1.clone(), client1.clone(), "password", "default")?; grin_wallet::controller::owner_single_use(wallet1.clone(), |api| { api.set_active_account("mining")?; let (refreshed, txs) = api.retrieve_txs(true, None, None)?; assert!(refreshed); assert_eq!(txs.len(), bh as usize + 1); Ok(()) })?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "mining", "send", "-m", "self", "-d", "mining", "-g", "Self love", "-o", "75", "-s", "smallest", "10", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; bh += 1; let wallet1 = instantiate_wallet(config1.clone(), client1.clone(), "password", "default")?; grin_wallet::controller::owner_single_use(wallet1.clone(), |api| { api.set_active_account("mining")?; let (refreshed, txs) = api.retrieve_txs(true, None, None)?; assert!(refreshed); assert_eq!(txs.len(), bh as usize + 2); Ok(()) })?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "mining", "send", "-m", "file", "-d", &file_name, "-g", "Ain't sending", "10", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec!["grin", "wallet", "-p", "password", "check_repair"]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec!["grin", "wallet", "-p", "password", "-a", "mining", "txs"]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "mining", "outputs", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; thread::sleep(Duration::from_millis(200)); Ok(()) } #[test] fn wallet_command_line() { let test_dir = "target/test_output/command_line"; if let Err(e) = command_line_test_impl(test_dir) { panic!("Libwallet Error: {} - {}", e, e.backtrace().unwrap()); } } }
#[cfg(test)] mod wallet_tests { use chrono; use clap; use grin_util as util; use grin_wallet; use serde; use grin_wallet::test_framework::{self, LocalWalletClient, WalletProxy}; use clap::{App, ArgMatches}; use grin_util::Mutex; use std::sync::Arc; use std::thread; use std::time::Duration; use std::{env, fs}; use grin_config::GlobalWalletConfig; use grin_core::global; use grin_core::global::ChainTypes; use grin_keychain::ExtKeychain; use grin_wallet::{LMDBBackend, WalletBackend, WalletConfig, WalletInst, WalletSeed}; use super::super::wallet_args; fn clean_output_dir(test_dir: &str) { let _ = fs::remove_dir_all(test_dir); } fn setup(test_dir: &str) { util::init_test_logger(); clean_output_dir(test_dir); global::set_mining_mode(ChainTypes::AutomatedTesting); } pub fn config_command_wallet( dir_name: &str, wallet_name: &str, ) -> Result<(), grin_wallet::Error> { let mut current_dir; let mut default_config = GlobalWalletConfig::default(); current_dir = env::current_dir().unwrap_or_else(|e| { panic!("Error creating config file: {}", e); }); current_dir.push(dir_name); current_dir.push(wallet_name); let _ = fs::create_dir_all(current_dir.clone()); let mut config_file_name = current_dir.clone(); config_file_name.push("grin-wallet.toml"); if config_file_name.exists() { return Err(grin_wallet::ErrorKind::ArgumentError( "grin-wallet.toml already exists in the target directory. Please remove it first" .to_owned(), ))?; } default_config.update_paths(&current_dir); default_config .write_to_file(config_file_name.to_str().unwrap()) .unwrap_or_else(|e| { panic!("Error creating config file: {}", e); }); println!( "File {} configured and created", config_file_name.to_str().unwrap(), ); Ok(()) } pub fn initial_setup_wallet(dir_name: &str, wallet_name: &str) -> WalletConfig { let mut current_dir; current_dir = env::current_dir().unwrap_or_else(|e| { panic!("Error creating config file: {}", e); }); current_dir.push(dir_name); current_dir.push(wallet_name); let _ = fs::create_dir_all(current_dir.clone()); let mut config_file_name = current_dir.clone(); config_file_name.push("grin-wallet.toml"); GlobalWalletConfig::new(config_file_name.to_str().unwrap()) .unwrap() .members .unwrap() .wallet } fn get_wallet_subcommand<'a>( wallet_dir: &str, wallet_name: &str, args: ArgMatches<'a>, ) -> ArgMatches<'a> { match args.subcommand() { ("wallet", Some(wallet_args)) => { if let ("init", Some(init_args)) = wallet_args.subcommand() { if init_args.is_present("here") { let _ = config_command_wallet(wallet_dir, wallet_name); } } wallet_args.to_owned() } _ => ArgMatches::new(), } } fn instantiate_wallet( mut wallet_config: WalletConfig, node_client: LocalWalletClient, passphrase: &str, account: &str, ) -> Result<Arc<Mutex<WalletInst<LocalWalletClient, ExtKeychain>>>, grin_wallet::Error> { wallet_config.chain_type = None; let _ = WalletSeed::from_file(&wallet_config, passphrase)?; let mut db_wallet = LMDBBackend::new(wallet_config.clone(), passphrase, node_client)?; db_wallet.set_parent_key_id_by_name(account)?; info!("Using LMDB Backend for wallet"); Ok(Arc::new(Mutex::new(db_wallet))) } fn execute_command( app: &App, test_dir: &str, wallet_name: &str, client: &LocalWalletClient, arg_vec: Vec<&str>, ) -> Result<String, grin_wallet::Error> { let args = app.clone().get_matches_from(arg_vec); let args = get_wallet_subcommand(test_dir, wallet_name, args.clone()); let mut config = initial_setup_wallet(test_dir, wallet_name); config.chain_type = None; wallet_args::wallet_command(&args, config.clone(), client.clone()) } fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet::Error> { setup(test_dir); let mut wallet_proxy: WalletProxy<LocalWalletClient, ExtKeychain> = WalletProxy::new(test_dir); let chain = wallet_proxy.chain.clone(); let yml = load_yaml!("../grin.yml"); let app = App::from_yaml(yml); let arg_vec = vec!["grin", "wallet", "-p", "password", "init", "-h"]; let client1 = LocalWalletClient::new("wallet1", wallet_proxy.tx.clone()); execute_command(&app, test_dir, "wallet1", &client1, arg_vec.clone())?; assert!(execute_command(&app, test_dir, "wallet1", &client1, arg_vec.clone()).is_err()); let client1 = LocalWalletClient::new("wallet1", wallet_proxy.tx.clone()); let config1 = initial_setup_wallet(test_dir, "wallet1"); let wallet1 = instantiate_wallet(config1.clone(), client1.clone(), "password", "default")?; wallet_proxy.add_wallet("wallet1", client1.get_send_instance(), wallet1.clone()); let client2 = LocalWalletClient::new("wallet2", wallet_proxy.tx.clone()); execute_command(&app, test_dir, "wallet2", &client2, arg_vec.clone())?; let config2 = initial_setup_wallet(test_dir, "wallet2"); let wallet2 = instantiate_wallet(config2.clone(), client2.clone(), "password", "default")?; wallet_proxy.add_wallet("wallet2", client2.get_send_instance(), wallet2.clone()); thread::spawn(move || { if let Err(e) = wallet_proxy.run() { error!("Wallet Proxy error: {}", e); } }); let arg_vec = vec![ "grin", "wallet", "-p", "password", "account", "-c", "mining", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "account", "-c", "account_1", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "account", "-c", "account_1", ]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec.clone())?; assert!(execute_command(&app, test_dir, "wallet2", &client2, arg_vec).is_err()); let arg_vec = vec![ "grin", "wallet", "-p", "password", "account", "-c", "account_2", ]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; let arg_vec = vec!["grin", "wallet", "-p", "password", "account"]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; let arg_vec = vec!["grin", "wallet", "-p", "password", "account"]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; let wallet1 = instantiate_wallet(config1.clone(), client1.clone(), "password", "default")?; grin_wallet::controller::owner_single_use(wallet1.clone(), |api| { api.set_active_account("mining")?; Ok(()) })?; let mut bh = 10u64; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), bh as usize); let arg_vec = vec!["grin", "wallet", "-p", "password", "-a", "mining", "info"]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let file_name = format!("{}/tx1.part_tx", test_dir); let response_file_name = format!("{}/tx1.part_tx.response", test_dir); let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "mining", "send", "-m", "file", "-d", &file_name, "-g", "Love, Yeast", "10", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "account_1", "receive", "-i", &file_name, "-g", "Thanks, Yeast!", ]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec.clone())?; assert!(execute_command(&app, test_dir, "wallet2", &client2, arg_vec).is_err()); let arg_vec = vec![ "grin", "wallet", "-p", "password", "finalize", "-i", &response_file_name, ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; bh += 1; let wallet1 = instantiate_wallet(config1.clone(), client1.clone(), "password", "default")?; grin_wallet::controller::owner_single_use(wallet1.clone(), |api| { api.set_active_account("mining")?; let (refreshed, txs) = api.retrieve_txs(true, None, None)?; assert!(refreshed); assert_eq!(txs.len(), bh as usize); Ok(()) })?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), 10); bh += 10; let arg_vec = vec!["grin", "wallet", "-p", "password", "-a", "mining", "info"]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "account_1", "info", ]; execute_command(&app, test_dir, "wallet2", &client1, arg_vec)?; let wallet2 = instantiate_wallet(config2.clone(), client2.clone(), "password", "default")?; grin_wallet::controller::owner_single_use(wallet2.clone(), |api| { api.set_active_account("account_1")?; let (_, wallet1_info) = api.retrieve_summary_info(true, 1)?; assert_eq!(wallet1_info.last_confirmed_height, bh); assert_eq!(wallet1_info.amount_currently_spendable, 10_000_000_000); Ok(()) })?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "mini
e_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec!["grin", "wallet", "-p", "password", "check_repair"]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec!["grin", "wallet", "-p", "password", "-a", "mining", "txs"]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "mining", "outputs", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; thread::sleep(Duration::from_millis(200)); Ok(()) } #[test] fn wallet_command_line() { let test_dir = "target/test_output/command_line"; if let Err(e) = command_line_test_impl(test_dir) { panic!("Libwallet Error: {} - {}", e, e.backtrace().unwrap()); } } }
ng", "send", "-m", "file", "-d", &file_name, "-g", "Love, Yeast, Smallest", "-s", "smallest", "10", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "mining", "receive", "-i", &file_name, "-g", "Thanks, Yeast!", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec.clone())?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "finalize", "-i", &response_file_name, ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; bh += 1; let wallet1 = instantiate_wallet(config1.clone(), client1.clone(), "password", "default")?; grin_wallet::controller::owner_single_use(wallet1.clone(), |api| { api.set_active_account("mining")?; let (refreshed, txs) = api.retrieve_txs(true, None, None)?; assert!(refreshed); assert_eq!(txs.len(), bh as usize + 1); Ok(()) })?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "mining", "send", "-m", "self", "-d", "mining", "-g", "Self love", "-o", "75", "-s", "smallest", "10", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; bh += 1; let wallet1 = instantiate_wallet(config1.clone(), client1.clone(), "password", "default")?; grin_wallet::controller::owner_single_use(wallet1.clone(), |api| { api.set_active_account("mining")?; let (refreshed, txs) = api.retrieve_txs(true, None, None)?; assert!(refreshed); assert_eq!(txs.len(), bh as usize + 2); Ok(()) })?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "mining", "send", "-m", "file", "-d", &file_name, "-g", "Ain't sending", "10", ]; execut
random
[ { "content": "/// Returns a list of account to BIP32 path mappings\n\npub fn accounts<T: ?Sized, C, K>(wallet: &mut T) -> Result<Vec<AcctPathMapping>, Error>\n\nwhere\n\n\tT: WalletBackend<C, K>,\n\n\tC: NodeClient,\n\n\tK: Keychain,\n\n{\n\n\tOk(wallet.acct_path_iter().collect())\n\n}\n\n\n", "file_path": ...
Rust
diesel/src/serialize.rs
unvalley/diesel
fd723880db6887a859ffa691890fe964de7dd3f8
use std::error::Error; use std::fmt; use std::io::{self, Write}; use std::result; use crate::backend::{Backend, HasBindCollector}; use crate::query_builder::bind_collector::RawBytesBindCollector; use crate::query_builder::BindCollector; #[cfg(feature = "postgres_backend")] pub use crate::pg::serialize::*; pub type Result = result::Result<IsNull, Box<dyn Error + Send + Sync>>; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum IsNull { Yes, No, } pub struct Output<'a, 'b, DB> where DB: Backend, DB::MetadataLookup: 'a, { out: <crate::backend::BindCollector<'a, DB> as BindCollector<'a, DB>>::Buffer, metadata_lookup: Option<&'b mut DB::MetadataLookup>, } impl<'a, 'b, DB: Backend> Output<'a, 'b, DB> { pub fn new( out: <crate::backend::BindCollector<'a, DB> as BindCollector<'a, DB>>::Buffer, metadata_lookup: &'b mut DB::MetadataLookup, ) -> Self { Output { out, metadata_lookup: Some(metadata_lookup), } } pub fn into_inner( self, ) -> <crate::backend::BindCollector<'a, DB> as BindCollector<'a, DB>>::Buffer { self.out } pub fn metadata_lookup(&mut self) -> &mut DB::MetadataLookup { *self.metadata_lookup.as_mut().expect("Lookup is there") } pub fn set_value<V>(&mut self, value: V) where V: Into<<crate::backend::BindCollector<'a, DB> as BindCollector<'a, DB>>::Buffer>, { self.out = value.into(); } } #[cfg(test)] impl<'a, DB: Backend> Output<'a, 'static, DB> { pub fn test( buffer: <crate::backend::BindCollector<'a, DB> as BindCollector<'a, DB>>::Buffer, ) -> Self { Self { out: buffer, metadata_lookup: None, } } } impl<'a, 'b, DB: Backend<BindCollector = RawBytesBindCollector<DB>>> Write for Output<'a, 'b, DB> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.out.write(buf) } fn flush(&mut self) -> io::Result<()> { self.out.flush() } fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { self.out.write_all(buf) } fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { self.out.write_fmt(fmt) } } impl<'a, 'b, DB: Backend<BindCollector = RawBytesBindCollector<DB>>> Output<'a, 'b, DB> { pub fn reborrow<'c>(&'c mut self) -> Output<'c, 'c, DB> where 'a: 'c, { Output { out: RawBytesBindCollector::<DB>::reborrow_buffer(self.out), metadata_lookup: match &mut self.metadata_lookup { None => None, Some(m) => Some(&mut **m), }, } } } impl<'a, 'b, DB> fmt::Debug for Output<'a, 'b, DB> where <<DB as HasBindCollector<'a>>::BindCollector as BindCollector<'a, DB>>::Buffer: fmt::Debug, DB: Backend, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.out.fmt(f) } } pub trait ToSql<A, DB: Backend>: fmt::Debug { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> Result; } impl<'a, A, T, DB> ToSql<A, DB> for &'a T where DB: Backend, T: ToSql<A, DB> + ?Sized, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> Result { (*self).to_sql(out) } }
use std::error::Error; use std::fmt; use std::io::{self, Write}; use std::result; use crate::backend::{Backend, HasBindCollector}; use crate::query_builder::bind_collector::RawBytesBindCollector; use crate::query_builder::BindCollector; #[cfg(feature = "postgres_backend")] pub use crate::pg::serialize::*; pub type Result = result::Result<IsNull, Box<dyn Error + Send + Sync>>; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum IsNull { Yes, No, } pub struct Output<'a, 'b, DB> where DB: Backend, DB::MetadataLookup: 'a, { out: <crate::backend::BindCollector<'a, DB> as BindCollector<'a, DB>>::Buffer, metadata_lookup: Option<&'b mut DB::MetadataLookup>, } impl<'a, 'b, DB: Backend> Output<'a, 'b, DB> {
pub fn into_inner( self, ) -> <crate::backend::BindCollector<'a, DB> as BindCollector<'a, DB>>::Buffer { self.out } pub fn metadata_lookup(&mut self) -> &mut DB::MetadataLookup { *self.metadata_lookup.as_mut().expect("Lookup is there") } pub fn set_value<V>(&mut self, value: V) where V: Into<<crate::backend::BindCollector<'a, DB> as BindCollector<'a, DB>>::Buffer>, { self.out = value.into(); } } #[cfg(test)] impl<'a, DB: Backend> Output<'a, 'static, DB> { pub fn test( buffer: <crate::backend::BindCollector<'a, DB> as BindCollector<'a, DB>>::Buffer, ) -> Self { Self { out: buffer, metadata_lookup: None, } } } impl<'a, 'b, DB: Backend<BindCollector = RawBytesBindCollector<DB>>> Write for Output<'a, 'b, DB> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.out.write(buf) } fn flush(&mut self) -> io::Result<()> { self.out.flush() } fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { self.out.write_all(buf) } fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { self.out.write_fmt(fmt) } } impl<'a, 'b, DB: Backend<BindCollector = RawBytesBindCollector<DB>>> Output<'a, 'b, DB> { pub fn reborrow<'c>(&'c mut self) -> Output<'c, 'c, DB> where 'a: 'c, { Output { out: RawBytesBindCollector::<DB>::reborrow_buffer(self.out), metadata_lookup: match &mut self.metadata_lookup { None => None, Some(m) => Some(&mut **m), }, } } } impl<'a, 'b, DB> fmt::Debug for Output<'a, 'b, DB> where <<DB as HasBindCollector<'a>>::BindCollector as BindCollector<'a, DB>>::Buffer: fmt::Debug, DB: Backend, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.out.fmt(f) } } pub trait ToSql<A, DB: Backend>: fmt::Debug { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> Result; } impl<'a, A, T, DB> ToSql<A, DB> for &'a T where DB: Backend, T: ToSql<A, DB> + ?Sized, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> Result { (*self).to_sql(out) } }
pub fn new( out: <crate::backend::BindCollector<'a, DB> as BindCollector<'a, DB>>::Buffer, metadata_lookup: &'b mut DB::MetadataLookup, ) -> Self { Output { out, metadata_lookup: Some(metadata_lookup), } }
function_block-full_function
[]
Rust
components/front_matter/src/lib.rs
zoosky/zola
b359cca4fe46a7abc8ce10620561d48d685b86ef
use lazy_static::lazy_static; use serde_derive::{Deserialize, Serialize}; use errors::{bail, Error, Result}; use regex::Regex; use std::path::Path; mod page; mod section; pub use page::PageFrontMatter; pub use section::SectionFrontMatter; lazy_static! { static ref PAGE_RE: Regex = Regex::new(r"^[[:space:]]*\+\+\+\r?\n((?s).*?(?-s))\+\+\+\r?\n?((?s).*(?-s))$").unwrap(); } #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum SortBy { Date, Weight, None, } #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum InsertAnchor { Left, Right, None, } fn split_content(file_path: &Path, content: &str) -> Result<(String, String)> { if !PAGE_RE.is_match(content) { bail!( "Couldn't find front matter in `{}`. Did you forget to add `+++`?", file_path.to_string_lossy() ); } let caps = PAGE_RE.captures(content).unwrap(); Ok((caps[1].to_string(), caps[2].to_string())) } pub fn split_section_content( file_path: &Path, content: &str, ) -> Result<(SectionFrontMatter, String)> { let (front_matter, content) = split_content(file_path, content)?; let meta = SectionFrontMatter::parse(&front_matter).map_err(|e| { Error::chain( format!("Error when parsing front matter of section `{}`", file_path.to_string_lossy()), e, ) })?; Ok((meta, content)) } pub fn split_page_content(file_path: &Path, content: &str) -> Result<(PageFrontMatter, String)> { let (front_matter, content) = split_content(file_path, content)?; let meta = PageFrontMatter::parse(&front_matter).map_err(|e| { Error::chain( format!("Error when parsing front matter of page `{}`", file_path.to_string_lossy()), e, ) })?; Ok((meta, content)) } #[cfg(test)] mod tests { use std::path::Path; use super::{split_page_content, split_section_content}; #[test] fn can_split_page_content_valid() { let content = r#" +++ title = "Title" description = "hey there" date = 2002-10-12 +++ Hello "#; let (front_matter, content) = split_page_content(Path::new(""), content).unwrap(); assert_eq!(content, "Hello\n"); assert_eq!(front_matter.title.unwrap(), "Title"); } #[test] fn can_split_section_content_valid() { let content = r#" +++ paginate_by = 10 +++ Hello "#; let (front_matter, content) = split_section_content(Path::new(""), content).unwrap(); assert_eq!(content, "Hello\n"); assert!(front_matter.is_paginated()); } #[test] fn can_split_content_with_only_frontmatter_valid() { let content = r#" +++ title = "Title" description = "hey there" date = 2002-10-12 +++"#; let (front_matter, content) = split_page_content(Path::new(""), content).unwrap(); assert_eq!(content, ""); assert_eq!(front_matter.title.unwrap(), "Title"); } #[test] fn can_split_content_lazily() { let content = r#" +++ title = "Title" description = "hey there" date = 2002-10-02T15:00:00Z +++ +++"#; let (front_matter, content) = split_page_content(Path::new(""), content).unwrap(); assert_eq!(content, "+++"); assert_eq!(front_matter.title.unwrap(), "Title"); } #[test] fn errors_if_cannot_locate_frontmatter() { let content = r#" +++ title = "Title" description = "hey there" date = 2002-10-12"#; let res = split_page_content(Path::new(""), content); assert!(res.is_err()); } }
use lazy_static::lazy_static; use serde_derive::{Deserialize, Serialize}; use errors::{bail, Error, Result}; use regex::Regex; use std::path::Path; mod page; mod section; pub use page::PageFrontMatter; pub use section::SectionFrontMatter; lazy_static! { static ref PAGE_RE: Regex = Regex::new(r"^[[:space:]]*\+\+\+\r?\n((?s).*?(?-s))\+\+\+\r?\n?((?s).*(?-s))$").unwrap(); } #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum SortBy { Date, Weight, None, } #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum InsertAnchor { Left, Right, None, } fn split_content(file_path: &Path, content: &str) -> Result<(String, String)> { if !PAGE_RE.is_match(content) { bail!( "Couldn't find front matter in `{}`. Did you forget to add `+++`?", file_path.to_string_lossy() ); } let caps = PAGE_RE.captures(content).unwrap(); Ok((caps[1].to_string(), caps[2].to_string())) } pub fn split_section_content( file_path: &Path, content: &str, ) -> Result<(SectionFrontMatter, String)> { let (front_matter, content) = split_content(file_path, content)?; let meta = SectionFrontMatter::parse(&front_matter).map_err(|e| { Error::chain( format!("Error when parsing front matter of section `{}`", file_path.to_string_lossy()), e, ) })?; Ok((meta, content)) } pub fn split_page_content(file_path: &Path, content: &str) -> Result<(PageFrontMatter, String)> { let (front_matter, content) = split_content(file_path, content)?; let meta = PageFrontMatter::parse(&front_matter).map_err(|e| { Error::chain( format!("Error when parsing front matter of page `{}`", file_path.to_string_lossy()), e, ) })?;
frontmatter() { let content = r#" +++ title = "Title" description = "hey there" date = 2002-10-12"#; let res = split_page_content(Path::new(""), content); assert!(res.is_err()); } }
Ok((meta, content)) } #[cfg(test)] mod tests { use std::path::Path; use super::{split_page_content, split_section_content}; #[test] fn can_split_page_content_valid() { let content = r#" +++ title = "Title" description = "hey there" date = 2002-10-12 +++ Hello "#; let (front_matter, content) = split_page_content(Path::new(""), content).unwrap(); assert_eq!(content, "Hello\n"); assert_eq!(front_matter.title.unwrap(), "Title"); } #[test] fn can_split_section_content_valid() { let content = r#" +++ paginate_by = 10 +++ Hello "#; let (front_matter, content) = split_section_content(Path::new(""), content).unwrap(); assert_eq!(content, "Hello\n"); assert!(front_matter.is_paginated()); } #[test] fn can_split_content_with_only_frontmatter_valid() { let content = r#" +++ title = "Title" description = "hey there" date = 2002-10-12 +++"#; let (front_matter, content) = split_page_content(Path::new(""), content).unwrap(); assert_eq!(content, ""); assert_eq!(front_matter.title.unwrap(), "Title"); } #[test] fn can_split_content_lazily() { let content = r#" +++ title = "Title" description = "hey there" date = 2002-10-02T15:00:00Z +++ +++"#; let (front_matter, content) = split_page_content(Path::new(""), content).unwrap(); assert_eq!(content, "+++"); assert_eq!(front_matter.title.unwrap(), "Title"); } #[test] fn errors_if_cannot_locate_
random
[ { "content": "/// Return the content of a file, with error handling added.\n\n/// The default error message is overwritten by the message given.\n\n/// That means it is allocation 2 strings, oh well\n\npub fn read_file_with_error(path: &Path, message: &str) -> Result<String> {\n\n let res = read_file(&path);...
Rust
near-sdk/src/collections/lookup_set.rs
nearprotocol/near-sdk-rs
8a2b2e19b27a764abf43df05bd0e530c3ad91d6c
use std::marker::PhantomData; use borsh::{BorshDeserialize, BorshSerialize}; use crate::collections::append_slice; use crate::{env, IntoStorageKey}; const ERR_ELEMENT_SERIALIZATION: &str = "Cannot serialize element with Borsh"; #[derive(BorshSerialize, BorshDeserialize)] pub struct LookupSet<T> { element_prefix: Vec<u8>, #[borsh_skip] el: PhantomData<T>, } impl<T> LookupSet<T> { pub fn new<S>(element_prefix: S) -> Self where S: IntoStorageKey, { Self { element_prefix: element_prefix.into_storage_key(), el: PhantomData } } fn raw_element_to_storage_key(&self, element_raw: &[u8]) -> Vec<u8> { append_slice(&self.element_prefix, element_raw) } fn contains_raw(&self, element_raw: &[u8]) -> bool { let storage_key = self.raw_element_to_storage_key(element_raw); env::storage_has_key(&storage_key) } pub fn insert_raw(&mut self, element_raw: &[u8]) -> bool { let storage_key = self.raw_element_to_storage_key(element_raw); !env::storage_write(&storage_key, b"") } pub fn remove_raw(&mut self, element_raw: &[u8]) -> bool { let storage_key = self.raw_element_to_storage_key(element_raw); env::storage_remove(&storage_key) } } impl<T> LookupSet<T> where T: BorshSerialize, { fn serialize_element(element: &T) -> Vec<u8> { match element.try_to_vec() { Ok(x) => x, Err(_) => env::panic_str(ERR_ELEMENT_SERIALIZATION), } } pub fn contains(&self, element: &T) -> bool { self.contains_raw(&Self::serialize_element(element)) } pub fn remove(&mut self, element: &T) -> bool { self.remove_raw(&Self::serialize_element(element)) } pub fn insert(&mut self, element: &T) -> bool { self.insert_raw(&Self::serialize_element(element)) } pub fn extend<IT: IntoIterator<Item = T>>(&mut self, iter: IT) { for el in iter { self.insert(&el); } } } impl<T> std::fmt::Debug for LookupSet<T> where T: std::fmt::Debug + BorshSerialize, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("LookupSet").field("element_prefix", &self.element_prefix).finish() } } #[cfg(not(target_arch = "wasm32"))] #[cfg(test)] mod tests { use crate::collections::LookupSet; use rand::seq::SliceRandom; use rand::{Rng, SeedableRng}; use std::collections::HashSet; #[test] pub fn test_insert_one() { let mut map = LookupSet::new(b"m"); assert!(map.insert(&1)); assert!(!map.insert(&1)); } #[test] pub fn test_insert() { let mut set = LookupSet::new(b"s"); let mut rng = rand_xorshift::XorShiftRng::seed_from_u64(0); for _ in 0..500 { let key = rng.gen::<u64>(); set.insert(&key); } } #[test] pub fn test_insert_remove() { let mut set = LookupSet::new(b"s"); let mut rng = rand_xorshift::XorShiftRng::seed_from_u64(1); let mut keys = vec![]; for _ in 0..100 { let key = rng.gen::<u64>(); keys.push(key); set.insert(&key); } keys.shuffle(&mut rng); for key in keys { assert!(set.remove(&key)); } } #[test] pub fn test_remove_last_reinsert() { let mut set = LookupSet::new(b"s"); let key1 = 1u64; set.insert(&key1); let key2 = 2u64; set.insert(&key2); let actual = set.remove(&key2); assert!(actual); let actual_reinsert = set.insert(&key2); assert!(actual_reinsert); } #[test] pub fn test_insert_override_remove() { let mut set = LookupSet::new(b"s"); let mut rng = rand_xorshift::XorShiftRng::seed_from_u64(2); let mut keys = vec![]; for _ in 0..100 { let key = rng.gen::<u64>(); keys.push(key); set.insert(&key); } keys.shuffle(&mut rng); for key in &keys { assert!(!set.insert(key)); } keys.shuffle(&mut rng); for key in keys { assert!(set.remove(&key)); } } #[test] pub fn test_contains_non_existent() { let mut set = LookupSet::new(b"s"); let mut rng = rand_xorshift::XorShiftRng::seed_from_u64(3); let mut set_tmp = HashSet::new(); for _ in 0..500 { let key = rng.gen::<u64>() % 20_000; set_tmp.insert(key); set.insert(&key); } for _ in 0..500 { let key = rng.gen::<u64>() % 20_000; assert_eq!(set.contains(&key), set_tmp.contains(&key)); } } #[test] pub fn test_extend() { let mut set = LookupSet::new(b"s"); let mut rng = rand_xorshift::XorShiftRng::seed_from_u64(4); let mut keys = HashSet::new(); for _ in 0..100 { let key = rng.gen::<u64>(); keys.insert(key); set.insert(&key); } for _ in 0..10 { let mut tmp = vec![]; for _ in 0..=(rng.gen::<u64>() % 20 + 1) { let key = rng.gen::<u64>(); tmp.push(key); } keys.extend(tmp.iter().cloned()); set.extend(tmp.iter().cloned()); } for key in keys { assert!(set.contains(&key)); } } #[test] fn test_debug() { let set: LookupSet<u64> = LookupSet::new(b"m"); assert_eq!( format!("{:?}", set), format!("LookupSet {{ element_prefix: {:?} }}", set.element_prefix) ); } }
use std::marker::PhantomData; use borsh::{BorshDeserialize, BorshSerialize}; use crate::collections::append_slice; use crate::{env, IntoStorageKey}; const ERR_ELEMENT_SERIALIZATION: &str = "Cannot serialize element with Borsh"; #[derive(BorshSerialize, BorshDeserialize)] pub struct LookupSet<T> { element_prefix: Vec<u8>, #[borsh_skip] el: PhantomData<T>, } impl<T> LookupSet<T> { pub fn new<S>(element_prefix: S) -> Self where S: IntoStorageKey, { Self { element_prefix: element_prefix.into_storage_key(), el: PhantomData } } fn raw_element_to_storage_key(&self, element_raw: &[u8]) -> Vec<u8> { append_slice(&self.element_prefix, element_raw) } fn contains_raw(&self, element_raw: &[u8]) -> bool { let storage_key = self.raw_element_to_storage_key(element_raw); env::storage_has_key(&storage_key) } pub fn insert_raw(&mut self, element_raw: &[u8]) -> bool { let storage_key = self.raw_element_to_storage_key(element_raw); !env::storage_write(&storage_key, b"") } pub fn remove_raw(&mut self, element_raw: &[u8]) -> bool { let storage_key = self.raw_element_to_storage_key(element_raw); env::storage_remove(&storage_key) } } impl<T> LookupSet<T> where T: BorshSerialize, { fn serialize_element(element: &T) -> Vec<u8> { match element.try_to_vec() { Ok(x) => x, Err(_) => env::panic_str(ERR_ELEMENT_SERIALIZATION), } } pub fn contains(&self, element: &T) -> bool { self.contains_raw(&Self::serialize_element(element)) } pub fn remove(&mut self, element: &T) -> bool { self.remove_raw(&Self::serialize_element(element)) } pub fn insert(&mut self, element: &T) -> bool { self.insert_raw(&Self::serialize_element(element)) } pub fn extend<IT: IntoIterator<Item = T>>(&mut self, iter: IT) { for el in iter { self.insert(&el); } } }
> std::fmt::Result { f.debug_struct("LookupSet").field("element_prefix", &self.element_prefix).finish() } } #[cfg(not(target_arch = "wasm32"))] #[cfg(test)] mod tests { use crate::collections::LookupSet; use rand::seq::SliceRandom; use rand::{Rng, SeedableRng}; use std::collections::HashSet; #[test] pub fn test_insert_one() { let mut map = LookupSet::new(b"m"); assert!(map.insert(&1)); assert!(!map.insert(&1)); } #[test] pub fn test_insert() { let mut set = LookupSet::new(b"s"); let mut rng = rand_xorshift::XorShiftRng::seed_from_u64(0); for _ in 0..500 { let key = rng.gen::<u64>(); set.insert(&key); } } #[test] pub fn test_insert_remove() { let mut set = LookupSet::new(b"s"); let mut rng = rand_xorshift::XorShiftRng::seed_from_u64(1); let mut keys = vec![]; for _ in 0..100 { let key = rng.gen::<u64>(); keys.push(key); set.insert(&key); } keys.shuffle(&mut rng); for key in keys { assert!(set.remove(&key)); } } #[test] pub fn test_remove_last_reinsert() { let mut set = LookupSet::new(b"s"); let key1 = 1u64; set.insert(&key1); let key2 = 2u64; set.insert(&key2); let actual = set.remove(&key2); assert!(actual); let actual_reinsert = set.insert(&key2); assert!(actual_reinsert); } #[test] pub fn test_insert_override_remove() { let mut set = LookupSet::new(b"s"); let mut rng = rand_xorshift::XorShiftRng::seed_from_u64(2); let mut keys = vec![]; for _ in 0..100 { let key = rng.gen::<u64>(); keys.push(key); set.insert(&key); } keys.shuffle(&mut rng); for key in &keys { assert!(!set.insert(key)); } keys.shuffle(&mut rng); for key in keys { assert!(set.remove(&key)); } } #[test] pub fn test_contains_non_existent() { let mut set = LookupSet::new(b"s"); let mut rng = rand_xorshift::XorShiftRng::seed_from_u64(3); let mut set_tmp = HashSet::new(); for _ in 0..500 { let key = rng.gen::<u64>() % 20_000; set_tmp.insert(key); set.insert(&key); } for _ in 0..500 { let key = rng.gen::<u64>() % 20_000; assert_eq!(set.contains(&key), set_tmp.contains(&key)); } } #[test] pub fn test_extend() { let mut set = LookupSet::new(b"s"); let mut rng = rand_xorshift::XorShiftRng::seed_from_u64(4); let mut keys = HashSet::new(); for _ in 0..100 { let key = rng.gen::<u64>(); keys.insert(key); set.insert(&key); } for _ in 0..10 { let mut tmp = vec![]; for _ in 0..=(rng.gen::<u64>() % 20 + 1) { let key = rng.gen::<u64>(); tmp.push(key); } keys.extend(tmp.iter().cloned()); set.extend(tmp.iter().cloned()); } for key in keys { assert!(set.contains(&key)); } } #[test] fn test_debug() { let set: LookupSet<u64> = LookupSet::new(b"m"); assert_eq!( format!("{:?}", set), format!("LookupSet {{ element_prefix: {:?} }}", set.element_prefix) ); } }
impl<T> std::fmt::Debug for LookupSet<T> where T: std::fmt::Debug + BorshSerialize, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -
random
[ { "content": "// ###############\n\n// # Storage API #\n\n// ###############\n\n/// Writes key-value into storage.\n\n/// If another key-value existed in the storage with the same key it returns `true`, otherwise `false`.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use near_sdk::env::{storage_write, stora...
Rust
src/encrypted_stream.rs
GWBasic/bounce
2d8a86b8c33bf408ad5d5b20c440233c0746b13a
/* use async_std::io; use async_std::io::{Read, Result, Write}; use async_std::task::{Context, Poll}; use std::marker::Unpin; use std::pin::Pin; use rand_core::{CryptoRng, RngCore}; pub struct EncryptedStream<TStream, TRng> where TStream: Read + Write, TRng: CryptoRng + RngCore { wrapped_stream: TStream, write_xor: Xor<TRng>, read_xor: Xor<TRng>, } pub struct Xor<TRng> { rng: TRng, xor: [u8; 1024], ctr: usize, } impl<TStream, TRng> Unpin for EncryptedStream<TStream, TRng> where TStream: Read + Write, TRng: CryptoRng + RngCore {} impl<TStream, TRng> EncryptedStream<TStream, TRng> where TStream: Read + Write, TRng: CryptoRng + RngCore { pub fn new(wrapped_stream: TStream, write_rng: TRng, read_rng: TRng) -> EncryptedStream<TStream, TRng> { EncryptedStream { wrapped_stream, write_xor: Xor::new(write_rng), read_xor: Xor::new(read_rng), } } } impl<TRng> Xor<TRng> where TRng: CryptoRng + RngCore { fn new(rng: TRng) -> Xor<TRng> { Xor { rng, xor: [0u8; 1024], ctr: usize::MAX, } } fn next_byte(&mut self) -> u8 { if self.ctr >= self.xor.len() { self.rng.fill_bytes(&mut self.xor[..]); self.ctr = 0; } let b = self.xor[self.ctr]; self.ctr = self.ctr + 1; b } } impl<TStream: Read + Unpin, TRng> Read for EncryptedStream<TStream, TRng> where TStream: Read + Write, TRng: CryptoRng + RngCore { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { let result = Pin::new(&mut self.wrapped_stream).poll_read(cx, buf); match result { Poll::Ready(result) => match result { Result::Ok(size) => { for ctr in 0..size { buf[ctr] = buf[ctr] ^ self.read_xor.next_byte(); } Poll::Ready(Result::Ok(size)) }, Result::Err(err) => Poll::Ready(Result::Err(err)) }, Poll::Pending => Poll::Pending } } } impl<TStream: Write + Unpin, TRng> Write for EncryptedStream<TStream, TRng> where TStream: Read + Write, TRng: CryptoRng + RngCore { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { let mut encrypted = vec![0; buf.len()]; for ctr in 0..buf.len() { encrypted[ctr] = buf[ctr] ^ self.write_xor.next_byte(); } Pin::new(&mut self.wrapped_stream).poll_write(cx, &encrypted) } fn poll_flush( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_> ) -> std::task::Poll<std::result::Result<(), std::io::Error>> { Pin::new(&mut self.wrapped_stream).poll_flush(cx) } fn poll_close( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_> ) -> std::task::Poll<std::result::Result<(), std::io::Error>> { Pin::new(&mut self.wrapped_stream).poll_close(cx) } } // Test with https://docs.rs/async-std/1.7.0/async_std/io/struct.Cursor.html #[cfg(test)] mod tests { use async_std::io::Cursor; use futures::io::{AsyncReadExt, AsyncWriteExt}; use rand::{Rng, SeedableRng, thread_rng}; use rand_chacha::ChaCha8Rng; use super::*; fn create_stream_and_data_and_rng(stream_buf: Vec<u8>) -> (Cursor<Vec<u8>>, <ChaCha8Rng as SeedableRng>::Seed, ChaCha8Rng, ChaCha8Rng) { let memory_stream = Cursor::new(stream_buf); let mut test_seed: <ChaCha8Rng as SeedableRng>::Seed = Default::default(); thread_rng().fill(&mut test_seed); let test_rng = ChaCha8Rng::from_seed(test_seed.clone()); let ignored_rng = ChaCha8Rng::seed_from_u64(0); (memory_stream, test_seed, test_rng, ignored_rng) } #[async_std::test] async fn encrypted_stream_works_write() { let len = 1024 * 1024; let stream_buf = vec![0u8; len]; let (memory_stream, test_seed, test_rng, ignored_rng) = create_stream_and_data_and_rng(stream_buf); let mut test_contents = vec![0u8; len]; thread_rng().fill(&mut test_contents[..]); let mut encrypted_stream = EncryptedStream::new(memory_stream, test_rng, ignored_rng); encrypted_stream.write_all(&test_contents).await.unwrap(); let stream_buf_encrypted = encrypted_stream.wrapped_stream.into_inner(); // Verify that the contents changed assert_ne!(test_contents, stream_buf_encrypted, "Contents weren't encrypted"); // Verify each byte let test_rng = ChaCha8Rng::from_seed(test_seed.clone()); let mut xor = Xor::new(test_rng); for ctr in 0..test_contents.len() { let b = xor.next_byte(); assert_eq!(test_contents[ctr], stream_buf_encrypted[ctr] ^ b, "Encrypted content isn't as expected"); } } #[async_std::test] async fn encrypted_stream_works_read() { let len = 1024 * 1024; let mut encrypted_contents = vec![0u8; len]; thread_rng().fill(&mut encrypted_contents[..]); let (memory_stream, test_seed, test_rng, ignored_rng) = create_stream_and_data_and_rng(encrypted_contents.clone()); let mut encrypted_stream = EncryptedStream::new(memory_stream, ignored_rng, test_rng); let mut decrypted_contents = vec![0u8; encrypted_contents.len()]; let mut bytes_read = 0; loop { bytes_read = bytes_read + encrypted_stream.read(&mut decrypted_contents[bytes_read..]).await.unwrap(); if bytes_read >= decrypted_contents.len() { break; } } // Verify that the contents changed assert_ne!(encrypted_contents, decrypted_contents, "Contents weren't decrypted"); // Verify each byte let test_rng = ChaCha8Rng::from_seed(test_seed.clone()); let mut xor = Xor::new(test_rng); for ctr in 0..encrypted_contents.len() { let b = xor.next_byte(); assert_eq!(decrypted_contents[ctr], encrypted_contents[ctr] ^ b, "Decrypted content isn't as expected"); } } } */
/* use async_std::io; use async_std::io::{Read, Result, Write}; use async_std::task::{Context, Poll}; use std::marker::Unpin; use std::pin::Pin; use rand_core::{CryptoRng, RngCore}; pub struct EncryptedStream<TStream, TRng> where TStream: Read + Write, TRng: CryptoRng + RngCore { wrapped_stream: TStream, write_xor: Xor<TRng>, read_xor: Xor<TRng>, } pub struct Xor<TRng> { rng: TRng, xor: [u8; 1024], ctr: usize, } impl<TSt
^ self.write_xor.next_byte(); } Pin::new(&mut self.wrapped_stream).poll_write(cx, &encrypted) } fn poll_flush( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_> ) -> std::task::Poll<std::result::Result<(), std::io::Error>> { Pin::new(&mut self.wrapped_stream).poll_flush(cx) } fn poll_close( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_> ) -> std::task::Poll<std::result::Result<(), std::io::Error>> { Pin::new(&mut self.wrapped_stream).poll_close(cx) } } // Test with https://docs.rs/async-std/1.7.0/async_std/io/struct.Cursor.html #[cfg(test)] mod tests { use async_std::io::Cursor; use futures::io::{AsyncReadExt, AsyncWriteExt}; use rand::{Rng, SeedableRng, thread_rng}; use rand_chacha::ChaCha8Rng; use super::*; fn create_stream_and_data_and_rng(stream_buf: Vec<u8>) -> (Cursor<Vec<u8>>, <ChaCha8Rng as SeedableRng>::Seed, ChaCha8Rng, ChaCha8Rng) { let memory_stream = Cursor::new(stream_buf); let mut test_seed: <ChaCha8Rng as SeedableRng>::Seed = Default::default(); thread_rng().fill(&mut test_seed); let test_rng = ChaCha8Rng::from_seed(test_seed.clone()); let ignored_rng = ChaCha8Rng::seed_from_u64(0); (memory_stream, test_seed, test_rng, ignored_rng) } #[async_std::test] async fn encrypted_stream_works_write() { let len = 1024 * 1024; let stream_buf = vec![0u8; len]; let (memory_stream, test_seed, test_rng, ignored_rng) = create_stream_and_data_and_rng(stream_buf); let mut test_contents = vec![0u8; len]; thread_rng().fill(&mut test_contents[..]); let mut encrypted_stream = EncryptedStream::new(memory_stream, test_rng, ignored_rng); encrypted_stream.write_all(&test_contents).await.unwrap(); let stream_buf_encrypted = encrypted_stream.wrapped_stream.into_inner(); // Verify that the contents changed assert_ne!(test_contents, stream_buf_encrypted, "Contents weren't encrypted"); // Verify each byte let test_rng = ChaCha8Rng::from_seed(test_seed.clone()); let mut xor = Xor::new(test_rng); for ctr in 0..test_contents.len() { let b = xor.next_byte(); assert_eq!(test_contents[ctr], stream_buf_encrypted[ctr] ^ b, "Encrypted content isn't as expected"); } } #[async_std::test] async fn encrypted_stream_works_read() { let len = 1024 * 1024; let mut encrypted_contents = vec![0u8; len]; thread_rng().fill(&mut encrypted_contents[..]); let (memory_stream, test_seed, test_rng, ignored_rng) = create_stream_and_data_and_rng(encrypted_contents.clone()); let mut encrypted_stream = EncryptedStream::new(memory_stream, ignored_rng, test_rng); let mut decrypted_contents = vec![0u8; encrypted_contents.len()]; let mut bytes_read = 0; loop { bytes_read = bytes_read + encrypted_stream.read(&mut decrypted_contents[bytes_read..]).await.unwrap(); if bytes_read >= decrypted_contents.len() { break; } } // Verify that the contents changed assert_ne!(encrypted_contents, decrypted_contents, "Contents weren't decrypted"); // Verify each byte let test_rng = ChaCha8Rng::from_seed(test_seed.clone()); let mut xor = Xor::new(test_rng); for ctr in 0..encrypted_contents.len() { let b = xor.next_byte(); assert_eq!(decrypted_contents[ctr], encrypted_contents[ctr] ^ b, "Decrypted content isn't as expected"); } } } */
ream, TRng> Unpin for EncryptedStream<TStream, TRng> where TStream: Read + Write, TRng: CryptoRng + RngCore {} impl<TStream, TRng> EncryptedStream<TStream, TRng> where TStream: Read + Write, TRng: CryptoRng + RngCore { pub fn new(wrapped_stream: TStream, write_rng: TRng, read_rng: TRng) -> EncryptedStream<TStream, TRng> { EncryptedStream { wrapped_stream, write_xor: Xor::new(write_rng), read_xor: Xor::new(read_rng), } } } impl<TRng> Xor<TRng> where TRng: CryptoRng + RngCore { fn new(rng: TRng) -> Xor<TRng> { Xor { rng, xor: [0u8; 1024], ctr: usize::MAX, } } fn next_byte(&mut self) -> u8 { if self.ctr >= self.xor.len() { self.rng.fill_bytes(&mut self.xor[..]); self.ctr = 0; } let b = self.xor[self.ctr]; self.ctr = self.ctr + 1; b } } impl<TStream: Read + Unpin, TRng> Read for EncryptedStream<TStream, TRng> where TStream: Read + Write, TRng: CryptoRng + RngCore { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { let result = Pin::new(&mut self.wrapped_stream).poll_read(cx, buf); match result { Poll::Ready(result) => match result { Result::Ok(size) => { for ctr in 0..size { buf[ctr] = buf[ctr] ^ self.read_xor.next_byte(); } Poll::Ready(Result::Ok(size)) }, Result::Err(err) => Poll::Ready(Result::Err(err)) }, Poll::Pending => Poll::Pending } } } impl<TStream: Write + Unpin, TRng> Write for EncryptedStream<TStream, TRng> where TStream: Read + Write, TRng: CryptoRng + RngCore { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { let mut encrypted = vec![0; buf.len()]; for ctr in 0..buf.len() { encrypted[ctr] = buf[ctr]
random
[ { "content": "pub fn run_bridge<TRng>(xors: Xors<TRng>, clear_stream: TcpStream, clear_stream_name: String, encrypted_stream: TcpStream, encrypted_stream_name: String) where\n\nTRng: CryptoRng + RngCore + Clone + Any {\n\n\n\n match clear_stream.set_nodelay(true) {\n\n Err(err) => {\n\n log...
Rust
src/routes/proxy/img_proxy.rs
Marc3842h/gitarena
c8c53a7331d4ebc12ea69dfbf6220c11c40526cd
use crate::die; use crate::prelude::HttpRequestExtensions; use crate::utils::reqwest_actix_stream::ResponseStream; use actix_web::http::header::CONTENT_LENGTH; use actix_web::{HttpRequest, HttpResponse, Responder, web}; use anyhow::{Context, Result}; use gitarena_macros::route; use log::debug; use reqwest::Client; use serde::Deserialize; use tokio_compat_02::FutureExt; const PASSTHROUGH_HEADERS: [&str; 6] = [ "cache-control", "content-encoding", "etag", "expires", "last-modified", "transfer-encoding" ]; const ACCEPTED_MIME_TYPES: [&str; 43] = [ "image/bmp", "image/cgm", "image/g3fax", "image/gif", "image/ief", "image/jp2", "image/jpeg", "image/jpg", "image/pict", "image/png", "image/prs.btif", "image/svg+xml", "image/tiff", "image/vnd.adobe.photoshop", "image/vnd.djvu", "image/vnd.dwg", "image/vnd.dxf", "image/vnd.fastbidsheet", "image/vnd.fpx", "image/vnd.fst", "image/vnd.fujixerox.edmics-mmr", "image/vnd.fujixerox.edmics-rlc", "image/vnd.microsoft.icon", "image/vnd.ms-modi", "image/vnd.net-fpx", "image/vnd.wap.wbmp", "image/vnd.xiff", "image/webp", "image/x-cmu-raster", "image/x-cmx", "image/x-icon", "image/x-macpaint", "image/x-pcx", "image/x-pict", "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-quicktime", "image/x-rgb", "image/x-xbitmap", "image/x-xpixmap", "image/x-xwindowdump" ]; #[route("/api/proxy/{url}", method = "GET", err = "text")] pub(crate) async fn proxy(uri: web::Path<ProxyRequest>, request: HttpRequest) -> Result<impl Responder> { let url = &uri.url; if url.is_empty() { die!(NOT_FOUND, "Invalid url"); } let bytes = hex::decode(url)?; let url = String::from_utf8(bytes)?; let mut client = Client::new().get(&url); if let Some(header_value) = request.get_header("if-modified-since") { client = client.header("if-modified-since", header_value); } if let Some(header_value) = request.get_header("if-none-match") { client = client.header("if-none-match", header_value); } if let Some(header_value) = request.get_header("cache-control") { client = client.header("cache-control", header_value); } debug!("Image proxy request for {}", &url); let gateway_response = client.send().compat().await.context("Failed to send request to gateway")?; let mut response = HttpResponse::build(gateway_response.status()); if let Some(length) = gateway_response.content_length() { if length > 5242880 { die!(BAD_GATEWAY, "Content too big"); } response.append_header((CONTENT_LENGTH, length.to_string())); } for (name, value) in gateway_response.headers() { let lowered_name = name.as_str().to_lowercase(); let value_str = value.to_str()?; if PASSTHROUGH_HEADERS.contains(&lowered_name.as_str()) { response.append_header((name.as_str(), value_str)); } if lowered_name == "content-type" && !ACCEPTED_MIME_TYPES.contains(&value_str) { die!(BAD_GATEWAY, "Response was not an image"); } } Ok(response.streaming(ResponseStream { stream: gateway_response.bytes_stream() })) } #[derive(Deserialize)] pub(crate) struct ProxyRequest { pub(crate) url: String }
use crate::die; use crate::prelude::HttpRequestExtensions; use crate::utils::reqwest_actix_stream::ResponseStream; use actix_web::http::header::CONTENT_LENGTH; use actix_web::{HttpRequest, HttpResponse, Responder, web}; use anyhow::{Context, Result}; use gitarena_macros::route; use log::debug; use reqwest::Client; use serde::Deserialize; use tokio_compat_02::FutureExt; const PASSTHROUGH_HEADERS: [&str; 6] = [ "cache-control", "content-encoding", "etag", "expires", "last-modified", "transfer-encoding" ]; const ACCEPTED_MIME_TYPES: [&str; 43] = [ "image/bmp", "image/cgm", "image/g3fax", "image/gif", "image/ief", "image/jp2", "image/jpeg", "image/jpg", "image/pict", "image/png", "image/prs.btif", "image/svg+xml", "image/tiff", "image/vnd.adobe.photoshop", "image/vnd.djvu", "image/vnd.dwg", "image/vnd.dxf", "image/vnd.fastbidsheet", "image/vnd.fpx", "image/vnd.fst", "image/vnd.fujixerox.edmics-mmr", "image/vnd.fujixerox.edmics-rlc", "image/vnd.microsoft.icon", "image/vnd.ms-modi", "image/vnd.net-fpx", "image/vnd.wap.wbmp", "image/vnd.xiff", "image/webp", "image/x-cmu-raster", "image/x-cmx", "image/x-icon", "image/x-macpaint", "image/x-pcx", "image/x-pict", "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-quicktime", "image/x-rgb", "image/x-xbitmap", "image/x-xpixmap", "image/x-xwindowdump" ]; #[route("/api/proxy/{url}", method = "GET", err = "text")] pub(crate) async fn proxy(uri: web::Path<ProxyRequest>, request: HttpRequest) -> Result<impl Responder> { let url = &uri.url; if url.is_empty() { die!(NOT_FOUND, "Invalid url"); } let bytes = hex::decode(url)?; let url = String::from_utf8(bytes)?; let mut client = Client::new().get(&url); if let Some(header_value) = request.get_header("if-modified-since") { client = client.header("if-modified-since", header_value); } if let Some(header_value) = request.get_header("if-none-match") { client = client.header("if-none-match", header_value); } if let Some(header_value) = request.get_header("cache-control") { client = client.header("cache-control", header_value); } debug!("Image proxy request for {}", &url); let gateway_response = client.send().compat().await.context("Failed to send request to gateway")?; let mut response = HttpResponse::build(gateway_response.status()); if let Some(length) = gateway_response.content_length() { if length > 5242880 { die!(BAD_GATEWAY, "Content too big"); } response.append_header((CONTENT_LENGTH, length.to_string())); } for (name, value) in gateway_response.headers() { let lowered_name = name.as_str().to_lowercase(); let value_str = value.to_str()?; if PASSTHROUGH_HEADERS.contains(&lowered_name.as_str()) { respon
#[derive(Deserialize)] pub(crate) struct ProxyRequest { pub(crate) url: String }
se.append_header((name.as_str(), value_str)); } if lowered_name == "content-type" && !ACCEPTED_MIME_TYPES.contains(&value_str) { die!(BAD_GATEWAY, "Response was not an image"); } } Ok(response.streaming(ResponseStream { stream: gateway_response.bytes_stream() })) }
function_block-function_prefixed
[ { "content": "fn extract_ip(request: &HttpRequest) -> IpNetwork {\n\n let connection_info = request.connection_info();\n\n let ip_str = connection_info.realip_remote_addr().unwrap_or(\"No user agent sent\");\n\n\n\n match IpNetwork::from_str(ip_str) {\n\n Ok(ip_network) => ip_network,\n\n ...
Rust
fusequery/query/src/datasources/local/csv_table_test.rs
leiysky/fuse-query
49e268ba7938469c2a3c0541a0c713ef447ccffb
use std::sync::Arc; #[tokio::test] async fn test_csv_table() -> anyhow::Result<()> { use std::env; use common_datavalues::*; use common_planners::*; use futures::TryStreamExt; use crate::datasources::local::*; let options: TableOptions = [( "location".to_string(), env::current_dir()? .join("../../tests/data/sample.csv") .display() .to_string() )] .iter() .cloned() .collect(); let ctx = crate::tests::try_create_context()?; let table = CsvTable::try_create( "default".into(), "test_csv".into(), DataSchema::new(vec![DataField::new("column1", DataType::UInt64, false)]).into(), options )?; let scan_plan = &ScanPlan { schema_name: "".to_string(), table_schema: Arc::new(DataSchema::new(vec![])), table_args: None, projection: None, projected_schema: Arc::new(DataSchema::new(vec![DataField::new( "column1", DataType::UInt64, false )])), filters: vec![], limit: None }; let source_plan = table.read_plan(ctx.clone(), &scan_plan)?; ctx.try_set_partitions(source_plan.partitions)?; let stream = table.read(ctx).await?; let result = stream.try_collect::<Vec<_>>().await?; let block = &result[0]; assert_eq!(block.num_columns(), 1); let expected = vec![ "+---------+", "| column1 |", "+---------+", "| 1 |", "| 2 |", "| 3 |", "| 4 |", "| 5 |", "| 6 |", "+---------+", ]; common_datablocks::assert_blocks_sorted_eq(expected, result.as_slice()); Ok(()) } #[tokio::test] async fn test_csv_table_parse_error() -> anyhow::Result<()> { use std::env; use common_datavalues::*; use common_planners::*; use futures::TryStreamExt; use pretty_assertions::assert_eq; use crate::datasources::local::*; let options: TableOptions = [( "location".to_string(), env::current_dir()? .join("../../tests/data/sample.csv") .display() .to_string() )] .iter() .cloned() .collect(); let ctx = crate::tests::try_create_context()?; let table = CsvTable::try_create( "default".into(), "test_csv".into(), DataSchema::new(vec![ DataField::new("column1", DataType::UInt64, false), DataField::new("column2", DataType::UInt64, false), DataField::new("column3", DataType::UInt64, false), DataField::new("column4", DataType::UInt64, false), ]) .into(), options )?; let scan_plan = &ScanPlan { schema_name: "".to_string(), table_schema: Arc::new(DataSchema::new(vec![])), table_args: None, projection: None, projected_schema: Arc::new(DataSchema::new(vec![DataField::new( "column2", DataType::UInt64, false )])), filters: vec![], limit: None }; let source_plan = table.read_plan(ctx.clone(), &scan_plan)?; ctx.try_set_partitions(source_plan.partitions)?; let stream = table.read(ctx).await?; let result = stream.try_collect::<Vec<_>>().await; assert_eq!(true, result.is_err()); if let Err(e) = result { assert_eq!( "Code: 1002, displayText = Parser error: Error while parsing value \'Shanghai\' for column 1 at line 1.", e.to_string() ); }; Ok(()) }
use std::sync::Arc; #[tokio::test] async fn test_csv_table() -> anyhow::Result<()> { use std::env; use common_datavalues::*; use common_planners::*; use futures::TryStreamExt; use crate::datasources::local::*; let options: TableOptions = [( "location".to_string(), env::current_dir()? .join("../../tests/data/sample.csv") .display() .to_string() )] .iter() .cloned() .collect(); let ctx = crate::tests::try_create_context()?; let table = CsvTable::try_create( "default".into(), "test_csv".into(), DataSchema::new(vec![DataField::new("column1", DataType::UInt64, false)]).into(), options )?; let scan_plan = &ScanPlan { schema_name: "".to_string(), table_schema: Arc::new(DataSchema::new(vec![])), table_args: None, projection: None, projected_schema: Arc::new(DataSchema::new(vec![DataField::new( "column1", DataType::UInt64, false )])), filters: vec![], limit: None }; let source_plan = table.read_plan(ctx.clone(), &scan_plan)?; ctx.try_set_partitions(source_plan.partitions)?; let stream = table.read(ctx).await?; let result = stream.try_collect::<Vec<_>>().await?; let block = &result[0]; assert_eq!(block.num_columns(), 1); let expected = vec![ "+---------+", "| column1 |", "+---------+", "| 1 |", "| 2 |", "| 3 |", "| 4 |", "| 5 |", "| 6 |", "+---------+", ]; common_datablocks::assert_blocks_sorted_eq(expected, result.as_slice()); Ok(()) } #[tokio::test]
async fn test_csv_table_parse_error() -> anyhow::Result<()> { use std::env; use common_datavalues::*; use common_planners::*; use futures::TryStreamExt; use pretty_assertions::assert_eq; use crate::datasources::local::*; let options: TableOptions = [( "location".to_string(), env::current_dir()? .join("../../tests/data/sample.csv") .display() .to_string() )] .iter() .cloned() .collect(); let ctx = crate::tests::try_create_context()?; let table = CsvTable::try_create( "default".into(), "test_csv".into(), DataSchema::new(vec![ DataField::new("column1", DataType::UInt64, false), DataField::new("column2", DataType::UInt64, false), DataField::new("column3", DataType::UInt64, false), DataField::new("column4", DataType::UInt64, false), ]) .into(), options )?; let scan_plan = &ScanPlan { schema_name: "".to_string(), table_schema: Arc::new(DataSchema::new(vec![])), table_args: None, projection: None, projected_schema: Arc::new(DataSchema::new(vec![DataField::new( "column2", DataType::UInt64, false )])), filters: vec![], limit: None }; let source_plan = table.read_plan(ctx.clone(), &scan_plan)?; ctx.try_set_partitions(source_plan.partitions)?; let stream = table.read(ctx).await?; let result = stream.try_collect::<Vec<_>>().await; assert_eq!(true, result.is_err()); if let Err(e) = result { assert_eq!( "Code: 1002, displayText = Parser error: Error while parsing value \'Shanghai\' for column 1 at line 1.", e.to_string() ); }; Ok(()) }
function_block-full_function
[ { "content": "fn build_boolean_column(values: &DataArrayRef) -> Result<Vec<Option<u8>>> {\n\n let values = as_boolean_array(values);\n\n\n\n Ok(match values.null_count() {\n\n //faster path\n\n 0 => (0..values.len())\n\n .map(|i| Some(values.value(i) as u8))\n\n .collec...
Rust
crates/bevy_winit/src/winit_windows.rs
Schell-0x52/bevy
39224eed1716a9a069ff2f19c4dc93dcd9f88452
use bevy_math::IVec2; use bevy_utils::HashMap; use bevy_window::{Window, WindowDescriptor, WindowId, WindowMode}; use raw_window_handle::HasRawWindowHandle; use winit::dpi::LogicalSize; #[derive(Debug, Default)] pub struct WinitWindows { pub windows: HashMap<winit::window::WindowId, winit::window::Window>, pub window_id_to_winit: HashMap<WindowId, winit::window::WindowId>, pub winit_to_window_id: HashMap<winit::window::WindowId, WindowId>, } impl WinitWindows { pub fn create_window( &mut self, event_loop: &winit::event_loop::EventLoopWindowTarget<()>, window_id: WindowId, window_descriptor: &WindowDescriptor, ) -> Window { #[cfg(target_os = "windows")] let mut winit_window_builder = { use winit::platform::windows::WindowBuilderExtWindows; winit::window::WindowBuilder::new().with_drag_and_drop(false) }; #[cfg(not(target_os = "windows"))] let mut winit_window_builder = winit::window::WindowBuilder::new(); winit_window_builder = match window_descriptor.mode { WindowMode::BorderlessFullscreen => winit_window_builder.with_fullscreen(Some( winit::window::Fullscreen::Borderless(event_loop.primary_monitor()), )), WindowMode::Fullscreen { use_size } => winit_window_builder.with_fullscreen(Some( winit::window::Fullscreen::Exclusive(match use_size { true => get_fitting_videomode( &event_loop.primary_monitor().unwrap(), window_descriptor.width as u32, window_descriptor.height as u32, ), false => get_best_videomode(&event_loop.primary_monitor().unwrap()), }), )), _ => { let WindowDescriptor { width, height, position, scale_factor_override, .. } = window_descriptor; if let Some(position) = position { if let Some(sf) = scale_factor_override { winit_window_builder = winit_window_builder.with_position( winit::dpi::LogicalPosition::new( position[0] as f64, position[1] as f64, ) .to_physical::<f64>(*sf), ); } else { winit_window_builder = winit_window_builder.with_position(winit::dpi::LogicalPosition::new( position[0] as f64, position[1] as f64, )); } } if let Some(sf) = scale_factor_override { winit_window_builder.with_inner_size( winit::dpi::LogicalSize::new(*width, *height).to_physical::<f64>(*sf), ) } else { winit_window_builder .with_inner_size(winit::dpi::LogicalSize::new(*width, *height)) } } .with_resizable(window_descriptor.resizable) .with_decorations(window_descriptor.decorations), }; let constraints = window_descriptor.resize_constraints.check_constraints(); let min_inner_size = LogicalSize { width: constraints.min_width, height: constraints.min_height, }; let max_inner_size = LogicalSize { width: constraints.max_width, height: constraints.max_height, }; let winit_window_builder = if constraints.max_width.is_finite() && constraints.max_height.is_finite() { winit_window_builder .with_min_inner_size(min_inner_size) .with_max_inner_size(max_inner_size) } else { winit_window_builder.with_min_inner_size(min_inner_size) }; #[allow(unused_mut)] let mut winit_window_builder = winit_window_builder.with_title(&window_descriptor.title); #[cfg(target_arch = "wasm32")] { use wasm_bindgen::JsCast; use winit::platform::web::WindowBuilderExtWebSys; if let Some(selector) = &window_descriptor.canvas { let window = web_sys::window().unwrap(); let document = window.document().unwrap(); let canvas = document .query_selector(&selector) .expect("Cannot query for canvas element."); if let Some(canvas) = canvas { let canvas = canvas.dyn_into::<web_sys::HtmlCanvasElement>().ok(); winit_window_builder = winit_window_builder.with_canvas(canvas); } else { panic!("Cannot find element: {}.", selector); } } } let winit_window = winit_window_builder.build(event_loop).unwrap(); match winit_window.set_cursor_grab(window_descriptor.cursor_locked) { Ok(_) => {} Err(winit::error::ExternalError::NotSupported(_)) => {} Err(err) => Err(err).unwrap(), } winit_window.set_cursor_visible(window_descriptor.cursor_visible); self.window_id_to_winit.insert(window_id, winit_window.id()); self.winit_to_window_id.insert(winit_window.id(), window_id); #[cfg(target_arch = "wasm32")] { use winit::platform::web::WindowExtWebSys; if window_descriptor.canvas.is_none() { let canvas = winit_window.canvas(); let window = web_sys::window().unwrap(); let document = window.document().unwrap(); let body = document.body().unwrap(); body.append_child(&canvas) .expect("Append canvas to HTML body."); } } let position = winit_window .outer_position() .ok() .map(|position| IVec2::new(position.x, position.y)); let inner_size = winit_window.inner_size(); let scale_factor = winit_window.scale_factor(); let raw_window_handle = winit_window.raw_window_handle(); self.windows.insert(winit_window.id(), winit_window); Window::new( window_id, window_descriptor, inner_size.width, inner_size.height, scale_factor, position, raw_window_handle, ) } pub fn get_window(&self, id: WindowId) -> Option<&winit::window::Window> { self.window_id_to_winit .get(&id) .and_then(|id| self.windows.get(id)) } pub fn get_window_id(&self, id: winit::window::WindowId) -> Option<WindowId> { self.winit_to_window_id.get(&id).cloned() } } pub fn get_fitting_videomode( monitor: &winit::monitor::MonitorHandle, width: u32, height: u32, ) -> winit::monitor::VideoMode { let mut modes = monitor.video_modes().collect::<Vec<_>>(); fn abs_diff(a: u32, b: u32) -> u32 { if a > b { return a - b; } b - a } modes.sort_by(|a, b| { use std::cmp::Ordering::*; match abs_diff(a.size().width, width).cmp(&abs_diff(b.size().width, width)) { Equal => { match abs_diff(a.size().height, height).cmp(&abs_diff(b.size().height, height)) { Equal => b.refresh_rate().cmp(&a.refresh_rate()), default => default, } } default => default, } }); modes.first().unwrap().clone() } pub fn get_best_videomode(monitor: &winit::monitor::MonitorHandle) -> winit::monitor::VideoMode { let mut modes = monitor.video_modes().collect::<Vec<_>>(); modes.sort_by(|a, b| { use std::cmp::Ordering::*; match b.size().width.cmp(&a.size().width) { Equal => match b.size().height.cmp(&a.size().height) { Equal => b.refresh_rate().cmp(&a.refresh_rate()), default => default, }, default => default, } }); modes.first().unwrap().clone() } #[cfg(target_arch = "wasm32")] unsafe impl Send for WinitWindows {} #[cfg(target_arch = "wasm32")] unsafe impl Sync for WinitWindows {}
use bevy_math::IVec2; use bevy_utils::HashMap; use bevy_window::{Window, WindowDescriptor, WindowId, WindowMode}; use raw_window_handle::HasRawWindowHandle; use winit::dpi::LogicalSize; #[derive(Debug, Default)] pub struct WinitWindows { pub windows: HashMap<winit::window::WindowId, winit::window::Window>, pub window_id_to_winit: HashMap<WindowId, winit::window::WindowId>, pub winit_to_window_id: HashMap<winit::window::WindowId, WindowId>, } impl WinitWindows {
pub fn get_window(&self, id: WindowId) -> Option<&winit::window::Window> { self.window_id_to_winit .get(&id) .and_then(|id| self.windows.get(id)) } pub fn get_window_id(&self, id: winit::window::WindowId) -> Option<WindowId> { self.winit_to_window_id.get(&id).cloned() } } pub fn get_fitting_videomode( monitor: &winit::monitor::MonitorHandle, width: u32, height: u32, ) -> winit::monitor::VideoMode { let mut modes = monitor.video_modes().collect::<Vec<_>>(); fn abs_diff(a: u32, b: u32) -> u32 { if a > b { return a - b; } b - a } modes.sort_by(|a, b| { use std::cmp::Ordering::*; match abs_diff(a.size().width, width).cmp(&abs_diff(b.size().width, width)) { Equal => { match abs_diff(a.size().height, height).cmp(&abs_diff(b.size().height, height)) { Equal => b.refresh_rate().cmp(&a.refresh_rate()), default => default, } } default => default, } }); modes.first().unwrap().clone() } pub fn get_best_videomode(monitor: &winit::monitor::MonitorHandle) -> winit::monitor::VideoMode { let mut modes = monitor.video_modes().collect::<Vec<_>>(); modes.sort_by(|a, b| { use std::cmp::Ordering::*; match b.size().width.cmp(&a.size().width) { Equal => match b.size().height.cmp(&a.size().height) { Equal => b.refresh_rate().cmp(&a.refresh_rate()), default => default, }, default => default, } }); modes.first().unwrap().clone() } #[cfg(target_arch = "wasm32")] unsafe impl Send for WinitWindows {} #[cfg(target_arch = "wasm32")] unsafe impl Sync for WinitWindows {}
pub fn create_window( &mut self, event_loop: &winit::event_loop::EventLoopWindowTarget<()>, window_id: WindowId, window_descriptor: &WindowDescriptor, ) -> Window { #[cfg(target_os = "windows")] let mut winit_window_builder = { use winit::platform::windows::WindowBuilderExtWindows; winit::window::WindowBuilder::new().with_drag_and_drop(false) }; #[cfg(not(target_os = "windows"))] let mut winit_window_builder = winit::window::WindowBuilder::new(); winit_window_builder = match window_descriptor.mode { WindowMode::BorderlessFullscreen => winit_window_builder.with_fullscreen(Some( winit::window::Fullscreen::Borderless(event_loop.primary_monitor()), )), WindowMode::Fullscreen { use_size } => winit_window_builder.with_fullscreen(Some( winit::window::Fullscreen::Exclusive(match use_size { true => get_fitting_videomode( &event_loop.primary_monitor().unwrap(), window_descriptor.width as u32, window_descriptor.height as u32, ), false => get_best_videomode(&event_loop.primary_monitor().unwrap()), }), )), _ => { let WindowDescriptor { width, height, position, scale_factor_override, .. } = window_descriptor; if let Some(position) = position { if let Some(sf) = scale_factor_override { winit_window_builder = winit_window_builder.with_position( winit::dpi::LogicalPosition::new( position[0] as f64, position[1] as f64, ) .to_physical::<f64>(*sf), ); } else { winit_window_builder = winit_window_builder.with_position(winit::dpi::LogicalPosition::new( position[0] as f64, position[1] as f64, )); } } if let Some(sf) = scale_factor_override { winit_window_builder.with_inner_size( winit::dpi::LogicalSize::new(*width, *height).to_physical::<f64>(*sf), ) } else { winit_window_builder .with_inner_size(winit::dpi::LogicalSize::new(*width, *height)) } } .with_resizable(window_descriptor.resizable) .with_decorations(window_descriptor.decorations), }; let constraints = window_descriptor.resize_constraints.check_constraints(); let min_inner_size = LogicalSize { width: constraints.min_width, height: constraints.min_height, }; let max_inner_size = LogicalSize { width: constraints.max_width, height: constraints.max_height, }; let winit_window_builder = if constraints.max_width.is_finite() && constraints.max_height.is_finite() { winit_window_builder .with_min_inner_size(min_inner_size) .with_max_inner_size(max_inner_size) } else { winit_window_builder.with_min_inner_size(min_inner_size) }; #[allow(unused_mut)] let mut winit_window_builder = winit_window_builder.with_title(&window_descriptor.title); #[cfg(target_arch = "wasm32")] { use wasm_bindgen::JsCast; use winit::platform::web::WindowBuilderExtWebSys; if let Some(selector) = &window_descriptor.canvas { let window = web_sys::window().unwrap(); let document = window.document().unwrap(); let canvas = document .query_selector(&selector) .expect("Cannot query for canvas element."); if let Some(canvas) = canvas { let canvas = canvas.dyn_into::<web_sys::HtmlCanvasElement>().ok(); winit_window_builder = winit_window_builder.with_canvas(canvas); } else { panic!("Cannot find element: {}.", selector); } } } let winit_window = winit_window_builder.build(event_loop).unwrap(); match winit_window.set_cursor_grab(window_descriptor.cursor_locked) { Ok(_) => {} Err(winit::error::ExternalError::NotSupported(_)) => {} Err(err) => Err(err).unwrap(), } winit_window.set_cursor_visible(window_descriptor.cursor_visible); self.window_id_to_winit.insert(window_id, winit_window.id()); self.winit_to_window_id.insert(winit_window.id(), window_id); #[cfg(target_arch = "wasm32")] { use winit::platform::web::WindowExtWebSys; if window_descriptor.canvas.is_none() { let canvas = winit_window.canvas(); let window = web_sys::window().unwrap(); let document = window.document().unwrap(); let body = document.body().unwrap(); body.append_child(&canvas) .expect("Append canvas to HTML body."); } } let position = winit_window .outer_position() .ok() .map(|position| IVec2::new(position.x, position.y)); let inner_size = winit_window.inner_size(); let scale_factor = winit_window.scale_factor(); let raw_window_handle = winit_window.raw_window_handle(); self.windows.insert(winit_window.id(), winit_window); Window::new( window_id, window_descriptor, inner_size.width, inner_size.height, scale_factor, position, raw_window_handle, ) }
function_block-full_function
[ { "content": "/// An ordered &str->ReflectValue mapping where &str is a \"field\".\n\n/// This corresponds to rust struct types.\n\npub trait Struct: Reflect {\n\n fn field(&self, name: &str) -> Option<&dyn Reflect>;\n\n fn field_mut(&mut self, name: &str) -> Option<&mut dyn Reflect>;\n\n fn field_at(&...
Rust
src/cargo/sources/registry/remote.rs
Aelnor/cargo
b1684e28490a111b4956b40377abb2b961bfd4b3
use crate::core::{GitReference, PackageId, SourceId}; use crate::sources::git; use crate::sources::registry::MaybeLock; use crate::sources::registry::{ RegistryConfig, RegistryData, CRATE_TEMPLATE, LOWER_PREFIX_TEMPLATE, PREFIX_TEMPLATE, VERSION_TEMPLATE, }; use crate::util::errors::CargoResult; use crate::util::interning::InternedString; use crate::util::{Config, Filesystem}; use anyhow::Context as _; use cargo_util::{paths, Sha256}; use lazycell::LazyCell; use log::{debug, trace}; use std::cell::{Cell, Ref, RefCell}; use std::fmt::Write as FmtWrite; use std::fs::{self, File, OpenOptions}; use std::io::prelude::*; use std::io::SeekFrom; use std::mem; use std::path::Path; use std::str; fn make_dep_prefix(name: &str) -> String { match name.len() { 1 => String::from("1"), 2 => String::from("2"), 3 => format!("3/{}", &name[..1]), _ => format!("{}/{}", &name[0..2], &name[2..4]), } } pub struct RemoteRegistry<'cfg> { index_path: Filesystem, cache_path: Filesystem, source_id: SourceId, index_git_ref: GitReference, config: &'cfg Config, tree: RefCell<Option<git2::Tree<'static>>>, repo: LazyCell<git2::Repository>, head: Cell<Option<git2::Oid>>, current_sha: Cell<Option<InternedString>>, } impl<'cfg> RemoteRegistry<'cfg> { pub fn new(source_id: SourceId, config: &'cfg Config, name: &str) -> RemoteRegistry<'cfg> { RemoteRegistry { index_path: config.registry_index_path().join(name), cache_path: config.registry_cache_path().join(name), source_id, config, index_git_ref: GitReference::DefaultBranch, tree: RefCell::new(None), repo: LazyCell::new(), head: Cell::new(None), current_sha: Cell::new(None), } } fn repo(&self) -> CargoResult<&git2::Repository> { self.repo.try_borrow_with(|| { let path = self.config.assert_package_cache_locked(&self.index_path); if let Ok(repo) = git2::Repository::open(&path) { trace!("opened a repo without a lock"); return Ok(repo); } trace!("acquiring registry index lock"); match git2::Repository::open(&path) { Ok(repo) => Ok(repo), Err(_) => { drop(paths::remove_dir_all(&path)); paths::create_dir_all(&path)?; let mut opts = git2::RepositoryInitOptions::new(); opts.external_template(false); Ok(git2::Repository::init_opts(&path, &opts) .with_context(|| "failed to initialize index git repository")?) } } }) } fn head(&self) -> CargoResult<git2::Oid> { if self.head.get().is_none() { let repo = self.repo()?; let oid = self.index_git_ref.resolve(repo)?; self.head.set(Some(oid)); } Ok(self.head.get().unwrap()) } fn tree(&self) -> CargoResult<Ref<'_, git2::Tree<'_>>> { { let tree = self.tree.borrow(); if tree.is_some() { return Ok(Ref::map(tree, |s| s.as_ref().unwrap())); } } let repo = self.repo()?; let commit = repo.find_commit(self.head()?)?; let tree = commit.tree()?; let tree = unsafe { mem::transmute::<git2::Tree<'_>, git2::Tree<'static>>(tree) }; *self.tree.borrow_mut() = Some(tree); Ok(Ref::map(self.tree.borrow(), |s| s.as_ref().unwrap())) } fn filename(&self, pkg: PackageId) -> String { format!("{}-{}.crate", pkg.name(), pkg.version()) } } const LAST_UPDATED_FILE: &str = ".last-updated"; impl<'cfg> RegistryData for RemoteRegistry<'cfg> { fn prepare(&self) -> CargoResult<()> { self.repo()?; Ok(()) } fn index_path(&self) -> &Filesystem { &self.index_path } fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path { self.config.assert_package_cache_locked(path) } fn current_version(&self) -> Option<InternedString> { if let Some(sha) = self.current_sha.get() { return Some(sha); } let sha = InternedString::new(&self.head().ok()?.to_string()); self.current_sha.set(Some(sha)); Some(sha) } fn load( &self, _root: &Path, path: &Path, data: &mut dyn FnMut(&[u8]) -> CargoResult<()>, ) -> CargoResult<()> { let repo = self.repo()?; let tree = self.tree()?; let entry = tree.get_path(path)?; let object = entry.to_object(repo)?; let blob = match object.as_blob() { Some(blob) => blob, None => anyhow::bail!("path `{}` is not a blob in the git repo", path.display()), }; data(blob.content()) } fn config(&mut self) -> CargoResult<Option<RegistryConfig>> { debug!("loading config"); self.prepare()?; self.config.assert_package_cache_locked(&self.index_path); let mut config = None; self.load(Path::new(""), Path::new("config.json"), &mut |json| { config = Some(serde_json::from_slice(json)?); Ok(()) })?; trace!("config loaded"); Ok(config) } fn update_index(&mut self) -> CargoResult<()> { if self.config.offline() { return Ok(()); } if self.config.cli_unstable().no_index_update { return Ok(()); } if self.config.updated_sources().contains(&self.source_id) { return Ok(()); } debug!("updating the index"); self.config.http()?; self.prepare()?; self.head.set(None); *self.tree.borrow_mut() = None; self.current_sha.set(None); let path = self.config.assert_package_cache_locked(&self.index_path); self.config .shell() .status("Updating", self.source_id.display_index())?; let url = self.source_id.url(); let repo = self.repo.borrow_mut().unwrap(); git::fetch(repo, url.as_str(), &self.index_git_ref, self.config) .with_context(|| format!("failed to fetch `{}`", url))?; self.config.updated_sources().insert(self.source_id); paths::create(&path.join(LAST_UPDATED_FILE))?; Ok(()) } fn download(&mut self, pkg: PackageId, _checksum: &str) -> CargoResult<MaybeLock> { let filename = self.filename(pkg); let path = self.cache_path.join(&filename); let path = self.config.assert_package_cache_locked(&path); if let Ok(dst) = File::open(&path) { let meta = dst.metadata()?; if meta.len() > 0 { return Ok(MaybeLock::Ready(dst)); } } let config = self.config()?.unwrap(); let mut url = config.dl; if !url.contains(CRATE_TEMPLATE) && !url.contains(VERSION_TEMPLATE) && !url.contains(PREFIX_TEMPLATE) && !url.contains(LOWER_PREFIX_TEMPLATE) { write!(url, "/{}/{}/download", CRATE_TEMPLATE, VERSION_TEMPLATE).unwrap(); } let prefix = make_dep_prefix(&*pkg.name()); let url = url .replace(CRATE_TEMPLATE, &*pkg.name()) .replace(VERSION_TEMPLATE, &pkg.version().to_string()) .replace(PREFIX_TEMPLATE, &prefix) .replace(LOWER_PREFIX_TEMPLATE, &prefix.to_lowercase()); Ok(MaybeLock::Download { url, descriptor: pkg.to_string(), }) } fn finish_download( &mut self, pkg: PackageId, checksum: &str, data: &[u8], ) -> CargoResult<File> { let actual = Sha256::new().update(data).finish_hex(); if actual != checksum { anyhow::bail!("failed to verify the checksum of `{}`", pkg) } let filename = self.filename(pkg); self.cache_path.create_dir()?; let path = self.cache_path.join(&filename); let path = self.config.assert_package_cache_locked(&path); let mut dst = OpenOptions::new() .create(true) .read(true) .write(true) .open(&path) .with_context(|| format!("failed to open `{}`", path.display()))?; let meta = dst.metadata()?; if meta.len() > 0 { return Ok(dst); } dst.write_all(data)?; dst.seek(SeekFrom::Start(0))?; Ok(dst) } fn is_crate_downloaded(&self, pkg: PackageId) -> bool { let filename = format!("{}-{}.crate", pkg.name(), pkg.version()); let path = Path::new(&filename); let path = self.cache_path.join(path); let path = self.config.assert_package_cache_locked(&path); if let Ok(meta) = fs::metadata(path) { return meta.len() > 0; } false } } impl<'cfg> Drop for RemoteRegistry<'cfg> { fn drop(&mut self) { self.tree.borrow_mut().take(); } } #[cfg(test)] mod tests { use super::make_dep_prefix; #[test] fn dep_prefix() { assert_eq!(make_dep_prefix("a"), "1"); assert_eq!(make_dep_prefix("ab"), "2"); assert_eq!(make_dep_prefix("abc"), "3/a"); assert_eq!(make_dep_prefix("Abc"), "3/A"); assert_eq!(make_dep_prefix("AbCd"), "Ab/Cd"); assert_eq!(make_dep_prefix("aBcDe"), "aB/cD"); } }
use crate::core::{GitReference, PackageId, SourceId}; use crate::sources::git; use crate::sources::registry::MaybeLock; use crate::sources::registry::{ RegistryConfig, RegistryData, CRATE_TEMPLATE, LOWER_PREFIX_TEMPLATE, PREFIX_TEMPLATE, VERSION_TEMPLATE, }; use crate::util::errors::CargoResult; use crate::util::interning::InternedString; use crate::util::{Config, Filesystem}; use anyhow::Context as _; use cargo_util::{paths, Sha256}; use lazycell::LazyCell; use log::{debug, trace}; use std::cell::{Cell, Ref, RefCell}; use std::fmt::Write as FmtWrite; use std::fs::{self, File, OpenOptions}; use std::io::prelude::*; use std::io::SeekFrom; use std::mem; use std::path::Path; use std::str; fn make_dep_prefix(name: &str) -> String { match name.len() { 1 => String::from("1"), 2 => String::from("2"), 3 => format!("3/{}", &name[..1]), _ => format!("{}/{}", &name[0..2], &name[2..4]), } } pub struct RemoteRegistry<'cfg> { index_path: Filesystem, cache_path: Filesystem, source_id: SourceId, index_git_ref: GitReference, config: &'cfg Config, tree: RefCell<Option<git2::Tree<'static>>>, repo: LazyCell<git2::Repository>, head: Cell<Option<git2::Oid>>, current_sha: Cell<Option<InternedString>>, } impl<'cfg> RemoteRegistry<'cfg> { pub fn new(source_id: SourceId, config: &'cfg Config, name: &str) -> RemoteRegistry<'cfg> { RemoteRegistry { index_path: config.registry_index_path().join(name), cache_path: config.registry_cache_path().join(name), source_id, config, index_git_ref: GitReference::DefaultBranch, tree: RefCell::new(None), repo: LazyCell::new(), head: Cell::new(None), current_sha: Cell::new(None), } } fn repo(&self) -> CargoResult<&git2::Repository> { self.repo.try_borrow_with(|| { let path = self.config.assert_package_cache_locked(&self.index_path); if let Ok(repo) = git2::Repository::open(&path) { trace!("opened a repo without a lock"); return Ok(repo); } trace!("acquiring registry index lock"); match git2::Repository::open(&path) { Ok(repo) => Ok(repo), Err(_) => { drop(paths::remove_dir_all(&path)); paths::create_dir_all(&path)?; let mut opts = git2::RepositoryInitOptions::new(); opts.external_template(false); Ok(git2::Repository::init_opts(&path, &opts) .with_context(|| "failed to initialize index git repository")?) } } }) } fn head(&self) -> CargoResult<git2::Oid> { if self.head.get().is_none() { let repo = self.repo()?; let oid = self.index_git_ref.resolve(repo)?; self.head.set(Some(oid)); } Ok(self.head.get().unwrap()) } fn tree(&self) -> CargoResult<Ref<'_, git2::Tree<'_>>> { { let tree = self.tree.borrow(); if tree.is_some() { return Ok(Ref::map(tree, |s| s.as_ref().unwrap())); } } let repo = self.repo()?; let commit = repo.find_commit(self.head()?)?; let tree = commit.tree()?; let tree = unsafe { mem::transmute::<git2::Tree<'_>, git2::Tree<'static>>(tree) }; *self.tree.borrow_mut() = Some(tree); Ok(Ref::map(self.tree.borrow(), |s| s.as_ref().unwrap())) } fn filename(&self, pkg: PackageId) -> String { format!("{}-{}.crate", pkg.name(), pkg.version()) } } const LAST_UPDATED_FILE: &str = ".last-updated"; impl<'cfg> RegistryData for RemoteRegistry<'cfg> { fn prepare(&self) -> CargoResult<()> { self.repo()?; Ok(()) } fn index_path(&self) -> &Filesystem { &self.index_path } fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path { self.config.assert_package_cache_locked(path) } fn current_version(&self) -> Option<InternedString> { if let Some(sha) = self.current_sha.get() { return Some(sha); } let sha = InternedString::new(&self.head().ok()?.to_string()); self.current_sha.set(Some(sha)); Some(sha) } fn load( &self, _root: &Path, path: &Path, data: &mut dyn FnMut(&[u8]) -> CargoResult<()>, ) -> CargoResult<()> { let repo = self.repo()?; let tree = self.tree()?; let entry = tree.get_path(path)?; let object = entry.to_object(repo)?; let blob = match object.as_blob() { Some(blob) => blob, None => anyhow::bail!("path `{}` is not a blob in the git repo", path.display()), }; data(blob.content()) } fn config(&mut self) -> CargoResult<Option<RegistryConfig>> { debug!("
th::new(""), Path::new("config.json"), &mut |json| { config = Some(serde_json::from_slice(json)?); Ok(()) })?; trace!("config loaded"); Ok(config) } fn update_index(&mut self) -> CargoResult<()> { if self.config.offline() { return Ok(()); } if self.config.cli_unstable().no_index_update { return Ok(()); } if self.config.updated_sources().contains(&self.source_id) { return Ok(()); } debug!("updating the index"); self.config.http()?; self.prepare()?; self.head.set(None); *self.tree.borrow_mut() = None; self.current_sha.set(None); let path = self.config.assert_package_cache_locked(&self.index_path); self.config .shell() .status("Updating", self.source_id.display_index())?; let url = self.source_id.url(); let repo = self.repo.borrow_mut().unwrap(); git::fetch(repo, url.as_str(), &self.index_git_ref, self.config) .with_context(|| format!("failed to fetch `{}`", url))?; self.config.updated_sources().insert(self.source_id); paths::create(&path.join(LAST_UPDATED_FILE))?; Ok(()) } fn download(&mut self, pkg: PackageId, _checksum: &str) -> CargoResult<MaybeLock> { let filename = self.filename(pkg); let path = self.cache_path.join(&filename); let path = self.config.assert_package_cache_locked(&path); if let Ok(dst) = File::open(&path) { let meta = dst.metadata()?; if meta.len() > 0 { return Ok(MaybeLock::Ready(dst)); } } let config = self.config()?.unwrap(); let mut url = config.dl; if !url.contains(CRATE_TEMPLATE) && !url.contains(VERSION_TEMPLATE) && !url.contains(PREFIX_TEMPLATE) && !url.contains(LOWER_PREFIX_TEMPLATE) { write!(url, "/{}/{}/download", CRATE_TEMPLATE, VERSION_TEMPLATE).unwrap(); } let prefix = make_dep_prefix(&*pkg.name()); let url = url .replace(CRATE_TEMPLATE, &*pkg.name()) .replace(VERSION_TEMPLATE, &pkg.version().to_string()) .replace(PREFIX_TEMPLATE, &prefix) .replace(LOWER_PREFIX_TEMPLATE, &prefix.to_lowercase()); Ok(MaybeLock::Download { url, descriptor: pkg.to_string(), }) } fn finish_download( &mut self, pkg: PackageId, checksum: &str, data: &[u8], ) -> CargoResult<File> { let actual = Sha256::new().update(data).finish_hex(); if actual != checksum { anyhow::bail!("failed to verify the checksum of `{}`", pkg) } let filename = self.filename(pkg); self.cache_path.create_dir()?; let path = self.cache_path.join(&filename); let path = self.config.assert_package_cache_locked(&path); let mut dst = OpenOptions::new() .create(true) .read(true) .write(true) .open(&path) .with_context(|| format!("failed to open `{}`", path.display()))?; let meta = dst.metadata()?; if meta.len() > 0 { return Ok(dst); } dst.write_all(data)?; dst.seek(SeekFrom::Start(0))?; Ok(dst) } fn is_crate_downloaded(&self, pkg: PackageId) -> bool { let filename = format!("{}-{}.crate", pkg.name(), pkg.version()); let path = Path::new(&filename); let path = self.cache_path.join(path); let path = self.config.assert_package_cache_locked(&path); if let Ok(meta) = fs::metadata(path) { return meta.len() > 0; } false } } impl<'cfg> Drop for RemoteRegistry<'cfg> { fn drop(&mut self) { self.tree.borrow_mut().take(); } } #[cfg(test)] mod tests { use super::make_dep_prefix; #[test] fn dep_prefix() { assert_eq!(make_dep_prefix("a"), "1"); assert_eq!(make_dep_prefix("ab"), "2"); assert_eq!(make_dep_prefix("abc"), "3/a"); assert_eq!(make_dep_prefix("Abc"), "3/A"); assert_eq!(make_dep_prefix("AbCd"), "Ab/Cd"); assert_eq!(make_dep_prefix("aBcDe"), "aB/cD"); } }
loading config"); self.prepare()?; self.config.assert_package_cache_locked(&self.index_path); let mut config = None; self.load(Pa
function_block-random_span
[ { "content": "/// Commit changes to the git repository.\n\npub fn commit(repo: &git2::Repository) -> git2::Oid {\n\n let tree_id = t!(t!(repo.index()).write_tree());\n\n let sig = t!(repo.signature());\n\n let mut parents = Vec::new();\n\n if let Some(parent) = repo.head().ok().map(|h| h.target().un...
Rust
game/src/sandbox/mod.rs
jvolker/abstreet
7d4cf4cd5b27bce37cf35d3d8aecf0e3d5148a2f
mod dashboards; pub mod gameplay; mod misc_tools; mod speed; mod uber_turns; use self::misc_tools::{RoutePreview, ShowTrafficSignal, TurnExplorer}; use crate::app::App; use crate::common::{tool_panel, CommonState, ContextualActions, Minimap}; use crate::debug::DebugMode; use crate::edit::{ apply_map_edits, can_edit_lane, save_edits_as, EditMode, LaneEditor, StopSignEditor, TrafficSignalEditor, }; use crate::game::{State, Transition, WizardState}; use crate::helpers::ID; use crate::layer::PickLayer; use crate::managed::{WrappedComposite, WrappedOutcome}; use crate::pregame::MainMenu; use crate::render::AgentColorScheme; use ezgui::{ hotkey, lctrl, Btn, Choice, Color, Composite, EventCtx, GeomBatch, GfxCtx, HorizontalAlignment, Key, Line, Outcome, Text, TextExt, UpdateType, VerticalAlignment, Widget, Wizard, }; pub use gameplay::{spawn_agents_around, GameplayMode, TutorialPointer, TutorialState}; use geom::{Polygon, Time}; use map_model::MapEdits; use sim::{TripMode, VehicleType}; pub use speed::TimeWarpScreen; pub use speed::{SpeedControls, TimePanel}; pub struct SandboxMode { gameplay: Box<dyn gameplay::GameplayState>, pub gameplay_mode: GameplayMode, pub controls: SandboxControls, } pub struct SandboxControls { pub common: Option<CommonState>, route_preview: Option<RoutePreview>, tool_panel: Option<WrappedComposite>, time_panel: Option<TimePanel>, speed: Option<SpeedControls>, pub agent_meter: Option<AgentMeter>, minimap: Option<Minimap>, } impl SandboxMode { pub fn new(ctx: &mut EventCtx, app: &mut App, mode: GameplayMode) -> SandboxMode { app.primary.clear_sim(); let gameplay = mode.initialize(ctx, app); SandboxMode { controls: SandboxControls { common: if gameplay.has_common() { Some(CommonState::new()) } else { None }, route_preview: if gameplay.can_examine_objects() { Some(RoutePreview::new()) } else { None }, tool_panel: if gameplay.has_tool_panel() { Some(tool_panel(ctx, app)) } else { None }, time_panel: if gameplay.has_time_panel() { Some(TimePanel::new(ctx, app)) } else { None }, speed: if gameplay.has_speed() { Some(SpeedControls::new(ctx, app)) } else { None }, agent_meter: if gameplay.has_agent_meter() { Some(AgentMeter::new(ctx, app)) } else { None }, minimap: if gameplay.has_minimap() { Some(Minimap::new(ctx, app)) } else { None }, }, gameplay, gameplay_mode: mode, } } pub fn contextual_actions(&self) -> Actions { Actions { is_paused: self .controls .speed .as_ref() .map(|s| s.is_paused()) .unwrap_or(true), can_interact: self.gameplay.can_examine_objects(), gameplay: self.gameplay_mode.clone(), } } } impl State for SandboxMode { fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition { if self.gameplay.can_move_canvas() { ctx.canvas_movement(); } if let Some(t) = self.gameplay.event(ctx, app, &mut self.controls) { return t; } if ctx.redo_mouseover() { app.recalculate_current_selection(ctx); } if app.opts.dev && ctx.input.new_was_pressed(&lctrl(Key::D).unwrap()) { return Transition::Push(Box::new(DebugMode::new(ctx, app))); } if let Some(ref mut m) = self.controls.minimap { if let Some(t) = m.event(ctx, app) { return t; } if let Some(t) = PickLayer::update(ctx, app, &m.composite) { return t; } } if let Some(ref mut s) = self.controls.speed { if let Some(t) = s.event(ctx, app, Some(&self.gameplay_mode)) { return t; } } if let Some(ref mut r) = self.controls.route_preview { if let Some(t) = r.event(ctx, app) { return t; } } let mut actions = self.contextual_actions(); if let Some(ref mut c) = self.controls.common { if let Some(t) = c.event(ctx, app, &mut actions) { return t; } } if let Some(ref mut tp) = self.controls.time_panel { tp.event(ctx, app); } if let Some(ref mut tp) = self.controls.tool_panel { match tp.event(ctx, app) { Some(WrappedOutcome::Transition(t)) => { return t; } Some(WrappedOutcome::Clicked(x)) => match x.as_ref() { "back" => { return maybe_exit_sandbox(); } _ => unreachable!(), }, None => {} } } if let Some(ref mut am) = self.controls.agent_meter { if let Some(t) = am.event(ctx, app) { return t; } } if self .controls .speed .as_ref() .map(|s| s.is_paused()) .unwrap_or(true) { Transition::Keep } else { ctx.request_update(UpdateType::Game); Transition::Keep } } fn draw(&self, g: &mut GfxCtx, app: &App) { if let Some(ref l) = app.layer { l.draw(g, app); } if let Some(ref c) = self.controls.common { c.draw(g, app); } else { CommonState::draw_osd(g, app); } if let Some(ref tp) = self.controls.tool_panel { tp.draw(g); } if let Some(ref s) = self.controls.speed { s.draw(g); } if let Some(ref tp) = self.controls.time_panel { tp.draw(g); } if let Some(ref am) = self.controls.agent_meter { am.draw(g); } if let Some(ref m) = self.controls.minimap { m.draw(g, app); } if let Some(ref r) = self.controls.route_preview { r.draw(g); } self.gameplay.draw(g, app); } fn on_destroy(&mut self, _: &mut EventCtx, app: &mut App) { app.layer = None; app.agent_cs = AgentColorScheme::new(&app.cs); self.gameplay.on_destroy(app); } } pub fn maybe_exit_sandbox() -> Transition { Transition::Push(WizardState::new(Box::new(exit_sandbox))) } fn exit_sandbox(wiz: &mut Wizard, ctx: &mut EventCtx, app: &mut App) -> Option<Transition> { let mut wizard = wiz.wrap(ctx); let unsaved = app.primary.map.unsaved_edits(); let (resp, _) = wizard.choose("Are you ready to leave this mode?", || { let mut choices = Vec::new(); choices.push(Choice::new("keep playing", ())); if unsaved { choices.push(Choice::new("save edits first", ())); } choices.push(Choice::new("quit to main screen", ()).key(Key::Q)); choices })?; if resp == "keep playing" { return Some(Transition::Pop); } if resp == "save edits first" { save_edits_as(&mut wizard, app)?; } ctx.loading_screen("reset map and sim", |ctx, mut timer| { if !app.primary.map.get_edits().commands.is_empty() { apply_map_edits(ctx, app, MapEdits::new()); app.primary .map .recalculate_pathfinding_after_edits(&mut timer); } app.primary.clear_sim(); app.set_prebaked(None); }); ctx.canvas.save_camera_state(app.primary.map.get_name()); Some(Transition::Clear(vec![MainMenu::new(ctx, app)])) } pub struct AgentMeter { time: Time, pub composite: Composite, } impl AgentMeter { pub fn new(ctx: &mut EventCtx, app: &App) -> AgentMeter { use abstutil::prettyprint_usize; let (finished, unfinished, by_mode) = app.primary.sim.num_trips(); let rows = vec![ "Active trips".draw_text(ctx), Widget::custom_row(vec![ Widget::custom_row(vec![ Widget::draw_svg(ctx, "../data/system/assets/meters/pedestrian.svg") .margin_right(5), prettyprint_usize(by_mode[&TripMode::Walk]).draw_text(ctx), ]), Widget::custom_row(vec![ Widget::draw_svg(ctx, "../data/system/assets/meters/bike.svg").margin_right(5), prettyprint_usize(by_mode[&TripMode::Bike]).draw_text(ctx), ]), Widget::custom_row(vec![ Widget::draw_svg(ctx, "../data/system/assets/meters/car.svg").margin_right(5), prettyprint_usize(by_mode[&TripMode::Drive]).draw_text(ctx), ]), Widget::custom_row(vec![ Widget::draw_svg(ctx, "../data/system/assets/meters/bus.svg").margin_right(5), prettyprint_usize(by_mode[&TripMode::Transit]).draw_text(ctx), ]), ]) .centered(), Widget::draw_batch( ctx, GeomBatch::from(vec![( Color::WHITE, Polygon::rectangle(0.2 * ctx.canvas.window_width / ctx.get_scale_factor(), 2.0), )]), ) .centered_horiz(), Widget::row(vec![ { let mut txt = Text::new(); let pct = if unfinished == 0 { 100.0 } else { 100.0 * (finished as f64) / ((finished + unfinished) as f64) }; txt.add(Line(format!( "Finished trips: {} ({}%)", prettyprint_usize(finished), pct as usize ))); txt.draw(ctx) }, Btn::svg_def("../data/system/assets/meters/trip_histogram.svg") .build(ctx, "more data", hotkey(Key::Q)) .align_right(), ]), ]; let composite = Composite::new(Widget::col(rows).bg(app.cs.panel_bg).padding(16)) .aligned(HorizontalAlignment::Right, VerticalAlignment::Top) .build(ctx); AgentMeter { time: app.primary.sim.time(), composite, } } pub fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Option<Transition> { if self.time != app.primary.sim.time() { *self = AgentMeter::new(ctx, app); return self.event(ctx, app); } match self.composite.event(ctx) { Some(Outcome::Clicked(x)) => match x.as_ref() { "more data" => { return Some(Transition::Push(dashboards::TripTable::new(ctx, app))); } _ => unreachable!(), }, None => {} } None } pub fn draw(&self, g: &mut GfxCtx) { self.composite.draw(g); } } pub struct Actions { is_paused: bool, can_interact: bool, gameplay: GameplayMode, } impl ContextualActions for Actions { fn actions(&self, app: &App, id: ID) -> Vec<(Key, String)> { let mut actions = Vec::new(); if self.can_interact { match id.clone() { ID::Intersection(i) => { if app.primary.map.get_i(i).is_traffic_signal() { actions.push((Key::F, "explore traffic signal details".to_string())); actions.push((Key::E, "edit traffic signal".to_string())); } if app.primary.map.get_i(i).is_stop_sign() && self.gameplay.can_edit_stop_signs() { actions.push((Key::E, "edit stop sign".to_string())); } if app.opts.dev { actions.push((Key::U, "explore uber-turns".to_string())); } } ID::Lane(l) => { if !app.primary.map.get_turns_from_lane(l).is_empty() { actions.push((Key::Z, "explore turns from this lane".to_string())); } if can_edit_lane(&self.gameplay, l, app) { actions.push((Key::E, "edit lane".to_string())); } } ID::Car(c) => { if c.1 == VehicleType::Bus { actions.push((Key::R, "show route".to_string())); } } _ => {} } } actions.extend(self.gameplay.actions(app, id)); actions } fn execute( &mut self, ctx: &mut EventCtx, app: &mut App, id: ID, action: String, close_panel: &mut bool, ) -> Transition { match (id, action.as_ref()) { (ID::Intersection(i), "explore traffic signal details") => { Transition::Push(ShowTrafficSignal::new(ctx, app, i)) } (ID::Intersection(i), "edit traffic signal") => Transition::PushTwice( Box::new(EditMode::new(ctx, app, self.gameplay.clone())), Box::new(TrafficSignalEditor::new(ctx, app, i, self.gameplay.clone())), ), (ID::Intersection(i), "edit stop sign") => Transition::PushTwice( Box::new(EditMode::new(ctx, app, self.gameplay.clone())), Box::new(StopSignEditor::new(ctx, app, i, self.gameplay.clone())), ), (ID::Intersection(i), "explore uber-turns") => { Transition::Push(uber_turns::UberTurnPicker::new(ctx, app, i)) } (ID::Lane(l), "explore turns from this lane") => { Transition::Push(TurnExplorer::new(ctx, app, l)) } (ID::Lane(l), "edit lane") => Transition::PushTwice( Box::new(EditMode::new(ctx, app, self.gameplay.clone())), Box::new(LaneEditor::new(ctx, app, l, self.gameplay.clone())), ), (ID::Car(c), "show route") => { *close_panel = false; app.layer = Some(Box::new(crate::layer::bus::ShowBusRoute::new( ctx, app, app.primary.sim.bus_route_id(c).unwrap(), ))); Transition::Keep } (_, "follow (run the simulation)") => { *close_panel = false; Transition::KeepWithData(Box::new(|state, ctx, app| { let mode = state.downcast_mut::<SandboxMode>().unwrap(); let speed = mode.controls.speed.as_mut().unwrap(); assert!(speed.is_paused()); speed.resume_realtime(ctx, app); })) } (_, "unfollow (pause the simulation)") => { *close_panel = false; Transition::KeepWithData(Box::new(|state, ctx, app| { let mode = state.downcast_mut::<SandboxMode>().unwrap(); let speed = mode.controls.speed.as_mut().unwrap(); assert!(!speed.is_paused()); speed.pause(ctx, app); })) } (id, action) => self .gameplay .execute(ctx, app, id, action.to_string(), close_panel), } } fn is_paused(&self) -> bool { self.is_paused } }
mod dashboards; pub mod gameplay; mod misc_tools; mod speed; mod uber_turns; use self::misc_tools::{RoutePreview, ShowTrafficSignal, TurnExplorer}; use crate::app::App; use crate::common::{tool_panel, CommonState, ContextualActions, Minimap}; use crate::debug::DebugMode; use crate::edit::{ apply_map_edits, can_edit_lane, save_edits_as, EditMode, LaneEditor, StopSignEditor, TrafficSignalEditor, }; use crate::game::{State, Transition, WizardState}; use crate::helpers::ID; use crate::layer::PickLayer; use crate::managed::{WrappedComposite, WrappedOutcome}; use crate::pregame::MainMenu; use crate::render::AgentColorScheme; use ezgui::{ hotkey, lctrl, Btn, Choice, Color, Composite, EventCtx, GeomBatch, GfxCtx, HorizontalAlignment, Key, Line, Outcome, Text, TextExt, UpdateType, VerticalAlignment, Widget, Wizard, }; pub use gameplay::{spawn_agents_around, GameplayMode, TutorialPointer, TutorialState}; use geom::{Polygon, Time}; use map_model::MapEdits; use sim::{TripMode, VehicleType}; pub use speed::TimeWarpScreen; pub use speed::{SpeedControls, TimePanel}; pub struct SandboxMode { gameplay: Box<dyn gameplay::GameplayState>, pub gameplay_mode: GameplayMode, pub controls: SandboxControls, } pub struct SandboxControls { pub common: Option<CommonState>, route_preview: Option<RoutePreview>, tool_panel: Option<WrappedComposite>, time_panel: Option<TimePanel>, speed: Option<SpeedControls>, pub agent_meter: Option<AgentMeter>, minimap: Option<Minimap>, } impl SandboxMode { pub fn new(ctx: &mut EventCtx, app: &mut App, mode: GameplayMode) -> SandboxMode { app.primary.clear_sim(); let gameplay = mode.initialize(ctx, app); SandboxMode { controls: SandboxControls { common: if gameplay.has_common() { Some(CommonState::new()) } else { None }, route_preview: if gameplay.can_examine_objects() { Some(RoutePreview::new()) } else { None }, tool_panel: if gameplay.has_tool_panel() { Some(tool_panel(ctx, app)) } else { None }, time_panel: if gameplay.has_time_panel() { Some(TimePanel::new(ctx, app)) } else { None }, speed: if gameplay.has_speed() { Some(SpeedControls::new(ctx, app)) } else { None }, agent_meter: if gameplay.has_agent_meter() { Some(AgentMeter::new(ctx, app)) } else { None }, minimap: if gameplay.has_minimap() { Some(Minimap::new(ctx, app)) } else { None }, }, gameplay, gameplay_mode: mode, } } pub fn contextual_actions(&self) -> Actions { Actions { is_paused: self .controls .speed .as_ref() .map(|s| s.is_paused()) .
} impl State for SandboxMode { fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition { if self.gameplay.can_move_canvas() { ctx.canvas_movement(); } if let Some(t) = self.gameplay.event(ctx, app, &mut self.controls) { return t; } if ctx.redo_mouseover() { app.recalculate_current_selection(ctx); } if app.opts.dev && ctx.input.new_was_pressed(&lctrl(Key::D).unwrap()) { return Transition::Push(Box::new(DebugMode::new(ctx, app))); } if let Some(ref mut m) = self.controls.minimap { if let Some(t) = m.event(ctx, app) { return t; } if let Some(t) = PickLayer::update(ctx, app, &m.composite) { return t; } } if let Some(ref mut s) = self.controls.speed { if let Some(t) = s.event(ctx, app, Some(&self.gameplay_mode)) { return t; } } if let Some(ref mut r) = self.controls.route_preview { if let Some(t) = r.event(ctx, app) { return t; } } let mut actions = self.contextual_actions(); if let Some(ref mut c) = self.controls.common { if let Some(t) = c.event(ctx, app, &mut actions) { return t; } } if let Some(ref mut tp) = self.controls.time_panel { tp.event(ctx, app); } if let Some(ref mut tp) = self.controls.tool_panel { match tp.event(ctx, app) { Some(WrappedOutcome::Transition(t)) => { return t; } Some(WrappedOutcome::Clicked(x)) => match x.as_ref() { "back" => { return maybe_exit_sandbox(); } _ => unreachable!(), }, None => {} } } if let Some(ref mut am) = self.controls.agent_meter { if let Some(t) = am.event(ctx, app) { return t; } } if self .controls .speed .as_ref() .map(|s| s.is_paused()) .unwrap_or(true) { Transition::Keep } else { ctx.request_update(UpdateType::Game); Transition::Keep } } fn draw(&self, g: &mut GfxCtx, app: &App) { if let Some(ref l) = app.layer { l.draw(g, app); } if let Some(ref c) = self.controls.common { c.draw(g, app); } else { CommonState::draw_osd(g, app); } if let Some(ref tp) = self.controls.tool_panel { tp.draw(g); } if let Some(ref s) = self.controls.speed { s.draw(g); } if let Some(ref tp) = self.controls.time_panel { tp.draw(g); } if let Some(ref am) = self.controls.agent_meter { am.draw(g); } if let Some(ref m) = self.controls.minimap { m.draw(g, app); } if let Some(ref r) = self.controls.route_preview { r.draw(g); } self.gameplay.draw(g, app); } fn on_destroy(&mut self, _: &mut EventCtx, app: &mut App) { app.layer = None; app.agent_cs = AgentColorScheme::new(&app.cs); self.gameplay.on_destroy(app); } } pub fn maybe_exit_sandbox() -> Transition { Transition::Push(WizardState::new(Box::new(exit_sandbox))) } fn exit_sandbox(wiz: &mut Wizard, ctx: &mut EventCtx, app: &mut App) -> Option<Transition> { let mut wizard = wiz.wrap(ctx); let unsaved = app.primary.map.unsaved_edits(); let (resp, _) = wizard.choose("Are you ready to leave this mode?", || { let mut choices = Vec::new(); choices.push(Choice::new("keep playing", ())); if unsaved { choices.push(Choice::new("save edits first", ())); } choices.push(Choice::new("quit to main screen", ()).key(Key::Q)); choices })?; if resp == "keep playing" { return Some(Transition::Pop); } if resp == "save edits first" { save_edits_as(&mut wizard, app)?; } ctx.loading_screen("reset map and sim", |ctx, mut timer| { if !app.primary.map.get_edits().commands.is_empty() { apply_map_edits(ctx, app, MapEdits::new()); app.primary .map .recalculate_pathfinding_after_edits(&mut timer); } app.primary.clear_sim(); app.set_prebaked(None); }); ctx.canvas.save_camera_state(app.primary.map.get_name()); Some(Transition::Clear(vec![MainMenu::new(ctx, app)])) } pub struct AgentMeter { time: Time, pub composite: Composite, } impl AgentMeter { pub fn new(ctx: &mut EventCtx, app: &App) -> AgentMeter { use abstutil::prettyprint_usize; let (finished, unfinished, by_mode) = app.primary.sim.num_trips(); let rows = vec![ "Active trips".draw_text(ctx), Widget::custom_row(vec![ Widget::custom_row(vec![ Widget::draw_svg(ctx, "../data/system/assets/meters/pedestrian.svg") .margin_right(5), prettyprint_usize(by_mode[&TripMode::Walk]).draw_text(ctx), ]), Widget::custom_row(vec![ Widget::draw_svg(ctx, "../data/system/assets/meters/bike.svg").margin_right(5), prettyprint_usize(by_mode[&TripMode::Bike]).draw_text(ctx), ]), Widget::custom_row(vec![ Widget::draw_svg(ctx, "../data/system/assets/meters/car.svg").margin_right(5), prettyprint_usize(by_mode[&TripMode::Drive]).draw_text(ctx), ]), Widget::custom_row(vec![ Widget::draw_svg(ctx, "../data/system/assets/meters/bus.svg").margin_right(5), prettyprint_usize(by_mode[&TripMode::Transit]).draw_text(ctx), ]), ]) .centered(), Widget::draw_batch( ctx, GeomBatch::from(vec![( Color::WHITE, Polygon::rectangle(0.2 * ctx.canvas.window_width / ctx.get_scale_factor(), 2.0), )]), ) .centered_horiz(), Widget::row(vec![ { let mut txt = Text::new(); let pct = if unfinished == 0 { 100.0 } else { 100.0 * (finished as f64) / ((finished + unfinished) as f64) }; txt.add(Line(format!( "Finished trips: {} ({}%)", prettyprint_usize(finished), pct as usize ))); txt.draw(ctx) }, Btn::svg_def("../data/system/assets/meters/trip_histogram.svg") .build(ctx, "more data", hotkey(Key::Q)) .align_right(), ]), ]; let composite = Composite::new(Widget::col(rows).bg(app.cs.panel_bg).padding(16)) .aligned(HorizontalAlignment::Right, VerticalAlignment::Top) .build(ctx); AgentMeter { time: app.primary.sim.time(), composite, } } pub fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Option<Transition> { if self.time != app.primary.sim.time() { *self = AgentMeter::new(ctx, app); return self.event(ctx, app); } match self.composite.event(ctx) { Some(Outcome::Clicked(x)) => match x.as_ref() { "more data" => { return Some(Transition::Push(dashboards::TripTable::new(ctx, app))); } _ => unreachable!(), }, None => {} } None } pub fn draw(&self, g: &mut GfxCtx) { self.composite.draw(g); } } pub struct Actions { is_paused: bool, can_interact: bool, gameplay: GameplayMode, } impl ContextualActions for Actions { fn actions(&self, app: &App, id: ID) -> Vec<(Key, String)> { let mut actions = Vec::new(); if self.can_interact { match id.clone() { ID::Intersection(i) => { if app.primary.map.get_i(i).is_traffic_signal() { actions.push((Key::F, "explore traffic signal details".to_string())); actions.push((Key::E, "edit traffic signal".to_string())); } if app.primary.map.get_i(i).is_stop_sign() && self.gameplay.can_edit_stop_signs() { actions.push((Key::E, "edit stop sign".to_string())); } if app.opts.dev { actions.push((Key::U, "explore uber-turns".to_string())); } } ID::Lane(l) => { if !app.primary.map.get_turns_from_lane(l).is_empty() { actions.push((Key::Z, "explore turns from this lane".to_string())); } if can_edit_lane(&self.gameplay, l, app) { actions.push((Key::E, "edit lane".to_string())); } } ID::Car(c) => { if c.1 == VehicleType::Bus { actions.push((Key::R, "show route".to_string())); } } _ => {} } } actions.extend(self.gameplay.actions(app, id)); actions } fn execute( &mut self, ctx: &mut EventCtx, app: &mut App, id: ID, action: String, close_panel: &mut bool, ) -> Transition { match (id, action.as_ref()) { (ID::Intersection(i), "explore traffic signal details") => { Transition::Push(ShowTrafficSignal::new(ctx, app, i)) } (ID::Intersection(i), "edit traffic signal") => Transition::PushTwice( Box::new(EditMode::new(ctx, app, self.gameplay.clone())), Box::new(TrafficSignalEditor::new(ctx, app, i, self.gameplay.clone())), ), (ID::Intersection(i), "edit stop sign") => Transition::PushTwice( Box::new(EditMode::new(ctx, app, self.gameplay.clone())), Box::new(StopSignEditor::new(ctx, app, i, self.gameplay.clone())), ), (ID::Intersection(i), "explore uber-turns") => { Transition::Push(uber_turns::UberTurnPicker::new(ctx, app, i)) } (ID::Lane(l), "explore turns from this lane") => { Transition::Push(TurnExplorer::new(ctx, app, l)) } (ID::Lane(l), "edit lane") => Transition::PushTwice( Box::new(EditMode::new(ctx, app, self.gameplay.clone())), Box::new(LaneEditor::new(ctx, app, l, self.gameplay.clone())), ), (ID::Car(c), "show route") => { *close_panel = false; app.layer = Some(Box::new(crate::layer::bus::ShowBusRoute::new( ctx, app, app.primary.sim.bus_route_id(c).unwrap(), ))); Transition::Keep } (_, "follow (run the simulation)") => { *close_panel = false; Transition::KeepWithData(Box::new(|state, ctx, app| { let mode = state.downcast_mut::<SandboxMode>().unwrap(); let speed = mode.controls.speed.as_mut().unwrap(); assert!(speed.is_paused()); speed.resume_realtime(ctx, app); })) } (_, "unfollow (pause the simulation)") => { *close_panel = false; Transition::KeepWithData(Box::new(|state, ctx, app| { let mode = state.downcast_mut::<SandboxMode>().unwrap(); let speed = mode.controls.speed.as_mut().unwrap(); assert!(!speed.is_paused()); speed.pause(ctx, app); })) } (id, action) => self .gameplay .execute(ctx, app, id, action.to_string(), close_panel), } } fn is_paused(&self) -> bool { self.is_paused } }
unwrap_or(true), can_interact: self.gameplay.can_examine_objects(), gameplay: self.gameplay_mode.clone(), } }
function_block-function_prefix_line
[ { "content": "// TODO Well, there goes the nice consolidation of stuff in BtnBuilder. :\\\n\npub fn hotkey_btn<I: Into<String>>(ctx: &EventCtx, app: &App, label: I, key: Key) -> Widget {\n\n let label = label.into();\n\n let mut txt = Text::new();\n\n txt.append(Line(key.describe()).fg(ctx.style().hotk...
Rust
src/sim2/training.rs
ryotaok/genshin
4f3778b787e59220853ae8cce4f7e7b94d34ac54
use crate::sim2::state::State; use crate::sim2::timeline::{Timeline}; use crate::sim2::attack::{WeaponAttack}; use crate::sim2::types::{WeaponType, SCORE}; use crate::sim2::record::{WeaponRecord, Artifact}; use WeaponType::*; pub enum TrainingWeaponUnion { TrainingSword(TrainingSword), TrainingClaymore(TrainingClaymore), TrainingPolearm(TrainingPolearm), TrainingBow(TrainingBow), TrainingCatalyst(TrainingCatalyst), } impl TrainingWeaponUnion { pub fn timeline(&mut self) -> &mut dyn Timeline { use TrainingWeaponUnion::*; match self { TrainingSword(x) => x, TrainingClaymore(x) => x, TrainingPolearm(x) => x, TrainingBow(x) => x, TrainingCatalyst(x) => x, } } pub fn field(&mut self) -> &mut dyn WeaponAttack { use TrainingWeaponUnion::*; match self { TrainingSword(x) => x, TrainingClaymore(x) => x, TrainingPolearm(x) => x, TrainingBow(x) => x, TrainingCatalyst(x) => x, } } } pub fn weapons() -> Vec<(WeaponRecord, TrainingWeaponUnion)> { vec![ (TrainingSword::record(), TrainingWeaponUnion::TrainingSword(TrainingSword)), (TrainingClaymore::record(), TrainingWeaponUnion::TrainingClaymore(TrainingClaymore)), (TrainingPolearm::record(), TrainingWeaponUnion::TrainingPolearm(TrainingPolearm)), (TrainingBow::record(), TrainingWeaponUnion::TrainingBow(TrainingBow)), (TrainingCatalyst::record(), TrainingWeaponUnion::TrainingCatalyst(TrainingCatalyst)), ] } #[derive(Debug)] pub struct TrainingSword; impl Timeline for TrainingSword {} impl WeaponAttack for TrainingSword {} impl TrainingSword { pub fn record() -> WeaponRecord { WeaponRecord::default() .name("Training Sword").type_(Sword).version(1.0) .base_atk(608.) } } #[derive(Debug)] pub struct TrainingClaymore; impl Timeline for TrainingClaymore {} impl WeaponAttack for TrainingClaymore {} impl TrainingClaymore { pub fn record() -> WeaponRecord { WeaponRecord::default() .name("Training Claymore").type_(Claymore).version(1.0) .base_atk(608.) } } #[derive(Debug)] pub struct TrainingPolearm; impl Timeline for TrainingPolearm {} impl WeaponAttack for TrainingPolearm {} impl TrainingPolearm { pub fn record() -> WeaponRecord { WeaponRecord::default() .name("Training Polearm").type_(Polearm).version(1.0) .base_atk(608.) } } #[derive(Debug)] pub struct TrainingBow; impl Timeline for TrainingBow {} impl WeaponAttack for TrainingBow {} impl TrainingBow { pub fn record() -> WeaponRecord { WeaponRecord::default() .name("Training Bow").type_(Bow).version(1.0) .base_atk(608.) } } #[derive(Debug)] pub struct TrainingCatalyst; impl Timeline for TrainingCatalyst {} impl WeaponAttack for TrainingCatalyst {} impl TrainingCatalyst { pub fn record() -> WeaponRecord { WeaponRecord::default() .name("Training Catalyst").type_(Catalyst).version(1.0) .base_atk(608.) } } pub enum TrainingArtifactUnion { TrainingArtifact0(TrainingArtifact0), TrainingArtifact1(TrainingArtifact1), TrainingArtifact2(TrainingArtifact2), TrainingArtifact3(TrainingArtifact3), TrainingArtifact4(TrainingArtifact4), TrainingArtifact5(TrainingArtifact5), TrainingArtifact6(TrainingArtifact6), TrainingArtifact7(TrainingArtifact7), TrainingArtifact8(TrainingArtifact8), TrainingArtifact9(TrainingArtifact9), } impl TrainingArtifactUnion { pub fn timeline(&mut self) -> &mut dyn Timeline { use TrainingArtifactUnion::*; match self { TrainingArtifact0(x) => x, TrainingArtifact1(x) => x, TrainingArtifact2(x) => x, TrainingArtifact3(x) => x, TrainingArtifact4(x) => x, TrainingArtifact5(x) => x, TrainingArtifact6(x) => x, TrainingArtifact7(x) => x, TrainingArtifact8(x) => x, TrainingArtifact9(x) => x, } } pub fn field(&mut self) -> &mut dyn WeaponAttack { use TrainingArtifactUnion::*; match self { TrainingArtifact0(x) => x, TrainingArtifact1(x) => x, TrainingArtifact2(x) => x, TrainingArtifact3(x) => x, TrainingArtifact4(x) => x, TrainingArtifact5(x) => x, TrainingArtifact6(x) => x, TrainingArtifact7(x) => x, TrainingArtifact8(x) => x, TrainingArtifact9(x) => x, } } } pub fn artifacts() -> Vec<(Artifact, TrainingArtifactUnion)> { vec![ (TrainingArtifact0::record(), TrainingArtifactUnion::TrainingArtifact0(TrainingArtifact0)), (TrainingArtifact1::record(), TrainingArtifactUnion::TrainingArtifact1(TrainingArtifact1)), (TrainingArtifact2::record(), TrainingArtifactUnion::TrainingArtifact2(TrainingArtifact2)), (TrainingArtifact3::record(), TrainingArtifactUnion::TrainingArtifact3(TrainingArtifact3)), (TrainingArtifact4::record(), TrainingArtifactUnion::TrainingArtifact4(TrainingArtifact4)), (TrainingArtifact5::record(), TrainingArtifactUnion::TrainingArtifact5(TrainingArtifact5)), (TrainingArtifact6::record(), TrainingArtifactUnion::TrainingArtifact6(TrainingArtifact6)), (TrainingArtifact7::record(), TrainingArtifactUnion::TrainingArtifact7(TrainingArtifact7)), (TrainingArtifact8::record(), TrainingArtifactUnion::TrainingArtifact8(TrainingArtifact8)), (TrainingArtifact9::record(), TrainingArtifactUnion::TrainingArtifact9(TrainingArtifact9)), ] } #[derive(Debug)] pub struct TrainingArtifact0; impl Timeline for TrainingArtifact0 {} impl WeaponAttack for TrainingArtifact0 {} impl TrainingArtifact0 { pub fn record() -> Artifact { Artifact::default() .name("Atk70 Em280 Er78").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(33.3333)) .em(SCORE.em(33.3333)) .er(SCORE.er(33.3333)) } } #[derive(Debug)] pub struct TrainingArtifact1; impl Timeline for TrainingArtifact1 {} impl WeaponAttack for TrainingArtifact1 {} impl TrainingArtifact1 { pub fn record() -> Artifact { Artifact::default() .name("Atk168 Em167").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(80.)) .em(SCORE.em(20.)) } } #[derive(Debug)] pub struct TrainingArtifact2; impl Timeline for TrainingArtifact2 {} impl WeaponAttack for TrainingArtifact2 {} impl TrainingArtifact2 { pub fn record() -> Artifact { Artifact::default() .name("Atk168 Er46").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(80.)) .er(SCORE.er(20.)) } } #[derive(Debug)] pub struct TrainingArtifact3; impl Timeline for TrainingArtifact3 {} impl WeaponAttack for TrainingArtifact3 {} impl TrainingArtifact3 { pub fn record() -> Artifact { Artifact::default() .name("Atk41 Em671").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(20.)) .em(SCORE.em(80.)) } } #[derive(Debug)] pub struct TrainingArtifact4; impl Timeline for TrainingArtifact4 {} impl WeaponAttack for TrainingArtifact4 {} impl TrainingArtifact4 { pub fn record() -> Artifact { Artifact::default() .name("Em671 Er46").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .em(SCORE.em(80.)) .er(SCORE.er(20.)) } } #[derive(Debug)] pub struct TrainingArtifact5; impl Timeline for TrainingArtifact5 {} impl WeaponAttack for TrainingArtifact5 {} impl TrainingArtifact5 { pub fn record() -> Artifact { Artifact::default() .name("Atk42 Er186").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(20.)) .er(SCORE.er(80.)) } } #[derive(Debug)] pub struct TrainingArtifact6; impl Timeline for TrainingArtifact6 {} impl WeaponAttack for TrainingArtifact6 {} impl TrainingArtifact6 { pub fn record() -> Artifact { Artifact::default() .name("Em167 Er186").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .em(SCORE.em(20.)) .er(SCORE.er(80.)) } } #[derive(Debug)] pub struct TrainingArtifact7; impl Timeline for TrainingArtifact7 {} impl WeaponAttack for TrainingArtifact7 {} impl TrainingArtifact7 { pub fn record() -> Artifact { Artifact::default() .name("Atk105 Em420").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(50.)) .em(SCORE.em(50.)) } } #[derive(Debug)] pub struct TrainingArtifact8; impl Timeline for TrainingArtifact8 {} impl WeaponAttack for TrainingArtifact8 {} impl TrainingArtifact8 { pub fn record() -> Artifact { Artifact::default() .name("Atk105 Er116").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(50.)) .er(SCORE.er(50.)) } } #[derive(Debug)] pub struct TrainingArtifact9; impl Timeline for TrainingArtifact9 {} impl WeaponAttack for TrainingArtifact9 {} impl TrainingArtifact9 { pub fn record() -> Artifact { Artifact::default() .name("Em420 Er116").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .em(SCORE.em(50.)) .er(SCORE.er(50.)) } } #[derive(Debug)] pub struct TrainingArtifact10; impl Timeline for TrainingArtifact10 {} impl WeaponAttack for TrainingArtifact10 {} impl TrainingArtifact10 { pub fn record() -> Artifact { Artifact::default() .name("Atk210").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(100.)) } } #[derive(Debug)] pub struct TrainingArtifact11; impl Timeline for TrainingArtifact11 {} impl WeaponAttack for TrainingArtifact11 {} impl TrainingArtifact11 { pub fn record() -> Artifact { Artifact::default() .name("Em839").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .em(SCORE.em(100.)) } } #[derive(Debug)] pub struct TrainingArtifact12; impl Timeline for TrainingArtifact12 {} impl WeaponAttack for TrainingArtifact12 {} impl TrainingArtifact12 { pub fn record() -> Artifact { Artifact::default() .name("Er233").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .er(SCORE.er(100.)) } }
use crate::sim2::state::State; use crate::sim2::timeline::{Timeline}; use crate::sim2::attack::{WeaponAttack}; use crate::sim2::types::{WeaponType, SCORE}; use crate::sim2::record::{WeaponRecord, Artifact}; use WeaponType::*; pub enum TrainingWeaponUnion { TrainingSword(TrainingSword), TrainingClaymore(TrainingClaymore), TrainingPolearm(TrainingPolearm), TrainingBow(TrainingBow), TrainingCatalyst(TrainingCatalyst), } impl TrainingWeaponUnion { pub fn timeline(&mut self) -> &mut dyn Timeline { use TrainingWeaponUnion::*; match self { TrainingSword(x) => x, TrainingClaymore(x) => x, TrainingPolearm(x) => x, TrainingBow(x) => x, TrainingCatalyst(x) => x, } } pub fn field(&mut self) -> &mut dyn WeaponAttack { use TrainingWeaponUnion::*; match self { TrainingSword(x) => x, TrainingClaymore(x) => x, TrainingPolearm(x) => x, TrainingBow(x) => x, TrainingCatalyst(x) => x, } } } pub fn weapons() -> Vec<(WeaponRecord, TrainingWeaponUnion)> { vec![ (TrainingSword::record(), TrainingWeaponUnion::TrainingSword(TrainingSword)), (TrainingClaymore::record(), TrainingWeaponUnion::TrainingClaymore(TrainingClaymore)), (TrainingPolearm::record(), TrainingWeaponUnion::TrainingPolearm(TrainingPolearm)), (TrainingBow::record(), TrainingWeaponUnion::TrainingBow(TrainingBow)), (TrainingCatalyst::record(), TrainingWeaponUnion::TrainingCatalyst(TrainingCatalyst)), ] } #[derive(Debug)] pub struct TrainingSword; impl Timeline for TrainingSword {} impl WeaponAttack for TrainingSword {} impl TrainingSword { pub fn record() -> WeaponRecord { WeaponRecord::default() .name("Training Sword").type_(Sword).version(1.0) .base_atk(608.) } } #[derive(Debug)] pub struct TrainingClaymore; impl Timeline for TrainingClaymore {} impl WeaponAttack for TrainingClaymore {} impl TrainingClaymore { pub fn record() -> WeaponRecord { WeaponRecord::default() .name("Training Claymore").type_(Claymore).version(1.0) .base_atk(608.) } } #[derive(Debug)] pub struct TrainingPolearm; impl Timeline for TrainingPolearm {} impl WeaponAttack for TrainingPolearm {} impl TrainingPolearm { pub fn record() -> WeaponRecord { WeaponRecord::default() .name("Training Polearm").type_(Polearm).version(1.0) .base_atk(608.) } } #[derive(Debug)] pub struct TrainingBow; impl Timeline for TrainingBow {} impl WeaponAttack for TrainingBow {} impl TrainingBow { pub fn record() -> WeaponRecord { WeaponRecord::default() .name("Training Bow").type_(Bow).version(1.0) .base_atk(608.) } } #[derive(Debug)] pub struct TrainingCatalyst; impl Timeline for TrainingCatalyst {} impl WeaponAttack for TrainingCatalyst {} impl TrainingCatalyst { pub fn record() -> WeaponRecord { WeaponRecord::default() .name("Training Catalyst").type_(Catalyst).version(1.0) .base_atk(608.) } } pub enum TrainingArtifactUnion { TrainingArtifact0(TrainingArtifact0), TrainingArtifact1(TrainingArtifact1), TrainingArtifact2(TrainingArtifact2), TrainingArtifact3(TrainingArtifact3), TrainingArtifact4(TrainingArtifact4), TrainingArtifact5(TrainingArtifact5), TrainingArtifact6(TrainingArtifact6), TrainingArtifact7(TrainingArtifact7), TrainingArtifact8(TrainingArtifact8), TrainingArtifact9(TrainingArtifact9), } impl TrainingArtifactUnion { pub fn timeline(&mut self) -> &mut dyn Timeline { use TrainingArtifactUnion::*; match self { TrainingArtifact0(x) => x, TrainingArtifact1(x) => x, TrainingArtifact2(x) => x, TrainingArtifact3(x) => x, TrainingArtifact4(x) => x, TrainingArtifact5(x) => x, TrainingArtifact6(x) => x, TrainingArtifact7(x) => x, TrainingArtifact8(x) => x, TrainingArtifact9(x) => x, } } pub fn field(&mut self) -> &mut dyn WeaponAttack { use TrainingArtifactUnion::*; match self { TrainingArtifact0(x) => x, TrainingArtifact1(x) => x,
} pub fn artifacts() -> Vec<(Artifact, TrainingArtifactUnion)> { vec![ (TrainingArtifact0::record(), TrainingArtifactUnion::TrainingArtifact0(TrainingArtifact0)), (TrainingArtifact1::record(), TrainingArtifactUnion::TrainingArtifact1(TrainingArtifact1)), (TrainingArtifact2::record(), TrainingArtifactUnion::TrainingArtifact2(TrainingArtifact2)), (TrainingArtifact3::record(), TrainingArtifactUnion::TrainingArtifact3(TrainingArtifact3)), (TrainingArtifact4::record(), TrainingArtifactUnion::TrainingArtifact4(TrainingArtifact4)), (TrainingArtifact5::record(), TrainingArtifactUnion::TrainingArtifact5(TrainingArtifact5)), (TrainingArtifact6::record(), TrainingArtifactUnion::TrainingArtifact6(TrainingArtifact6)), (TrainingArtifact7::record(), TrainingArtifactUnion::TrainingArtifact7(TrainingArtifact7)), (TrainingArtifact8::record(), TrainingArtifactUnion::TrainingArtifact8(TrainingArtifact8)), (TrainingArtifact9::record(), TrainingArtifactUnion::TrainingArtifact9(TrainingArtifact9)), ] } #[derive(Debug)] pub struct TrainingArtifact0; impl Timeline for TrainingArtifact0 {} impl WeaponAttack for TrainingArtifact0 {} impl TrainingArtifact0 { pub fn record() -> Artifact { Artifact::default() .name("Atk70 Em280 Er78").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(33.3333)) .em(SCORE.em(33.3333)) .er(SCORE.er(33.3333)) } } #[derive(Debug)] pub struct TrainingArtifact1; impl Timeline for TrainingArtifact1 {} impl WeaponAttack for TrainingArtifact1 {} impl TrainingArtifact1 { pub fn record() -> Artifact { Artifact::default() .name("Atk168 Em167").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(80.)) .em(SCORE.em(20.)) } } #[derive(Debug)] pub struct TrainingArtifact2; impl Timeline for TrainingArtifact2 {} impl WeaponAttack for TrainingArtifact2 {} impl TrainingArtifact2 { pub fn record() -> Artifact { Artifact::default() .name("Atk168 Er46").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(80.)) .er(SCORE.er(20.)) } } #[derive(Debug)] pub struct TrainingArtifact3; impl Timeline for TrainingArtifact3 {} impl WeaponAttack for TrainingArtifact3 {} impl TrainingArtifact3 { pub fn record() -> Artifact { Artifact::default() .name("Atk41 Em671").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(20.)) .em(SCORE.em(80.)) } } #[derive(Debug)] pub struct TrainingArtifact4; impl Timeline for TrainingArtifact4 {} impl WeaponAttack for TrainingArtifact4 {} impl TrainingArtifact4 { pub fn record() -> Artifact { Artifact::default() .name("Em671 Er46").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .em(SCORE.em(80.)) .er(SCORE.er(20.)) } } #[derive(Debug)] pub struct TrainingArtifact5; impl Timeline for TrainingArtifact5 {} impl WeaponAttack for TrainingArtifact5 {} impl TrainingArtifact5 { pub fn record() -> Artifact { Artifact::default() .name("Atk42 Er186").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(20.)) .er(SCORE.er(80.)) } } #[derive(Debug)] pub struct TrainingArtifact6; impl Timeline for TrainingArtifact6 {} impl WeaponAttack for TrainingArtifact6 {} impl TrainingArtifact6 { pub fn record() -> Artifact { Artifact::default() .name("Em167 Er186").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .em(SCORE.em(20.)) .er(SCORE.er(80.)) } } #[derive(Debug)] pub struct TrainingArtifact7; impl Timeline for TrainingArtifact7 {} impl WeaponAttack for TrainingArtifact7 {} impl TrainingArtifact7 { pub fn record() -> Artifact { Artifact::default() .name("Atk105 Em420").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(50.)) .em(SCORE.em(50.)) } } #[derive(Debug)] pub struct TrainingArtifact8; impl Timeline for TrainingArtifact8 {} impl WeaponAttack for TrainingArtifact8 {} impl TrainingArtifact8 { pub fn record() -> Artifact { Artifact::default() .name("Atk105 Er116").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(50.)) .er(SCORE.er(50.)) } } #[derive(Debug)] pub struct TrainingArtifact9; impl Timeline for TrainingArtifact9 {} impl WeaponAttack for TrainingArtifact9 {} impl TrainingArtifact9 { pub fn record() -> Artifact { Artifact::default() .name("Em420 Er116").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .em(SCORE.em(50.)) .er(SCORE.er(50.)) } } #[derive(Debug)] pub struct TrainingArtifact10; impl Timeline for TrainingArtifact10 {} impl WeaponAttack for TrainingArtifact10 {} impl TrainingArtifact10 { pub fn record() -> Artifact { Artifact::default() .name("Atk210").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .atk(SCORE.atk(100.)) } } #[derive(Debug)] pub struct TrainingArtifact11; impl Timeline for TrainingArtifact11 {} impl WeaponAttack for TrainingArtifact11 {} impl TrainingArtifact11 { pub fn record() -> Artifact { Artifact::default() .name("Em839").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .em(SCORE.em(100.)) } } #[derive(Debug)] pub struct TrainingArtifact12; impl Timeline for TrainingArtifact12 {} impl WeaponAttack for TrainingArtifact12 {} impl TrainingArtifact12 { pub fn record() -> Artifact { Artifact::default() .name("Er233").version(1.0).preference(&[]) .elemental_dmg(15.).physical_dmg(25.).cr(20.) .er(SCORE.er(100.)) } }
TrainingArtifact2(x) => x, TrainingArtifact3(x) => x, TrainingArtifact4(x) => x, TrainingArtifact5(x) => x, TrainingArtifact6(x) => x, TrainingArtifact7(x) => x, TrainingArtifact8(x) => x, TrainingArtifact9(x) => x, } }
function_block-function_prefix_line
[]
Rust
common/functions/src/scalars/dates/date.rs
flaneur2020/databend
b2758473f59bd23f1a278699e6cf292724c204cd
use common_datavalues::DataValueArithmeticOperator; use common_exception::Result; use super::interval_function::MonthsArithmeticFunction; use super::interval_function::SecondsArithmeticFunction; use super::now::NowFunction; use super::RoundFunction; use super::ToStartOfISOYearFunction; use super::ToStartOfMonthFunction; use super::ToStartOfQuarterFunction; use super::ToStartOfWeekFunction; use super::ToStartOfYearFunction; use super::ToYYYYMMDDFunction; use super::ToYYYYMMDDhhmmssFunction; use super::ToYYYYMMFunction; use super::TodayFunction; use super::TomorrowFunction; use super::YesterdayFunction; use crate::scalars::FactoryFuncRef; #[derive(Clone)] pub struct DateFunction {} impl DateFunction { pub fn register(map: FactoryFuncRef) -> Result<()> { let mut map = map.write(); map.insert("today".into(), TodayFunction::try_create); map.insert("yesterday".into(), YesterdayFunction::try_create); map.insert("tomorrow".into(), TomorrowFunction::try_create); map.insert("now".into(), NowFunction::try_create); map.insert("toYYYYMM".into(), ToYYYYMMFunction::try_create); map.insert("toYYYYMMDD".into(), ToYYYYMMDDFunction::try_create); map.insert( "toYYYYMMDDhhmmss".into(), ToYYYYMMDDhhmmssFunction::try_create, ); map.insert("toStartOfYear".into(), ToStartOfYearFunction::try_create); map.insert( "toStartOfISOYear".into(), ToStartOfISOYearFunction::try_create, ); map.insert( "toStartOfQuarter".into(), ToStartOfQuarterFunction::try_create, ); map.insert("toStartOfWeek".into(), ToStartOfWeekFunction::try_create); map.insert("toStartOfMonth".into(), ToStartOfMonthFunction::try_create); { map.insert("toStartOfSecond".into(), |display_name| { RoundFunction::try_create(display_name, 1) }); map.insert("toStartOfMinute".into(), |display_name| { RoundFunction::try_create(display_name, 60) }); map.insert("toStartOfFiveMinutes".into(), |display_name| { RoundFunction::try_create(display_name, 5 * 60) }); map.insert("toStartOfTenMinutes".into(), |display_name| { RoundFunction::try_create(display_name, 10 * 60) }); map.insert("toStartOfFifteenMinutes".into(), |display_name| { RoundFunction::try_create(display_name, 15 * 60) }); map.insert("timeSlot".into(), |display_name| { RoundFunction::try_create(display_name, 30 * 60) }); map.insert("toStartOfHour".into(), |display_name| { RoundFunction::try_create(display_name, 60 * 60) }); map.insert("toStartOfDay".into(), |display_name| { RoundFunction::try_create(display_name, 60 * 60 * 24) }); } { map.insert("addYears".into(), |display_name| { MonthsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Plus, 12, /* one year is 12 months */ ) }); map.insert("subtractYears".into(), |display_name| { MonthsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Minus, 12, /* one year is 12 months */ ) }); map.insert("addMonths".into(), |display_name| { MonthsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Plus, 1, ) }); map.insert("subtractMonths".into(), |display_name| { MonthsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Minus, 1, ) }); map.insert("addDays".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Plus, 24 * 3600, /* one day is 24 * 3600 seconds */ ) }); map.insert("subtractDays".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Minus, 24 * 3600, /* one day is 24 * 3600 seconds */ ) }); map.insert("addHours".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Plus, 3600, /* one hour is 3600 seconds */ ) }); map.insert("subtractHours".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Minus, 3600, /* one hour is 3600 seconds */ ) }); map.insert("addMinutes".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Plus, 60, /* one minute is 60 seconds */ ) }); map.insert("subtractMinutes".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Minus, 60, /* one minute is 60 seconds */ ) }); map.insert("addSeconds".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Plus, 1, ) }); map.insert("subtractSeconds".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Minus, 1, ) }); } Ok(()) } }
use common_datavalues::DataValueArithmeticOperator; use common_exception::Result; use super::interval_function::MonthsArithmeticFunction; use super::interval_function::SecondsArithmeticFunction; use super::now::NowFunction; use super::RoundFunction; use super::ToStartOfISOYearFunction; use super::ToStartOfMonthFunction; use super::ToStartOfQuarterFunction; use super::ToStar
}); map.insert("toStartOfFifteenMinutes".into(), |display_name| { RoundFunction::try_create(display_name, 15 * 60) }); map.insert("timeSlot".into(), |display_name| { RoundFunction::try_create(display_name, 30 * 60) }); map.insert("toStartOfHour".into(), |display_name| { RoundFunction::try_create(display_name, 60 * 60) }); map.insert("toStartOfDay".into(), |display_name| { RoundFunction::try_create(display_name, 60 * 60 * 24) }); } { map.insert("addYears".into(), |display_name| { MonthsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Plus, 12, /* one year is 12 months */ ) }); map.insert("subtractYears".into(), |display_name| { MonthsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Minus, 12, /* one year is 12 months */ ) }); map.insert("addMonths".into(), |display_name| { MonthsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Plus, 1, ) }); map.insert("subtractMonths".into(), |display_name| { MonthsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Minus, 1, ) }); map.insert("addDays".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Plus, 24 * 3600, /* one day is 24 * 3600 seconds */ ) }); map.insert("subtractDays".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Minus, 24 * 3600, /* one day is 24 * 3600 seconds */ ) }); map.insert("addHours".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Plus, 3600, /* one hour is 3600 seconds */ ) }); map.insert("subtractHours".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Minus, 3600, /* one hour is 3600 seconds */ ) }); map.insert("addMinutes".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Plus, 60, /* one minute is 60 seconds */ ) }); map.insert("subtractMinutes".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Minus, 60, /* one minute is 60 seconds */ ) }); map.insert("addSeconds".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Plus, 1, ) }); map.insert("subtractSeconds".into(), |display_name| { SecondsArithmeticFunction::try_create( display_name, DataValueArithmeticOperator::Minus, 1, ) }); } Ok(()) } }
tOfWeekFunction; use super::ToStartOfYearFunction; use super::ToYYYYMMDDFunction; use super::ToYYYYMMDDhhmmssFunction; use super::ToYYYYMMFunction; use super::TodayFunction; use super::TomorrowFunction; use super::YesterdayFunction; use crate::scalars::FactoryFuncRef; #[derive(Clone)] pub struct DateFunction {} impl DateFunction { pub fn register(map: FactoryFuncRef) -> Result<()> { let mut map = map.write(); map.insert("today".into(), TodayFunction::try_create); map.insert("yesterday".into(), YesterdayFunction::try_create); map.insert("tomorrow".into(), TomorrowFunction::try_create); map.insert("now".into(), NowFunction::try_create); map.insert("toYYYYMM".into(), ToYYYYMMFunction::try_create); map.insert("toYYYYMMDD".into(), ToYYYYMMDDFunction::try_create); map.insert( "toYYYYMMDDhhmmss".into(), ToYYYYMMDDhhmmssFunction::try_create, ); map.insert("toStartOfYear".into(), ToStartOfYearFunction::try_create); map.insert( "toStartOfISOYear".into(), ToStartOfISOYearFunction::try_create, ); map.insert( "toStartOfQuarter".into(), ToStartOfQuarterFunction::try_create, ); map.insert("toStartOfWeek".into(), ToStartOfWeekFunction::try_create); map.insert("toStartOfMonth".into(), ToStartOfMonthFunction::try_create); { map.insert("toStartOfSecond".into(), |display_name| { RoundFunction::try_create(display_name, 1) }); map.insert("toStartOfMinute".into(), |display_name| { RoundFunction::try_create(display_name, 60) }); map.insert("toStartOfFiveMinutes".into(), |display_name| { RoundFunction::try_create(display_name, 5 * 60) }); map.insert("toStartOfTenMinutes".into(), |display_name| { RoundFunction::try_create(display_name, 10 * 60)
random
[ { "content": "-- {ErrorCode 3, but it not work, because it's trimed in msql-srv}\n\nUSE not_exists_db;\n\nUSE default;\n\nUSE system;\n", "file_path": "tests/suites/0_stateless/07_0000_use_database.sql", "rank": 0, "score": 56735.32093857074 }, { "content": "use common_streams::SendableDataB...
Rust
src/raycasting_engine.rs
N-Hoque/rustenstein3D
97a483eeb20977a4d241d7b68e5be12e673fcad9
use rsfml::{ graphics::{ Color, PrimitiveType, RenderStates, RenderTarget, RenderWindow, Vertex, VertexArray, }, system::{Vector2f, Vector2i}, window::Key, }; use crate::{event_handler::EventHandler, map::Map, texture_loader::TextureLoader}; pub struct RaycastEngine { player_position: Vector2f, vector_direction: Vector2f, cam_plane: Vector2f, map: Map, window_size: Vector2f, vertex_array: Vec<Box<VertexArray>>, textures_id: Vec<i32>, ground: Vec<Box<VertexArray>>, sky: Vec<Box<VertexArray>>, no_ground: bool, } impl RaycastEngine { pub fn new(map: Map, window_size: &Vector2f, no_ground: bool) -> RaycastEngine { RaycastEngine { player_position: Vector2f { x: 22., y: 12. }, vector_direction: Vector2f { x: -1., y: 0. }, cam_plane: Vector2f { x: 0., y: 0.66 }, map, window_size: Vector2f { x: window_size.x, y: window_size.y - 80., }, vertex_array: RaycastEngine::create_line_array(window_size), textures_id: Vec::new(), ground: RaycastEngine::create_ground_array(window_size), sky: RaycastEngine::create_ground_array(window_size), no_ground, } } pub fn update(&mut self, event_handler: &EventHandler) { self.textures_id.clear(); let ray_pos = self.player_position.clone(); let mut ray_dir = Vector2f { x: 0., y: 0. }; let mut map_pos = Vector2i { x: 0, y: 0 }; let mut side_dist = Vector2f { x: 0., y: 0. }; let mut delta_dist = Vector2f { x: 0., y: 0. }; let mut step = Vector2i { x: 0, y: 0 }; let mut draw_start: i32 = 0; let mut draw_end: i32 = 0; let mut camera_x: f32; let mut side: i32; let mut perpendicular_wall_dist: f32 = 0.; let mut wall_x: f32 = 0.; for x in 0..(self.window_size.x as i32) { camera_x = 2. * x as f32 / self.window_size.x - 1.; ray_dir.x = self.vector_direction.x + self.cam_plane.x * camera_x; ray_dir.y = self.vector_direction.y + self.cam_plane.y * camera_x; map_pos.x = ray_pos.x as i32; map_pos.y = ray_pos.y as i32; delta_dist.x = (1. + (ray_dir.y * ray_dir.y) / (ray_dir.x * ray_dir.x)).sqrt(); delta_dist.y = (1. + (ray_dir.x * ray_dir.x) / (ray_dir.y * ray_dir.y)).sqrt(); side = 0; self.calculate_step( &ray_dir, &mut step, &ray_pos, &map_pos, &delta_dist, &mut side_dist, ); self.hit_wall( &mut map_pos, &mut side_dist, &mut step, &mut delta_dist, &mut side, ); self.calculate_wall_height( side, &mut draw_start, &mut draw_end, &map_pos, &ray_pos, &ray_dir, &step, &mut perpendicular_wall_dist, ); self.calculate_wall_texture( side, &ray_dir, x, &map_pos, &step, &ray_pos, draw_end, draw_start, &mut wall_x, ); if !self.no_ground { self.calculate_ground( side, &map_pos, wall_x, &ray_dir, perpendicular_wall_dist, &mut draw_end, x, ); } } self.update_events(event_handler); } fn calculate_ground( &mut self, side: i32, map_pos: &Vector2i, wall_x: f32, ray_dir: &Vector2f, perpendicular_wall_dist: f32, draw_end: &mut i32, x: i32, ) { if *draw_end < 0 { *draw_end = self.window_size.y as i32; } self.ground.get_mut(x as usize).unwrap().clear(); self.sky.get_mut(x as usize).unwrap().clear(); let mut vertex = Vertex::default(); let mut current_dist: f32; let mut weight: f32; let mut current_floor = Vector2f { x: 0., y: 0. }; let mut tex_coord = Vector2f { x: 0., y: 0. }; let mut pos = Vector2f { x: x as f32, y: 0. }; let dist_player: f32 = 0.; let (map_pos_x, map_pos_y) = (map_pos.x as f32, map_pos.y as f32); let floor = if side == 0 && ray_dir.x > 0. { Vector2f { x: map_pos_x, y: map_pos_y + wall_x, } } else if side == 0 && ray_dir.x < 0. { Vector2f { x: map_pos_x + 1., y: map_pos_y + wall_x, } } else if side == 1 && ray_dir.y > 0. { Vector2f { x: map_pos_x + wall_x, y: map_pos_y, } } else { Vector2f { x: map_pos_x + wall_x, y: map_pos_y + 1., } }; for y in (*draw_end + 1)..(self.window_size.y as i32) { current_dist = self.window_size.y / (2. * y as f32 - self.window_size.y as f32); weight = (current_dist - dist_player) / (perpendicular_wall_dist - dist_player); current_floor.x = weight * floor.x + (1. - weight) * self.player_position.x; current_floor.y = weight * floor.y + (1. - weight) * self.player_position.y; tex_coord.x = ((current_floor.x * 128.) as i32 % 128) as f32; tex_coord.y = ((current_floor.y * 128.) as i32 % 128) as f32; pos.y = y as f32; vertex.position.x = pos.x; vertex.position.y = pos.y; vertex.tex_coords.x = tex_coord.x; vertex.tex_coords.y = tex_coord.y; self.ground.get_mut(x as usize).unwrap().append(&vertex); pos.y = self.window_size.y - y as f32; vertex.position.x = pos.x; vertex.position.y = pos.y; vertex.tex_coords.x = tex_coord.x; vertex.tex_coords.y = tex_coord.y; self.sky.get_mut(x as usize).unwrap().append(&vertex); } } fn calculate_wall_height( &mut self, side: i32, draw_start: &mut i32, draw_end: &mut i32, map_pos: &Vector2i, ray_pos: &Vector2f, ray_dir: &Vector2f, step: &Vector2i, perpendicular_wall_dist: &mut f32, ) { *perpendicular_wall_dist = if side == 0 { (map_pos.x as f32 - ray_pos.x + (1 - step.x) as f32 / 2.) / ray_dir.x } else { (map_pos.y as f32 - ray_pos.y + (1 - step.y) as f32 / 2.) / ray_dir.y } .abs(); let line_height: i32 = if *perpendicular_wall_dist as i32 == 0 { self.window_size.y as i32 } else { ((self.window_size.y / *perpendicular_wall_dist) as i32).abs() }; *draw_start = (self.window_size.y as i32 / 2) - (line_height / 2); if *draw_start < 0 { *draw_start = 0; } *draw_end = line_height / 2 + self.window_size.y as i32 / 2; if *draw_end > self.window_size.y as i32 { *draw_end = self.window_size.y as i32 - 1; } } fn calculate_wall_texture( &mut self, side: i32, ray_dir: &Vector2f, x: i32, map_pos: &Vector2i, step: &Vector2i, ray_pos: &Vector2f, draw_end: i32, draw_start: i32, wall_x: &mut f32, ) { let mut texture_id = self .map .get_block(map_pos) .expect(&format!("ERROR: Cannot get block ID {:?}", map_pos)); *wall_x = if side == 1 { ray_pos.x + ((map_pos.y as f32 - ray_pos.y + (1. - step.y as f32) / 2.) / ray_dir.y) * ray_dir.x } else { ray_pos.y + ((map_pos.x as f32 - ray_pos.x + (1. - step.x as f32) / 2.) / ray_dir.x) * ray_dir.y }; *wall_x -= wall_x.floor(); let mut texture_x = (*wall_x * 128.) as i32; if side == 0 && ray_dir.x > 0. { texture_x = 128 - texture_x - 1; } if side == 1 && ray_dir.y < 0. { texture_x = 128 - texture_x - 1; } if side == 1 { texture_id += 5; } self.textures_id.push(texture_id); self.vertex_array.get_mut(x as usize).unwrap().clear(); self.vertex_array .get_mut(x as usize) .unwrap() .append(&Vertex::new( Vector2f::new(x as f32, draw_end as f32), Color::WHITE, Vector2f::new(texture_x as f32, 128.), )); self.vertex_array .get_mut(x as usize) .unwrap() .append(&Vertex::new( Vector2f::new(x as f32, draw_start as f32), Color::WHITE, Vector2f::new(texture_x as f32, 0.), )); } fn calculate_step( &self, ray_dir: &Vector2f, step: &mut Vector2i, ray_pos: &Vector2f, map_pos: &Vector2i, delta_dist: &Vector2f, side_dist: &mut Vector2f, ) { if ray_dir.x < 0. { step.x = -1; side_dist.x = (ray_pos.x - map_pos.x as f32) * delta_dist.x; } else { step.x = 1; side_dist.x = (map_pos.x as f32 + 1. - ray_pos.x) * delta_dist.x; } if ray_dir.y < 0. { step.y = -1; side_dist.y = (ray_pos.y - map_pos.y as f32) * delta_dist.y; } else { step.y = 1; side_dist.y = (map_pos.y as f32 + 1. - ray_pos.y) * delta_dist.y; } } fn hit_wall( &self, map_pos: &mut Vector2i, side_dist: &mut Vector2f, step: &mut Vector2i, delta_dist: &mut Vector2f, side: &mut i32, ) { let mut hit: bool = false; while !hit { if side_dist.x < side_dist.y { side_dist.x += delta_dist.x; map_pos.x += step.x; *side = 0; } else { side_dist.y += delta_dist.y; map_pos.y += step.y; *side = 1; } hit = match self.map.get_block(map_pos) { Some(block) if block == 0 => false, _ => true, }; } } fn update_events(&mut self, event_handler: &EventHandler) { let mut pos = Vector2i { x: 0, y: 0 }; if event_handler.is_key_pressed(Key::W) { pos.x = (self.player_position.x + (self.vector_direction.x * 0.1)) as i32; pos.y = self.player_position.y as i32; if self .map .get_block(&pos) .expect(&format!("ERROR: Cannot get block ID {:?}", &pos)) == 0 { self.player_position.x += self.vector_direction.x * 0.1; } pos.y = (self.player_position.y + (self.vector_direction.y * 0.1)) as i32; pos.x = self.player_position.x as i32; if self .map .get_block(&pos) .expect(&format!("ERROR: Cannot get block ID {:?}", &pos)) == 0 { self.player_position.y += self.vector_direction.y * 0.1; } } if event_handler.is_key_pressed(Key::S) { pos.x = (self.player_position.x - (self.vector_direction.x * 0.1)) as i32; pos.y = self.player_position.y as i32; if self .map .get_block(&pos) .expect(&format!("ERROR: Cannot get block ID {:?}", &pos)) == 0 { self.player_position.x -= self.vector_direction.x * 0.1; } pos.y = (self.player_position.y - (self.vector_direction.y * 0.1)) as i32; pos.x = self.player_position.x as i32; if self .map .get_block(&pos) .expect(&format!("ERROR: Cannot get block ID {:?}", &pos)) == 0 { self.player_position.y -= self.vector_direction.y * 0.1; } } let mouse_move = match event_handler.has_mouse_moved_event() { Some((x, _)) => x as f32 - (self.window_size.x / 2.) as f32, None => 0., } / -250.; let old_dir_x = self.vector_direction.x; self.vector_direction.x = self.vector_direction.x * (mouse_move).cos() - self.vector_direction.y * (mouse_move).sin(); self.vector_direction.y = old_dir_x * (mouse_move).sin() + self.vector_direction.y * (mouse_move).cos(); let old_cam_plane_x = self.cam_plane.x; self.cam_plane.x = self.cam_plane.x * (mouse_move).cos() - self.cam_plane.y * (mouse_move).sin(); self.cam_plane.y = old_cam_plane_x * (mouse_move).sin() + self.cam_plane.y * (mouse_move).cos(); } fn create_line_array(window_size: &Vector2f) -> Vec<Box<VertexArray>> { let mut lines: Vec<Box<VertexArray>> = Vec::new(); for _ in 0..(window_size.x as i32) { let mut line: Box<VertexArray> = Box::new(VertexArray::default()); line.set_primitive_type(PrimitiveType::Lines); lines.push(line); } lines } fn create_ground_array(window_size: &Vector2f) -> Vec<Box<VertexArray>> { let mut lines: Vec<Box<VertexArray>> = Vec::new(); for _ in 0..(window_size.x as i32) { let line: Box<VertexArray> = Box::new(VertexArray::default()); lines.push(line); } lines } pub fn get_player_pos(&self) -> Vector2f { self.player_position.clone() } pub fn draw<'r>(&self, render_window: &'r mut RenderWindow, texture_loader: &'r TextureLoader) { let mut render_states = RenderStates::default(); for (line_idx, line) in self.vertex_array.iter().enumerate() { render_states.texture = Some(texture_loader.get_texture(self.textures_id[line_idx as usize])); render_window.draw_with_renderstates(&*(*line), render_states); } render_states.texture = Some(texture_loader.get_texture(0)); for gr in self.ground.iter() { render_window.draw_with_renderstates(&*(*gr), render_states); } render_states.texture = Some(texture_loader.get_texture(11)); for sky in self.sky.iter() { render_window.draw_with_renderstates(&*(*sky), render_states); } } }
use rsfml::{ graphics::{ Color, PrimitiveType, RenderStates, RenderTarget, RenderWindow, Vertex, VertexArray, }, system::{Vector2f, Vector2i}, window::Key, }; use crate::{event_handler::EventHandler, map::Map, texture_loader::TextureLoader}; pub struct RaycastEngine { player_position: Vector2f, vector_direction: Vector2f, cam_plane: Vector2f, map: Map, window_size: Vector2f, vertex_array: Vec<Box<VertexArray>>, textures_id: Vec<i32>, ground: Vec<Box<VertexArray>>, sky: Vec<Box<VertexArray>>, no_ground: bool, } impl RaycastEngine { pub fn new(map: Map, window_size: &Vector2f, no_ground: bool) -> RaycastEngine { RaycastEngine { player_position: Vector2f { x: 22., y: 12. }, vector_direction: Vector2f { x: -1., y: 0. }, cam_plane: Vector2f { x: 0., y: 0.66 }, map, window_size: Vector2f { x: window_size.x, y: window_size.y - 80., }, vertex_array: RaycastEngine::create_line_array(window_size), textures_id: Vec::new(), ground: RaycastEngine::create_ground_array(window_size), sky: RaycastEngine::create_ground_array(window_size), no_ground, } } pub fn update(&mut self, event_handler: &EventHandler) { self.textures_id.clear(); let ray_pos = self.player_position.clone(); let mut ray_dir = Vector2f { x: 0., y: 0. }; let mut map_pos = Vector2i { x: 0, y: 0 }; let mut side_dist = Vector2f { x: 0., y: 0. }; let mut delta_dist = Vector2f { x: 0., y: 0. }; let mut step = Vector2i { x: 0, y: 0 }; let mut draw_start: i32 = 0; let mut draw_end: i32 = 0; let mut camera_x: f32; let mut side: i32; let mut perpendicular_wall_dist: f32 = 0.; let mut wall_x: f32 = 0.; for x in 0..(self.window_size.x as i32) { camera_x = 2. * x as f32 / self.window_size.x - 1.; ray_dir.x = self.vector_direction.x + self.cam_plane.x * camera_x; ray_dir.y = self.vector_direction.y + self.cam_plane.y * camera_x; map_pos.x = ray_pos.x as i32; map_pos.y = ray_pos.y as i32; delta_dist.x = (1. + (ray_dir.y * ray_dir.y) / (ray_dir.x * ray_dir.x)).sqrt(); delta_dist.y = (1. + (ray_dir.x * ray_dir.x) / (ray_dir.y * ray_dir.y)).sqrt(); side = 0; self.calculate_step( &ray_dir, &mut step, &ray_pos, &map_pos, &delta_dist, &mut side_dist, ); self.hit_wall( &mut map_pos, &mut side_dist, &mut step, &mut delta_dist, &mut side, ); self.calculate_wall_height( side, &mut draw_start, &mut draw_end, &map_pos, &ray_pos, &ray_dir, &step, &mut perpendicular_wall_dist, ); self.calculate_wall_texture( side, &ray_dir, x, &map_pos, &step, &ray_pos, draw_end, draw_start, &mut wall_x, ); if !self.no_ground { self.calculate_ground( side, &map_pos, wall_x, &ray_dir, perpendicular_wall_dist, &mut draw_end, x, ); } } self.update_events(event_handler); } fn calculate_ground( &mut self, side: i32, map_pos: &Vector2i, wall_x: f32, ray_dir: &Vector2f, perpendicular_wall_dist: f32, draw_end: &mut i32, x: i32, ) { if *draw_end < 0 { *draw_end = self.window_size.y as i32; } self.ground.get_mut(x as usize).unwrap().clear(); self.sky.get_mut(x as usize).unwrap().clear(); let mut vertex = Vertex::default(); let mut current_dist: f32; let mut weight: f32; let mut current_floor = Vector2f { x: 0., y: 0. }; let mut tex_coord = Vector2f { x: 0., y: 0. }; let mut pos = Vector2f { x: x as f32, y: 0. }; let dist_player: f32 = 0.; let (map_pos_x, map_pos_y) = (map_pos.x as f32, map_pos.y as f32); let floor = if side == 0 && ray_dir.x > 0. { Vector2f { x: map_pos_x, y: map_pos_y + wall_x, } } else if side == 0 && ray_dir.x < 0. { Vector2f { x: map_pos_x + 1., y: map_pos_y + wall_x, } } else if side == 1 && ray_dir.y > 0. { Vector2f { x: map_pos_x + wall_x, y: map_pos_y, } } else { Vector2f { x: map_pos_x + wall_x, y: map_pos_y + 1., } }; for y in (*draw_end + 1)..(self.window_size.y as i32) { current_dist = self.window_size.y / (2. * y as f32 - self.window_size.y as f32); weight = (current_dist - dist_player) / (perpendicular_wall_dist - dist_player); current_floor.x = weight * floor.x + (1. - weight) * self.player_position.x; current_floor.y = weight * floor.y + (1. - weight) * self.player_position.y; tex_coord.x = ((current_floor.x * 128.) as i32 % 128) as f32; tex_coord.y = ((current_floor.y * 128.) as i32 % 128) as f32; pos.y = y as f32; vertex.position.x = pos.x; vertex.position.y = pos.y; vertex.tex_coords.x = tex_coord.x; vertex.tex_coords.y = tex_coord.y; self.ground.get_mut(x as usize).unwrap().append(&vertex); pos.y = self.window_size.y - y as f32; vertex.position.x = pos.x; vertex.position.y = pos.y; vertex.tex_coords.x = tex_coord.x; vertex.tex_coords.y = tex_coord.y; self.sky.get_mut(x as usize).unwrap().append(&vertex); } } fn calculate_wall_height( &mut self, side: i32, draw_start: &mut i32, draw_end: &mut i32, map_pos: &Vector2i, ray_pos: &Vector2f, ray_dir: &Vector2f, step: &Vector2i, perpendicular_wall_dist: &mut f32, ) { *perpendicular_wall_dist = if side == 0 { (map_pos.x as f32 - ray_pos.x + (1 - step.x) as f32 / 2.) / ray_dir.x } else { (map_pos.y as f32 - ray_pos.y + (1 - step.y) as f32 / 2.) / ray_dir.y } .abs(); let line_height: i32 = if *perpendicular_wall_dist as i32 == 0 { self.window_size.y as i32 } else { ((self.window_size.y / *perpendicular_wall_dist) as i32).abs() }; *draw_start = (self.window_size.y as i32 / 2) - (line_height / 2); if *draw_start < 0 { *draw_start = 0; } *draw_end = line_height / 2 + self.window_size.y as i32 / 2; if *draw_end > self.window_size.y as i32 { *draw_end = self.window_size.y as i32 - 1; } } fn calculate_wall_texture( &mut self, side: i32, ray_dir: &Vector2f, x: i32, map_pos: &Vector2i, step: &Vector2i, ray_pos: &Vector2f, draw_end: i32, draw_start: i32, wall_x: &mut f32, ) { let mut texture_id = self .map .get_block(map_pos) .expect(&format!("ERROR: Cannot get block ID {:?}", map_pos)); *wall_x = if side == 1 { ray_pos.x + ((map_pos.y as f32 - ray_pos.y + (1. - step.y as f32) / 2.) / ray_dir.y) * ray_dir.x } else { ray_pos.y + ((map_pos.x as f32 - ray_pos.x + (1. - step.x as f32) / 2.) / ray_dir.x) * ray_dir.y }; *wall_x -= wall_x.floor(); let mut texture_x = (*wall_x * 128.) as i32; if side == 0 && ray_dir.x > 0. { texture_x = 128 - texture_x - 1; } if side == 1 && ray_dir.y < 0. { texture_x = 128 - texture_x - 1; } if side == 1 { texture_id += 5; } self.textures_id.push(texture_id); self.vertex_array.get_mut(x as usize).unwrap().clear(); self.vertex_array .get_mut(x as usize) .unwrap() .append(&Vertex::new( Vector2f::new(x as f32, draw_end as f32), Color::WHITE, Vector2f::new(texture_x as f32, 128.), )); self.vertex_array .get_mut(x as usize) .unwrap() .append(&Vertex::new( Vector2f::new(x as f32, draw_start as f32), Color::WHITE, Vector2f::new(texture_x as f32, 0.), )); }
fn hit_wall( &self, map_pos: &mut Vector2i, side_dist: &mut Vector2f, step: &mut Vector2i, delta_dist: &mut Vector2f, side: &mut i32, ) { let mut hit: bool = false; while !hit { if side_dist.x < side_dist.y { side_dist.x += delta_dist.x; map_pos.x += step.x; *side = 0; } else { side_dist.y += delta_dist.y; map_pos.y += step.y; *side = 1; } hit = match self.map.get_block(map_pos) { Some(block) if block == 0 => false, _ => true, }; } } fn update_events(&mut self, event_handler: &EventHandler) { let mut pos = Vector2i { x: 0, y: 0 }; if event_handler.is_key_pressed(Key::W) { pos.x = (self.player_position.x + (self.vector_direction.x * 0.1)) as i32; pos.y = self.player_position.y as i32; if self .map .get_block(&pos) .expect(&format!("ERROR: Cannot get block ID {:?}", &pos)) == 0 { self.player_position.x += self.vector_direction.x * 0.1; } pos.y = (self.player_position.y + (self.vector_direction.y * 0.1)) as i32; pos.x = self.player_position.x as i32; if self .map .get_block(&pos) .expect(&format!("ERROR: Cannot get block ID {:?}", &pos)) == 0 { self.player_position.y += self.vector_direction.y * 0.1; } } if event_handler.is_key_pressed(Key::S) { pos.x = (self.player_position.x - (self.vector_direction.x * 0.1)) as i32; pos.y = self.player_position.y as i32; if self .map .get_block(&pos) .expect(&format!("ERROR: Cannot get block ID {:?}", &pos)) == 0 { self.player_position.x -= self.vector_direction.x * 0.1; } pos.y = (self.player_position.y - (self.vector_direction.y * 0.1)) as i32; pos.x = self.player_position.x as i32; if self .map .get_block(&pos) .expect(&format!("ERROR: Cannot get block ID {:?}", &pos)) == 0 { self.player_position.y -= self.vector_direction.y * 0.1; } } let mouse_move = match event_handler.has_mouse_moved_event() { Some((x, _)) => x as f32 - (self.window_size.x / 2.) as f32, None => 0., } / -250.; let old_dir_x = self.vector_direction.x; self.vector_direction.x = self.vector_direction.x * (mouse_move).cos() - self.vector_direction.y * (mouse_move).sin(); self.vector_direction.y = old_dir_x * (mouse_move).sin() + self.vector_direction.y * (mouse_move).cos(); let old_cam_plane_x = self.cam_plane.x; self.cam_plane.x = self.cam_plane.x * (mouse_move).cos() - self.cam_plane.y * (mouse_move).sin(); self.cam_plane.y = old_cam_plane_x * (mouse_move).sin() + self.cam_plane.y * (mouse_move).cos(); } fn create_line_array(window_size: &Vector2f) -> Vec<Box<VertexArray>> { let mut lines: Vec<Box<VertexArray>> = Vec::new(); for _ in 0..(window_size.x as i32) { let mut line: Box<VertexArray> = Box::new(VertexArray::default()); line.set_primitive_type(PrimitiveType::Lines); lines.push(line); } lines } fn create_ground_array(window_size: &Vector2f) -> Vec<Box<VertexArray>> { let mut lines: Vec<Box<VertexArray>> = Vec::new(); for _ in 0..(window_size.x as i32) { let line: Box<VertexArray> = Box::new(VertexArray::default()); lines.push(line); } lines } pub fn get_player_pos(&self) -> Vector2f { self.player_position.clone() } pub fn draw<'r>(&self, render_window: &'r mut RenderWindow, texture_loader: &'r TextureLoader) { let mut render_states = RenderStates::default(); for (line_idx, line) in self.vertex_array.iter().enumerate() { render_states.texture = Some(texture_loader.get_texture(self.textures_id[line_idx as usize])); render_window.draw_with_renderstates(&*(*line), render_states); } render_states.texture = Some(texture_loader.get_texture(0)); for gr in self.ground.iter() { render_window.draw_with_renderstates(&*(*gr), render_states); } render_states.texture = Some(texture_loader.get_texture(11)); for sky in self.sky.iter() { render_window.draw_with_renderstates(&*(*sky), render_states); } } }
fn calculate_step( &self, ray_dir: &Vector2f, step: &mut Vector2i, ray_pos: &Vector2f, map_pos: &Vector2i, delta_dist: &Vector2f, side_dist: &mut Vector2f, ) { if ray_dir.x < 0. { step.x = -1; side_dist.x = (ray_pos.x - map_pos.x as f32) * delta_dist.x; } else { step.x = 1; side_dist.x = (map_pos.x as f32 + 1. - ray_pos.x) * delta_dist.x; } if ray_dir.y < 0. { step.y = -1; side_dist.y = (ray_pos.y - map_pos.y as f32) * delta_dist.y; } else { step.y = 1; side_dist.y = (map_pos.y as f32 + 1. - ray_pos.y) * delta_dist.y; } }
function_block-full_function
[ { "content": "pub fn parse_arguments() -> ParsedResult {\n\n let args = std::env::args().collect::<Vec<String>>();\n\n let arg_length = args.len();\n\n\n\n let mut arguments = Arguments {\n\n window_dimensions: (768, 480),\n\n no_ground: false,\n\n framerate_limit: 30,\n\n };\n\...
Rust
datafusion/src/logical_plan/window_frames.rs
cube-js/arrow-datafusion
4e9d31e05b69017d972ae4c1ffbeeaab163fd654
use crate::error::{DataFusionError, Result}; use crate::execution::context::ExecutionContextState; use crate::logical_plan::Expr; use crate::scalar::ScalarValue; use crate::sql::planner::SqlToRel; use serde_derive::{Deserialize, Serialize}; use sqlparser::ast; use sqlparser::ast::DateTimeField; use std::cmp::Ordering; use std::convert::TryInto; use std::convert::{From, TryFrom}; use std::fmt; #[derive(Debug, Clone, PartialEq)] pub struct WindowFrame { pub units: WindowFrameUnits, pub start_bound: WindowFrameBound, pub end_bound: WindowFrameBound, } impl fmt::Display for WindowFrame { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{} BETWEEN {} AND {}", self.units, self.start_bound, self.end_bound )?; Ok(()) } } impl TryFrom<ast::WindowFrame> for WindowFrame { type Error = DataFusionError; fn try_from(value: ast::WindowFrame) -> Result<Self> { let start_bound = value.start_bound.try_into()?; let end_bound = value .end_bound .map(WindowFrameBound::try_from) .unwrap_or(Ok(WindowFrameBound::CurrentRow))?; check_window_bound_order(&start_bound, &end_bound)?; let is_allowed_range_bound = |s: &ScalarValue| match s { ScalarValue::Int64(Some(i)) => *i == 0, _ => false, }; let units = value.units.into(); if units == WindowFrameUnits::Range { for bound in &[&start_bound, &end_bound] { match bound { WindowFrameBound::Preceding(Some(v)) | WindowFrameBound::Following(Some(v)) if !is_allowed_range_bound(v) => { Err(DataFusionError::NotImplemented(format!( "With WindowFrameUnits={}, the bound cannot be {} PRECEDING or FOLLOWING at the moment", units, v ))) } _ => Ok(()), }?; } } Ok(Self { units, start_bound, end_bound, }) } } #[allow(missing_docs)] pub fn check_window_bound_order( start_bound: &WindowFrameBound, end_bound: &WindowFrameBound, ) -> Result<()> { if let WindowFrameBound::Following(None) = start_bound { Err(DataFusionError::Execution( "Invalid window frame: start bound cannot be unbounded following".to_owned(), )) } else if let WindowFrameBound::Preceding(None) = end_bound { Err(DataFusionError::Execution( "Invalid window frame: end bound cannot be unbounded preceding".to_owned(), )) } else { match start_bound.logical_cmp(&end_bound) { None => Err(DataFusionError::Execution(format!( "Invalid window frame: start bound ({}) is incompatble with the end bound ({})", start_bound, end_bound ))), Some(o) if o > Ordering::Equal => Err(DataFusionError::Execution(format!( "Invalid window frame: start bound ({}) cannot be larger than end bound ({})", start_bound, end_bound ))), Some(_) => Ok(()), } } } impl Default for WindowFrame { fn default() -> Self { WindowFrame { units: WindowFrameUnits::Range, start_bound: WindowFrameBound::Preceding(None), end_bound: WindowFrameBound::CurrentRow, } } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum WindowFrameBound { Preceding(Option<ScalarValue>), CurrentRow, Following(Option<ScalarValue>), } impl TryFrom<ast::WindowFrameBound> for WindowFrameBound { type Error = DataFusionError; fn try_from(value: ast::WindowFrameBound) -> Result<Self> { let value_to_scalar = |v| -> Result<_> { match v { None => Ok(None), Some(ast::Value::Number(v, _)) => match v.parse() { Err(_) => Err(DataFusionError::Plan(format!("could not convert window frame bound '{}' to int64", v))), Ok(v) => Ok(Some(ScalarValue::Int64(Some(v)))), }, Some(ast::Value::Interval { value, leading_field, leading_precision, last_field, fractional_seconds_precision }) => Ok(Some(interval_to_scalar(&value, &leading_field, &leading_precision, &last_field, &fractional_seconds_precision)?)), Some(o) => Err(DataFusionError::Plan(format!("window frame bound must be a positive integer or an INTERVAL, got {}", o))), } }; match value { ast::WindowFrameBound::Preceding(v) => { Ok(Self::Preceding(value_to_scalar(v)?)) } ast::WindowFrameBound::Following(v) => { Ok(Self::Following(value_to_scalar(v)?)) } ast::WindowFrameBound::CurrentRow => Ok(Self::CurrentRow), } } } fn interval_to_scalar( value: &str, leading_field: &Option<DateTimeField>, leading_precision: &Option<u64>, last_field: &Option<DateTimeField>, fractional_seconds_precision: &Option<u64>, ) -> Result<ScalarValue> { match SqlToRel::<ExecutionContextState>::sql_interval_to_literal( value, leading_field, leading_precision, last_field, fractional_seconds_precision, )? { Expr::Literal(v) => Ok(v), o => panic!("unexpected result of interval_to_literal: {:?}", o), } } impl fmt::Display for WindowFrameBound { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { WindowFrameBound::CurrentRow => f.write_str("CURRENT ROW"), WindowFrameBound::Preceding(None) => f.write_str("UNBOUNDED PRECEDING"), WindowFrameBound::Following(None) => f.write_str("UNBOUNDED FOLLOWING"), WindowFrameBound::Preceding(Some(n)) => write!(f, "{} PRECEDING", n), WindowFrameBound::Following(Some(n)) => write!(f, "{} FOLLOWING", n), } } } impl WindowFrameBound { pub fn logical_cmp(&self, other: &Self) -> Option<Ordering> { use WindowFrameBound::{CurrentRow, Following, Preceding}; let ord = |v: &WindowFrameBound| match v { Preceding(_) => 0, CurrentRow => 1, Following(_) => 2, }; let lo = ord(self); let ro = ord(other); let o = lo.cmp(&ro); if o != Ordering::Equal { return Some(o); } let (l, r) = match (self, other) { (Preceding(Some(l)), Preceding(Some(r))) => (r, l), (Following(Some(l)), Following(Some(r))) => (l, r), (CurrentRow, CurrentRow) => return Some(Ordering::Equal), (Preceding(None), Preceding(None)) => return Some(Ordering::Equal), (Preceding(None), Preceding(Some(_))) => return Some(Ordering::Less), (Preceding(Some(_)), Preceding(None)) => return Some(Ordering::Greater), (Following(None), Following(None)) => return Some(Ordering::Equal), (Following(Some(_)), Following(None)) => return Some(Ordering::Less), (Following(None), Following(Some(_))) => return Some(Ordering::Greater), _ => panic!("unhandled bounds: {} and {}", self, other), }; match (l, r) { (ScalarValue::Int64(Some(l)), ScalarValue::Int64(Some(r))) => Some(l.cmp(r)), ( ScalarValue::IntervalDayTime(Some(l)), ScalarValue::IntervalDayTime(Some(r)), ) => Some(l.cmp(r)), ( ScalarValue::IntervalYearMonth(Some(l)), ScalarValue::IntervalYearMonth(Some(r)), ) => Some(l.cmp(r)), _ => None, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum WindowFrameUnits { Rows, Range, Groups, } impl fmt::Display for WindowFrameUnits { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match self { WindowFrameUnits::Rows => "ROWS", WindowFrameUnits::Range => "RANGE", WindowFrameUnits::Groups => "GROUPS", }) } } impl From<ast::WindowFrameUnits> for WindowFrameUnits { fn from(value: ast::WindowFrameUnits) -> Self { match value { ast::WindowFrameUnits::Range => Self::Range, ast::WindowFrameUnits::Groups => Self::Groups, ast::WindowFrameUnits::Rows => Self::Rows, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_window_frame_creation() -> Result<()> { let window_frame = ast::WindowFrame { units: ast::WindowFrameUnits::Range, start_bound: ast::WindowFrameBound::Following(None), end_bound: None, }; let result = WindowFrame::try_from(window_frame); assert_eq!( result.err().unwrap().to_string(), "Execution error: Invalid window frame: start bound cannot be unbounded following".to_owned() ); let window_frame = ast::WindowFrame { units: ast::WindowFrameUnits::Range, start_bound: ast::WindowFrameBound::Preceding(None), end_bound: Some(ast::WindowFrameBound::Preceding(None)), }; let result = WindowFrame::try_from(window_frame); assert_eq!( result.err().unwrap().to_string(), "Execution error: Invalid window frame: end bound cannot be unbounded preceding".to_owned() ); let window_frame = ast::WindowFrame { units: ast::WindowFrameUnits::Range, start_bound: ast::WindowFrameBound::Preceding(Some(1)), end_bound: Some(ast::WindowFrameBound::Preceding(Some(2))), }; let result = WindowFrame::try_from(window_frame); assert_eq!( result.err().unwrap().to_string(), "Execution error: Invalid window frame: start bound (1 PRECEDING) cannot be larger than end bound (2 PRECEDING)".to_owned() ); let window_frame = ast::WindowFrame { units: ast::WindowFrameUnits::Range, start_bound: ast::WindowFrameBound::Preceding(Some(2)), end_bound: Some(ast::WindowFrameBound::Preceding(Some(1))), }; let result = WindowFrame::try_from(window_frame); assert_eq!( result.err().unwrap().to_string(), "This feature is not implemented: With WindowFrameUnits=RANGE, the bound cannot be 2 PRECEDING or FOLLOWING at the moment".to_owned() ); let window_frame = ast::WindowFrame { units: ast::WindowFrameUnits::Rows, start_bound: ast::WindowFrameBound::Preceding(Some(2)), end_bound: Some(ast::WindowFrameBound::Preceding(Some(1))), }; let result = WindowFrame::try_from(window_frame); assert!(result.is_ok()); Ok(()) } #[test] fn test_eq() { assert_eq!( WindowFrameBound::Preceding(Some(0)), WindowFrameBound::CurrentRow ); assert_eq!( WindowFrameBound::CurrentRow, WindowFrameBound::Following(Some(0)) ); assert_eq!( WindowFrameBound::Following(Some(2)), WindowFrameBound::Following(Some(2)) ); assert_eq!( WindowFrameBound::Following(None), WindowFrameBound::Following(None) ); assert_eq!( WindowFrameBound::Preceding(Some(2)), WindowFrameBound::Preceding(Some(2)) ); assert_eq!( WindowFrameBound::Preceding(None), WindowFrameBound::Preceding(None) ); } #[test] fn test_ord() { assert!(WindowFrameBound::Preceding(Some(1)) < WindowFrameBound::CurrentRow); assert!( WindowFrameBound::Preceding(Some(2)) < WindowFrameBound::Preceding(Some(1)) ); assert!( WindowFrameBound::Preceding(Some(u64::MAX)) < WindowFrameBound::Preceding(Some(u64::MAX - 1)) ); assert!( WindowFrameBound::Preceding(None) < WindowFrameBound::Preceding(Some(1000000)) ); assert!( WindowFrameBound::Preceding(None) < WindowFrameBound::Preceding(Some(u64::MAX)) ); assert!(WindowFrameBound::Preceding(None) < WindowFrameBound::Following(Some(0))); assert!( WindowFrameBound::Preceding(Some(1)) < WindowFrameBound::Following(Some(1)) ); assert!(WindowFrameBound::CurrentRow < WindowFrameBound::Following(Some(1))); assert!( WindowFrameBound::Following(Some(1)) < WindowFrameBound::Following(Some(2)) ); assert!(WindowFrameBound::Following(Some(2)) < WindowFrameBound::Following(None)); assert!( WindowFrameBound::Following(Some(u64::MAX)) < WindowFrameBound::Following(None) ); } }
use crate::error::{DataFusionError, Result}; use crate::execution::context::ExecutionContextState; use crate::logical_plan::Expr; use crate::scalar::ScalarValue; use crate::sql::planner::SqlToRel; use serde_derive::{Deserialize, Serialize}; use sqlparser::ast; use sqlparser::ast::DateTimeField; use std::cmp::Ordering; use std::convert::TryInto; use std::convert::{From, TryFrom}; use std::fmt; #[derive(Debug, Clone, PartialEq)] pub struct WindowFrame { pub units: WindowFrameUnits, pub start_bound: WindowFrameBound, pub end_bound: WindowFrameBound, } impl fmt::Display for WindowFrame { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{} BETWEEN {} AND {}", self.units, self.start_bound, self.end_bound )?; Ok(()) } } impl TryFrom<ast::WindowFrame> for WindowFrame { type Error = DataFusionError; fn try_from(value: ast::WindowFrame) -> Result<Self> { let start_bound = value.start_bound.try_into()?; let end_bound = value .end_bound .map(WindowFrameBound::try_from) .unwrap_or(Ok(WindowFrameBound::CurrentRow))?; check_window_bound_order(&start_bound, &end_bound)?; let is_allowed_range_bound = |s: &ScalarValue| match s { ScalarValue::Int64(Some(i)) => *i == 0, _ => false, }; let units = value.units.into(); if units == WindowFrameUnits::Range { for bound in &[&start_bound, &end_bound] { match bound { WindowFrameBound::Preceding(Some(v)) | WindowFrameBound::Following(Some(v)) if !is_allowed_range_bound(v) => { Err(DataFusionError::NotImplemented(format!( "With WindowFrameUnits={}, the bound cannot be {} PRECEDING or FOLLOWING at the moment", units, v ))) } _ => Ok(()), }?; } } Ok(Self { units, start_bound, end_bound, }) } } #[allow(missing_docs)] pub fn check_window_bound_order( start_bound: &WindowFrameBound, end_bound: &WindowFrameBound, ) -> Result<()> { if let WindowFrameBound::Following(None) = start_bound { Err(DataFusionError::Execution( "Invalid window frame: start bound cannot be unbounded following".to_owned(), )) } else if let WindowFrameBound::Preceding(None) = end_bound { Err(DataFusionError::Execution( "Invalid window frame: end bound cannot be unbounded preceding".to_owned(), )) } else { match start_bound.logical_cmp(&end_bound) { None => Err(DataFusionError::Execution(format!( "Invalid window frame: start bound ({}) is incompatble with the end bound ({})", start_bound, end_bound ))), Some(o) if o > Ordering::Equal => Err(DataFusionError::Execution(format!( "Invalid window frame: start bound ({}) cannot be larger than end bound ({})", start_bound, end_bound ))), Some(_) => Ok(()), } } } impl Default for WindowFrame { fn default() -> Self { WindowFrame { units: WindowFrameUnits::Range, start_bound: WindowFrameBound::Preceding(None), end_bound: WindowFrameBound::CurrentRow, } } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum WindowFrameBound { Preceding(Option<ScalarValue>), CurrentRow, Following(Option<ScalarValue>), } impl TryFrom<ast::WindowFrameBound> for WindowFrameBound { type Error = DataFusionError; fn try_from(value: ast::WindowFrameBound) -> Result<Self> { let value_to_scalar = |v| -> Result<_> { match v { None => Ok(None), Some(ast::Value::Number(v, _)) => match v.parse() { Err(_) => Err(DataFusionError::Plan(format!("could not convert window frame bound '{}' to int64", v))), Ok(v) => Ok(Some(ScalarValue::Int64(Some(v)))), }, Some(ast::Value::Interval { value, leading_field, leading_precision, last_field, fractional_seconds_precision }) => Ok(Some(interval_to_scalar(&value, &leading_field, &leading_precision, &last_field, &fractional_seconds_precision)?)), Some(o) => Err(DataFusionError::Plan(format!("window frame bound must be a positive integer or an INTERVAL, got {}", o))), } }; match value { ast::WindowFrameBound::Preceding(v) => { Ok(Self::Preceding(value_to_scalar(v)?)) } ast::WindowFrameBound::Following(v) => { Ok(Self::Following(value_to_scalar(v)?)) } ast::WindowFrameBound::CurrentRow => Ok(Self::CurrentRow), } } } fn interval_to_scalar( value: &str, leading_field: &Option<DateTimeField>, leading_precision: &Option<u64>, last_field: &Option<DateTimeField>, fractional_seconds_precision: &Option<u64>, ) -> Result<ScalarValue> { match SqlToRel::<ExecutionContextState>::sql_interval_to_literal( value, leading_field, leading_precision, last_field, fractional_seconds_precision, )? { Expr::Literal(v) => Ok(v), o => panic!("unexpected result of interval_to_literal: {:?}", o), } } impl fmt::Display for WindowFrameBound { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { WindowFrameBound::CurrentRow => f.write_str("CURRENT ROW"), WindowFrameBound::Preceding(None) => f.write_str("UNBOUNDED PRECEDING"), WindowFrameBound::Following(None) => f.write_str("UNBOUNDED FOLLOWING"), WindowFrameBound::Preceding(Some(n)) => write!(f, "{} PRECEDING", n), WindowFrameBound::Following(Some(n)) => write!(f, "{} FOLLOWING", n), } } } impl WindowFrameBound { pub fn logical_cmp(&self, other: &Self) -> Option<Ordering> { use WindowFrameBound::{CurrentRow, Following, Preceding}; let ord = |v: &WindowFrameBound| match v { Preceding(_) => 0, CurrentRow => 1, Following(_) => 2, }; let lo = ord(self); let ro = ord(other); let o = lo.cmp(&ro); if o != Ordering::Equal { return Some(o); } let (l, r) = match (self, other) { (Preceding(Some(l)), Preceding(Some(r))) => (r, l), (Following(Some(l)), Following(Some(r))) => (l, r), (CurrentRow, CurrentRow) => return Some(Ordering::Equal), (Preceding(None), Preceding(None)) => return Some(Ordering::Equal), (Preceding(None), Preceding(Some(_))) => return Some(Ordering::Less), (Preceding(Some(_)), Preceding(None)) => return Some(Ordering::Greater), (Following(None), Following(None)) => return Some(Ordering::Equal), (Following(Some(_)), Following(None)) => return Some(Ordering::Less), (Following(None), Following(Some(_))) => return Some(Ordering::Greater), _ => panic!("unhandled bounds: {} and {}", self, other), }; match (l, r) { (ScalarValue::Int64(Some(l)), ScalarValue::Int64(Some(r))) => Some(l.cmp(r)), ( ScalarValue::IntervalDayTime(Some(l)), ScalarValue::IntervalDayTime(Some(r)), ) => Some(l.cmp(r)), ( ScalarValue::IntervalYearMonth(Some(l)), ScalarValue::IntervalYearMonth(Some(r)), ) => Some(l.cmp(r)), _ => None, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum WindowFrameUnits { Rows, Range, Groups, } impl fmt::Display for WindowFrameUnits { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(
) } } impl From<ast::WindowFrameUnits> for WindowFrameUnits { fn from(value: ast::WindowFrameUnits) -> Self { match value { ast::WindowFrameUnits::Range => Self::Range, ast::WindowFrameUnits::Groups => Self::Groups, ast::WindowFrameUnits::Rows => Self::Rows, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_window_frame_creation() -> Result<()> { let window_frame = ast::WindowFrame { units: ast::WindowFrameUnits::Range, start_bound: ast::WindowFrameBound::Following(None), end_bound: None, }; let result = WindowFrame::try_from(window_frame); assert_eq!( result.err().unwrap().to_string(), "Execution error: Invalid window frame: start bound cannot be unbounded following".to_owned() ); let window_frame = ast::WindowFrame { units: ast::WindowFrameUnits::Range, start_bound: ast::WindowFrameBound::Preceding(None), end_bound: Some(ast::WindowFrameBound::Preceding(None)), }; let result = WindowFrame::try_from(window_frame); assert_eq!( result.err().unwrap().to_string(), "Execution error: Invalid window frame: end bound cannot be unbounded preceding".to_owned() ); let window_frame = ast::WindowFrame { units: ast::WindowFrameUnits::Range, start_bound: ast::WindowFrameBound::Preceding(Some(1)), end_bound: Some(ast::WindowFrameBound::Preceding(Some(2))), }; let result = WindowFrame::try_from(window_frame); assert_eq!( result.err().unwrap().to_string(), "Execution error: Invalid window frame: start bound (1 PRECEDING) cannot be larger than end bound (2 PRECEDING)".to_owned() ); let window_frame = ast::WindowFrame { units: ast::WindowFrameUnits::Range, start_bound: ast::WindowFrameBound::Preceding(Some(2)), end_bound: Some(ast::WindowFrameBound::Preceding(Some(1))), }; let result = WindowFrame::try_from(window_frame); assert_eq!( result.err().unwrap().to_string(), "This feature is not implemented: With WindowFrameUnits=RANGE, the bound cannot be 2 PRECEDING or FOLLOWING at the moment".to_owned() ); let window_frame = ast::WindowFrame { units: ast::WindowFrameUnits::Rows, start_bound: ast::WindowFrameBound::Preceding(Some(2)), end_bound: Some(ast::WindowFrameBound::Preceding(Some(1))), }; let result = WindowFrame::try_from(window_frame); assert!(result.is_ok()); Ok(()) } #[test] fn test_eq() { assert_eq!( WindowFrameBound::Preceding(Some(0)), WindowFrameBound::CurrentRow ); assert_eq!( WindowFrameBound::CurrentRow, WindowFrameBound::Following(Some(0)) ); assert_eq!( WindowFrameBound::Following(Some(2)), WindowFrameBound::Following(Some(2)) ); assert_eq!( WindowFrameBound::Following(None), WindowFrameBound::Following(None) ); assert_eq!( WindowFrameBound::Preceding(Some(2)), WindowFrameBound::Preceding(Some(2)) ); assert_eq!( WindowFrameBound::Preceding(None), WindowFrameBound::Preceding(None) ); } #[test] fn test_ord() { assert!(WindowFrameBound::Preceding(Some(1)) < WindowFrameBound::CurrentRow); assert!( WindowFrameBound::Preceding(Some(2)) < WindowFrameBound::Preceding(Some(1)) ); assert!( WindowFrameBound::Preceding(Some(u64::MAX)) < WindowFrameBound::Preceding(Some(u64::MAX - 1)) ); assert!( WindowFrameBound::Preceding(None) < WindowFrameBound::Preceding(Some(1000000)) ); assert!( WindowFrameBound::Preceding(None) < WindowFrameBound::Preceding(Some(u64::MAX)) ); assert!(WindowFrameBound::Preceding(None) < WindowFrameBound::Following(Some(0))); assert!( WindowFrameBound::Preceding(Some(1)) < WindowFrameBound::Following(Some(1)) ); assert!(WindowFrameBound::CurrentRow < WindowFrameBound::Following(Some(1))); assert!( WindowFrameBound::Following(Some(1)) < WindowFrameBound::Following(Some(2)) ); assert!(WindowFrameBound::Following(Some(2)) < WindowFrameBound::Following(None)); assert!( WindowFrameBound::Following(Some(u64::MAX)) < WindowFrameBound::Following(None) ); } }
match self { WindowFrameUnits::Rows => "ROWS", WindowFrameUnits::Range => "RANGE", WindowFrameUnits::Groups => "GROUPS", }
if_condition
[ { "content": "fn handle<F, R>(args: &[ColumnarValue], op: F, name: &str) -> Result<ColumnarValue>\n\nwhere\n\n R: AsRef<[u8]>,\n\n F: Fn(&str) -> R,\n\n{\n\n match &args[0] {\n\n ColumnarValue::Array(a) => match a.data_type() {\n\n DataType::Utf8 => {\n\n Ok(ColumnarVal...
Rust
src/runtime/thread/continuation.rs
jamesbornholt/shuttle
24ffc0aa2a2c30059c263ea7e5516f90af1c828b
#![allow(deprecated)] use crate::runtime::execution::ExecutionState; use generator::{Generator, Gn}; use scoped_tls::scoped_thread_local; use std::cell::{Cell, RefCell}; use std::collections::VecDeque; use std::ops::Deref; use std::ops::DerefMut; use std::rc::Rc; scoped_thread_local! { pub(crate) static CONTINUATION_POOL: ContinuationPool } pub(crate) struct Continuation { generator: Generator<'static, ContinuationInput, ContinuationOutput>, function: ContinuationFunction, state: ContinuationState, } #[allow(clippy::type_complexity)] #[derive(Clone)] struct ContinuationFunction(Rc<Cell<Option<Box<dyn FnOnce() + Send>>>>); unsafe impl Send for ContinuationFunction {} #[derive(Debug, PartialEq, Eq, Clone, Copy)] enum ContinuationInput { Resume, Exit, } #[derive(Debug, PartialEq, Eq, Clone, Copy)] enum ContinuationOutput { Yielded, Finished, Exited, } #[derive(Debug, PartialEq, Eq, Clone, Copy)] enum ContinuationState { NotReady, Ready, Running, } impl Continuation { pub fn new(stack_size: usize) -> Self { let function = ContinuationFunction(Rc::new(Cell::new(None))); let mut gen = { let function = function.clone(); Gn::new_opt(stack_size, move || { loop { match generator::yield_(ContinuationOutput::Finished) { None | Some(ContinuationInput::Exit) => break, _ => (), } let f = function.0.take().expect("must have a function to run"); f(); } ContinuationOutput::Exited }) }; let ret = gen.resume().unwrap(); debug_assert_eq!(ret, ContinuationOutput::Finished); Self { generator: gen, function, state: ContinuationState::NotReady, } } pub fn initialize(&mut self, fun: Box<dyn FnOnce() + Send>) { debug_assert_eq!( self.state, ContinuationState::NotReady, "shouldn't replace a function before it runs" ); let old = self.function.0.replace(Some(fun)); debug_assert!(old.is_none(), "shouldn't replace a function before it runs"); self.state = ContinuationState::Ready; } pub fn resume(&mut self) -> bool { debug_assert!(self.state == ContinuationState::Ready || self.state == ContinuationState::Running); let ret = self.resume_with_input(ContinuationInput::Resume); debug_assert_ne!( ret, ContinuationOutput::Exited, "continuation should not exit if resumed from user code" ); ret == ContinuationOutput::Finished } fn resume_with_input(&mut self, input: ContinuationInput) -> ContinuationOutput { self.generator.set_para(input); let ret = self.generator.resume().unwrap(); if ret == ContinuationOutput::Finished { self.state = ContinuationState::NotReady; } ret } fn reusable(&self) -> bool { self.state == ContinuationState::NotReady } } impl Drop for Continuation { fn drop(&mut self) { if self.reusable() { let ret = self.resume_with_input(ContinuationInput::Exit); debug_assert_eq!(ret, ContinuationOutput::Exited); } } } pub(crate) struct ContinuationPool { continuations: Rc<RefCell<VecDeque<Continuation>>>, } impl ContinuationPool { pub fn new() -> Self { Self { continuations: Rc::new(RefCell::new(VecDeque::new())), } } pub fn acquire(stack_size: usize) -> PooledContinuation { if CONTINUATION_POOL.is_set() { CONTINUATION_POOL.with(|p| p.acquire_inner(stack_size)) } else { let p = Self::new(); p.acquire_inner(stack_size) } } fn acquire_inner(&self, stack_size: usize) -> PooledContinuation { let continuation = self .continuations .borrow_mut() .pop_front() .unwrap_or_else(move || Continuation::new(stack_size)); PooledContinuation { continuation: Some(continuation), queue: self.continuations.clone(), } } } impl Drop for ContinuationPool { fn drop(&mut self) { for c in self.continuations.borrow_mut().iter_mut() { c.state = ContinuationState::Running; } } } pub(crate) struct PooledContinuation { continuation: Option<Continuation>, queue: Rc<RefCell<VecDeque<Continuation>>>, } impl Drop for PooledContinuation { fn drop(&mut self) { let c = self.continuation.take().unwrap(); if c.reusable() { self.queue.borrow_mut().push_back(c); } } } impl Deref for PooledContinuation { type Target = Continuation; fn deref(&self) -> &Self::Target { self.continuation.as_ref().unwrap() } } impl DerefMut for PooledContinuation { fn deref_mut(&mut self) -> &mut Self::Target { self.continuation.as_mut().unwrap() } } impl std::fmt::Debug for PooledContinuation { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.debug_struct("PooledContinuation").finish() } } unsafe impl Send for PooledContinuation {} pub(crate) fn switch() { if ExecutionState::maybe_yield() { let r = generator::yield_(ContinuationOutput::Yielded).unwrap(); assert!(matches!(r, ContinuationInput::Resume)); } } #[cfg(test)] mod tests { use super::*; use crate::Config; #[test] fn reusable_continuation_drop() { let pool = ContinuationPool::new(); let config: Config = Default::default(); let mut c = pool.acquire_inner(config.stack_size); c.initialize(Box::new(|| { let _ = 1 + 1; })); let r = c.resume(); assert!(r, "continuation only has one step"); drop(c); assert_eq!( pool.continuations.borrow().len(), 1, "continuation should be reusable because the function finished" ); let mut c = pool.acquire_inner(config.stack_size); c.initialize(Box::new(|| { generator::yield_with(ContinuationOutput::Yielded); let _ = 1 + 1; })); let r = c.resume(); assert!(!r, "continuation yields once, shouldn't be finished yet"); drop(c); assert_eq!( pool.continuations.borrow().len(), 0, "continuation should not be reusable because the function wasn't finished" ); let c = pool.acquire_inner(config.stack_size); drop(pool); drop(c); } }
#![allow(deprecated)] use crate::runtime::execution::ExecutionState; use generator::{Generator, Gn}; use scoped_tls::scoped_thread_local; use std::cell::{Cell, RefCell}; use std::collections::VecDeque; use std::ops::Deref; use std::ops::DerefMut; use std::rc::Rc; scoped_thread_local! { pub(crate) static CONTINUATION_POOL: ContinuationPool } pub(crate) struct Continuation { generator: Generator<'static, ContinuationInput, ContinuationOutput>, function: ContinuationFunction, state: ContinuationState, } #[allow(clippy::type_complexity)] #[derive(Clone)] struct ContinuationFunction(Rc<Cell<Option<Box<dyn FnOnce() + Send>>>>); unsafe impl Send for ContinuationFunction {} #[derive(Debug, PartialEq, Eq, Clone, Copy)] enum ContinuationInput { Resume, Exit, } #[derive(Debug, PartialEq, Eq, Clone, Copy)] enum ContinuationOutput { Yielded, Finished, Exited, } #[derive(Debug, PartialEq, Eq, Clone, Copy)] enum ContinuationState { NotReady, Ready, Running, } impl Continuation { pub fn new(stack_size: usize) -> Self { let function = ContinuationFunction(Rc::new(Cell::new(None))); let mut gen = { let function = function.clone(); Gn::new_opt(stack_size, move || { loop { match generator::yield_(ContinuationOutput::Finished) { None | Some(ContinuationInput::Exit) => break, _ => (), } let f = function.0.take().expect("must have a function to run"); f(); } ContinuationOutput::Exited }) }; let ret = gen.resume().unwrap(); debug_assert_eq!(ret, ContinuationOutput::Finished); Self { generator: gen, function, state: ContinuationState::NotReady, } }
pub fn resume(&mut self) -> bool { debug_assert!(self.state == ContinuationState::Ready || self.state == ContinuationState::Running); let ret = self.resume_with_input(ContinuationInput::Resume); debug_assert_ne!( ret, ContinuationOutput::Exited, "continuation should not exit if resumed from user code" ); ret == ContinuationOutput::Finished } fn resume_with_input(&mut self, input: ContinuationInput) -> ContinuationOutput { self.generator.set_para(input); let ret = self.generator.resume().unwrap(); if ret == ContinuationOutput::Finished { self.state = ContinuationState::NotReady; } ret } fn reusable(&self) -> bool { self.state == ContinuationState::NotReady } } impl Drop for Continuation { fn drop(&mut self) { if self.reusable() { let ret = self.resume_with_input(ContinuationInput::Exit); debug_assert_eq!(ret, ContinuationOutput::Exited); } } } pub(crate) struct ContinuationPool { continuations: Rc<RefCell<VecDeque<Continuation>>>, } impl ContinuationPool { pub fn new() -> Self { Self { continuations: Rc::new(RefCell::new(VecDeque::new())), } } pub fn acquire(stack_size: usize) -> PooledContinuation { if CONTINUATION_POOL.is_set() { CONTINUATION_POOL.with(|p| p.acquire_inner(stack_size)) } else { let p = Self::new(); p.acquire_inner(stack_size) } } fn acquire_inner(&self, stack_size: usize) -> PooledContinuation { let continuation = self .continuations .borrow_mut() .pop_front() .unwrap_or_else(move || Continuation::new(stack_size)); PooledContinuation { continuation: Some(continuation), queue: self.continuations.clone(), } } } impl Drop for ContinuationPool { fn drop(&mut self) { for c in self.continuations.borrow_mut().iter_mut() { c.state = ContinuationState::Running; } } } pub(crate) struct PooledContinuation { continuation: Option<Continuation>, queue: Rc<RefCell<VecDeque<Continuation>>>, } impl Drop for PooledContinuation { fn drop(&mut self) { let c = self.continuation.take().unwrap(); if c.reusable() { self.queue.borrow_mut().push_back(c); } } } impl Deref for PooledContinuation { type Target = Continuation; fn deref(&self) -> &Self::Target { self.continuation.as_ref().unwrap() } } impl DerefMut for PooledContinuation { fn deref_mut(&mut self) -> &mut Self::Target { self.continuation.as_mut().unwrap() } } impl std::fmt::Debug for PooledContinuation { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.debug_struct("PooledContinuation").finish() } } unsafe impl Send for PooledContinuation {} pub(crate) fn switch() { if ExecutionState::maybe_yield() { let r = generator::yield_(ContinuationOutput::Yielded).unwrap(); assert!(matches!(r, ContinuationInput::Resume)); } } #[cfg(test)] mod tests { use super::*; use crate::Config; #[test] fn reusable_continuation_drop() { let pool = ContinuationPool::new(); let config: Config = Default::default(); let mut c = pool.acquire_inner(config.stack_size); c.initialize(Box::new(|| { let _ = 1 + 1; })); let r = c.resume(); assert!(r, "continuation only has one step"); drop(c); assert_eq!( pool.continuations.borrow().len(), 1, "continuation should be reusable because the function finished" ); let mut c = pool.acquire_inner(config.stack_size); c.initialize(Box::new(|| { generator::yield_with(ContinuationOutput::Yielded); let _ = 1 + 1; })); let r = c.resume(); assert!(!r, "continuation yields once, shouldn't be finished yet"); drop(c); assert_eq!( pool.continuations.borrow().len(), 0, "continuation should not be reusable because the function wasn't finished" ); let c = pool.acquire_inner(config.stack_size); drop(pool); drop(c); } }
pub fn initialize(&mut self, fun: Box<dyn FnOnce() + Send>) { debug_assert_eq!( self.state, ContinuationState::NotReady, "shouldn't replace a function before it runs" ); let old = self.function.0.replace(Some(fun)); debug_assert!(old.is_none(), "shouldn't replace a function before it runs"); self.state = ContinuationState::Ready; }
function_block-function_prefix_line
[ { "content": "/// Run the given function under a randomized concurrency scheduler for some number of iterations.\n\n/// Each iteration will run a (potentially) different randomized schedule.\n\npub fn check_random<F>(f: F, iterations: usize)\n\nwhere\n\n F: Fn() + Send + Sync + 'static,\n\n{\n\n use crate...
Rust
fyrox-sound/src/dsp/filters.rs
Libertus-Lab/Fyrox
c925304f42744659fd3a6be5c4a1a8609556033a
use crate::dsp::DelayLine; use fyrox_core::{ inspect::{Inspect, PropertyInfo}, visitor::{Visit, VisitResult, Visitor}, }; #[derive(Debug, Clone, Visit)] pub struct OnePole { a0: f32, b1: f32, last: f32, } impl Default for OnePole { fn default() -> Self { Self { a0: 1.0, b1: 0.0, last: 0.0, } } } fn get_b1(fc: f32) -> f32 { (-2.0 * std::f32::consts::PI * fc.min(1.0).max(0.0)).exp() } impl OnePole { pub fn new(fc: f32) -> Self { let b1 = get_b1(fc); Self { b1, a0: 1.0 - b1, last: 0.0, } } pub fn set_fc(&mut self, fc: f32) { self.b1 = get_b1(fc); self.a0 = 1.0 - self.b1; } pub fn set_pole(&mut self, pole: f32) { self.b1 = pole.min(1.0).max(0.0); self.a0 = 1.0 - self.b1; } pub fn feed(&mut self, sample: f32) -> f32 { let result = sample * self.a0 + self.last * self.b1; self.last = result; result } } #[derive(Debug, Clone, Visit)] pub struct LpfComb { low_pass: OnePole, delay_line: DelayLine, feedback: f32, } impl Default for LpfComb { fn default() -> Self { Self { low_pass: Default::default(), delay_line: Default::default(), feedback: 0.0, } } } impl LpfComb { pub fn new(len: usize, fc: f32, feedback: f32) -> Self { Self { low_pass: OnePole::new(fc), delay_line: DelayLine::new(len), feedback, } } pub fn set_feedback(&mut self, feedback: f32) { self.feedback = feedback; } pub fn feedback(&self) -> f32 { self.feedback } pub fn set_fc(&mut self, fc: f32) { self.low_pass.set_fc(fc) } pub fn len(&self) -> usize { self.delay_line.len() } pub fn feed(&mut self, sample: f32) -> f32 { let result = sample + self.feedback * self.low_pass.feed(self.delay_line.last()); self.delay_line.feed(result); result } } #[derive(Debug, Clone, Visit)] pub struct AllPass { delay_line: DelayLine, gain: f32, } impl Default for AllPass { fn default() -> Self { Self { delay_line: Default::default(), gain: 1.0, } } } impl AllPass { pub fn new(len: usize, gain: f32) -> Self { Self { delay_line: DelayLine::new(len), gain, } } pub fn set_gain(&mut self, gain: f32) { self.gain = gain; } pub fn len(&self) -> usize { self.delay_line.len() } pub fn feed(&mut self, sample: f32) -> f32 { let delay_line_output = self.delay_line.last(); let am_arm = -self.gain * delay_line_output; let sum_left = sample + am_arm; let b0_arm = sum_left * self.gain; self.delay_line.feed(sum_left); delay_line_output + b0_arm } } pub enum BiquadKind { LowPass, HighPass, BandPass, AllPass, LowShelf, HighShelf, } #[derive(Clone, Debug, Inspect, Visit)] pub struct Biquad { pub b0: f32, pub b1: f32, pub b2: f32, pub a1: f32, pub a2: f32, #[inspect(skip)] prev1: f32, #[inspect(skip)] prev2: f32, } impl Biquad { pub fn new(kind: BiquadKind, fc: f32, gain: f32, quality: f32) -> Self { let mut filter = Self::default(); filter.tune(kind, fc, gain, quality); filter } pub fn from_coefficients(b0: f32, b1: f32, b2: f32, a1: f32, a2: f32) -> Self { Self { b0, b1, b2, a1, a2, prev1: 0.0, prev2: 0.0, } } pub fn tune(&mut self, kind: BiquadKind, fc: f32, gain: f32, quality: f32) { let w0 = 2.0 * std::f32::consts::PI * fc; let w0_cos = w0.cos(); let w0_sin = w0.sin(); let alpha = w0_sin / (2.0 * quality); let (b0, b1, b2, a0, a1, a2) = match kind { BiquadKind::LowPass => { let b0 = (1.0 - w0_cos) / 2.0; let b1 = 1.0 - w0_cos; let b2 = b0; let a0 = 1.0 + alpha; let a1 = -2.0 * w0_cos; let a2 = 1.0 - alpha; (b0, b1, b2, a0, a1, a2) } BiquadKind::HighPass => { let b0 = (1.0 + w0_cos) / 2.0; let b1 = -(1.0 + w0_cos); let b2 = b0; let a0 = 1.0 + alpha; let a1 = -2.0 * w0_cos; let a2 = 1.0 - alpha; (b0, b1, b2, a0, a1, a2) } BiquadKind::BandPass => { let b0 = w0_sin / 2.0; let b1 = 0.0; let b2 = -b0; let a0 = 1.0 + alpha; let a1 = -2.0 * w0_cos; let a2 = 1.0 - alpha; (b0, b1, b2, a0, a1, a2) } BiquadKind::AllPass => { let b0 = 1.0 - alpha; let b1 = -2.0 * w0_cos; let b2 = 1.0 + alpha; let a0 = b2; let a1 = -2.0 * w0_cos; let a2 = 1.0 - alpha; (b0, b1, b2, a0, a1, a2) } BiquadKind::LowShelf => { let sq = 2.0 * gain.sqrt() * alpha; let b0 = gain * ((gain + 1.0) - (gain - 1.0) * w0_cos + sq); let b1 = 2.0 * gain * ((gain - 1.0) - (gain + 1.0) * w0_cos); let b2 = gain * ((gain + 1.0) - (gain - 1.0) * w0_cos - sq); let a0 = (gain + 1.0) + (gain - 1.0) * w0_cos + sq; let a1 = -2.0 * ((gain - 1.0) + (gain + 1.0) * w0_cos); let a2 = (gain + 1.0) + (gain - 1.0) * w0_cos - sq; (b0, b1, b2, a0, a1, a2) } BiquadKind::HighShelf => { let sq = 2.0 * gain.sqrt() * alpha; let b0 = gain * ((gain + 1.0) + (gain - 1.0) * w0_cos + sq); let b1 = -2.0 * gain * ((gain - 1.0) + (gain + 1.0) * w0_cos); let b2 = gain * ((gain + 1.0) + (gain - 1.0) * w0_cos - sq); let a0 = (gain + 1.0) - (gain - 1.0) * w0_cos + sq; let a1 = 2.0 * ((gain - 1.0) - (gain + 1.0) * w0_cos); let a2 = (gain + 1.0) - (gain - 1.0) * w0_cos - sq; (b0, b1, b2, a0, a1, a2) } }; self.b0 = b0 / a0; self.b1 = b1 / a0; self.b2 = b2 / a0; self.a1 = a1 / a0; self.a2 = a2 / a0; } pub fn feed(&mut self, sample: f32) -> f32 { let result = sample * self.b0 + self.prev1; self.prev1 = sample * self.b1 - result * self.a1 + self.prev2; self.prev2 = sample * self.b2 - result * self.a2; result } } impl Default for Biquad { fn default() -> Self { Self { b0: 1.0, b1: 0.0, b2: 0.0, a1: 0.0, a2: 0.0, prev1: 0.0, prev2: 0.0, } } }
use crate::dsp::DelayLine; use fyrox_core::{ inspect::{Inspect, PropertyInfo}, visitor::{Visit, VisitResult, Visitor}, }; #[derive(Debug, Clone, Visit)] pub struct OnePole { a0: f32, b1: f32, last: f32, } impl Default for OnePole { fn default() -> Self { Self { a0: 1.0, b1: 0.0, last: 0.0, } } } fn get_b1(fc: f32) -> f32 { (-2.0 * std::f32::consts::PI * fc.min(1.0).max(0.0)).exp() } impl OnePole { pub fn new(fc: f32) -> Self { let b1 = get_b1(fc); Self { b1, a0: 1.0 - b1, last: 0.0, } } pub fn set_fc(&mut self, fc: f32) { self.b1 = get_b1(fc); self.a0 = 1.0 - self.b1; } pub fn set_pole(&mut self, pole: f32) { self.b1 = pole.min(1.0).max(0.0); self.a0 = 1.0 - self.b1; } pub fn feed(&mut self, sample: f32) -> f32 { let result = sample * self.a0 + self.last * self.b1; self.last = result; result } } #[derive(Debug, Clone, Visit)] pub struct LpfComb { low_pass: OnePole, delay_line: DelayLine, feedback: f32, } impl Default for LpfComb { fn default() -> Self { Self { low_pass: Default::default(), delay_line: Default::default(), feedback: 0.0, } } } impl LpfComb { pub fn new(len: usize, fc: f32, feedback: f32) -> Self { Self { low_pass: OnePole::new(fc), delay_line: DelayLine::new(len), feedback, } } pub fn set_feedback(&mut self, feedback: f32) { self.feedback = feedback; } pub fn feedback(&self) -> f32 { self.feedback } pub fn set_fc(&mut self, fc: f32) { self.low_pass.set_fc(fc) } pub fn len(&self) -> usize { self.delay_line.len() } pub fn feed(&mut self, sample: f32) -> f32 { let result = sample + self.feedback * self.low_pass.feed(self.delay_line.last()); self.delay_line.feed(result); result } } #[derive(Debug, Clone, Visit)] pub struct AllPass { delay_line: DelayLine, gain: f32, } impl Default for AllPass { fn default() -> Self { Self { delay_line: Default::default(), gain: 1.0, } } } impl AllPass { pub fn new(len: usize, gain: f32) -> Self { Self { delay_line: DelayLine::new(len), gain, } } pub fn set_gain(&mut self, gain: f32) { self.gain = gain; } pub fn len(&self) -> usize { self.delay_line.len() } pub fn feed(&mut self, sample: f32) -> f32 { let delay_line_output = self.delay_line.last(); let am_arm = -self.gain * delay_line_output; let sum_left = sample + am_arm; let b0_arm = sum_left * self.gain; self.delay_line.feed(sum_left); delay_line_output + b0_arm } } pub enum BiquadKind { LowPass, HighPass, BandPass, AllPass, LowShelf, HighShelf, } #[derive(Clone, Debug, Inspect, Visit)] pub struct Biquad { pub b0: f32, pub b1: f32, pub b2: f32, pub a1: f32, pub a2: f32, #[inspect(skip)] prev1: f32, #[inspect(skip)] prev2: f32, } impl Biquad { pub fn new(kind: BiquadKind, fc: f32, gain: f32, quality: f32) -> Self { let mut filter = Self::default(); filter.tune(kind, fc, gain, quality); filter } pub fn from_coefficients(b0: f32, b1: f32, b2: f32, a1: f32, a2: f32) -> Self { Self { b0, b1, b2, a1, a2, prev1: 0.0, prev2: 0.0, } } pub fn tune(&mut self, kind: BiquadKind, fc: f32, gain: f32, quality: f32) { let w0 = 2.0 * std::f32::consts::PI * fc; let w0_cos = w0.cos(); let w0_sin = w0.sin(); let alpha = w0_sin / (2.0 * quality); let (b0, b1, b2, a0, a1, a2) = match kind { BiquadKind::LowPass => { let b0 = (1.0 - w0_cos) / 2.0; let b1 = 1.0 - w0_cos; let b2 = b0; let a0 = 1.0 + alpha; let a1 = -2.0 * w0_cos; let a2 = 1.0 - alpha; (b0, b1, b2, a0, a1, a2) } BiquadKind::HighPass => { let b0 = (1.0 + w0_cos) / 2.0; let b1 = -(1.0 + w0_cos); let b2 = b0; let a0 = 1.0 + alpha; let a1 = -2.0 * w0_cos; let a2 = 1.0 - alpha; (b0, b1, b2, a0, a1, a2) } BiquadKind::BandPass => { let b0 = w0_sin / 2.0; let b1 = 0.0; let b2 = -b0; let a0 = 1.0 + alpha; let a1 = -2.0 * w0_cos; let a2 = 1.0 - alpha; (b0, b1, b2, a0, a1, a2) } BiquadKind::AllPass => { let b0 = 1.0 - alpha; let b1 = -2.0 * w0_cos; let b2 = 1.0 + alpha; let a0 = b2; let a1 = -2.0 * w0_cos; let a2 = 1.0 - alpha; (b0, b1, b2, a0, a1, a2) } BiquadKind::LowShelf => { let sq = 2.0 * gain.sqrt() * alpha; let b0 = gain * ((gain + 1.0) - (gain - 1.0) * w0_cos + sq); let b1 = 2.0 * gain * ((gain - 1.0) - (gain + 1.0) * w0_cos); let b2 = gain * ((gain + 1.0) - (gain - 1.0) * w0_cos - sq); let a0 = (gain + 1.0) + (gain - 1.0) * w0_cos + sq; let a1 = -2.0 * ((gain - 1.0) + (gain + 1.0) * w0_cos); let a2 = (gain + 1.0) + (gain - 1.0) * w0_cos - sq; (b0, b1, b2, a0, a1, a2) } BiquadKind::HighShelf => { let sq = 2.0 * gain.sqrt() * alpha; let b0 = gain * ((gain + 1.0) + (gain - 1.0) * w0_cos + sq); let b1 = -2.0 * gain * ((gain - 1.0) + (gain + 1.0) * w0_cos); let b2 = gain * ((gain + 1.0) + (gain - 1.0) * w0_cos - sq); let a0 = (gain + 1.0) - (gain - 1.0) * w0_cos + sq; let a1 = 2.0 * ((gain - 1.0) - (gain + 1.0) * w0_cos); let a2 = (gain + 1.0) - (gain - 1.0) * w0_cos - sq; (b0, b1, b2, a0, a1, a2) } }; self.b0 = b0 / a0; self.b1 = b1 / a0; self.b2 = b2 / a0; self.a1 = a1 / a0; self.a2 = a2 / a0; } pub fn feed(&mut self, sample: f32) -> f32 { let result = sample * self.b0 + self.prev1; self.prev1 = sample * self.b1 - result * self.a1 + self.prev2; self.prev2 = sample * self.b2 - result * self.a2; result } } impl Default for Biquad {
}
fn default() -> Self { Self { b0: 1.0, b1: 0.0, b2: 0.0, a1: 0.0, a2: 0.0, prev1: 0.0, prev2: 0.0, } }
function_block-full_function
[ { "content": "fn write_node(name: &str, node: &mut Node, visitor: &mut Visitor) -> VisitResult {\n\n let mut region = visitor.enter_region(name)?;\n\n\n\n let mut id = node.id();\n\n id.visit(\"TypeUuid\", &mut region)?;\n\n\n\n node.visit(\"NodeData\", &mut region)?;\n\n\n\n Ok(())\n\n}\n\n\n\ni...
Rust
vm-bindings/build_support/builder.rs
feenkcom/gtoolkit-vm
0647fe53203d614d776cb5af4f228cddc4a5f29d
use file_matcher::{FileNamed, OneEntry, OneEntryCopier}; use std::fmt::Debug; use std::path::{Path, PathBuf}; use std::{env, fmt, fs}; const VM_CLIENT_VMMAKER_VM_VAR: &str = "VM_CLIENT_VMMAKER"; const VM_CLIENT_VMMAKER_IMAGE_VAR: &str = "VM_CLIENT_VMMAKER_IMAGE"; pub trait Builder: Debug { fn is_compiled(&self) -> bool { self.vm_binary().exists() } fn profile(&self) -> String { std::env::var("PROFILE").unwrap() } fn is_debug(&self) -> bool { self.profile() == "debug" } fn ensure_build_tools(&self) {} fn vmmaker_vm(&self) -> Option<PathBuf> { std::env::var(VM_CLIENT_VMMAKER_VM_VAR).map_or(None, |path| { let path = Path::new(&path); if path.exists() { Some(path.to_path_buf()) } else { panic!( "Specified {} does not exist: {}", VM_CLIENT_VMMAKER_VM_VAR, path.display() ); } }) } fn vmmaker_image(&self) -> Option<PathBuf> { std::env::var(VM_CLIENT_VMMAKER_IMAGE_VAR).map_or(None, |path| { let path = Path::new(&path); if path.exists() { Some(path.to_path_buf()) } else { panic!( "Specified {} does not exist: {}", VM_CLIENT_VMMAKER_IMAGE_VAR, path.display() ); } }) } fn output_directory(&self) -> PathBuf { Path::new(env::var("OUT_DIR").unwrap().as_str()).to_path_buf() } fn vm_binary(&self) -> PathBuf; fn vm_sources_directory(&self) -> PathBuf { std::env::current_dir() .unwrap() .parent() .unwrap() .to_path_buf() .join("opensmalltalk-vm") } fn compiled_libraries_directory(&self) -> PathBuf; fn exported_libraries_directory(&self) -> PathBuf { let target = std::env::var("CARGO_TARGET"); let mut path = PathBuf::new() .join("..") .join(std::env::var("CARGO_TARGET_DIR").unwrap_or("target".to_string())); if let Ok(target) = target { path = path.join(target); } path.join(self.profile()).join("shared_libraries") } fn compile_sources(&self); fn squeak_include_directory(&self) -> PathBuf { self.vm_sources_directory() .join("extracted") .join("vm") .join("include") } fn common_include_directory(&self) -> PathBuf { self.squeak_include_directory().join("common") } fn platform_include_directory(&self) -> PathBuf; fn generated_config_directory(&self) -> PathBuf { self.output_directory() .join("build") .join("build") .join("include") .join("pharovm") } fn generated_include_directory(&self) -> PathBuf { self.output_directory() .join("build") .join("generated") .join("64") .join("vm") .join("include") } fn generate_bindings(&self) { let include_dir = self.vm_sources_directory().join("include"); let generated_vm_include_dir = self.generated_include_directory(); assert!( generated_vm_include_dir.exists(), "Generated vm include directory must exist: {:?}", generated_vm_include_dir.display() ); let generated_config_directory = self.generated_config_directory(); assert!( generated_config_directory.exists(), "Generated config.h directory must exist: {:?}", generated_config_directory.display() ); let bindings = bindgen::Builder::default() .whitelist_function("vm_.*") .whitelist_function("free") .header( include_dir .join("pharovm") .join("pharoClient.h") .display() .to_string(), ) .clang_arg(format!("-I{}", &include_dir.display())) .clang_arg(format!("-I{}", &include_dir.join("pharovm").display())) .clang_arg(format!("-I{}", generated_config_directory.display())) .clang_arg(format!("-I{}", generated_vm_include_dir.display())) .clang_arg(format!("-I{}", self.common_include_directory().display())) .clang_arg(format!("-I{}", self.platform_include_directory().display())) .clang_arg("-DLSB_FIRST=1") .parse_callbacks(Box::new(bindgen::CargoCallbacks)) .generate() .expect("Unable to generate bindings"); bindings .write_to_file(self.output_directory().join("bindings.rs")) .expect("Couldn't write bindings!"); } fn link_libraries(&self); fn export_shared_libraries(&self) { if !self.exported_libraries_directory().exists() { fs::create_dir_all(self.exported_libraries_directory()).unwrap(); } for shared_library in self.shared_libraries_to_export() { let target = self.exported_libraries_directory(); match shared_library.copy(&target) { Ok(_) => {} Err(error) => { panic!( "Could not copy {:?} to {} due to {}", &shared_library, &target.display(), error ) } } } } fn shared_libraries_to_export(&self) -> Vec<OneEntry>; fn print_directories(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_map() .entry(&"is_compiled".to_string(), &self.is_compiled()) .entry( &"output_directory".to_string(), &self.output_directory().display(), ) .entry(&"vm_binary".to_string(), &self.vm_binary().display()) .entry( &"vm_sources_directory".to_string(), &self.vm_sources_directory().display(), ) .entry( &"compiled_libraries_directory".to_string(), &self.compiled_libraries_directory().display(), ) .entry( &"exported_libraries_directory".to_string(), &self.exported_libraries_directory().display(), ) .finish() } fn boxed(self) -> Box<dyn Builder>; fn filenames_from_libdir(&self, filenames: Vec<&str>, libdir: PathBuf) -> Vec<OneEntry> { filenames .into_iter() .map(FileNamed::exact) .map(|each| each.within(&libdir)) .collect() } }
use file_matcher::{FileNamed, OneEntry, OneEntryCopier}; use std::fmt::Debug; use std::path::{Path, PathBuf}; use std::{env, fmt, fs}; const VM_CLIENT_VMMAKER_VM_VAR: &str = "VM_CLIENT_VMMAKER"; const VM_CLIENT_VMMAKER_IMAGE_VAR: &str = "VM_CLIENT_VMMAKER_IMAGE"; pub trait Builder: Debug { fn is_compiled(&self) -> bool { self.vm_binary().exists() } fn profile(&self) -> String { std::env::var("PROFILE").un
(), &self.is_compiled()) .entry( &"output_directory".to_string(), &self.output_directory().display(), ) .entry(&"vm_binary".to_string(), &self.vm_binary().display()) .entry( &"vm_sources_directory".to_string(), &self.vm_sources_directory().display(), ) .entry( &"compiled_libraries_directory".to_string(), &self.compiled_libraries_directory().display(), ) .entry( &"exported_libraries_directory".to_string(), &self.exported_libraries_directory().display(), ) .finish() } fn boxed(self) -> Box<dyn Builder>; fn filenames_from_libdir(&self, filenames: Vec<&str>, libdir: PathBuf) -> Vec<OneEntry> { filenames .into_iter() .map(FileNamed::exact) .map(|each| each.within(&libdir)) .collect() } }
wrap() } fn is_debug(&self) -> bool { self.profile() == "debug" } fn ensure_build_tools(&self) {} fn vmmaker_vm(&self) -> Option<PathBuf> { std::env::var(VM_CLIENT_VMMAKER_VM_VAR).map_or(None, |path| { let path = Path::new(&path); if path.exists() { Some(path.to_path_buf()) } else { panic!( "Specified {} does not exist: {}", VM_CLIENT_VMMAKER_VM_VAR, path.display() ); } }) } fn vmmaker_image(&self) -> Option<PathBuf> { std::env::var(VM_CLIENT_VMMAKER_IMAGE_VAR).map_or(None, |path| { let path = Path::new(&path); if path.exists() { Some(path.to_path_buf()) } else { panic!( "Specified {} does not exist: {}", VM_CLIENT_VMMAKER_IMAGE_VAR, path.display() ); } }) } fn output_directory(&self) -> PathBuf { Path::new(env::var("OUT_DIR").unwrap().as_str()).to_path_buf() } fn vm_binary(&self) -> PathBuf; fn vm_sources_directory(&self) -> PathBuf { std::env::current_dir() .unwrap() .parent() .unwrap() .to_path_buf() .join("opensmalltalk-vm") } fn compiled_libraries_directory(&self) -> PathBuf; fn exported_libraries_directory(&self) -> PathBuf { let target = std::env::var("CARGO_TARGET"); let mut path = PathBuf::new() .join("..") .join(std::env::var("CARGO_TARGET_DIR").unwrap_or("target".to_string())); if let Ok(target) = target { path = path.join(target); } path.join(self.profile()).join("shared_libraries") } fn compile_sources(&self); fn squeak_include_directory(&self) -> PathBuf { self.vm_sources_directory() .join("extracted") .join("vm") .join("include") } fn common_include_directory(&self) -> PathBuf { self.squeak_include_directory().join("common") } fn platform_include_directory(&self) -> PathBuf; fn generated_config_directory(&self) -> PathBuf { self.output_directory() .join("build") .join("build") .join("include") .join("pharovm") } fn generated_include_directory(&self) -> PathBuf { self.output_directory() .join("build") .join("generated") .join("64") .join("vm") .join("include") } fn generate_bindings(&self) { let include_dir = self.vm_sources_directory().join("include"); let generated_vm_include_dir = self.generated_include_directory(); assert!( generated_vm_include_dir.exists(), "Generated vm include directory must exist: {:?}", generated_vm_include_dir.display() ); let generated_config_directory = self.generated_config_directory(); assert!( generated_config_directory.exists(), "Generated config.h directory must exist: {:?}", generated_config_directory.display() ); let bindings = bindgen::Builder::default() .whitelist_function("vm_.*") .whitelist_function("free") .header( include_dir .join("pharovm") .join("pharoClient.h") .display() .to_string(), ) .clang_arg(format!("-I{}", &include_dir.display())) .clang_arg(format!("-I{}", &include_dir.join("pharovm").display())) .clang_arg(format!("-I{}", generated_config_directory.display())) .clang_arg(format!("-I{}", generated_vm_include_dir.display())) .clang_arg(format!("-I{}", self.common_include_directory().display())) .clang_arg(format!("-I{}", self.platform_include_directory().display())) .clang_arg("-DLSB_FIRST=1") .parse_callbacks(Box::new(bindgen::CargoCallbacks)) .generate() .expect("Unable to generate bindings"); bindings .write_to_file(self.output_directory().join("bindings.rs")) .expect("Couldn't write bindings!"); } fn link_libraries(&self); fn export_shared_libraries(&self) { if !self.exported_libraries_directory().exists() { fs::create_dir_all(self.exported_libraries_directory()).unwrap(); } for shared_library in self.shared_libraries_to_export() { let target = self.exported_libraries_directory(); match shared_library.copy(&target) { Ok(_) => {} Err(error) => { panic!( "Could not copy {:?} to {} due to {}", &shared_library, &target.display(), error ) } } } } fn shared_libraries_to_export(&self) -> Vec<OneEntry>; fn print_directories(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_map() .entry(&"is_compiled".to_string
random
[ { "content": "#[no_mangle]\n\npub fn gtoolkit_vm_is_on_worker_thread(gt_vm_ptr: *const Mutex<Option<GToolkitVM>>) -> bool {\n\n gt_vm_ptr.with(|| false, |gt_vm| gt_vm.is_on_worker_thread())\n\n}\n\n\n", "file_path": "experimental/src/lib.rs", "rank": 1, "score": 118262.39327501913 }, { "c...
Rust
src/mock.rs
fossabot/client-rust
4540c1cdfa9a4d17ac15a1242daf32ef53a17133
use crate::{ pd::{PdClient, PdRpcClient, RetryClient}, request::DispatchHook, Config, Error, Key, Result, Timestamp, }; use fail::fail_point; use futures::future::{ready, BoxFuture, FutureExt}; use grpcio::CallOption; use kvproto::{errorpb, kvrpcpb, metapb, tikvpb::TikvClient}; use std::{future::Future, sync::Arc, time::Duration}; use tikv_client_store::{HasError, KvClient, KvConnect, Region, RegionId, Store}; pub async fn pd_rpc_client() -> PdRpcClient<MockKvConnect, MockCluster> { let config = Config::default(); PdRpcClient::new( &config, |_, _| MockKvConnect, |e, sm| { futures::future::ok(RetryClient::new_with_cluster( e, sm, config.timeout, MockCluster, )) }, ) .await .unwrap() } #[derive(Clone, Eq, PartialEq, Debug)] pub struct MockKvClient { addr: String, } pub struct MockKvConnect; pub struct MockCluster; pub struct MockPdClient; impl KvClient for MockKvClient { fn dispatch<Resp, RpcFuture>( &self, _request_name: &'static str, _fut: grpcio::Result<RpcFuture>, ) -> BoxFuture<'static, Result<Resp>> where RpcFuture: Future<Output = std::result::Result<Resp, ::grpcio::Error>>, Resp: HasError + Sized + Clone + Send + 'static, RpcFuture: Send + 'static, { unimplemented!() } fn get_rpc_client(&self) -> Arc<TikvClient> { unimplemented!() } } impl KvConnect for MockKvConnect { type KvClient = MockKvClient; fn connect(&self, address: &str) -> Result<Self::KvClient> { Ok(MockKvClient { addr: address.to_owned(), }) } } impl MockPdClient { pub fn region1() -> Region { let mut region = Region::default(); region.region.id = 1; region.region.set_start_key(vec![0]); region.region.set_end_key(vec![10]); let mut leader = metapb::Peer::default(); leader.store_id = 41; region.leader = Some(leader); region } pub fn region2() -> Region { let mut region = Region::default(); region.region.id = 2; region.region.set_start_key(vec![10]); region.region.set_end_key(vec![250, 250]); let mut leader = metapb::Peer::default(); leader.store_id = 42; region.leader = Some(leader); region } } impl PdClient for MockPdClient { type KvClient = MockKvClient; fn map_region_to_store( self: Arc<Self>, region: Region, ) -> BoxFuture<'static, Result<Store<Self::KvClient>>> { Box::pin(ready(Ok(Store::new( region, MockKvClient { addr: String::new(), }, Duration::from_secs(60), )))) } fn region_for_key(&self, key: &Key) -> BoxFuture<'static, Result<Region>> { let bytes: &[_] = key.into(); let region = if bytes.is_empty() || bytes[0] < 10 { Self::region1() } else { Self::region2() }; Box::pin(ready(Ok(region))) } fn region_for_id(&self, id: RegionId) -> BoxFuture<'static, Result<Region>> { let result = match id { 1 => Ok(Self::region1()), 2 => Ok(Self::region2()), _ => Err(Error::region_not_found(id)), }; Box::pin(ready(result)) } fn get_timestamp(self: Arc<Self>) -> BoxFuture<'static, Result<Timestamp>> { unimplemented!() } } impl DispatchHook for kvrpcpb::ResolveLockRequest { fn dispatch_hook( &self, _opt: CallOption, ) -> Option<BoxFuture<'static, Result<kvrpcpb::ResolveLockResponse>>> { fail_point!("region-error", |_| { let mut resp = kvrpcpb::ResolveLockResponse::default(); resp.region_error = Some(errorpb::Error::default()); Some(ready(Ok(resp)).boxed()) }); Some(ready(Ok(kvrpcpb::ResolveLockResponse::default())).boxed()) } }
use crate::{ pd::{PdClient, PdRpcClient, RetryClient}, request::DispatchHook, Config, Error, Key, Result, Timestamp, }; use fail::fail_point; use futures::future::{ready, BoxFuture, FutureExt}; use grpcio::CallOption; use kvproto::{errorpb, kvrpcpb, metapb, tikvpb::TikvClient}; use std::{future::Future, sync::Arc, time::Duration}; use tikv_client_store::{HasError, KvClient, KvConnect, Region, RegionId, Store}; pub async fn pd_rpc_client() -> PdRpcClient<MockKvConnect, MockCluster> { let config = Config::default(); PdRpcClient::new( &config, |_, _| MockKvConnect, |e, sm| { futures::future::ok(RetryClient::new_with_cluster( e, sm, config.timeout, MockCluster, )) }, ) .await .unwrap() } #[derive(Clone, Eq, PartialEq, Debug)] pub struct MockKvClient { addr: String, } pub struct MockKvConnect; pub struct MockCluster; pub struct MockPdClient; impl KvClient for MockKvClient { fn dispatch<Resp, RpcFuture>( &self, _request_name: &'st
_ => Err(Error::region_not_found(id)), }; Box::pin(ready(result)) } fn get_timestamp(self: Arc<Self>) -> BoxFuture<'static, Result<Timestamp>> { unimplemented!() } } impl DispatchHook for kvrpcpb::ResolveLockRequest { fn dispatch_hook( &self, _opt: CallOption, ) -> Option<BoxFuture<'static, Result<kvrpcpb::ResolveLockResponse>>> { fail_point!("region-error", |_| { let mut resp = kvrpcpb::ResolveLockResponse::default(); resp.region_error = Some(errorpb::Error::default()); Some(ready(Ok(resp)).boxed()) }); Some(ready(Ok(kvrpcpb::ResolveLockResponse::default())).boxed()) } }
atic str, _fut: grpcio::Result<RpcFuture>, ) -> BoxFuture<'static, Result<Resp>> where RpcFuture: Future<Output = std::result::Result<Resp, ::grpcio::Error>>, Resp: HasError + Sized + Clone + Send + 'static, RpcFuture: Send + 'static, { unimplemented!() } fn get_rpc_client(&self) -> Arc<TikvClient> { unimplemented!() } } impl KvConnect for MockKvConnect { type KvClient = MockKvClient; fn connect(&self, address: &str) -> Result<Self::KvClient> { Ok(MockKvClient { addr: address.to_owned(), }) } } impl MockPdClient { pub fn region1() -> Region { let mut region = Region::default(); region.region.id = 1; region.region.set_start_key(vec![0]); region.region.set_end_key(vec![10]); let mut leader = metapb::Peer::default(); leader.store_id = 41; region.leader = Some(leader); region } pub fn region2() -> Region { let mut region = Region::default(); region.region.id = 2; region.region.set_start_key(vec![10]); region.region.set_end_key(vec![250, 250]); let mut leader = metapb::Peer::default(); leader.store_id = 42; region.leader = Some(leader); region } } impl PdClient for MockPdClient { type KvClient = MockKvClient; fn map_region_to_store( self: Arc<Self>, region: Region, ) -> BoxFuture<'static, Result<Store<Self::KvClient>>> { Box::pin(ready(Ok(Store::new( region, MockKvClient { addr: String::new(), }, Duration::from_secs(60), )))) } fn region_for_key(&self, key: &Key) -> BoxFuture<'static, Result<Region>> { let bytes: &[_] = key.into(); let region = if bytes.is_empty() || bytes[0] < 10 { Self::region1() } else { Self::region2() }; Box::pin(ready(Ok(region))) } fn region_for_id(&self, id: RegionId) -> BoxFuture<'static, Result<Region>> { let result = match id { 1 => Ok(Self::region1()), 2 => Ok(Self::region2()),
random
[ { "content": "pub fn new_mvcc_get_request(key: impl Into<Key>, timestamp: Timestamp) -> kvrpcpb::GetRequest {\n\n let mut req = kvrpcpb::GetRequest::default();\n\n req.set_key(key.into().into());\n\n req.set_version(timestamp.version());\n\n req\n\n}\n\n\n\nimpl KvRequest for kvrpcpb::BatchGetReques...
Rust
2021/05_hydrothermal-venture/src/main.rs
macisamuele/adventofcode
34d8994493446f951afc4584d6da7f83e85fd8f8
use helpers::input_lines; use scan_fmt::scan_fmt; use std::collections::HashMap; use std::str::FromStr; const INPUT: &str = include_str!("../input.txt"); #[derive(Debug, PartialEq, Eq, Hash)] struct Point { x: usize, y: usize, } #[derive(Debug, PartialEq, Eq, Hash)] struct Line { point1: Point, point2: Point, } impl FromStr for Line { type Err = anyhow::Error; fn from_str(line: &str) -> Result<Self, Self::Err> { let (x1, y1, x2, y2) = scan_fmt!(line, "{},{} -> {},{}", usize, usize, usize, usize)?; Ok(Self { point1: Point { x: x1, y: y1 }, point2: Point { x: x2, y: y2 }, }) } } impl Line { fn to_horizontal_points(&self) -> impl Iterator<Item = Point> { let y: usize = self.point1.y; let (min_x, max_x): (usize, usize) = if self.point1.y == self.point2.y { if self.point1.x < self.point2.x { (self.point1.x, self.point2.x + 1) } else { (self.point2.x, self.point1.x + 1) } } else { (0, 0) }; (min_x..max_x).map(move |x| Point { x, y }) } fn to_vertical_points(&self) -> impl Iterator<Item = Point> { let x: usize = self.point1.x; let (min_y, max_y): (usize, usize) = if self.point1.x == self.point2.x { if self.point1.y < self.point2.y { (self.point1.y, self.point2.y + 1) } else { (self.point2.y, self.point1.y + 1) } } else { (0, 0) }; (min_y..max_y).map(move |y| Point { x, y }) } fn to_diagonal_points(&self) -> impl Iterator<Item = Point> { let (min_x, max_x): (usize, usize) = if self.point1.x < self.point2.x { (self.point1.x, self.point2.x + 1) } else { (self.point2.x, self.point1.x + 1) }; let (min_y, max_y): (usize, usize) = if self.point1.y < self.point2.y { (self.point1.y, self.point2.y + 1) } else { (self.point2.y, self.point1.y + 1) }; let (is_x_negative_increment, is_y_negative_increment, points_in_line) = if max_x - min_x == max_y - min_y { ( self.point1.x > self.point2.x, self.point1.y > self.point2.y, max_x - min_x, ) } else { (false, false, 0) }; let point1_x = self.point1.x; let point1_y = self.point1.y; (0..points_in_line).map(move |point_number| Point { x: if is_x_negative_increment { point1_x - point_number } else { point1_x + point_number }, y: if is_y_negative_increment { point1_y - point_number } else { point1_y + point_number }, }) } } fn register_point(sparse_grid: &mut HashMap<Point, usize>, key: Point) { let current_value = sparse_grid.get(&key).map_or(0, |value| *value); sparse_grid.insert(key, current_value + 1); } fn part01(lines: &[Line]) -> usize { let mut sparse_grid = HashMap::new(); for line in lines { for point in line.to_horizontal_points().chain(line.to_vertical_points()) { register_point(&mut sparse_grid, point); } } sparse_grid.values().filter(|count| **count >= 2).count() } fn part02(lines: &[Line]) -> usize { let mut sparse_grid = HashMap::new(); for line in lines { for point in line .to_horizontal_points() .chain(line.to_vertical_points()) .chain(line.to_diagonal_points()) { register_point(&mut sparse_grid, point); } } sparse_grid.values().filter(|count| **count >= 2).count() } fn main() -> anyhow::Result<()> { let lines: Vec<Line> = input_lines(INPUT)? .iter() .map(|line| line.parse()) .collect::<Result<_, _>>()?; println!("Part 1: {}", part01(&lines)); println!("Part 2: {}", part02(&lines)); Ok(()) }
use helpers::input_lines; use scan_fmt::scan_fmt; use std::collections::HashMap; use std::str::FromStr; const INPUT: &str = include_str!("../input.txt"); #[derive(Debug, PartialEq, Eq, Hash)] struct Point { x: usize, y: usize, } #[derive(Debug, PartialEq, Eq, Hash)] struct Line { point1: Point, point2: Point, } impl FromStr for Line { type Err = anyhow::Error;
} impl Line { fn to_horizontal_points(&self) -> impl Iterator<Item = Point> { let y: usize = self.point1.y; let (min_x, max_x): (usize, usize) = if self.point1.y == self.point2.y { if self.point1.x < self.point2.x { (self.point1.x, self.point2.x + 1) } else { (self.point2.x, self.point1.x + 1) } } else { (0, 0) }; (min_x..max_x).map(move |x| Point { x, y }) } fn to_vertical_points(&self) -> impl Iterator<Item = Point> { let x: usize = self.point1.x; let (min_y, max_y): (usize, usize) = if self.point1.x == self.point2.x { if self.point1.y < self.point2.y { (self.point1.y, self.point2.y + 1) } else { (self.point2.y, self.point1.y + 1) } } else { (0, 0) }; (min_y..max_y).map(move |y| Point { x, y }) } fn to_diagonal_points(&self) -> impl Iterator<Item = Point> { let (min_x, max_x): (usize, usize) = if self.point1.x < self.point2.x { (self.point1.x, self.point2.x + 1) } else { (self.point2.x, self.point1.x + 1) }; let (min_y, max_y): (usize, usize) = if self.point1.y < self.point2.y { (self.point1.y, self.point2.y + 1) } else { (self.point2.y, self.point1.y + 1) }; let (is_x_negative_increment, is_y_negative_increment, points_in_line) = if max_x - min_x == max_y - min_y { ( self.point1.x > self.point2.x, self.point1.y > self.point2.y, max_x - min_x, ) } else { (false, false, 0) }; let point1_x = self.point1.x; let point1_y = self.point1.y; (0..points_in_line).map(move |point_number| Point { x: if is_x_negative_increment { point1_x - point_number } else { point1_x + point_number }, y: if is_y_negative_increment { point1_y - point_number } else { point1_y + point_number }, }) } } fn register_point(sparse_grid: &mut HashMap<Point, usize>, key: Point) { let current_value = sparse_grid.get(&key).map_or(0, |value| *value); sparse_grid.insert(key, current_value + 1); } fn part01(lines: &[Line]) -> usize { let mut sparse_grid = HashMap::new(); for line in lines { for point in line.to_horizontal_points().chain(line.to_vertical_points()) { register_point(&mut sparse_grid, point); } } sparse_grid.values().filter(|count| **count >= 2).count() } fn part02(lines: &[Line]) -> usize { let mut sparse_grid = HashMap::new(); for line in lines { for point in line .to_horizontal_points() .chain(line.to_vertical_points()) .chain(line.to_diagonal_points()) { register_point(&mut sparse_grid, point); } } sparse_grid.values().filter(|count| **count >= 2).count() } fn main() -> anyhow::Result<()> { let lines: Vec<Line> = input_lines(INPUT)? .iter() .map(|line| line.parse()) .collect::<Result<_, _>>()?; println!("Part 1: {}", part01(&lines)); println!("Part 2: {}", part02(&lines)); Ok(()) }
fn from_str(line: &str) -> Result<Self, Self::Err> { let (x1, y1, x2, y2) = scan_fmt!(line, "{},{} -> {},{}", usize, usize, usize, usize)?; Ok(Self { point1: Point { x: x1, y: y1 }, point2: Point { x: x2, y: y2 }, }) }
function_block-full_function
[ { "content": "type Point = (usize, usize);\n\n\n", "file_path": "2021/15_chiton/src/main.rs", "rank": 0, "score": 208321.5886531291 }, { "content": "fn part02(line: &str) -> usize {\n\n let mut game = GameTable::new(\n\n line.as_bytes()\n\n .iter()\n\n .map(|b...
Rust
src/connectivity/network/tests/dhcp_interop/dhcp_validity/src/lib.rs
EnderNightLord-ChromeBook/fuchsia-pine64-pinephone
05e2c059b57b6217089090a0315971d1735ecf57
use { anyhow::{format_err, Context as _, Error}, fidl_fuchsia_net as fnet, fidl_fuchsia_net_dhcpv6 as fdhcpv6, fidl_fuchsia_net_interfaces as finterfaces, fidl_fuchsia_net_name as fnetname, fidl_fuchsia_net_stack as fstack, fidl_fuchsia_net_stack_ext::FidlReturn as _, fidl_fuchsia_netemul_guest::{ CommandListenerMarker, GuestDiscoveryMarker, GuestInteractionMarker, }, fuchsia_async::TimeoutExt as _, fuchsia_component::client, netemul_guest_lib::wait_for_command_completion, std::time::Duration, }; pub async fn configure_dhcp_server(guest_name: &str, command_to_run: &str) -> Result<(), Error> { let mut env = vec![]; let guest_discovery_service = client::connect_to_service::<GuestDiscoveryMarker>()?; let (gis, gis_ch) = fidl::endpoints::create_proxy::<GuestInteractionMarker>()?; let () = guest_discovery_service.get_guest(None, guest_name, gis_ch)?; let (client_proxy, server_end) = fidl::endpoints::create_proxy::<CommandListenerMarker>()?; gis.execute_command(command_to_run, &mut env.iter_mut(), None, None, None, server_end)?; wait_for_command_completion(client_proxy.take_event_stream(), None).await } pub async fn verify_v4_addr_present(addr: fnet::IpAddress, timeout: Duration) -> Result<(), Error> { let interface_state = client::connect_to_service::<finterfaces::StateMarker>()?; let mut if_map = std::collections::HashMap::new(); fidl_fuchsia_net_interfaces_ext::wait_interface( fidl_fuchsia_net_interfaces_ext::event_stream_from_state(&interface_state)?, &mut if_map, |if_map| { if_map .iter() .filter_map(|(_, properties)| properties.addresses.as_ref()) .flatten() .find_map(|a| if a.addr?.addr == addr { Some(()) } else { None }) }, ) .on_timeout(timeout, || Err(anyhow::anyhow!("timed out"))) .await .map_err(|e| { e.context(format!( "DHCPv4 client got unexpected addresses: {}, address missing: {:?}", if_map.iter().fold(String::from("addresses present:"), |s, (id, properties)| { s + &format!(" {:?}: {:?}", id, properties.addresses) }), addr )) }) } pub async fn verify_v6_dns_servers( interface_id: u64, want_dns_servers: Vec<fnetname::DnsServer_>, ) -> Result<(), Error> { let stack = client::connect_to_service::<fstack::StackMarker>() .context("connecting to stack service")?; let info = stack .get_interface_info(interface_id) .await .squash_result() .context("getting interface info")?; let addr = info .properties .addresses .into_iter() .find_map(|addr: fnet::Subnet| match addr.addr { fnet::IpAddress::Ipv4(_addr) => None, fnet::IpAddress::Ipv6(addr) => { if addr.addr[..8] == [0xfe, 0x80, 0, 0, 0, 0, 0, 0] { Some(addr) } else { None } } }) .ok_or(format_err!("no addresses found to start DHCPv6 client on"))?; let provider = client::connect_to_service::<fdhcpv6::ClientProviderMarker>() .context("connecting to DHCPv6 client")?; let (client_end, server_end) = fidl::endpoints::create_endpoints::<fdhcpv6::ClientMarker>() .context("creating DHCPv6 client channel")?; let () = provider.new_client( fdhcpv6::NewClientParams { interface_id: Some(interface_id), address: Some(fnet::Ipv6SocketAddress { address: addr, port: fdhcpv6::DEFAULT_CLIENT_PORT, zone_index: interface_id, }), models: Some(fdhcpv6::OperationalModels { stateless: Some(fdhcpv6::Stateless { options_to_request: Some(vec![fdhcpv6::RequestableOptionCode::DnsServers]), }), }), }, server_end, )?; let client_proxy = client_end.into_proxy().context("getting client proxy from channel")?; let got_dns_servers = client_proxy.watch_servers().await.context("watching DNS servers")?; if got_dns_servers == want_dns_servers { Ok(()) } else { Err(format_err!( "DHCPv6 client received unexpected DNS servers:\ngot dns servers: {:?}\n, want dns servers: {:?}\n", got_dns_servers, want_dns_servers )) } }
use { anyhow::{format_err, Context as _, Error}, fidl_fuchsia_net as fnet, fidl_fuchsia_net_dhcpv6 as fdhcpv6, fidl_fuchsia_net_interfaces as finterfaces, fidl_fuchsia_net_name as fnetname, fidl_fuchsia_net_stack as fstack, fidl_fuchsia_net_stack_ext::FidlReturn as _, fidl_fuchsia_netemul_guest::{ CommandListenerMarker, GuestDiscoveryMarker, GuestInteractionMarker, }, fuchsia_async::TimeoutExt as _, fuchsia_component::client, netemul_guest_lib::wait_for_command_completion, std::time::Duration, }; pub async fn configure_dhcp_server(guest_name: &str, command_to_run: &str) -> Result<(), Error> { let mut env = vec![]; let guest_discovery_service = client::connect_to_service::<GuestDiscoveryMarker>()?; let (gis, gis_ch) = fidl::endpoints::create_proxy::<GuestInteractionMarker>()?; let () = guest_discovery_service.get_guest(None, guest_name, gis_ch)?; let (client_proxy, server_end) = fidl::endpoints::create_proxy::<CommandListenerMarker>()?; gis.execute_command(command_to_run, &mut env.iter_mut(), None, None, None, server_end)?; wait_for_command_completion(client_proxy.take_event_stream(), None).await }
pub async fn verify_v6_dns_servers( interface_id: u64, want_dns_servers: Vec<fnetname::DnsServer_>, ) -> Result<(), Error> { let stack = client::connect_to_service::<fstack::StackMarker>() .context("connecting to stack service")?; let info = stack .get_interface_info(interface_id) .await .squash_result() .context("getting interface info")?; let addr = info .properties .addresses .into_iter() .find_map(|addr: fnet::Subnet| match addr.addr { fnet::IpAddress::Ipv4(_addr) => None, fnet::IpAddress::Ipv6(addr) => { if addr.addr[..8] == [0xfe, 0x80, 0, 0, 0, 0, 0, 0] { Some(addr) } else { None } } }) .ok_or(format_err!("no addresses found to start DHCPv6 client on"))?; let provider = client::connect_to_service::<fdhcpv6::ClientProviderMarker>() .context("connecting to DHCPv6 client")?; let (client_end, server_end) = fidl::endpoints::create_endpoints::<fdhcpv6::ClientMarker>() .context("creating DHCPv6 client channel")?; let () = provider.new_client( fdhcpv6::NewClientParams { interface_id: Some(interface_id), address: Some(fnet::Ipv6SocketAddress { address: addr, port: fdhcpv6::DEFAULT_CLIENT_PORT, zone_index: interface_id, }), models: Some(fdhcpv6::OperationalModels { stateless: Some(fdhcpv6::Stateless { options_to_request: Some(vec![fdhcpv6::RequestableOptionCode::DnsServers]), }), }), }, server_end, )?; let client_proxy = client_end.into_proxy().context("getting client proxy from channel")?; let got_dns_servers = client_proxy.watch_servers().await.context("watching DNS servers")?; if got_dns_servers == want_dns_servers { Ok(()) } else { Err(format_err!( "DHCPv6 client received unexpected DNS servers:\ngot dns servers: {:?}\n, want dns servers: {:?}\n", got_dns_servers, want_dns_servers )) } }
pub async fn verify_v4_addr_present(addr: fnet::IpAddress, timeout: Duration) -> Result<(), Error> { let interface_state = client::connect_to_service::<finterfaces::StateMarker>()?; let mut if_map = std::collections::HashMap::new(); fidl_fuchsia_net_interfaces_ext::wait_interface( fidl_fuchsia_net_interfaces_ext::event_stream_from_state(&interface_state)?, &mut if_map, |if_map| { if_map .iter() .filter_map(|(_, properties)| properties.addresses.as_ref()) .flatten() .find_map(|a| if a.addr?.addr == addr { Some(()) } else { None }) }, ) .on_timeout(timeout, || Err(anyhow::anyhow!("timed out"))) .await .map_err(|e| { e.context(format!( "DHCPv4 client got unexpected addresses: {}, address missing: {:?}", if_map.iter().fold(String::from("addresses present:"), |s, (id, properties)| { s + &format!(" {:?}: {:?}", id, properties.addresses) }), addr )) }) }
function_block-full_function
[]
Rust
src/csv2json/mod.rs
perzanko/csv2json
aae4c50856f73fc0f88450dd2f38ad8fc6ffaeae
extern crate serde_json; use std::collections::HashMap; use std::env; use std::fs::File; use std::io; use std::io::prelude::*; use std::process; use std::time::Instant; type Lines = Vec<String>; type Nav = String; type NavKeys = Vec<String>; type Args = Vec<String>; type Rows = Vec<HashMap<String, String>>; type Hash = HashMap<String, String>; pub fn new() { let start_time = Instant::now(); let (input_file, output_file) = parse_args(&env::args().collect::<Args>()); if is_str_empty(&input_file) || is_str_empty(&output_file) { show_help(); process::exit(0x0100); } let nav_with_lines: (Nav, Lines) = read_file(&input_file).unwrap(); let nav: NavKeys = fetch_keys(&nav_with_lines.0); let rows: Rows = generate_rows(&nav_with_lines.1, &nav); let json = serde_json::to_string(&rows).unwrap(); match write_file(&output_file, &json) { Ok(()) => println!("Ok, done! - {}", output_file), Err(err) => println!("Something went wrong. {}", err), }; println!("Rows: {}", rows.len()); println!("Elapsed: {} ms", get_elapsed_time(start_time)); } fn parse_args(args: &Args) -> (String, String) { let mut input_file = String::new(); let mut output_file = String::new(); let mut args: Args = args.clone(); args.remove(0); args.chunks(2).for_each(|x| match x[0].as_ref() { "--input" => { input_file = x[1].clone(); } "-i" => { input_file = x[1].clone(); } "--output" => { output_file = x[1].clone(); } "-o" => { output_file = x[1].clone(); } _ => {} }); (input_file, output_file) } fn read_file(file_path: &String) -> Result<(Nav, Lines), io::Error> { let file = File::open(file_path)?; let buf_reader = io::BufReader::new(file); let mut lines = Vec::new(); let mut nav = String::new(); for (i, line) in buf_reader.lines().enumerate() { let line = line.unwrap(); if i == 0 { nav = line } else { lines.push(line) } } Ok((nav, lines)) } fn write_file(file_path: &String, data: &String) -> Result<(), io::Error> { let mut file = File::create(file_path)?; file.write_all(&data.as_bytes())?; Ok(()) } fn fetch_keys(keys_str: &String) -> NavKeys { let mut i: i16 = -1; keys_str .split(",") .collect::<Vec<&str>>() .into_iter() .map(|key| { i += 1; String::from(key) }) .collect() } fn generate_rows(lines: &Lines, nav: &NavKeys) -> Vec<Hash> { lines .into_iter() .map(|line| { let mut hash: HashMap<String, String> = HashMap::new(); let mut i = 0; let nav = nav; line.split(",") .collect::<Vec<&str>>() .into_iter() .for_each(|x| { i += 1; hash.insert(nav[i - 1].clone(), String::from(x)); }); return hash; }) .collect() } fn show_help() { print!( " Created by perzanko ---- .o88b. .d8888. db db .d888b. d88b .d8888. .d88b. d8b db d8P Y8 88' YP 88 88 VP `8D `8P' 88' YP .8P Y8. 888o 88 8P `8bo. Y8 8P odD' 88 `8bo. 88 88 88V8o 88 8b `Y8b. `8b d8' .88' 88 `Y8b. 88 88 88 V8o88 Y8b d8 db 8D `8bd8' j88. db. 88 db 8D `8b d8' 88 V888 `Y88P' `8888Y' YP 888888D Y8888P `8888Y' `Y88P' VP V8P This tool provides simple and efficient csv to json conversion. Usage: csv2json --input [path] --output [path] -h, --help print this help -i, --input input path of CSV file -o, --output output path of converted JSON " ) } fn is_str_empty(text: &String) -> bool { if text.trim().len() == 0 { true } else { false } } fn get_elapsed_time(start_time: Instant) -> String { let x = start_time.elapsed(); ((x.as_secs() * 1_000) + (x.subsec_nanos() / 1_000_000) as u64).to_string() }
extern crate serde_json; use std::collections::HashMap; use std::env; use std::fs::File; use std::io; use std::io::prelude::*; use std::process; use std::time::Instant; type Lines = Vec<String>; type Nav = String; type NavKeys = Vec<String>; type Args = Vec<String>; type Rows = Vec<HashMap<String, String>>; type Hash = HashMap<String, String>; pub fn new() { let start_time = Instant::now(); let (input_file, output_file) = parse_args(&env::args().collect::<Args>()); if is_str_empty(&input_file) || is_str_empty(&output_file) { show_help(); process::exit(0x0100); } let nav_with_lines: (Nav, Lines) = read_file(&input_file).unwrap(); let nav: NavKeys = fetch_keys(&nav_with_lines.0); let rows: Rows = generate_rows(&nav_with_lines.1, &nav); let json = serde_json::to_string(&rows).unwrap(); match write_file(&output_file, &json) { Ok(()) => println!("Ok, done! - {}", output_file), Err(err) => println!("Something went wrong. {}", err), }; println!("Rows: {}", rows.len()); println!("Elapsed: {} ms", get_elapsed_time(start_time)); } fn parse_args(args: &Args) -> (String, String) {
fn read_file(file_path: &String) -> Result<(Nav, Lines), io::Error> { let file = File::open(file_path)?; let buf_reader = io::BufReader::new(file); let mut lines = Vec::new(); let mut nav = String::new(); for (i, line) in buf_reader.lines().enumerate() { let line = line.unwrap(); if i == 0 { nav = line } else { lines.push(line) } } Ok((nav, lines)) } fn write_file(file_path: &String, data: &String) -> Result<(), io::Error> { let mut file = File::create(file_path)?; file.write_all(&data.as_bytes())?; Ok(()) } fn fetch_keys(keys_str: &String) -> NavKeys { let mut i: i16 = -1; keys_str .split(",") .collect::<Vec<&str>>() .into_iter() .map(|key| { i += 1; String::from(key) }) .collect() } fn generate_rows(lines: &Lines, nav: &NavKeys) -> Vec<Hash> { lines .into_iter() .map(|line| { let mut hash: HashMap<String, String> = HashMap::new(); let mut i = 0; let nav = nav; line.split(",") .collect::<Vec<&str>>() .into_iter() .for_each(|x| { i += 1; hash.insert(nav[i - 1].clone(), String::from(x)); }); return hash; }) .collect() } fn show_help() { print!( " Created by perzanko ---- .o88b. .d8888. db db .d888b. d88b .d8888. .d88b. d8b db d8P Y8 88' YP 88 88 VP `8D `8P' 88' YP .8P Y8. 888o 88 8P `8bo. Y8 8P odD' 88 `8bo. 88 88 88V8o 88 8b `Y8b. `8b d8' .88' 88 `Y8b. 88 88 88 V8o88 Y8b d8 db 8D `8bd8' j88. db. 88 db 8D `8b d8' 88 V888 `Y88P' `8888Y' YP 888888D Y8888P `8888Y' `Y88P' VP V8P This tool provides simple and efficient csv to json conversion. Usage: csv2json --input [path] --output [path] -h, --help print this help -i, --input input path of CSV file -o, --output output path of converted JSON " ) } fn is_str_empty(text: &String) -> bool { if text.trim().len() == 0 { true } else { false } } fn get_elapsed_time(start_time: Instant) -> String { let x = start_time.elapsed(); ((x.as_secs() * 1_000) + (x.subsec_nanos() / 1_000_000) as u64).to_string() }
let mut input_file = String::new(); let mut output_file = String::new(); let mut args: Args = args.clone(); args.remove(0); args.chunks(2).for_each(|x| match x[0].as_ref() { "--input" => { input_file = x[1].clone(); } "-i" => { input_file = x[1].clone(); } "--output" => { output_file = x[1].clone(); } "-o" => { output_file = x[1].clone(); } _ => {} }); (input_file, output_file) }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n csv2json::new();\n\n}\n", "file_path": "src/main.rs", "rank": 15, "score": 25552.07465452124 }, { "content": "# csv2json\n\n\n\nThis tool provides simple and efficient csv to json converting, written in Rust.\n\n\n\n## Getting Started\n\n\n\nYou need to have ...
Rust
python/src/lib.rs
kngwyu/rogue-gym
00de77e6c9f3d2b9ed602f93abb5526c13791ca9
#[macro_use] extern crate failure; extern crate ndarray; extern crate numpy; extern crate pyo3; extern crate rect_iter; extern crate rogue_gym_core; #[cfg(unix)] extern crate rogue_gym_devui; mod fearures; mod state_impls; mod thread_impls; use fearures::{MessageFlagInner, StatusFlagInner}; use ndarray::{Array2, Axis, Zip}; use numpy::PyArray3; use pyo3::{ basic::{PyObjectProtocol, PyObjectReprProtocol, PyObjectStrProtocol}, exceptions::RuntimeError, prelude::*, }; use rect_iter::{Get2D, GetMut2D, RectRange}; use rogue_gym_core::character::player::Status; use rogue_gym_core::dungeon::{Positioned, X, Y}; use rogue_gym_core::{error::*, symbol, GameConfig, RunTime}; use state_impls::GameStateImpl; use std::collections::HashMap; use std::fmt::Display; use std::str::from_utf8_unchecked; use thread_impls::ThreadConductor; fn pyresult<T, E: Display>(result: Result<T, E>) -> PyResult<T> { pyresult_with(result, "Error in rogue-gym") } fn pyresult_with<T, E: Display>(result: Result<T, E>, msg: &str) -> PyResult<T> { result.map_err(|e| PyErr::new::<RuntimeError, _>(format!("{}: {}", msg, e))) } #[pyclass] #[derive(Clone, Debug, PartialEq)] struct PlayerState { map: Vec<Vec<u8>>, history: Array2<bool>, status: Status, symbols: u8, message: MessageFlagInner, is_terminal: bool, } impl PlayerState { fn new(w: X, h: Y, symbols: u8) -> Self { let (w, h) = (w.0 as usize, h.0 as usize); PlayerState { map: vec![vec![b' '; w]; h], history: Array2::from_elem([h, w], false), status: Status::default(), symbols, message: MessageFlagInner::new(), is_terminal: false, } } fn reset(&mut self, runtime: &RunTime) -> GameResult<()> { self.status = runtime.player_status(); self.draw_map(runtime)?; self.message = MessageFlagInner::new(); self.is_terminal = false; Ok(()) } fn draw_map(&mut self, runtime: &RunTime) -> GameResult<()> { self.history = runtime.history(&self.status).unwrap(); runtime.draw_screen(|Positioned(cd, tile)| -> GameResult<()> { *self .map .try_get_mut_p(cd) .into_chained(|| "in python::GameState::react")? = tile.to_byte(); Ok(()) }) } fn dungeon_str(&self) -> impl Iterator<Item = &str> { self.map.iter().map(|v| unsafe { from_utf8_unchecked(v) }) } fn gray_image_with_offset<'py>( &self, py: Python<'py>, offset: usize, ) -> PyResult<&'py PyArray3<f32>> { let (h, w) = (self.map.len(), self.map[0].len()); let py_array = PyArray3::zeros(py, [1 + offset, h, w], false); RectRange::zero_start(w, h) .unwrap() .into_iter() .for_each(|(x, y)| unsafe { let symbol = symbol::tile_to_sym(*self.map.get_xy(x, y)).unwrap(); *py_array.uget_mut([0, y, x]) = f32::from(symbol) / f32::from(self.symbols); }); Ok(py_array) } fn symbol_image_with_offset<'py>( &self, py: Python<'py>, offset: usize, ) -> PyResult<&'py PyArray3<f32>> { let (h, w) = (self.map.len(), self.map[0].len()); let channels = usize::from(self.symbols); let py_array = PyArray3::zeros(py, [channels + offset, h, w], false); pyresult(symbol::construct_symbol_map( &self.map, h, w, self.symbols - 1, |idx| unsafe { py_array.uget_mut(idx) }, ))?; Ok(py_array) } fn copy_hist(&self, py_array: &PyArray3<f32>, offset: usize) { let mut array = py_array.as_array_mut(); let hist_array = array.index_axis_mut(Axis(0), usize::from(offset)); Zip::from(hist_array).and(&self.history).apply(|p, &r| { *p = if r { 1.0 } else { 0.0 }; }); } } impl<'p> PyObjectReprProtocol<'p> for PlayerState { type Success = String; type Result = PyResult<String>; } impl<'p> PyObjectStrProtocol<'p> for PlayerState { type Success = String; type Result = PyResult<String>; } impl<'p> PyObjectProtocol<'p> for PlayerState { fn __repr__(&'p self) -> <Self as PyObjectReprProtocol>::Result { let mut dungeon = self.dungeon_str().fold(String::new(), |mut res, s| { res.push_str(s); res.push('\n'); res }); dungeon.push_str(&format!("{}", self.status)); Ok(dungeon) } fn __str__(&'p self) -> <Self as PyObjectStrProtocol>::Result { self.__repr__() } } #[pymethods] impl PlayerState { #[getter] fn status(&self) -> PyResult<HashMap<String, u32>> { Ok(self .status .to_dict_vec() .into_iter() .map(|(s, v)| (s.to_owned(), v)) .collect()) } #[getter] fn dungeon(&self) -> PyResult<Vec<String>> { Ok(self.dungeon_str().map(|s| s.to_string()).collect()) } #[getter] fn dungeon_level(&self) -> PyResult<u32> { Ok(self.status.dungeon_level) } #[getter] fn gold(&self) -> PyResult<u32> { Ok(self.status.gold) } #[getter] fn symbols(&self) -> PyResult<usize> { Ok(usize::from(self.symbols)) } #[getter] fn is_terminal(&self) -> PyResult<bool> { Ok(self.is_terminal) } fn status_vec(&self, flag: u32) -> Vec<i32> { let flag = StatusFlagInner(flag); flag.to_vector(&self.status) } fn gray_image(&self, flag: Option<u32>) -> PyResult<&PyArray3<f32>> { let (py, flag) = ( unsafe { Python::assume_gil_acquired() }, StatusFlagInner::from(flag), ); let array = self.gray_image_with_offset(py, flag.len())?; flag.copy_status(&self.status, 1, &mut array.as_array_mut()); Ok(array) } fn gray_image_with_hist(&self, flag: Option<u32>) -> PyResult<&PyArray3<f32>> { let (py, flag) = ( unsafe { Python::assume_gil_acquired() }, StatusFlagInner::from(flag), ); let array = self.gray_image_with_offset(py, flag.len() + 1)?; let offset = flag.copy_status(&self.status, 1, &mut array.as_array_mut()); self.copy_hist(&array, offset); Ok(array) } fn symbol_image(&self, flag: Option<u32>) -> PyResult<&PyArray3<f32>> { let (py, flag) = ( unsafe { Python::assume_gil_acquired() }, StatusFlagInner::from(flag), ); let array = self.symbol_image_with_offset(py, flag.len())?; flag.copy_status( &self.status, usize::from(self.symbols), &mut array.as_array_mut(), ); Ok(array) } fn symbol_image_with_hist(&self, flag: Option<u32>) -> PyResult<&PyArray3<f32>> { let (py, flag) = ( unsafe { Python::assume_gil_acquired() }, StatusFlagInner::from(flag), ); let array = self.symbol_image_with_offset(py, flag.len() + 1)?; let offset = flag.copy_status( &self.status, usize::from(self.symbols), &mut array.as_array_mut(), ); self.copy_hist(&array, offset); Ok(array) } } #[pyclass] struct GameState { inner: GameStateImpl, config: GameConfig, } #[pymethods] impl GameState { #[new] fn __new__(obj: &PyRawObject, max_steps: usize, config_str: Option<String>) -> PyResult<()> { let config = if let Some(cfg) = config_str { pyresult_with(GameConfig::from_json(&cfg), "Failed to parse config")? } else { GameConfig::default() }; let inner = pyresult(GameStateImpl::new(config.clone(), max_steps))?; obj.init(GameState { inner, config }); Ok(()) } fn screen_size(&self) -> (i32, i32) { (self.config.height, self.config.width) } fn set_seed(&mut self, seed: u64) -> PyResult<()> { self.config.seed = Some(seed as u128); Ok(()) } fn reset(&mut self) -> PyResult<()> { pyresult(self.inner.reset(self.config.clone())) } fn prev(&self) -> PlayerState { self.inner.state() } fn react(&mut self, input: u8) -> PyResult<()> { pyresult(self.inner.react(input)) } fn dump_history(&self) -> PyResult<String> { pyresult_with( self.inner.runtime.saved_inputs_as_json(), "Error when getting history", ) } fn dump_config(&self) -> PyResult<String> { pyresult_with(self.config.to_json(), "Error when getting config") } fn symbols(&self) -> PyResult<usize> { Ok(self.inner.symbols()) } } #[pyclass] struct ParallelGameState { conductor: ThreadConductor, configs: Vec<GameConfig>, symbols: u8, } #[pymethods] impl ParallelGameState { #[new] fn __new__( obj: &PyRawObject, py: Python, max_steps: usize, configs: Vec<String>, ) -> PyResult<()> { let configs = { let mut res = vec![]; for cfg in configs { res.push(pyresult_with( GameConfig::from_json(&cfg), "Failed to parse config", )?); } res }; let symbols = configs[0] .symbol_max() .expect("Failed to get symbol max") .to_byte() + 1; let cloned = configs.clone(); let conductor = py.allow_threads(move || ThreadConductor::new(cloned, max_steps)); let conductor = pyresult(conductor)?; obj.init(ParallelGameState { conductor, configs, symbols, }); Ok(()) } fn screen_size(&self) -> (i32, i32) { (self.configs[0].height, self.configs[0].width) } fn symbols(&self) -> PyResult<usize> { Ok(usize::from(self.symbols)) } fn seed(&mut self, py: Python, seed: Vec<u128>) -> PyResult<()> { let ParallelGameState { ref mut conductor, .. } = self; let res = py.allow_threads(move || conductor.seed(seed)); pyresult(res) } fn states(&mut self, py: Python) -> PyResult<Vec<PlayerState>> { let ParallelGameState { ref mut conductor, .. } = self; let res = py.allow_threads(move || conductor.states()); pyresult(res) } fn step(&mut self, py: Python, input: Vec<u8>) -> PyResult<Vec<PlayerState>> { let ParallelGameState { ref mut conductor, .. } = self; let res = py.allow_threads(move || conductor.step(input)); pyresult(res) } fn reset(&mut self, py: Python) -> PyResult<Vec<PlayerState>> { let ParallelGameState { ref mut conductor, .. } = self; let res = py.allow_threads(move || conductor.reset()); pyresult(res) } fn close(&mut self, py: Python) -> PyResult<()> { let ParallelGameState { ref mut conductor, .. } = self; pyresult(py.allow_threads(move || conductor.close())) } } #[cfg(unix)] #[pyfunction] fn replay(game: &GameState, py: Python, interval_ms: u64) -> PyResult<()> { use rogue_gym_devui::show_replay; let inputs = game.inner.runtime.saved_inputs().to_vec(); let config = game.config.clone(); let res = py.allow_threads(move || show_replay(config, inputs, interval_ms)); pyresult(res) } #[cfg(unix)] #[pyfunction] fn play_cli(game: &GameState) -> PyResult<()> { use rogue_gym_devui::play_game; pyresult(play_game(game.config.clone(), false))?; Ok(()) } #[pymodule(_rogue_gym)] fn init_mod(_py: Python, m: &PyModule) -> PyResult<()> { m.add_class::<GameState>()?; m.add_class::<PlayerState>()?; m.add_class::<ParallelGameState>()?; #[cfg(unix)] m.add_wrapped(pyo3::wrap_pyfunction!(replay))?; #[cfg(unix)] m.add_wrapped(pyo3::wrap_pyfunction!(play_cli))?; Ok(()) }
#[macro_use] extern crate failure; extern crate ndarray; extern crate numpy; extern crate pyo3; extern crate rect_iter; exter
sage: MessageFlagInner, is_terminal: bool, } impl PlayerState { fn new(w: X, h: Y, symbols: u8) -> Self { let (w, h) = (w.0 as usize, h.0 as usize); PlayerState { map: vec![vec![b' '; w]; h], history: Array2::from_elem([h, w], false), status: Status::default(), symbols, message: MessageFlagInner::new(), is_terminal: false, } } fn reset(&mut self, runtime: &RunTime) -> GameResult<()> { self.status = runtime.player_status(); self.draw_map(runtime)?; self.message = MessageFlagInner::new(); self.is_terminal = false; Ok(()) } fn draw_map(&mut self, runtime: &RunTime) -> GameResult<()> { self.history = runtime.history(&self.status).unwrap(); runtime.draw_screen(|Positioned(cd, tile)| -> GameResult<()> { *self .map .try_get_mut_p(cd) .into_chained(|| "in python::GameState::react")? = tile.to_byte(); Ok(()) }) } fn dungeon_str(&self) -> impl Iterator<Item = &str> { self.map.iter().map(|v| unsafe { from_utf8_unchecked(v) }) } fn gray_image_with_offset<'py>( &self, py: Python<'py>, offset: usize, ) -> PyResult<&'py PyArray3<f32>> { let (h, w) = (self.map.len(), self.map[0].len()); let py_array = PyArray3::zeros(py, [1 + offset, h, w], false); RectRange::zero_start(w, h) .unwrap() .into_iter() .for_each(|(x, y)| unsafe { let symbol = symbol::tile_to_sym(*self.map.get_xy(x, y)).unwrap(); *py_array.uget_mut([0, y, x]) = f32::from(symbol) / f32::from(self.symbols); }); Ok(py_array) } fn symbol_image_with_offset<'py>( &self, py: Python<'py>, offset: usize, ) -> PyResult<&'py PyArray3<f32>> { let (h, w) = (self.map.len(), self.map[0].len()); let channels = usize::from(self.symbols); let py_array = PyArray3::zeros(py, [channels + offset, h, w], false); pyresult(symbol::construct_symbol_map( &self.map, h, w, self.symbols - 1, |idx| unsafe { py_array.uget_mut(idx) }, ))?; Ok(py_array) } fn copy_hist(&self, py_array: &PyArray3<f32>, offset: usize) { let mut array = py_array.as_array_mut(); let hist_array = array.index_axis_mut(Axis(0), usize::from(offset)); Zip::from(hist_array).and(&self.history).apply(|p, &r| { *p = if r { 1.0 } else { 0.0 }; }); } } impl<'p> PyObjectReprProtocol<'p> for PlayerState { type Success = String; type Result = PyResult<String>; } impl<'p> PyObjectStrProtocol<'p> for PlayerState { type Success = String; type Result = PyResult<String>; } impl<'p> PyObjectProtocol<'p> for PlayerState { fn __repr__(&'p self) -> <Self as PyObjectReprProtocol>::Result { let mut dungeon = self.dungeon_str().fold(String::new(), |mut res, s| { res.push_str(s); res.push('\n'); res }); dungeon.push_str(&format!("{}", self.status)); Ok(dungeon) } fn __str__(&'p self) -> <Self as PyObjectStrProtocol>::Result { self.__repr__() } } #[pymethods] impl PlayerState { #[getter] fn status(&self) -> PyResult<HashMap<String, u32>> { Ok(self .status .to_dict_vec() .into_iter() .map(|(s, v)| (s.to_owned(), v)) .collect()) } #[getter] fn dungeon(&self) -> PyResult<Vec<String>> { Ok(self.dungeon_str().map(|s| s.to_string()).collect()) } #[getter] fn dungeon_level(&self) -> PyResult<u32> { Ok(self.status.dungeon_level) } #[getter] fn gold(&self) -> PyResult<u32> { Ok(self.status.gold) } #[getter] fn symbols(&self) -> PyResult<usize> { Ok(usize::from(self.symbols)) } #[getter] fn is_terminal(&self) -> PyResult<bool> { Ok(self.is_terminal) } fn status_vec(&self, flag: u32) -> Vec<i32> { let flag = StatusFlagInner(flag); flag.to_vector(&self.status) } fn gray_image(&self, flag: Option<u32>) -> PyResult<&PyArray3<f32>> { let (py, flag) = ( unsafe { Python::assume_gil_acquired() }, StatusFlagInner::from(flag), ); let array = self.gray_image_with_offset(py, flag.len())?; flag.copy_status(&self.status, 1, &mut array.as_array_mut()); Ok(array) } fn gray_image_with_hist(&self, flag: Option<u32>) -> PyResult<&PyArray3<f32>> { let (py, flag) = ( unsafe { Python::assume_gil_acquired() }, StatusFlagInner::from(flag), ); let array = self.gray_image_with_offset(py, flag.len() + 1)?; let offset = flag.copy_status(&self.status, 1, &mut array.as_array_mut()); self.copy_hist(&array, offset); Ok(array) } fn symbol_image(&self, flag: Option<u32>) -> PyResult<&PyArray3<f32>> { let (py, flag) = ( unsafe { Python::assume_gil_acquired() }, StatusFlagInner::from(flag), ); let array = self.symbol_image_with_offset(py, flag.len())?; flag.copy_status( &self.status, usize::from(self.symbols), &mut array.as_array_mut(), ); Ok(array) } fn symbol_image_with_hist(&self, flag: Option<u32>) -> PyResult<&PyArray3<f32>> { let (py, flag) = ( unsafe { Python::assume_gil_acquired() }, StatusFlagInner::from(flag), ); let array = self.symbol_image_with_offset(py, flag.len() + 1)?; let offset = flag.copy_status( &self.status, usize::from(self.symbols), &mut array.as_array_mut(), ); self.copy_hist(&array, offset); Ok(array) } } #[pyclass] struct GameState { inner: GameStateImpl, config: GameConfig, } #[pymethods] impl GameState { #[new] fn __new__(obj: &PyRawObject, max_steps: usize, config_str: Option<String>) -> PyResult<()> { let config = if let Some(cfg) = config_str { pyresult_with(GameConfig::from_json(&cfg), "Failed to parse config")? } else { GameConfig::default() }; let inner = pyresult(GameStateImpl::new(config.clone(), max_steps))?; obj.init(GameState { inner, config }); Ok(()) } fn screen_size(&self) -> (i32, i32) { (self.config.height, self.config.width) } fn set_seed(&mut self, seed: u64) -> PyResult<()> { self.config.seed = Some(seed as u128); Ok(()) } fn reset(&mut self) -> PyResult<()> { pyresult(self.inner.reset(self.config.clone())) } fn prev(&self) -> PlayerState { self.inner.state() } fn react(&mut self, input: u8) -> PyResult<()> { pyresult(self.inner.react(input)) } fn dump_history(&self) -> PyResult<String> { pyresult_with( self.inner.runtime.saved_inputs_as_json(), "Error when getting history", ) } fn dump_config(&self) -> PyResult<String> { pyresult_with(self.config.to_json(), "Error when getting config") } fn symbols(&self) -> PyResult<usize> { Ok(self.inner.symbols()) } } #[pyclass] struct ParallelGameState { conductor: ThreadConductor, configs: Vec<GameConfig>, symbols: u8, } #[pymethods] impl ParallelGameState { #[new] fn __new__( obj: &PyRawObject, py: Python, max_steps: usize, configs: Vec<String>, ) -> PyResult<()> { let configs = { let mut res = vec![]; for cfg in configs { res.push(pyresult_with( GameConfig::from_json(&cfg), "Failed to parse config", )?); } res }; let symbols = configs[0] .symbol_max() .expect("Failed to get symbol max") .to_byte() + 1; let cloned = configs.clone(); let conductor = py.allow_threads(move || ThreadConductor::new(cloned, max_steps)); let conductor = pyresult(conductor)?; obj.init(ParallelGameState { conductor, configs, symbols, }); Ok(()) } fn screen_size(&self) -> (i32, i32) { (self.configs[0].height, self.configs[0].width) } fn symbols(&self) -> PyResult<usize> { Ok(usize::from(self.symbols)) } fn seed(&mut self, py: Python, seed: Vec<u128>) -> PyResult<()> { let ParallelGameState { ref mut conductor, .. } = self; let res = py.allow_threads(move || conductor.seed(seed)); pyresult(res) } fn states(&mut self, py: Python) -> PyResult<Vec<PlayerState>> { let ParallelGameState { ref mut conductor, .. } = self; let res = py.allow_threads(move || conductor.states()); pyresult(res) } fn step(&mut self, py: Python, input: Vec<u8>) -> PyResult<Vec<PlayerState>> { let ParallelGameState { ref mut conductor, .. } = self; let res = py.allow_threads(move || conductor.step(input)); pyresult(res) } fn reset(&mut self, py: Python) -> PyResult<Vec<PlayerState>> { let ParallelGameState { ref mut conductor, .. } = self; let res = py.allow_threads(move || conductor.reset()); pyresult(res) } fn close(&mut self, py: Python) -> PyResult<()> { let ParallelGameState { ref mut conductor, .. } = self; pyresult(py.allow_threads(move || conductor.close())) } } #[cfg(unix)] #[pyfunction] fn replay(game: &GameState, py: Python, interval_ms: u64) -> PyResult<()> { use rogue_gym_devui::show_replay; let inputs = game.inner.runtime.saved_inputs().to_vec(); let config = game.config.clone(); let res = py.allow_threads(move || show_replay(config, inputs, interval_ms)); pyresult(res) } #[cfg(unix)] #[pyfunction] fn play_cli(game: &GameState) -> PyResult<()> { use rogue_gym_devui::play_game; pyresult(play_game(game.config.clone(), false))?; Ok(()) } #[pymodule(_rogue_gym)] fn init_mod(_py: Python, m: &PyModule) -> PyResult<()> { m.add_class::<GameState>()?; m.add_class::<PlayerState>()?; m.add_class::<ParallelGameState>()?; #[cfg(unix)] m.add_wrapped(pyo3::wrap_pyfunction!(replay))?; #[cfg(unix)] m.add_wrapped(pyo3::wrap_pyfunction!(play_cli))?; Ok(()) }
n crate rogue_gym_core; #[cfg(unix)] extern crate rogue_gym_devui; mod fearures; mod state_impls; mod thread_impls; use fearures::{MessageFlagInner, StatusFlagInner}; use ndarray::{Array2, Axis, Zip}; use numpy::PyArray3; use pyo3::{ basic::{PyObjectProtocol, PyObjectReprProtocol, PyObjectStrProtocol}, exceptions::RuntimeError, prelude::*, }; use rect_iter::{Get2D, GetMut2D, RectRange}; use rogue_gym_core::character::player::Status; use rogue_gym_core::dungeon::{Positioned, X, Y}; use rogue_gym_core::{error::*, symbol, GameConfig, RunTime}; use state_impls::GameStateImpl; use std::collections::HashMap; use std::fmt::Display; use std::str::from_utf8_unchecked; use thread_impls::ThreadConductor; fn pyresult<T, E: Display>(result: Result<T, E>) -> PyResult<T> { pyresult_with(result, "Error in rogue-gym") } fn pyresult_with<T, E: Display>(result: Result<T, E>, msg: &str) -> PyResult<T> { result.map_err(|e| PyErr::new::<RuntimeError, _>(format!("{}: {}", msg, e))) } #[pyclass] #[derive(Clone, Debug, PartialEq)] struct PlayerState { map: Vec<Vec<u8>>, history: Array2<bool>, status: Status, symbols: u8, mes
random
[ { "content": "#![cfg_attr(test, feature(test))]\n\n#[macro_use]\n\nextern crate bitflags;\n\n#[macro_use]\n\nextern crate derive_more;\n\n#[macro_use]\n\nextern crate enum_iterator;\n\n#[macro_use]\n\nextern crate failure;\n\nextern crate fixedbitset;\n\nextern crate ndarray;\n\nextern crate num_traits;\n\n#[ma...
Rust
src/bin/2019_day20.rs
ibookstein/aoc
6beb8369f80d47eef95022ced9a9b9a9bccc7d99
use aoc::aoc_input::get_input; use itertools::iproduct; use std::collections::{HashMap, HashSet}; use std::convert::{TryFrom, TryInto}; use std::ops::Index; use std::str::FromStr; type Vertex = usize; type Label = (usize, usize); type LabelMap = HashMap<Label, Vertex>; type VertexSet = HashSet<Vertex>; type AdjacencyList = Vec<VertexSet>; #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum BfsReply { Halt, Continue, } #[derive(Debug)] struct Graph { label_map: LabelMap, adj_list: AdjacencyList, } impl Graph { fn new() -> Graph { Graph { label_map: LabelMap::new(), adj_list: AdjacencyList::new(), } } fn get_or_insert_vertex(&mut self, label: &Label) -> Vertex { match self.label_map.get(label) { Some(v) => *v, None => { let new_vertex = self.adj_list.len(); self.adj_list.push(VertexSet::new()); self.label_map.insert(label.to_owned(), new_vertex); new_vertex } } } fn add_edge_by_labels(&mut self, from_label: &Label, to_label: &Label) { let from_vertex = self.get_or_insert_vertex(from_label); let to_vertex = self.get_or_insert_vertex(to_label); self.adj_list[from_vertex].insert(to_vertex); } fn add_bidirectional_edge_by_labels(&mut self, label1: &Label, label2: &Label) { self.add_edge_by_labels(label1, label2); self.add_edge_by_labels(label2, label1); } fn bfs_layers(&self, origin: Vertex, mut func: impl FnMut(usize, &VertexSet) -> BfsReply) { let mut visited = VertexSet::new(); visited.insert(origin); let mut current_layer = VertexSet::new(); current_layer.insert(origin); let mut depth = 0usize; while !current_layer.is_empty() { match func(depth, &current_layer) { BfsReply::Halt => return, BfsReply::Continue => (), } let new_layer: VertexSet = current_layer .iter() .flat_map(|v| &self.adj_list[*v]) .cloned() .filter(|v| !visited.contains(v)) .collect(); visited.extend(&new_layer); current_layer = new_layer; depth += 1; } } } #[derive(Debug)] struct AsciiGrid { grid: Vec<u8>, width: usize, } impl AsciiGrid { fn height(&self) -> usize { self.grid.len() / self.width } fn width(&self) -> usize { self.width } } impl Index<Label> for AsciiGrid { type Output = u8; fn index(&self, index: Label) -> &Self::Output { self.grid.index(self.width * index.1 + index.0) } } impl FromStr for AsciiGrid { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut grid: Vec<u8> = Vec::new(); let mut width: Option<usize> = None; for line in s.lines() { if !line.is_ascii() { return Err("Non-ASCII line"); } if line.is_empty() { return Err("Empty line"); } if width.is_some() && width.unwrap() != line.len() { return Err("Non-uniform line length"); } width = Some(line.len()); grid.extend(line.bytes()); } if grid.len() == 0 { return Err("No lines"); } Ok(AsciiGrid { grid, width: width.unwrap(), }) } } #[derive(Debug)] struct Maze { graph: Graph, start: Vertex, end: Vertex, } impl TryFrom<&AsciiGrid> for Maze { type Error = &'static str; fn try_from(grid: &AsciiGrid) -> Result<Self, Self::Error> { let width = grid.width(); let height = grid.height(); let mid_x = width / 2; let mid_y = height / 2; let wall = '#' as u8; let empty = '.' as u8; let space = ' ' as u8; let tiles = [wall, empty]; let left_width = (2..width - 2) .take_while(|x| tiles.contains(&grid[(*x, mid_y)])) .count(); let right_width = (2..width - 2) .rev() .take_while(|x| tiles.contains(&grid[(*x, mid_y)])) .count(); let top_height = (2..height - 2) .take_while(|y| tiles.contains(&grid[(mid_x, *y)])) .count(); let bottom_height = (2..height - 2) .rev() .take_while(|y| tiles.contains(&grid[(mid_x, *y)])) .count(); let mut portals = HashMap::<[u8; 2], Vec<Label>>::new(); let outer_ys = 2..height - 2; let inner_ys = 4 + top_height..height - bottom_height - 4; let outer_xs = 2..width - 2; let inner_xs = 4 + left_width..width - right_width - 4; let leftbound1 = outer_ys.clone().map(|y| (0, y)); let leftbound2 = inner_ys.clone().map(|y| (width - right_width - 4, y)); for (x, y) in leftbound1.chain(leftbound2) { let key = [grid[(x, y)], grid[(x + 1, y)]]; if key[0] != space { portals.entry(key).or_default().push((x + 2, y)); } } let rightbound1 = inner_ys.map(|y| (2 + left_width, y)); let rightbound2 = outer_ys.map(|y| (width - 2, y)); for (x, y) in rightbound1.chain(rightbound2) { let key = [grid[(x, y)], grid[(x + 1, y)]]; if key[0] != space { portals.entry(key).or_default().push((x - 1, y)); } } let topbound1 = outer_xs.clone().map(|x| (x, 0)); let topbound2 = inner_xs.clone().map(|x| (x, height - bottom_height - 4)); for (x, y) in topbound1.chain(topbound2) { let key = [grid[(x, y)], grid[(x, y + 1)]]; if key[0] != space { portals.entry(key).or_default().push((x, y + 2)); } } let bottombound1 = inner_xs.map(|x| (x, 2 + top_height)); let bottombound2 = outer_xs.map(|x| (x, height - 2)); for (x, y) in bottombound1.chain(bottombound2) { let key = [grid[(x, y)], grid[(x, y + 1)]]; if key[0] != space { portals.entry(key).or_default().push((x, y - 1)); } } let start_portal = ['A' as u8; 2]; let end_portal = ['Z' as u8; 2]; let mut graph = Graph::new(); let mut start: Option<Vertex> = None; let mut end: Option<Vertex> = None; for (key, value) in portals.iter() { match value[..] { [point] => { if *key == start_portal { start = Some(graph.get_or_insert_vertex(&point)) } else if *key == end_portal { end = Some(graph.get_or_insert_vertex(&point)) } else { return Err("Bad portal"); } } [point1, point2] => graph.add_bidirectional_edge_by_labels(&point1, &point2), _ => { return Err("Bad portal"); } } } if start.is_none() { return Err("Start portal not found"); } if end.is_none() { return Err("End portal not found"); } for coord in iproduct!(2..width - 2, 2..height - 2) { if grid[coord] != empty { continue; } let (x, y) = coord; let adjacents = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]; for adj in adjacents.iter().copied() { if grid[adj] != empty { continue; } graph.add_bidirectional_edge_by_labels(&coord, &adj); } } Ok(Maze { graph, start: start.unwrap(), end: end.unwrap(), }) } } impl Maze { fn start_end_distance(&self) -> usize { let mut result: Option<usize> = None; self.graph.bfs_layers(self.start, |depth, layer| { if layer.contains(&self.end) { result = Some(depth); BfsReply::Halt } else { BfsReply::Continue } }); result.unwrap() } } fn main() { let input = get_input(2019, 20); let grid: AsciiGrid = input.parse().unwrap(); let maze: Maze = (&grid).try_into().unwrap(); println!("Start-end distance: {}", maze.start_end_distance()); }
use aoc::aoc_input::get_input; use itertools::iproduct; use std::collections::{HashMap, HashSet}; use std::convert::{TryFrom, TryInto}; use std::ops::Index; use std::str::FromStr; type Vertex = usize; type Label = (usize, usize); type LabelMap = HashMap<Label, Vertex>; type VertexSet = HashSet<Vertex>; type AdjacencyList = Vec<VertexSet>; #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum BfsReply { Halt, Continue, } #[derive(Debug)] struct Graph { label_map: LabelMap, adj_list: AdjacencyList, } impl Graph { fn new() -> Graph { Graph { label_map: LabelMap::new(), adj_list: AdjacencyList::new(), } } fn get_or_insert_vertex(&mut self, label: &Label) -> Vertex { match self.label_map.get(label) { Some(v) => *v, None => { let new_vertex = self.adj_list.len(); self.adj_list.push(VertexSet::new()); self.label_map.insert(label.to_owned(), new_vertex); new_vertex } } } fn add_edge_by_labels(&mut self, from_label: &Label, to_label: &Label) { let from_vertex = self.get_or_insert_vertex(from_label); let to_vertex = self.get_or_insert_vertex(to_label); self.adj_list[from_vertex].insert(to_vertex); } fn add_bidirectional_edge_by_labels(&mut self, label1: &Label, label2: &Label) { self.add_edge_by_labels(label1, label2); self.add_edge_by_labels(label2, label1); } fn bfs_layers(&self, origin: Vertex, mut func: impl FnMut(usize, &VertexSet) -> BfsReply) { let mut visited = VertexSet::new(); visited.insert(origin); let mut current_layer = VertexSet::new(); current_layer.insert(origin); let mut depth = 0usize; while !current_layer.is_e
nsert_vertex(&point)) } else if *key == end_portal { end = Some(graph.get_or_insert_vertex(&point)) } else { return Err("Bad portal"); } } [point1, point2] => graph.add_bidirectional_edge_by_labels(&point1, &point2), _ => { return Err("Bad portal"); } } } if start.is_none() { return Err("Start portal not found"); } if end.is_none() { return Err("End portal not found"); } for coord in iproduct!(2..width - 2, 2..height - 2) { if grid[coord] != empty { continue; } let (x, y) = coord; let adjacents = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]; for adj in adjacents.iter().copied() { if grid[adj] != empty { continue; } graph.add_bidirectional_edge_by_labels(&coord, &adj); } } Ok(Maze { graph, start: start.unwrap(), end: end.unwrap(), }) } } impl Maze { fn start_end_distance(&self) -> usize { let mut result: Option<usize> = None; self.graph.bfs_layers(self.start, |depth, layer| { if layer.contains(&self.end) { result = Some(depth); BfsReply::Halt } else { BfsReply::Continue } }); result.unwrap() } } fn main() { let input = get_input(2019, 20); let grid: AsciiGrid = input.parse().unwrap(); let maze: Maze = (&grid).try_into().unwrap(); println!("Start-end distance: {}", maze.start_end_distance()); }
mpty() { match func(depth, &current_layer) { BfsReply::Halt => return, BfsReply::Continue => (), } let new_layer: VertexSet = current_layer .iter() .flat_map(|v| &self.adj_list[*v]) .cloned() .filter(|v| !visited.contains(v)) .collect(); visited.extend(&new_layer); current_layer = new_layer; depth += 1; } } } #[derive(Debug)] struct AsciiGrid { grid: Vec<u8>, width: usize, } impl AsciiGrid { fn height(&self) -> usize { self.grid.len() / self.width } fn width(&self) -> usize { self.width } } impl Index<Label> for AsciiGrid { type Output = u8; fn index(&self, index: Label) -> &Self::Output { self.grid.index(self.width * index.1 + index.0) } } impl FromStr for AsciiGrid { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut grid: Vec<u8> = Vec::new(); let mut width: Option<usize> = None; for line in s.lines() { if !line.is_ascii() { return Err("Non-ASCII line"); } if line.is_empty() { return Err("Empty line"); } if width.is_some() && width.unwrap() != line.len() { return Err("Non-uniform line length"); } width = Some(line.len()); grid.extend(line.bytes()); } if grid.len() == 0 { return Err("No lines"); } Ok(AsciiGrid { grid, width: width.unwrap(), }) } } #[derive(Debug)] struct Maze { graph: Graph, start: Vertex, end: Vertex, } impl TryFrom<&AsciiGrid> for Maze { type Error = &'static str; fn try_from(grid: &AsciiGrid) -> Result<Self, Self::Error> { let width = grid.width(); let height = grid.height(); let mid_x = width / 2; let mid_y = height / 2; let wall = '#' as u8; let empty = '.' as u8; let space = ' ' as u8; let tiles = [wall, empty]; let left_width = (2..width - 2) .take_while(|x| tiles.contains(&grid[(*x, mid_y)])) .count(); let right_width = (2..width - 2) .rev() .take_while(|x| tiles.contains(&grid[(*x, mid_y)])) .count(); let top_height = (2..height - 2) .take_while(|y| tiles.contains(&grid[(mid_x, *y)])) .count(); let bottom_height = (2..height - 2) .rev() .take_while(|y| tiles.contains(&grid[(mid_x, *y)])) .count(); let mut portals = HashMap::<[u8; 2], Vec<Label>>::new(); let outer_ys = 2..height - 2; let inner_ys = 4 + top_height..height - bottom_height - 4; let outer_xs = 2..width - 2; let inner_xs = 4 + left_width..width - right_width - 4; let leftbound1 = outer_ys.clone().map(|y| (0, y)); let leftbound2 = inner_ys.clone().map(|y| (width - right_width - 4, y)); for (x, y) in leftbound1.chain(leftbound2) { let key = [grid[(x, y)], grid[(x + 1, y)]]; if key[0] != space { portals.entry(key).or_default().push((x + 2, y)); } } let rightbound1 = inner_ys.map(|y| (2 + left_width, y)); let rightbound2 = outer_ys.map(|y| (width - 2, y)); for (x, y) in rightbound1.chain(rightbound2) { let key = [grid[(x, y)], grid[(x + 1, y)]]; if key[0] != space { portals.entry(key).or_default().push((x - 1, y)); } } let topbound1 = outer_xs.clone().map(|x| (x, 0)); let topbound2 = inner_xs.clone().map(|x| (x, height - bottom_height - 4)); for (x, y) in topbound1.chain(topbound2) { let key = [grid[(x, y)], grid[(x, y + 1)]]; if key[0] != space { portals.entry(key).or_default().push((x, y + 2)); } } let bottombound1 = inner_xs.map(|x| (x, 2 + top_height)); let bottombound2 = outer_xs.map(|x| (x, height - 2)); for (x, y) in bottombound1.chain(bottombound2) { let key = [grid[(x, y)], grid[(x, y + 1)]]; if key[0] != space { portals.entry(key).or_default().push((x, y - 1)); } } let start_portal = ['A' as u8; 2]; let end_portal = ['Z' as u8; 2]; let mut graph = Graph::new(); let mut start: Option<Vertex> = None; let mut end: Option<Vertex> = None; for (key, value) in portals.iter() { match value[..] { [point] => { if *key == start_portal { start = Some(graph.get_or_i
random
[ { "content": "pub fn digits<T>(mut num: T, radix: T) -> impl Iterator<Item = T>\n\nwhere\n\n T: UnsignedDigits<T>,\n\n{\n\n let zero = T::zero();\n\n\n\n let mut divisor = T::one();\n\n while num >= divisor * radix {\n\n divisor *= radix;\n\n }\n\n\n\n std::iter::from_fn(move || {\n\n ...
Rust
src/cli/commands/color_commands.rs
dandycheung/pastel
3719824a56fb9eb92eb960068e513b95486756a7
use crate::colorspace::get_mixing_function; use crate::commands::prelude::*; use pastel::ColorblindnessType; use pastel::Fraction; fn clamp(lower: f64, upper: f64, x: f64) -> f64 { f64::max(f64::min(upper, x), lower) } macro_rules! color_command { ($cmd_name:ident, $config:ident, $matches:ident, $color:ident, $body:block) => { pub struct $cmd_name; impl ColorCommand for $cmd_name { fn run( &self, out: &mut Output, $matches: &ArgMatches, $config: &Config, $color: &Color, ) -> Result<()> { let output = $body; out.show_color($config, &output) } } }; } color_command!(SaturateCommand, _config, matches, color, { let amount = number_arg(matches, "amount")?; color.saturate(amount) }); color_command!(DesaturateCommand, _config, matches, color, { let amount = number_arg(matches, "amount")?; color.desaturate(amount) }); color_command!(LightenCommand, _config, matches, color, { let amount = number_arg(matches, "amount")?; color.lighten(amount) }); color_command!(DarkenCommand, _config, matches, color, { let amount = number_arg(matches, "amount")?; color.darken(amount) }); color_command!(RotateCommand, _config, matches, color, { let degrees = number_arg(matches, "degrees")?; color.rotate_hue(degrees) }); color_command!(ComplementCommand, _config, _matches, color, { color.complementary() }); color_command!(ToGrayCommand, _config, _matches, color, { color.to_gray() }); color_command!(TextColorCommand, _config, _matches, color, { color.text_color() }); color_command!(MixCommand, config, matches, color, { let mut print_spectrum = PrintSpectrum::Yes; let base = ColorArgIterator::from_color_arg( config, matches.value_of("base").expect("required argument"), &mut print_spectrum, )?; let fraction = Fraction::from(1.0 - number_arg(matches, "fraction")?); let mix = get_mixing_function(matches.value_of("colorspace").expect("required argument")); mix(&base, color, fraction) }); color_command!(ColorblindCommand, config, matches, color, { let cb_ty = matches.value_of("type").expect("required argument"); let cb_ty = cb_ty.to_lowercase(); let cb_ty = match cb_ty.as_ref() { "prot" => ColorblindnessType::Protanopia, "deuter" => ColorblindnessType::Deuteranopia, "trit" => ColorblindnessType::Tritanopia, &_ => { unreachable!("Unknown property"); } }; color.simulate_colorblindness(cb_ty) }); color_command!(SetCommand, config, matches, color, { let property = matches.value_of("property").expect("required argument"); let property = property.to_lowercase(); let property = property.as_ref(); let value = number_arg(matches, "value")?; match property { "red" | "green" | "blue" => { let mut rgba = color.to_rgba(); let value = clamp(0.0, 255.0, value) as u8; match property { "red" => { rgba.r = value; } "green" => { rgba.g = value; } "blue" => { rgba.b = value; } _ => unreachable!(), } Color::from_rgba(rgba.r, rgba.g, rgba.b, rgba.alpha) } "hsl-hue" | "hsl-saturation" | "hsl-lightness" => { let mut hsla = color.to_hsla(); match property { "hsl-hue" => { hsla.h = value; } "hsl-saturation" => { hsla.s = value; } "hsl-lightness" => { hsla.l = value; } _ => unreachable!(), } Color::from_hsla(hsla.h, hsla.s, hsla.l, hsla.alpha) } "lightness" | "lab-a" | "lab-b" => { let mut lab = color.to_lab(); match property { "lightness" => { lab.l = value; } "lab-a" => { lab.a = value; } "lab-b" => { lab.b = value; } _ => unreachable!(), } Color::from_lab(lab.l, lab.a, lab.b, lab.alpha) } "hue" | "chroma" => { let mut lch = color.to_lch(); match property { "hue" => { lch.h = value; } "chroma" => { lch.c = value; } _ => unreachable!(), } Color::from_lch(lch.l, lch.c, lch.h, lch.alpha) } &_ => { unreachable!("Unknown property"); } } });
use crate::colorspace::get_mixing_function; use crate::commands::prelude::*; use pastel::ColorblindnessType; use pastel::Fraction; fn clamp(lower: f64, upper: f64, x: f64) -> f64 { f64::max(f64::min(upper, x), lower) } macro_rules! color_command { ($cmd_name:ident, $config:ident, $matches:ident, $color:ident, $body:block) => { pub struct $cmd_name; impl ColorCommand for $cmd_name { fn run( &self, out: &mut Output, $matches: &ArgMatches, $config: &Config, $color: &Color,
match property { "hsl-hue" => { hsla.h = value; } "hsl-saturation" => { hsla.s = value; } "hsl-lightness" => { hsla.l = value; } _ => unreachable!(), } Color::from_hsla(hsla.h, hsla.s, hsla.l, hsla.alpha) } "lightness" | "lab-a" | "lab-b" => { let mut lab = color.to_lab(); match property { "lightness" => { lab.l = value; } "lab-a" => { lab.a = value; } "lab-b" => { lab.b = value; } _ => unreachable!(), } Color::from_lab(lab.l, lab.a, lab.b, lab.alpha) } "hue" | "chroma" => { let mut lch = color.to_lch(); match property { "hue" => { lch.h = value; } "chroma" => { lch.c = value; } _ => unreachable!(), } Color::from_lch(lch.l, lch.c, lch.h, lch.alpha) } &_ => { unreachable!("Unknown property"); } } });
) -> Result<()> { let output = $body; out.show_color($config, &output) } } }; } color_command!(SaturateCommand, _config, matches, color, { let amount = number_arg(matches, "amount")?; color.saturate(amount) }); color_command!(DesaturateCommand, _config, matches, color, { let amount = number_arg(matches, "amount")?; color.desaturate(amount) }); color_command!(LightenCommand, _config, matches, color, { let amount = number_arg(matches, "amount")?; color.lighten(amount) }); color_command!(DarkenCommand, _config, matches, color, { let amount = number_arg(matches, "amount")?; color.darken(amount) }); color_command!(RotateCommand, _config, matches, color, { let degrees = number_arg(matches, "degrees")?; color.rotate_hue(degrees) }); color_command!(ComplementCommand, _config, _matches, color, { color.complementary() }); color_command!(ToGrayCommand, _config, _matches, color, { color.to_gray() }); color_command!(TextColorCommand, _config, _matches, color, { color.text_color() }); color_command!(MixCommand, config, matches, color, { let mut print_spectrum = PrintSpectrum::Yes; let base = ColorArgIterator::from_color_arg( config, matches.value_of("base").expect("required argument"), &mut print_spectrum, )?; let fraction = Fraction::from(1.0 - number_arg(matches, "fraction")?); let mix = get_mixing_function(matches.value_of("colorspace").expect("required argument")); mix(&base, color, fraction) }); color_command!(ColorblindCommand, config, matches, color, { let cb_ty = matches.value_of("type").expect("required argument"); let cb_ty = cb_ty.to_lowercase(); let cb_ty = match cb_ty.as_ref() { "prot" => ColorblindnessType::Protanopia, "deuter" => ColorblindnessType::Deuteranopia, "trit" => ColorblindnessType::Tritanopia, &_ => { unreachable!("Unknown property"); } }; color.simulate_colorblindness(cb_ty) }); color_command!(SetCommand, config, matches, color, { let property = matches.value_of("property").expect("required argument"); let property = property.to_lowercase(); let property = property.as_ref(); let value = number_arg(matches, "value")?; match property { "red" | "green" | "blue" => { let mut rgba = color.to_rgba(); let value = clamp(0.0, 255.0, value) as u8; match property { "red" => { rgba.r = value; } "green" => { rgba.g = value; } "blue" => { rgba.b = value; } _ => unreachable!(), } Color::from_rgba(rgba.r, rgba.g, rgba.b, rgba.alpha) } "hsl-hue" | "hsl-saturation" | "hsl-lightness" => { let mut hsla = color.to_hsla();
random
[ { "content": "/// Trim a number such that it fits into the range [lower, upper].\n\npub fn clamp(lower: Scalar, upper: Scalar, x: Scalar) -> Scalar {\n\n Scalar::max(Scalar::min(upper, x), lower)\n\n}\n\n\n\n#[derive(Debug, Clone, Copy)]\n\npub struct Fraction {\n\n f: Scalar,\n\n}\n\n\n\nimpl Fraction {\...
Rust
mshv-ioctls/src/ioctls/system.rs
russell-islam/mshv
99da566389546aedb56fc3d279e01c5dbde79bce
use crate::ioctls::vm::{new_vmfd, VmFd}; use crate::ioctls::Result; use crate::mshv_ioctls::*; use libc::{open, O_CLOEXEC, O_NONBLOCK}; use mshv_bindings::*; use std::fs::File; use std::os::raw::c_char; use std::os::unix::io::{FromRawFd, RawFd}; use vmm_sys_util::errno; use vmm_sys_util::ioctl::ioctl_with_ref; pub struct Mshv { hv: File, } impl Mshv { #[allow(clippy::new_ret_no_self)] pub fn new() -> Result<Self> { let fd = Self::open_with_cloexec(true)?; let ret = unsafe { Self::new_with_fd_number(fd) }; Ok(ret) } pub unsafe fn new_with_fd_number(fd: RawFd) -> Self { Mshv { hv: File::from_raw_fd(fd), } } pub fn open_with_cloexec(close_on_exec: bool) -> Result<RawFd> { let open_flags = O_NONBLOCK | if close_on_exec { O_CLOEXEC } else { 0 }; let ret = unsafe { open("/dev/mshv\0".as_ptr() as *const c_char, open_flags) }; if ret < 0 { Err(errno::Error::last()) } else { Ok(ret) } } pub fn create_vm(&self) -> Result<VmFd> { let creation_flags: u64 = HV_PARTITION_CREATION_FLAG_LAPIC_ENABLED as u64; let mut pr = mshv_create_partition { partition_creation_properties: hv_partition_creation_properties { disabled_processor_features: hv_partition_processor_features { as_uint64: [0; 2] }, disabled_processor_xsave_features: hv_partition_processor_xsave_features { as_uint64: 0_u64, }, }, synthetic_processor_features: hv_partition_synthetic_processor_features { as_uint64: [0; 1], }, flags: creation_flags, }; /* TODO pass in arg for this */ unsafe { pr.synthetic_processor_features .__bindgen_anon_1 .set_hypervisor_present(1); pr.synthetic_processor_features.__bindgen_anon_1.set_hv1(1); pr.synthetic_processor_features .__bindgen_anon_1 .set_access_partition_reference_counter(1); pr.synthetic_processor_features .__bindgen_anon_1 .set_access_synic_regs(1); pr.synthetic_processor_features .__bindgen_anon_1 .set_access_synthetic_timer_regs(1); pr.synthetic_processor_features .__bindgen_anon_1 .set_access_partition_reference_tsc(1); /* Need this for linux on CH, as there's no PIT or HPET */ pr.synthetic_processor_features .__bindgen_anon_1 .set_access_frequency_regs(1); /* Linux I'm using appears to require vp assist page... */ pr.synthetic_processor_features .__bindgen_anon_1 .set_access_intr_ctrl_regs(1); /* According to Hv#1 spec, these must be set also, but they aren't in KVM? */ pr.synthetic_processor_features .__bindgen_anon_1 .set_access_vp_index(1); pr.synthetic_processor_features .__bindgen_anon_1 .set_access_hypercall_regs(1); /* Windows requires this */ pr.synthetic_processor_features .__bindgen_anon_1 .set_access_guest_idle_reg(1); } let ret = unsafe { ioctl_with_ref(&self.hv, MSHV_CREATE_PARTITION(), &pr) }; if ret >= 0 { let vm_file = unsafe { File::from_raw_fd(ret) }; Ok(new_vmfd(vm_file)) } else { Err(errno::Error::last()) } } pub fn check_stable(&self) -> Result<bool> { let cap: u32 = MSHV_CAP_CORE_API_STABLE; let ret = unsafe { ioctl_with_ref(&self.hv, MSHV_CHECK_EXTENSION(), &cap) }; match ret { 0 => Ok(false), r if r > 0 => Ok(true), _ => Err(errno::Error::last()), } } pub fn get_msr_index_list(&self) -> Result<MsrList> { /* return all the MSRs we currently support */ Ok(MsrList::from_entries(&[ IA32_MSR_TSC, IA32_MSR_EFER, IA32_MSR_KERNEL_GS_BASE, IA32_MSR_APIC_BASE, IA32_MSR_PAT, IA32_MSR_SYSENTER_CS, IA32_MSR_SYSENTER_ESP, IA32_MSR_SYSENTER_EIP, IA32_MSR_STAR, IA32_MSR_LSTAR, IA32_MSR_CSTAR, IA32_MSR_SFMASK, IA32_MSR_MTRR_DEF_TYPE, IA32_MSR_MTRR_PHYSBASE0, IA32_MSR_MTRR_PHYSMASK0, IA32_MSR_MTRR_PHYSBASE1, IA32_MSR_MTRR_PHYSMASK1, IA32_MSR_MTRR_PHYSBASE2, IA32_MSR_MTRR_PHYSMASK2, IA32_MSR_MTRR_PHYSBASE3, IA32_MSR_MTRR_PHYSMASK3, IA32_MSR_MTRR_PHYSBASE4, IA32_MSR_MTRR_PHYSMASK4, IA32_MSR_MTRR_PHYSBASE5, IA32_MSR_MTRR_PHYSMASK5, IA32_MSR_MTRR_PHYSBASE6, IA32_MSR_MTRR_PHYSMASK6, IA32_MSR_MTRR_PHYSBASE7, IA32_MSR_MTRR_PHYSMASK7, IA32_MSR_MTRR_FIX64K_00000, IA32_MSR_MTRR_FIX16K_80000, IA32_MSR_MTRR_FIX16K_a0000, IA32_MSR_MTRR_FIX4K_c0000, IA32_MSR_MTRR_FIX4K_c8000, IA32_MSR_MTRR_FIX4K_d0000, IA32_MSR_MTRR_FIX4K_d8000, IA32_MSR_MTRR_FIX4K_e0000, IA32_MSR_MTRR_FIX4K_e8000, IA32_MSR_MTRR_FIX4K_f0000, IA32_MSR_MTRR_FIX4K_f8000, IA32_MSR_TSC_AUX, IA32_MSR_BNDCFGS, IA32_MSR_DEBUG_CTL, IA32_MSR_SPEC_CTRL, ]) .unwrap()) } } #[allow(dead_code)] #[cfg(test)] mod tests { use super::*; #[test] #[ignore] fn test_create_vm() { let hv = Mshv::new().unwrap(); let vm = hv.create_vm(); assert!(vm.is_ok()); } #[test] #[ignore] fn test_get_msr_index_list() { let hv = Mshv::new().unwrap(); let msr_list = hv.get_msr_index_list().unwrap(); assert!(msr_list.as_fam_struct_ref().nmsrs == 44); let mut found = false; for index in msr_list.as_slice() { if *index == IA32_MSR_SYSENTER_CS { found = true; break; } } assert!(found); /* Test all MSRs in the list individually and determine which can be get/set */ let vm = hv.create_vm().unwrap(); let vcpu = vm.create_vcpu(0).unwrap(); let mut num_errors = 0; for idx in hv.get_msr_index_list().unwrap().as_slice().iter() { let mut get_set_msrs = Msrs::from_entries(&[msr_entry { index: *idx, ..Default::default() }]) .unwrap(); vcpu.get_msrs(&mut get_set_msrs).unwrap_or_else(|_| { println!("Error getting MSR: 0x{:x}", *idx); num_errors += 1; 0 }); vcpu.set_msrs(&get_set_msrs).unwrap_or_else(|_| { println!("Error setting MSR: 0x{:x}", *idx); num_errors += 1; 0 }); } assert!(num_errors == 0); } }
use crate::ioctls::vm::{new_vmfd, VmFd}; use crate::ioctls::Result; use crate::mshv_ioctls::*; use libc::{open, O_CLOEXEC, O_NONBLOCK}; use mshv_bindings::*; use std::fs::File; use std::os::raw::c_char; use std::os::unix::io::{FromRawFd, RawFd}; use vmm_sys_util::errno; use vmm_sys_util::ioctl::ioctl_with_ref; pub struct Mshv { hv: File, } impl Mshv { #[allow(clippy::new_ret_no_self)] pub fn new() -> Result<Self> { let fd = Self::open_with_cloexec(true)?; let ret = unsafe { Self::new_with_fd_number(fd) }; Ok(ret) } pub unsafe fn new_with_fd_number(fd: RawFd) -> Self { Mshv { hv: File::from_raw_fd(fd), } } pub fn open_with_cloexec(close_on_exec: bool) -> Result<RawFd> { let open_flags = O_NONBLOCK | if close_on_exec { O_CLOEXEC } else { 0 }; let ret = unsafe { open("/dev/mshv\0".as_ptr() as *const c_char, open_flags) }; if ret < 0 { Err(errno::Error::last()) } else { Ok(ret) } }
pub fn check_stable(&self) -> Result<bool> { let cap: u32 = MSHV_CAP_CORE_API_STABLE; let ret = unsafe { ioctl_with_ref(&self.hv, MSHV_CHECK_EXTENSION(), &cap) }; match ret { 0 => Ok(false), r if r > 0 => Ok(true), _ => Err(errno::Error::last()), } } pub fn get_msr_index_list(&self) -> Result<MsrList> { /* return all the MSRs we currently support */ Ok(MsrList::from_entries(&[ IA32_MSR_TSC, IA32_MSR_EFER, IA32_MSR_KERNEL_GS_BASE, IA32_MSR_APIC_BASE, IA32_MSR_PAT, IA32_MSR_SYSENTER_CS, IA32_MSR_SYSENTER_ESP, IA32_MSR_SYSENTER_EIP, IA32_MSR_STAR, IA32_MSR_LSTAR, IA32_MSR_CSTAR, IA32_MSR_SFMASK, IA32_MSR_MTRR_DEF_TYPE, IA32_MSR_MTRR_PHYSBASE0, IA32_MSR_MTRR_PHYSMASK0, IA32_MSR_MTRR_PHYSBASE1, IA32_MSR_MTRR_PHYSMASK1, IA32_MSR_MTRR_PHYSBASE2, IA32_MSR_MTRR_PHYSMASK2, IA32_MSR_MTRR_PHYSBASE3, IA32_MSR_MTRR_PHYSMASK3, IA32_MSR_MTRR_PHYSBASE4, IA32_MSR_MTRR_PHYSMASK4, IA32_MSR_MTRR_PHYSBASE5, IA32_MSR_MTRR_PHYSMASK5, IA32_MSR_MTRR_PHYSBASE6, IA32_MSR_MTRR_PHYSMASK6, IA32_MSR_MTRR_PHYSBASE7, IA32_MSR_MTRR_PHYSMASK7, IA32_MSR_MTRR_FIX64K_00000, IA32_MSR_MTRR_FIX16K_80000, IA32_MSR_MTRR_FIX16K_a0000, IA32_MSR_MTRR_FIX4K_c0000, IA32_MSR_MTRR_FIX4K_c8000, IA32_MSR_MTRR_FIX4K_d0000, IA32_MSR_MTRR_FIX4K_d8000, IA32_MSR_MTRR_FIX4K_e0000, IA32_MSR_MTRR_FIX4K_e8000, IA32_MSR_MTRR_FIX4K_f0000, IA32_MSR_MTRR_FIX4K_f8000, IA32_MSR_TSC_AUX, IA32_MSR_BNDCFGS, IA32_MSR_DEBUG_CTL, IA32_MSR_SPEC_CTRL, ]) .unwrap()) } } #[allow(dead_code)] #[cfg(test)] mod tests { use super::*; #[test] #[ignore] fn test_create_vm() { let hv = Mshv::new().unwrap(); let vm = hv.create_vm(); assert!(vm.is_ok()); } #[test] #[ignore] fn test_get_msr_index_list() { let hv = Mshv::new().unwrap(); let msr_list = hv.get_msr_index_list().unwrap(); assert!(msr_list.as_fam_struct_ref().nmsrs == 44); let mut found = false; for index in msr_list.as_slice() { if *index == IA32_MSR_SYSENTER_CS { found = true; break; } } assert!(found); /* Test all MSRs in the list individually and determine which can be get/set */ let vm = hv.create_vm().unwrap(); let vcpu = vm.create_vcpu(0).unwrap(); let mut num_errors = 0; for idx in hv.get_msr_index_list().unwrap().as_slice().iter() { let mut get_set_msrs = Msrs::from_entries(&[msr_entry { index: *idx, ..Default::default() }]) .unwrap(); vcpu.get_msrs(&mut get_set_msrs).unwrap_or_else(|_| { println!("Error getting MSR: 0x{:x}", *idx); num_errors += 1; 0 }); vcpu.set_msrs(&get_set_msrs).unwrap_or_else(|_| { println!("Error setting MSR: 0x{:x}", *idx); num_errors += 1; 0 }); } assert!(num_errors == 0); } }
pub fn create_vm(&self) -> Result<VmFd> { let creation_flags: u64 = HV_PARTITION_CREATION_FLAG_LAPIC_ENABLED as u64; let mut pr = mshv_create_partition { partition_creation_properties: hv_partition_creation_properties { disabled_processor_features: hv_partition_processor_features { as_uint64: [0; 2] }, disabled_processor_xsave_features: hv_partition_processor_xsave_features { as_uint64: 0_u64, }, }, synthetic_processor_features: hv_partition_synthetic_processor_features { as_uint64: [0; 1], }, flags: creation_flags, }; /* TODO pass in arg for this */ unsafe { pr.synthetic_processor_features .__bindgen_anon_1 .set_hypervisor_present(1); pr.synthetic_processor_features.__bindgen_anon_1.set_hv1(1); pr.synthetic_processor_features .__bindgen_anon_1 .set_access_partition_reference_counter(1); pr.synthetic_processor_features .__bindgen_anon_1 .set_access_synic_regs(1); pr.synthetic_processor_features .__bindgen_anon_1 .set_access_synthetic_timer_regs(1); pr.synthetic_processor_features .__bindgen_anon_1 .set_access_partition_reference_tsc(1); /* Need this for linux on CH, as there's no PIT or HPET */ pr.synthetic_processor_features .__bindgen_anon_1 .set_access_frequency_regs(1); /* Linux I'm using appears to require vp assist page... */ pr.synthetic_processor_features .__bindgen_anon_1 .set_access_intr_ctrl_regs(1); /* According to Hv#1 spec, these must be set also, but they aren't in KVM? */ pr.synthetic_processor_features .__bindgen_anon_1 .set_access_vp_index(1); pr.synthetic_processor_features .__bindgen_anon_1 .set_access_hypercall_regs(1); /* Windows requires this */ pr.synthetic_processor_features .__bindgen_anon_1 .set_access_guest_idle_reg(1); } let ret = unsafe { ioctl_with_ref(&self.hv, MSHV_CREATE_PARTITION(), &pr) }; if ret >= 0 { let vm_file = unsafe { File::from_raw_fd(ret) }; Ok(new_vmfd(vm_file)) } else { Err(errno::Error::last()) } }
function_block-full_function
[ { "content": "/// Helper function to create a new `VmFd`.\n\n///\n\n/// This should not be exported as a public function because the preferred way is to use\n\n/// `create_vm` from `Mshv`. The function cannot be part of the `VmFd` implementation because\n\n/// then it would be exported with the public `VmFd` in...
Rust
src/test/debuginfo/recursive-struct.rs
komaeda/rust
b2c6b8c29f13f8d1f242da89e587960b95337819
#![allow(unused_variables)] #![feature(box_syntax)] #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] use self::Opt::{Empty, Val}; enum Opt<T> { Empty, Val { val: T } } struct UniqueNode<T> { next: Opt<Box<UniqueNode<T>>>, value: T } struct LongCycle1<T> { next: Box<LongCycle2<T>>, value: T, } struct LongCycle2<T> { next: Box<LongCycle3<T>>, value: T, } struct LongCycle3<T> { next: Box<LongCycle4<T>>, value: T, } struct LongCycle4<T> { next: Option<Box<LongCycle1<T>>>, value: T, } struct LongCycleWithAnonymousTypes { next: Opt<Box<Box<Box<Box<Box<LongCycleWithAnonymousTypes>>>>>>, value: usize, } fn main() { let stack_unique: UniqueNode<u16> = UniqueNode { next: Val { val: box UniqueNode { next: Empty, value: 1, } }, value: 0, }; let unique_unique: Box<UniqueNode<u32>> = box UniqueNode { next: Val { val: box UniqueNode { next: Empty, value: 3, } }, value: 2, }; let vec_unique: [UniqueNode<f32>; 1] = [UniqueNode { next: Val { val: box UniqueNode { next: Empty, value: 7.5, } }, value: 6.5, }]; let borrowed_unique: &UniqueNode<f64> = &UniqueNode { next: Val { val: box UniqueNode { next: Empty, value: 9.5, } }, value: 8.5, }; let long_cycle1: LongCycle1<u16> = LongCycle1 { next: box LongCycle2 { next: box LongCycle3 { next: box LongCycle4 { next: None, value: 23, }, value: 22, }, value: 21 }, value: 20 }; let long_cycle2: LongCycle2<u32> = LongCycle2 { next: box LongCycle3 { next: box LongCycle4 { next: None, value: 26, }, value: 25, }, value: 24 }; let long_cycle3: LongCycle3<u64> = LongCycle3 { next: box LongCycle4 { next: None, value: 28, }, value: 27, }; let long_cycle4: LongCycle4<f32> = LongCycle4 { next: None, value: 29.5, }; let long_cycle_w_anonymous_types = box box box box box LongCycleWithAnonymousTypes { next: Val { val: box box box box box LongCycleWithAnonymousTypes { next: Empty, value: 31, } }, value: 30 }; zzz(); } fn zzz() {()}
#![allow(unused_variables)] #![feature(box_syntax)] #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] use self::Opt::{Empty, Val}; enum Opt<T> { Empty, Val { val: T } } struct UniqueNode<T> { next: Opt<Box<UniqueNode<T>>>, value: T } struct LongCycle1<T> { next: Box<LongCycle2<T>>, value: T, } struct LongCycle2<T> { next: Box<LongCycle3<T>>, value: T, } struct LongCycle3<T> { next: Box<LongCycle4<T>>, value: T, } struct LongCycle4<T> { next: Option<Box<LongCycle1<T>>>, value: T, } struct LongCycleWithAnonymousTypes { next: Opt<Box<Box<Box<Box<Box<LongCycleWithAnonymousTypes>>>>>>, value: usize, } fn main() { let stack_unique: UniqueNode<u16> = UniqueNode { next: Val { val: box UniqueNode { next: Empty, value: 1, } }, value: 0, };
let vec_unique: [UniqueNode<f32>; 1] = [UniqueNode { next: Val { val: box UniqueNode { next: Empty, value: 7.5, } }, value: 6.5, }]; let borrowed_unique: &UniqueNode<f64> = &UniqueNode { next: Val { val: box UniqueNode { next: Empty, value: 9.5, } }, value: 8.5, }; let long_cycle1: LongCycle1<u16> = LongCycle1 { next: box LongCycle2 { next: box LongCycle3 { next: box LongCycle4 { next: None, value: 23, }, value: 22, }, value: 21 }, value: 20 }; let long_cycle2: LongCycle2<u32> = LongCycle2 { next: box LongCycle3 { next: box LongCycle4 { next: None, value: 26, }, value: 25, }, value: 24 }; let long_cycle3: LongCycle3<u64> = LongCycle3 { next: box LongCycle4 { next: None, value: 28, }, value: 27, }; let long_cycle4: LongCycle4<f32> = LongCycle4 { next: None, value: 29.5, }; let long_cycle_w_anonymous_types = box box box box box LongCycleWithAnonymousTypes { next: Val { val: box box box box box LongCycleWithAnonymousTypes { next: Empty, value: 31, } }, value: 30 }; zzz(); } fn zzz() {()}
let unique_unique: Box<UniqueNode<u32>> = box UniqueNode { next: Val { val: box UniqueNode { next: Empty, value: 3, } }, value: 2, };
assignment_statement
[]
Rust
shared/rust/src/api/endpoints/jig.rs
corinnewo/ji-cloud
58fc898703ca0fc5b962e644dfcfbcce8547c525
use crate::{ api::Method, domain::{ jig::{ JigBrowseQuery, JigBrowseResponse, JigCountResponse, JigCreateRequest, JigId, JigResponse, JigSearchQuery, JigSearchResponse, JigUpdateDraftDataRequest, JigUpdateRequest, }, CreateResponse, }, error::{EmptyError, MetadataNotFound}, }; use super::ApiEndpoint; pub mod module; pub mod additional_resource; pub mod player; pub struct Create; impl ApiEndpoint for Create { type Req = JigCreateRequest; type Res = CreateResponse<JigId>; type Err = MetadataNotFound; const PATH: &'static str = "/v1/jig"; const METHOD: Method = Method::Post; } pub struct Update; impl ApiEndpoint for Update { type Req = JigUpdateRequest; type Res = (); type Err = EmptyError; const PATH: &'static str = "/v1/jig/{id}"; const METHOD: Method = Method::Patch; } pub struct GetLive; impl ApiEndpoint for GetLive { type Req = (); type Res = JigResponse; type Err = EmptyError; const PATH: &'static str = "/v1/jig/{id}/live"; const METHOD: Method = Method::Get; } pub struct GetDraft; impl ApiEndpoint for GetDraft { type Req = (); type Res = JigResponse; type Err = EmptyError; const PATH: &'static str = "/v1/jig/{id}/draft"; const METHOD: Method = Method::Get; } pub struct UpdateDraftData; impl ApiEndpoint for UpdateDraftData { type Req = JigUpdateDraftDataRequest; type Res = (); type Err = MetadataNotFound; const PATH: &'static str = "/v1/jig/{id}/draft"; const METHOD: Method = Method::Patch; } pub struct Publish; impl ApiEndpoint for Publish { type Req = (); type Res = (); type Err = EmptyError; const PATH: &'static str = "/v1/jig/{id}/draft/publish"; const METHOD: Method = Method::Put; } pub struct Browse; impl ApiEndpoint for Browse { type Req = JigBrowseQuery; type Res = JigBrowseResponse; type Err = EmptyError; const PATH: &'static str = "/v1/jig/browse"; const METHOD: Method = Method::Get; } pub struct Search; impl ApiEndpoint for Search { type Req = JigSearchQuery; type Res = JigSearchResponse; type Err = EmptyError; const PATH: &'static str = "/v1/jig"; const METHOD: Method = Method::Get; } pub struct Clone; impl ApiEndpoint for Clone { type Req = (); type Res = CreateResponse<JigId>; type Err = EmptyError; const PATH: &'static str = "/v1/jig/{id}/clone"; const METHOD: Method = Method::Post; } pub struct Delete; impl ApiEndpoint for Delete { type Req = (); type Res = (); type Err = EmptyError; const PATH: &'static str = "/v1/jig/{id}"; const METHOD: Method = Method::Delete; } pub struct Count; impl ApiEndpoint for Count { type Req = (); type Res = JigCountResponse; type Err = EmptyError; const PATH: &'static str = "/v1/jig/count"; const METHOD: Method = Method::Get; }
use crate::{ api::Method, domain::{ jig::{ JigBrowseQuery, JigBrowseResponse, JigCountResponse, JigCreateRequest, JigId, JigResponse, JigSearchQuery, JigSearchResponse, JigUpdateDraftDataRequest, JigUpdateRequest, }, CreateResponse, }, error::{EmptyError, MetadataNotFound}, }; use super::ApiEndpoint; pub
ApiEndpoint for Browse { type Req = JigBrowseQuery; type Res = JigBrowseResponse; type Err = EmptyError; const PATH: &'static str = "/v1/jig/browse"; const METHOD: Method = Method::Get; } pub struct Search; impl ApiEndpoint for Search { type Req = JigSearchQuery; type Res = JigSearchResponse; type Err = EmptyError; const PATH: &'static str = "/v1/jig"; const METHOD: Method = Method::Get; } pub struct Clone; impl ApiEndpoint for Clone { type Req = (); type Res = CreateResponse<JigId>; type Err = EmptyError; const PATH: &'static str = "/v1/jig/{id}/clone"; const METHOD: Method = Method::Post; } pub struct Delete; impl ApiEndpoint for Delete { type Req = (); type Res = (); type Err = EmptyError; const PATH: &'static str = "/v1/jig/{id}"; const METHOD: Method = Method::Delete; } pub struct Count; impl ApiEndpoint for Count { type Req = (); type Res = JigCountResponse; type Err = EmptyError; const PATH: &'static str = "/v1/jig/count"; const METHOD: Method = Method::Get; }
mod module; pub mod additional_resource; pub mod player; pub struct Create; impl ApiEndpoint for Create { type Req = JigCreateRequest; type Res = CreateResponse<JigId>; type Err = MetadataNotFound; const PATH: &'static str = "/v1/jig"; const METHOD: Method = Method::Post; } pub struct Update; impl ApiEndpoint for Update { type Req = JigUpdateRequest; type Res = (); type Err = EmptyError; const PATH: &'static str = "/v1/jig/{id}"; const METHOD: Method = Method::Patch; } pub struct GetLive; impl ApiEndpoint for GetLive { type Req = (); type Res = JigResponse; type Err = EmptyError; const PATH: &'static str = "/v1/jig/{id}/live"; const METHOD: Method = Method::Get; } pub struct GetDraft; impl ApiEndpoint for GetDraft { type Req = (); type Res = JigResponse; type Err = EmptyError; const PATH: &'static str = "/v1/jig/{id}/draft"; const METHOD: Method = Method::Get; } pub struct UpdateDraftData; impl ApiEndpoint for UpdateDraftData { type Req = JigUpdateDraftDataRequest; type Res = (); type Err = MetadataNotFound; const PATH: &'static str = "/v1/jig/{id}/draft"; const METHOD: Method = Method::Patch; } pub struct Publish; impl ApiEndpoint for Publish { type Req = (); type Res = (); type Err = EmptyError; const PATH: &'static str = "/v1/jig/{id}/draft/publish"; const METHOD: Method = Method::Put; } pub struct Browse; impl
random
[ { "content": "pub fn delete_jig(state: Rc<State>, jig_id: JigId) {\n\n state.loader.load(clone!(state => async move {\n\n let path = Delete::PATH.replace(\"{id}\",&jig_id.0.to_string());\n\n match api_with_auth_empty::<EmptyError, ()>(&path, Delete::METHOD, None).await {\n\n Ok(_) =>...
Rust
src/columnar_transposition.rs
sula0/embedo
fa3ddcc54ea481ecffe5c765706aa6e1b42a6be1
use crate::util; const META_ROWS: usize = 2; const EMPTY_CHAR: u32 = 32; pub fn encrypt(text: &str, key: &str) -> String { let mut result = String::new(); let cols = key.len(); let required_rows = text.len() as f32 / cols as f32; let rows = META_ROWS + (required_rows as f32).ceil() as usize; let mut matrix = vec![vec![32; cols]; rows]; let key_chars: Vec<char> = key.to_uppercase().chars().collect(); let text_chars: Vec<char> = text.chars().collect(); /* Keys vec contains tuple consisted of the alphabetized value of the key char and its index. Later we sort by the alphabetized value to get the column reading order. */ let mut keys: Vec<(u32, u32)> = vec![]; /* Fill up the matrix. First row contains the key. Second row contains the order of alphabets in the key. Rest of the rows are filled with the text which will be encrypted. */ for i in 0..rows { for j in 0..cols { if i == 0 { matrix[i][j] = key_chars[j] as u32; } else if i == 1 { let alphabetized_char = util::alphabetize_char(key_chars[j] as u32, true); matrix[i][j] = alphabetized_char; keys.push((j as u32, alphabetized_char)); } else { let char_index = (i - META_ROWS) + j + ((i - META_ROWS) * (cols - 1)); if char_index < text_chars.len() { matrix[i][j] = text_chars[char_index] as u32; } else { matrix[i][j] = EMPTY_CHAR; } } } } keys.sort_by(|a, b| a.1.cmp(&b.1)); /* Read the columns of the text. Order of reading is determined but the key alphabets. */ for j in keys.iter() { for i in META_ROWS..rows { let c = matrix[i as usize][j.0 as usize]; result += std::str::from_utf8(&[c as u8]).unwrap(); } } result } pub fn decrypt(text: &str, key: &str) -> String { let mut result = String::new(); let cols = key.len(); let required_rows = text.len() as f32 / cols as f32; let rows = META_ROWS + (required_rows as f32).ceil() as usize; let mut matrix = vec![vec![32; cols]; rows]; let key_chars: Vec<char> = key.to_uppercase().chars().collect(); let text_chars: Vec<char> = text.chars().collect(); /* Keys vec contains tuple consisted of the alphabetized value of the key char and its index. Later we sort by the alphabetized value to get the column reading order. */ let mut keys: Vec<(u32, u32)> = vec![]; /* Fill up the matrix. First row contains the key. Second row contains the order of alphabets in the key. Rest of the rows are filled with the text which will be decrypted. */ for i in 0..rows { for j in 0..cols { if i == 0 { matrix[i][j] = key_chars[j] as u32; } else if i == 1 { let alphabetized_char = util::alphabetize_char(key_chars[j] as u32, true); matrix[i][j] = alphabetized_char; keys.push((j as u32, alphabetized_char)); } } } keys.sort_by(|a, b| a.1.cmp(&b.1)); let mut char_index: usize = 0; /* Write the columns of the text. Order of writing is determined but the key alphabets. */ for j in keys.iter() { for i in META_ROWS..rows { if char_index < text_chars.len() { matrix[i as usize][j.0 as usize] = text_chars[char_index] as u32; } else { matrix[i as usize][j.0 as usize] = EMPTY_CHAR; } char_index += 1; } } for i in META_ROWS..rows { for j in 0..cols { let c = matrix[i as usize][j as usize]; result += std::str::from_utf8(&[c as u8]).unwrap(); } } result }
use crate::util; const META_ROWS: usize = 2; const EMPTY_CHAR: u32 = 32; pub fn encrypt(text: &str, key: &str) -> String { let mut result = String::new(); let cols = key.len(); let required_rows = text.len() as f32 / cols as f32; let rows = META_ROWS + (required_rows as f32).ceil() as usize; let mut matrix = vec![vec![32; cols]; rows]; let key_chars: Vec<char> = key.to_uppercase().chars().collect(); let text_chars: Vec<char> = text.chars().collect(); /* Keys vec contains tuple consisted of the alphabetized value of the key char and its index. Later we sort by the alphabetized value to get the column reading order. */ let mut keys: Vec<(u32, u32)> = vec![]; /* Fill up the matrix. First row contains the key. Second row contains the order of alphabets in the key. Rest of the rows are filled with the text which will be encrypted. */ for i in 0..rows { for j in 0..cols { if i == 0 { matrix[i][j] = key_chars[j] as u32; } else if i == 1 { let alphabetized_char = util::alphabetize_char(key_chars[j] as u32, true); matrix[i][j] = alphabetized_char; keys.push((j as u32, alphabetized_char)); } else { let char_index = (i - META_ROWS) + j + ((i - META_ROWS) * (cols - 1)); if char_index < text_chars.len() { matrix[i][j] = text_chars[char_index] as u32; } else { matrix[i][j] = EMPTY_CHAR; } } } } keys.sort_by(|a, b| a.1.cmp(&b.1)); /* Read the columns of the text. Order of reading is determined but the key alphabets. */ for j in keys.iter() { for i in META_ROWS..rows { let c = matrix[i as usize][j.0 as usize]; result += std::str::from_utf8(&[c as u8]).unwrap(); } } result } pub fn decr
f i == 1 { let alphabetized_char = util::alphabetize_char(key_chars[j] as u32, true); matrix[i][j] = alphabetized_char; keys.push((j as u32, alphabetized_char)); } } } keys.sort_by(|a, b| a.1.cmp(&b.1)); let mut char_index: usize = 0; /* Write the columns of the text. Order of writing is determined but the key alphabets. */ for j in keys.iter() { for i in META_ROWS..rows { if char_index < text_chars.len() { matrix[i as usize][j.0 as usize] = text_chars[char_index] as u32; } else { matrix[i as usize][j.0 as usize] = EMPTY_CHAR; } char_index += 1; } } for i in META_ROWS..rows { for j in 0..cols { let c = matrix[i as usize][j as usize]; result += std::str::from_utf8(&[c as u8]).unwrap(); } } result }
ypt(text: &str, key: &str) -> String { let mut result = String::new(); let cols = key.len(); let required_rows = text.len() as f32 / cols as f32; let rows = META_ROWS + (required_rows as f32).ceil() as usize; let mut matrix = vec![vec![32; cols]; rows]; let key_chars: Vec<char> = key.to_uppercase().chars().collect(); let text_chars: Vec<char> = text.chars().collect(); /* Keys vec contains tuple consisted of the alphabetized value of the key char and its index. Later we sort by the alphabetized value to get the column reading order. */ let mut keys: Vec<(u32, u32)> = vec![]; /* Fill up the matrix. First row contains the key. Second row contains the order of alphabets in the key. Rest of the rows are filled with the text which will be decrypted. */ for i in 0..rows { for j in 0..cols { if i == 0 { matrix[i][j] = key_chars[j] as u32; } else i
function_block-random_span
[ { "content": "pub fn encrypt(text: &str, n: u32) -> String {\n\n let mut result = String::new();\n\n\n\n for c in text.chars() {\n\n let is_upper = c.is_uppercase();\n\n\n\n let encrypted = (util::alphabetize_char(c as u32, is_upper) + n) % 26;\n\n result += std::str::from_utf8(&[util...
Rust
experiments/src/bin/graphs.rs
petrosagg/differential-dataflow
2e38abbb62aedf02cb9b6b5debb73c29b6e97dbb
extern crate rand; extern crate timely; extern crate differential_dataflow; use std::rc::Rc; use rand::{Rng, SeedableRng, StdRng}; use timely::dataflow::*; use differential_dataflow::input::Input; use differential_dataflow::Collection; use differential_dataflow::operators::*; use differential_dataflow::trace::Trace; use differential_dataflow::operators::arrange::ArrangeByKey; use differential_dataflow::operators::arrange::ArrangeBySelf; use differential_dataflow::trace::implementations::spine_fueled::Spine; type Node = usize; use differential_dataflow::trace::implementations::ord::OrdValBatch; type GraphTrace = Spine<Node, Node, (), isize, Rc<OrdValBatch<Node, Node, (), isize>>>; fn main() { let nodes: usize = std::env::args().nth(1).unwrap().parse().unwrap(); let edges: usize = std::env::args().nth(2).unwrap().parse().unwrap(); timely::execute_from_args(std::env::args().skip(3), move |worker| { let index = worker.index(); let peers = worker.peers(); let timer = ::std::time::Instant::now(); let (mut graph, mut trace) = worker.dataflow(|scope| { let (graph_input, graph) = scope.new_collection(); let graph_indexed = graph.arrange_by_key(); (graph_input, graph_indexed.trace) }); let seed: &[_] = &[1, 2, 3, index]; let mut rng1: StdRng = SeedableRng::from_seed(seed); if index == 0 { println!("performing workload on random graph with {} nodes, {} edges:", nodes, edges); } let worker_edges = edges/peers + if index < (edges % peers) { 1 } else { 0 }; for _ in 0 .. worker_edges { graph.insert((rng1.gen_range(0, nodes) as Node, rng1.gen_range(0, nodes) as Node)); } graph.close(); while worker.step() { } if index == 0 { println!("{:?}\tgraph loaded", timer.elapsed()); } let mut roots = worker.dataflow(|scope| { let (roots_input, roots) = scope.new_collection(); reach(&mut trace, roots); roots_input }); if index == 0 { roots.insert(0); } roots.close(); while worker.step() { } if index == 0 { println!("{:?}\treach complete", timer.elapsed()); } let mut roots = worker.dataflow(|scope| { let (roots_input, roots) = scope.new_collection(); bfs(&mut trace, roots); roots_input }); if index == 0 { roots.insert(0); } roots.close(); while worker.step() { } if index == 0 { println!("{:?}\tbfs complete", timer.elapsed()); } }).unwrap(); } use differential_dataflow::operators::arrange::TraceAgent; type TraceHandle = TraceAgent<GraphTrace>; fn reach<G: Scope<Timestamp = ()>> ( graph: &mut TraceHandle, roots: Collection<G, Node> ) -> Collection<G, Node> { let graph = graph.import(&roots.scope()); roots.iterate(|inner| { let graph = graph.enter(&inner.scope()); let roots = roots.enter(&inner.scope()); graph.join_core(&inner.arrange_by_self(), |_src,&dst,&()| Some(dst)) .concat(&roots) .distinct_total() }) } fn bfs<G: Scope<Timestamp = ()>> ( graph: &mut TraceHandle, roots: Collection<G, Node> ) -> Collection<G, (Node, u32)> { let graph = graph.import(&roots.scope()); let roots = roots.map(|r| (r,0)); roots.iterate(|inner| { let graph = graph.enter(&inner.scope()); let roots = roots.enter(&inner.scope()); graph.join_map(&inner, |_src,&dest,&dist| (dest, dist+1)) .concat(&roots) .reduce(|_key, input, output| output.push((*input[0].0,1))) }) }
extern crate rand; extern crate timely; extern crate differential_dataflow; use std::rc::Rc; use rand::{Rng, SeedableRng, StdRng}; use timely::dataflow::*; use differential_dataflow::input::Input; use differential_dataflow::Collection; use differential_dataflow::operators::*; use differential_dataflow::trace::Trace; use differential_dataflow::operators::arrange::ArrangeByKey; use differential_dataflow::operators::arrange::ArrangeBySelf; use differential_dataflow::trace::implementations::spine_fueled::Spine; type Node = usize; use differential_dataflow::trace::implementations::ord::OrdValBatch; type GraphTrace = Spine<Node, Node, (), isize, Rc<OrdValBatch<Node, Node, (), isize>>>; fn main() { let nodes: usize = std::env::args().nth(1).unwrap().parse().unwrap(); let edges: usize = std::env::args().nth(2).unwrap().parse().unwrap(); timely::execute_from_args(std::env::args().skip(3), move |worker| { let index = worker.index(); let peers = worker.peers(); let timer = ::std::time::Instant::now(); let (mut graph, mut trace) = worker.dataflow(|scope| { let (graph_input, graph) = scope.new_collection(); let graph_indexed = graph.arrange_by_key(); (graph_input, graph_indexed.trace) }); let seed: &[_] = &[1, 2, 3, index]; let mut rng1: StdRng = SeedableRng::from_seed(seed); if index == 0 { println!("performing workload on random graph with {} nodes, {} edges:", nodes, edges); } let worker_edges = edges/peers + if index < (edges % peers) { 1 } else { 0 }; for _ in 0 .. worker_edges { graph.insert((rng1.gen_range(0, nodes) as Node, rng1.gen_range(0, nodes) as Node)); } graph.close(); while worker.step() { } if index == 0 { println!("{:?}\tgraph loaded", timer.elapsed()); } let mut roots = worker.dataflow(|scope| { let (roots_input, roots) = scope.new_collection(); reach(&mut trace, roots); roots_input }); if index == 0 { roots.insert(0); } roots.close(); while worker.step() { } if index == 0 { println!("{:?}\treach complete", timer.elapsed()); } let mut roots = worker.dataflow(|scope| { let (roots_input, roots) = scope.new_collection(); bfs(&mut trace, roots); roots_input }); if index == 0 { roots.insert(0); } roots.close(); while worker.step() { } if index == 0 { println!("{:?}\tbfs complete", timer.elapsed()); } }).unwrap(); } use differential_dataflow::operators::arrange::TraceAgent; type TraceHandle = TraceAgent<GraphTrace>; fn reach<G: Scope<Timestamp = ()>> ( graph: &mut TraceHandle, roots: Collection<G, Node> ) -> Collection<G, Node> { let graph = graph.import(&roots.scope()); roots.iterate(|inner| { let graph = graph.enter(&inne
fn bfs<G: Scope<Timestamp = ()>> ( graph: &mut TraceHandle, roots: Collection<G, Node> ) -> Collection<G, (Node, u32)> { let graph = graph.import(&roots.scope()); let roots = roots.map(|r| (r,0)); roots.iterate(|inner| { let graph = graph.enter(&inner.scope()); let roots = roots.enter(&inner.scope()); graph.join_map(&inner, |_src,&dest,&dist| (dest, dist+1)) .concat(&roots) .reduce(|_key, input, output| output.push((*input[0].0,1))) }) }
r.scope()); let roots = roots.enter(&inner.scope()); graph.join_core(&inner.arrange_by_self(), |_src,&dst,&()| Some(dst)) .concat(&roots) .distinct_total() }) }
function_block-function_prefixed
[ { "content": "fn dump_cursor<Tr>(round: u32, index: usize, trace: &mut Tr)\n\nwhere\n\n Tr: TraceReader,\n\n Tr::Key: Debug + Clone,\n\n Tr::Val: Debug + Clone,\n\n Tr::Time: Debug + Clone,\n\n Tr::R: Debug + Clone,\n\n{\n\n let (mut cursor, storage) = trace.cursor();\n\n for ((k, v), diffs...
Rust
boa/src/exec/mod.rs
RageKnify/boa
7d318f0582a2aac5a01af762635000c686452ab4
mod array; mod block; mod break_node; mod call; mod conditional; mod declaration; mod field; mod identifier; mod iteration; mod new; mod object; mod operator; mod return_smt; mod spread; mod statement_list; mod switch; mod throw; mod try_node; #[cfg(test)] mod tests; use crate::{ syntax::ast::{constant::Const, node::Node}, BoaProfiler, Context, Result, Value, }; pub trait Executable { fn run(&self, interpreter: &mut Context) -> Result<Value>; } #[derive(Debug, Eq, PartialEq)] pub(crate) enum InterpreterState { Executing, Return, Break(Option<String>), Continue(Option<String>), } #[derive(Debug)] pub struct Interpreter { state: InterpreterState, } impl Default for Interpreter { fn default() -> Self { Self::new() } } impl Interpreter { pub fn new() -> Self { Self { state: InterpreterState::Executing, } } #[inline] pub(crate) fn set_current_state(&mut self, new_state: InterpreterState) { self.state = new_state } #[inline] pub(crate) fn get_current_state(&self) -> &InterpreterState { &self.state } } impl Executable for Node { fn run(&self, interpreter: &mut Context) -> Result<Value> { let _timer = BoaProfiler::global().start_event("Executable", "exec"); match *self { Node::Const(Const::Null) => Ok(Value::null()), Node::Const(Const::Num(num)) => Ok(Value::rational(num)), Node::Const(Const::Int(num)) => Ok(Value::integer(num)), Node::Const(Const::BigInt(ref num)) => Ok(Value::from(num.clone())), Node::Const(Const::Undefined) => Ok(Value::Undefined), Node::Const(Const::String(ref value)) => Ok(Value::string(value.to_string())), Node::Const(Const::Bool(value)) => Ok(Value::boolean(value)), Node::Block(ref block) => block.run(interpreter), Node::Identifier(ref identifier) => identifier.run(interpreter), Node::GetConstField(ref get_const_field_node) => get_const_field_node.run(interpreter), Node::GetField(ref get_field) => get_field.run(interpreter), Node::Call(ref call) => call.run(interpreter), Node::WhileLoop(ref while_loop) => while_loop.run(interpreter), Node::DoWhileLoop(ref do_while) => do_while.run(interpreter), Node::ForLoop(ref for_loop) => for_loop.run(interpreter), Node::If(ref if_smt) => if_smt.run(interpreter), Node::ConditionalOp(ref op) => op.run(interpreter), Node::Switch(ref switch) => switch.run(interpreter), Node::Object(ref obj) => obj.run(interpreter), Node::ArrayDecl(ref arr) => arr.run(interpreter), Node::FunctionDecl(ref decl) => decl.run(interpreter), Node::FunctionExpr(ref function_expr) => function_expr.run(interpreter), Node::ArrowFunctionDecl(ref decl) => decl.run(interpreter), Node::BinOp(ref op) => op.run(interpreter), Node::UnaryOp(ref op) => op.run(interpreter), Node::New(ref call) => call.run(interpreter), Node::Return(ref ret) => ret.run(interpreter), Node::Throw(ref throw) => throw.run(interpreter), Node::Assign(ref op) => op.run(interpreter), Node::VarDeclList(ref decl) => decl.run(interpreter), Node::LetDeclList(ref decl) => decl.run(interpreter), Node::ConstDeclList(ref decl) => decl.run(interpreter), Node::Spread(ref spread) => spread.run(interpreter), Node::This => { Ok(interpreter.realm().environment.get_this_binding()) } Node::Try(ref try_node) => try_node.run(interpreter), Node::Break(ref break_node) => break_node.run(interpreter), Node::Continue(ref continue_node) => continue_node.run(interpreter), } } }
mod array; mod block; mod break_node; mod call; mod conditional; mod declaration; mod field; mod identifier; mod iteration; mod new; mod object; mod operator; mod return_smt; mod spread; mod statement_list; mod switch; mod throw; mod try_node; #[cfg(test)] mod tests; use crate::{ syntax::ast::{constant::Const, node::Node}, BoaProfiler, Context, Result, Value, }; pub trait Executable { fn run(&self, interpreter: &mut Context) -> Result<Value>; } #[derive(Debug, Eq, PartialEq)] pub(crate) enum InterpreterState { Executing, Return, Break(Option<String>), Continue(Option<String>), } #[derive(Debug)] pub struct Interpreter { state: InterpreterState, } impl Default for Interpreter { fn default() -> Self { Self::new() } } impl Interpreter { pub fn new() -> Self { Self { state: InterpreterState::Executing, } } #[inline] pub(crate) fn set_current_state(&mut self, new_state: InterpreterState) { self.state = new_state } #[inline] pub(crate) fn get_current_state(&self) -> &InterpreterState { &self.state } } impl Executable for Node { fn run(&self, interpreter: &mut Context) -> Result<Value> { let _timer = BoaProfiler::global().start_event("Executable", "exec"); match *self { Node::Const(Const::Null) => Ok(Value::null()), Node::Const(Const::Num(num)) => Ok(Value::rational(num)), Node::Const(Const::Int(num)) => Ok(Value::integer(num)), Node::Const(Const::BigInt(ref num)) => Ok(Value::from(num.clone())), Node::Const(Const::Undefined) => Ok(Value::Undefined), Node::Const(Const::String(ref value)) => Ok(Value::string(value.to_string())), Node::Const(Const::Bool(value)) => Ok(Value::boolean(value)), Node::Block(ref block) => block.run(interpreter), Node::Identifier(ref identifier) => identifier.run(interpreter), Node::GetConstField(ref get_const_field_node) => get_const_field_node.run(interpreter), Node::GetField(ref get_field) => get_field.run(interpreter), Node::Call(ref call) => call.run(interpreter), Node::WhileLoop(ref while_loo
}
p) => while_loop.run(interpreter), Node::DoWhileLoop(ref do_while) => do_while.run(interpreter), Node::ForLoop(ref for_loop) => for_loop.run(interpreter), Node::If(ref if_smt) => if_smt.run(interpreter), Node::ConditionalOp(ref op) => op.run(interpreter), Node::Switch(ref switch) => switch.run(interpreter), Node::Object(ref obj) => obj.run(interpreter), Node::ArrayDecl(ref arr) => arr.run(interpreter), Node::FunctionDecl(ref decl) => decl.run(interpreter), Node::FunctionExpr(ref function_expr) => function_expr.run(interpreter), Node::ArrowFunctionDecl(ref decl) => decl.run(interpreter), Node::BinOp(ref op) => op.run(interpreter), Node::UnaryOp(ref op) => op.run(interpreter), Node::New(ref call) => call.run(interpreter), Node::Return(ref ret) => ret.run(interpreter), Node::Throw(ref throw) => throw.run(interpreter), Node::Assign(ref op) => op.run(interpreter), Node::VarDeclList(ref decl) => decl.run(interpreter), Node::LetDeclList(ref decl) => decl.run(interpreter), Node::ConstDeclList(ref decl) => decl.run(interpreter), Node::Spread(ref spread) => spread.run(interpreter), Node::This => { Ok(interpreter.realm().environment.get_this_binding()) } Node::Try(ref try_node) => try_node.run(interpreter), Node::Break(ref break_node) => break_node.run(interpreter), Node::Continue(ref continue_node) => continue_node.run(interpreter), } }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn this_time_value(value: &Value, ctx: &mut Context) -> Result<Date> {\n\n if let Value::Object(ref object) = value {\n\n if let ObjectData::Date(ref date) = object.borrow().data {\n\n return Ok(*date);\n\n }\n\n }\n\n Err(ctx.construct_type_error...
Rust
term/src/test/csi.rs
bcully/wezterm
ea401e1f58ca5a088ac5d5e1d7963f36269afb76
use super::*; #[test] fn test_vpa() { let mut term = TestTerm::new(3, 4, 0); term.assert_cursor_pos(0, 0, None); term.print("a\r\nb\r\nc"); term.assert_cursor_pos(1, 2, None); term.print("\x1b[d"); term.assert_cursor_pos(1, 0, None); term.print("\r\n\r\n"); term.assert_cursor_pos(0, 2, None); term.print("\x1b[2d"); term.assert_cursor_pos(0, 1, None); term.print("\x1b[-2d"); term.assert_cursor_pos(0, 1, None); } #[test] fn test_rep() { let mut term = TestTerm::new(3, 4, 0); term.print("h"); term.cup(1, 0); term.print("\x1b[2ba"); assert_visible_contents(&term, file!(), line!(), &["hhha", " ", " "]); } #[test] fn test_irm() { let mut term = TestTerm::new(3, 8, 0); term.print("foo"); term.cup(0, 0); term.print("\x1b[4hBAR"); assert_visible_contents( &term, file!(), line!(), &["BARfoo ", " ", " "], ); } #[test] fn test_ich() { let mut term = TestTerm::new(3, 4, 0); term.print("hey!wat?"); term.cup(1, 0); term.print("\x1b[2@"); assert_visible_contents(&term, file!(), line!(), &["h e", "wat?", " "]); term.print("\x1b[12@"); assert_visible_contents(&term, file!(), line!(), &["h ", "wat?", " "]); term.print("\x1b[-12@"); assert_visible_contents(&term, file!(), line!(), &["h ", "wat?", " "]); } #[test] fn test_ech() { let mut term = TestTerm::new(3, 4, 0); term.print("hey!wat?"); term.cup(1, 0); term.print("\x1b[2X"); assert_visible_contents(&term, file!(), line!(), &["h !", "wat?", " "]); term.print("\x1b[12X"); assert_visible_contents(&term, file!(), line!(), &["h ", "wat?", " "]); term.print("\x1b[-12X"); assert_visible_contents(&term, file!(), line!(), &["h ", "wat?", " "]); } #[test] fn test_dch() { let mut term = TestTerm::new(1, 12, 0); term.print("hello world"); term.cup(1, 0); term.print("\x1b[P"); assert_visible_contents(&term, file!(), line!(), &["hllo world "]); term.cup(4, 0); term.print("\x1b[2P"); assert_visible_contents(&term, file!(), line!(), &["hlloorld "]); term.print("\x1b[-2P"); assert_visible_contents(&term, file!(), line!(), &["hlloorld "]); } #[test] fn test_cup() { let mut term = TestTerm::new(3, 4, 0); term.cup(1, 1); term.assert_cursor_pos(1, 1, None); term.cup(-1, -1); term.assert_cursor_pos(0, 0, None); term.cup(2, 2); term.assert_cursor_pos(2, 2, None); term.cup(-1, -1); term.assert_cursor_pos(0, 0, None); term.cup(500, 500); term.assert_cursor_pos(3, 2, None); } #[test] fn test_hvp() { let mut term = TestTerm::new(3, 4, 0); term.hvp(1, 1); term.assert_cursor_pos(1, 1, None); term.hvp(-1, -1); term.assert_cursor_pos(0, 0, None); term.hvp(2, 2); term.assert_cursor_pos(2, 2, None); term.hvp(-1, -1); term.assert_cursor_pos(0, 0, None); term.hvp(500, 500); term.assert_cursor_pos(3, 2, None); } #[test] fn test_dl() { let mut term = TestTerm::new(3, 1, 0); term.print("a\r\nb\r\nc"); term.cup(0, 1); term.delete_lines(1); assert_visible_contents(&term, file!(), line!(), &["a", "c", " "]); term.assert_cursor_pos(0, 1, None); term.cup(0, 0); term.delete_lines(2); assert_visible_contents(&term, file!(), line!(), &[" ", " ", " "]); term.print("1\r\n2\r\n3"); term.cup(0, 1); term.delete_lines(-2); assert_visible_contents(&term, file!(), line!(), &["1", "2", "3"]); } #[test] fn test_cha() { let mut term = TestTerm::new(3, 4, 0); term.cup(1, 1); term.assert_cursor_pos(1, 1, None); term.print("\x1b[G"); term.assert_cursor_pos(0, 1, None); term.print("\x1b[2G"); term.assert_cursor_pos(1, 1, None); term.print("\x1b[0G"); term.assert_cursor_pos(0, 1, None); term.print("\x1b[-1G"); term.assert_cursor_pos(0, 1, None); term.print("\x1b[100G"); term.assert_cursor_pos(3, 1, None); } #[test] fn test_ed() { let mut term = TestTerm::new(3, 3, 0); term.print("abc\r\ndef\r\nghi"); term.cup(1, 2); term.print("\x1b[J"); assert_visible_contents(&term, file!(), line!(), &["abc", "def", "g "]); term.print("\x1b[44m"); term.print("\x1b[2J"); let attr = CellAttributes::default() .set_background(color::AnsiColor::Navy) .clone(); let mut line: Line = " ".into(); line.fill_range(0..=2, &Cell::new(' ', attr.clone())); assert_lines_equal( file!(), line!(), &term.screen().visible_lines(), &[line.clone(), line.clone(), line], Compare::TEXT | Compare::ATTRS, ); }
use super::*; #[test] fn test_vpa() { let mut term = TestTerm::new(3, 4, 0); term.assert_cursor_pos(0, 0, None); term.print("a\r\nb\r\nc"); term.assert_cursor_pos(1, 2, None); term.print("\x1b[d"); term.assert_cursor_pos(1, 0, None); term.print("\r\n\r\n"); term.assert_cursor_pos(0, 2, None); term.print("\x1b[2d"); term.assert_cursor_pos(0, 1, None); term.print("\x1b[-2d"); term.assert_cursor_pos(0, 1, None); } #[test] fn test_rep() { let mut term = TestTerm::new(3, 4, 0); term.print("h"); term.cup(1, 0); term.print("\x1b[2ba"); assert_visible_contents(&term, file!(), line!(), &["hhha", " ", " "]); } #[test] fn test_irm() { let mut term = TestTerm::new(3, 8, 0); term.print("foo"); term.cup(0, 0); term.print("\x1b[4hBAR"); assert_visible_contents( &term, file!(), line!(), &["BARfoo ", " ", " "], ); } #[test] fn test_ich() { let mut term = TestTerm::new(3, 4, 0); term.print("hey!wat?"); term.cup(1, 0); term.print("\x1b[2@");
#[test] fn test_ech() { let mut term = TestTerm::new(3, 4, 0); term.print("hey!wat?"); term.cup(1, 0); term.print("\x1b[2X"); assert_visible_contents(&term, file!(), line!(), &["h !", "wat?", " "]); term.print("\x1b[12X"); assert_visible_contents(&term, file!(), line!(), &["h ", "wat?", " "]); term.print("\x1b[-12X"); assert_visible_contents(&term, file!(), line!(), &["h ", "wat?", " "]); } #[test] fn test_dch() { let mut term = TestTerm::new(1, 12, 0); term.print("hello world"); term.cup(1, 0); term.print("\x1b[P"); assert_visible_contents(&term, file!(), line!(), &["hllo world "]); term.cup(4, 0); term.print("\x1b[2P"); assert_visible_contents(&term, file!(), line!(), &["hlloorld "]); term.print("\x1b[-2P"); assert_visible_contents(&term, file!(), line!(), &["hlloorld "]); } #[test] fn test_cup() { let mut term = TestTerm::new(3, 4, 0); term.cup(1, 1); term.assert_cursor_pos(1, 1, None); term.cup(-1, -1); term.assert_cursor_pos(0, 0, None); term.cup(2, 2); term.assert_cursor_pos(2, 2, None); term.cup(-1, -1); term.assert_cursor_pos(0, 0, None); term.cup(500, 500); term.assert_cursor_pos(3, 2, None); } #[test] fn test_hvp() { let mut term = TestTerm::new(3, 4, 0); term.hvp(1, 1); term.assert_cursor_pos(1, 1, None); term.hvp(-1, -1); term.assert_cursor_pos(0, 0, None); term.hvp(2, 2); term.assert_cursor_pos(2, 2, None); term.hvp(-1, -1); term.assert_cursor_pos(0, 0, None); term.hvp(500, 500); term.assert_cursor_pos(3, 2, None); } #[test] fn test_dl() { let mut term = TestTerm::new(3, 1, 0); term.print("a\r\nb\r\nc"); term.cup(0, 1); term.delete_lines(1); assert_visible_contents(&term, file!(), line!(), &["a", "c", " "]); term.assert_cursor_pos(0, 1, None); term.cup(0, 0); term.delete_lines(2); assert_visible_contents(&term, file!(), line!(), &[" ", " ", " "]); term.print("1\r\n2\r\n3"); term.cup(0, 1); term.delete_lines(-2); assert_visible_contents(&term, file!(), line!(), &["1", "2", "3"]); } #[test] fn test_cha() { let mut term = TestTerm::new(3, 4, 0); term.cup(1, 1); term.assert_cursor_pos(1, 1, None); term.print("\x1b[G"); term.assert_cursor_pos(0, 1, None); term.print("\x1b[2G"); term.assert_cursor_pos(1, 1, None); term.print("\x1b[0G"); term.assert_cursor_pos(0, 1, None); term.print("\x1b[-1G"); term.assert_cursor_pos(0, 1, None); term.print("\x1b[100G"); term.assert_cursor_pos(3, 1, None); } #[test] fn test_ed() { let mut term = TestTerm::new(3, 3, 0); term.print("abc\r\ndef\r\nghi"); term.cup(1, 2); term.print("\x1b[J"); assert_visible_contents(&term, file!(), line!(), &["abc", "def", "g "]); term.print("\x1b[44m"); term.print("\x1b[2J"); let attr = CellAttributes::default() .set_background(color::AnsiColor::Navy) .clone(); let mut line: Line = " ".into(); line.fill_range(0..=2, &Cell::new(' ', attr.clone())); assert_lines_equal( file!(), line!(), &term.screen().visible_lines(), &[line.clone(), line.clone(), line], Compare::TEXT | Compare::ATTRS, ); }
assert_visible_contents(&term, file!(), line!(), &["h e", "wat?", " "]); term.print("\x1b[12@"); assert_visible_contents(&term, file!(), line!(), &["h ", "wat?", " "]); term.print("\x1b[-12@"); assert_visible_contents(&term, file!(), line!(), &["h ", "wat?", " "]); }
function_block-function_prefix_line
[ { "content": "fn assert_all_contents(term: &Terminal, file: &str, line: u32, expect_lines: &[&str]) {\n\n print_all_lines(&term);\n\n let screen = term.screen();\n\n\n\n let expect: Vec<Line> = expect_lines.iter().map(|s| (*s).into()).collect();\n\n\n\n assert_lines_equal(file, line, &screen.all_lin...
Rust
src/materialized/src/bin/materialized/sys.rs
bobbyiliev/materialize
44e3bcae151179075232ad436ae72f5883361fd1
use std::alloc::{self, Layout}; use std::io::{self, Write}; use std::process; use std::ptr; use std::sync::atomic::{AtomicUsize, Ordering}; use anyhow::{bail, Context}; use nix::errno; use nix::sys::signal; use tracing::trace; #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "ios")))] pub fn adjust_rlimits() { trace!("rlimit crate does not support this OS; not adjusting nofile limit"); } #[cfg(any(target_os = "macos", target_os = "linux", target_os = "ios"))] pub fn adjust_rlimits() { use rlimit::Resource; use tracing::warn; let (soft, hard) = match Resource::NOFILE.get() { Ok(limits) => limits, Err(e) => { trace!("unable to read initial nofile rlimit: {}", e); return; } }; trace!("initial nofile rlimit: ({}, {})", soft, hard); #[cfg(target_os = "macos")] let hard = { use mz_ore::result::ResultExt; use std::cmp; use sysctl::Sysctl; let res = sysctl::Ctl::new("kern.maxfilesperproc") .and_then(|ctl| ctl.value()) .map_err_to_string() .and_then(|v| match v { sysctl::CtlValue::Int(v) => u64::try_from(v) .map_err(|_| format!("kern.maxfilesperproc unexpectedly negative: {}", v)), o => Err(format!("unexpected sysctl value type: {:?}", o)), }); match res { Ok(v) => { trace!("sysctl kern.maxfilesperproc hard limit: {}", v); cmp::min(v, hard) } Err(e) => { trace!("error while reading sysctl: {}", e); hard } } }; trace!("attempting to adjust nofile rlimit to ({0}, {0})", hard); if let Err(e) = Resource::NOFILE.set(hard, hard) { trace!("error adjusting nofile rlimit: {}", e); return; } let (soft, hard) = match Resource::NOFILE.get() { Ok(limits) => limits, Err(e) => { trace!("unable to read adjusted nofile rlimit: {}", e); return; } }; trace!("adjusted nofile rlimit: ({}, {})", soft, hard); const RECOMMENDED_SOFT: u64 = 1024; if soft < RECOMMENDED_SOFT { warn!( "soft nofile rlimit ({}) is dangerously low; at least {} is recommended", soft, RECOMMENDED_SOFT ) } } pub fn enable_sigbus_sigsegv_backtraces() -> Result<(), anyhow::Error> { const STACK_SIZE: usize = 2 << 20; const STACK_ALIGN: usize = 16; let buf_layout = Layout::from_size_align(STACK_SIZE, STACK_ALIGN).expect("layout known to be valid"); let buf = unsafe { alloc::alloc(buf_layout) }; let stack = libc::stack_t { ss_sp: buf as *mut libc::c_void, ss_flags: 0, ss_size: STACK_SIZE, }; let ret = unsafe { libc::sigaltstack(&stack, ptr::null_mut()) }; if ret == -1 { let errno = errno::from_i32(errno::errno()); bail!("failed to configure alternate signal stack: {}", errno); } let action = signal::SigAction::new( signal::SigHandler::Handler(handle_sigbus_sigsegv), signal::SaFlags::SA_NODEFER | signal::SaFlags::SA_ONSTACK, signal::SigSet::empty(), ); unsafe { signal::sigaction(signal::SIGBUS, &action) } .context("failed to install SIGBUS handler")?; unsafe { signal::sigaction(signal::SIGSEGV, &action) } .context("failed to install SIGSEGV handler")?; Ok(()) } pub fn enable_sigusr2_coverage_dump() -> Result<(), anyhow::Error> { let action = signal::SigAction::new( signal::SigHandler::Handler(handle_sigusr2_signal), signal::SaFlags::SA_NODEFER | signal::SaFlags::SA_ONSTACK, signal::SigSet::empty(), ); unsafe { signal::sigaction(signal::SIGUSR2, &action) } .context("failed to install SIGUSR2 handler")?; Ok(()) } extern "C" fn handle_sigbus_sigsegv(_: i32) { static SEEN: AtomicUsize = AtomicUsize::new(0); match SEEN.fetch_add(1, Ordering::SeqCst) { 0 => { panic!("received SIGSEGV or SIGBUS (maybe a stack overflow?)"); } _ => { let _ = io::stderr().write_all(b"SIGBUS or SIGSEGV while handling SIGSEGV or SIGBUS\n"); let _ = io::stderr().write_all(b"(maybe a stack overflow while allocating?)\n"); process::abort(); } } } pub fn enable_termination_signal_cleanup() -> Result<(), anyhow::Error> { let action = signal::SigAction::new( signal::SigHandler::Handler(handle_termination_signal), signal::SaFlags::SA_NODEFER | signal::SaFlags::SA_ONSTACK, signal::SigSet::empty(), ); for signum in &[ signal::SIGHUP, signal::SIGINT, signal::SIGALRM, signal::SIGTERM, signal::SIGUSR1, ] { unsafe { signal::sigaction(*signum, &action) } .with_context(|| format!("failed to install handler for {}", signum))?; } Ok(()) } extern "C" { fn __llvm_profile_write_file() -> libc::c_int; } extern "C" fn handle_sigusr2_signal(_: i32) { let _ = unsafe { __llvm_profile_write_file() }; } extern "C" fn handle_termination_signal(signum: i32) { let _ = unsafe { __llvm_profile_write_file() }; let action = signal::SigAction::new( signal::SigHandler::SigDfl, signal::SaFlags::SA_NODEFER | signal::SaFlags::SA_ONSTACK, signal::SigSet::empty(), ); unsafe { signal::sigaction(signum.try_into().unwrap(), &action) } .unwrap_or_else(|_| panic!("failed to uninstall handler for {}", signum)); let ret = unsafe { libc::raise(signum) }; if ret == -1 { let errno = errno::from_i32(errno::errno()); panic!("failed to re-raise signal {}: {}", signum, errno); } }
use std::alloc::{self, Layout}; use std::io::{self, Write}; use std::process; use std::ptr; use std::sync::atomic::{AtomicUsize, Ordering}; use anyhow::{bail, Context}; use nix::errno; use nix::sys::signal; use tracing::trace; #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "ios")))] pub fn adjust_rlimits() { trace!("rlimit crate does not support this OS; not adjusting nofile limit"); } #[cfg(any(target_os = "macos", target_os = "linux", target_os = "ios"))] pub fn adjust_rlimits() { use rlimit::Resource; use tracing::warn; let (soft, hard) = match Resource::NOFILE.get() { Ok(limits) => limits, Err(e) => { trace!("unable to read initial nofile rlimit: {}", e); return; } }; trace!("initial nofile rlimit: ({}, {})", soft, hard); #[cfg(target_os = "macos")] let hard = { use mz_ore::result::ResultExt; use std::cmp; use sysctl::Sysctl; let res = sysctl::Ctl::new("kern.maxfilesperproc") .and_then(|ctl| ctl.value()) .map_err_to_string() .and_then(|v| match v { sysctl::CtlValue::Int(v) => u64::try_from(v) .map_err(|_| format!("kern.maxfilesperproc unexpectedly negative: {}", v)), o => Err(format!("unexpected sysctl value type: {:?}", o)), }); match res { Ok(v) => { trace!("sysctl kern.maxfilesperproc hard limit: {}", v); cmp::min(v, hard) } Err(e) => { trace!("error while reading sysctl: {}", e); hard } } }; trace!("attempting to adjust nofile rlimit to ({0}, {0})", hard); if let Err(e) = Resource::NOFILE.set(hard, hard) { trace!("error adjusting nofile rlimit: {}", e); return; } let (soft, hard) = match Resource::NOFILE.get() { Ok(limits) => limits, Err(e) => { trace!("unable to read adjusted nofile rlimit: {}", e); return; } }; trace!("adjusted nofile rlimit: ({}, {})", soft, hard); const RECOMMENDED_SOFT: u64 = 1024; if soft < RECOMMENDED_SOFT { warn!( "soft nofile rlimit ({}) is dangerously low; at least {} is recommended", soft, RECOMMENDED_SOFT ) } } pub fn enable_sigbus_sigsegv_backtraces() -> Result<(), anyhow::Error> { const STACK_SIZE: usize = 2 << 20; const STACK_ALIGN: usize = 16; let buf_layout = Layout::from_size_align(STACK_SIZE, STACK_ALIGN).expect("layout known to be valid"); let buf = unsafe { alloc::alloc(buf_layout) }; let stack = libc::stack_
pub fn enable_sigusr2_coverage_dump() -> Result<(), anyhow::Error> { let action = signal::SigAction::new( signal::SigHandler::Handler(handle_sigusr2_signal), signal::SaFlags::SA_NODEFER | signal::SaFlags::SA_ONSTACK, signal::SigSet::empty(), ); unsafe { signal::sigaction(signal::SIGUSR2, &action) } .context("failed to install SIGUSR2 handler")?; Ok(()) } extern "C" fn handle_sigbus_sigsegv(_: i32) { static SEEN: AtomicUsize = AtomicUsize::new(0); match SEEN.fetch_add(1, Ordering::SeqCst) { 0 => { panic!("received SIGSEGV or SIGBUS (maybe a stack overflow?)"); } _ => { let _ = io::stderr().write_all(b"SIGBUS or SIGSEGV while handling SIGSEGV or SIGBUS\n"); let _ = io::stderr().write_all(b"(maybe a stack overflow while allocating?)\n"); process::abort(); } } } pub fn enable_termination_signal_cleanup() -> Result<(), anyhow::Error> { let action = signal::SigAction::new( signal::SigHandler::Handler(handle_termination_signal), signal::SaFlags::SA_NODEFER | signal::SaFlags::SA_ONSTACK, signal::SigSet::empty(), ); for signum in &[ signal::SIGHUP, signal::SIGINT, signal::SIGALRM, signal::SIGTERM, signal::SIGUSR1, ] { unsafe { signal::sigaction(*signum, &action) } .with_context(|| format!("failed to install handler for {}", signum))?; } Ok(()) } extern "C" { fn __llvm_profile_write_file() -> libc::c_int; } extern "C" fn handle_sigusr2_signal(_: i32) { let _ = unsafe { __llvm_profile_write_file() }; } extern "C" fn handle_termination_signal(signum: i32) { let _ = unsafe { __llvm_profile_write_file() }; let action = signal::SigAction::new( signal::SigHandler::SigDfl, signal::SaFlags::SA_NODEFER | signal::SaFlags::SA_ONSTACK, signal::SigSet::empty(), ); unsafe { signal::sigaction(signum.try_into().unwrap(), &action) } .unwrap_or_else(|_| panic!("failed to uninstall handler for {}", signum)); let ret = unsafe { libc::raise(signum) }; if ret == -1 { let errno = errno::from_i32(errno::errno()); panic!("failed to re-raise signal {}: {}", signum, errno); } }
t { ss_sp: buf as *mut libc::c_void, ss_flags: 0, ss_size: STACK_SIZE, }; let ret = unsafe { libc::sigaltstack(&stack, ptr::null_mut()) }; if ret == -1 { let errno = errno::from_i32(errno::errno()); bail!("failed to configure alternate signal stack: {}", errno); } let action = signal::SigAction::new( signal::SigHandler::Handler(handle_sigbus_sigsegv), signal::SaFlags::SA_NODEFER | signal::SaFlags::SA_ONSTACK, signal::SigSet::empty(), ); unsafe { signal::sigaction(signal::SIGBUS, &action) } .context("failed to install SIGBUS handler")?; unsafe { signal::sigaction(signal::SIGSEGV, &action) } .context("failed to install SIGSEGV handler")?; Ok(()) }
function_block-function_prefixed
[ { "content": "fn encode_element(buf: &mut BytesMut, elem: Option<&Value>, ty: &Type) -> Result<(), io::Error> {\n\n match elem {\n\n None => buf.put_i32(-1),\n\n Some(elem) => {\n\n let base = buf.len();\n\n buf.put_i32(0);\n\n elem.encode_binary(ty, buf)?;\n\n ...