blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
140
path
stringlengths
5
183
src_encoding
stringclasses
6 values
length_bytes
int64
12
5.32M
score
float64
2.52
4.94
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
12
5.32M
download_success
bool
1 class
1f851e3946451a77e68374c228aecd7b397fe6f7
Rust
hvnsweeting/adventofcode
/2021/src/day22.rs
UTF-8
5,015
2.921875
3
[ "BSD-3-Clause" ]
permissive
use regex::Regex; use std::collections::HashMap; use std::collections::HashSet; fn line_mapper(line: &str) -> (&str, ((i64, i64), (i64, i64), (i64, i64))) { let re = Regex::new(r"(?P<state>\w+) x=(?P<xs>-?\d+)..(?P<xe>-?\d+),y=(?P<ys>-?\d+)..(?P<ye>-?\d+),z=(?P<zs>-?\d+)..(?P<ze>-?\d+)").unwrap(); let caps = re.captures(line).unwrap(); let state = if &caps["state"] == "on" { "on" } else { "off" }; ( state, ( (caps["xs"].parse().unwrap(), caps["xe"].parse().unwrap()), (caps["ys"].parse().unwrap(), caps["ye"].parse().unwrap()), (caps["zs"].parse().unwrap(), caps["ze"].parse().unwrap()), ), ) } pub fn part1(xs: Vec<&str>) -> i64 { println!("xs[0..3] {:?}", &xs[0..3]); let mapped: Vec<_> = xs.iter().map(|&line| line_mapper(line)).collect(); dbg!(&mapped); let mut set: HashSet<(i64, i64, i64)> = HashSet::new(); for (state, ((xs, xe), (ys, ye), (zs, ze))) in mapped { if [xe, ye, ze].iter().any(|x| x < &-50) { continue; } if [xs, ys, zs].iter().any(|x| x > &50) { continue; } let xs = if xs < -50 { -50 } else { xs }; let ys = if ys < -50 { -50 } else { ys }; let zs = if zs < -50 { -50 } else { zs }; let xe = if xe > 50 { 50 } else { xe }; let ye = if ye > 50 { 50 } else { ye }; let ze = if ze > 50 { 50 } else { ze }; for x in xs..=xe { for y in ys..=ye { for z in zs..=ze { if state == "off" { set.remove(&(x, y, z)); } else { set.extend([(x, y, z)]); } } } } } set.len() as i64 } pub fn part2(xs: Vec<&str>) -> i64 { let mut mapped: Vec<_> = xs.iter().map(|&line| line_mapper(line)).collect(); fn disjoint((s1, e1): (i64, i64), (s2, e2): (i64, i64)) -> bool { e1 < s2 || e2 < s1 } fn non_overlap( ((x1start, x1end), (y1start, y1end), (z1start, z1end)): ( (i64, i64), (i64, i64), (i64, i64), ), ((x2start, x2end), (y2start, y2end), (z2start, z2end)): ( (i64, i64), (i64, i64), (i64, i64), ), ) -> Vec<((i64, i64), (i64, i64), (i64, i64))> { if disjoint((x1start, x1end), (x2start, x2end)) || disjoint((y1start, y1end), (y2start, y2end)) || disjoint((z1start, z1end), (z2start, z2end)) { return vec![((x1start, x1end), (y1start, y1end), (z1start, z1end))]; } return vec![ ((x1start, x1end), (y1start, y1end), (z1start, z2start - 1)), ((x1start, x1end), (y1start, y1end), (z2end + 1, z1end)), ( (x1start, x2start - 1), (y1start, y1end), (z1start.max(z2start), z1end.min(z2end)), ), ( (x2end + 1, x1end), (y1start, y1end), (z1start.max(z2start), z1end.min(z2end)), ), ( (x1start.max(x2start), x1end.min(x2end)), (y1start, y2start - 1), (z1start.max(z2start), z1end.min(z2end)), ), ( (x1start.max(x2start), x1end.min(x2end)), (y2end + 1, y1end), (z1start.max(z2start), z1end.min(z2end)), ), ] .iter() .filter(|(x, y, z)| [x, y, z].iter().all(|(s, e)| s <= e)) .cloned() .collect(); } let mut cuboids: Vec<_> = Vec::new(); while mapped.len() > 0 { let (on_off, coordinate) = mapped.remove(0); let mut parts: Vec<_> = Vec::new(); for c in cuboids { let mut ns = non_overlap(c, coordinate); parts.append(&mut ns); } if on_off == "on" { parts.push(coordinate); } cuboids = parts; } //for i in &cuboids { // println!("{:?}", i); //} cuboids .iter() .map(|((x1start, x1end), (y1start, y1end), (z1start, z1end))| { (x1end - x1start + 1) * (y1end - y1start + 1) * (z1end - z1start + 1) }) .sum() } #[cfg(test)] mod tests { use super::*; use std::fs; static S: &str = "on x=10..12,y=10..12,z=10..12 on x=11..13,y=11..13,z=11..13 off x=9..11,y=9..11,z=9..11 on x=10..10,y=10..10,z=10..10"; #[test] fn test_221() { let s = fs::read_to_string("src/input22").expect("cannot read file"); let xs = s.trim().split("\n").collect::<Vec<&str>>(); let r = part1(xs); assert_eq!(r, 611378); } #[test] fn test_222() { let s = fs::read_to_string("src/input22").expect("Cannot read file"); let xs = s.trim().split("\n").collect::<Vec<&str>>(); let r = part2(xs); assert_eq!(r, 1214313344725528); } }
true
af51d6735b914f920082a04a1b26adb310d7b57f
Rust
liljencrantz/crush
/src/lib/io/http.rs
UTF-8
3,300
2.59375
3
[ "MIT" ]
permissive
use crate::lang::errors::{argument_error_legacy, to_crush_error, CrushResult}; use crate::lang::state::contexts::CommandContext; use crate::lang::{ data::binary::binary_channel, data::r#struct::Struct, data::table::ColumnType, data::table::Row, data::table::Table, value::Value, value::ValueType, }; use reqwest::header::HeaderMap; use reqwest::{Method, StatusCode}; use signature::signature; fn parse_method(m: &str) -> CrushResult<Method> { Ok(match m { "get" => Method::GET, "post" => Method::POST, "put" => Method::PUT, "delete" => Method::DELETE, "head" => Method::HEAD, "options" => Method::OPTIONS, "connect" => Method::CONNECT, "patch" => Method::PATCH, "trace" => Method::TRACE, _ => return argument_error_legacy(format!("Unknown method {}", m).as_str()), }) } #[signature( http, short = "Make a http request", long = "Return a struct with the following fields:", long = "* status:integer, the http status of the reply", long = "* header:list, the http headers of the reply", long = "* body:binary_stream, the content of the reply", example = "http \"https://example.com/\" header=(\"Authorization: Bearer {}\":format token)", can_block = true )] pub struct Http { #[description("URI to request")] uri: String, #[description("HTTP method.")] #[values("get", "post", "put", "delete", "head", "options", "connect", "patch", "trace")] #[default("get")] method: String, #[description("form content, if any.")] form: Option<String>, #[description("HTTP headers, must be on the form \"key:value\".")] header: Vec<String>, } fn http(context: CommandContext) -> CrushResult<()> { let cfg: Http = Http::parse(context.arguments, &context.global_state.printer())?; let (mut output, input) = binary_channel(); let client = reqwest::blocking::Client::new(); let mut request = client.request(parse_method(&cfg.method)?, cfg.uri.as_str()); for t in cfg.header.iter() { let h = t.splitn(2, ':').collect::<Vec<&str>>(); match h.len() { 2 => { request = request.header(h[0], h[1].to_string()); } _ => { return argument_error_legacy("Bad header format"); } } } if let Some(body) = cfg.form { request = request.body(body) } let mut b = to_crush_error(request.send())?; let status: StatusCode = b.status(); let header_map: &HeaderMap = b.headers(); let headers = Table::from(( vec![ ColumnType::new("name", ValueType::String), ColumnType::new("value", ValueType::String), ], header_map .iter() .map(|(n, v)| { Row::new(vec![ Value::from(n.as_str()), Value::from(v.to_str().unwrap()), ]) }) .collect(), )); context.output.send(Value::Struct(Struct::new( vec![ ("status", Value::Integer(status.as_u16() as i128)), ("headers", Value::Table(headers)), ("body", Value::BinaryInputStream(input)), ], None, )))?; to_crush_error(b.copy_to(output.as_mut()))?; Ok(()) }
true
2827f4034c1c45ccd56726c9d819d7e25cc025c2
Rust
dannypsnl/elz
/src/codegen/llvm.rs
UTF-8
9,783
2.65625
3
[ "MIT" ]
permissive
use super::ir; pub trait LLVMValue { fn llvm_represent(&self) -> String; } impl LLVMValue for ir::Module { fn llvm_represent(&self) -> String { let mut s = String::new(); for (_, t) in &self.types { s.push_str(t.llvm_def().as_str()); s.push_str("\n"); } for v in &self.variables { s.push_str(v.llvm_represent().as_str()); s.push_str("\n"); } for (_, f) in &self.functions { s.push_str(f.llvm_represent().as_str()); s.push_str("\n"); } s } } impl LLVMValue for ir::GlobalName { fn llvm_represent(&self) -> String { use ir::GlobalName::*; match self { String(s) => s.clone(), ID(id) => format!("@{}", id.borrow()), } } } impl ir::Instruction { pub(crate) fn return_void(&self) -> bool { match self { ir::Instruction::FunctionCall { ret_type, .. } => { if ret_type == &Box::new(ir::Type::Void) { true } else { false } } _ => false, } } } impl LLVMValue for ir::Instruction { fn llvm_represent(&self) -> String { use ir::Instruction::*; match self { Load { id, load_from } => format!( "%{id} = load {to_type}, {from_type} {load_from}", id = id.borrow(), to_type = load_from.type_().llvm_represent(), from_type = (ir::Type::Pointer(load_from.type_().into())).llvm_represent(), load_from = load_from.llvm_represent() ), GEP { id, load_from, indices, } => { let mut s = String::new(); s.push_str( format!( "%{id} = getelementptr {target}, {ptr_to_target} {load_from}", id = id.borrow(), target = load_from.type_().element_type().llvm_represent(), ptr_to_target = load_from.type_().llvm_represent(), load_from = load_from.llvm_represent() ) .as_str(), ); for i in indices { s.push_str(format!(", i32 {}", i).as_str()) } s } Return(e) => match e { None => "ret void".to_string(), Some(ex) => { let es = ex.llvm_represent(); let ret_typ = ex.type_(); format!("ret {} {}", ret_typ.llvm_represent(), es) } }, BinaryOperation { id, op_name, lhs, rhs, } => { let mut s = String::new(); let ret_type = lhs.type_(); s.push_str( format!( "%{} = {} {} {}, {}", id.borrow(), op_name, ret_type.llvm_represent(), lhs.llvm_represent(), rhs.llvm_represent() ) .as_str(), ); s } FunctionCall { id, func_name, ret_type, args_expr, } => { let mut s = String::new(); if !self.return_void() { s.push_str(format!("%{} = ", id.borrow()).as_str()); } s.push_str("call "); s.push_str(format!("{} ", ret_type.llvm_represent()).as_str()); s.push_str(func_name.as_str()); s.push_str("("); for (index, arg_expr) in args_expr.iter().enumerate() { s.push_str(arg_expr.type_().llvm_represent().as_str()); s.push_str(" "); s.push_str(arg_expr.llvm_represent().as_str()); if index < args_expr.len() - 1 { s.push_str(", "); } } s.push_str(")"); s } Malloca { id, typ } => format!( "%{id} = call i8* @malloc(i64 {type_size})", id = id.borrow(), type_size = typ.size() ), BitCast { id, from_id, target_type, } => format!( "%{id} = bitcast i8* %{from} to {target_type}", id = id.borrow(), from = from_id.borrow(), target_type = target_type.llvm_represent() ), Store { source, destination, } => format!( "store {} {}, {} %{}", source.type_().llvm_represent(), source.llvm_represent(), (ir::Type::Pointer(source.type_().into())).llvm_represent(), destination.borrow() ), Branch { cond, if_true, if_false, } => format!( "br {} {}, {}, {}", cond.type_().llvm_represent(), cond.llvm_represent(), if_true.llvm_represent(), if_false.llvm_represent(), ), Goto(block) => format!("br {}", block.llvm_represent()), Label(label) => format!("; <label>:{}:", label.id.borrow()), } } } impl LLVMValue for ir::Label { fn llvm_represent(&self) -> String { format!("label %{}", self.id.borrow()) } } impl LLVMValue for ir::Body { fn llvm_represent(&self) -> String { let mut s = String::new(); for instruction in &self.instructions { match instruction { ir::Instruction::Label(..) => { s.push_str(format!("{}\n", instruction.llvm_represent()).as_str()); } _ => { s.push_str(format!(" {}\n", instruction.llvm_represent()).as_str()); } } } s } } impl LLVMValue for ir::Function { fn llvm_represent(&self) -> String { let mut s = String::new(); let is_declaration = self.body.is_none(); if is_declaration { s.push_str("declare "); } else { s.push_str("define "); } s.push_str(self.ret_typ.llvm_represent().as_str()); s.push_str(" "); s.push_str(self.name.as_str()); s.push_str("("); for (index, (name, typ)) in self.parameters.iter().enumerate() { s.push_str(typ.llvm_represent().as_str()); s.push_str(" %"); s.push_str(name.as_str()); if index < self.parameters.len() - 1 { s.push_str(", "); } } s.push_str(")"); match &self.body { Some(b) => { s.push_str(" {\n"); s.push_str(b.llvm_represent().as_str()); match self.ret_typ { ir::Type::Void => { s.push_str(" ret void\n"); } _ => {} } s.push_str("}"); } None => (), }; s } } impl LLVMValue for ir::Variable { fn llvm_represent(&self) -> String { let mut s = String::new(); s.push_str(self.name.llvm_represent().as_str()); s.push_str(" = "); s.push_str("global "); s.push_str(self.expr.type_().llvm_represent().as_str()); s.push_str(" "); s.push_str(self.expr.llvm_represent().as_str()); s } } impl LLVMValue for ir::Type { fn llvm_represent(&self) -> String { use ir::Type::*; match self { Void => format!("void"), Float(n) => format!("f{}", n), Int(n) => format!("i{}", n), Pointer(typ) => format!("{}*", typ.llvm_represent()), Array { len, element_type } => format!("[{} x {}]", len, element_type.llvm_represent()), Struct { name, .. } => format!("%{}*", name), Named(name) => format!("%{}", name), } } } impl ir::Type { pub(crate) fn llvm_def(&self) -> String { use ir::Type::*; match self { Struct { name, fields } => { let mut s = String::new(); s.push_str(format!("%{}", name).as_str()); s.push_str(" = type { "); for (index, field) in fields.iter().enumerate() { s.push_str(field.typ.llvm_represent().as_str()); if index < fields.len() - 1 { s.push_str(" "); } } s.push_str(" }"); s } _ => unreachable!(), } } } impl LLVMValue for ir::Expr { fn llvm_represent(&self) -> String { use ir::Expr; match self { Expr::F64(f) => format!("{}", f), Expr::I64(i) => format!("{}", i), Expr::Bool(b) => format!("{}", b), Expr::CString(s_l) => format!("c\"{}\"", s_l), Expr::Identifier(_, name) => format!("%{}", name), Expr::LocalIdentifier(_, id) => format!("%{}", id.borrow()), Expr::GlobalIdentifier(_, id) => format!("@{}", id.borrow()), } } }
true
a8b8ebc7d25af6ad4855c21b4bf2a726a787780f
Rust
FelixStridsberg/rjvm
/src/class/constant.rs
UTF-8
4,419
3.078125
3
[]
no_license
use crate::class::constant::Constant::{ ClassRef, Double, InterfaceMethodRef, Long, MethodRef, NameAndType, Utf8, NOOP, }; use crate::error::{Error, ErrorKind, Result}; use crate::vm::data_type::FieldRef; type Index = u16; #[derive(Debug, PartialEq, Clone)] pub enum MethodHandleKind { GetField, GetStatic, PutField, PutStatic, InvokeVirtual, InvokeStatic, InvokeSpecial, NewInvokeSpecial, InvokeInterface, } #[derive(Debug, PartialEq, Clone)] pub enum Constant { Utf8(String), Integer(i32), Float(f32), Long(i64), Double(f64), ClassRef(Index), StringRef(Index), FieldRef(Index, Index), MethodRef(Index, Index), InterfaceMethodRef(Index, Index), NameAndType(Index, Index), MethodHandle(MethodHandleKind, Index), MethodType(Index), Dynamic(Index, Index), InvokeDynamic(Index, Index), Module(Index), Package(Index), NOOP, } #[derive(Debug, Clone)] pub struct ConstantPool { constants: Vec<Constant>, } impl ConstantPool { pub fn new(size: u16) -> Self { ConstantPool { constants: Vec::with_capacity(size as usize), } } pub fn add(&mut self, constant: Constant) { let double = matches!(constant, Long(_) | Double(_)); self.constants.push(constant); // Long and doubles takes up two spaces. We have to add a noop to keep the indexes intact // since we don't store the actual bytes. if double { self.constants.push(NOOP) } } pub fn get(&self, index: u16) -> &Constant { &self.constants[(index - 1) as usize] } pub fn get_utf8(&self, index: u16) -> Result<&str> { let entry = self.get(index); if let Utf8(s) = entry { Ok(s.as_ref()) } else { Err(Error::new( ErrorKind::RuntimeError, Some(format!("Tried to get {:?} as a utf8", entry)), )) } } pub fn get_class_info_name(&self, index: u16) -> Result<&str> { let entry = self.get(index); if let ClassRef(name_index) = entry { self.get_utf8(*name_index) } else { Err(Error::new( ErrorKind::RuntimeError, Some(format!("Tried to get {:?} as a class reference", entry)), )) } } pub fn get_name_and_type(&self, index: u16) -> Result<(&str, &str)> { let entry = self.get(index); if let NameAndType(name_index, descriptor_index) = entry { Ok(( self.get_utf8(*name_index)?, self.get_utf8(*descriptor_index)?, )) } else { Err(Error::new( ErrorKind::RuntimeError, Some(format!("Tried to get {:?} as a class reference", entry)), )) } } pub fn get_method_ref(&self, index: u16) -> Result<(&str, &str, &str)> { let entry = self.get(index); if let MethodRef(class_index, name_type_index) = entry { let class_name = self.get_class_info_name(*class_index)?; let (method_name, descriptor_string) = self.get_name_and_type(*name_type_index)?; Ok((class_name, method_name, descriptor_string)) } else { panic!("Tried to get {:?} as a method reference", entry) } } pub fn get_interface_method_ref(&self, index: u16) -> Result<(&str, &str, &str)> { let entry = self.get(index); if let InterfaceMethodRef(class_index, name_type_index) = entry { let class_name = self.get_class_info_name(*class_index)?; let (method_name, descriptor_string) = self.get_name_and_type(*name_type_index)?; Ok((class_name, method_name, descriptor_string)) } else { panic!("Tried to get {:?} as a method reference", entry) } } pub fn get_field_ref(&self, index: u16) -> Result<FieldRef> { let entry = self.get(index); if let Constant::FieldRef(class_index, name_type_index) = entry { let class_name = self.get_class_info_name(*class_index)?; let (field_name, field_type) = self.get_name_and_type(*name_type_index)?; Ok(FieldRef::new(class_name, field_name, field_type)) } else { panic!("Tried to get {:?} as a field reference", entry) } } }
true
4fdd578f3de3f49c10511fd3f24aaa2f039c1554
Rust
Yoshiaki-Harada/rust-cqrs-sample-crud
/src/domain/todos/model/mod.rs
UTF-8
1,175
2.78125
3
[]
no_license
pub mod store; use diesel::{Queryable, Insertable}; use crate::schema::todo; #[derive(Clone, Queryable)] pub struct TodoData { pub id: i32, pub title: String, pub description: String, pub done: bool, } #[derive(Insertable)] #[table_name = "todo"] pub struct NewTodo { pub id: i32, pub title: String, pub description: String, pub done: bool, } pub struct Todo { data: TodoData, } impl Todo { pub(self) fn from_data(data: TodoData) -> Self { Todo { data: data } } // read only, borrow pub fn to_data(&self) -> &TodoData { &self.data } // read only, move ownership pub fn new_data(self) -> NewTodo { NewTodo { id: self.data.id, title: self.data.title, description: self.data.description, done: self.data.done, } } pub fn into_data(self) -> TodoData { self.data } pub fn new(id: i32, title: String, description: String, done: bool) -> Self { Todo::from_data(TodoData { id: id, title: title, description: description, done: done, }) } }
true
2ec8be92d88fa901591dc0563f1ce46933ef3720
Rust
kalaninja/algorithmic-toolbox
/week2_algorithmic_warmup/1_fibonacci_number/rust/src/main.rs
UTF-8
764
3.5
4
[]
no_license
use std::io; fn main() { let mut line = String::new(); io::stdin().read_line(&mut line).unwrap(); let n = line.trim().parse::<u32>().unwrap(); println!("{}", fibonacci_list(n)); } fn _fibonacci_naive(n: u32) -> u32 { if n > 1 { _fibonacci_naive(n - 1) + _fibonacci_naive(n - 2) } else { n } } fn fibonacci_list(n: u32) -> u32 { if n > 1 { let mut f = Vec::with_capacity((n + 1) as usize); f.push(0); f.push(1); for i in 2..=n as usize { let a = f[i - 1]; let b = f[i - 2]; f.push(a + b); } *f.last().unwrap() } else { n } } #[test] fn test_same_result() { for n in 0..=45 { assert_eq!(_fibonacci_naive(n), fibonacci_list(n)) } }
true
7b4107e930e314322c39b014c8827522c90eec17
Rust
snakemake-workflows/dna-seq-varlociraptor
/workflow/scripts/filter_primers.rs
UTF-8
3,621
2.65625
3
[ "MIT" ]
permissive
//! This is a regular crate doc comment, but it also contains a partial //! Cargo manifest. Note the use of a *fenced* code block, and the //! `cargo` "language". //! //! ```cargo //! cargo-features = ["edition2021"] //! [dependencies] //! indexmap = "1.8" //! noodles = { version = "0.18.0", features = ["bam", "sam", "bgzf"] } //! ``` use indexmap::IndexMap; use noodles::bam::{Reader, Record, Writer}; use noodles::bgzf::writer; use noodles::sam::{header::ReferenceSequence, record::data::field::Tag, Header}; use std::collections::HashSet; use std::error::Error; use std::ffi::CString; use std::fs::File; use std::i32; use std::io::BufWriter; use std::str::FromStr; fn main() -> Result<(), Box<dyn Error>> { snakemake.redirect_stderr(&snakemake.log[0])?; let mut input = File::open(&snakemake.input[0]).map(Reader::new)?; let header = input.read_header()?.parse()?; let reference_sequences = input.read_reference_sequences()?; let mut primerless_writer = build_writer(&snakemake.output.primerless, &header, &reference_sequences)?; let mut primer_writer = build_writer(&snakemake.output.primers, &header, &reference_sequences)?; let ra_tag: Tag = Tag::from_str("ra")?; let mut primary_records = HashSet::new(); for result in input.records() { let record = result?; let data = record.data(); match data.get(ra_tag) { Some(Ok(_)) => { let idx = i32::from(record.reference_sequence_id().unwrap()); let chr = reference_sequences .get_index(idx as usize) .unwrap() .0 .as_bytes(); let pos: i32 = i32::from(record.position().unwrap()); primary_records.insert((chr, pos, record.read_name().unwrap().to_owned())); } _ => continue, } } let mut input = File::open(&snakemake.input[0]).map(Reader::new)?; input.read_header()?; input.read_reference_sequences()?; let ma_tag = Tag::from_str("ma")?; for result in input.records() { let record = result?; let data = record.data(); if data.get(ra_tag).is_some() || data.get(ma_tag).is_some() || is_secondary_alignment(&record, &primary_records)? { primer_writer.write_record(&record)?; } else { primerless_writer.write_record(&record)? } } Ok(()) } fn is_secondary_alignment( record: &Record, primary_records: &HashSet<(&[u8], i32, CString)>, ) -> Result<bool, Box<dyn Error>> { let data = record.data(); match data.get(Tag::OtherAlignments) { Some(Ok(sa_entry)) => { let split_tag = sa_entry .value() .as_str() .unwrap() .split(',') .collect::<Vec<&str>>(); let chrom = split_tag[0].as_bytes(); let pos = split_tag[1].parse::<i32>()?; return Ok(primary_records.contains(&( chrom, pos, record.read_name().unwrap().to_owned(), ))); } _ => Ok(false), } } fn build_writer( file_path: &str, header: &Header, reference_sequences: &IndexMap<String, ReferenceSequence>, ) -> Result<Writer<writer::Writer<BufWriter<File>>>, Box<dyn Error>> { let mut writer = std::fs::File::create(file_path) .map(BufWriter::new) .map(Writer::new)?; writer.write_header(header)?; writer.write_reference_sequences(reference_sequences)?; Ok(writer) }
true
335bb9a397ca8d95904a3361f6b6ba2131c1f4c7
Rust
katyo/literium
/rust/backend/src/auth/method/traits.rs
UTF-8
4,653
2.75
3
[ "MIT" ]
permissive
use auth::AuthError; use base::BoxFuture; use serde::{de::DeserializeOwned, Serialize}; use user::{HasUserStorage, IsUserStorage}; /// Authentication method interface pub trait IsAuthMethod<S> where S: HasUserStorage, { /// Auth info type type AuthInfo: Serialize + Send + 'static; /// User identification type type UserIdent: DeserializeOwned + Send + 'static; /// Auth method may provide some data to client fn get_auth_info(&self, state: &S) -> Self::AuthInfo; /// Auth method should made some checks itself fn try_user_auth( &self, state: &S, ident: &Self::UserIdent, ) -> BoxFuture<<S::UserStorage as IsUserStorage>::User, AuthError>; } /// Access to auth method pub trait HasAuthMethod where Self: HasUserStorage + AsRef<<Self as HasAuthMethod>::AuthMethod> + Sized, { /// Auth method type type AuthMethod: IsAuthMethod<Self>; } /// Joining of two authentication method info #[derive(Debug, Serialize)] pub struct BothAuthInfo<A, B> { #[serde(flatten)] a: A, #[serde(flatten)] b: B, } impl<A, B> BothAuthInfo<A, B> { pub fn new(a: A, b: B) -> Self { Self { a, b } } } /// Either of two alternative user identification data #[derive(Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq)] #[serde(untagged)] pub enum EitherUserIdent<A, B> { A(A), B(B), } macro_rules! auth_info_type { ($a:ident, $b:ident) => { BothAuthInfo<$a::AuthInfo, $b::AuthInfo> }; ($a:ident, $($b:ident),+) => { BothAuthInfo<$a::AuthInfo, auth_info_type!($($b),+)> }; } macro_rules! user_ident_type { ($a:ident, $b:ident) => { EitherUserIdent<$a::UserIdent, $b::UserIdent> }; ($a:ident, $($b:ident),+) => { EitherUserIdent<$a::UserIdent, user_ident_type!($($b),+)> }; } macro_rules! get_auth_info { ($self:expr, $state:expr, $i:tt, $j:tt) => { BothAuthInfo::new($self.$i.get_auth_info($state), $self.$j.get_auth_info($state)) }; ($self:expr, $state:expr, $i:tt, $($j:tt),+) => { BothAuthInfo::new($self.$i.get_auth_info($state), get_auth_info!($self, $state, $($j),+)) }; } macro_rules! try_user_auth { ($self:expr, $state:expr, $ident:expr, $i:tt, $j:tt) => { match $ident { EitherUserIdent::A(a) => $self.$i.try_user_auth($state, a), EitherUserIdent::B(b) => $self.$j.try_user_auth($state, b), } }; ($self:expr, $state:expr, $ident:expr, $i:tt, $($j:tt),+) => { match $ident { EitherUserIdent::A(a) => $self.$i.try_user_auth($state, a), EitherUserIdent::B(ident) => try_user_auth!($self, $state, ident, $($j),+), } }; } macro_rules! tuple_method { (($($type:ident),+) => ($($id:tt),+)) => { impl<S, $($type),+> IsAuthMethod<S> for ($($type),+) where S: HasUserStorage, $($type: IsAuthMethod<S>),+ { type AuthInfo = auth_info_type!($($type),+); type UserIdent = user_ident_type!($($type),+); fn get_auth_info(&self, state: &S) -> Self::AuthInfo { get_auth_info!(self, state, $($id),+) } fn try_user_auth( &self, state: &S, ident: &Self::UserIdent, ) -> BoxFuture<<S::UserStorage as IsUserStorage>::User, AuthError> { try_user_auth!(self, state, ident, $($id),+) } } }; } tuple_method!((A, B) => (0, 1)); tuple_method!((A, B, C) => (0, 1, 2)); tuple_method!((A, B, C, D) => (0, 1, 2, 3)); tuple_method!((A, B, C, D, E) => (0, 1, 2, 3, 4)); tuple_method!((A, B, C, D, E, F) => (0, 1, 2, 3, 4, 5)); tuple_method!((A, B, C, D, E, F, G) => (0, 1, 2, 3, 4, 5, 6)); tuple_method!((A, B, C, D, E, F, G, H) => (0, 1, 2, 3, 4, 5, 6, 7)); tuple_method!((A, B, C, D, E, F, G, H, I) => (0, 1, 2, 3, 4, 5, 6, 7, 8)); tuple_method!((A, B, C, D, E, F, G, H, I, J) => (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); tuple_method!((A, B, C, D, E, F, G, H, I, J, K) => (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); tuple_method!((A, B, C, D, E, F, G, H, I, J, K, L) => (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)); tuple_method!((A, B, C, D, E, F, G, H, I, J, K, L, M) => (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)); tuple_method!((A, B, C, D, E, F, G, H, I, J, K, L, M, N) => (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)); tuple_method!((A, B, C, D, E, F, G, H, I, J, K, L, M, N, O) => (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)); tuple_method!((A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P) => (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15));
true
87f0f30d145cb7f271bb2cebd2e16cf5096cd0fb
Rust
AmitBisht14/RustFromScratch
/src/tuples.rs
UTF-8
786
3.828125
4
[]
no_license
//A tuple is a collection of values of different types. //Syntax (T1, T2, T3.... Tn), where T can be any type //method should be named in snake_case // function syntax fn fn_name(param_name: param_type ) -> return_type { } fn reverse_tuple(pair: (i32, bool)) -> (bool, i32) { let (integer, boolean) = pair; (boolean, integer) } //method should be named in snake_case pub fn access_tuples() { let random_tuple: (i32, bool) = (10, false); println!("{}, {}", random_tuple.0, random_tuple.1); let _x: (bool, i32) = reverse_tuple(random_tuple); println!("{}, {}", _x.0, _x.1); // to print whole tuple, but long tuples cannot be printed println!("{:?}", _x); //tuples can be assigned to variables let (a, b) = _x; println!("{} , {}", a, b); }
true
e0e71a1410ce147f97fa93118e51d163c8c2c15d
Rust
harski/todo
/src/optutil.rs
UTF-8
3,006
2.5625
3
[ "BSD-2-Clause" ]
permissive
// Copyright 2016 Tuomo Hartikainen <tth@harski.org>. // Licensed under the 2-clause BSD license, see LICENSE for details. use std::io::{Error, ErrorKind}; use getopts::Options; use action::Action; use opt::Opt; // TODO: rephrase option messages pub fn get_options() -> Options { let mut opts = Options::new(); opts.optflag("a", "agenda", "show agenda"); opts.optopt("A", "agenda-days", "set agenda days", "NUM"); opts.optflag("D", "debug", "set debug mode"); opts.optflag("d", "dump", "show raw todo items"); opts.optflag("e", "edit", "edit item"); opts.optflag("h", "help", "print this help"); opts.optopt("i", "id", "select item by ID", "ID"); opts.optflag("s", "show", "show item identified by -i"); opts.optflag("t", "today", "print today's and past undone items"); opts.optflag("T", "today-only", "print only today's items"); opts.optflag("v", "version", "show version"); opts.optflag("X", "delete", "delete item"); opts } pub fn parse_options(args: &Vec<String>, opts_in: &Options) -> Result<Opt, Error> { let mut opts: Opt = Opt::new(); let matches = match opts_in.parse(&args[1..]) { Ok(m) => { m } Err(f) => { panic!(f.to_string()) } }; if matches.opt_present("A") { opts.actions.push(Action::Agenda); match matches.opt_str("A") { Some(id) => match id.parse::<i64>() { Ok(i) => { opts.agenda_days = i; }, Err(err) => { let err_msg = format!("Invalid '--agenda-days' argument '{}': {}", id, err); return Err(Error::new(ErrorKind::Other, err_msg)); }, }, None => {}, }; }; if matches.opt_present("a") { opts.actions.push(Action::Agenda); } if matches.opt_present("D") { opts.debug = true; } if matches.opt_present("d") { opts.actions.push(Action::Dump); } if matches.opt_present("e") { opts.actions.push(Action::Edit); } if matches.opt_present("h") { opts.actions.push(Action::Help); } if matches.opt_present("i") { match matches.opt_str("i") { Some(id) => match id.parse::<i32>() { Ok(i) => { opts.item_id = i; }, Err(err) => { let err_msg = format!("Invalid item ID '{}': {}", id, err); return Err(Error::new(ErrorKind::Other, err_msg)); }, }, None => {}, }; } if matches.opt_present("s") { opts.actions.push(Action::Show); }; if matches.opt_present("t") { opts.actions.push(Action::Today); } if matches.opt_present("T") { opts.actions.push(Action::TodayOnly); } if matches.opt_present("v") { opts.actions.push(Action::Version); } if matches.opt_present("X") { opts.actions.push(Action::Delete); } opts.actions.sort(); opts.actions.dedup(); Ok(opts) }
true
8f4dd7a69d8686cd7dc3ca7b55fa48e797a7b64f
Rust
Qyanjia/talent-plan-rs
/kvs-rs/project-4/src/dbengines/sled.rs
UTF-8
870
2.65625
3
[]
no_license
use std::path::Path; use sled::Db; use crate::{KvsEngine, Result}; use crate::error::KvsError::KeyNotFound; #[derive(Clone, Debug)] pub struct SledKvsEngine(Db); impl SledKvsEngine { pub fn new(db: Db) -> Self { Self(db) } pub fn open(p: &Path) -> Result<Self> { Ok(Self(sled::open(p)?)) } } impl KvsEngine for SledKvsEngine { fn set(&self, key: String, value: String) -> Result<()> { let db = &self.0; db.insert(key, value.into_bytes())?; //db.flush()?; Ok(()) } fn get(&self, key: String) -> Result<Option<String>> { let db = &self.0; Ok(db.get(key)?.map_or(None, |v| Some(String::from_utf8(v.to_vec()).unwrap()))) } fn remove(&self, key: String) -> Result<()> { self.0.remove(key)?.ok_or(KeyNotFound)?; self.0.flush()?; Ok(()) } }
true
2446efac2f8f8d0eb7f72efd98ced2ca5f53ec4c
Rust
soorajkarthik/LearningRust
/leetcode/src/lib.rs
UTF-8
3,515
3.484375
3
[]
no_license
use std::borrow::BorrowMut; use std::cmp::max; use std::collections::HashMap; use std::fs::read_to_string; use std::panic::resume_unwind; pub struct Solution {} //********************************************* Two Sum ********************************************// impl Solution { pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { let mut map = HashMap::new(); for (i, num) in nums.iter().enumerate() { match map.get(num) { Some(res) => return vec![*res, i as i32], None => { map.insert(target - *num, i as i32); } } } vec![-1, -1] } } //*************************************** Add Two LinkedLists ***************************************// #[derive(PartialEq, Eq, Clone, Debug)] pub struct ListNode { pub val: i32, pub next: Option<Box<ListNode>>, } impl ListNode { #[inline] fn new(val: i32) -> Self { ListNode { next: None, val, } } } impl Solution { pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> { match (l1, l2) { (None, None) => None, (Some(n), None) | (None, Some(n)) => Some(n), (Some(n1), Some(n2)) => { let sum = n1.val + n2.val; let (digit, carry) = if sum < 10 { (sum, None) } else { (sum % 10, Some(Box::new(ListNode::new(sum / 10)))) }; Some(Box::new(ListNode { val: digit, next: Solution::add_two_numbers(Solution::add_two_numbers(n1.next, carry), n2.next), })) } } } } //********************************** Longest Unique Substring ************************************// impl Solution { pub fn length_of_longest_substring(s: String) -> i32 { let mut res = 0; let mut start: usize = 0; let mut map: HashMap<char, usize> = HashMap::new(); for (i, c) in s.chars().enumerate() { if map.contains_key(&c) { res = max(res, i - start); start = max(*map.get(&c).unwrap() + 1, start); } map.insert(c, i); } max(res, s.len() - start) as i32 } } //******************************** Longest Palindrome Substring **********************************// impl Solution { pub fn longest_palindrome(s: String) -> String { if s.len() == 0 { return String::new(); } let mut start = 0; let mut end = 0; for i in 1..s.len() - 1 { let len1 = Solution::expand_from_center(&s, i, i); let len2 = Solution::expand_from_center(&s, i, i + 1); let max = if len1.2 > len2.2 { len1 } else { len2 }; println!("{:?}", max); if max.2 > end - start { start = max.0; end = max.1; } } String::from(&s[start..end + 1]) } fn expand_from_center(s: &str, l: usize, r: usize) -> (usize, usize, usize) { let mut left = l; let mut right = r; while left >= 0 && right < s.len() && s[left..left + 1] == s[right..right + 1] { left -= 1; right += 1; } println!("{:?}", (left, right)); (left + 1, right - 1, right - left - 1) } }
true
60bc331c3b2be6a123d0103246ca9a82b4593dcf
Rust
uw-ictd/dAuth
/services/dauth-service/src/database/general.rs
UTF-8
2,806
2.703125
3
[]
no_license
use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions}; use sqlx::ConnectOptions; use crate::data::error::DauthError; use crate::database; /// Constructs the sqlite pool for running queries. #[tracing::instrument(name = "database::general")] pub async fn build_pool(database_path: &str) -> Result<SqlitePool, DauthError> { tracing::info!("Building database pool"); Ok(SqlitePoolOptions::new() .max_connections(1) .connect_with( SqliteConnectOptions::new() .disable_statement_logging() .clone() .create_if_missing(true) .filename(database_path), ) .await?) } /// Builds the database connection pool. /// Creates the database and tables if they don't exist. #[tracing::instrument(name = "database::general")] pub async fn database_init(database_path: &str) -> Result<SqlitePool, DauthError> { tracing::info!("Initializing database and all tables"); let path = std::path::Path::new(database_path); let prefix = path.parent().unwrap(); std::fs::create_dir_all(prefix).unwrap(); let pool: SqlitePool = database::general::build_pool(database_path).await?; database::flood_vectors::init_table(&pool).await?; database::auth_vectors::init_table(&pool).await?; database::kasmes::init_table(&pool).await?; database::kseafs::init_table(&pool).await?; database::user_infos::init_table(&pool).await?; database::key_shares::init_table(&pool).await?; database::key_share_state::init_table(&pool).await?; database::backup_networks::init_table(&pool).await?; database::backup_users::init_table(&pool).await?; database::vector_state::init_table(&pool).await?; database::tasks::update_users::init_table(&pool).await?; database::tasks::replace_key_shares::init_table(&pool).await?; database::tasks::report_key_shares::init_table(&pool).await?; database::tasks::report_auth_vectors::init_table(&pool).await?; Ok(pool) } /* Testing */ #[cfg(test)] mod tests { use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use sqlx::SqlitePool; use tempfile::tempdir; use crate::database; fn gen_name() -> String { let s: String = thread_rng().sample_iter(&Alphanumeric).take(10).collect(); format!("sqlite_{}.db", s) } async fn init() -> SqlitePool { let dir = tempdir().unwrap(); let path = String::from(dir.path().join(gen_name()).to_str().unwrap()); println!("Building temporary db: {}", path); let pool = database::general::database_init(&path).await.unwrap(); pool } /// Test that db and table creation will work #[tokio::test] async fn test_db_init() { init().await; } }
true
af5ef5d1fb687fb8c83b9e0d719e0ed6a1580c8d
Rust
robbym/restson-rust
/tests/error.rs
UTF-8
1,307
2.765625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
extern crate restson; #[macro_use] extern crate serde_derive; use restson::{RestClient,Error,RestPath}; #[derive(Serialize,Deserialize)] struct InvalidResource { } impl RestPath<()> for InvalidResource { fn get_path(_: ()) -> Result<String,Error> { Ok(String::from("not_found")) } } impl RestPath<bool> for InvalidResource { fn get_path(param: bool) -> Result<String,Error> { if param { return Ok(String::from("path")); } Err(Error::UrlError) } } #[test] fn invalid_baseurl() { match RestClient::new("1234") { Err(Error::UrlError) => (), _ => panic!("Expected url error") }; } #[test] fn invalid_get() { let mut client = RestClient::new("http://httpbin.org").unwrap(); if client.get::<(), InvalidResource>(()).is_ok() { panic!("expected error"); } } #[test] fn invalid_post() { let mut client = RestClient::new("http://httpbin.org").unwrap(); let data = InvalidResource {}; if client.post((), &data).is_ok() { panic!("expected error"); } } #[test] fn path_error() { let mut client = RestClient::new("http://httpbin.org").unwrap(); if let Err(Error::UrlError) = client.get::<bool, InvalidResource>(false) { } else { panic!("expected url error"); } }
true
afcbd47c178d3c9363e77775e38f17e0f09be579
Rust
gmbeard/server-fx
/examples/simple_http/content_handler.rs
UTF-8
1,733
2.515625
3
[]
no_license
extern crate pulldown_cmark; use std::path::PathBuf; use std::io::Read; use server_fx::http::router::{Parameters, RouteHandler}; use server_fx::http::types::{Request, Response, ResponseBuilder}; use self::pulldown_cmark::{html, Parser}; pub struct ContentRouteHandler { base_path: PathBuf, } impl ContentRouteHandler { pub fn new<P: Into<PathBuf>>(base_path: P) -> ContentRouteHandler { ContentRouteHandler { base_path: base_path.into(), } } } fn get_param_value<'a>(name: &'a str, params: &'a Parameters) -> Option<&'a str> { params.iter().position(|n| n.0 == name) .map(|n| &*params[n].1) } impl RouteHandler for ContentRouteHandler { fn handle(&self, _: Request, params: &Parameters) -> Response { let path = match get_param_value("page", params) { Some(v) => self.base_path.join(format!("{}.md", v)), None => { return ResponseBuilder::new(404, "Not found") .build(); } }; if !path.exists() { return ResponseBuilder::new(404, "Not found") .build(); } let mut html_buf = String::new(); let mut data_buf = vec![]; ::std::fs::File::open(path) .unwrap() .read_to_end(&mut data_buf) .unwrap(); let parser = Parser::new(::std::str::from_utf8(&data_buf).unwrap()); html::push_html(&mut html_buf, parser); let mut resp = ResponseBuilder::new(200, "OK") .build_with_stream(html_buf.into_bytes()); resp.add_header("Content-Type", "text/html"); resp } }
true
0cd51c2ad684cb1ffe4e4cf176cc48177e69fbea
Rust
p-flock/rust-shamir
/src/lib.rs
UTF-8
5,702
3.46875
3
[]
no_license
use rand::{thread_rng, Rng}; mod utils; use crate::utils::{utilities}; pub const P: i64 = 65413; // 16 bit prime, #[derive(Debug)] pub struct Share { x: i64, y: i64, threshold: i64, id: String } #[derive(Debug)] struct Polynomial { degree: i64, coefficients: Vec<i64>, // coefficients[0] is the y_intercept (b in, y=mx+b) as it is the coefficient for the 0th term } } impl Polynomial { pub fn new_random_poly(y_intercept: i64, degree: i64) -> Polynomial { let mut coefficients: Vec<i64> = Vec::new(); coefficients.push(y_intercept); let mut rng = thread_rng(); for _ in 0..degree { let a: i64 = rng.gen_range(0, P); coefficients.push(a); } Polynomial { degree: degree, coefficients: coefficients, } } // only used if you want to specify the polynomial as opposed to creating a random one // create_shares uses new_random_poly pub fn new(coefficients: Vec<i64>) -> Polynomial { let degree: i64 = (coefficients.len() - 1) as i64; Polynomial { degree: degree, coefficients: coefficients } } pub fn eval_at_point(&self, point: i64) -> i64 { let mut result: i64 = 0; for (degree, coeff) in self.coefficients.iter().enumerate() { let d = degree as i64; result += (coeff * utilities::mod_exp(point, d, P)) % P; } result % P } } #[test] fn test_polynomial_impl() { let p = Polynomial::new(vec![0, 0, 1]); let y = p.eval_at_point(1); let y2 = p.eval_at_point(2); assert_eq!(y, 1); assert_eq!(y2, 4); } /// Split a secret into n shares via shamir /// returns a vector of share objects which each represent a distinct point on a random polynomial /// with root = secret pub fn create_shares(secret: i64, n: i64, threshold: i64) -> Vec<Share> { let poly = Polynomial::new_random_poly(secret, threshold - 1); //println!("{:?}", poly); let mut shares: Vec<Share> = Vec::new(); for x in 1..n+1 { // don't eval at 0 (this is the secret) shares.push(Share{ x: x, y: poly.eval_at_point(x), threshold, id: String::from("") }); } shares } /// reconstruct a secret based on a set of shares (x, y) coordinates /// using lagrange interpolation pub fn reconstruct(shares: &Vec<Share>) -> i64 { let t = shares[0].threshold; assert!(shares.len() as i64 >= t, "not enough shares to reconstruct secret with threshold {}.", t); let x_values = shares.iter().map(|share| share.x).collect::<Vec<i64>>(); let y_values = shares.iter().map(|share| share.y).collect::<Vec<i64>>(); utilities::interpolate_at_zero(x_values, y_values, t - 1) % P } #[test] fn test_share_and_reconstruct() { let mut secret = 100; let mut shares = create_shares(secret, 3, 3); let mut recons = reconstruct(&shares); assert_eq!(secret, recons); secret = 60; shares = create_shares(secret, 8, 4); recons = reconstruct(&shares); assert_eq!(secret, recons); let mut rng = thread_rng(); let a: i64 = rng.gen_range(0, P); shares = create_shares(a, 10, 10); recons = reconstruct(&shares); assert_eq!(a, recons); } /// Adds two vectors of shares /// representing addition of two secret-shared values pub fn add_shares(a: &Vec<Share>, b: &Vec<Share>) -> Vec<Share> { assert_eq!(a.len(), b.len(), "Can only add shares with equal number of points, otherwise may be unable to reconstruct"); a.iter().zip(b.iter()).map(|tup| tup.0.add(tup.1)).collect::<Vec<Share>>() } #[test] fn test_add_shares() { let mut rng = thread_rng(); for _ in 0..20 { let a: i64 = rng.gen_range(0, P); let b: i64 = rng.gen_range(0, P); let s1 = create_shares(a, 5, 5); let s2 = create_shares(b, 5, 5); let result = utilities::modulo(a + b, P); let c = add_shares(&s1, &s2); let recons = reconstruct(&c); assert_eq!(result, recons); } } /// Subtracts one vector of shares from another /// representing subtraction of two secret-shared values pub fn sub_shares(a: &Vec<Share>, b: &Vec<Share>) -> Vec<Share> { assert_eq!(a.len(), b.len(), "Can only add shares with equal number of points, otherwise may be unable to reconstruct"); a.iter().zip(b.iter()).map(|tup| tup.0.sub(tup.1)).collect::<Vec<Share>>() } #[test] fn test_sub_shares() { let mut rng = thread_rng(); for _ in 0..20 { let a: i64 = rng.gen_range(0, P); let b: i64 = rng.gen_range(0, P); let s1 = create_shares(a, 5, 5); let s2 = create_shares(b, 5, 5); let result = utilities::modulo(a - b, P); let c = sub_shares(&s1, &s2); let recons = reconstruct(&c); assert_eq!(result, recons); } } impl Share { pub fn add(&self, o: &Share) -> Share { assert!(self.threshold == o.threshold, "Shares do not have the same threshold"); assert!(self.x == o.x, "Cannot add two shares with different x-coordinates"); Share { x: self.x, y: utilities::modulo(self.y + o.y, P), threshold: self.threshold, id: String::from("") } } pub fn sub(&self, o: &Share) -> Share { assert!(self.threshold == o.threshold, "Shares do not have the same threshold"); assert!(self.x == o.x, "Cannot subtract two shares with different x-coordinates"); Share { x: self.x, y: utilities::modulo(self.y - o.y, P), threshold: self.threshold, id: String::from("") } } }
true
0c22f3e5c93126cece776104fbfaadb456a4e1ef
Rust
ToRainu256/rust_dct
/src/common.rs
UTF-8
1,245
3.3125
3
[ "MIT", "Apache-2.0" ]
permissive
use rustfft::num_traits::FloatConst; use rustfft::FftNum; /// Generic floating point number pub trait DctNum: FftNum + FloatConst { fn half() -> Self; fn two() -> Self; } impl<T: FftNum + FloatConst> DctNum for T { fn half() -> Self { Self::from_f64(0.5).unwrap() } fn two() -> Self { Self::from_f64(2.0).unwrap() } } #[inline(always)] pub fn verify_length<T>(input: &[T], output: &[T], expected: usize) { assert_eq!( input.len(), expected, "Input is the wrong length. Expected {}, got {}", expected, input.len() ); assert_eq!( output.len(), expected, "Output is the wrong length. Expected {}, got {}", expected, output.len() ); } #[allow(unused)] #[inline(always)] pub fn verify_length_divisible<T>(input: &[T], output: &[T], expected: usize) { assert_eq!( input.len() % expected, 0, "Input is the wrong length. Expected multiple of {}, got {}", expected, input.len() ); assert_eq!( input.len(), output.len(), "Input and output must have the same length. Expected {}, got {}", input.len(), output.len() ); }
true
4f4a37c10651e482ea9e3ec9c83abfd0ea47c94d
Rust
ergpopler/yasper
/src/parse.rs
UTF-8
1,097
2.734375
3
[ "CC0-1.0" ]
permissive
use serde_derive::Deserialize; use std::fs; use std::vec::Vec; #[derive(Deserialize)] pub struct Config { pub package: Package, pub bind: Bind, pub etc: Etcetera, } #[derive(Deserialize)] pub struct Bind { pub read: ReadOnly, pub dev: Dev, pub tmpfs: Tmpfs, pub ext: Extra, } #[derive(Deserialize)] pub struct ReadOnly { pub dirs: Option<Vec<String>>, } #[derive(Deserialize)] pub struct Dev { pub dirs: Option<Vec<String>>, } #[derive(Deserialize)] pub struct Tmpfs { pub dirs: Option<Vec<String>>, } #[derive(Deserialize)] pub struct Extra { pub proc: Option<Vec<String>>, pub dev: Option<Vec<String>>, } #[derive(Deserialize)] pub struct Package { pub name: String, pub bin: String, pub args: Option<Vec<String>>, } #[derive(Deserialize)] pub struct Etcetera { pub die_with_parent: Option<bool>, } pub fn parse_file(path: &str) -> Config{ println!("Path: {}", path); let x: Config = toml::from_str(&fs::read_to_string(path).expect("Failed to read path.")).expect("Failed to parse file"); return x; }
true
aee0aa8e1765c6db1b41f1ba919c9d78884affd3
Rust
erohkohl/n-queens-sat
/tests/trim_cnf_test.rs
UTF-8
4,255
2.84375
3
[]
no_license
extern crate dpll; use std::collections::HashSet; use dpll::logic::sat as sat; #[test] fn test_trim_simple_one() { let mut cnf_to_trim: HashSet<Vec<i32>> = HashSet::new(); cnf_to_trim.insert(vec![1]); cnf_to_trim.insert(vec![2]); let result = sat::trim_cnf(cnf_to_trim, 1); let mut cnf_expected: HashSet<Vec<i32>> = HashSet::new(); cnf_expected.insert(vec![2]); assert_eq!(result, cnf_expected); } #[test] fn test_trim_simple_two() { let mut cnf_to_trim: HashSet<Vec<i32>> = HashSet::new(); cnf_to_trim.insert(vec![1, 2]); cnf_to_trim.insert(vec![3, 4]); let result = sat::trim_cnf(cnf_to_trim, 1); let mut cnf_expected: HashSet<Vec<i32>> = HashSet::new(); cnf_expected.insert(vec![3, 4]); assert_eq!(result, cnf_expected); } #[test] fn test_trim_simple_three() { let mut cnf_to_trim: HashSet<Vec<i32>> = HashSet::new(); cnf_to_trim.insert(vec![1, 2]); cnf_to_trim.insert(vec![2, 4]); cnf_to_trim.insert(vec![5]); let result = sat::trim_cnf(cnf_to_trim, 2); let mut cnf_expected: HashSet<Vec<i32>> = HashSet::new(); cnf_expected.insert(vec![5]); assert_eq!(result, cnf_expected); } #[test] fn test_trim_neg_one() { let mut cnf_to_trim: HashSet<Vec<i32>> = HashSet::new(); cnf_to_trim.insert(vec![1, -2]); cnf_to_trim.insert(vec![2, 4]); cnf_to_trim.insert(vec![5]); let result = sat::trim_cnf(cnf_to_trim, 2); let mut cnf_expected: HashSet<Vec<i32>> = HashSet::new(); cnf_expected.insert(vec![5]); cnf_expected.insert(vec![1]); assert_eq!(result, cnf_expected); } #[test] fn test_trim_neg_two() { let mut cnf_to_trim: HashSet<Vec<i32>> = HashSet::new(); cnf_to_trim.insert(vec![1, -2]); cnf_to_trim.insert(vec![2, 4]); cnf_to_trim.insert(vec![5]); let result = sat::trim_cnf(cnf_to_trim, -2); let mut cnf_expected: HashSet<Vec<i32>> = HashSet::new(); cnf_expected.insert(vec![5]); cnf_expected.insert(vec![4]); assert_eq!(result, cnf_expected); } #[test] fn test_trim_neg_three() { let mut cnf_to_trim: HashSet<Vec<i32>> = HashSet::new(); cnf_to_trim.insert(vec![1, -2]); cnf_to_trim.insert(vec![2, 4]); cnf_to_trim.insert(vec![-5]); let result = sat::trim_cnf(cnf_to_trim, -5); let mut cnf_expected: HashSet<Vec<i32>> = HashSet::new(); cnf_expected.insert(vec![1, -2]); cnf_expected.insert(vec![2, 4]); assert_eq!(result, cnf_expected); } #[test] fn test_trim_neg_four() { let mut cnf_to_trim: HashSet<Vec<i32>> = HashSet::new(); cnf_to_trim.insert(vec![1, -2]); cnf_to_trim.insert(vec![2, 4]); cnf_to_trim.insert(vec![-2, -5]); let result = sat::trim_cnf(cnf_to_trim, -2); let mut cnf_expected: HashSet<Vec<i32>> = HashSet::new(); cnf_expected.insert(vec![4]); assert_eq!(result, cnf_expected); } #[test] fn trim_test_clausel_five_lit_cnf() { let mut cnf: HashSet<Vec<i32>> = HashSet::new(); cnf.insert(vec![2, 3]); cnf.insert(vec![1, -2]); cnf.insert(vec![3, 4, 5]); let result: HashSet<Vec<i32>>; result = sat::trim_cnf(cnf.clone(), -2); let mut cnf_expected: HashSet<Vec<i32>> = HashSet::new(); cnf_expected.insert(vec![3]); cnf_expected.insert(vec![3, 4, 5]); assert_eq!(result, cnf_expected); } #[test] fn trim_test_two_clausel_one_unit() { let mut cnf: HashSet<Vec<i32>> = HashSet::new(); cnf.insert(vec![3]); cnf.insert(vec![-3, 4, 5]); let result: HashSet<Vec<i32>>; result = sat::trim_cnf(cnf.clone(), 3); let mut cnf_expected: HashSet<Vec<i32>> = HashSet::new(); cnf_expected.insert(vec![4, 5]); assert_eq!(result, cnf_expected); } #[test] fn trim_test_two_clausel_cnf_empty() { let mut cnf: HashSet<Vec<i32>> = HashSet::new(); cnf.insert(vec![3]); cnf.insert(vec![3, 4, 5]); let result: HashSet<Vec<i32>>; result = sat::trim_cnf(cnf.clone(), 3); assert!(result.is_empty()); } #[test] fn trom_cnf_two_clause_each_one_lit() { let mut cnf: HashSet<Vec<i32>> = HashSet::new(); let cnf_expected: HashSet<Vec<i32>> = HashSet::new(); cnf.insert(vec![1]); cnf.insert(vec![2]); cnf = sat::trim_cnf(cnf.clone(), 1); cnf = sat::trim_cnf(cnf.clone(), 2); assert_eq!(cnf, cnf_expected); }
true
0cd41364f99ddd210075e8af2c570741dac38261
Rust
alexsult/bernard
/src/entities/release_group.rs
UTF-8
2,130
2.78125
3
[]
no_license
use entities::artist::ArtistCredit; use entities::release::Release; use enums::*; use futures; use futures::{Future, Stream}; use hyper; use serde_json; use std::fmt; use std::io; use traits::Entity; use uuid::Uuid; #[derive(Debug, Clone, Serialize, Deserialize, Entity)] #[serde(rename_all = "kebab-case")] #[serde(default)] pub struct ReleaseGroup { pub title: String, pub primary_type: AlbumType, pub primary_type_id: Uuid, pub disambiguation: Option<String>, pub secondary_types: Option<Vec<AlbumType>>, pub first_release_date: Option<String>, pub id: Option<Uuid>, pub artist_credit: Option<Vec<ArtistCredit>>, pub releases: Option<Vec<Release>>, pub score: Option<String>, } impl ReleaseGroup { pub fn new(title: String, primary_type: AlbumType, primary_type_id: Uuid) -> ReleaseGroup { let mut release_group = ReleaseGroup::empty(); release_group.title = title; release_group.primary_type = primary_type; release_group.primary_type_id = primary_type_id; release_group } pub fn empty() -> ReleaseGroup { ReleaseGroup { title: String::new(), primary_type: AlbumType::Other, primary_type_id: Uuid::nil(), disambiguation: None, secondary_types: None, first_release_date: None, id: None, artist_credit: None, releases: None, score: None, } } } impl Default for ReleaseGroup { fn default() -> ReleaseGroup { ReleaseGroup::empty() } } impl PartialEq for ReleaseGroup { fn eq(&self, other: &ReleaseGroup) -> bool { let self_rg_id = self.id.expect("self.ReleaseGroup_id doesn't exist"); let other_rg_id = other.id.expect("other.ReleaseGroup_id doesn't exist"); self_rg_id == other_rg_id } } impl fmt::Display for ReleaseGroup { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!( f, "{title} {primary}", title = self.title, primary = self.primary_type ) } }
true
0e711e8ce36843ebb2650e5b413cc0d37aae17a0
Rust
RReverser/wasm-bindgen
/crates/cli/src/bin/wasm2es6js.rs
UTF-8
2,518
2.71875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
#[macro_use] extern crate serde_derive; extern crate docopt; extern crate failure; extern crate wasm_bindgen_cli_support; use std::fs; use std::path::PathBuf; use std::process; use docopt::Docopt; use failure::{Error, ResultExt}; // no need for jemalloc bloat in this binary (and we don't need speed) #[global_allocator] static ALLOC: std::alloc::System = std::alloc::System; const USAGE: &'static str = " Converts a wasm file to an ES6 JS module Usage: wasm2es6js [options] <input> wasm2es6js -h | --help Options: -h --help Show this screen. -o --output FILE File to place output in --typescript Output a `*.d.ts` file next to the JS output --base64 Inline the wasm module using base64 encoding --fetch PATH Load module by passing the PATH argument to `fetch()` Note that this is not intended to produce a production-ready output module but rather is intended purely as a temporary \"hack\" until it's standard in bundlers for working with wasm. Use this program with care! "; #[derive(Debug, Deserialize)] struct Args { flag_output: Option<PathBuf>, flag_typescript: bool, flag_base64: bool, flag_fetch: Option<String>, arg_input: PathBuf, } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.deserialize()) .unwrap_or_else(|e| e.exit()); let err = match rmain(&args) { Ok(()) => return, Err(e) => e, }; eprintln!("error: {}", err); for cause in err.iter_causes() { eprintln!("\tcaused by: {}", cause); } process::exit(1); } fn rmain(args: &Args) -> Result<(), Error> { let wasm = fs::read(&args.arg_input) .with_context(|_| format!("failed to read `{}`", args.arg_input.display()))?; let object = wasm_bindgen_cli_support::wasm2es6js::Config::new() .base64(args.flag_base64) .fetch(args.flag_fetch.clone()) .generate(&wasm)?; if args.flag_typescript { if let Some(ref p) = args.flag_output { let dst = p.with_extension("d.ts"); let ts = object.typescript(); fs::write(&dst, ts).with_context(|_| format!("failed to write `{}`", dst.display()))?; } } let js = object.js()?; match args.flag_output { Some(ref p) => { fs::write(p, js).with_context(|_| format!("failed to write `{}`", p.display()))?; } None => { println!("{}", js); } } Ok(()) }
true
b72b93e5e9da0d7f4934daa10facd834ca068537
Rust
krishna-gogineni-765/Advent-of-Code-2020
/rust/src/days/day17.rs
UTF-8
2,882
2.90625
3
[]
no_license
use std::io::{BufReader, BufRead}; use std::fs::File; use std::time::Instant; use std::collections::HashSet; use counter::Counter; /////////////////////////////////////////////////////////////////////////////// type Coord = i16; type CubeCoords = (Coord, Coord, Coord, Coord); /////////////////////////////////////////////////////////////////////////////// pub fn run() { let time = Instant::now(); let f = BufReader::new(File::open("../input/day17.txt").unwrap()); let initial = get_initial_cubes(f); let sol_part_1 = get_sol(&initial, 3); let sol_part_2 = get_sol(&initial, 4); let elapsed_ms = time.elapsed().as_nanos() as f64 / 1_000_000.0; println!("Part 1: {}", sol_part_1); println!("Part 2: {}", sol_part_2); println!("Elapsed: {:.3} ms", elapsed_ms); } /////////////////////////////////////////////////////////////////////////////// fn get_sol(state: &HashSet<CubeCoords>, n_dims: usize) -> usize { let mut state = state.clone(); for _ in 0..6 { let counter = state.iter() .flat_map(|cube| get_neighbors(cube, n_dims)) .collect::<Counter<_>>(); let mut stay_on: HashSet<CubeCoords> = state.iter() .filter(|cube| { let cnt = counter[cube]; (2..=3).contains(&cnt) }) .copied() .collect(); let become_on = counter.iter() .filter(|(coords, cnt)| **cnt == 3 && !state.contains(coords)) .map(|(coords, _)| *coords); stay_on.extend(become_on); state = stay_on; } return state.len(); } fn get_neighbors(cube: &CubeCoords, dim: usize) -> Vec<CubeCoords> { let cap = if dim == 3 { 26 } else { 80 }; let mut res = Vec::with_capacity(cap); let wstart = if dim == 3 { 0 } else { -1 }; let wend = if dim == 3 { 0 } else { 1 }; for dx in -1..=1 { for dy in -1..=1 { for dz in -1..=1 { for dw in wstart..=wend { if dx != 0 || dy != 0 || dz != 0 || dw != 0 { res.push((cube.0 + dx, cube.1 + dy, cube.2 + dz, cube.3 + dw)); } } } } } return res; } fn get_initial_cubes(f: BufReader<File>) -> HashSet<CubeCoords> { let mut res = HashSet::new(); for (y, line) in f.lines().enumerate() { for (x, ch) in line.unwrap().chars().enumerate() { if ch == '#' { res.insert((x as Coord, y as Coord, 0, 0)); } } } return res; }
true
67720e74b3ce6c6a633416f42e08293bef71a2d7
Rust
shaunstanislaus/kiss-ui
/src/container.rs
UTF-8
5,927
3.546875
4
[ "MIT" ]
permissive
//! Assorted types that can contain multiple widgets. //! //! All container types can be nested. use super::{BaseWidget, Orientation}; /// Vertical alignment setting, used by `Horizontal` and `Grid`. #[derive(Copy, Clone)] pub enum VAlign { Top, Center, Bottom, } impl VAlign { fn as_cstr(self) -> &'static str { use self::VAlign::*; match self { Top => cstr!("ATOP"), Center => cstr!("ACENTER"), Bottom => cstr!("ABOTTOM"), } } } /// Horizontal alignment setting, used by `Vertical` and `Grid`. #[derive(Copy, Clone)] pub enum HAlign { Left, Center, Right, } impl HAlign { fn as_cstr(self) -> &'static str { use self::HAlign::*; match self { Left => cstr!("ALEFT"), Center => cstr!("ACENTER"), Right => cstr!("ARIGHT"), } } } fn raw_handle_vec<B>(widgets: B) -> Vec<*mut ::iup_sys::Ihandle> where B: AsRef<[BaseWidget]> { let mut raw_handles: Vec<_> = widgets.as_ref().iter().map(|child| child.0).collect(); raw_handles.push(::std::ptr::null_mut()); raw_handles } /// A container type that makes no effort to arrange its children. Instead, they must be positioned /// manually. pub struct Absolute(BaseWidget); /// A container widget that lines up its children from left to right. pub struct Horizontal(BaseWidget); impl Horizontal { /// Create a new horizontal container with the given vector or array of children, which may /// also be empty. /// /// See the `children![]` macro in this crate for more info. pub fn new<C>(children: C) -> Horizontal where C: AsRef<[BaseWidget]> { let mut raw_handles = raw_handle_vec(children); unsafe { let ptr = ::iup_sys::IupHboxv(raw_handles.as_mut_ptr()); Horizontal(BaseWidget::from_ptr(ptr)) } } pub fn set_valign(mut self, valign: VAlign) -> Self { self.set_const_str_attribute(::attrs::ALIGNMENT_VERT, valign.as_cstr()); self } pub fn set_elem_spacing_pixels(mut self, spacing: u32) -> Self { self.set_str_attribute(::attrs::GAP, spacing.to_string()); self } } impl_base_widget! { Horizontal, Horizontal, "hbox" } /// A container widget that lines up its children from top to bottom. pub struct Vertical(BaseWidget); impl Vertical { pub fn new<C>(children: C) -> Vertical where C: AsRef<[BaseWidget]> { let mut raw_handles = raw_handle_vec(children); unsafe { let ptr = ::iup_sys::IupVboxv(raw_handles.as_mut_ptr()); Vertical(BaseWidget::from_ptr(ptr)) } } pub fn set_halign(mut self, halign: HAlign) -> Self { self.set_const_str_attribute(::attrs::ALIGNMENT_HORI, halign.as_cstr()); self } pub fn set_elem_spacing_pixels(mut self, spacing: u32) -> Self { self.set_str_attribute(::attrs::GAP, spacing.to_string()); self } } impl_base_widget! { Vertical, Vertical, "vbox" } /// A container widget that lines up its children from left to right, and from top to bottom. pub struct Grid(BaseWidget); impl Grid { pub fn set_valign(mut self, valign: VAlign) -> Self { self.set_const_str_attribute(::attrs::ALIGNMENT_VERT, valign.as_cstr()); self } pub fn set_halign(mut self, halign: HAlign) -> Self { self.set_const_str_attribute(::attrs::ALIGNMENT_HORI, halign.as_cstr()); self } /// Sets how children are distributed in the container. /// /// * `Vertical`: The container will prefer full columns to rows. /// /// Visual example (3x3 grid with 7 children): /// <table> /// <tr> /// <td>Child</td> /// <td>Child</td> /// <td>Child</td> /// </tr> /// <tr> /// <td>Child</td> /// <td>Child</td> /// </tr> /// <tr> /// <td>Child</td> /// <td>Child</td> /// </tr> /// </table> /// /// * `Horizontal`: The container will prefer full rows to columns. /// /// Visual example (3x3 grid with 7 children): /// <table> /// <tr> /// <td>Child</td> /// <td>Child</td> /// <td>Child</td> /// </tr> /// <tr> /// <td>Child</td> /// <td>Child</td> /// <td>Child</td> /// </tr> /// <tr> /// <td>Child</td> /// </tr> /// </table> /// pub fn set_orientation(mut self, orientation: Orientation) -> Self { self.set_const_str_attribute(::attrs::ORIENTATION, orientation.as_cstr()); self } } impl_base_widget! { Grid, Grid, "matrix" } /// Convert a heterogeneous list of widgets into an array of `BaseWidget`, /// suitable for passing to any function that takes `AsRef<[BaseWidget]>`. /// /// ##Note /// If you are getting an error saying `[BaseWidget; <integer>] does not implement /// AsRef<[BaseWidget]>`, then this array is too large. This is because `AsRef<[T]>` is only implemented for /// arrays up to size 32. To fix this, use `children_vec!` instead, which will work for any size. #[macro_export] macro_rules! children [ ($($child:expr),+,) => ([$($child.into()),+]); () => ([]); ]; /// Convert a heterogeneous list of widgets into a vector of `BaseWidget`, /// suitable for passing to any function that takes `AsRef<[BaseWidget]>`. /// /// ##Note /// While this may be used for any number of children, you should prefer the `children![]` macro, /// as it uses a stack-allocated array instead of a heap-allocated vector. Use this macro only for /// child lists of size 33 or more, as `AsRef<[T]>` is only implemented for arrays of up to /// size 32. #[macro_export] macro_rules! children_vec [ ($($child:expr),+) => (vec![$($child.into()),+]); () => (vec![]); ];
true
96098caf4bf36512e638b8dd180dc3d4e99fa138
Rust
salahgapr5/web
/cryptography-core/src/asset_proofs/transcript.rs
UTF-8
3,755
2.828125
3
[ "Apache-2.0" ]
permissive
//! The TranscriptProtocol implementation for a Merlin transcript. //! //! The role of a Merlin transcript in a non-interactive zero knowledge //! proof system is to provide a challenge without revealing any information //! about the secrets while protecting against Chosen Message attacks. use crate::{ asset_proofs::elgamal_encryption::CommitmentWitness, asset_proofs::encryption_proofs::ZKPChallenge, }; use super::errors::{ErrorKind, Fallible}; use curve25519_dalek::{ristretto::CompressedRistretto, scalar::Scalar}; use merlin::{Transcript, TranscriptRng}; use rand_core::{CryptoRng, RngCore}; use sp_std::convert::TryInto; pub trait TranscriptProtocol { /// If the inputted message is not trivial append it to the /// transcript's state. /// /// # Inputs /// * `label` a domain label for the point to append. /// * `message` a compressed Ristretto point. /// /// # Output /// Ok on success, or an error on failure. fn append_validated_point( &mut self, label: &'static [u8], message: &CompressedRistretto, ) -> Fallible<()>; /// Appends a domain separator string to the transcript's state. /// /// # Inputs /// * `message` a message string. fn append_domain_separator(&mut self, message: &'static [u8]); /// Get the protocol's challenge. /// /// # Inputs /// * `label` a domain label. /// /// # Output /// A scalar challenge. fn scalar_challenge(&mut self, label: &'static [u8]) -> Fallible<ZKPChallenge>; /// Create an RNG seeded from the transcript's cloned state and /// randomness from an external `rng`. /// /// # Inputs /// * `rng` an external RNG. /// * `witness` a commitment witness which will be used to reseed the RNG. /// /// # Output /// A new RNG. fn create_transcript_rng_from_witness<T: RngCore + CryptoRng>( &self, rng: &mut T, witness: &CommitmentWitness, ) -> TranscriptRng; } impl TranscriptProtocol for Transcript { fn append_validated_point( &mut self, label: &'static [u8], message: &CompressedRistretto, ) -> Fallible<()> { use curve25519_dalek::traits::IsIdentity; ensure!(!message.is_identity(), ErrorKind::VerificationError); self.append_message(label, message.as_bytes()); Ok(()) } fn append_domain_separator(&mut self, message: &'static [u8]) { self.append_message(b"dom-sep", message) } fn scalar_challenge(&mut self, label: &'static [u8]) -> Fallible<ZKPChallenge> { let mut buf = [0u8; 64]; self.challenge_bytes(label, &mut buf); Scalar::from_bytes_mod_order_wide(&buf).try_into() } fn create_transcript_rng_from_witness<T: RngCore + CryptoRng>( &self, rng: &mut T, witness: &CommitmentWitness, ) -> TranscriptRng { self.build_rng() .rekey_with_witness_bytes(b"w_value", &witness.value().to_bytes()) .rekey_with_witness_bytes(b"w_blinding", witness.blinding().as_bytes()) .finalize(rng) } } /// A trait that is used to update the transcript with the initial message /// that results from the first round of the protocol. pub trait UpdateTranscript { fn update_transcript(&self, d: &mut Transcript) -> Fallible<()>; } #[cfg(test)] mod tests { use super::*; #[test] fn detect_trivial_message() { use curve25519_dalek::ristretto::CompressedRistretto; let mut transcript = Transcript::new(b"unit test"); assert_err!( transcript.append_validated_point(b"identity", &CompressedRistretto::default()), ErrorKind::VerificationError ); } }
true
6d854177871ea982e3a8acc12540daef5341cb29
Rust
intdxdt/robust_segment_intersection
/src/lib.rs
UTF-8
5,056
2.765625
3
[ "MIT" ]
permissive
extern crate robust_sum; extern crate robust_scale; extern crate two_product; extern crate robust_compress_seq; extern crate robust_segment_intersect; use robust_compress_seq::compress; use robust_sum::robust_sum as rsum; use robust_scale::robust_scale as rscale; use two_product::two_product as tprod; use robust_segment_intersect::segment_intersects; //Robust segment intersection of line segments pub fn segment_intersection(a: &[f64], b: &[f64], c: &[f64], d: &[f64]) -> Vec<Vec<f64>> { exact_intersect(a, b, c, d) } // Find solution to system of two linear equations // // | a[0] a[1] 1 | // | b[0] b[1] 1 | = 0 // | x y 1 | // // | c[0] c[1] 1 | // | d[0] d[1] 1 | = 0 // | x y 1 | // fn exact_intersect(a: &[f64], b: &[f64], c: &[f64], d: &[f64]) -> Vec<Vec<f64>> { if !segment_intersects(a, b, c, d) { return vec!(vec!(0.), vec!(0.), vec!(0.)); } let x1 = rsum(&vec!(c[1]), &vec!(-d[1])); let y1 = rsum(&vec!(-c[0]), &vec!(d[0])); let mut denom = rsum( &rsum(&rscale(&y1, a[1]), &rscale(&y1, -b[1])), &rsum(&rscale(&x1, a[0]), &rscale(&x1, -b[0])), ); let w0 = rsum(&tprod(-a[0], b[1]), &tprod(a[1], b[0])); let w1 = rsum(&tprod(-c[0], d[1]), &tprod(c[1], d[0])); //Calculate nX, nY let mut nx = rsum( &rsum(&rscale(&w1, a[0]), &rscale(&w1, -b[0])), &rsum(&rscale(&w0, -c[0]), &rscale(&w0, d[0])), ); let mut ny = rsum( &rsum(&rscale(&w1, a[1]), &rscale(&w1, -b[1])), &rsum(&rscale(&w0, -c[1]), &rscale(&w0, d[1])), ); vec!(compress(&mut nx), compress(&mut ny), compress(&mut denom)) } #[cfg(test)] mod robust_seg_intersection { extern crate validate_robust_seq; extern crate robust_determinant; extern crate robust_product; extern crate robust_subtract; extern crate robust_compare; extern crate rand; use self::rand::random; use self::robust_determinant::det2; use self::robust_compare::robust_compare as cmp; use self::robust_subtract::robust_subtract as rsub; use self::robust_product::robust_product as rprod; use super::{segment_intersection as segintersection, rsum}; use self::validate_robust_seq::validate_sequence as validate; fn rnd() -> f64 { random::<f64>() } #[test] fn test_seg_intersection() { // | a[0] a[1] 1 | // | b[0] b[1] 1 | // | x y w | fn test_pt_seq(a: &[f64], b: &[f64], x: &[f64], y: &[f64], w: &[f64]) { let d0 = rsum(&vec!(a[1]), &vec!(-b[1])); let d1 = rsum(&vec!(a[0]), &vec!(-b[0])); let d2 = det2(&vec!(vec!(a[0], a[1]), vec!(b[0], b[1]))); //validate det.RobustDet2 assert!(validate(&d2)); let p0 = rprod(&x, &d0); let p1 = rprod(&y, &d1); let p2 = rprod(&w, &d2); //validate p0 assert!(validate(&p0)); //validate p1 assert!(validate(&p1)); //validate p2 assert!(validate(&p2)); let s = rsum(&rsub(&p0, &p1), &p2); //validate s assert!(validate(&s)); //check point on line assert!(cmp(&s, &vec!(0.)) == 0.) } fn verify(a: &[f64], b: &[f64], c: &[f64], d: &[f64]) { let x = segintersection(a, b, c, d); //validate x assert!(validate(&x[0])); //validate y assert!(validate(&x[1])); //validate w assert!(validate(&x[2])); test_pt_seq(&a, &b, &x[0], &x[1], &x[2]); test_pt_seq(&c, &d, &x[0], &x[1], &x[2]); let p = vec!(vec!(a, b), vec!(c, d)); for s in 0..2 { for r in 0..2 { for h in 0..2 { let y = segintersection( p[h][s], p[h][s ^ 1], p[h ^ 1][r], p[h ^ 1][r ^ 1], ); //validate x assert!(validate(&y[0])); //validate y assert!(validate(&y[1])); //validate w assert!(validate(&y[2])); //check x assert!(cmp(&rprod(&y[0], &x[2]), &rprod(&x[0], &y[2])) == 0.); //check y assert!(cmp(&rprod(&y[1], &x[2]), &rprod(&x[1], &y[2])) == 0.); } } } } //Fuzz test for _ in 0..100 { verify( &vec!(rnd(), rnd()), &vec!(rnd(), rnd()), &vec!(rnd(), rnd()), &vec!(rnd(), rnd()), ) } let isect = segintersection( &vec!(-1., 10.), &vec!(-10., 1.), &vec!(10., 0.), &vec!(10., 10.) ); //no intersections assert!(isect[2][0] == 0.); } }
true
848bc97028a583fd4734d824f6d68d6ca0f01c6d
Rust
askoufis/advent-of-code-2020
/src/day11.rs
UTF-8
8,388
3.3125
3
[]
no_license
use std::fmt; use std::str::FromStr; #[derive(Debug, PartialEq, Copy, Clone)] enum Seat { Floor, Empty, Occupied, } impl Seat { fn is_not_floor(&self) -> bool { *self != Seat::Floor } } impl FromStr for Seat { type Err = core::convert::Infallible; fn from_str(s: &str) -> Result<Self, Self::Err> { if s == "L" { return Ok(Seat::Empty); } if s == "#" { return Ok(Seat::Occupied); } return Ok(Seat::Floor); } } impl fmt::Display for Seat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self == &Seat::Empty { write!(f, "L") } else if self == &Seat::Occupied { write!(f, "#") } else { write!(f, ".") } } } #[derive(Clone)] struct Universe { width: usize, height: usize, seats: Vec<Seat>, } impl fmt::Display for Universe { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let s: String = self .seats .chunks(self.width) .into_iter() .map(|chunk| { let mut new_chunk: String = chunk.clone().iter().map(|seat| seat.to_string()).collect(); new_chunk.push_str("\n"); new_chunk }) .collect(); write!(f, "{}", s) } } #[derive(PartialEq)] enum State { Stable, Unstable, } impl Universe { fn get_index(&self, row: isize, column: isize) -> isize { if row < 0 || row >= self.height as isize { return -1; } else if column < 0 || column >= self.width as isize { return -1; } row * self.width as isize + column } fn occupied_neighbour_count(&self, row: isize, column: isize) -> usize { let north = row - 1; let south = row + 1; let west = column - 1; let east = column + 1; let nw = self.get_index(north, west); let n = self.get_index(north, column); let ne = self.get_index(north, east); let w = self.get_index(row, west); let e = self.get_index(row, east); let sw = self.get_index(south, west); let s = self.get_index(south, column); let se = self.get_index(south, east); let seat_indexes = vec![nw, n, ne, w, e, sw, s, se]; let seats = seat_indexes .iter() .filter(|i| **i != -1) .map(|i| self.seats[*i as usize]) .collect::<Vec<Seat>>(); count_occupied_seats(&seats) } fn seat_in_direction(&self, row: isize, column: isize, direction: (isize, isize)) -> Seat { match [direction] .iter() .cycle() .enumerate() .skip(1) .map(|(i, d)| { let rc = (row + (i as isize * d.0), column + (i as isize * d.1)); self.get_index(rc.0, rc.1) }) .take_while(|index| *index != -1) .map(|index| self.seats[index as usize]) .find(|seat| seat.is_not_floor()) { Some(seat) => seat, None => Seat::Floor, } } fn occupied_visible_count(&self, row: isize, column: isize) -> usize { // (row transform, column transform) let north = (-1, 0); let nw = (-1, -1); let ne = (-1, 1); let south = (1, 0); let sw = (1, -1); let se = (1, 1); let west = (0, -1); let east = (0, 1); let directions = [north, nw, ne, south, sw, se, west, east]; directions .iter() .map(|d| self.seat_in_direction(row, column, *d)) .filter(|seat| *seat == Seat::Occupied) .count() } fn get_next_seat_state(&self, seat: &Seat, row: isize, column: isize) -> Seat { if *seat == Seat::Floor { return Seat::Floor; } else { let num_occupied = self.occupied_neighbour_count(row, column); if *seat == Seat::Empty && num_occupied == 0 { return Seat::Occupied; } else if *seat == Seat::Occupied && num_occupied >= 4 { return Seat::Empty; } } return *seat; } fn get_next_seat_state2(&self, seat: &Seat, row: isize, column: isize) -> Seat { if *seat == Seat::Floor { return Seat::Floor; } else { let num_occupied_visible = self.occupied_visible_count(row, column); if *seat == Seat::Empty && num_occupied_visible == 0 { return Seat::Occupied; } else if *seat == Seat::Occupied && num_occupied_visible >= 5 { return Seat::Empty; } } return *seat; } fn tick(&mut self) -> State { let mut next = self.seats.clone(); for row in 0..self.height { for column in 0..self.width { let index = self.get_index(row as isize, column as isize); let current_seat = self.seats[index as usize]; let next_seat_state = self.get_next_seat_state(&current_seat, row as isize, column as isize); next[index as usize] = next_seat_state; } } if next == self.seats { return State::Stable; } else { self.seats = next; return State::Unstable; } } fn tick2(&mut self) -> State { let mut next = self.seats.clone(); for row in 0..self.height { for column in 0..self.width { let index = self.get_index(row as isize, column as isize); let current_seat = self.seats[index as usize]; let next_seat_state = self.get_next_seat_state2(&current_seat, row as isize, column as isize); next[index as usize] = next_seat_state; } } if next == self.seats { return State::Stable; } else { self.seats = next; return State::Unstable; } } } fn count_occupied_seats(seats: &[Seat]) -> usize { seats.iter().filter(|seat| seat == &&Seat::Occupied).count() } #[aoc_generator(day11)] fn input_generator(input: &str) -> Universe { let seats = input .lines() .map(|line| { line.chars() .map(|c| Seat::from_str(&c.to_string()).unwrap()) .collect::<Vec<Seat>>() }) .flatten() .collect(); let width = input.lines().next().unwrap().chars().count(); let height = input.lines().count(); Universe { width, height, seats, } } #[aoc(day11, part1)] fn part1(state: &Universe) -> usize { let mut u = state.clone(); loop { let tick_result = &mut u.tick(); if tick_result == &State::Stable { break; } } count_occupied_seats(&u.seats) } #[aoc(day11, part2)] fn part2(state: &Universe) -> usize { let mut u = state.clone(); loop { let tick_result = &mut u.tick2(); if tick_result == &State::Stable { break; } } count_occupied_seats(&u.seats) } #[cfg(test)] mod tests { use super::*; #[test] fn part1_test() { let input = r"L.LL.LL.LL LLLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLLL L.LLLLLL.L L.LLLLL.LL"; let generated_input = input_generator(&input); let result = part1(&generated_input); let expected = 37; assert_eq!(result, expected); } #[test] fn occupied_visible_count_test() { let input = r".......#. ...#..... .#....... ......... ..#L....# ....#.... ......... #........ ...#....."; let generated_input = input_generator(&input); let result = generated_input.occupied_visible_count(4, 3); let expected = 8; assert_eq!(result, expected); } #[test] fn part2_test() { let input = r"L.LL.LL.LL LLLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLLL L.LLLLLL.L L.LLLLL.LL"; let generated_input = input_generator(&input); let result = part2(&generated_input); let expected = 26; assert_eq!(result, expected); } }
true
73ca8ea2909277235f623e36ae016456dc68a9cd
Rust
fcsonline/trawler
/src/lib/buffer.rs
UTF-8
272
2.671875
3
[ "MIT" ]
permissive
use std::fmt; use std::collections::HashMap; pub struct Buffer { pub content: String, pub meta: HashMap<String, String> } impl fmt::Debug for Buffer { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { self.content.fmt(formatter) } }
true
c547df3b63de1266568998d928782af54a2c46a0
Rust
windniw/just-for-fun
/leetcode/1.rs
UTF-8
932
3.453125
3
[ "Apache-2.0" ]
permissive
/// link: https://leetcode.com/problems/two-sum /// problem: 数组中有两个元素相加等于target,返回其下标 /// solution: 暴力扫 /// solution-fix: 用map存取已扫描过的值 impl Solution { pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { for i in 0..nums.len() { for j in i + 1..nums.len() { if nums[i] + nums[j] == target { return vec![i as i32, j as i32]; } } } vec![] } } // --- impl Solution { pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { use std::collections::HashMap; let mut m: HashMap<i32, i32> = HashMap::new(); for i in 0..nums.len() { if m.contains_key(&(target - nums[i])) { return vec![i as i32, m[&(target - nums[i])]]; } m.insert(nums[i], i as i32); } vec![] } }
true
536b225931441d07336bf79f4f4cc8fe3d8e4939
Rust
ahbali/adventofcode2020
/day14/src/main.rs
UTF-8
3,586
3.421875
3
[ "MIT" ]
permissive
use std::io::{self, prelude::*}; use std::{collections::HashMap, error::Error}; use std::{unreachable, vec, writeln}; type Position = usize; type Value = usize; #[derive(Debug, Clone)] struct Mask { ones: Vec<usize>, xs: Vec<usize>, } impl Mask { fn new() -> Self { Self { ones: Vec::new(), xs: Vec::new(), } } fn from_str(input: &str) -> Self { let len = input.len() - 1; let input_iter = input .chars() .enumerate() .filter(|&(_, ch)| ch != '0') .map(|(idx, ch)| (len - idx, ch)); let mut ones: Vec<usize> = vec![]; let mut xs: Vec<usize> = vec![]; for (idx, ch) in input_iter { match ch { 'X' => xs.push(idx), '1' => ones.push(idx), _ => unreachable!(), } } Self { ones, xs } } fn apply(&self, value: usize) -> Vec<usize> { let mut vec_result: Vec<usize> = vec![]; let mut result = value; for &i in self.ones.iter() { result = change_bit(result, i, 1); } // generating all possible permutations for positions with X's for permutation in 0..(1 << self.xs.len()) { let mut val = result; for i in 0..self.xs.len() { // going through bits of permutation by shifting to the right and selecting // the last bit. val = change_bit(val, self.xs[i], (permutation >> i) & 1); } vec_result.push(val); } vec_result } } #[derive(Debug, Clone)] enum Instruction { MASK(Mask), MEM(Position, Value), } impl Instruction { fn from_str(line: &str) -> Self { let mut line_iter = line.split(" = "); let op = line_iter.next().unwrap().trim(); let value = line_iter.next().unwrap().trim(); match op { "mask" => Instruction::MASK(Mask::from_str(value)), _ => Instruction::MEM( op.get(4..op.len() - 1).unwrap().parse::<usize>().unwrap(), value.parse::<usize>().unwrap(), ), } } } fn change_bit(number: usize, position: usize, new_val: usize) -> usize { let mask = 1 << position; (number & !mask) | (new_val << position) } fn main() -> Result<(), Box<dyn Error>> { let stdin = io::stdin(); let stdout = io::stdout(); let mut out = io::BufWriter::new(stdout.lock()); let reader = io::BufReader::new(stdin.lock()); let instructions: Vec<Instruction> = reader .lines() .filter_map(Result::ok) .map(|line| Instruction::from_str(&line)) .collect(); let mut memory: HashMap<usize, usize> = HashMap::new(); let mut global_mask: &Mask = &Mask::new(); for instruction in instructions.iter() { match instruction { Instruction::MASK(mask) => global_mask = mask, &Instruction::MEM(position, value) => { for floating in global_mask.apply(position) { // println!("floating= {:?}", floating); memory.insert(floating, value); } } }; } // mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X // mem[8] = 11 // writeln!(&mut out, "instructions= {:?}", instructions)?; // writeln!(&mut out, "memory= {:?}", memory)?; writeln!(&mut out, "sum= {:?}", memory.values().sum::<usize>())?; writeln!(&mut out, "memory length= {:?}", memory.len())?; Ok(()) }
true
969f99eaf53417744901672b7b2e75c786deea61
Rust
bouzuya/rust-atcoder
/cargo-atcoder/contests/past202004-open/src/bin/d.rs
UTF-8
1,072
3.03125
3
[]
no_license
use proconio::input; use proconio::marker::Chars; fn f(s: &Vec<char>, t: &Vec<char>) -> bool { for s_i in s.windows(t.len()) { if s_i .iter() .zip(t.iter()) .all(|(&s_j, &t_j)| t_j == '.' || s_j == t_j) { return true; } } false } fn main() { input! { s: Chars, }; let chars = "abcdefghijklmnopqrstuvwxyz.".chars().collect::<Vec<char>>(); let mut count = 0; for &c1 in chars.iter() { let t = vec![c1]; if f(&s, &t) { count += 1; } } for &c1 in chars.iter() { for &c2 in chars.iter() { let t = vec![c1, c2]; if f(&s, &t) { count += 1; } } } for &c1 in chars.iter() { for &c2 in chars.iter() { for &c3 in chars.iter() { let t = vec![c1, c2, c3]; if f(&s, &t) { count += 1; } } } } let ans = count; println!("{}", ans); }
true
d17d1951ca0419df0cc84371e9039d37ce1a5975
Rust
vitiral/packed_struct.rs
/packed_struct/src/lib.rs
UTF-8
8,063
3.609375
4
[ "Apache-2.0", "MIT" ]
permissive
//! Bit-level packing and unpacking for Rust //! =========================================== //! //! [![Build Status](https://travis-ci.org/hashmismatch/packed_struct.rs.svg?branch=master)](https://travis-ci.org/hashmismatch/packed_struct.rs) //! //! [![Documentation](https://docs.rs/packed_struct/badge.svg)](https://docs.rs/packed_struct) //! //! # Introduction //! //! Packing and unpacking bit-level structures is usually a programming tasks that needlessly reinvents the wheel. This library provides //! a meta-programming aproach, using attributes to document fields and how they should be packed. The resulting trait implementations //! provide safe packing, unpacking and runtime debugging formatters with per-field documentation generated for each structure. //! //! # Features //! //! * Plain Rust structures, decorated with attributes //! * MSB or LSB integers of user-defined bit widths //! * Primitive enum code generation helper //! * MSB or LSB bit positioning //! * Documents the field's packing table //! * Runtime packing visualization //! * Nested packed types //! * Arrays //! //! # Sample usage //! //! ## Cargo.toml //! //! ```toml //! [dependencies] //! packed_struct = "^0.1.0" //! packed_struct_codegen = "^0.1.0" //! ``` //! ## Including the library and the code generator //! //! ```rust,ignore //! extern crate packed_struct; //! #[macro_use] //! extern crate packed_struct_codegen; //! ``` //! //! ## Example of a single-byte structure, with a 3 bit integer, primitive enum and a bool field. //! //! ```rust //! extern crate packed_struct; //! #[macro_use] extern crate packed_struct_codegen; //! //! use packed_struct::prelude::*; //! //! #[derive(PackedStruct)] //! #[packed_struct(bit_numbering="msb0")] //! pub struct TestPack { //! #[packed_field(bits="0..2")] //! tiny_int: Integer<u8, ::packed_bits::Bits3>, //! #[packed_field(bits="3..4", ty="enum")] //! mode: SelfTestMode, //! #[packed_field(bits="7")] //! enabled: bool //! } //! //! #[derive(PrimitiveEnum_u8, Clone, Copy, Debug, PartialEq)] //! pub enum SelfTestMode { //! NormalMode = 0, //! PositiveSignSelfTest = 1, //! NegativeSignSelfTest = 2, //! DebugMode = 3, //! } //! //! fn main() { //! let test = TestPack { //! tiny_int: 5.into(), //! mode: SelfTestMode::DebugMode, //! enabled: true //! }; //! //! let packed = test.pack(); //! assert_eq!([0b10111001], packed); //! //! let unpacked = TestPack::unpack(&packed).unwrap(); //! assert_eq!(*unpacked.tiny_int, 5); //! assert_eq!(unpacked.mode, SelfTestMode::DebugMode); //! assert_eq!(unpacked.enabled, true); //! } //! ``` //! //! # Packing attributes //! //! ## Syntax //! //! ```rust,ignore //! #[packed_struct(attr1="val", attr2="val")] //! struct Structure { //! #[packed_field(attr1="val", attr2="val")] //! field: u8 //! } //! ``` //! //! ## Per-structure attributes //! //! Attribute | Values | Comment //! :--|:--|:-- //! ```size_bytes``` | ```1``` ... n | Size of the packed byte stream //! ```bit_numbering``` | ```msb0``` or ```lsb0``` | Bit numbering for bit positioning of fields. Required if the bits attribute field is used. //! ```endian``` | ```msb``` or ```lsb``` | Default integer endianness //! //! ## Per-field attributes //! //! Attribute | Values | Comment //! :--|:--|:-- //! ```bits``` | ```0```, ```0..``` or ```0..2``` | Position of the field in the packed structure. Three modes are supported: a single bit, the starting bit, or the range of bits, inclusive. ```0..2``` occupies 3 bits. //! ```bytes``` | ```0```, ```0..``` or ```0..2``` | Same as above, multiplied by 8. //! ```size_bits``` | ```1```, ... | Specifies the size of the packed structure. Mandatory for certain types. Specifying a range of bits like ```bits="0..2"``` can substite the required usage of ```size_bits```. //! ```size_bytes``` | ```1```, ... | Same as above, multiplied by 8. //! ```element_size_bits``` | ```1```, ... | For packed arrays, specifies the size of a single element of the array. Explicitly stating the size of the entire array can substite the usage of this attribute. //! ```element_size_bytes``` | ```1```, ... | Same as above, multiplied by 8. //! ```ty``` | ```enum``` | Packing helper for primitive enums. //! ```endian``` | ```msb``` or ```lsb``` | Integer endianness. Applies to u16/i16 and larger types. //! //! # More examples //! //! ## Mixed endian integers //! //! ```rust //! extern crate packed_struct; //! #[macro_use] extern crate packed_struct_codegen; //! //! use packed_struct::prelude::*; //! //! #[derive(PackedStruct)] //! #[packed_struct] //! pub struct EndianExample { //! #[packed_field(endian="lsb")] //! int1: u16, //! #[packed_field(endian="msb")] //! int2: i32 //! } //! //! fn main() { //! let example = EndianExample { //! int1: 0xBBAA, //! int2: 0x11223344 //! }; //! //! let packed = example.pack(); //! assert_eq!([0xAA, 0xBB, 0x11, 0x22, 0x33, 0x44], packed); //! } //! ``` //! //! ## 24 bit LSB integers //! //! ```rust //! extern crate packed_struct; //! #[macro_use] extern crate packed_struct_codegen; //! //! use packed_struct::prelude::*; //! //! #[derive(PackedStruct)] //! #[packed_struct(endian="lsb")] //! pub struct LsbIntExample { //! int1: Integer<u32, ::packed_bits::Bits24>, //! } //! //! fn main() { //! let example = LsbIntExample { //! int1: 0xCCBBAA.into() //! }; //! //! let packed = example.pack(); //! assert_eq!([0xAA, 0xBB, 0xCC], packed); //! } //! ``` //! //! ## Nested packed types within arrays //! //! ```rust //! extern crate packed_struct; //! #[macro_use] extern crate packed_struct_codegen; //! //! use packed_struct::prelude::*; //! //! #[derive(PackedStruct, Debug, PartialEq)] //! #[packed_struct(bit_numbering="msb0")] //! pub struct TinyFlags { //! #[packed_field(bits="4..")] //! flag1: bool, //! val1: Integer<u8, ::packed_bits::Bits2>, //! flag2: bool //! } //! //! #[derive(PackedStruct, Debug, PartialEq)] //! #[packed_struct] //! pub struct Settings { //! #[packed_field(element_size_bits="4")] //! values: [TinyFlags; 4] //! } //! //! fn main() { //! let example = Settings { //! values: [ //! TinyFlags { flag1: true, val1: 1.into(), flag2: false }, //! TinyFlags { flag1: true, val1: 2.into(), flag2: true }, //! TinyFlags { flag1: false, val1: 3.into(), flag2: false }, //! TinyFlags { flag1: true, val1: 0.into(), flag2: false }, //! ] //! }; //! //! let packed = example.pack(); //! let unpacked = Settings::unpack(&packed).unwrap(); //! //! assert_eq!(example, unpacked); //! } //! ``` #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(feature="core_collections", feature(alloc))] #![cfg_attr(feature="core_collections", feature(collections))] #[cfg(any(feature="core_collections"))] #[macro_use] extern crate alloc; #[cfg(any(feature="core_collections"))] #[macro_use] extern crate collections; extern crate serde; #[macro_use] extern crate serde_derive; mod internal_prelude; #[macro_use] mod packing; mod primitive_enum; pub use primitive_enum::*; #[cfg(any(feature="core_collections", feature="std"))] pub mod debug_fmt; mod types_array; mod types_basic; mod types_bits; mod types_num; /// Implementations and wrappers for various packing types. pub mod types { pub use super::types_basic::*; /// Types that specify the exact number of bits a packed integer should occupy. pub mod bits { pub use super::super::types_bits::*; } pub use super::types_num::*; pub use super::types_array::*; } pub use self::packing::*; pub mod prelude { //! Re-exports the most useful traits and types. Meant to be glob imported. pub use PackedStruct; pub use PackedStructSlice; pub use PackingError; pub use PrimitiveEnum; pub use types::*; pub use types::bits as packed_bits; }
true
62b75effbc27be82ea257915ae1a46cf7981b5e4
Rust
Ralith/hecs
/tests/tests.rs
UTF-8
26,726
2.734375
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#![allow(deprecated)] // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. use std::borrow::Cow; use hecs::*; #[test] fn random_access() { let mut world = World::new(); let e = world.spawn(("abc", 123)); let f = world.spawn(("def", 456, true)); assert_eq!(*world.get::<&&str>(e).unwrap(), "abc"); assert_eq!(*world.get::<&i32>(e).unwrap(), 123); assert_eq!(*world.get::<&&str>(f).unwrap(), "def"); assert_eq!(*world.get::<&i32>(f).unwrap(), 456); *world.get::<&mut i32>(f).unwrap() = 42; assert_eq!(*world.get::<&i32>(f).unwrap(), 42); } #[test] fn despawn() { let mut world = World::new(); let e = world.spawn(("abc", 123)); let f = world.spawn(("def", 456)); assert_eq!(world.query::<()>().iter().count(), 2); world.despawn(e).unwrap(); assert_eq!(world.query::<()>().iter().count(), 1); assert!(world.get::<&&str>(e).is_err()); assert!(world.get::<&i32>(e).is_err()); assert_eq!(*world.get::<&&str>(f).unwrap(), "def"); assert_eq!(*world.get::<&i32>(f).unwrap(), 456); } #[test] fn query_all() { let mut world = World::new(); let e = world.spawn(("abc", 123)); let f = world.spawn(("def", 456)); let ents = world .query::<(&i32, &&str)>() .iter() .map(|(e, (&i, &s))| (e, i, s)) .collect::<Vec<_>>(); assert_eq!(ents.len(), 2); assert!(ents.contains(&(e, 123, "abc"))); assert!(ents.contains(&(f, 456, "def"))); let ents = world.query::<()>().iter().collect::<Vec<_>>(); assert_eq!(ents.len(), 2); assert!(ents.contains(&(e, ()))); assert!(ents.contains(&(f, ()))); } #[test] #[cfg(feature = "macros")] fn derived_query() { #[derive(Query, Debug, PartialEq)] struct Foo<'a> { x: &'a i32, y: &'a mut bool, } let mut world = World::new(); let e = world.spawn((42, false)); assert_eq!( world.query_one_mut::<Foo>(e).unwrap(), Foo { x: &42, y: &mut false } ); } #[test] #[cfg(feature = "macros")] fn derived_bundle_clone() { #[derive(Bundle, DynamicBundleClone)] struct Foo<T: Clone + Component> { x: i32, y: bool, z: T, } #[derive(PartialEq, Debug, Query)] struct FooQuery<'a> { x: &'a i32, y: &'a bool, z: &'a String, } let mut world = World::new(); let mut builder = EntityBuilderClone::new(); builder.add_bundle(Foo { x: 42, y: false, z: String::from("Foo"), }); let entity = builder.build(); let e = world.spawn(&entity); assert_eq!( world.query_one_mut::<FooQuery>(e).unwrap(), FooQuery { x: &42, y: &false, z: &String::from("Foo"), } ); } #[test] fn query_single_component() { let mut world = World::new(); let e = world.spawn(("abc", 123)); let f = world.spawn(("def", 456, true)); let ents = world .query::<&i32>() .iter() .map(|(e, &i)| (e, i)) .collect::<Vec<_>>(); assert_eq!(ents.len(), 2); assert!(ents.contains(&(e, 123))); assert!(ents.contains(&(f, 456))); } #[test] fn query_missing_component() { let mut world = World::new(); world.spawn(("abc", 123)); world.spawn(("def", 456)); assert!(world.query::<(&bool, &i32)>().iter().next().is_none()); } #[test] fn query_sparse_component() { let mut world = World::new(); world.spawn(("abc", 123)); let f = world.spawn(("def", 456, true)); let ents = world .query::<&bool>() .iter() .map(|(e, &b)| (e, b)) .collect::<Vec<_>>(); assert_eq!(ents, &[(f, true)]); } #[test] fn query_optional_component() { let mut world = World::new(); let e = world.spawn(("abc", 123)); let f = world.spawn(("def", 456, true)); let ents = world .query::<(Option<&bool>, &i32)>() .iter() .map(|(e, (b, &i))| (e, b.copied(), i)) .collect::<Vec<_>>(); assert_eq!(ents.len(), 2); assert!(ents.contains(&(e, None, 123))); assert!(ents.contains(&(f, Some(true), 456))); } #[test] fn prepare_query() { let mut world = World::new(); let e = world.spawn(("abc", 123)); let f = world.spawn(("def", 456)); let mut query = PreparedQuery::<(&i32, &&str)>::default(); let ents = query .query(&world) .iter() .map(|(e, (&i, &s))| (e, i, s)) .collect::<Vec<_>>(); assert_eq!(ents.len(), 2); assert!(ents.contains(&(e, 123, "abc"))); assert!(ents.contains(&(f, 456, "def"))); let ents = query .query_mut(&mut world) .map(|(e, (&i, &s))| (e, i, s)) .collect::<Vec<_>>(); assert_eq!(ents.len(), 2); assert!(ents.contains(&(e, 123, "abc"))); assert!(ents.contains(&(f, 456, "def"))); } #[test] fn invalidate_prepared_query() { let mut world = World::new(); let e = world.spawn(("abc", 123)); let f = world.spawn(("def", 456)); let mut query = PreparedQuery::<(&i32, &&str)>::default(); let ents = query .query(&world) .iter() .map(|(e, (&i, &s))| (e, i, s)) .collect::<Vec<_>>(); assert_eq!(ents.len(), 2); assert!(ents.contains(&(e, 123, "abc"))); assert!(ents.contains(&(f, 456, "def"))); world.spawn((true,)); let g = world.spawn(("ghi", 789)); let ents = query .query_mut(&mut world) .map(|(e, (&i, &s))| (e, i, s)) .collect::<Vec<_>>(); assert_eq!(ents.len(), 3); assert!(ents.contains(&(e, 123, "abc"))); assert!(ents.contains(&(f, 456, "def"))); assert!(ents.contains(&(g, 789, "ghi"))); } #[test] fn random_access_via_view() { let mut world = World::new(); let e = world.spawn(("abc", 123)); let f = world.spawn(("def",)); let mut query = PreparedQuery::<(&i32, &&str)>::default(); let mut query = query.query(&world); let mut view = query.view(); let (i, s) = view.get(e).unwrap(); assert_eq!(*i, 123); assert_eq!(*s, "abc"); assert!(view.get_mut(f).is_none()); } #[test] fn random_access_via_view_mut() { let mut world = World::new(); let e = world.spawn(("abc", 123)); let f = world.spawn(("def",)); let mut query = PreparedQuery::<(&i32, &&str)>::default(); let mut view = query.view_mut(&mut world); let (i, s) = view.get(e).unwrap(); assert_eq!(*i, 123); assert_eq!(*s, "abc"); assert!(view.get_mut(f).is_none()); } #[test] #[should_panic] fn simultaneous_access_must_be_non_overlapping() { let mut world = World::new(); let a = world.spawn((1,)); let b = world.spawn((2,)); let c = world.spawn((3,)); let d = world.spawn((4,)); let mut query = world.query_mut::<&mut i32>(); let mut view = query.view(); view.get_mut_n([a, d, c, b, a]); } #[test] fn build_entity() { let mut world = World::new(); let mut entity = EntityBuilder::new(); entity.add("abc"); entity.add(123); let e = world.spawn(entity.build()); entity.add("def"); entity.add([0u8; 1024]); entity.add(456); entity.add(789); let f = world.spawn(entity.build()); assert_eq!(*world.get::<&&str>(e).unwrap(), "abc"); assert_eq!(*world.get::<&i32>(e).unwrap(), 123); assert_eq!(*world.get::<&&str>(f).unwrap(), "def"); assert_eq!(*world.get::<&i32>(f).unwrap(), 789); } #[test] fn build_entity_clone() { let mut world = World::new(); let mut entity = EntityBuilderClone::new(); entity.add("def"); entity.add([0u8; 1024]); entity.add(456); entity.add(789); entity.add_bundle(("yup", 67_usize)); entity.add_bundle((5.0_f32, String::from("Foo"))); entity.add_bundle((7.0_f32, String::from("Bar"), 42_usize)); let entity = entity.build(); let e = world.spawn(&entity); let f = world.spawn(&entity); let g = world.spawn(&entity); world .insert_one(g, Cow::<'static, str>::from("after")) .unwrap(); for e in [e, f, g] { assert_eq!(*world.get::<&&str>(e).unwrap(), "yup"); assert_eq!(*world.get::<&i32>(e).unwrap(), 789); assert_eq!(*world.get::<&usize>(e).unwrap(), 42); assert_eq!(*world.get::<&f32>(e).unwrap(), 7.0); assert_eq!(*world.get::<&String>(e).unwrap(), "Bar"); } assert_eq!(*world.get::<&Cow<'static, str>>(g).unwrap(), "after"); } #[test] fn build_builder_clone() { let mut a = EntityBuilderClone::new(); a.add(String::from("abc")); a.add(123); let mut b = EntityBuilderClone::new(); b.add(String::from("def")); b.add_bundle(&a.build()); assert_eq!(b.get::<&String>(), Some(&String::from("abc"))); assert_eq!(b.get::<&i32>(), Some(&123)); } #[test] #[allow(clippy::redundant_clone)] fn cloned_builder() { let mut builder = EntityBuilderClone::new(); builder.add(String::from("abc")).add(123); let mut world = World::new(); let e = world.spawn(&builder.build().clone()); assert_eq!(*world.get::<&String>(e).unwrap(), "abc"); assert_eq!(*world.get::<&i32>(e).unwrap(), 123); } #[test] #[cfg(feature = "macros")] fn build_dynamic_bundle() { #[derive(Bundle, DynamicBundleClone)] struct Foo { x: i32, y: char, } let mut world = World::new(); let mut entity = EntityBuilderClone::new(); entity.add_bundle(Foo { x: 5, y: 'c' }); entity.add_bundle((String::from("Bar"), 6.0_f32)); entity.add('a'); let entity = entity.build(); let e = world.spawn(&entity); let f = world.spawn(&entity); let g = world.spawn(&entity); world .insert_one(g, Cow::<'static, str>::from("after")) .unwrap(); for e in [e, f, g] { assert_eq!(*world.get::<&i32>(e).unwrap(), 5); assert_eq!(*world.get::<&char>(e).unwrap(), 'a'); assert_eq!(*world.get::<&String>(e).unwrap(), "Bar"); assert_eq!(*world.get::<&f32>(e).unwrap(), 6.0); } assert_eq!(*world.get::<&Cow<'static, str>>(g).unwrap(), "after"); } #[test] fn access_builder_components() { let mut world = World::new(); let mut entity = EntityBuilder::new(); entity.add("abc"); entity.add(123); assert!(entity.has::<&str>()); assert!(entity.has::<i32>()); assert!(!entity.has::<usize>()); assert_eq!(*entity.get::<&&str>().unwrap(), "abc"); assert_eq!(*entity.get::<&i32>().unwrap(), 123); assert_eq!(entity.get::<&usize>(), None); *entity.get_mut::<&mut i32>().unwrap() = 456; assert_eq!(*entity.get::<&i32>().unwrap(), 456); let g = world.spawn(entity.build()); assert_eq!(*world.get::<&&str>(g).unwrap(), "abc"); assert_eq!(*world.get::<&i32>(g).unwrap(), 456); } #[test] fn build_entity_bundle() { let mut world = World::new(); let mut entity = EntityBuilder::new(); entity.add_bundle(("abc", 123)); let e = world.spawn(entity.build()); entity.add(456); entity.add_bundle(("def", [0u8; 1024], 789)); let f = world.spawn(entity.build()); assert_eq!(*world.get::<&&str>(e).unwrap(), "abc"); assert_eq!(*world.get::<&i32>(e).unwrap(), 123); assert_eq!(*world.get::<&&str>(f).unwrap(), "def"); assert_eq!(*world.get::<&i32>(f).unwrap(), 789); } #[test] fn dynamic_components() { let mut world = World::new(); let e = world.spawn((42,)); world.insert(e, (true, "abc")).unwrap(); assert_eq!( world .query::<(&i32, &bool)>() .iter() .map(|(e, (&i, &b))| (e, i, b)) .collect::<Vec<_>>(), &[(e, 42, true)] ); assert_eq!(world.remove_one::<i32>(e), Ok(42)); assert_eq!( world .query::<(&i32, &bool)>() .iter() .map(|(e, (&i, &b))| (e, i, b)) .collect::<Vec<_>>(), &[] ); assert_eq!( world .query::<(&bool, &&str)>() .iter() .map(|(e, (&b, &s))| (e, b, s)) .collect::<Vec<_>>(), &[(e, true, "abc")] ); } #[test] fn spawn_buffered_entity() { let mut world = World::new(); let mut buffer = CommandBuffer::new(); let ent = world.reserve_entity(); let ent1 = world.reserve_entity(); let ent2 = world.reserve_entity(); let ent3 = world.reserve_entity(); buffer.insert(ent, (1, true)); buffer.insert(ent1, (13, 7.11, "hecs")); buffer.insert(ent2, (17i8, false, 'o')); buffer.insert(ent3, (2u8, "qwe", 101.103, false)); buffer.run_on(&mut world); assert!(*world.get::<&bool>(ent).unwrap()); assert!(!*world.get::<&bool>(ent2).unwrap()); assert_eq!(*world.get::<&&str>(ent1).unwrap(), "hecs"); assert_eq!(*world.get::<&i32>(ent1).unwrap(), 13); assert_eq!(*world.get::<&u8>(ent3).unwrap(), 2); } #[test] fn despawn_buffered_entity() { let mut world = World::new(); let mut buffer = CommandBuffer::new(); let ent = world.spawn((1, true)); buffer.despawn(ent); buffer.run_on(&mut world); assert!(!world.contains(ent)); } #[test] fn remove_buffered_component() { let mut world = World::new(); let mut buffer = CommandBuffer::new(); let ent = world.spawn((7, true, "hecs")); buffer.remove::<(i32, &str)>(ent); buffer.run_on(&mut world); assert!(world.get::<&&str>(ent).is_err()); assert!(world.get::<&i32>(ent).is_err()); } #[test] #[should_panic(expected = "already borrowed")] fn illegal_borrow() { let mut world = World::new(); world.spawn(("abc", 123)); world.spawn(("def", 456)); world.query::<(&mut i32, &i32)>().iter(); } #[test] #[should_panic(expected = "already borrowed")] fn illegal_borrow_2() { let mut world = World::new(); world.spawn(("abc", 123)); world.spawn(("def", 456)); world.query::<(&mut i32, &mut i32)>().iter(); } #[test] #[should_panic(expected = "query violates a unique borrow")] fn illegal_query_mut_borrow() { let mut world = World::new(); world.spawn(("abc", 123)); world.spawn(("def", 456)); world.query_mut::<(&i32, &mut i32)>(); } #[test] #[should_panic(expected = "query violates a unique borrow")] fn illegal_query_one_borrow() { let mut world = World::new(); let entity = world.spawn(("abc", 123)); world.query_one::<(&mut i32, &i32)>(entity).unwrap(); } #[test] #[should_panic(expected = "query violates a unique borrow")] fn illegal_query_one_borrow_2() { let mut world = World::new(); let entity = world.spawn(("abc", 123)); world.query_one::<(&mut i32, &mut i32)>(entity).unwrap(); } #[test] #[should_panic(expected = "query violates a unique borrow")] fn illegal_query_one_mut_borrow() { let mut world = World::new(); let entity = world.spawn(("abc", 123)); world.query_one_mut::<(&mut i32, &i32)>(entity).unwrap(); } #[test] #[should_panic(expected = "query violates a unique borrow")] fn illegal_query_one_mut_borrow_2() { let mut world = World::new(); let entity = world.spawn(("abc", 123)); world.query_one_mut::<(&mut i32, &mut i32)>(entity).unwrap(); } #[test] fn disjoint_queries() { let mut world = World::new(); world.spawn(("abc", true)); world.spawn(("def", 456)); let _a = world.query::<(&mut &str, &bool)>(); let _b = world.query::<(&mut &str, &i32)>(); } #[test] fn shared_borrow() { let mut world = World::new(); world.spawn(("abc", 123)); world.spawn(("def", 456)); world.query::<(&i32, &i32)>(); } #[test] #[should_panic(expected = "already borrowed")] fn illegal_random_access() { let mut world = World::new(); let e = world.spawn(("abc", 123)); let _borrow = world.get::<&mut i32>(e).unwrap(); world.get::<&i32>(e).unwrap(); } #[test] #[cfg(feature = "macros")] fn derived_bundle() { #[derive(Bundle)] struct Foo { x: i32, y: char, } let mut world = World::new(); let e = world.spawn(Foo { x: 42, y: 'a' }); assert_eq!(*world.get::<&i32>(e).unwrap(), 42); assert_eq!(*world.get::<&char>(e).unwrap(), 'a'); } #[test] #[cfg(feature = "macros")] #[cfg_attr( debug_assertions, should_panic( expected = "attempted to allocate entity with duplicate i32 components; each type must occur at most once!" ) )] #[cfg_attr( not(debug_assertions), should_panic( expected = "attempted to allocate entity with duplicate components; each type must occur at most once!" ) )] fn bad_bundle_derive() { #[derive(Bundle)] struct Foo { x: i32, y: i32, } let mut world = World::new(); world.spawn(Foo { x: 42, y: 42 }); } #[test] #[cfg_attr(miri, ignore)] fn spawn_many() { let mut world = World::new(); const N: usize = 100_000; for _ in 0..N { world.spawn((42u128,)); } assert_eq!(world.iter().count(), N); } #[test] fn clear() { let mut world = World::new(); world.spawn(("abc", 123)); world.spawn(("def", 456, true)); world.clear(); assert_eq!(world.iter().count(), 0); } #[test] fn remove_missing() { let mut world = World::new(); let e = world.spawn(("abc", 123)); assert!(world.remove_one::<bool>(e).is_err()); } #[test] fn exchange_components() { let mut world = World::new(); let entity = world.spawn(("abc".to_owned(), 123)); assert!(world.get::<&String>(entity).is_ok()); assert!(world.get::<&i32>(entity).is_ok()); assert!(world.get::<&bool>(entity).is_err()); world.exchange_one::<String, _>(entity, true).unwrap(); assert!(world.get::<&String>(entity).is_err()); assert!(world.get::<&i32>(entity).is_ok()); assert!(world.get::<&bool>(entity).is_ok()); } #[test] fn reserve() { let mut world = World::new(); let a = world.reserve_entity(); let b = world.reserve_entity(); assert_eq!(world.query::<()>().iter().count(), 0); world.flush(); let entities = world .query::<()>() .iter() .map(|(e, ())| e) .collect::<Vec<_>>(); assert_eq!(entities.len(), 2); assert!(entities.contains(&a)); assert!(entities.contains(&b)); } #[test] fn query_batched() { let mut world = World::new(); let a = world.spawn(()); let b = world.spawn(()); let c = world.spawn((42,)); assert_eq!(world.query::<()>().iter_batched(1).count(), 3); assert_eq!(world.query::<()>().iter_batched(2).count(), 2); assert_eq!(world.query::<()>().iter_batched(2).flatten().count(), 3); // different archetypes are always in different batches assert_eq!(world.query::<()>().iter_batched(3).count(), 2); assert_eq!(world.query::<()>().iter_batched(3).flatten().count(), 3); assert_eq!(world.query::<()>().iter_batched(4).count(), 2); let entities = world .query::<()>() .iter_batched(1) .flatten() .map(|(e, ())| e) .collect::<Vec<_>>(); dbg!(&entities); assert_eq!(entities.len(), 3); assert!(entities.contains(&a)); assert!(entities.contains(&b)); assert!(entities.contains(&c)); } #[test] fn query_mut_batched() { let mut world = World::new(); let a = world.spawn(()); let b = world.spawn(()); let c = world.spawn((42,)); assert_eq!(world.query_mut::<()>().into_iter_batched(1).count(), 3); assert_eq!(world.query_mut::<()>().into_iter_batched(2).count(), 2); assert_eq!( world .query_mut::<()>() .into_iter_batched(2) .flatten() .count(), 3 ); // different archetypes are always in different batches assert_eq!(world.query_mut::<()>().into_iter_batched(3).count(), 2); assert_eq!( world .query_mut::<()>() .into_iter_batched(3) .flatten() .count(), 3 ); assert_eq!(world.query_mut::<()>().into_iter_batched(4).count(), 2); let entities = world .query_mut::<()>() .into_iter_batched(1) .flatten() .map(|(e, ())| e) .collect::<Vec<_>>(); dbg!(&entities); assert_eq!(entities.len(), 3); assert!(entities.contains(&a)); assert!(entities.contains(&b)); assert!(entities.contains(&c)); } #[test] fn spawn_batch() { let mut world = World::new(); world.spawn_batch((0..10).map(|x| (x, "abc"))); let entity_count = world.query::<&i32>().iter().count(); assert_eq!(entity_count, 10); } #[test] fn query_one() { let mut world = World::new(); let a = world.spawn(("abc", 123)); let b = world.spawn(("def", 456)); let c = world.spawn(("ghi", 789, true)); assert_eq!(world.query_one::<&i32>(a).unwrap().get(), Some(&123)); assert_eq!(world.query_one::<&i32>(b).unwrap().get(), Some(&456)); assert!(world.query_one::<(&i32, &bool)>(a).unwrap().get().is_none()); assert_eq!( world.query_one::<(&i32, &bool)>(c).unwrap().get(), Some((&789, &true)) ); world.despawn(a).unwrap(); assert!(world.query_one::<&i32>(a).is_err()); } #[test] #[cfg_attr( debug_assertions, should_panic( expected = "attempted to allocate entity with duplicate f32 components; each type must occur at most once!" ) )] #[cfg_attr( not(debug_assertions), should_panic( expected = "attempted to allocate entity with duplicate components; each type must occur at most once!" ) )] fn duplicate_components_panic() { let mut world = World::new(); world.reserve::<(f32, i64, f32)>(1); } #[test] fn spawn_column_batch() { let mut world = World::new(); let mut batch_ty = ColumnBatchType::new(); batch_ty.add::<i32>().add::<bool>(); // Unique archetype let b; { let mut batch = batch_ty.clone().into_batch(2); let mut bs = batch.writer::<bool>().unwrap(); bs.push(true).unwrap(); bs.push(false).unwrap(); let mut is = batch.writer::<i32>().unwrap(); is.push(42).unwrap(); is.push(43).unwrap(); let entities = world .spawn_column_batch(batch.build().unwrap()) .collect::<Vec<_>>(); assert_eq!(entities.len(), 2); assert_eq!( world.query_one_mut::<(&i32, &bool)>(entities[0]).unwrap(), (&42, &true) ); assert_eq!( world.query_one_mut::<(&i32, &bool)>(entities[1]).unwrap(), (&43, &false) ); world.despawn(entities[0]).unwrap(); b = entities[1]; } // Duplicate archetype { let mut batch = batch_ty.clone().into_batch(2); let mut bs = batch.writer::<bool>().unwrap(); bs.push(true).unwrap(); bs.push(false).unwrap(); let mut is = batch.writer::<i32>().unwrap(); is.push(44).unwrap(); is.push(45).unwrap(); let entities = world .spawn_column_batch(batch.build().unwrap()) .collect::<Vec<_>>(); assert_eq!(entities.len(), 2); assert_eq!(*world.get::<&i32>(b).unwrap(), 43); assert_eq!(*world.get::<&i32>(entities[0]).unwrap(), 44); assert_eq!(*world.get::<&i32>(entities[1]).unwrap(), 45); } } #[test] fn columnar_access() { let mut world = World::new(); let e = world.spawn(("abc", 123)); let f = world.spawn(("def", 456, true)); let g = world.spawn(("ghi", 789, false)); let mut archetypes = world.archetypes(); let _empty = archetypes.next().unwrap(); let a = archetypes.next().unwrap(); assert_eq!(a.ids(), &[e.id()]); assert_eq!(*a.get::<&i32>().unwrap(), [123]); assert!(a.get::<&bool>().is_none()); let b = archetypes.next().unwrap(); assert_eq!(b.ids(), &[f.id(), g.id()]); assert_eq!(*b.get::<&i32>().unwrap(), [456, 789]); } #[test] fn empty_entity_ref() { let mut world = World::new(); let e = world.spawn(()); let r = world.entity(e).unwrap(); assert_eq!(r.entity(), e); } #[test] fn query_or() { let mut world = World::new(); let e = world.spawn(("abc", 123)); let _ = world.spawn(("def",)); let f = world.spawn(("ghi", true)); let g = world.spawn(("jkl", 456, false)); let results = world .query::<(&&str, Or<&i32, &bool>)>() .iter() .map(|(handle, (&s, value))| (handle, s, value.cloned())) .collect::<Vec<_>>(); assert_eq!(results.len(), 3); assert!(results.contains(&(e, "abc", Or::Left(123)))); assert!(results.contains(&(f, "ghi", Or::Right(true)))); assert!(results.contains(&(g, "jkl", Or::Both(456, false)))); } #[test] fn len() { let mut world = World::new(); let ent = world.spawn(()); world.spawn(()); world.spawn(()); assert_eq!(world.len(), 3); world.despawn(ent).unwrap(); assert_eq!(world.len(), 2); world.clear(); assert_eq!(world.len(), 0); } #[test] fn take() { let mut world_a = World::new(); let e = world_a.spawn(("abc".to_string(), 42)); let f = world_a.spawn(("def".to_string(), 17)); let mut world_b = World::new(); let e2 = world_b.spawn(world_a.take(e).unwrap()); assert!(!world_a.contains(e)); assert_eq!(*world_b.get::<&String>(e2).unwrap(), "abc"); assert_eq!(*world_b.get::<&i32>(e2).unwrap(), 42); assert_eq!(*world_a.get::<&String>(f).unwrap(), "def"); assert_eq!(*world_a.get::<&i32>(f).unwrap(), 17); world_b.take(e2).unwrap(); assert!(!world_b.contains(e2)); } #[test] fn empty_archetype_conflict() { let mut world = World::new(); let _ = world.spawn((42, true)); let _ = world.spawn((17, "abc")); let e = world.spawn((12, false, "def")); world.despawn(e).unwrap(); for _ in world.query::<(&mut i32, &&str)>().iter() { for _ in world.query::<(&mut i32, &bool)>().iter() {} } } #[test] fn component_ref_map() { struct TestComponent { id: i32, } let mut world = World::new(); let e = world.spawn((TestComponent { id: 21 },)); let e_ref = world.entity(e).unwrap(); { let comp = e_ref.get::<&'_ TestComponent>().unwrap(); // Test that no unbalanced releases occur when cloning refs. let _comp2 = comp.clone(); let id = Ref::map(comp, |c| &c.id); assert_eq!(*id, 21); } { let comp = e_ref.get::<&'_ mut TestComponent>().unwrap(); let mut id = RefMut::map(comp, |c| &mut c.id); *id = 31; } { let comp = e_ref.get::<&'_ TestComponent>().unwrap(); let id = Ref::map(comp, |c| &c.id); assert_eq!(*id, 31); } }
true
5fdaa3c9a6125239a643fec746723428d05d3df8
Rust
creativcoder/bastion
/src/bastion/src/dispatcher.rs
UTF-8
23,488
3.25
3
[ "MIT", "Apache-2.0" ]
permissive
//! //! Special module that allows users to interact and communicate with a //! group of actors through the dispatchers that holds information about //! actors grouped together. use crate::child_ref::ChildRef; use crate::envelope::SignedMessage; use anyhow::Result as AnyResult; use lever::prelude::*; use std::fmt::{self, Debug}; use std::hash::{Hash, Hasher}; use std::sync::{ atomic::{AtomicU64, Ordering}, Arc, }; use tracing::{trace, warn}; /// Type alias for the concurrency hashmap. Each key-value pair stores /// the Bastion identifier as the key and the module name as the value. pub type DispatcherMap = LOTable<ChildRef, String>; #[derive(Debug, Clone)] /// Defines types of the notifications handled by the dispatcher /// when the group of actors is changing. pub enum NotificationType { /// Represents a notification when a new actor wants to /// join to the existing group of actors. Register, /// Represents a notification when the existing actor /// was stopped, killed, suspended or finished an execution. Remove, } #[derive(Debug, Clone)] /// Defines types of the notifications handled by the dispatcher /// when the group of actors is changing. /// /// If the message can't be delivered to the declared group, then /// the message will be marked as the "dead letter". pub enum BroadcastTarget { /// Send the broadcasted message to everyone in the system. All, /// Send the broadcasted message to each actor in group. Group(String), } #[derive(Debug, Clone, Eq, PartialEq)] /// Defines the type of the dispatcher. /// /// The default type is `Anonymous`. pub enum DispatcherType { /// The default kind of the dispatcher which is using for /// handling all actors in the cluster. Can be more than /// one instance of this type. Anonymous, /// The dispatcher with a unique name which will be using /// for updating and notifying actors in the same group /// base on the desired strategy. The logic handling broadcasted /// messages and their distribution across the group depends on /// the dispatcher's handler. Named(String), } /// The default handler, which does round-robin. pub type DefaultDispatcherHandler = RoundRobinHandler; /// Dispatcher that will do simple round-robin distribution #[derive(Default, Debug)] pub struct RoundRobinHandler { index: AtomicU64, } impl DispatcherHandler for RoundRobinHandler { // Will left this implementation as empty. fn notify( &self, _from_child: &ChildRef, _entries: &DispatcherMap, _notification_type: NotificationType, ) { } // Each child in turn will receive a message. fn broadcast_message(&self, entries: &DispatcherMap, message: &Arc<SignedMessage>) { if entries.len() == 0 { return; } let current_index = self.index.load(Ordering::SeqCst) % entries.len() as u64; let mut skipped = 0; for pair in entries.iter() { if skipped != current_index { skipped += 1; continue; } let entry = pair.0; entry.tell_anonymously(message.clone()).unwrap(); break; } self.index.store(current_index + 1, Ordering::SeqCst); } } /// Generic trait which any custom dispatcher handler must implement for /// the further usage by the `Dispatcher` instances. pub trait DispatcherHandler { /// Sends the notification of the certain type to each actor in group. fn notify( &self, from_child: &ChildRef, entries: &DispatcherMap, notification_type: NotificationType, ); /// Broadcasts the message to actors in according to the implemented behaviour. fn broadcast_message(&self, entries: &DispatcherMap, message: &Arc<SignedMessage>); } /// A generic implementation of the Bastion dispatcher /// /// The main idea of the dispatcher is to provide an alternative way to /// communicate between a group of actors. For example, dispatcher can /// be used when a developer wants to send a specific message or share a /// local state between the specific group of registered actors with /// the usage of a custom dispatcher. pub struct Dispatcher { /// Defines the type of the dispatcher. dispatcher_type: DispatcherType, /// The handler used for a notification or a message. handler: Box<dyn DispatcherHandler + Send + Sync + 'static>, /// Special field that stores information about all /// registered actors in the group. actors: DispatcherMap, } impl Dispatcher { /// Returns the type of the dispatcher. pub fn dispatcher_type(&self) -> DispatcherType { self.dispatcher_type.clone() } /// Returns the used handler by the dispatcher. pub fn handler(&self) -> &(dyn DispatcherHandler + Send + Sync + 'static) { &*self.handler } /// Sets the dispatcher type. pub fn with_dispatcher_type(mut self, dispatcher_type: DispatcherType) -> Self { trace!("Setting dispatcher the {:?} type.", dispatcher_type); self.dispatcher_type = dispatcher_type; self } /// Creates a dispatcher with a specific dispatcher type. pub fn with_type(dispatcher_type: DispatcherType) -> Self { trace!( "Instanciating a dispatcher with type {:?}.", dispatcher_type ); Self { dispatcher_type, handler: Box::new(DefaultDispatcherHandler::default()), actors: Default::default(), } } /// Sets the handler for the dispatcher. pub fn with_handler( mut self, handler: Box<dyn DispatcherHandler + Send + Sync + 'static>, ) -> Self { trace!( "Setting handler for the {:?} dispatcher.", self.dispatcher_type ); self.handler = handler; self } /// Appends the information about actor to the dispatcher. pub(crate) fn register(&self, key: &ChildRef, module_name: String) -> AnyResult<()> { self.actors.insert(key.to_owned(), module_name)?; self.handler .notify(key, &self.actors, NotificationType::Register); Ok(()) } /// Removes and then returns the record from the registry by the given key. /// Returns `None` when the record wasn't found by the given key. pub(crate) fn remove(&self, key: &ChildRef) { if self.actors.remove(key).is_ok() { self.handler .notify(key, &self.actors, NotificationType::Remove); } } /// Forwards the message to the handler for processing. pub fn notify(&self, from_child: &ChildRef, notification_type: NotificationType) { self.handler .notify(from_child, &self.actors, notification_type) } /// Sends the message to the group of actors. /// The logic of who and how should receive the message relies onto /// the handler implementation. pub fn broadcast_message(&self, message: &Arc<SignedMessage>) { self.handler.broadcast_message(&self.actors, &message); } } impl Debug for Dispatcher { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "Dispatcher(type: {:?}, actors: {:?})", self.dispatcher_type, self.actors.len() ) } } impl DispatcherType { pub(crate) fn name(&self) -> String { match self { DispatcherType::Anonymous => String::from("__Anonymous__"), DispatcherType::Named(value) => value.to_owned(), } } } impl Default for Dispatcher { fn default() -> Self { Dispatcher { dispatcher_type: DispatcherType::default(), handler: Box::new(DefaultDispatcherHandler::default()), actors: LOTable::new(), } } } impl Default for DispatcherType { fn default() -> Self { DispatcherType::Anonymous } } #[allow(clippy::derive_hash_xor_eq)] impl Hash for DispatcherType { fn hash<H: Hasher>(&self, state: &mut H) { self.name().hash(state); } } impl Into<DispatcherType> for String { fn into(self) -> DispatcherType { match self == DispatcherType::Anonymous.name() { true => DispatcherType::Anonymous, false => DispatcherType::Named(self), } } } #[derive(Debug)] /// The global dispatcher of bastion the cluster. /// /// The main purpose of this dispatcher is be a point through /// developers can communicate with actors through group names. pub(crate) struct GlobalDispatcher { /// Storage for all registered group of actors. pub dispatchers: LOTable<DispatcherType, Arc<Box<Dispatcher>>>, } impl GlobalDispatcher { /// Creates a new instance of the global registry. pub(crate) fn new() -> Self { GlobalDispatcher { dispatchers: LOTable::new(), } } /// Appends the information about actor to the dispatcher. pub(crate) fn register( &self, dispatchers: &[DispatcherType], child_ref: &ChildRef, module_name: String, ) -> AnyResult<()> { dispatchers .iter() .filter(|key| self.dispatchers.contains_key(*key)) .map(|key| { if let Some(dispatcher) = self.dispatchers.get(key) { dispatcher.register(child_ref, module_name.clone()) } else { Ok(()) } }) .collect::<AnyResult<Vec<_>>>()?; Ok(()) } /// Removes and then returns the record from the registry by the given key. /// Returns `None` when the record wasn't found by the given key. pub(crate) fn remove(&self, dispatchers: &[DispatcherType], child_ref: &ChildRef) { dispatchers .iter() .filter(|key| self.dispatchers.contains_key(*key)) .for_each(|key| { if let Some(dispatcher) = self.dispatchers.get(key) { dispatcher.remove(child_ref) } }) } /// Passes the notification from the actor to everyone that registered in the same /// groups as the caller. pub(crate) fn notify( &self, from_actor: &ChildRef, dispatchers: &[DispatcherType], notification_type: NotificationType, ) { self.dispatchers .iter() .filter(|pair| dispatchers.contains(&pair.0)) .for_each(|pair| { let dispatcher = pair.1; dispatcher.notify(from_actor, notification_type.clone()) }) } /// Broadcasts the given message in according with the specified target. pub(crate) fn broadcast_message(&self, target: BroadcastTarget, message: &Arc<SignedMessage>) { let mut acked_dispatchers: Vec<DispatcherType> = Vec::new(); match target { BroadcastTarget::All => self .dispatchers .iter() .map(|pair| pair.0.name().into()) .for_each(|group_name| acked_dispatchers.push(group_name)), BroadcastTarget::Group(name) => { let target_dispatcher = name.into(); acked_dispatchers.push(target_dispatcher); } } for dispatcher_type in acked_dispatchers { match self.dispatchers.get(&dispatcher_type) { Some(dispatcher) => { dispatcher.broadcast_message(&message.clone()); } // TODO: Put the message into the dead queue None => { let name = dispatcher_type.name(); warn!( "The message can't be delivered to the group with the '{}' name.", name ); } } } } /// Adds dispatcher to the global registry. pub(crate) fn register_dispatcher(&self, dispatcher: &Arc<Box<Dispatcher>>) -> AnyResult<()> { let dispatcher_type = dispatcher.dispatcher_type(); let is_registered = self.dispatchers.contains_key(&dispatcher_type); if is_registered && dispatcher_type != DispatcherType::Anonymous { warn!( "The dispatcher with the '{:?}' name already registered in the cluster.", dispatcher_type ); return Ok(()); } let instance = dispatcher.clone(); self.dispatchers.insert(dispatcher_type, instance)?; Ok(()) } /// Removes dispatcher from the global registry. pub(crate) fn remove_dispatcher(&self, dispatcher: &Arc<Box<Dispatcher>>) -> AnyResult<()> { self.dispatchers.remove(&dispatcher.dispatcher_type())?; Ok(()) } } #[cfg(test)] mod tests { use crate::child_ref::ChildRef; use crate::context::BastionId; use crate::dispatcher::*; use crate::envelope::{RefAddr, SignedMessage}; use crate::message::Msg; use crate::path::BastionPath; use futures::channel::mpsc; use std::sync::{Arc, Mutex}; #[derive(Clone)] struct CustomHandler { called: Arc<Mutex<bool>>, } // Here we actually want both // the locking mechanism and // the bool value #[allow(clippy::mutex_atomic)] impl CustomHandler { pub fn new(value: bool) -> Self { CustomHandler { called: Arc::new(Mutex::new(value)), } } pub fn was_called(&self) -> bool { *self.called.clone().lock().unwrap() } } impl DispatcherHandler for CustomHandler { fn notify( &self, _from_child: &ChildRef, _entries: &DispatcherMap, _notification_type: NotificationType, ) { let handler_field_ref = self.called.clone(); let mut data = handler_field_ref.lock().unwrap(); *data = true; } fn broadcast_message(&self, _entries: &DispatcherMap, _message: &Arc<SignedMessage>) { let handler_field_ref = self.called.clone(); let mut data = handler_field_ref.lock().unwrap(); *data = true; } } #[test] fn test_get_dispatcher_type_as_anonymous() { let instance = Dispatcher::default(); assert_eq!(instance.dispatcher_type(), DispatcherType::Anonymous); } #[test] fn test_get_dispatcher_type_as_named() { let name = "test_group".to_string(); let dispatcher_type = DispatcherType::Named(name); let instance = Dispatcher::with_type(dispatcher_type.clone()); assert_eq!(instance.dispatcher_type(), dispatcher_type); } #[test] fn test_local_dispatcher_append_child_ref() { let instance = Dispatcher::default(); let bastion_id = BastionId::new(); let (sender, _) = mpsc::unbounded(); let path = Arc::new(BastionPath::root()); let name = "test_name".to_string(); let child_ref = ChildRef::new(bastion_id, sender, name, path); assert_eq!(instance.actors.contains_key(&child_ref), false); instance .register(&child_ref, "my::test::module".to_string()) .unwrap(); assert_eq!(instance.actors.contains_key(&child_ref), true); } #[test] fn test_dispatcher_remove_child_ref() { let instance = Dispatcher::default(); let bastion_id = BastionId::new(); let (sender, _) = mpsc::unbounded(); let path = Arc::new(BastionPath::root()); let name = "test_name".to_string(); let child_ref = ChildRef::new(bastion_id, sender, name, path); instance .register(&child_ref, "my::test::module".to_string()) .unwrap(); assert_eq!(instance.actors.contains_key(&child_ref), true); instance.remove(&child_ref); assert_eq!(instance.actors.contains_key(&child_ref), false); } #[test] fn test_local_dispatcher_notify() { let handler = Box::new(CustomHandler::new(false)); let instance = Dispatcher::default().with_handler(handler.clone()); let bastion_id = BastionId::new(); let (sender, _) = mpsc::unbounded(); let path = Arc::new(BastionPath::root()); let name = "test_name".to_string(); let child_ref = ChildRef::new(bastion_id, sender, name, path); instance.notify(&child_ref, NotificationType::Register); let handler_was_called = handler.was_called(); assert_eq!(handler_was_called, true); } #[test] fn test_local_dispatcher_broadcast_message() { let handler = Box::new(CustomHandler::new(false)); let instance = Dispatcher::default().with_handler(handler.clone()); let (sender, _) = mpsc::unbounded(); let path = Arc::new(BastionPath::root()); const DATA: &str = "A message containing data (ask)."; let message = Arc::new(SignedMessage::new( Msg::broadcast(DATA), RefAddr::new(path, sender), )); instance.broadcast_message(&message); let handler_was_called = handler.was_called(); assert_eq!(handler_was_called, true); } #[test] fn test_global_dispatcher_add_local_dispatcher() { let dispatcher_type = DispatcherType::Named("test".to_string()); let local_dispatcher = Arc::new(Box::new(Dispatcher::with_type(dispatcher_type.clone()))); let global_dispatcher = GlobalDispatcher::new(); assert_eq!( global_dispatcher.dispatchers.contains_key(&dispatcher_type), false ); global_dispatcher .register_dispatcher(&local_dispatcher) .unwrap(); assert_eq!( global_dispatcher.dispatchers.contains_key(&dispatcher_type), true ); } #[test] fn test_global_dispatcher_remove_local_dispatcher() { let dispatcher_type = DispatcherType::Named("test".to_string()); let local_dispatcher = Arc::new(Box::new(Dispatcher::with_type(dispatcher_type.clone()))); let global_dispatcher = GlobalDispatcher::new(); global_dispatcher .register_dispatcher(&local_dispatcher) .unwrap(); assert_eq!( global_dispatcher.dispatchers.contains_key(&dispatcher_type), true ); global_dispatcher .remove_dispatcher(&local_dispatcher) .unwrap(); assert_eq!( global_dispatcher.dispatchers.contains_key(&dispatcher_type), false ); } #[test] fn test_global_dispatcher_register_actor() { let bastion_id = BastionId::new(); let (sender, _) = mpsc::unbounded(); let path = Arc::new(BastionPath::root()); let name = "test_name".to_string(); let child_ref = ChildRef::new(bastion_id, sender, name, path); let dispatcher_type = DispatcherType::Named("test".to_string()); let local_dispatcher = Arc::new(Box::new(Dispatcher::with_type(dispatcher_type.clone()))); let actor_groups = vec![dispatcher_type]; let module_name = "my::test::module".to_string(); let global_dispatcher = GlobalDispatcher::new(); global_dispatcher .register_dispatcher(&local_dispatcher) .unwrap(); assert_eq!(local_dispatcher.actors.contains_key(&child_ref), false); global_dispatcher .register(&actor_groups, &child_ref, module_name) .unwrap(); assert_eq!(local_dispatcher.actors.contains_key(&child_ref), true); } #[test] fn test_global_dispatcher_remove_actor() { let bastion_id = BastionId::new(); let (sender, _) = mpsc::unbounded(); let path = Arc::new(BastionPath::root()); let name = "test_name".to_string(); let child_ref = ChildRef::new(bastion_id, sender, name, path); let dispatcher_type = DispatcherType::Named("test".to_string()); let local_dispatcher = Arc::new(Box::new(Dispatcher::with_type(dispatcher_type.clone()))); let actor_groups = vec![dispatcher_type]; let module_name = "my::test::module".to_string(); let global_dispatcher = GlobalDispatcher::new(); global_dispatcher .register_dispatcher(&local_dispatcher) .unwrap(); global_dispatcher .register(&actor_groups, &child_ref, module_name) .unwrap(); assert_eq!(local_dispatcher.actors.contains_key(&child_ref), true); global_dispatcher.remove(&actor_groups, &child_ref); assert_eq!(local_dispatcher.actors.contains_key(&child_ref), false); } #[test] fn test_global_dispatcher_notify() { let bastion_id = BastionId::new(); let (sender, _) = mpsc::unbounded(); let path = Arc::new(BastionPath::root()); let name = "test_name".to_string(); let child_ref = ChildRef::new(bastion_id, sender, name, path); let dispatcher_type = DispatcherType::Named("test".to_string()); let handler = Box::new(CustomHandler::new(false)); let local_dispatcher = Arc::new(Box::new( Dispatcher::with_type(dispatcher_type.clone()).with_handler(handler.clone()), )); let actor_groups = vec![dispatcher_type]; let module_name = "my::test::module".to_string(); let global_dispatcher = GlobalDispatcher::new(); global_dispatcher .register_dispatcher(&local_dispatcher) .unwrap(); global_dispatcher .register(&actor_groups, &child_ref, module_name) .unwrap(); global_dispatcher.notify(&child_ref, &actor_groups, NotificationType::Register); let handler_was_called = handler.was_called(); assert_eq!(handler_was_called, true); } #[test] fn test_global_dispatcher_broadcast_message() { let bastion_id = BastionId::new(); let (sender, _) = mpsc::unbounded(); let path = Arc::new(BastionPath::root()); let name = "test_name".to_string(); let child_ref = ChildRef::new(bastion_id, sender, name, path); let dispatcher_type = DispatcherType::Named("test".to_string()); let handler = Box::new(CustomHandler::new(false)); let local_dispatcher = Arc::new(Box::new( Dispatcher::with_type(dispatcher_type.clone()).with_handler(handler.clone()), )); let actor_groups = vec![dispatcher_type]; let module_name = "my::test::module".to_string(); let global_dispatcher = GlobalDispatcher::new(); global_dispatcher .register_dispatcher(&local_dispatcher) .unwrap(); global_dispatcher .register(&actor_groups, &child_ref, module_name) .unwrap(); let (sender, _) = mpsc::unbounded(); let path = Arc::new(BastionPath::root()); const DATA: &str = "A message containing data (ask)."; let message = Arc::new(SignedMessage::new( Msg::broadcast(DATA), RefAddr::new(path, sender), )); global_dispatcher.broadcast_message(BroadcastTarget::Group("".to_string()), &message); let handler_was_called = handler.was_called(); assert_eq!(handler_was_called, true); } }
true
be636b4f43552f990c45eee59757eba13085397f
Rust
CyberWolf37/bot
/src/utils/block.rs
UTF-8
7,026
2.9375
3
[]
no_license
use std::sync::Arc; use super::{BotUser, PipeBox, PipeStatus}; use log::{info, warn}; use crate::api::{button::*, card::*}; use crate::api::{ApiMessage, Message}; #[derive(Clone)] pub struct Block{ name: String, token: String, childs: Arc<Vec<(BotUser,usize)>>, pipe: Vec<Arc<dyn PipeBox + Send + Sync>>, } impl Default for Block { fn default() -> Self { Block{ name: String::from("Hello"), token: String::from(""), childs: Arc::new(Vec::new()), pipe: Vec::new(), } } } impl Block { // Init Block pub fn new(name: &str) -> Self { let mut block = Block::default(); block.set_name(name); block } // Rooting user pub fn root(&mut self ,user: &BotUser) { let find = self.find(user); match find { true => { self.consume(user) }, false => { (*Arc::make_mut(&mut self.childs)).push((user.clone(),0)); self.consume(user); } } } // Consume the PipeBox for the user fn consume(&mut self ,user: &BotUser) { let value = match (*Arc::make_mut(&mut self.childs)).iter_mut().enumerate().find(|x| {x.1.0 == *user}) { Some(x) => { match self.pipe[x.1.1].consume(user, &self.token) { PipeStatus::NEXT => { x.1.1 = x.1.1 + 1; if x.1.1 >= self.pipe.len() { Some(x.0) } else { match self.pipe[x.1.1].internal_state() { PipeStatus::NEXT => { self.consume(user); None } _ => { None } } } }, PipeStatus::REPLAY => { x.1.1 = 0; None }, PipeStatus::RESTART => { x.1.1 = 0; None }, } } None => { warn!("Don't match with any childs"); None } }; match value { Some(e) => { (*Arc::make_mut(&mut self.childs)).remove(e); }, None => {} } } // Setter pub fn set_name(&mut self, name: &str) -> &mut Self{ self.name = String::from(name); self } pub fn set_token(&mut self, token: &str) { self.token = String::from(token); } pub fn get_name(&self) -> &str { &self.name } pub fn get_pipe(&self) -> &[Arc<dyn PipeBox + Send + Sync>] { &self.pipe } pub fn cartBox<T: 'static + PipeBox + Send + Sync> (mut self, pipeBox: T) -> Self { self.pipe.push(Arc::new(pipeBox)); self } pub fn find(&self,user: &BotUser) -> bool { match self.childs.iter().find(|x| { x.0.get_sender() == user.get_sender() }) { Some(_) => { return true } None => { return false } } } pub fn find_mut(&mut self,user: &BotUser) -> Option<&mut (BotUser,usize)> { (*Arc::make_mut(&mut self.childs)).iter_mut().find(|x| { x.0.get_sender() == user.get_sender() }) } pub fn remove_child(&mut self,user: &BotUser) { let child = (*Arc::make_mut(&mut self.childs)).iter_mut().enumerate().find(|x| { x.1.0.get_sender() == user.get_sender() }); let child = match child { Some(e) => Some(e.0), None => None, }; match child { Some(e) => {(*Arc::make_mut(&mut self.childs)).remove(e);}, None => {}, } } } #[derive(Clone)] pub struct CartBox { function_controle: Arc<dyn Fn(&BotUser) -> Option<&BotUser> + Send + Sync>, internal_state: PipeStatus, text: Option<String>, button: Option<Vec<Button>>, cards: Option<Vec<Arc<dyn Card>>>, } impl PipeBox for CartBox{ fn consume(&self,message: &BotUser, token: &str) -> PipeStatus { info!("Consume in the block the pipebox"); match (self.function_controle)(message) { Some(e) => { self.build().send(e,token); PipeStatus::NEXT } None => { PipeStatus::REPLAY } } } fn internal_state(&self) -> &PipeStatus { &self.internal_state } } impl CartBox { pub fn new() -> Self { let function_controle: Arc<dyn Fn(&BotUser) -> Option<&BotUser> + Send + Sync> = Arc::new(|u| {Some(u)}); CartBox{ function_controle: function_controle, internal_state: PipeStatus::NEXT, text: None, button: None, cards: None, } } pub fn text(mut self,text: &str) -> Self { self.text = Some(String::from(text)); self } pub fn button_postback(mut self,button_text: &str ,button_payload: &str) -> Self { match &mut self.button { Some(e) => {e.push(Button::new_button_quick_pb(button_text, button_payload));}, None => { let mut buttons = Vec::new(); buttons.push(Button::new_button_quick_pb(button_text, button_payload)); self.button = Some(buttons); }, } self } pub fn card<T: 'static + Card>(mut self, card: T) -> Self { let card = Arc::new(card); match &mut self.cards { Some(e) => { e.push(card); } None => { self.cards = Some(vec![card]); } } self } pub fn with_func_ctrl(&mut self,func: Arc<dyn Fn(&BotUser) -> Option<&BotUser> + Send + Sync>){ self.function_controle = func; } pub fn internal_state(&mut self,state: PipeStatus) { self.internal_state = state; } fn build(&self) -> Box<dyn ApiMessage> { let text = &self.text; let button = &self.button; let cards = &self.cards; if text.is_some() && button.is_some() { Box::new(Message::new(Some(text.clone().unwrap()),Some(button.clone().unwrap()),None)) } else if text.is_some() && button.is_none() { Box::new(Message::new(Some(text.clone().unwrap()),None,None)) } else if cards.is_some() { Box::new(Message::new(None,None,cards.clone())) } else { Box::new(Message::new(Some(String::from("Basic Text")),None,None)) } } }
true
d10c61228684188671b40637d4a9e72db57ed195
Rust
omprakashsridharan/rust_learning
/src/bin/implementation.rs
UTF-8
215
3.234375
3
[]
no_license
struct GenericVal<T> { gen_val : T, } impl<T> GenericVal<T> { fn val(&self) -> &T{ &self.gen_val } } fn main(){ let y = GenericVal { gen_val: 25 }; println!("{}",y.val()); }
true
035dd9bfa05754efa49267378fc184f2893c8fda
Rust
asapostolov/seeds-authenticator
/src/utils/blockchain.rs
UTF-8
912
2.84375
3
[]
no_license
use actix_web::client::{Client}; use crate::utils::settings::Blockchain; use serde::{Deserialize, Serialize}; use std::str; #[derive(Serialize, Deserialize, Debug)] pub struct Account { account_name: String } pub async fn get_account(account_name: &String, settings: &Blockchain) -> Result<Account, &'static str> { let client = Client::default(); let response = client.post(format!("{}/v1/chain/get_account", &settings.host)) // <- Create request builder .send_body(format!("{{\"account_name\": \"{}\"}}", &account_name)) .await; match response { Ok(mut resp) => { let body = resp.body().await.unwrap(); let json: Result<Account, _> = serde_json::from_str(str::from_utf8(&body).unwrap()); match json { Ok(account) => { println!("{:?}", &account); Ok(account) }, Err(_) => { Err("Account not found") } } }, Err(_) => Err("Invalid response") } }
true
f1592f1f11596bd910fb2fe78083b741bb5b817a
Rust
mov-rax/rcas
/src/rcas_lib.rs
UTF-8
67,738
2.65625
3
[ "MIT" ]
permissive
use rust_decimal::*; use std::fmt; use crate::rcas_lib::SmartValue::Operator; use std::str::FromStr; use std::error; use std::ops::{Deref, MulAssign, DivAssign, AddAssign, SubAssign}; use crate::rcas_functions; use std::rc::Rc; use std::cell::RefCell; use std::time::Instant; use std::fmt::{Debug, Formatter}; use fxhash::FxHashMap; use crate::rcas_functions::{FunctionController, Function}; use crate::rcas_constants::ConstantController; use fltk::table::TableRowSelectMode::SelectMulti; pub mod matrix; pub mod number; use matrix::SmartMatrix; //constants const ADD:char = '+'; //addition const SUB:char = '-'; //subtraction const MUL:char = '*'; //multiplication const DIV:char = '/'; //division const MOD:char = '%'; //modulo const POW:char = '^'; //power const FAC:char = '!'; //factorial const PHD:char = '█'; //placeholder const FNC:char = 'ƒ'; //pre-defined (constant) function const FNV:char = '⭒'; //variable function const VAR:char = '⭑'; //variable const PAR:char = '⮂'; //parameters static SYM:&str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; //allowed symbols static NUM:&str = "1234567890."; //allowed numbers static OPR:&str = "+-*/"; //allowed operators //Errors #[derive(Debug, Clone, PartialEq)] struct ParenthesesError{ positive:bool, //too much or too little parentheses. true == too much, false == too little position:u32, } #[derive(Debug, Clone, PartialEq)] pub struct FormattingError{ pub position:u32 } #[derive(Debug, Clone, PartialEq)] struct GenericError; #[derive(Debug, Clone, PartialEq)] struct UnknownIdentifierError{ position:u32, identifier:String, } #[derive(Debug,Clone,PartialEq)] pub struct TypeMismatchError{ pub found_in: String, // name can be dynamic pub found_type: String, // type found can be dynamic pub required_type: &'static str, } #[derive(Debug,Clone,PartialEq)] pub struct NegativeNumberError; #[derive(Debug,Clone,PartialEq)] pub struct DivideByZeroError; #[derive(Debug,Clone,PartialEq)] pub struct IndexOutOfBoundsError{ pub found_index: isize, pub max_index: usize, } #[derive(Debug,Clone,PartialEq)] pub struct IncorrectNumberOfArgumentsError<'a>{ pub name: &'a str, pub found: usize, pub requires: usize, } #[derive(Debug,Clone,PartialEq)] pub struct OverflowError; #[derive(Debug,Clone,PartialEq)] pub struct DimensionMismatch{ pub name: String, pub found: (usize, usize), // row, col pub requires: (usize, usize), // row, col pub extra_info: Option<String> } #[derive(Debug,Clone,PartialEq)] pub struct TypeConversionError{ pub info: Option<String> } #[derive(Debug,Clone,PartialEq)] pub struct AnyError{ pub info: Option<String> } impl fmt::Display for AnyError{ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { return if let Some(info) = &self.info{ write!(f,"ERROR: {}", info) } else { write!(f,"ERROR") } } } impl fmt::Display for TypeConversionError{ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { if let Some(info) = &self.info{ return write!(f, "TYPE CONVERSION ERROR.\n{}\n", &info) } write!(f,"TYPE CONVERSION ERROR.\n") } } impl fmt::Display for DimensionMismatch{ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { if let Some(info) = &self.extra_info{ write!(f, "DIMENSION MISMATCH!\nMatrix {} index dimensions are {}x{}. Found {}x{} instead.\n {}", &self.name, self.requires.0, self.requires.1, self.found.0, self.found.1, info) } else { write!(f, "DIMENSION MISMATCH!\nMatrix {} index dimensions are {}x{}. Found {}x{} instead.", &self.name, self.requires.0, self.requires.1, self.found.0, self.found.1,) } } } impl fmt::Display for IndexOutOfBoundsError{ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "INDEX OUT OF BOUNDS!\nIndex {} is not within 1:{}", self.found_index, self.max_index) } } impl fmt::Display for OverflowError{ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "OVERFLOW ERROR.") } } impl<'a> fmt::Display for IncorrectNumberOfArgumentsError<'a>{ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f,"INCORRECT NUMBER OF ARGUMENTS IN FUNCTION '{}'.\nFOUND {} ARGUMENTS.\nREQUIRES {} ARGUMENTS.", self.name, self.found, self.requires) } } impl fmt::Display for TypeMismatchError{ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "TYPE MISMATCH ERROR.") } } impl fmt::Display for ParenthesesError{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "PARENTHESES ERROR AT {}", self.position) } } impl fmt::Display for FormattingError{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "FORMATTING ERROR AT {}", self.position) } } impl fmt::Display for GenericError{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "GENERIC ERROR") } } impl fmt::Display for UnknownIdentifierError{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "UNKNOWN IDENTIFIER {} AT {}",&self.identifier, self.position) } } impl fmt::Display for NegativeNumberError{ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "NEGATIVE NUMBER ERROR") } } impl fmt::Display for DivideByZeroError{ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "DIVIDE BY ZERO ERROR") } } impl error::Error for ParenthesesError{} impl error::Error for FormattingError{} impl error::Error for GenericError{} impl error::Error for UnknownIdentifierError{} impl error::Error for TypeMismatchError{} impl error::Error for NegativeNumberError{} impl error::Error for DivideByZeroError{} impl<'a> error::Error for IncorrectNumberOfArgumentsError<'a>{} impl error::Error for OverflowError{} impl error::Error for IndexOutOfBoundsError{} impl error::Error for DimensionMismatch{} impl error::Error for TypeConversionError{} impl error::Error for AnyError{} pub struct RCas{ // Environment that holds user-defined variables and functions. It is an FxHashMap instead of a HashMap for speed purposes. // The Environment is encapsulated in an Rc<RefCell<>> In order for it to freely and safely shared to other processes. environment: Rc<RefCell<FxHashMap<String, Vec<SmartValue>>>>, // The Function Controller is used for any pre-defined functions that are given for users. It is able to modify the RCas environment. function_controller: FunctionController, } impl RCas{ pub fn new() -> RCas{ let environment = Rc::from(RefCell::from(FxHashMap::default())); let function_controller = FunctionController::new(environment.clone()); RCas {environment, function_controller} } pub fn query(&mut self, input:&str) -> QueryResult { let time = Instant::now(); match self.parser(input) { Ok(mut parsed) => { Wrapper::recurse_print(&parsed, 0); let time = time.elapsed().as_micros(); let mut assignment = None; // used to check if there was an assignment let mut new_value = None; if let Some(value) = parsed.get(0){ if let SmartValue::Assign(id,index, value) = value{ if let Some(index) = index{ assignment = Some((id.clone(), Some(index.clone()))) } else { assignment = Some((id.clone(), None)); } new_value = Some(value.clone()); } } if let Some(value) = new_value{ parsed = value; } let mut wrapper = Wrapper::compose(parsed); //Wrapper::recurse_print(&wrapper.values, 0); wrapper.solve(self); //Wrapper::recurse_print(&wrapper.values, 0); let mut environment = self.environment.borrow_mut(); // sets ans // this looks really ugly, but it works for variable assignment. let result = if assignment == None{ if let Some(SmartValue::Cmd(_)) = wrapper.values.get(0){ // DO NOTHING. YOU DON'T WANT TO ADD COMMAND VALUES TO THE ENVIRONMENT. } else { environment.insert("ans".to_string(), wrapper.values.clone()); // sets ans } wrapper.to_result() } else { if let Some(values) = wrapper.values.get(0){ // Check to see if the value returned is an error. if let SmartValue::Error(err) = values{ return QueryResult::Error(err.clone()) } let (id, index) = assignment.unwrap(); if let Some(index) = index{ if let Some(mat) = environment.get_mut(id.as_str()){ if let SmartValue::Matrix(mat) = &mut mat[0]{ mat.set_from(&index, values.clone()); mat.set_id(id.clone()); // set the name of the matrix } } } else { environment.insert(id.clone(), wrapper.values.clone()); // adds the assignment to the environment.insert("ans".to_string(), wrapper.values.clone()); // adds to ans } return match values{ SmartValue::Number(number) => QueryResult::Assign(QueryAssign { id, data: DataType::Number(*number), }), SmartValue::Function(identifier) => QueryResult::Assign(QueryAssign { id: identifier.clone(), data: DataType::Function }), SmartValue::Parameters(_) => QueryResult::Assign(QueryAssign { id: "function".to_string(), data: DataType::Function }), SmartValue::Variable(identifier) => QueryResult::Assign(QueryAssign { id: identifier.clone(), data: DataType::Function }), SmartValue::Text(identifier) => QueryResult::Assign(QueryAssign { id: identifier.clone(), data: DataType::Function }), SmartValue::Range(bound1,step,bound2) => QueryResult::Assign(QueryAssign{ id, data: DataType::Function }), SmartValue::Matrix(_) => QueryResult::Assign(QueryAssign{ id, data: DataType::Matrix }), _ => QueryResult::Error("ASSIGNMENT NOT IMPLEMENTED".to_string()), } } wrapper.to_result() // done in case the result is empty. }; println!("PARSE TIME:\t {} µs", time); result }, Err(error) => { Self::error_handle(error) } } } fn error_handle(err: Box<dyn std::error::Error>) -> QueryResult{ println!("Parsing Error :("); let error = err.deref(); let mut info = String::new(); //time to try all types of errors :) if let Some(error) = error.downcast_ref::<ParenthesesError>(){ let add_or_remove = { // returns REMOVING or ADDING depending on whether it is suggested to add or remove a parentheses let mut option = "REMOVING"; if error.positive { option = "ADDING"; } option }; info = format!("PARENTHESES ERROR detected at character {}. Have you tried {} \ a parentheses?", &error.position, add_or_remove); } if let Some(error) = error.downcast_ref::<FormattingError>(){ info = format!("FORMATTING ERROR detected at character {}.", &error.position); } if let Some(_) = error.downcast_ref::<GenericError>(){ info = format!("GENERIC ERROR detected. Please report what was done for this \ to appear. Thanks!"); } if let Some(error) = error.downcast_ref::<UnknownIdentifierError>(){ info = format!("UNKNOWN IDENTIFIER detected at character {}. {} is NOT A VALID \ variable or function name.", &error.position, &error.identifier); } QueryResult::Error(info) } ///Checks to see if rules were correctly followed. Returns Result. fn parser(&mut self, input:&str) -> Result<Vec<SmartValue>, Box<dyn error::Error>>{ //ONE RULE MUST FOLLOWED, WHICH IS THAT EACH NTH IN THE LOOP CAN ONLY SEE //THE NTH IN FRONT OF IT. GOING BACK TO CHECK VALUES IS NOT ALLOWED. // [sin(1) cos(1) 1+1 3 1/3] // GETS THE INPUT let input = { // [[4 2 3] [4 3 2]] let mut flag = false; let mut count = 0; let mut dq = false; // double quotes let mut sq = false; // single quotes let mut sf = false; // space flag let mut scf = false; // semicolon flag let mut jsf = true; // (Matrix) just-started flag let tinput = input.chars().filter_map(|x|{ // UNICODE: 0022 -> " // UNICODE: 0027 -> ' ' if count < 0{ return None } if x == '\u{0022}' || x == '\u{0027}'{ flag = !flag; // flips flag } if x == '\u{0022}'{ dq = !dq; } if x == '\u{0027}'{ sq = !sq; } if x == ';'{ scf = true; } if count != 0 { // Deals with removing excess spaces from matrices if scf{ // if there was a semicolon if x == ' '{ return None } else if x == ';'{ return Some(x) } else { scf = false; //Some(x) } } if jsf && x == ' '{ // prevents , from being inserted before first element return None; } else { jsf = false; } if x == ' '{ return if sf { None // No more spaces } else { sf = true; Some(',') // Replace space with a comma } } else { sf = false; // Not a space anymore } } if x == '[' { count += 1; } else if x == ']' { count -= 1; } if flag || count != 0{ return Some(x) } if x != ' '{ return Some(x) } None }).collect::<String>(); let mut result = Err(FormattingError{position: tinput.len() as u32 }); // (A + B + C + (COUNT != 0))' = A'B'C'(COUNT == 0) if !flag && !dq && !sq && count == 0{ // if one of these flags are true, there there was either " ', ' ", present, or a missing closing quotation result = Ok(tinput); } result }; let input = match input{ Ok(val) => val, Err(err) => return Err(Box::from(err)) }; let mut environment = self.environment.borrow_mut(); // gets a mutable reference to the environment. let mut temp:Vec<SmartValue> = Vec::with_capacity(30); //temp value that will be returned let mut buf:Vec<char> = Vec::new(); //buffer for number building let mut counter = 0; //used to keep track of parentheses let mut number = false; //used to keep track of number building let mut position = 0; //used to keep track of error position let mut dec = false; //used to keep track of decimal usage let mut operator = false; //used to keep track of operator usage let mut paren_open = false; //used to keep track of a prior open let mut comma = false; //used to keep track of commas let mut string = false; // used to keep track of string-building let mut was_double = false; // used to know if a currently-building string was started with double or single quotes let mut beginning_index = 0; // used to keep track of the starting index, in case there is an assignment let mut parameters = Vec::new(); // holds identifiers of any parameters when a query is an assignment let mut was_matrix = false; // used to keep track if a matrix from the environment is present let assignment = is_assignment(&*input); // checks to see if this input is an assignment :) if let Some((_, input_index, _, params)) = &assignment{ beginning_index = *input_index; if let Some(params) = params{ parameters = params.clone(); temp.push(SmartValue::Parameters(parameters.clone())); // pushes a marker } // f(x,y) = x + y*2 } if parameters.len() != 0 { println!("{:?}", &parameters) } // Converts a vector of characters into a Result<Decimal, Err> let to_dec = |x:&Vec<char>| { let buffer = (0..x.len()).map(|i| x[i]).collect::<String>(); // turns a vector of characters into a String Decimal::from_str(buffer.as_str()) }; for i in beginning_index..input.len(){ let nth:char = input.chars().nth(i).ok_or(GenericError)?; let next_nth = input.chars().nth(i + 1); if nth == r#"""#.chars().nth(0).unwrap(){ // double quotes if string{ string = false; let text = buf.iter().collect::<String>(); temp.push(SmartValue::Text(text)); buf.clear(); continue; } string = true; was_double = true; continue; } if nth == r#"'"#.chars().nth(0).unwrap(){ // single quotes if string{ if was_double{ buf.push(r#"'"#.chars().nth(0).unwrap()); continue; } string = false; let text = buf.iter().collect::<String>(); temp.push(SmartValue::Text(text)); buf.clear(); continue; } string = true; continue; } if string{ buf.push(nth); continue; } //check parentheses/braces if nth == '(' || nth == '['{ if number{ //if a number is being built, then assume that it will multiply temp.push(SmartValue::Number(to_dec(&buf)?)); temp.push(SmartValue::Operator('*')); } if nth == '['{ temp.push(SmartValue::MatrixMarker); // Shows that the following is a matrix } temp.push(SmartValue::LParen); buf.clear(); number = false; dec = false; counter += 1; position += 1; operator = false; paren_open = true; continue } if nth == ')' || nth == ']'{ if number{ temp.push(SmartValue::Number(to_dec(&buf)?)) } temp.push(SmartValue::RParen); buf.clear(); number = false; operator = false; dec = false; paren_open = false; counter -= 1; position += 1; continue } //check if it is an operator if OPR.contains(nth){ // takes care of negative values in parameters if (paren_open | comma) && NUM.contains(next_nth.ok_or(GenericError)?){ buf.push('-'); comma = false; continue; } // takes care of -(num) if nth == '-' && next_nth.ok_or(GenericError)? == '(' && !number{ buf.push('-'); buf.push('1'); number = true; operator = false; continue; } //if buf currently isn't building a number and the next char isn't a number, //and it is not a - sign, then something is wrong. if !number && (!NUM.contains(next_nth.ok_or(GenericError)?) && next_nth.ok_or(GenericError)? != '(' && !SYM.contains(next_nth.ok_or(GenericError)?)) && nth != '-'{ return Err(Box::new(FormattingError {position})) } //if there was already an operator, and the the next operator is not negative // (for setting negative values) then something is wrong if operator && nth != '-'{ return Err(Box::new(FormattingError {position})) } if let Some(x) = next_nth{ //can't be +) or *) if x == ')'{ return Err(Box::new(FormattingError{position})) } } //if nth - and an operator was already written, then number is negative if nth == '-' && operator{ buf.push('-'); continue } //if nth is - and is first to appear, then it must be a negative if nth == '-' && (i == 0 ||( i == beginning_index + 1 && beginning_index != 0)){ buf.push('-'); continue } if number{ temp.push(SmartValue::Number(to_dec(&buf)?)) } operator = true; number = false; dec = false; comma = false; temp.push(Operator(nth)); buf.clear(); position += 1; continue } //check if it is a number if NUM.contains(nth){ if nth == '.'{ //cant be 4.237. if dec{ return Err(Box::new(FormattingError{position})) } dec = true; //sets dec to true, as a decimal was inserted } buf.push(nth); number = true; operator = false; paren_open = false; comma = false; position += 1; continue } //check if it contains symbols if SYM.contains(nth){ if number{ temp.push(SmartValue::Number(to_dec(&buf)?)); temp.push(SmartValue::Operator('*')); // multiplies buf.clear(); } buf.push(nth); //push symbol onto the buffer let foo = &buf.iter().collect::<String>(); if let Some(next) = next_nth { let mut found = false; if let Some(value) = environment.get(foo){ // custom function finding :) let eee = value.iter().take_while(|s| { if let SmartValue::Variable(_) = s{ return false; } if let SmartValue::Placeholder(_) = s{ // the only reason why there would be a placeholder is if there is a variable return false; } true }).count(); // this gets the length of the environment variable, not including any Variables being in it. if eee != value.len(){ // if it found a Variable, then it means that this is a function. temp.push(SmartValue::Function(foo.clone())); paren_open = false; found = true; operator = false; position += 1; buf.clear(); continue } } if next == '(' || next == ')' || next == '[' || next == ']' || next == ',' || NUM.contains(next) || OPR.contains(next) { if self.function_controller.get(foo) != Function::Nil{ temp.push(SmartValue::Function(foo.clone())); //number = true; paren_open = false; found = true; operator = false; position += 1; buf.clear(); continue } else if parameters.contains(foo){ temp.push(SmartValue::Variable(foo.clone())); // pushes the variable onto the temporary array paren_open = false; found = true; operator = false; position += 1; buf.clear(); continue } else if environment.contains_key(foo){ for value in environment.get(foo).unwrap() { temp.push(value.clone()); } //number = true; paren_open = false; found = true; operator = false; position += 1; buf.clear(); continue } else if let Some(constant) = ConstantController::get(foo){ temp.push(constant); paren_open = false; found = true; operator = false; position += 1; buf.clear(); } else { return Err(Box::new(UnknownIdentifierError{position, identifier:foo.clone()})) } } if (next == '(' || NUM.contains(next)) && found{ temp.push(SmartValue::Operator('*')); continue } } else { if self.function_controller.get(foo) != Function::Nil{ temp.push(SmartValue::Function(foo.clone())); buf.clear(); } else if parameters.contains(foo){ temp.push(SmartValue::Variable(foo.clone())); buf.clear(); } else if environment.contains_key(foo){ for value in environment.get(foo).unwrap() { temp.push(value.clone()); } buf.clear(); } else if let Some(constant) = ConstantController::get(foo){ temp.push(constant); buf.clear(); } else { return Err(Box::new(UnknownIdentifierError{position, identifier:foo.clone()})) } } number = false; operator = false; paren_open = false; position += 1; } if nth == ',' || nth == ':' || nth == ';'{ // Comma, RangeMarker & SemiColon if counter == 0 && nth == ','{ // if a Comma is not within parentheses (or is alone), something is wrong. return Err(Box::new(FormattingError {position})); } if number { temp.push(SmartValue::Number(to_dec(&buf)?)); buf.clear(); number = false; operator = false; } if nth == ','{ comma = true; temp.push(SmartValue::Comma); } else if nth == ':'{ temp.push(SmartValue::RangeMarker); } else { temp.push(SmartValue::SemiColon) } position += 1; } } //now, at the end of the road, do some final checking. if operator{ //shouldn't be a lone operator at the end of some input return Err(Box::new(FormattingError{position})) } if number{ temp.push(SmartValue::Number(to_dec(&buf)?)) } drop(environment); // Mutable reference to the environment is no longer needed. if let Some((id, _, index, _)) = assignment{ // if there was an assignment, this is a special type of parsed information :) if let Some(index) = index{ let index_result = self.parser(index.as_str()).unwrap(); let mut wrapped = Wrapper::compose(index_result); wrapped.solve(self); if let Some(SmartValue::Matrix(mat)) = wrapped.values.get(0){ return Ok(vec![SmartValue::Assign(id.clone(), Some(mat.clone()), temp)]) } } return Ok(vec![SmartValue::Assign(id.clone(), None, temp)]) // returns a singular assign SmartValue } Ok(temp) //sends back the parsed information. } ///Only takes slices with NO PARENTHESES. pub fn calculate(&mut self, input: &mut Vec<SmartValue>){ let mut count:usize = 0; let mut last_comma_location:isize = -1; //println!("Number of SmartValues in input: {}", input.len()); //println!("CALCULATE"); //print_sv_vec(&input); //Wrapper::recurse_print(&input, 0); //println!("---"); let get_numbers = |data:&Vec<SmartValue>, cnt:usize| { let mut num_left = None; let mut num_right = None; if let Some(SmartValue::Number(left)) = data.get(cnt - 1){ num_left = Some(left.clone()); } if let Some(SmartValue::Number(right)) = data.get(cnt + 1){ num_right = Some(right.clone()) } (num_left, num_right) }; // does magic with Vec<SmartValue> that have Commas, i.e., are parameters in functions/ values in matrices loop{ if input.get(count) == None { // All indices have been looked through break; } if let Some(SmartValue::Error(err)) = input.get(count){ // if there exists an error, then all other values removed and only error exists. let val = (0..input.len()).filter_map(|i| { // filters out all values that do not have an error. Leaving only the error. if i == count{ return Some(input[i].clone()) } None }).collect::<Vec<SmartValue>>(); *input = val; return; } match input.get(count){ // if it has a comma or a semicolon, it will compute all the values before it. Some(SmartValue::Comma) => { let comma_remove = |inny:&mut Vec<SmartValue>| { for i in 0..inny.len(){ if let Some(value) = inny.get(i){ if *value == SmartValue::Comma { // TODO - Fix semicolon getting removed inny.remove(i); } } } }; let range = ((last_comma_location+1) as usize)..count; // a range of important information last_comma_location = count as isize; self.calculate(&mut input[range.clone()].to_vec()); comma_remove(input); // I tried removing it using math but I guess I couldn't figure out how to make it work consistently continue; }, Some(SmartValue::SemiColon) => { let range = ((last_comma_location+1) as usize)..count; last_comma_location = count as isize; self.calculate(&mut input[range].to_vec()); count += 1; continue; } _ => {} } if let Some(SmartValue::RangeMarker) = input.get(count){ let step_upper_bound = if let Some(SmartValue::RangeMarker) = input.get(count+2){ // there is another RangeMarker here, meaning that it is a range with a step given Some((input[count+1].clone(), input[count+3].clone())) } else { None }; // if a second RangeMarker exists, step_upper_bound will contain the step and the upper bound let lower_bound = input[count-1].clone(); let range = if let Some(step_upper_bound) = &step_upper_bound{ let mut result = None; if let SmartValue::Number(lower) = lower_bound{ if let SmartValue::Number(step) = step_upper_bound.0{ if let SmartValue::Number(upper) = step_upper_bound.1{ if step > Decimal::from(0){ // Only positive, nonzero step is allowed result = Some(SmartValue::Range(lower,step,upper)); } } } } result } else { // A range with a default step of 1 let mut result = None; if let SmartValue::Number(lower) = lower_bound{ if let SmartValue::Number(upper) = input[count+1]{ result = Some(SmartValue::Range(lower,Decimal::from(1),upper)); } } result }; if let Some(range) = range{ // check to see if the range was obtained if let Some(_) = step_upper_bound{ // BOUND:STEP:BOUND for _ in 0..5{ input.remove(count-1); // remove what was once there } input.insert(count-1,range.clone()); } else { // BOUND:BOUND for _ in 0..3{ input.remove(count-1); // remove what was once there } input.insert(count-1, range.clone()); } count = safe_sub(count); // move it back } else { // There was an error :( input.clear(); input.push(SmartValue::Error(String::from("Range Syntax Error"))); } } count += 1; } count = 0; //println!("COMMAS REMOVED"); //print_sv_vec(&input); // Calculates functions & Creates Matrices!! loop { if input.get(count) == None{ break; } // Indexing a Matrix if let Some(SmartValue::Matrix(mat)) = input.get(count){ if let Some(SmartValue::MatrixMarker) = input.get(count+1){ if let Some(SmartValue::Placeholder(index)) = input.get(count+2){ let index = SmartMatrix::new_from(index).unwrap(); // Always will be a SmartMatrix match mat.get_from(&index){ Ok(val) => { // Remove matrix, marker, and placeholder and replace it with value input.remove(count); input.remove(count); input.remove(count); input.insert(count,val); }, Err(err) => { input.clear(); input.push(SmartValue::Error(err.to_string())) } } } } } if let Some(val) = input.get(count+1){ //if there is a value in front of a function, it is not a handle to a function! if let SmartValue::Placeholder(parameters) = val{ // A placeholder MUST be in front of a function, otherwise it will not be executed. fn take_while_loop(input:&Vec<SmartValue>) -> usize{ input.iter().take_while(|s| { if let SmartValue::Variable(_) = s{ return false; } if let SmartValue::Placeholder(holder) = s{ return take_while_loop(holder) == input.len() } true }).count() } if let Some(SmartValue::Function(name)) = input.get(count){ let len = take_while_loop(&parameters); if len == parameters.len(){ let function = self.function_controller.get(name.as_str()); // gets the function from its identifier let value:Result<Vec<SmartValue>, Box<dyn std::error::Error>> = match function { rcas_functions::Function::Standard(func) => { func(&mut self.function_controller, parameters.clone()) // Executes the function!! }, rcas_functions::Function::Nil => { // Function identifier does NOT exist. Err(Box::new(GenericError {})) } }; match value { Ok(val) => { input.remove(count+1); input.remove(count); for i in 0..val.len(){ // INSERTS EVERY VALUE RETURNED INTO INPUT input.insert(count+i, val[i].clone()); } }, Err(err) => { // IF THERE IS AN ERROR, EVERY VALUE IS REMOVED. input.clear(); input.push(SmartValue::Error(err.to_string())); return; } } } } else if let Some(SmartValue::MatrixMarker) = input.get(count){ let mat = SmartMatrix::new_from(&parameters[..]); match mat{ Ok(mat) => { input.remove(count); input.remove(count); input.insert(count, SmartValue::Matrix(mat)); count = safe_sub(count); }, Err(err) => { // NUKE THE ENTIRE INPUT input.clear(); input.push(SmartValue::Error(err.to_string())); return; } } } } } count += 1; } count = 0; //println!("FUNCTIONS AND MATRICES CALCULATED"); //print_sv_vec(&input); //loop for multiplication and division loop{ if input.get(count) == None{ //All indices have been looked through //No need to loop again, therefore it breaks. break; } let op = if let Some(SmartValue::Operator(operator)) = input.get(count){ Some(*operator) } else { None }; if let Some(operator) = op{ if operator == '*' || operator == '/'{ let data = input.split_at_mut(count); let mut removal = None; // If Some(x) -> if x is true it will remove + and element to the right, if false, the left let mut error = None; // some error as a string match data.0.last_mut(){ Some(SmartValue::Number(left)) => { match data.1.get_mut(1){ Some(SmartValue::Number(right)) => { if operator == '*'{ // multiplication left.mul_assign(right.clone()); } else { // division if *right != Decimal::from(0){ left.div_assign(right.clone()); } else { error = Some(DivideByZeroError.to_string()); } } removal = Some((true, count)); // remove right count = 0; }, Some(SmartValue::Matrix(right)) => { if operator == '*'{ if let Err(err) = right.mul_scalar(left.clone()){ error = Some(err.to_string()); } removal = Some((false, count)); // remove left count = 0; } else { error = Some("ERROR. Cannot divide Number by Matrix".to_string()); } }, _ => {} } }, Some(SmartValue::Matrix(left)) => { match data.1.get_mut(1){ Some(SmartValue::Number(right)) => { if operator == '*'{ if let Err(err) = left.mul_scalar(right.clone()){ error = Some(err.to_string()); } } else { // A * 1/B is used instead of A/B for increased speed. if let Err(err) = left.mul_scalar(Decimal::from(1)/right.clone()){ error = Some(err.to_string()); } } removal = Some((true, count)); // remove right count = 0; }, Some(SmartValue::Matrix(right)) => { if operator == '*'{ if let Err(err) = right.mul(left){ error = Some(err.to_string()); } removal = Some((false, count)); // remove left count = 0; } else { error = Some("ERROR. Cannot divide Matrix by Matrix".to_string()); } }, _ => {} } }, _ => {} } drop(data); if let Some(error) = error{ input.clear(); input.push(SmartValue::Error(error.clone())); return; } if let Some((remove_right, location)) = removal{ if remove_right { input.remove(location); input.remove(location); } else { input.remove(location - 1); input.remove(location - 1); } } } } count += 1; //increment so that each index can be calculated } count = 0; //loop for addition and subtraction loop{ if input.get(count) == None{ //all indices have been looked through //No need to loop again, therefore it breaks. break; } let op = if let Some(SmartValue::Operator(operator)) = input.get(count){ Some(*operator) } else { None }; if let Some(operator) = op{ if operator == '+' || operator == '-'{ let data = input.split_at_mut(count); let mut removal = None; let mut error = None; match data.0.last_mut(){ Some(SmartValue::Number(left)) => match data.1.get_mut(1) { Some(SmartValue::Number(right)) => { if operator == '+'{ left.add_assign(*right); } else { left.sub_assign(*right); } removal = Some((true, count)); // remove right }, Some(SmartValue::Matrix(right)) => { if operator == '+'{ if let Err(err) = right.add_scalar(*left){ error = Some(err.to_string()); } } else { if let Err(err) = right.add_scalar(-(*left)){ error = Some(err.to_string()); } } removal = Some((false, count)); // remove left }, _ => {} }, Some(SmartValue::Matrix(left)) => match data.1.get_mut(1){ Some(SmartValue::Number(right)) => { if operator == '+'{ if let Err(err) = left.add_scalar(*right){ error = Some(err.to_string()); } } else { if let Err(err) = left.add_scalar(-(*right)){ error = Some(err.to_string()); } } removal = Some((true, count)); // remove right }, Some(SmartValue::Matrix(right)) => { if operator == '+'{ if let Err(err) = left.add(right){ error = Some(err.to_string()); } } else { if let Err(err) = left.sub(right){ error = Some(err.to_string()); } } removal = Some((true, count)); // remove right }, _ => {} }, _ => {} } drop(data); // data is no longer needed, and input needs to be mutated, therefore, it is dropped. if let Some(err) = error{ input.clear(); input.push(SmartValue::Error(err.clone())); return; } if let Some((remove_right, location)) = removal{ if remove_right { input.remove(location); input.remove(location); } else { input.remove(location - 1); input.remove(location - 1); } } } } count += 1; //increment so that each index can be calculated } } ///Takes a Vec<SmartValue> and composes it such that no LParen or RParen /// exists. Sections wrapped by parentheses are stored in a series of /// SmartValue::Placeholder pub fn composer(mut input: Vec<SmartValue>) -> Vec<SmartValue>{ let mut placeholder_locations:Vec<usize> = Vec::new(); let sections = number_of_parentheses_sections(&input); if sections == 0{ //no parentheses, therefore, no need to compose. return input; } else { //This will replace all parentheses within the same depth. for _ in 0..sections{ let parentheses_locations = get_outermost_parentheses(&input); //gets value inside first parentheses and puts it into a Placeholder if parentheses_locations.0 == 0 && parentheses_locations.1 == 0{ break; } let subsection = input[parentheses_locations.0+1 .. parentheses_locations.1].to_vec(); let placeholder = SmartValue::Placeholder(Self::composer(subsection)); // The power of recursion placeholder_locations.push(parentheses_locations.0); for _ in parentheses_locations.0 ..parentheses_locations.1{ input.remove(parentheses_locations.0); } if parentheses_locations.0 == input.len(){ input.push(placeholder) } else{ //input.insert(parentheses_locations.0, placeholder); input[parentheses_locations.0] = placeholder; } } for location in placeholder_locations{ if let SmartValue::Placeholder(mut subsection) = input[location].clone(){ subsection = Self::composer(subsection); //does it all over again :) } } input //the magic has been done. } } /// Returns a safe reference to the rcas environment. pub fn get_environment(&mut self) -> Rc<RefCell<FxHashMap<String, Vec<SmartValue>>>>{ self.environment.clone() } pub fn recurse_solve(&mut self, mut input:Vec<SmartValue>) -> Vec<SmartValue>{ //print_sv_vec(&input); return if has_placeholder(&input) { for x in 0..input.len() { if let Some(SmartValue::Placeholder(holder)) = input.get(x) { //print_sv_vec(&holder); let solved = self.recurse_solve(holder.clone()); // Doesn't remove the placeholder if there is a function before it. if let Some(SmartValue::Function(_)) = input.get(safe_sub(x)){ //NOTHING HERE. } else if solved.len() == 0 { // if the solve returned NOTHING, and there is no function before this placeholder, then the entire answer must be nothing. return Vec::new() } // a nice way to get the resolved value. If the previous value is a not function, then it is just a Number. // Otherwise, it is probably parameters to a function, and as such should be in // A placeholder. // This also works for Matrices :) let value = if let Some(SmartValue::Function(_)) = input.get(safe_sub(x)){ // if previous was a function, then put the solution in a placeholder. SmartValue::Placeholder(solved) } else if let Some(SmartValue::MatrixMarker) = input.get(safe_sub(x)){ // creating matrix SmartValue::Placeholder(solved) } else if let Some(SmartValue::MatrixMarker) = input.get(safe_sub(safe_sub(x))){ // in case x[1](num) SmartValue::Placeholder(solved) } else { solved[0].clone() }; input[x] = value; } //println!("X: {}", &input[x].get_value()); } let mut input = input; self.calculate(&mut input); input } else { let mut input = input; // Wrapper::recurse_print(&input,0); // println!("----"); self.calculate(&mut input); input } } } pub enum QueryResult{ Simple(String), // Common arithmetic query results will appear here Assign(QueryAssign), // Query result that assigns a value to a variable or function identifier Image(QueryImage), // Query result that returns an Image Execute(Command), // Query result that requires the GUI to execute Error(String) // Returned in case of parsing or function error } /// Commands that interface with the GUI. #[derive(Debug, PartialEq, Clone)] pub enum Command{ ClearScreen, //cls() RemoveCurrentPlot, //clear("current") RemovePlots, //clear("*") ClearEnvironment, //clear("env") ClearAll, //clear("all") SavePlot, //saveplot("magic.png") RefreshEnvironment, SetMode(CalculationMode), } /// A structure that contains a raster (PNG) and vector (SVG) versions of a plot. /// The vector is used for displaying a plot in high-resolution. /// The raster is used in case of saving the plot to any format. pub struct QueryImage{ pub raster: Vec<u8>, // raster image (A PNG FILE) pub vector: String, // vector iamge (AN SVG FILE) } /// A structure that contains the identifier to data and the data itself. pub struct QueryAssign{ pub id: String, pub data: DataType, } /// Used to facilitate the transfer of information. pub enum DataType{ Number(Decimal), // A Number Matrix, Image(QueryImage), // Assigning to a query Function // Assigned to a function } #[derive(PartialEq, Clone)] pub struct Wrapper{ pub values: Vec<SmartValue>, } impl Wrapper{ pub fn new() -> Self{ Wrapper {values:Vec::new()} } ///Composes a Wrapper. pub fn compose(input: Vec<SmartValue>) -> Self{ //Self::recurse_print(&input, 0); let values = RCas::composer(input); //Self::recurse_print(&values, 0); Wrapper {values} } pub fn recurse_print(input:&Vec<SmartValue>, level:usize){ for value in input{ match value{ SmartValue::Number(num) => { println!("{}:{}", level, num); }, SmartValue::Function(name) => { println!("{}:{}", level, &name); }, SmartValue::Placeholder(holder) => { println!("{}:PLACEHOLDER", level); Self::recurse_print(&holder, level+1); }, SmartValue::Operator(opr) => { println!("{}:{}", level, *opr); }, SmartValue::LParen => { println!("{}:(", level); }, SmartValue::RParen => { println!("{}:)", level); }, SmartValue::Comma => { println!("{}:,", level); }, SmartValue::Variable(id) => println!("{}:{}", level, id), SmartValue::Matrix(mat) => { println!("[{}x{}]", mat.cols(), mat.rows()); } idk => println!("{}:{}", level, idk.get_value(false)) } } } ///Solves a Wrapper. pub fn solve(&mut self, rcas:&mut RCas){ self.values = rcas.recurse_solve(self.values.clone()) } pub fn print_raw(&self){ print_sv_vec(&self.values); } pub fn to_string(&self) -> String{ sv_vec_string(&self.values) } pub fn to_result(&self) -> QueryResult{ if self.values.len() == 1 { return match &self.values[0]{ SmartValue::Error(err) => QueryResult::Error(err.clone()), SmartValue::Cmd(cmd) => QueryResult::Execute(cmd.clone()), _ => QueryResult::Simple(self.to_string()), }; } else if self.values.len() == 0{ return QueryResult::Simple("".to_string()) } return QueryResult::Error("FUNCTION ERROR".to_string()) } } #[derive(Debug, PartialEq, Clone)] pub enum SmartValue{ Operator(char), Function(String), //holds a function identifier Number(Decimal), Text(String), LParen, // for parentheses RParen, LBrace, // for matrices RBrace, MatrixMarker, // Used when calculating/composing Matrix(SmartMatrix), SemiColon, // a semicolon for matrices. Variable(String), // Utilized in user-defined functions. Each variable as an identifier attributed to it. Parameters(Vec<String>), // A marker that is utilized during parsing that identifies the order in which the name of parameters are placed in a function declaration Placeholder(Vec<SmartValue>), Range(Decimal,Decimal,Decimal), // Bound1, Step, Bound2 RangeMarker, // A colon : Label(String,Vec<SmartValue>), // A label can contains an identifier and a possible expression. Comma, // A special character used to separate parameters Assign(String, Option<SmartMatrix>, Vec<SmartValue>), // A special equals = operator. It is used to show that a value is being assigned to an identifier. Error(String), // An error returned from a function call. The Stringified version of the error is returned. Cmd(Command), // A command that is returned from a function call. May exist when solving } impl SmartValue{ pub fn get_value(&self, extended:bool) -> String{ let mut buf = String::new(); match self{ SmartValue::Operator(x) => buf.push(*x), SmartValue::Function(id) => buf.push_str(id), SmartValue::Number(x) => { let num = format!("{}", x); buf.push_str(&num); }, SmartValue::LParen => buf.push('('), SmartValue::RParen => buf.push(')'), SmartValue::Placeholder(holder) => { buf.push('('); for x in holder{ buf.push_str(&*x.get_value(extended)); } buf.push(')'); }, SmartValue::Text(string) => buf.push_str(&**string), SmartValue::Variable(id) => buf.push_str(id), SmartValue::Parameters(_) => {}, SmartValue::Range(bound1,step,bound2) => { if *step == Decimal::from(1){ buf.push_str(format!("{}:{}", bound1, bound2).as_str()); } else { buf.push_str(format!("{}:{}:{}", bound1, step, bound2).as_str()); } }, SmartValue::Matrix(mat) => { if extended{ buf.push_str(format!("{}", mat).as_str()); } else { buf.push_str(format!("[{}x{}]", mat.cols(), mat.rows()).as_str()); } }, SmartValue::MatrixMarker => buf.push_str("MatrixMarker"), SmartValue::SemiColon => buf.push(';'), SmartValue::RangeMarker => buf.push(':'), _ => buf.push('?') } buf } } #[derive(Debug,Clone,PartialEq)] pub enum CalculationMode{ Radian, Degree } impl CalculationMode{ pub fn to_string(&self) -> String{ match &self{ CalculationMode::Radian => format!("RAD -> "), CalculationMode::Degree => format!("DEG -> ") } } } fn expression_clone(input:&Vec<SmartValue>, lower:usize, upper:usize) -> Vec<SmartValue>{ let mut clone = Vec::new(); clone.clone_from_slice(&input[lower..upper]); clone } #[inline(always)] fn safe_sub(input:usize) -> usize{ return if input > 0{ input -1 } else{ 0 } } fn has_function(input:&Vec<SmartValue>) -> bool{ let mut value = false; for x in input{ if let SmartValue::Function(_) = x{ value = true; } } value } fn has_placeholder(input:&Vec<SmartValue>) -> bool{ for x in input{ if let SmartValue::Placeholder(_) = x{ return true; } } false } fn recurse_check_paren(input:&Vec<SmartValue>, left:usize, right:usize, counter:u32) -> (usize, usize) { if left < input.len() && right < input.len(){ if input[left] != SmartValue::LParen{ return recurse_check_paren(input, left + 1, left + 1, counter) } if input[right] == SmartValue::LParen{ return recurse_check_paren(input, left, right + 1, counter + 1) } if input[right] == SmartValue::RParen && counter != 0{ //subtracts one from counter return recurse_check_paren(input, left, right + 1, counter - 1) } if counter != 0{ //advances return recurse_check_paren(input, left, right + 1, counter) } } //returns left and right if counter is 0, and both left and right are on parentheses (left, right) } fn get_outermost_parentheses(input:&Vec<SmartValue>) -> (usize,usize){ let mut left = 0; let mut right= 0; let mut counter = 0; let mut found_left = false; for x in 0..input.len(){ //gets leftmost if input[x] == SmartValue::LParen && !found_left{ left = x; found_left = true; } if input[x] == SmartValue::LParen{ counter += 1; } if input[x] == SmartValue::RParen{ counter -= 1; if counter == 0{ // in case this is the last loop and this is the outermost parentheses. right = x; } } if input[x] == SmartValue::RParen && counter == 0{ right = x; break; } } (left, right) } fn number_of_parentheses_sections(input: &Vec<SmartValue>) -> usize{ input.iter().filter(|x| **x == SmartValue::LParen).count() } //for debugging parser result pub fn print_sv_vec(sv:&Vec<SmartValue>){ let mut buf = String::new(); for value in sv{ buf.push_str(value.get_value(false).as_str()); //buf.push('|'); } println!("{}", buf) } /// Converts a &Vec<SmartValue> to a String pub fn sv_vec_string(sv:&Vec<SmartValue>) -> String { let mut buf = String::new(); for value in sv{ buf.push_str(value.get_value(true).as_str()); } buf } /// Checks to see of an input contains an assignment. If it does, it returns the index after the assignment operator was found. fn is_assignment(input:&str) -> Option<(String, usize, Option<String>, Option<Vec<String>>)>{ let mut identifier = input.chars().take_while(|x| *x != '=' ).collect::<String>(); let identifier_len = identifier.len(); if identifier.chars().filter_map(|x| match x { '(' => Some(1), ')' => Some(-1), _ => None }).sum::<i32>() > 0 { // if it is within open parentheses, then this is no assignment. return None; } // There is an identifier at this point. //This will get the parameters if the assignment was that of a function. let parameters = if identifier.chars().last().unwrap() == ')'{ // if there is a closing word there let count = identifier.chars().take_while(|x| *x != '(').count(); let parameters = identifier.chars() .skip(count+1) .take_while(|x| *x != ')') .collect::<String>(); let parameter_identifiers = parameters.split(",").map(|x| String::from(x)).collect::<Vec<String>>(); identifier = (&identifier[0..count]).to_string(); Some(parameter_identifiers) } else { None }; //This will get the index if the assignment contains an index. let index = if identifier.contains("["){ // get the number of characters between the name of the identifier and the bracket let count = identifier.chars().take_while(|x| *x != '[').count(); let index = identifier.chars() .skip(count) .collect::<String>(); identifier = (&identifier[0..count]).to_string(); // removes the [ ] from the identifier Some(index) } else { None }; if identifier_len == input.len(){ return None; } Some((identifier, identifier_len, index, parameters)) }
true
c6d69b4eed40b64026463d33db42ec0d88a7fb71
Rust
38/d4-format
/d4-framefile/src/mapped.rs
UTF-8
4,817
2.953125
3
[ "MIT" ]
permissive
use crate::randfile::mapping::MappingHandle; use crate::randfile::RandFile; use crate::stream::FrameHeader; use crate::{Directory, EntryKind}; use std::collections::HashMap; use std::fs::File; use std::io::Result; /// A memory mapped data structure for a directory object in frame file pub struct MappedDirectory { streams: HashMap<String, (usize, usize)>, handle: MappingHandle, } /// A memory mapped stream object pub struct MappedStream<'a>(&'a u8, usize); /// A single stream frame in a mapped stream object #[repr(packed)] pub struct MappedStreamFrame { header: FrameHeader, pub data: [u8], } impl AsRef<[u8]> for MappedStreamFrame { fn as_ref(&self) -> &[u8] { &self.data } } impl<'a> MappedStream<'a> { pub(crate) fn new(data: &'a u8, primary_size: usize) -> Self { MappedStream(data, primary_size) } /// Get the first frame in this stream pub fn get_primary_frame(&self) -> &'a MappedStreamFrame { unsafe { std::mem::transmute((self.0, self.1 - std::mem::size_of::<FrameHeader>())) } } /// Copy the full content of the stream pub fn copy_content(&self, buf: &mut Vec<u8>) { //let mut ret = Vec::<u8>::new(); let mut current = Some(self.get_primary_frame()); while let Some(frame) = current { buf.extend_from_slice(&frame.data); current = frame.next_frame(); } } } impl MappedStreamFrame { pub unsafe fn offset_from(&self, base: *const u8) -> isize { (self as *const _ as *const u8).offset_from(base) } pub fn next_frame(&self) -> Option<&MappedStreamFrame> { self.header.linked_frame.map(|offset| { let payload_size = self.header.linked_frame_size.to_le() - std::mem::size_of::<FrameHeader>() as u64; let next_frame_addr = unsafe { (self as *const _ as *const u8).offset(i64::from(offset).to_le() as isize) }; // Actually, this is the only reliable way to construct a custom DST reference from raw memory address // It's not obvious and hacky: // - First, we use `std::ptr::slice_from_raw_parts` that make a DST fat pointer by introducing size // information to the pointer. At this point, the pointer doesn't actually points to the correct memory region. // Because returned *const [u8] actually describes memory region from frame_addr to frame_addr + payload_size // thus, there are exactly sizeof(Header) bytes of payload data is out of the range. But this doesn't matter. // - Then, we cast the pointer to *const MappedStreamFrame, which is a DST pointer as well. But this time, the // pointer will be interpreted correctly, as it points to the correct location, plus it carries correct size info. // Thus the purpose of calling slice_from_raw_parts is not yield a well-formed pointer, but a compiler supported // way to introduce size information to a thin pointer. After that we then cast the pointer make sure that the // pointer can be dereferenced correctly. // See https://github.com/rust-lang/unsafe-code-guidelines/issues/288 for details let frame_ptr = std::ptr::slice_from_raw_parts(next_frame_addr, payload_size as usize) as *const Self; unsafe { &*frame_ptr } }) } } impl MappedDirectory { pub fn get_base_addr(&self) -> *const u8 { self.handle.as_ref().as_ptr() } pub fn open_stream(&self, name: &str) -> Option<MappedStream<'_>> { if let Some((ptr, size)) = self.streams.get(name) { Some(unsafe { MappedStream::new(std::mem::transmute(*ptr), *size) }) } else { None } } pub fn new(file: RandFile<File>, offset: u64, size: usize) -> Result<Self> { let handle = file.mmap(offset, size)?; let data = handle.as_ref(); let root_stream = MappedStream::new( &data[0], crate::directory::Directory::<File>::INIT_BLOCK_SIZE, ); let mut content = Vec::new(); root_stream.copy_content(&mut content); let mut dir_table = HashMap::new(); let mut cursor = &content[..]; while let Some(entry) = Directory::<File>::read_next_entry(0, &mut cursor)? { if entry.kind == EntryKind::Stream { dir_table.insert( entry.name, ( &data[entry.primary_offset as usize] as *const u8 as usize, entry.primary_size as usize, ), ); } } Ok(MappedDirectory { streams: dir_table, handle, }) } }
true
0f00390e2277d432d7543f424fbea2cf333cea7f
Rust
timakro/rust-unsorted
/aoc12/src/main.rs
UTF-8
1,879
3.4375
3
[]
no_license
use std::fs; struct PartOne { pos: (i32, i32), dir: i32, // North 3, East 2, South 1, West 0 } impl PartOne { fn take(&mut self, action: &str, value: i32) { match action { "N" => self.pos.1 += value, "S" => self.pos.1 -= value, "E" => self.pos.0 += value, "W" => self.pos.0 -= value, "L" => self.dir = (self.dir + value/90).rem_euclid(4), "R" => self.dir = (self.dir - value/90).rem_euclid(4), "F" => if self.dir % 2 == 0 { self.pos.0 += value * (self.dir-1) } else { self.pos.1 += value * (self.dir-2) }, _ => panic!("Unknown action {}", action) } } } struct PartTwo { pos: (i32, i32), wpp: (i32, i32), } impl PartTwo { fn take(&mut self, action: &str, value: i32) { match action { "N" => self.wpp.1 += value, "S" => self.wpp.1 -= value, "E" => self.wpp.0 += value, "W" => self.wpp.0 -= value, "L" => for _ in 0..value/90 { self.wpp = (-self.wpp.1, self.wpp.0) }, "R" => for _ in 0..value/90 { self.wpp = (self.wpp.1, -self.wpp.0) }, "F" => { self.pos.0 += value * self.wpp.0; self.pos.1 += value * self.wpp.1 }, _ => panic!("Unknown action {}", action) } } } fn main() { let mut one = PartOne { pos: (0, 0), dir: 2 }; let mut two = PartTwo { pos: (0, 0), wpp: (10, 1) }; for line in fs::read_to_string("input").unwrap().lines() { let (action, value) = line.split_at(1); let value: i32 = value.parse().unwrap(); one.take(action, value); two.take(action, value); } println!("{} with old rules", one.pos.0.abs() + one.pos.1.abs()); println!("{} with waypoint", two.pos.0.abs() + two.pos.1.abs()); }
true
5d40f902cf0764733b51e3fa0afb285909fc53be
Rust
raymondjcox/rust-learning
/hangman/src/main.rs
UTF-8
1,473
3.65625
4
[]
no_license
extern crate rand; use std::io; use rand::Rng; use std::collections::HashMap; fn main() { println!("Welcome to hangman!"); let words = ["Jiayi", "RJ"]; let chosen_word = words[rand::thread_rng().gen_range(0, words.len())]; let mut guesses_left = chosen_word.chars().count() + 2; println!("You have a total of {} guesses. The word is {} characters long", guesses_left, chosen_word.chars().count()); let mut guesses = HashMap::new(); while guesses_left > 0 { println!("What's your guess?"); let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("Failed to read line"); let guess: char = match guess.trim().parse() { Ok(ch) => ch, Err(_) => { println!("You may only enter 1 letter at a time"); continue }, }; guesses.insert(guess, true); let mut guessed_word = String::new(); for c in chosen_word.chars() { match guesses.get(&c) { Some(_) => guessed_word.push(c), None => guessed_word.push('_'), }; } println!("Guessed word: {}", guessed_word); guesses_left -= 1; if guessed_word == chosen_word { println!("You win! with {} guesses left", guesses_left); return; } println!("You have {} guesses left", guesses_left); } println!("You lose!"); }
true
292fb0447580e99321274bd143367f4c6d51e534
Rust
jtojnar/lorri
/src/roots.rs
UTF-8
1,790
3.25
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! TODO use std::env; use std::os::unix::fs::symlink; use std::path::PathBuf; /// Roots manipulation #[derive(Clone)] pub struct Roots { root_dir: PathBuf, id: String, } impl Roots { /// Create a Roots struct to manage roots within the root_dir /// directory. /// /// `id` is a unique identifier for this project's checkout. pub fn new(root_dir: PathBuf, id: String) -> Roots { Roots { root_dir, id } } /// Store a new root under name pub fn add(&self, name: &str, store_path: &PathBuf) -> Result<PathBuf, AddRootError> { let mut path = self.root_dir.clone(); path.push(name); debug!("Adding root from {:?} to {:?}", store_path, path,); ignore_missing(std::fs::remove_file(&path))?; symlink(&store_path, &path)?; // this is bad. let mut root = PathBuf::from("/nix/var/nix/gcroots/per-user"); root.push(env::var("USER").expect("env var 'USER' must be set")); root.push(format!("{}-{}", self.id, name)); debug!("Connecting root from {:?} to {:?}", path, root,); ignore_missing(std::fs::remove_file(&root))?; symlink(&path, &root)?; Ok(path) } } fn ignore_missing(err: Result<(), std::io::Error>) -> Result<(), std::io::Error> { if let Err(e) = err { match e.kind() { std::io::ErrorKind::NotFound => Ok(()), _ => Err(e), } } else { Ok(()) } } /// Error conditions encountered when adding roots #[derive(Debug)] pub enum AddRootError { /// IO-related errors Io(std::io::Error), /// Execution time errors FailureToAdd, } impl From<std::io::Error> for AddRootError { fn from(e: std::io::Error) -> AddRootError { AddRootError::Io(e) } }
true
22619b87a176cab512780dfecea828106a1bf523
Rust
fredmorcos/attic
/Snippets/Rust/test2.rs
UTF-8
692
4.09375
4
[ "Unlicense" ]
permissive
fn test(x: &mut u8) { *x = 3; } /// tests something /// /// # Examples /// ``` /// let five = 5; /// assert_eq!(6, 5 + 1); /// ``` fn test2(x: &mut Vec<u8>) { x.push(32); } fn main() { let mut x: u8 = 5; test(&mut x); println!("{}", x); let mut y: Vec<u8> = Vec::new(); y.push(3); y.push(4); for i in &y { print!("{}, ", i); } println!(""); test2(&mut y); for i in &y { print!("{}, ", i); } println!(""); let z: [u8; 3] = [1, 2, 3]; for i in z.iter() { print!("{}, ", i); } println!(""); let mut v: Vec<u8> = Vec::new(); let v2: &mut Vec<u8> = &mut v; v2.push(3); for i in v2 { print!("{}, ", i); } println!(""); }
true
ad051444404c94d2b87ddf813cc57cc55cb8c375
Rust
IThawk/rust-project
/rust-master/src/test/ui/resolve/issue-2356.rs
UTF-8
1,771
3.578125
4
[ "MIT", "LicenseRef-scancode-other-permissive", "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "NCSA" ]
permissive
trait Groom { fn shave(other: usize); } pub struct Cat { whiskers: isize, } pub enum MaybeDog { Dog, NoDog } impl MaybeDog { fn bark() { // If this provides a suggestion, it's a bug as MaybeDog doesn't impl Groom shave(); //~^ ERROR cannot find function `shave` } } impl Clone for Cat { fn clone(&self) -> Self { clone(); //~^ ERROR cannot find function `clone` loop {} } } impl Default for Cat { fn default() -> Self { default(); //~^ ERROR cannot find function `default` loop {} } } impl Groom for Cat { fn shave(other: usize) { whiskers -= other; //~^ ERROR cannot find value `whiskers` shave(4); //~^ ERROR cannot find function `shave` purr(); //~^ ERROR cannot find function `purr` } } impl Cat { fn static_method() {} fn purr_louder() { static_method(); //~^ ERROR cannot find function `static_method` purr(); //~^ ERROR cannot find function `purr` purr(); //~^ ERROR cannot find function `purr` purr(); //~^ ERROR cannot find function `purr` } } impl Cat { fn meow() { if self.whiskers > 3 { //~^ ERROR expected value, found module `self` println!("MEOW"); } } fn purr(&self) { grow_older(); //~^ ERROR cannot find function `grow_older` shave(); //~^ ERROR cannot find function `shave` } fn burn_whiskers(&mut self) { whiskers = 0; //~^ ERROR cannot find value `whiskers` } pub fn grow_older(other:usize) { whiskers = 4; //~^ ERROR cannot find value `whiskers` purr_louder(); //~^ ERROR cannot find function `purr_louder` } } fn main() { self += 1; //~^ ERROR expected value, found module `self` }
true
291c161f18df7da42fd0f3e263bbec54ca944453
Rust
blackmesalab/fireguard
/src/cmd/wg.rs
UTF-8
4,357
2.96875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
use std::path::Path; use clap::Clap; use color_eyre::eyre::{bail, Result}; use tokio::fs::read_to_string; use crate::cmd::{Command, Fireguard}; use crate::wg::{WgConfig, WgQuick}; /// Wg - Wireguard management #[derive(Clap, Debug)] pub struct Wg { /// Wg subcommands #[clap(subcommand)] pub action: Action, /// Repository name #[clap(short = 'r', long = "repository")] pub repository: String, } #[derive(Clap, Debug)] pub enum Action { /// Render the Wireguard configuration for the current host Render(Render), /// Start the Wireguard userspace tunnel Up(Up), /// Stop the Wireguard userspace tunnel Down(Down), /// Show the Wireguard userspace tunnel status and stats Status(Status), } impl Wg { async fn pre_checks(&self, fg: &Fireguard) -> Result<()> { let config = Path::new(&fg.config_dir); if config.is_dir() { Ok(()) } else { bail!( "Please create Fireguard config directory {} as root: mkdir -p {} && chown {} {}", fg.config_dir, fg.config_dir, whoami::username(), fg.config_dir ); } } pub async fn exec(&self, fg: &Fireguard) -> Result<()> { self.pre_checks(fg).await?; match self.action { Action::Render(ref action) => action.exec(fg, &self.repository).await?, Action::Up(ref action) => action.exec(None, &self.repository).await?, Action::Down(ref action) => action.exec(None, &self.repository).await?, Action::Status(ref action) => action.exec(None, &self.repository).await?, } Ok(()) } } /// Render the Wireguard configuration for the current host #[derive(Clap, Debug)] pub struct Render { /// User name #[clap(short = 'u', long = "username")] pub username: String, /// Peer name #[clap(short = 'p', long = "peername")] pub peername: String, /// Private key #[clap(short = 'P', long = "private-key")] pub private_key: String, /// Config file path #[clap(short = 'c', long = "config-dir", default_value = "/etc/wireguard")] pub config_dir: String, } impl Command for Render {} impl Render { async fn pre_checks(&self, _fg: &Fireguard) -> Result<()> { let config = Path::new(&self.config_dir); if config.is_dir() { Ok(()) } else { bail!( "Please create Wireguard config directory {} as root: mkdir -p {} && chown {} {}", self.config_dir, self.config_dir, whoami::username(), self.config_dir ); } } pub async fn exec(&self, fg: &Fireguard, repository: &str) -> Result<()> { self.pre_checks(fg).await?; let config = self.load_config(repository, &fg.config_dir, &fg.config_file).await?; let wg_config_path = Path::new(&self.config_dir).join(&format!("{}.conf", repository)); let wg_config = WgConfig::new(config.peers, repository, &self.username, &self.peername, &self.private_key)?; wg_config.render(&wg_config_path).await?; let data = read_to_string(&wg_config_path).await?; info!("Wireguard configuration written to {}:\n{}", wg_config_path.display(), data.trim()); Ok(()) } } /// Start the Wireguard tunnel for the current host after rendering the config #[derive(Clap, Debug)] pub struct Up {} impl Command for Up {} impl Up { pub async fn exec(&self, _fg: Option<&Fireguard>, repository: &str) -> Result<()> { let bt = WgQuick::new(repository)?; bt.up().await?; Ok(()) } } /// Stop the Wireguard tunnel for the current host #[derive(Clap, Debug)] pub struct Down {} impl Command for Down {} impl Down { pub async fn exec(&self, _fg: Option<&Fireguard>, repository: &str) -> Result<()> { let bt = WgQuick::new(repository)?; Ok(bt.down().await?) } } /// Start the Wireguard tunnel for the current host after rendering the config #[derive(Clap, Debug)] pub struct Status {} impl Command for Status {} impl Status { pub async fn exec(&self, _fg: Option<&Fireguard>, repository: &str) -> Result<()> { let bt = WgQuick::new(repository)?; bt.status().await?; Ok(()) } }
true
d58d8a51cc7fc9b01a233c2c9b3085f6cf84bdc7
Rust
drewm1980/rust-omr
/src/loaders.rs
UTF-8
1,783
2.953125
3
[ "LicenseRef-scancode-public-domain" ]
permissive
use pgm; use image::{Image}; use std::str::{from_utf8}; /// Load an image file using ImageMagick in a separate process, /// with automatic fallback (and fast case) to a native pgm file loader. pub fn load(path: &Path) -> Image { match path.extension() { Some(s) if from_utf8(s).unwrap()=="pgm" => pgm::load(path), _ => load_using_magick(path), } } // Load a file by first using imageMagick to convert it to a .pgm file. fn load_using_magick(path: &Path) -> Image { use std::io::Command; use std::io::process::ProcessExit::{ExitStatus,ExitSignal}; let output = Command::new("convert") .arg(path) .arg("pgm:-") // Dark imagemagick magick to force output of specific image type to stdout .output().ok().unwrap(); let data: Vec<u8> = match output.status { ExitStatus(i) if i==0 => output.output, ExitStatus(i) => panic!("Image Magick reported an error: {}",String::from_utf8_lossy(output.error.as_slice())), ExitSignal(i) => panic!("Convert subprocess threw a signal {}",i), }; pgm::parse(data.as_slice()) } #[cfg(test)] mod test { extern crate test; #[test] fn test_load_png_from_file() { let loadfile = "test_images/rust_favicon.png"; let loadpath = Path::new(loadfile); super::load(&loadpath); } #[test] fn test_load_jpg_from_file() { let loadfile = "test_images/rust_favicon.jpg"; let loadpath = Path::new(loadfile); super::load(&loadpath); } #[test] fn test_load_gif_from_file() { let loadfile = "test_images/rust_favicon.gif"; let loadpath = Path::new(loadfile); super::load(&loadpath); } #[test] fn test_load_non_toy_image() { let loadfile = "sheet_music/La_yumba1.gif"; let loadpath = Path::new(loadfile); super::load(&loadpath); } }
true
08739d5978b3b5573e3cdcc99444d7ce362aa31f
Rust
johnwstanford/cufft_rs
/examples/01_fft_benchmark.rs
UTF-8
1,479
2.6875
3
[]
no_license
use std::time::Instant; use rand::{thread_rng, Rng}; use rustfft::FFTplanner; use rustfft::num_complex::Complex; use rustfft::num_traits::Zero; use cufft_rs::cufft::{Plan, ExecCudaFFT}; fn main() -> Result<(), &'static str> { let n:usize = 2usize.pow(26); println!("FFT size = {:.3e}", n); let mut rng = thread_rng(); let mut plan = Plan::new(n as i32, 1).unwrap(); let time_domain_host:Vec<Complex<f32>> = (0..n).map(|_| Complex{re: rng.gen_range(-100.0, 100.0), im: rng.gen_range(-100.0, 100.0)}).collect(); let time_domain_slice:&[Complex<f32>] = &time_domain_host; let gpu_start = Instant::now(); let freq_domain_host:Vec<Complex<f32>> = time_domain_slice.fwd(&mut plan).unwrap(); println!("GPU time: {:.4} [sec]", gpu_start.elapsed().as_secs_f32()); let freq_domain_cpu:Vec<Complex<f32>> = { let mut time_domain:Vec<Complex<f32>> = time_domain_host.clone(); let mut freq_domain: Vec<Complex<f32>> = vec![Complex::zero(); n]; let mut planner = FFTplanner::new(false); let fft = planner.plan_fft(n); // This function uses time_domain as scratch space, so it's to be considered garbage after this call let cpu_start = Instant::now(); fft.process(&mut time_domain, &mut freq_domain); println!("CPU time: {:.4} [sec]", cpu_start.elapsed().as_secs_f32()); freq_domain }; println!("First few freq domain values:"); for i in 0..5 { println!("{} CPU: {:25.3}, GPU: {:25.3}", i, freq_domain_cpu[i], freq_domain_host[i]); } Ok(()) }
true
ab48de9aff8a723cfcce976529185614f756e260
Rust
jannik4/openmls
/src/messages/proposals.rs
UTF-8
12,855
2.75
3
[ "MIT" ]
permissive
use crate::ciphersuite::*; use crate::codec::*; use crate::framing::{sender::*, *}; use crate::key_packages::*; use crate::tree::index::*; use std::collections::{HashMap, HashSet}; #[derive(PartialEq, Clone, Copy, Debug)] #[repr(u8)] pub enum ProposalType { Invalid = 0, Add = 1, Update = 2, Remove = 3, Default = 255, } impl From<u8> for ProposalType { fn from(value: u8) -> Self { match value { 0 => ProposalType::Invalid, 1 => ProposalType::Add, 2 => ProposalType::Update, 3 => ProposalType::Remove, _ => ProposalType::Default, } } } impl Codec for ProposalType { fn encode(&self, buffer: &mut Vec<u8>) -> Result<(), CodecError> { (*self as u8).encode(buffer)?; Ok(()) } } #[allow(clippy::large_enum_variant)] #[derive(Debug, PartialEq, Clone)] pub enum Proposal { Add(AddProposal), Update(UpdateProposal), Remove(RemoveProposal), } impl Proposal { pub(crate) fn get_type(&self) -> ProposalType { match self { Proposal::Add(ref _a) => ProposalType::Add, Proposal::Update(ref _u) => ProposalType::Update, Proposal::Remove(ref _r) => ProposalType::Remove, } } pub(crate) fn is_type(&self, proposal_type: ProposalType) -> bool { self.get_type() == proposal_type } pub(crate) fn as_add(&self) -> Option<AddProposal> { match self { Proposal::Add(add_proposal) => Some(add_proposal.clone()), _ => None, } } pub(crate) fn as_update(&self) -> Option<UpdateProposal> { match self { Proposal::Update(update_proposal) => Some(update_proposal.clone()), _ => None, } } pub(crate) fn as_remove(&self) -> Option<RemoveProposal> { match self { Proposal::Remove(remove_proposal) => Some(remove_proposal.clone()), _ => None, } } } impl Codec for Proposal { fn encode(&self, buffer: &mut Vec<u8>) -> Result<(), CodecError> { match self { Proposal::Add(add) => { ProposalType::Add.encode(buffer)?; add.encode(buffer)?; } Proposal::Update(update) => { ProposalType::Update.encode(buffer)?; update.encode(buffer)?; } Proposal::Remove(remove) => { ProposalType::Remove.encode(buffer)?; remove.encode(buffer)?; } } Ok(()) } fn decode(cursor: &mut Cursor) -> Result<Self, CodecError> { let proposal_type = ProposalType::from(u8::decode(cursor)?); match proposal_type { ProposalType::Add => Ok(Proposal::Add(AddProposal::decode(cursor)?)), ProposalType::Update => Ok(Proposal::Update(UpdateProposal::decode(cursor)?)), ProposalType::Remove => Ok(Proposal::Remove(RemoveProposal::decode(cursor)?)), _ => Err(CodecError::DecodingError), } } } #[derive(Debug, Eq, PartialEq, Hash, Clone)] pub struct ProposalID { value: Vec<u8>, } impl ProposalID { pub(crate) fn from_proposal(ciphersuite: &Ciphersuite, proposal: &Proposal) -> Self { let encoded = proposal.encode_detached().unwrap(); let value = ciphersuite.hash(&encoded); Self { value } } } impl Codec for ProposalID { fn encode(&self, buffer: &mut Vec<u8>) -> Result<(), CodecError> { encode_vec(VecSize::VecU8, buffer, &self.value)?; Ok(()) } fn decode(cursor: &mut Cursor) -> Result<Self, CodecError> { let value = decode_vec(VecSize::VecU8, cursor)?; Ok(ProposalID { value }) } } /// Alternative representation of a Proposal, where the sender is extracted from /// the encapsulating MLSPlaintext and the ProposalID is attached. #[derive(Clone)] pub struct QueuedProposal { proposal: Proposal, proposal_id: ProposalID, sender: Sender, } impl QueuedProposal { /// Creates a new `QueuedProposal` from an `MLSPlaintext` pub(crate) fn new(ciphersuite: &Ciphersuite, mls_plaintext: MLSPlaintext) -> Self { debug_assert!(mls_plaintext.content_type == ContentType::Proposal); let proposal = match mls_plaintext.content { MLSPlaintextContentType::Proposal(p) => p, _ => panic!("API misuse. Only proposals can end up in the proposal queue"), }; let proposal_id = ProposalID::from_proposal(ciphersuite, &proposal); Self { proposal, proposal_id, sender: mls_plaintext.sender, } } /// Returns the `Proposal` as a reference pub(crate) fn get_proposal_ref(&self) -> &Proposal { &self.proposal } /// Returns the `ProposalID` as a reference pub(crate) fn get_proposal_id_ref(&self) -> &ProposalID { &self.proposal_id } /// Returns the `Sender` as a reference pub(crate) fn get_sender_ref(&self) -> &Sender { &self.sender } } /// Proposal queue that helps filtering and sorting the Proposals from one /// epoch. #[derive(Default)] pub struct ProposalQueue { queued_proposals: HashMap<ProposalID, QueuedProposal>, } impl ProposalQueue { // Returns a new empty `ProposalQueue` pub(crate) fn new() -> Self { ProposalQueue { queued_proposals: HashMap::new(), } } /// Returns a new `ProposalQueue` from proposals that were committed and /// don't need filtering pub(crate) fn new_from_committed_proposals( ciphersuite: &Ciphersuite, proposals: Vec<MLSPlaintext>, ) -> Self { let mut proposal_queue = ProposalQueue::new(); for mls_plaintext in proposals { let queued_proposal = QueuedProposal::new(ciphersuite, mls_plaintext); proposal_queue.add(queued_proposal); } proposal_queue } /// Filters received proposals /// /// 11.2 Commit /// If there are multiple proposals that apply to the same leaf, /// the committer chooses one and includes only that one in the Commit, /// considering the rest invalid. The committer MUST prefer any Remove /// received, or the most recent Update for the leaf if there are no /// Removes. If there are multiple Add proposals for the same client, /// the committer again chooses one to include and considers the rest /// invalid. /// /// The function performs the following steps: /// /// - Extract Adds and filter for duplicates /// - Build member list with chains: Updates & Removes /// - Check for invalid indexes and drop proposal /// - Check for presence of Removes and delete Updates /// - Only keep the last Update /// /// Return a `ProposalQueue` a bool that indicates whether Updates for the /// own node were included pub(crate) fn filtered_proposals( ciphersuite: &Ciphersuite, proposals: Vec<MLSPlaintext>, own_index: LeafIndex, tree_size: LeafIndex, ) -> (Self, bool) { #[derive(Clone)] struct Member { updates: Vec<QueuedProposal>, removes: Vec<QueuedProposal>, } let mut members: Vec<Member> = vec![ Member { updates: vec![], removes: vec![], }; tree_size.as_usize() ]; let mut adds: HashSet<ProposalID> = HashSet::new(); let mut valid_proposals: HashSet<ProposalID> = HashSet::new(); let mut proposal_queue = ProposalQueue::new(); let mut contains_own_updates = false; // Parse proposals and build adds and member list for mls_plaintext in proposals { let queued_proposal = QueuedProposal::new(ciphersuite, mls_plaintext); match queued_proposal.proposal.get_type() { ProposalType::Add => { adds.insert(queued_proposal.get_proposal_id_ref().clone()); proposal_queue.add(queued_proposal); } ProposalType::Update => { let sender_index = queued_proposal.sender.sender.as_usize(); if sender_index != own_index.as_usize() { members[sender_index].updates.push(queued_proposal.clone()); } else { contains_own_updates = true; } proposal_queue.add(queued_proposal); } ProposalType::Remove => { let removed_index = queued_proposal.proposal.as_remove().unwrap().removed as usize; if removed_index < tree_size.as_usize() { members[removed_index].updates.push(queued_proposal.clone()); } proposal_queue.add(queued_proposal); } _ => {} } } // Check for presence of Removes and delete Updates for member in members.iter_mut() { // Check if there are Removes if !member.removes.is_empty() { // Delete all Updates when a Remove is found member.updates = Vec::new(); // Only keep the last Remove valid_proposals .insert(member.removes.last().unwrap().get_proposal_id_ref().clone()); } if !member.updates.is_empty() { // Only keep the last Update valid_proposals .insert(member.updates.last().unwrap().get_proposal_id_ref().clone()); } } // Only retain valid proposals proposal_queue.retain(|k, _| valid_proposals.get(k).is_some() || adds.get(k).is_some()); (proposal_queue, contains_own_updates) } /// Returns `true` if all `ProposalID` values from the list are contained in /// the queue pub(crate) fn contains(&self, proposal_id_list: &[ProposalID]) -> bool { for proposal_id in proposal_id_list { if !self.queued_proposals.contains_key(proposal_id) { return false; } } true } /// Add a new `QueuedProposal` to the queue pub(crate) fn add(&mut self, queued_proposal: QueuedProposal) { self.queued_proposals .entry(queued_proposal.proposal_id.clone()) .or_insert(queued_proposal); } /// Retains only the elements specified by the predicate pub(crate) fn retain<F>(&mut self, f: F) where F: FnMut(&ProposalID, &mut QueuedProposal) -> bool, { self.queued_proposals.retain(f); } /// Gets the list of all `ProposalID` pub(crate) fn get_proposal_id_list(&self) -> Vec<ProposalID> { self.queued_proposals.keys().into_iter().cloned().collect() } /// Return a list of fileterd `QueuedProposal` pub(crate) fn get_filtered_proposals( &self, proposal_id_list: &[ProposalID], proposal_type: ProposalType, ) -> Vec<&QueuedProposal> { let mut filtered_proposal_id_list = Vec::new(); for proposal_id in proposal_id_list.iter() { if let Some(queued_proposal) = self.queued_proposals.get(proposal_id) { if queued_proposal.proposal.is_type(proposal_type) { filtered_proposal_id_list.push(queued_proposal); } } } filtered_proposal_id_list } } #[derive(Debug, PartialEq, Clone)] pub struct AddProposal { pub key_package: KeyPackage, } impl Codec for AddProposal { fn encode(&self, buffer: &mut Vec<u8>) -> Result<(), CodecError> { self.key_package.encode(buffer)?; Ok(()) } fn decode(cursor: &mut Cursor) -> Result<Self, CodecError> { let key_package = KeyPackage::decode(cursor)?; Ok(AddProposal { key_package }) } } #[derive(Debug, PartialEq, Clone)] pub struct UpdateProposal { pub key_package: KeyPackage, } impl Codec for UpdateProposal { fn encode(&self, buffer: &mut Vec<u8>) -> Result<(), CodecError> { self.key_package.encode(buffer)?; Ok(()) } fn decode(cursor: &mut Cursor) -> Result<Self, CodecError> { let key_package = KeyPackage::decode(cursor)?; Ok(UpdateProposal { key_package }) } } #[derive(Debug, PartialEq, Clone)] pub struct RemoveProposal { pub removed: u32, } impl Codec for RemoveProposal { fn encode(&self, buffer: &mut Vec<u8>) -> Result<(), CodecError> { self.removed.encode(buffer)?; Ok(()) } fn decode(cursor: &mut Cursor) -> Result<Self, CodecError> { let removed = u32::decode(cursor)?; Ok(RemoveProposal { removed }) } }
true
3edb5b6de9a2f32d25af45224861f0622988fe82
Rust
jakequade/strain
/src/systems/direction.rs
UTF-8
1,042
2.890625
3
[]
no_license
use amethyst::{ core::Transform, ecs::{Entities, Join, ReadStorage, System, WriteStorage}, }; use std::f32::consts::PI; use crate::components::direction::{Direction, Directions}; // Responsible for flipping components to face the direction they are moving in. pub struct DirectionSystem; impl<'s> System<'s> for DirectionSystem { type SystemData = ( Entities<'s>, ReadStorage<'s, Direction>, WriteStorage<'s, Transform>, ); fn run(&mut self, (entities, directions, mut transforms): Self::SystemData) { for (_, direction, transform) in (&entities, &directions, &mut transforms).join() { match direction.x { None => { transform.set_rotation_y_axis(0.); }, Some(Directions::Right) => { transform.set_rotation_y_axis(0.); }, Some(Directions::Left) => { transform.set_rotation_y_axis(PI); } } } } }
true
db872332167c7964c08eb86cdf61baf735f20d73
Rust
distil/rust_meetup_ffi
/rust/asynchronous_callbacks/src/main.rs
UTF-8
707
2.84375
3
[ "Unlicense" ]
permissive
extern crate libc; use libc::c_void; struct Userdata { callback: Box<Fn(i32)>, } #[link(name = "asynchronous_callbacks")] extern { fn c_perform_task(value: i32, callback: unsafe extern "C" fn(*mut c_void, i32), userdata: *mut c_void); } unsafe extern fn callback(userdata: *mut c_void, result: i32) { (Box::from_raw(userdata as *mut Userdata).callback)(result); } fn perform_task<F: Fn(i32) + 'static>(value: i32, f: F) { let userdata = Box::into_raw(Box::new(Userdata { callback: Box::new(f) })) as *mut c_void; unsafe { c_perform_task(value, callback, userdata) } } fn main() { println!("Performing task..."); perform_task(5, |result| println!("Result: {}", result)); }
true
4c1dcd7d58fd9776a7c92aeaa4b792ebba4dc8c0
Rust
mluluz/lighthouse
/beacon_node/db/src/stores/pow_chain_store.rs
UTF-8
1,708
2.984375
3
[ "Apache-2.0" ]
permissive
use super::POW_CHAIN_DB_COLUMN as DB_COLUMN; use super::{ClientDB, DBError}; use std::sync::Arc; pub struct PoWChainStore<T> where T: ClientDB, { db: Arc<T>, } impl<T: ClientDB> PoWChainStore<T> { pub fn new(db: Arc<T>) -> Self { Self { db } } pub fn put_block_hash(&self, hash: &[u8]) -> Result<(), DBError> { self.db.put(DB_COLUMN, hash, &[0]) } pub fn block_hash_exists(&self, hash: &[u8]) -> Result<bool, DBError> { self.db.exists(DB_COLUMN, hash) } } #[cfg(test)] mod tests { extern crate types; use super::super::super::MemoryDB; use super::*; use self::types::Hash256; #[test] fn test_put_block_hash() { let db = Arc::new(MemoryDB::open()); let store = PoWChainStore::new(db.clone()); let hash = &Hash256::from([0xAA; 32]).as_bytes().to_vec(); store.put_block_hash(hash).unwrap(); assert!(db.exists(DB_COLUMN, hash).unwrap()); } #[test] fn test_block_hash_exists() { let db = Arc::new(MemoryDB::open()); let store = PoWChainStore::new(db.clone()); let hash = &Hash256::from([0xAA; 32]).as_bytes().to_vec(); db.put(DB_COLUMN, hash, &[0]).unwrap(); assert!(store.block_hash_exists(hash).unwrap()); } #[test] fn test_block_hash_does_not_exist() { let db = Arc::new(MemoryDB::open()); let store = PoWChainStore::new(db.clone()); let hash = &Hash256::from([0xAA; 32]).as_bytes().to_vec(); let other_hash = &Hash256::from([0xBB; 32]).as_bytes().to_vec(); db.put(DB_COLUMN, hash, &[0]).unwrap(); assert!(!store.block_hash_exists(other_hash).unwrap()); } }
true
b3c84c7749beac9618df80f32c143878d4efab96
Rust
cryptogarageinc/rust-cfd-cli
/src/main.rs
UTF-8
2,363
2.78125
3
[ "MIT" ]
permissive
extern crate cfd_rust; extern crate clap; extern crate hex; extern crate json; use self::cfd_rust as cfd; use cfd::{decode_raw_transaction, Network}; use clap::{App, Arg, ArgMatches, SubCommand}; use std::fs; const VERSION: &str = env!("CARGO_PKG_VERSION"); fn main() { let network_arg = Arg::with_name("network") .help("network option") .short("n") .long("network") .takes_value(true); let tx_arg = Arg::with_name("tx") .help("transaction hex") .short("t") .long("tx") .takes_value(true); let file_arg = Arg::with_name("file") .help("transaction hex file") .short("f") .long("file") .takes_value(true); let app = App::new("rust-cfd-cli") .about("cfd CLI tool") .version(VERSION) .subcommand( SubCommand::with_name("decoderawtransaction") .about("decode raw transaction data.") .arg(tx_arg.clone()) .arg(file_arg.clone()) .arg(network_arg.clone()), ); let matches = app.get_matches(); if let Some(ref matches) = matches.subcommand_matches("decoderawtransaction") { decode(matches); return; } } fn get_network(matches: &ArgMatches) -> Network { let mut network_type = Network::Mainnet; if let Some(network) = matches.value_of("network") { network_type = match network { "mainnet" => Network::Mainnet, "testnet" => Network::Testnet, "regtest" => Network::Regtest, "liquidv1" => Network::LiquidV1, "elementsregtest" => Network::ElementsRegtest, _ => Network::Mainnet, }; } network_type } fn get_tx(matches: &ArgMatches) -> String { let tx; if let Some(hex) = matches.value_of("tx") { tx = hex.to_string(); } else if let Some(file) = matches.value_of("file") { tx = fs::read_to_string(file).expect("Failed to read file."); } else { eprintln!("error: require tx or file."); panic!("error: require tx or file."); } tx } fn decode(matches: &ArgMatches) { let network_type = get_network(matches); let tx = get_tx(matches); let dec_tx_ret = decode_raw_transaction(&network_type, tx.trim()); match dec_tx_ret { Ok(dec_tx) => { let json_obj = json::parse(&dec_tx).expect("Invalid json format."); let json_str = json::stringify_pretty(json_obj, 2); println!("tx: {}", json_str) } Err(e) => eprintln!("error: {}", e), } }
true
6c78c31d7b43340b8e7fd1259ccde0236bd9beed
Rust
NLnetLabs/routinator
/src/http/ui.rs
UTF-8
2,980
2.90625
3
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown" ]
permissive
//! Handling of endpoints related to the UI. //! //! The frontend is served on BASE_DIR by including all web resources (html, //! css, js) from a single vec of structs; each struct holds a bytes array //! that represents a single file from the web resources. #![cfg(feature = "ui")] use hyper::{Body, Method, Request}; use super::response::{ContentType, Response, ResponseBuilder}; // Sensible settings for BASE_URL are either: // "/" => just route everything from the domain-name without further ado, or // "/ui" => the default prodution setting in the Vue App, this means that all // request URLs should either start with `/ui`. // // Note that this setting MUST correspond with the environment variable // VUE_APP_BASE_DIR in the Vue App (set by the .env.* files in routinator-ui). // // CATCH_ALL_URL is the path of the asset, that all unknown URLs starting with // BASE_URL will be redirected to. All other URLs will return a 404. const BASE_URL: &str = "/ui"; const CATCH_ALL_URL: &str = "index.html"; pub fn handle_get_or_head(req: &Request<Body>) -> Option<Response> { let head = *req.method() == Method::HEAD; if req.uri().path() == "/" { return Some(Response::moved_permanently("/ui/")) } let req_path = std::path::Path::new(req.uri().path()); if let Ok(p) = req_path.strip_prefix(BASE_URL) { match routinator_ui::endpoints::ui_resource(p) { Some(endpoint) => { Some(serve(head, endpoint.content, endpoint.content_type)) } None => { // In order to have the frontend handle all routing and // queryparams under BASE_URL, all unknown URLs that start // with BASE_URL will route to CATCH_ALL_URL. // // Note that we could be smarter about this and do a // (somewhat convoluted) regex on the requested URL to figure // out if it makes sense as a search prefix url. if let Some(default) = routinator_ui::endpoints::ui_resource( std::path::Path::new(CATCH_ALL_URL) ) { Some(serve(head, default.content, default.content_type)) } else { // if CATCH_ALL_URL is not defined in ui_resources // we'll return a 404 Some(Response::not_found()) } } } } else { // This is the last handler in the chain, so if the requested URL did // not start with BASE_URL, we're returning 404. Some(Response::not_found()) } } /// Creates the response from data and the content type. fn serve(head: bool, data: &'static [u8], ctype: &'static [u8]) -> Response { let res = ResponseBuilder::ok().content_type(ContentType::external(ctype)); if head { res.empty() } else { res.body(data) } }
true
983ae26df2041950bd49b2c6e805b4400a5f3bae
Rust
daniel5151/gba-rs
/src/cpu/reg.rs
UTF-8
3,448
2.671875
3
[ "MIT" ]
permissive
use std::default::Default; use std::fmt; use std::ops::{Index, IndexMut}; use serde::{Serialize, Serializer, Deserialize, Deserializer}; use serde::ser::SerializeTuple; use serde::de; use serde::de::{Visitor, SeqAccess}; use bit_util::extract; use super::mode::Mode; pub type Reg = u8; const NUM_RGSR: usize = 37; pub const SP: Reg = 13; pub const LR: Reg = 14; pub const PC: Reg = 15; pub const CPSR: Reg = 16; pub const SPSR: Reg = 17; #[cfg_attr(rustfmt, rustfmt_skip)] const REG_MAP: [[usize; 18]; 6] = [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 16], [0, 1, 2, 3, 4, 5, 6, 7, 17, 18, 19, 20, 21, 22, 23, 15, 16, 24], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 25, 26, 15, 16, 27], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 29, 15, 16, 30], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 31, 32, 15, 16, 33], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 34, 35, 15, 16, 36], ]; pub struct RegFile { reg: [u32; NUM_RGSR], bank: usize, } impl RegFile { #[inline] pub fn mode(&self) -> Mode { Mode::from_bits(extract(self.reg[CPSR as usize], 0, 5) as u8) } #[inline] pub fn update_bank(&mut self) { self.bank = self.mode().reg_bank(); } #[inline] pub fn set(&mut self, bank: usize, reg: Reg, val: u32) { self.reg[REG_MAP[bank][reg as usize]] = val; if reg == CPSR { self.update_bank() } } #[inline] pub fn get(&self, bank: usize, reg: Reg) -> u32 { self.reg[REG_MAP[bank][reg as usize]] } } impl Default for RegFile { fn default() -> RegFile { RegFile { reg: [0; NUM_RGSR], bank: 0, } } } impl Index<Reg> for RegFile { type Output = u32; #[inline] fn index(&self, idx: Reg) -> &u32 { &self.reg[REG_MAP[self.bank][idx as usize]] } } impl IndexMut<Reg> for RegFile { #[inline] fn index_mut(&mut self, idx: Reg) -> &mut u32 { &mut self.reg[REG_MAP[self.bank][idx as usize]] } } impl Serialize for RegFile { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { let mut seq = serializer.serialize_tuple(NUM_RGSR)?; for r in self.reg.iter() { seq.serialize_element(r)?; } seq.end() } } impl<'de> Deserialize<'de> for RegFile { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { struct RegVisitor; impl<'de> Visitor<'de> for RegVisitor { type Value = RegFile; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("tuple RegFile") } fn visit_seq<V: SeqAccess<'de>>(self, mut seq: V) -> Result<RegFile, V::Error> { let mut reg = RegFile { reg: [0; NUM_RGSR], bank: 0, }; for i in 0..NUM_RGSR { reg.reg[i] = seq.next_element()? .ok_or_else(|| de::Error::invalid_length(i, &self))?; } reg.update_bank(); Ok(reg) } } deserializer.deserialize_tuple(NUM_RGSR, RegVisitor) } } pub mod cpsr { use super::Reg; pub const N: Reg = 31; pub const Z: Reg = 30; pub const C: Reg = 29; pub const V: Reg = 28; pub const T: Reg = 5; }
true
87de6e6464c33a322e99cd01054b7075c5bc3f98
Rust
kyle-mccarthy/retl
/src/pipeline.rs
UTF-8
229
2.640625
3
[]
no_license
pub struct Pipeline { id: String, description: String, tasks: Vec<Task>, } pub enum TaskKind { Source, Op, Destination, } pub struct Task { id: String, description: String, kind: TaskKind, }
true
d383d8535f853feb9f3a743c5d738dab516dfcb9
Rust
diesel-rs/diesel
/diesel_compile_tests/tests/fail/derive/embed_and_serialize_as_cannot_be_mixed.rs
UTF-8
500
2.671875
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#[macro_use] extern crate diesel; table! { users (id) { id -> Integer, name -> Text, hair_color -> Text, } } #[derive(Insertable)] #[diesel(table_name = users)] struct NameAndHairColor<'a> { name: &'a str, hair_color: &'a str, } #[derive(Insertable)] struct User<'a> { id: i32, #[diesel(embed, serialize_as = SomeType)] // to test the compile error, this type doesn't need to exist name_and_hair_color: NameAndHairColor<'a>, } fn main() {}
true
0082fa729f5b12ed295374879fecffd0b4e9959a
Rust
agabopinho/rust-tests
/src/inherit.rs
UTF-8
341
3.234375
3
[]
no_license
trait Foo { fn foo(&self); } trait FooBar : Foo { fn foo_bar(&self); } struct Baz; impl FooBar for Baz { fn foo_bar(&self) { println!("call baz.foo_bar()"); } } impl Foo for Baz { fn foo(&self) { println!("call baz.foo()"); } } fn main() { let baz = Baz; baz.foo(); baz.foo_bar(); }
true
479fe2125e2db6f877b67b6a11a86fb5e3f18b5c
Rust
dchammond/mips-rs
/src/instructions/itype.rs
UTF-8
14,167
2.78125
3
[ "MIT" ]
permissive
//use crate::machine::state::State; use std::{convert::TryFrom, num::NonZeroU32}; use crate::machine::{address::Address, register::Reg}; #[derive(Clone, Debug)] pub struct ITypeImm { opcode: IInst, rs: Reg, rt: Reg, imm: u16, } #[derive(Clone, Debug)] pub struct ITypeLabel { opcode: IInst, rs: Reg, rt: Reg, label: Address, } impl ITypeImm { pub fn new(opcode: IInst, rs: Reg, rt: Reg, imm: u16) -> ITypeImm { ITypeImm { opcode, rs, rt, imm, } } /* pub fn perform(&self, state: &mut State) { let rs = state.read_reg(self.rs); let rt = state.read_reg(self.rt); let imm = u32::from(self.imm); match self.opcode { IInst::addi => state.write_reg(self.rt, i32::wrapping_add(rs as i32, imm as i32) as u32), IInst::addiu => state.write_reg(self.rt, u32::wrapping_add(rs, imm)), IInst::andi => state.write_reg(self.rt, rs & imm), IInst::beq => if rs == rt { state.jump(imm) }, IInst::bne => if rs != rt { state.jump(imm) }, IInst::lbu => state.write_reg(self.rt, state.read_mem(u32::wrapping_add(rs, imm)) & 0xFFu32), IInst::lhu => state.write_reg(self.rt, state.read_mem(u32::wrapping_add(rs, imm)) & 0xFFFFu32), IInst::ll | IInst::lw => state.write_reg(self.rt, state.read_mem(u32::wrapping_add(rs, imm))), IInst::li | IInst::la => state.write_reg(self.rt, imm), IInst::lui => state.write_reg(self.rt, imm << 16), IInst::ori => state.write_reg(self.rt, rs | imm), IInst::slti => state.write_reg(self.rt, match (rs as i32) < (imm as i32) { true => 1u32, false => 0u32 }), IInst::sltiu => state.write_reg(self.rt, match rs < imm { true => 1u32, false => 0u32 }), IInst::sb => state.write_mem(u32::wrapping_add(rs, imm), rt & 0xFFu32), IInst::sc => unimplemented!(), IInst::sh => state.write_mem(u32::wrapping_add(rs, imm), rt & 0xFFFFu32), IInst::sw => state.write_mem(u32::wrapping_add(rs, imm), rt), } } pub fn convert_to_string(&self, state: &State) -> String { let imm_str_label = match self.imm { Imm::Address(j) => state.find_label_by_addr(j), Imm::Label(l) => state.find_label_by_addr(l), Imm::Raw(_) => None, }; let imm_str = format!("0x{:08X}", u16::from(self.imm)); match self.opcode { IInst::addi | IInst::addiu | IInst::andi | IInst::ori | IInst::slti | IInst::sltiu => { format!("{} {}, {}, {}", String::from(self.opcode), String::from(self.rt), String::from(self.rs), imm_str) }, IInst::beq | IInst::bne => { let branch_imm = match imm_str_label { Some(s) => s, None => { state.find_label_by_addr(u16::from(self.imm)).unwrap() } }; format!("{} {}, {}, {}", String::from(self.opcode), String::from(self.rt), String::from(self.rs), branch_imm) }, IInst::lbu | IInst::lhu | IInst::ll | IInst::lw | IInst::sb | IInst::sh | IInst::sw => { format!("{} {}, {}({})", String::from(self.opcode), String::from(self.rt), imm_str, String::from(self.rs)) }, IInst::li | IInst::lui | IInst::la => { format!("{} {}, {}", String::from(self.opcode), String::from(self.rt), imm_str) }, IInst::sc => unimplemented!() } } pub fn convert_from_string(string: &str, state: &State) -> Option<IType> { lazy_static! { static ref I_ARITH_HEX_RE: Regex = Regex::new(r"^\s*(?P<opcode>\w+)\s*(?P<rt>\$[\w\d]+?),\s*(?P<rs>\$[\w\d]+?),\s*0x(?P<imm>[\da-fA-F]+)\s*$").unwrap(); static ref I_ARITH_DEC_RE: Regex = Regex::new(r"^\s*(?P<opcode>\w+)\s*(?P<rt>\$[\w\d]+?),\s*(?P<rs>\$[\w\d]+?),\s*(?P<imm>\d+)\s*$").unwrap(); static ref I_BRANCH_HEX_RE: Regex = Regex::new(r"^\s*(?P<opcode>\w+)\s*(?P<rt>\$[\w\d]+?),\s*(?P<rs>\$[\w\d]+?),\s*0x(?P<imm>[\da-fA-F]+)\s*$").unwrap(); static ref I_BRANCH_STR_RE: Regex = Regex::new(r"^\s*(?P<opcode>\w+)\s*(?P<rt>\$[\w\d]+?),\s*(?P<rs>\$[\w\d]+?),\s*(?P<label>\w+)\s*$").unwrap(); static ref I_MEM_HEX_RE: Regex = Regex::new(r"^\s*(?P<opcode>\w+)\s*(?P<rt>\$[\w\d]+?),\s*0x(?P<imm>[\da-fA-F]+)\((?P<rs>\$[\w\d]+?)\)\s*$").unwrap(); static ref I_MEM_DEC_RE: Regex = Regex::new(r"^\s*(?P<opcode>\w+)\s*(?P<rt>\$[\w\d]+?),\s*(?P<imm>\d+)\((?P<rs>\$[\w\d]+?)\)\s*$").unwrap(); static ref I_MEM_STR_RE: Regex = Regex::new(r"^\s*(?P<opcode>\w+)\s*(?P<rt>\$[\w\d]+?),\s*(?P<label>\w+)\((?P<rs>\$[\w\d]+?)\)\s*$").unwrap(); static ref I_IMM_HEX_RE: Regex = Regex::new(r"^\s*(?P<opcode>\w+)\s*(?P<rt>\$[\w\d]+?),\s*0x(?P<imm>[\da-fA-F]+)\s*$").unwrap(); static ref I_IMM_DEC_RE: Regex = Regex::new(r"^\s*(?P<opcode>\w+)\s*(?P<rt>\$[\w\d]+?),\s*(?P<imm>\d+)\s*$").unwrap(); static ref I_IMM_STR_RE: Regex = Regex::new(r"^\s*(?P<opcode>\w+)\s*(?P<rt>\$[\w\d]+?),\s*(?P<label>\w+)\s*$").unwrap(); } for caps in I_ARITH_HEX_RE.captures_iter(string) { return Some(IType::new(&caps["opcode"], &caps["rs"], &caps["rt"], u32::from_str_radix(&caps["imm"], 16).unwrap())); } for caps in I_ARITH_DEC_RE.captures_iter(string) { return Some(IType::new(&caps["opcode"], &caps["rs"], &caps["rt"], u32::from_str_radix(&caps["imm"], 10).unwrap())); } for caps in I_BRANCH_HEX_RE.captures_iter(string) { return Some(IType::new(&caps["opcode"], &caps["rs"], &caps["rt"], Imm::Raw(u32::from_str_radix(&caps["imm"], 16).unwrap()))); } for caps in I_BRANCH_STR_RE.captures_iter(string) { match state.find_label_by_name(&caps["label"]) { Some(a) => return Some(IType::new(&caps["opcode"], &caps["rs"], &caps["rt"], a)), None => { panic!("Unresolved label: {}", string); } } } for caps in I_MEM_HEX_RE.captures_iter(string) { return Some(IType::new(&caps["opcode"], &caps["rs"], &caps["rt"], Imm::Raw(u32::from_str_radix(&caps["imm"], 16).unwrap()))); } for caps in I_MEM_DEC_RE.captures_iter(string) { return Some(IType::new(&caps["opcode"], &caps["rs"], &caps["rt"], Imm::Raw(u32::from_str_radix(&caps["imm"], 10).unwrap()))); } for caps in I_MEM_STR_RE.captures_iter(string) { match state.find_label_by_name(&caps["label"]) { Some(a) => return Some(IType::new(&caps["opcode"], &caps["rs"], &caps["rt"], a)), None => { panic!("Unresolved label: {}", string); } } } for caps in I_IMM_HEX_RE.captures_iter(string) { return Some(IType::new(&caps["opcode"], 0u16, &caps["rt"], Imm::Raw(u32::from_str_radix(&caps["imm"], 16).unwrap()))); } for caps in I_IMM_DEC_RE.captures_iter(string) { return Some(IType::new(&caps["opcode"], 0u16, &caps["rt"], Imm::Raw(u32::from_str_radix(&caps["imm"], 10).unwrap()))); } for caps in I_IMM_STR_RE.captures_iter(string) { match state.find_label_by_name(&caps["label"]) { Some(a) => return Some(IType::new(&caps["opcode"], 0u16, &caps["rt"], a)), None => { panic!("Unresolved label: {}", string); } } } None } */ } impl ITypeLabel { pub fn new(opcode: IInst, rs: Reg, rt: Reg, label: Address) -> ITypeLabel { ITypeLabel { opcode, rs, rt, label, } } } impl From<u32> for ITypeImm { fn from(n: u32) -> ITypeImm { let opcode = IInst::from(n >> 26); let rs = Reg::from(n >> 21); let rt = Reg::from(n >> 16); let imm = (n & 0xFFFF) as u16; ITypeImm::new(opcode, rs, rt, imm) } } impl From<ITypeImm> for u32 { fn from(i: ITypeImm) -> Self { let mut x = 0u32; x |= u32::from(i.opcode) << 26; x |= u32::from(i.rs) << 21; x |= u32::from(i.rt) << 16; x |= u32::from(i.imm); x } } impl From<u32> for ITypeLabel { fn from(n: u32) -> Self { let opcode = IInst::from(n >> 26); let rs = Reg::from(n >> 21); let rt = Reg::from(n >> 16); let addr_raw = n & 0xFFFF; if addr_raw == 0 { panic!( "Cannot convert 0x{:08X} into ITypeLabel because immediate is 0", n ); } let addr; unsafe { addr = Address::new(Some(NonZeroU32::new_unchecked(addr_raw)), None); } ITypeLabel::new(opcode, rs, rt, addr) } } impl TryFrom<ITypeLabel> for u32 { type Error = String; fn try_from(i: ITypeLabel) -> Result<Self, Self::Error> { match i.label.numeric { Some(nz) => { let mut x = 0u32; x |= u32::from(i.opcode) << 26; x |= u32::from(i.rs) << 21; x |= u32::from(i.rt) << 16; x |= nz.get() & 0xFFFF; Ok(x) } None => Err(format!( "Cannot convert ITypeLabel to u32, immediate is {:#?}", i.label )), } } } #[allow(non_camel_case_types)] #[derive(Copy, Clone, Debug)] pub enum IInst { addi, addiu, andi, beq, bne, lbu, lhu, ll, li, la, lui, lw, ori, slti, sltiu, sb, sc, sh, sw, } impl From<IInst> for String { fn from(i: IInst) -> String { match i { IInst::addi => "addi", IInst::addiu => "addiu", IInst::andi => "andi", IInst::beq => "beq", IInst::bne => "bne", IInst::lbu => "lbu", IInst::lhu => "lhu", IInst::ll => "ll", IInst::li => "li", IInst::la => "la", IInst::lui => "lui", IInst::lw => "lw", IInst::ori => "ori", IInst::slti => "slti", IInst::sltiu => "sltiu", IInst::sb => "sb", IInst::sc => "sc", IInst::sh => "sh", IInst::sw => "sw", } .to_owned() } } impl From<&str> for IInst { fn from(s: &str) -> IInst { match s.to_lowercase().as_ref() { "addi" => IInst::addi, "addiu" => IInst::addiu, "andi" => IInst::andi, "beq" => IInst::beq, "bne" => IInst::bne, "lbu" => IInst::lbu, "lhu" => IInst::lhu, "ll" => IInst::ll, "li" => IInst::li, "la" => IInst::la, "lui" => IInst::lui, "lw" => IInst::lw, "ori" => IInst::ori, "slti" => IInst::slti, "sltiu" => IInst::sltiu, "sb" => IInst::sb, "sc" => IInst::sc, "sh" => IInst::sh, "sw" => IInst::sw, _ => panic!("No such IType: {}", s), } } } macro_rules! iinst_map { ($type_name: ty) => { impl From<$type_name> for IInst { fn from(num: $type_name) -> Self { match num & 0x3F { 0x08 => IInst::addi, 0x09 => IInst::addiu, 0x0C => IInst::andi, 0x04 => IInst::beq, 0x05 => IInst::bne, 0x24 => IInst::lbu, 0x25 => IInst::lhu, 0x30 => IInst::ll, 0x3F => IInst::li, 0x01 => IInst::la, 0x0F => IInst::lui, 0x23 => IInst::lw, 0x0D => IInst::ori, 0x0A => IInst::slti, 0x0B => IInst::sltiu, 0x28 => IInst::sb, 0x38 => IInst::sc, 0x29 => IInst::sh, 0x2B => IInst::sw, _ => panic!("No match for IType op-code: 0x{:08X}", num), } } } }; } macro_rules! iinst_inv_map { ($type_name: ty) => { impl From<IInst> for $type_name { fn from(i: IInst) -> Self { match i { IInst::addi => 0x08, IInst::addiu => 0x09, IInst::andi => 0x0C, IInst::beq => 0x04, IInst::bne => 0x05, IInst::lbu => 0x24, IInst::lhu => 0x25, IInst::ll => 0x30, IInst::li => 0x3F, IInst::la => 0x01, IInst::lui => 0x0F, IInst::lw => 0x23, IInst::ori => 0x0D, IInst::slti => 0x0A, IInst::sltiu => 0x0B, IInst::sb => 0x28, IInst::sc => 0x38, IInst::sh => 0x29, IInst::sw => 0x2B, } } } }; } iinst_map!(u8); iinst_map!(u16); iinst_map!(u32); iinst_map!(u64); iinst_map!(u128); iinst_map!(i8); iinst_map!(i16); iinst_map!(i32); iinst_map!(i64); iinst_map!(i128); iinst_inv_map!(u8); iinst_inv_map!(u16); iinst_inv_map!(u32); iinst_inv_map!(u64); iinst_inv_map!(u128); iinst_inv_map!(i8); iinst_inv_map!(i16); iinst_inv_map!(i32); iinst_inv_map!(i64); iinst_inv_map!(i128);
true
ef9005d7b84d4007d016758f69cf0faf1e0c6af0
Rust
psychon/x11rb
/x11rb/src/extension_manager.rs
UTF-8
12,414
2.828125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
//! Helper for implementing `RequestConnection::extension_information()`. use std::collections::{hash_map::Entry as HashMapEntry, HashMap}; use crate::connection::RequestConnection; use crate::cookie::Cookie; use crate::errors::{ConnectionError, ReplyError}; use crate::protocol::xproto::{ConnectionExt, QueryExtensionReply}; use crate::x11_utils::{ExtInfoProvider, ExtensionInformation}; use x11rb_protocol::SequenceNumber; /// Helper for implementing `RequestConnection::extension_information()`. /// /// This helps with implementing `RequestConnection`. Most likely, you do not need this in your own /// code, unless you really want to implement your own X11 connection. #[derive(Debug, Default)] pub struct ExtensionManager(HashMap<&'static str, CheckState>); #[derive(Debug)] enum CheckState { Prefetched(SequenceNumber), Present(ExtensionInformation), Missing, Error, } impl ExtensionManager { /// If the extension has not prefetched yet, sends a `QueryExtension` /// requests, adds a field to the hash map and returns a reference to it. fn prefetch_extension_information_aux<C: RequestConnection>( &mut self, conn: &C, extension_name: &'static str, ) -> Result<&mut CheckState, ConnectionError> { match self.0.entry(extension_name) { // Extension already checked, return the cached value HashMapEntry::Occupied(entry) => Ok(entry.into_mut()), HashMapEntry::Vacant(entry) => { crate::debug!( "Prefetching information about '{}' extension", extension_name ); let cookie = conn.query_extension(extension_name.as_bytes())?; Ok(entry.insert(CheckState::Prefetched(cookie.into_sequence_number()))) } } } /// Prefetchs an extension sending a `QueryExtension` without waiting for /// the reply. pub fn prefetch_extension_information<C: RequestConnection>( &mut self, conn: &C, extension_name: &'static str, ) -> Result<(), ConnectionError> { // We are not interested on the reference to the entry. let _ = self.prefetch_extension_information_aux(conn, extension_name)?; Ok(()) } /// Insert an extension if you already have the information. pub fn insert_extension_information( &mut self, extension_name: &'static str, info: Option<ExtensionInformation>, ) { crate::debug!( "Inserting '{}' extension information directly: {:?}", extension_name, info ); let state = match info { Some(info) => CheckState::Present(info), None => CheckState::Missing, }; let _ = self.0.insert(extension_name, state); } /// An implementation of `RequestConnection::extension_information()`. /// /// The given connection is used for sending a `QueryExtension` request if needed. pub fn extension_information<C: RequestConnection>( &mut self, conn: &C, extension_name: &'static str, ) -> Result<Option<ExtensionInformation>, ConnectionError> { let _guard = crate::debug_span!("extension_information", extension_name).entered(); let entry = self.prefetch_extension_information_aux(conn, extension_name)?; match entry { CheckState::Prefetched(sequence_number) => { crate::debug!( "Waiting for QueryInfo reply for '{}' extension", extension_name ); match Cookie::<C, QueryExtensionReply>::new(conn, *sequence_number).reply() { Err(err) => { crate::warning!( "Got error {:?} for QueryInfo reply for '{}' extension", err, extension_name ); *entry = CheckState::Error; match err { ReplyError::ConnectionError(e) => Err(e), // The X11 protocol specification does not specify any error // for the QueryExtension request, so this should not happen. ReplyError::X11Error(_) => Err(ConnectionError::UnknownError), } } Ok(info) => { if info.present { let info = ExtensionInformation { major_opcode: info.major_opcode, first_event: info.first_event, first_error: info.first_error, }; crate::debug!("Extension '{}' is present: {:?}", extension_name, info); *entry = CheckState::Present(info); Ok(Some(info)) } else { crate::debug!("Extension '{}' is not present", extension_name); *entry = CheckState::Missing; Ok(None) } } } } CheckState::Present(info) => Ok(Some(*info)), CheckState::Missing => Ok(None), CheckState::Error => Err(ConnectionError::UnknownError), } } } impl ExtInfoProvider for ExtensionManager { fn get_from_major_opcode(&self, major_opcode: u8) -> Option<(&str, ExtensionInformation)> { self.0 .iter() .filter_map(|(name, state)| { if let CheckState::Present(info) = state { Some((*name, *info)) } else { None } }) .find(|(_, info)| info.major_opcode == major_opcode) } fn get_from_event_code(&self, event_code: u8) -> Option<(&str, ExtensionInformation)> { self.0 .iter() .filter_map(|(name, state)| { if let CheckState::Present(info) = state { if info.first_event <= event_code { Some((*name, *info)) } else { None } } else { None } }) .max_by_key(|(_, info)| info.first_event) } fn get_from_error_code(&self, error_code: u8) -> Option<(&str, ExtensionInformation)> { self.0 .iter() .filter_map(|(name, state)| { if let CheckState::Present(info) = state { if info.first_error <= error_code { Some((*name, *info)) } else { None } } else { None } }) .max_by_key(|(_, info)| info.first_error) } } #[cfg(test)] mod test { use std::cell::RefCell; use std::io::IoSlice; use crate::connection::{BufWithFds, ReplyOrError, RequestConnection, RequestKind}; use crate::cookie::{Cookie, CookieWithFds, VoidCookie}; use crate::errors::{ConnectionError, ParseError}; use crate::utils::RawFdContainer; use crate::x11_utils::{ExtInfoProvider, ExtensionInformation, TryParse, TryParseFd}; use x11rb_protocol::{DiscardMode, SequenceNumber}; use super::{CheckState, ExtensionManager}; struct FakeConnection(RefCell<SequenceNumber>); impl RequestConnection for FakeConnection { type Buf = Vec<u8>; fn send_request_with_reply<R>( &self, _bufs: &[IoSlice<'_>], _fds: Vec<RawFdContainer>, ) -> Result<Cookie<'_, Self, R>, ConnectionError> where R: TryParse, { Ok(Cookie::new(self, 1)) } fn send_request_with_reply_with_fds<R>( &self, _bufs: &[IoSlice<'_>], _fds: Vec<RawFdContainer>, ) -> Result<CookieWithFds<'_, Self, R>, ConnectionError> where R: TryParseFd, { unimplemented!() } fn send_request_without_reply( &self, _bufs: &[IoSlice<'_>], _fds: Vec<RawFdContainer>, ) -> Result<VoidCookie<'_, Self>, ConnectionError> { unimplemented!() } fn discard_reply(&self, _sequence: SequenceNumber, _kind: RequestKind, _mode: DiscardMode) { unimplemented!() } fn prefetch_extension_information( &self, _extension_name: &'static str, ) -> Result<(), ConnectionError> { unimplemented!(); } fn extension_information( &self, _extension_name: &'static str, ) -> Result<Option<ExtensionInformation>, ConnectionError> { unimplemented!() } fn wait_for_reply_or_raw_error( &self, sequence: SequenceNumber, ) -> Result<ReplyOrError<Vec<u8>>, ConnectionError> { // Code should only ask once for the reply to a request. Check that this is the case // (by requiring monotonically increasing sequence numbers here). let mut last = self.0.borrow_mut(); assert!( *last < sequence, "Last sequence number that was awaited was {}, but now {}", *last, sequence ); *last = sequence; // Then return an error, because that's what the #[test] below needs. Err(ConnectionError::UnknownError) } fn wait_for_reply( &self, _sequence: SequenceNumber, ) -> Result<Option<Vec<u8>>, ConnectionError> { unimplemented!() } fn wait_for_reply_with_fds_raw( &self, _sequence: SequenceNumber, ) -> Result<ReplyOrError<BufWithFds<Vec<u8>>, Vec<u8>>, ConnectionError> { unimplemented!() } fn check_for_raw_error( &self, _sequence: SequenceNumber, ) -> Result<Option<Vec<u8>>, ConnectionError> { unimplemented!() } fn maximum_request_bytes(&self) -> usize { 0 } fn prefetch_maximum_request_bytes(&self) { unimplemented!() } fn parse_error(&self, _error: &[u8]) -> Result<crate::x11_utils::X11Error, ParseError> { unimplemented!() } fn parse_event(&self, _event: &[u8]) -> Result<crate::protocol::Event, ParseError> { unimplemented!() } } #[test] fn test_double_await() { let conn = FakeConnection(RefCell::new(0)); let mut ext_info = ExtensionManager::default(); // Ask for an extension info. FakeConnection will return an error. match ext_info.extension_information(&conn, "whatever") { Err(ConnectionError::UnknownError) => {} r => panic!("Unexpected result: {:?}", r), } // Ask again for the extension information. ExtensionInformation should not try to get the // reply again, because that would just hang. Once upon a time, this caused a hang. match ext_info.extension_information(&conn, "whatever") { Err(ConnectionError::UnknownError) => {} r => panic!("Unexpected result: {:?}", r), } } #[test] fn test_info_provider() { let info = ExtensionInformation { major_opcode: 4, first_event: 5, first_error: 6, }; let mut ext_info = ExtensionManager::default(); let _ = ext_info.0.insert("prefetched", CheckState::Prefetched(42)); let _ = ext_info.0.insert("present", CheckState::Present(info)); let _ = ext_info.0.insert("missing", CheckState::Missing); let _ = ext_info.0.insert("error", CheckState::Error); assert_eq!(ext_info.get_from_major_opcode(4), Some(("present", info))); assert_eq!(ext_info.get_from_event_code(5), Some(("present", info))); assert_eq!(ext_info.get_from_error_code(6), Some(("present", info))); } }
true
1f085e62b394811220ae3cd2bd2d6b343bc63ab6
Rust
dashscript/dashscript
/core/src/runtime/core/methods.rs
UTF-8
26,489
3
3
[]
no_license
macro_rules! methods { ($self:expr, {$($key:expr => $value:expr,)+}) => {{ $($self.insert(TinyString::new($key.as_bytes()), $value);)+ }}; } pub mod iterator { use crate::{Vm, Value, TinyString, ValueIter}; use crate::runtime::core::map_builder::MapBuilder; pub fn init(vm: &mut Vm) { methods!(vm.iterator_methods, { "clone" => |vm, iterator, _, _| Ok(Value::Iterator(vm.allocate_with(iterator.clone()))), "current" => |_, iterator, _, _| Ok(iterator.current()), "next" => |_, iterator, _, _| Ok( match iterator.next() { Some(value) => value, None => Value::Null } ), }); let mut iterator_object = MapBuilder::new(vm); iterator_object.native_fn("empty", |vm, _| { Ok(Value::Iterator(vm.allocate_with(ValueIter::default()))) }); iterator_object.native_fn("from", |vm, args| { let iter = match args.get(0) { Some(value) => vm.iter_value(*value), None => Value::Iterator(vm.allocate_with(ValueIter::default())) }; Ok(iter) }); let iterator = Value::Dict(iterator_object.allocate_with()); vm.add_global("Iterator", iterator); } } pub mod string { use std::ops::Deref; use crate::{Vm, Value, TinyString}; use crate::runtime::core::map_builder::MapBuilder; pub fn init(vm: &mut Vm) { methods!(vm.string_methods, { "len" => |_, string, _, _| Ok(Value::Int(string.len() as isize)), "isEmpty" => |_, string, _, _| Ok(Value::Bool(string.len() == 0)), "toLowerCase" => |vm, string, _, _| Ok(Value::String(vm.allocate_string(string.deref().to_lowercase()))), "toUpperCase" => |vm, string, _, _| Ok(Value::String(vm.allocate_string(string.deref().to_uppercase()))), "trim" => |vm, string, _, _| Ok(Value::String(vm.allocate_static_str(string.deref().trim()))), "trimStart" => |vm, string, _, _| Ok(Value::String(vm.allocate_static_str(string.deref().trim_start()))), "trimEnd" => |vm, string, _, _| Ok(Value::String(vm.allocate_static_str(string.deref().trim_end()))), "charCodeAt" => |_, string, _, args| Ok( match args.get(0) { Some(&Value::Int(index)) if index >= 0 => { match string.char_code_at(index as usize) { Some(code) => Value::Int(code as isize), None => Value::Null } }, _ => Value::Null } ), "charCount" => |_, string, _, _| { let mut count = 0; for _ in string.chars() { count += 1; } Ok(Value::Int(count)) }, "endsWith" => |_, string, _, args| Ok(Value::Bool( match args.get(0) { Some(Value::String(a)) => string.deref().ends_with(a.unwrap_ref() as &str), _ => false } )), "startsWith" => |_, string, _, args| Ok(Value::Bool( match args.get(0) { Some(&Value::String(a)) => string.deref().starts_with(a.unwrap_ref() as &str), _ => false } )), "split" => |vm, string, _, args| Ok( match args.get(0) { Some(&Value::String(a)) => { let mut result = Vec::new(); for item in string.deref().split(a.unwrap_ref() as &str) { result.push(Value::String(vm.allocate_static_str(item))); } Value::Array(vm.allocate_with(result)) }, _ => Value::Null } ), "includes" => |_, string, _, args| Ok(Value::Bool( match args.get(0) { Some(&Value::String(a)) => string.deref().contains(a.unwrap_ref() as &str), _ => false } )), "repeat" => |vm, string, _, args| Ok( match args.get(0) { Some(times) => Value::String(vm.allocate_string(string.deref().repeat(times.to_usize()))), _ => Value::Null } ), "slice" => |vm, string, _, args| Ok( match args.get(0..2) { Some(&[start, end]) => { match string.deref().get(start.to_usize()..end.to_usize()) { Some(string) => Value::String(vm.allocate_string_bytes(string.as_bytes())), None => Value::Null } }, _ => Value::Null } ), "toBytes" => |vm, string, _, _| { let mut bytes = Vec::new(); for byte in string.to_bytes() { bytes.push(Value::Int(*byte as isize)); } Ok(Value::Array(vm.allocate_with(bytes))) }, }); let mut string_object = MapBuilder::new(vm); let replacement_str = Value::String(string_object.vm.allocate_static_str(std::char::REPLACEMENT_CHARACTER.encode_utf8(&mut [0; 4]))); string_object.constant("REPLACEMENT", replacement_str); string_object.native_fn("from", |vm, args| { let string = format!("{}", match args.get(0) { Some(value) => *value, None => Value::Null }); Ok(Value::String(vm.allocate_string(string))) }); string_object.native_fn("fromCharCode", |vm, args| Ok( match args.get(0) { Some(value) => { match std::char::from_u32(value.to_u32()) { Some(char_) => Value::String(vm.allocate_with(TinyString::new(char_.encode_utf8(&mut [0; 4]).as_bytes()))), None => Value::Null } }, None => Value::Null } )); let string = Value::Dict(string_object.allocate_with()); vm.add_global("String", string) } } pub mod boolean { use crate::{Vm, Value}; use crate::runtime::core::map_builder::MapBuilder; pub fn init(vm: &mut Vm) { let mut boolean_object = MapBuilder::new(vm); boolean_object.native_fn("from", |_, args| Ok(Value::Bool( match args.get(0) { Some(value) => value.to_bool(), None => false } ))); let boolean = Value::Dict(boolean_object.allocate_with()); vm.add_global("Boolean", boolean); } } pub mod object { use crate::{Vm, Value, RuntimeError, Map}; use crate::runtime::core::map_builder::MapBuilder; pub fn init(vm: &mut Vm) { let mut object_ = MapBuilder::new(vm); object_.native_fn("create", |vm, args| Ok( match args.get(0) { Some(Value::Dict(ptr)) => { let mut object = Map::with_capacity(1); object.insert(vm.constants.prototype, (Value::Dict(*ptr), true)); Value::Dict(vm.allocate_with(object)) }, _ => return Err(RuntimeError::new(vm, "[Object.create]: Expected (object) arguments.")) } )); object_.native_fn("defineProperty", |vm, args| { match args.get(0..3) { Some(&[Value::Dict(ptr), key, value]) => { if let Some((_, true)) = ptr.unwrap_mut().insert(key, (value, false)) { return Err(RuntimeError::new_uncatchable(vm, format!("[Object.defineReadonlyProperty]: The key {:?} is private to assign.", key))) } }, Some(&[Value::Instance(ptr), key, value]) => { if let Some((_, true)) = ptr.unwrap_map_mut().insert(key, (value, false)) { return Err(RuntimeError::new_uncatchable(vm, format!("[Object.defineReadonlyProperty]: The key {:?} is private to assign.", key))) } }, _ => () } Ok(Value::Null) }); object_.native_fn("defineReadonlyProperty", |vm, args| { match args.get(0..3) { Some(&[Value::Dict(ptr), key, value]) => { if let Some((_, true)) = ptr.unwrap_mut().insert(key, (value, true)) { return Err(RuntimeError::new_uncatchable(vm, format!("[Object.defineReadonlyProperty]: The key {:?} is private to assign.", key))) } }, Some(&[Value::Instance(ptr), key, value]) => { if let Some((_, true)) = ptr.unwrap_map_mut().insert(key, (value, true)) { return Err(RuntimeError::new_uncatchable(vm, format!("[Object.defineReadonlyProperty]: The key {:?} is private to assign.", key))) } }, _ => () } Ok(Value::Null) }); object_.native_fn("convertIntoReadonlyObject", |_, args| Ok( match args.get(0) { Some(Value::Dict(ptr)) => { for (_, value) in ptr.unwrap_mut() { *value = (value.0, true); } Value::Dict(*ptr) }, Some(Value::Instance(ptr)) => { for (_, value) in ptr.unwrap_map_mut() { *value = (value.0, true); } Value::Instance(*ptr) }, _ => Value::Null } )); object_.native_fn("entries", |vm, args| Ok( match args.get(0) { Some(Value::Dict(ptr)) => { let mut entries = Vec::new(); for (key, value) in ptr.unwrap_ref() { entries.push(Value::Array(vm.allocate_with(vec![*key, value.0]))) } Value::Array(vm.allocate_with(entries)) }, Some(Value::Instance(ptr)) => { let mut entries = Vec::new(); for (key, value) in ptr.unwrap_map() { entries.push(Value::Array(vm.allocate_with(vec![*key, value.0]))) } Value::Array(vm.allocate_with(entries)) }, _ => Value::Null } )); object_.native_fn("keys", |vm, args| Ok( match args.get(0) { Some(Value::Dict(ptr)) => { let mut keys = Vec::new(); for (key, _) in ptr.unwrap_ref() { keys.push(*key); } Value::Array(vm.allocate_with(keys)) }, Some(Value::Instance(ptr)) => { let mut keys = Vec::new(); for (key, _) in ptr.unwrap_map() { keys.push(*key); } Value::Array(vm.allocate_with(keys)) }, _ => Value::Null } )); object_.native_fn("values", |vm, args| Ok( match args.get(0) { Some(Value::Dict(ptr)) => { let mut values = Vec::new(); for (_, (value, _)) in ptr.unwrap_ref() { values.push(*value); } Value::Array(vm.allocate_with(values)) }, Some(Value::Instance(ptr)) => { let mut values = Vec::new(); for (_, (value, _)) in ptr.unwrap_map() { values.push(*value); } Value::Array(vm.allocate_with(values)) }, _ => Value::Null } )); object_.native_fn("remove", |vm, args| { match args.get(0) { Some(Value::Dict(ptr)) => { let map = ptr.unwrap_mut(); for key in args.get(1..).unwrap() { map.remove(key); } Ok(Value::Null) }, Some(Value::Instance(ptr)) => { let map = ptr.unwrap_map_mut(); for key in args.get(1..).unwrap() { map.remove(key); } Ok(Value::Null) }, _ => return Err(RuntimeError::new(vm, "[Object.remove]: Expected (object, ..keys) arguments.")) } }); object_.native_fn("clone", |vm, args| Ok( match args.get(0) { Some(Value::Dict(ptr)) => Value::Dict(vm.allocate_with(ptr.unwrap())), Some(Value::Instance(ptr)) => Value::Instance(vm.allocate_with(ptr.unwrap())), _ => Value::Null } )); object_.native_fn("instanceOf", |vm, args| Ok(Value::Bool( match args.get(0..2) { Some([Value::Instance(instance), Value::Dict(ptr)]) => { match ptr.unwrap_ref().get(&vm.constants.prototype) { Some((Value::Dict(ptr), _)) => instance.unwrap_ref().methods.0 == ptr.0, _ => false } }, _ => false } ))); object_.native_fn("isInstanceObject", |_, args| { Ok(Value::Bool(matches!(args.get(0), Some(Value::Instance(_))))) }); object_.native_fn("getPrototypeOf", |_, args| Ok( match args.get(0) { Some(Value::Instance(ptr)) => Value::Dict(ptr.unwrap_ref().methods), _ => Value::Null } )); object_.native_fn("setPrototypeOf", |_, args| { if let Some([Value::Instance(ptr), Value::Dict(proto)]) = args.get(0..2) { ptr.unwrap_mut().methods = *proto; } Ok(Value::Null) }); let object = Value::Dict(object_.allocate_with()); vm.add_global("Object", object); } } pub mod function { use crate::{Vm, Value, NativeFunction, TinyString}; use crate::runtime::core::map_builder::MapBuilder; pub fn init(vm: &mut Vm) { let mut function_object = MapBuilder::new(vm); let noop = function_object.vm.allocate_with(NativeFunction { func: |_, _| Ok(Value::Null), name: TinyString::new(b"noop") }); function_object.constant("noop", Value::NativeFn(noop)); function_object.native_fn("getName", |vm, args| { let name = match args.get(0) { Some(Value::Function(ptr)) => ptr.unwrap_ref().name.to_bytes(), Some(Value::NativeFn(ptr)) => ptr.unwrap_ref().name.to_bytes(), _ => return Ok(Value::Null) }; Ok(Value::String(vm.allocate_string_bytes(name))) }); function_object.native_fn("isNative", |_, args| Ok(Value::Bool( match args.get(0) { Some(Value::NativeFn(_)) => true, _ => false } ))); let function = Value::Dict(function_object.allocate_with()); vm.add_global("Function", function); } } pub mod array { use crate::{Vm, Value, TinyString, ValuePtr}; use crate::runtime::core::map_builder::MapBuilder; fn ptr_as_value_array(ptr: *const u8) -> Value { Value::Array(ValuePtr::new_unchecked(ptr)) } pub fn init(vm: &mut Vm) { methods!(vm.array_methods, { "len" => |_, array, _, _| Ok(Value::Int(array.len() as isize)), "clone" => |vm, array, _, _| Ok(Value::Array(vm.allocate_with(array.clone()))), "isEmpty" => |_, array, _, _| Ok(Value::Bool(array.len() == 0)), "concat" => |vm, array, ptr, args| Ok( match args.get(0) { Some(Value::Array(ptr)) => { let mut array = array.clone(); array.extend(ptr.unwrap_ref()); Value::Array(vm.allocate_with(array)) }, _ => ptr_as_value_array(ptr) } ), "extend" => |_, array, ptr, args| { array.extend_from_slice(args); Ok(ptr_as_value_array(ptr)) }, "extendFromArray" => |_, array, ptr, args| { match args.get(0) { Some(Value::Array(ptr)) => array.extend(ptr.unwrap_ref()), _ => () } Ok(ptr_as_value_array(ptr)) }, "forEach" => |vm, array, _, args| { let mut index = 0; let function = match args.get(0) { Some(value) => *value, None => return Ok(Value::Null) }; for item in array.iter() { vm.fiber.stack.extend_from_slice(&[*item, Value::Int(index)]); if let Err(error) = vm.call_function_with_returned_value(function, 2) { return Err(error); } index += 1; } Ok(Value::Null) }, "filter" => |vm, array, _, args| { let mut index = 0; let mut values = Vec::new(); let function = match args.get(0) { Some(value) => *value, None => return Ok(Value::Null) }; for &item in array.iter() { vm.fiber.stack.extend_from_slice(&[item, Value::Int(index)]); match vm.call_function_with_returned_value(function, 2) { Ok(value) => values.push(value), Err(error) => return Err(error) } index += 1; } Ok(Value::Array(vm.allocate_with(values))) }, "find" => |vm, array, _, args| { let mut index = 0; let function = match args.get(0) { Some(value) => *value, None => return Ok(Value::Null) }; for &item in array.iter() { vm.fiber.stack.extend_from_slice(&[item, Value::Int(index)]); match vm.call_function_with_returned_value(function, 2) { Ok(value) => { if value.to_bool() { return Ok(item); } }, Err(error) => return Err(error) } index += 1; } Ok(Value::Null) }, "findIndex" => |vm, array, _, args| { let mut index = 0; let function = match args.get(0) { Some(value) => *value, None => return Ok(Value::Null) }; for &item in array.iter() { vm.fiber.stack.extend_from_slice(&[item, Value::Int(index)]); match vm.call_function_with_returned_value(function, 2) { Ok(value) => { if value.to_bool() { return Ok(Value::Int(index)) } }, Err(error) => return Err(error) } index += 1; } Ok(Value::Int(-1)) }, "includes" => |_, array, _, args| { let value = match args.get(0) { Some(value) => *value, None => return Ok(Value::Null) }; for item in array.iter() { if *item == value { return Ok(Value::Bool(true)); } } Ok(Value::Bool(false)) }, "indexOf" => |_, array, _, args| { let mut index = 0; let value = match args.get(0) { Some(value) => *value, None => return Ok(Value::Null) }; for item in array.iter() { if *item == value { return Ok(Value::Int(index)); } index += 1; } Ok(Value::Int(-1)) }, "lastIndexOf" => |_, array, _, args| { let mut index = 0; let mut result = -1; let value = match args.get(0) { Some(value) => *value, None => return Ok(Value::Null) }; for item in array.iter() { if *item == value { result = index; } index += 1; } Ok(Value::Int(result)) }, "join" => |vm, array, _, args| { let seperator = match args.get(0) { Some(Value::String(ptr)) if array.len() != 0 => ptr.unwrap_bytes(), _ => return Ok(Value::String(vm.allocate_string_bytes(&[]))) }; let mut bytes = Vec::new(); let mut index = 0; let li = array.len() - 1; for item in array.iter() { bytes.extend_from_slice(format!("{}", item).as_bytes()); bytes.extend_from_slice(seperator); if index == li { break } index += 1; } Ok(Value::String(vm.allocate_string_bytes(bytes.as_slice()))) }, "map" => |vm, array, _, args| { let mut index = 0; let mut result = Vec::new(); let function = match args.get(0) { Some(value) => *value, None => return Ok(Value::Null) }; for &item in array.iter() { vm.fiber.stack.extend_from_slice(&[item, Value::Int(index)]); match vm.call_function_with_returned_value(function, 2) { Ok(value) => result.push(value), Err(error) => return Err(error) } index += 1; } Ok(Value::Array(vm.allocate_with(result))) }, "pop" => |_, array, _, _| { Ok(array.pop().unwrap_or(Value::Null)) }, "push" => |_, array, _, args| { let value = match args.get(0) { Some(value) => *value, None => Value::Null }; array.push(value); Ok(value) }, "reverse" => |_, array, ptr, _| { array.reverse(); Ok(ptr_as_value_array(ptr)) }, "resize" => |_, array, ptr, args| { array.resize_with(match args.get(0) { Some(&Value::Int(int)) if int >= 0 => int as usize, Some(&Value::Float(float)) if float >= 0.0 => float as usize, _ => 0 }, || Value::Null); Ok(ptr_as_value_array(ptr)) }, "remove" => |_, array, ptr, args| { array.remove(match args.get(0) { Some(&Value::Int(int)) if int >= 0 => int as usize, Some(&Value::Float(float)) if float >= 0.0 => float as usize, _ => 0 }); Ok(ptr_as_value_array(ptr)) }, }); let mut array_object = MapBuilder::new(vm); array_object.native_fn("from", |vm, args| Ok(Value::Array( match args.get(0) { Some(Value::Array(ptr)) => *ptr, Some(Value::String(ptr)) => { let mut chars = Vec::new(); for u32_ in ptr.unwrap_ref().chars() { let char_ = match std::char::from_u32(u32_) { Some(character) => character, None => std::char::REPLACEMENT_CHARACTER }; chars.push(Value::String(vm.allocate_static_str(char_.encode_utf8(&mut [0; 4])))); } vm.allocate_with(chars) }, Some(Value::Iterator(ptr)) => { let mut items = Vec::new(); let iter = ptr.unwrap_mut(); while let Some(item) = iter.next() { items.push(item); } vm.allocate_with(items) }, _ => vm.allocate_with(Vec::new()) } ))); array_object.native_fn("of", |vm, args| { let cap = match args.get(0) { Some(&Value::Int(int)) if int >= 0 => int as usize, Some(&Value::Float(float)) if float >= 0.0 => float as usize, _ => 0 }; let mut array = Vec::with_capacity(cap); array.resize_with(cap, || Value::Null); Ok(Value::Array(vm.allocate_with(array))) }); let array = Value::Dict(array_object.allocate_with()); vm.add_global("Array", array); } }
true
cdd9b08ab4cab843607348a748b4ffcf24015d90
Rust
hsyang1222/rust_example_code
/example1_3/Exercises/JIS's problem/JIS.rs
UTF-8
813
3.5625
4
[]
no_license
/* 정인수 코딩 문제 서울대학교에 다니고 있는 현식이는 돈을 많이 주는 과외 학생만 받아서 과외를 하고 싶다. 10명의 과외비를 입력하고 과외비를 5만원 이상 주는 학생이 몇 명인지 답을 출력하는 프로그램를 작성하라. 입력 값 타입: 정수형 / 출력 값 타입: 정수형 참조 : https://doc.rust-lang.org/std/string/struct.String.html#method.parse */ use std::io; fn main() { let mut count = 0; for i in 1..11 { let mut input = String::new(); io::stdin().read_line(&mut input).expect("Failed to read line"); let input: u32 = input.trim().parse().expect("Please type a number"); if input >= 50000 { count += 1; } } println!("{} people", count); }
true
12f87f05eb834d44632ab14d4ced21e0f1c1ee40
Rust
jamuc/rust
/shadowing/shadowing.rs
UTF-8
230
3.453125
3
[]
no_license
/* * Variables are immutable by default. However you can use let * statement to "shadow" variables in Rust. */ fn main() { let x = 5; let x = x + 1; let x = x * 5; println!("This is variable shadowing, x is: {}", x); }
true
18d02312c44d99561e11116191f6d94ca27e7b54
Rust
euclio/editor
/src/ui.rs
UTF-8
1,096
3.296875
3
[]
no_license
//! Traits and types for drawing to an abstracted screen. use euclid::{Box2D, Point2D, Size2D}; /// Used to group units that deal with the screen. pub struct ScreenSpace; /// The XY coordinates of a cell on the screen, starting from (0, 0) at the top left. The /// Y-coordinate is the row, and the X-coordinate is the column. pub type Coordinates = Point2D<u16, ScreenSpace>; /// A width and height on the screen, in cells. pub type Size = Size2D<u16, ScreenSpace>; /// A bounding rectangle on the screen, in cells. /// /// This rectangle is endpoint-exclusive. pub type Bounds = Box2D<u16, ScreenSpace>; mod color; mod screen; pub use color::Color; pub use screen::Screen; /// Context for the rendering of a widget. pub struct Context<'screen> { /// The bounds that the widget should be drawn within. /// /// It is the `Drawable` implementation's responsibility to *not* draw outside these bounds. pub bounds: Bounds, pub screen: &'screen mut Screen, } /// Objects that can draw themselves to a screen. pub trait Drawable { fn draw(&self, ctx: &mut Context); }
true
2980971f4bcb08b66fc86450f25f883f3aab9314
Rust
Herschel/AdventOfCode2016
/day9b/src/main.rs
UTF-8
1,059
3.0625
3
[]
no_license
extern crate regex; use regex::Regex; use std::io::{self, Read}; fn main() { let mut input = String::new(); io::stdin().read_to_string(&mut input).expect("Invalid input"); let line = input.lines().next().expect("No input").split_whitespace().collect::<Vec<_>>().join(""); let len = decompressed_len(line.as_ref()); println!("Decompressed len: {}", len); } fn decompressed_len(line: &str) -> usize { let mut cur_char = 0; let mut len = 0; let re = Regex::new(r"\((\d+)x(\d+)\)").unwrap(); while let Some(cap) = re.captures(&line[cur_char..]) { let (mut begin, mut end) = cap.pos(0).unwrap(); begin += cur_char; end += cur_char; let num_chars: usize = cap.at(1).unwrap().parse().unwrap(); let num_repeats: usize = cap.at(2).unwrap().parse().unwrap(); len += begin - cur_char; let sub_len = decompressed_len(&line[end..end+num_chars]); len += sub_len * num_repeats; cur_char = end + num_chars; } len += line.len() - cur_char; len }
true
ffc4c3d24aa0907d2afc3a96cfc62141a1b103b5
Rust
mgburns/rust-programming-language
/ch5/structs/src/main.rs
UTF-8
1,288
3.6875
4
[]
no_license
fn main() { let user1 = User { email: String::from("someone@example.com"), username: String::from("someusername123"), active: true, sign_in_count: 1, }; println!("{:?}", user1); // *all* struct fields inherit mutability from instance let mut user2 = build_user(String::from("someone@example.com"), String::from("someusername123")); user2.email = String::from("anotheremail@example.com"); println!("{:?}", user2); let user3 = User { email: String::from("another@example.com"), username: String::from("anotherusername567"), // struct update syntax (think es6 object destructuring) // note: no change in ownership as it copies values into new instance ..user1 }; println!("{:?}", user3); // Tuple struct instantiation let black = Color(0, 0, 0); let origin = Point(0, 0, 0); } fn build_user(email: String, username: String) -> User { User { email, // field init shorthand (think es6 prop value shorthand) username, active: true, sign_in_count: 1, } } #[derive(Debug)] struct User { username: String, email: String, sign_in_count: u64, active: bool, } // Tuple structs -- like tuples, but with a name struct Color(i32, i32, i32); struct Point(i32, i32, i32);
true
523e2eff7276ba4071a0a86a414a5fe734840621
Rust
aatxe/oxide-test-suite
/nll/borrowed-temporary-error.rs
UTF-8
292
2.890625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
fn gimme<'a>(x: &'a (u32,)) -> &'a u32 { #[lft = "t"] &(*x).0 } fn main() { let x: &'v u32 = gimme::<'v>({ let v: u32 = 22; let tmp0: (u32,) = (v,); &tmp0 //~^ ERROR temporary value dropped while borrowed [E0716] }); // println!("{:?}", x); }
true
e562e12230792dc407cf332069b25d800d155e65
Rust
MarcoLugo/rust-hangman
/src/console_io.rs
UTF-8
1,242
3.765625
4
[]
no_license
use std::io::prelude::*; use std::io; /// Removes trailing newline from string. fn trim_newline(s: &mut String) { while s.ends_with('\n') || s.ends_with('\r') { s.pop(); } } /// Shows welcome message on console. pub fn welcome() { let welcome_bar = "=".repeat(40); println!("{}", welcome_bar); println!(" Hangman"); println!("{}\n", welcome_bar); } /// Gets one letter from console input. /// /// If the string is empty or larger than one letter, /// it loops again until the input is a single letter. pub fn get_letter() -> char { let mut guess = String::new(); print!("Please enter a letter: "); io::stdout().flush().expect("Could not flush stdout"); loop { io::stdin().read_line(&mut guess) .expect("Failed to read line"); trim_newline(&mut guess); match guess.len() { 0 => continue, 1 => break, _ => { println!("Please enter a single letter. You entered: {}\n", guess); guess.clear(); // clear contents, otherwise read_line will append on user input } } } guess.chars().next().unwrap() // return first character of string }
true
e22854cdf84e8ee4016996cdb3661c4110e6607a
Rust
PolideaPlayground/RustJuliaSet
/src/main.rs
UTF-8
3,952
3.390625
3
[]
no_license
mod buffer; mod render; use buffer::Buffer; use minifb::{Key, MouseMode, Window, WindowOptions}; use render::{render_loop, RenderCommand, RenderParameters, RenderResult}; use std::sync::mpsc::channel; use std::thread::spawn; fn main() { // Create buffer for rendering. const WIDTH: usize = 800; const HEIGHT: usize = 600; let buffer = Buffer::new(WIDTH, HEIGHT); // Create window. let mut window = Window::new( "Fractal", WIDTH, HEIGHT, WindowOptions { resize: false, ..WindowOptions::default() }, ) .expect("Cannot create a window."); // Create communication channels. let (request_tx, request_rx) = channel::<RenderCommand>(); let (response_tx, response_rx) = channel::<RenderResult>(); // Spawn rendering thread let render_thread = spawn(|| { render_loop(request_rx, response_tx); }); // Let's describe out window's state #[derive(Debug)] enum WindowState { RenderRequest { buffer: Buffer, params: RenderParameters, }, RequestPending { params: RenderParameters, }, Idle { buffer: Buffer, params: RenderParameters, }, } let mut state = WindowState::RenderRequest { buffer, params: RenderParameters { iterations: 110, cx: -0.6, cy: 0.5, }, }; // Main window loop while window.is_open() && !window.is_key_down(Key::Escape) { // Collect input let new_params = window .get_mouse_pos(MouseMode::Clamp) .map(|mouse_pos| RenderParameters { iterations: 110, cx: -0.6 + mouse_pos.0 / WIDTH as f32 * 0.2, cy: 0.5 + mouse_pos.1 / HEIGHT as f32 * 0.2, }); // Handle state state = match state { // Send render request to render thread. WindowState::RenderRequest { buffer, params } => { request_tx .send(RenderCommand::RenderRequest { buffer, params }) .expect("Cannot send request to a render thread"); WindowState::RequestPending { params } } // Check if buffer is available again WindowState::RequestPending { params } => { if let Ok(RenderResult { buffer, render_time, }) = response_rx.try_recv() { // Update screen and go to idle state window.update_with_buffer(buffer.as_slice()).unwrap(); window.set_title(&format!( "Fractal ({:?}, {}, {})", render_time, params.cx, params.cy )); WindowState::Idle { buffer, params } } else { // Work is still pending WindowState::RequestPending { params } } } // Handle Idle WindowState::Idle { buffer, params } => match new_params { Some(new_params) if new_params != params => WindowState::RenderRequest { buffer, params: new_params, }, _ => WindowState::Idle { buffer, params }, }, }; // Update inputs. // Note: MiniFB library doesn't have "sleeping" functionality and the // main thread will spin CPU to 100%. It's OK as we want to keep code // to a minimum and there are other libraries, which provide this functionality. window.update(); } // Close render thread. request_tx .send(RenderCommand::Quit) .expect("Cannot close render thread."); render_thread.join().expect("Cannot join render thread.") }
true
67c872417a85aa964da41644b33b448f2e16319e
Rust
sajuthankappan/urlshortener-rest-rs
/src/main.rs
UTF-8
5,192
2.546875
3
[ "Apache-2.0", "MIT" ]
permissive
#![feature(custom_derive, plugin)] #![plugin(serde_macros)] #![feature(custom_attribute)] extern crate bodyparser; extern crate hyper; extern crate iron; extern crate mount; extern crate unicase; extern crate serde; extern crate serde_json; extern crate router; extern crate urlshortener; use hyper::mime::{Mime}; use iron::AfterMiddleware; use iron::headers; use iron::method::Method::*; use iron::modifiers::Redirect; use iron::prelude::*; use iron::Url; use iron::status; use mount::Mount; use router::Router; use unicase::UniCase; use urlshortener::errors; use urlshortener::models; use urlshortener::UrlManager; macro_rules! try_or_500 { ($expr:expr) => (match $expr { Ok(val) => val, Err(e) => { println!("Errored: {:?}", e); return Ok(Response::with((status::InternalServerError))) } }) } fn main() { let mut router = Router::new(); router.get("/", redirect_to_home); router.get("/ping", pong); router.get("/:alias", redirect_to_alias); let mut api_router = Router::new(); api_router.get("/", pong); api_router.get("/ping", pong); api_router.get("/url", pong); api_router.get("/url/ping", pong); api_router.get("/url/:alias", get_url); api_router.post("/url", shorten_url); let mut mount = Mount::new(); mount.mount("/", router); mount.mount("/api/", api_router); let mut chain = Chain::new(mount); chain.link_after(CORS); println!("Urlshortener rest services running at http://localhost:3000"); Iron::new(chain).http("0.0.0.0:3000").unwrap(); } fn respond_json(value: String) -> IronResult<Response> { let content_type = "application/json".parse::<Mime>().unwrap(); Ok(Response::with((content_type, iron::status::Ok, value))) } fn redirect_to_home(_req: &mut Request) -> IronResult<Response> { let homepage_url_str = "http://tsaju.in/urlshortener"; let homepage_url = Url::parse(homepage_url_str).unwrap(); Ok(Response::with((status::MovedPermanently, Redirect(homepage_url.clone())))) } fn redirect_to_alias(req: &mut Request) -> IronResult<Response> { let alias = req.extensions.get::<Router>().unwrap().find("alias").unwrap(); let long_url = UrlManager::new().find_one(alias.to_string()).unwrap().long_url; let url_str: &str = &*long_url; let url_result = Url::parse(url_str); if let Ok(url) = url_result { Ok(Response::with((status::MovedPermanently, Redirect(url.clone())))) } else { // Try to handle if long url do not start with http / https let new_long_url = "http://".to_string() + &long_url; let new_long_url_str: &str = &*new_long_url; let new_url = Url::parse(new_long_url_str).unwrap(); Ok(Response::with((status::MovedPermanently, Redirect(new_url.clone())))) } } fn pong(_: &mut Request) -> IronResult<Response> { let pong = Pong { message: Some("pong".to_string()) }; let serialized = serde_json::to_string(&pong).unwrap(); respond_json(serialized) } fn get_url(req: &mut Request) -> IronResult<Response> { let alias = req.extensions.get::<Router>().unwrap().find("alias").unwrap_or(""); let find = UrlManager::new().find_one(alias.to_string()); match find { Some(url) => { let serialized = serde_json::to_string(&url).unwrap(); respond_json(serialized) }, None => { Ok(Response::with(status::NotFound)) } } } fn shorten_url(req: &mut Request) -> IronResult<Response> { //let mut buffer = String::new(); //let size = req.body.read_to_string(&mut buffer); //req.body.read_to_string(&mut buffer).unwrap(); let body = req.get::<bodyparser::Raw>().unwrap().unwrap(); //println!("{:?}", body); let url: models::Url = try_or_500!(serde_json::from_str(&body)); let url_manager = UrlManager::new(); let created = url_manager.add(url); match created { Ok(v) =>{ let serialized = serde_json::to_string(&v).unwrap(); return respond_json(serialized); }, Err(e) => { match e { errors::UrlError::AliasAlreadyExists => { return Ok(Response::with((status::Conflict))) }, errors::UrlError::OtherError => { return Ok(Response::with((status::InternalServerError))) } } } } } #[derive(Serialize, Deserialize, Debug, Clone)] struct Point { x: i32, // #[serde(rename="xx")] y: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] struct Pong { message: Option<String>, } struct CORS; impl AfterMiddleware for CORS { fn after(&self, _: &mut Request, mut res: Response) -> IronResult<Response> { res.headers.set(headers::AccessControlAllowOrigin::Any); res.headers.set(headers::AccessControlAllowHeaders( vec![UniCase("accept".to_string()), UniCase("content-type".to_string())])); res.headers.set(headers::AccessControlAllowMethods( vec![Get,Head,Post,Delete,Options,Put,Patch])); Ok(res) } }
true
d184995993b70c5f715df4801adfad4d7e696172
Rust
cloudcalvin/unseemly
/src/macros/flimsy_syntax.rs
UTF-8
11,531
2.625
3
[ "MIT" ]
permissive
#![macro_use] // For testing purposes, we want to generate valid Asts without a full-fledged parser. // `ast!` is clunky and makes it *super* easy to leave off `QuoteMore`, `QuoteLess`, and `ExtendEnv` // We'll assume that the form itself is known and that we can drop all the literals on the ground. // The result is a terse way to make valid ASTs. // It's weird to be relying on the grammar while ignoring parts of it, hence "flimsy", // but errors are much more likely to be compile-time than inscrutable test problems. // It's not unsafe to use `u!` for runtime operations, but there's a runtime cost, so don't do it. use crate::{ ast::Ast::{self, *}, grammar::FormPat, name::*, util::mbe::EnvMBE, }; use std::iter::{Iterator, Peekable}; // First, transforms from `[a b c; d e f; g h i]` to `[g h i] {[a b c] [d e f]}` // to get around a Rust macro parsing restriction, // then makes a REP flimsy shape for it. macro_rules! u_rep { ([; $( $ts:tt )*] $acc_cur:tt { $( $acc_rest:tt )* }) => { u_rep!( [ $( $ts )* ] [] { $( $acc_rest )* $acc_cur }) }; ([$t:tt $( $ts:tt )*] [ $( $acc_cur:tt )* ] { $( $acc_rest:tt )* }) => { u_rep!( [ $( $ts )* ] [$($acc_cur)* $t] { $( $acc_rest )* }) }; ([] [] {}) => { // Empty repeat crate::ast::Shape(vec![crate::ast::Atom(n("REP"))]) }; ([] [ $( $acc_cur:tt )* ] { $( [ $( $acc_rest:tt )* ] )* }) => { crate::ast::Shape(vec![ crate::ast::Atom(n("REP")), $( u_shape_if_many!( $($acc_rest)* ), )* u_shape_if_many!( $($acc_cur)* ) ]) }; } macro_rules! u_shape_if_many { ($t:tt) => { u!($t) }; () => { compile_error!("empty u!") }; ( $($ts:tt)* ) => { u!((~ $($ts)* )) }; } thread_local! { pub static default_nt: std::cell::RefCell<String> = std::cell::RefCell::new("Expr".to_owned()); } macro_rules! u { ($atom:ident) => { // Default to this, because `Call` will use whatever it's given, without a grammar: crate::ast::VariableReference(n(stringify!($atom))) }; ( [ , $seq:expr ] ) => { { let mut contents: Vec<Ast> = $seq; contents.insert(0, crate::ast::Atom(n("REP"))); crate::ast::Shape(contents) } }; ( [ $( $ts:tt )* ] ) => { u_rep!( [$($ts)*] [] {} ) }; ( { $form:ident : $( $ts:tt )*} ) => { { let f = crate::macros::flimsy_syntax::default_nt.with(|def_nt| { crate::core_forms::find_core_form(&def_nt.borrow(), stringify!($form)) }); crate::ast::Node(f.clone(), crate::macros::flimsy_syntax::parse_flimsy_mbe(&u!( (~ $($ts)* ) ), &f.grammar) .unwrap_or_else(crate::util::mbe::EnvMBE::new), crate::beta::ExportBeta::Nothing) } }; ( { $nt:ident $form:ident : $( $ts:tt )*} ) => { { let mut old_default_nt = "".to_owned(); let f = crate::macros::flimsy_syntax::default_nt.with(|def_nt| { old_default_nt = def_nt.borrow().clone(); let nt = stringify!($nt); *def_nt.borrow_mut() = nt.to_string(); crate::core_forms::find_core_form(&nt, stringify!($form)) }); let res = crate::ast::Node(f.clone(), crate::macros::flimsy_syntax::parse_flimsy_mbe(&u!( (~ $($ts)* ) ), &f.grammar) .unwrap_or_else(crate::util::mbe::EnvMBE::new), crate::beta::ExportBeta::Nothing); crate::macros::flimsy_syntax::default_nt.with(|def_nt| { *def_nt.borrow_mut() = old_default_nt; }); res } }; // The need for explicit exports is unfortunate; // that information is part of `Scope`, not `Form` (maybe we should change that?) ( { $form:ident => $ebeta:tt : $( $ts:tt )*} ) => { { let f = crate::macros::flimsy_syntax::default_nt.with(|def_nt| { crate::core_forms::find_core_form(&def_nt.borrow(), stringify!($form)) }); crate::ast::Node(f.clone(), crate::macros::flimsy_syntax::parse_flimsy_mbe(&u!( (~ $($ts)* ) ), &f.grammar) .unwrap_or_else(crate::util::mbe::EnvMBE::new), ebeta!($ebeta)) } }; ( { $nt:ident $form:ident => $ebeta:tt : $( $ts:tt )*} ) => { { // code duplication from above ) : let mut old_default_nt = "".to_owned(); let f = crate::macros::flimsy_syntax::default_nt.with(|def_nt| { old_default_nt = def_nt.borrow().clone(); let nt = stringify!($nt); *def_nt.borrow_mut() = nt.to_string(); crate::core_forms::find_core_form(&nt, stringify!($form)) }); let res =crate::ast::Node(f.clone(), crate::macros::flimsy_syntax::parse_flimsy_mbe(&u!( (~ $($ts)* ) ), &f.grammar) .unwrap_or_else(crate::util::mbe::EnvMBE::new), ebeta!($ebeta)); crate::macros::flimsy_syntax::default_nt.with(|def_nt| { *def_nt.borrow_mut() = old_default_nt; }); res } }; ( { $form:expr ; $( $ts:tt )*} ) => { { let f = $form; crate::ast::Node(f.clone(), crate::macros::flimsy_syntax::parse_flimsy_mbe(&u!( (~ $($ts)* ) ), &f.grammar) .unwrap_or_else(crate::util::mbe::EnvMBE::new), crate::beta::ExportBeta::Nothing) } }; ({ $( $anything:tt )* }) => { compile_error!("Needed a : or ; in u!"); }; // Currently, nested `Seq`s need to correspond to nested `SEQ`s, so this creates one explicitly: ((~ $($ts:tt)*)) => { crate::ast::Shape(vec![ crate::ast::Atom(n("SEQ")), $( u!( $ts ) ),* ]) }; ((at $t:tt)) => { crate::ast::Atom(n(stringify!($t))) }; ((prim $t:tt)) => { crate::core_type_forms::get__primitive_type(n(stringify!($t))).concrete() }; ((, $interpolate:expr)) => { $interpolate }; // Two or more token trees (avoid infinite regress by not handling the one-element case) ( $t_first:tt $t_second:tt $( $t:tt )* ) => { ::ast::Shape(vec![ ::ast::Atom(n("SEQ")), u!( $t_first ), u!( $t_second ), $( u!( $t ) ),* ]) }; } macro_rules! uty { ($( $ts:tt )*) => { { let mut old_default_nt = "".to_owned(); crate::macros::flimsy_syntax::default_nt.with(|def_nt| { old_default_nt = def_nt.borrow().clone(); *def_nt.borrow_mut() = "Type".to_owned(); }); let res = crate::ty::Ty(u!( $($ts)* )); crate::macros::flimsy_syntax::default_nt.with(|def_nt| { *def_nt.borrow_mut() = old_default_nt; }); res } }; } fn parse_flimsy_seq<'a, I>(flimsy_seq: &mut Peekable<I>, grammar: &FormPat) -> EnvMBE<Ast> where I: Iterator<Item = &'a Ast> { use crate::grammar::FormPat::*; match grammar { Seq(ref grammar_parts) => { let mut result = EnvMBE::new(); for grammar_part in grammar_parts { result = result.combine_overriding(&parse_flimsy_seq(flimsy_seq, grammar_part)); } result } _ => { let flimsy = *match flimsy_seq.peek() { None => return EnvMBE::new(), // Or is this an error? Some(f) => f, }; match parse_flimsy_mbe(flimsy, grammar) { None => EnvMBE::new(), Some(res) => { // `Anyways`es shouldn't consume anything (and they'll always be `Named`): let consuming = match grammar { Named(_, ref body) => match **body { Anyways(_) => false, _ => true, }, _ => true, }; if consuming { let _ = flimsy_seq.next(); } res } } } } } pub fn parse_flimsy_mbe(flimsy: &Ast, grammar: &FormPat) -> Option<EnvMBE<Ast>> { use crate::grammar::FormPat::*; match grammar { Literal(_, _) => None, Call(_) => None, Scan(_) => None, Seq(_) => match flimsy { Shape(flimsy_parts) => { if flimsy_parts[0] != Atom(n("SEQ")) { panic!("Needed a SEQ, got {}", flimsy) } let mut fpi = flimsy_parts[1..].iter().peekable(); Some(parse_flimsy_seq(&mut fpi, grammar)) } _ => panic!("Needed a SEQ shape, got {}", flimsy), }, Star(ref body) | Plus(ref body) => match flimsy { Shape(flimsy_parts) => { if flimsy_parts[0] != Atom(n("REP")) { panic!("Need a REP, got {}", flimsy_parts[0]) } let mut reps = vec![]; for flimsy_part in flimsy_parts[1..].iter() { reps.push(parse_flimsy_mbe(flimsy_part, &*body).unwrap()); } Some(EnvMBE::new_from_anon_repeat(reps)) } _ => panic!("Needed a REP shape, got {}", flimsy), }, Alt(ref subs) => { // HACK: always pick the first branch of the `Alt` // (mainly affects unquotation, where it skips the type annotation) parse_flimsy_mbe(flimsy, &*subs[0]) } Named(name, ref body) => Some(EnvMBE::new_from_leaves( crate::util::assoc::Assoc::new().set(*name, parse_flimsy_ast(flimsy, &*body)), )), SynImport(_, _, _) => panic!("`SynImport` can't work without a real parser"), NameImport(_, _) => panic!("`NameImport` should live underneath `Named`: {:?}", grammar), _ => unimplemented!("Can't handle {:?}", grammar), } } fn parse_flimsy_ast(flimsy: &Ast, grammar: &FormPat) -> Ast { use crate::grammar::FormPat::*; match grammar { Anyways(ref a) => a.clone(), Impossible => unimplemented!(), Scan(_) => flimsy.clone(), Literal(_, _) => Trivial, VarRef(_) => match flimsy { VariableReference(a) => VariableReference(*a), non_atom => panic!("Needed an atom, got {}", non_atom), }, NameImport(body, beta) => { ExtendEnv(Box::new(parse_flimsy_ast(flimsy, &*body)), beta.clone()) } QuoteDeepen(body, pos) => QuoteMore(Box::new(parse_flimsy_ast(flimsy, &*body)), *pos), QuoteEscape(body, depth) => QuoteLess(Box::new(parse_flimsy_ast(flimsy, &*body)), *depth), Call(name) => { // HACK: don't descend into `Call(n("DefaultAtom")) if *name == n("DefaultAtom") || *name == n("AtomNotInPat") { match flimsy { VariableReference(a) => Atom(*a), non_atom => panic!("Needed an atom, got {}", non_atom), } } else { flimsy.clone() } } _ => unimplemented!("Can't handle {:?}", grammar), } }
true
f9fd8b23990b0cd982e6f6fec495a77e364fe8dc
Rust
cpcloud/exercism
/rust/raindrops/src/lib.rs
UTF-8
363
2.84375
3
[]
no_license
pub fn raindrops(n: u32) -> String { let mut result = vec![]; if n % 3 == 0 { result.push("Pling".to_owned()); } if n % 5 == 0 { result.push("Plang".to_owned()); } if n % 7 == 0 { result.push("Plong".to_owned()); } if result.is_empty() { result.push(n.to_string()); } result.join("") }
true
ce35fc35993e2283039d77ee98bc6f86090d21cd
Rust
Ayase-252/frontend-lab
/rust/rust-language/src/main.rs
UTF-8
108
3.109375
3
[]
no_license
fn main() { let x = [1, 2, 3, 45]; let index = 6; println!("The value of x is {}", x[index]); }
true
2747a23bcdf09543df15297cef635ebd12167c2b
Rust
harcomaase/aoc
/rs-22/src/bin/day6.rs
UTF-8
635
3.09375
3
[]
no_license
use std::fs; fn main() { let input = fs::read_to_string("../input/22/day6.txt").unwrap(); let chars: Vec<char> = input.chars().collect(); let start_of_packet_marker_length = 4; for i in 0..(chars.len() - start_of_packet_marker_length) { let end = i + start_of_packet_marker_length; if !contains_duplicates(&chars[i..end]) { println!("{}", end); break; } } } fn contains_duplicates(slice: &[char]) -> bool { let mut buf = Vec::new(); for c in slice { if buf.contains(c) { return true; } buf.push(*c); } false }
true
5471425fa8637b6a19e02d396e612d51a9807afb
Rust
kroeckx/ruma
/crates/ruma-federation-api/src/knock/send_knock/v1.rs
UTF-8
1,603
2.671875
3
[ "MIT" ]
permissive
//! [PUT /_matrix/federation/v1/send_knock/{roomId}/{eventId}](https://spec.matrix.org/unstable/server-server-api/#put_matrixfederationv1send_knockroomideventid) use ruma_api::ruma_api; use ruma_events::{room::member::MemberEvent, AnyStrippedStateEvent}; use ruma_identifiers::{EventId, RoomId}; ruma_api! { metadata: { description: "Submits a signed knock event to the resident homeserver for it to accept into the room's graph.", name: "send_knock", method: PUT, path: "/_matrix/federation/v1/send_knock/:room_id/:event_id", rate_limited: false, authentication: ServerSignatures, } request: { /// The room ID that should receive the knock. #[ruma_api(path)] pub room_id: &'a RoomId, /// The event ID for the knock event. #[ruma_api(path)] pub event_id: &'a EventId, /// The full knock event. #[ruma_api(body)] pub knock_event: &'a MemberEvent, } response: { /// State events providing public room metadata. pub knock_room_state: Vec<AnyStrippedStateEvent>, } } impl<'a> Request<'a> { /// Creates a new `Request` with the given room ID, event ID and knock event. pub fn new(room_id: &'a RoomId, event_id: &'a EventId, knock_event: &'a MemberEvent) -> Self { Self { room_id, event_id, knock_event } } } impl Response { /// Creates a new `Response` with the given public room metadata state events. pub fn new(knock_room_state: Vec<AnyStrippedStateEvent>) -> Self { Self { knock_room_state } } }
true
a787a2623d9be047ef25aa5bfcc959e5e3e3f36c
Rust
IThawk/rust-project
/rust-master/src/test/ui/proc-macro/gen-macro-rules-hygiene.rs
UTF-8
678
2.53125
3
[ "MIT", "LicenseRef-scancode-other-permissive", "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "NCSA" ]
permissive
// `macro_rules` items produced by transparent macros have correct hygiene in basic cases. // Local variables and labels are hygienic, items are not hygienic. // `$crate` refers to the crate that defines `macro_rules` and not the outer transparent macro. // aux-build:gen-macro-rules-hygiene.rs #[macro_use] extern crate gen_macro_rules_hygiene; struct ItemUse; gen_macro_rules!(); //~^ ERROR use of undeclared label `'label_use` //~| ERROR cannot find value `local_use` in this scope fn main() { 'label_use: loop { let local_use = 1; generated!(); ItemDef; // OK local_def; //~ ERROR cannot find value `local_def` in this scope } }
true
c7d19117eed24659caf672b5b32d22e0ce9e1cca
Rust
koompi/koompi-desktop
/desktop/src/configs/desktop_item_conf.rs
UTF-8
1,930
2.859375
3
[ "MIT" ]
permissive
use serde::{Deserialize, Serialize}; use std::fmt::{self, Display, Formatter}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DesktopItemConf { pub icon_size: u16, pub grid_spacing: u16, pub arrangement: Arrangement, pub sort_descending: bool, pub sorting: Sorting, pub show_tooltip: bool, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum Arrangement { Rows, Columns, } impl Arrangement { pub const ALL: [Arrangement; 2] = [Arrangement::Rows, Arrangement::Columns]; } impl Display for Arrangement { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { use Arrangement::*; write!( f, "{}", match self { Rows => "Rows", Columns => "Columns", } ) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum Sorting { Manual, Name, Type, Date, } impl Sorting { pub const ALL: [Sorting; 4] = [Sorting::Manual, Sorting::Name, Sorting::Type, Sorting::Date]; } impl Display for Sorting { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { use Sorting::*; write!( f, "{}", match self { Manual => "None", Name => "Name", Type => "Type", Date => "Date", } ) } } impl Default for DesktopItemConf { fn default() -> Self { Self { icon_size: 45, grid_spacing: 10, arrangement: Arrangement::Rows, sort_descending: false, sorting: Sorting::Manual, show_tooltip: false, } } } impl DesktopItemConf { pub const MIN_ICON_SIZE: u16 = 32; pub const MAX_ICON_SIZE: u16 = 96; pub const MIN_GRID_SPACING: u16 = 5; pub const MAX_GRID_SPACING: u16 = 20; }
true
ef976ac2f12abfccddf9f316943d610205afcc10
Rust
userbaruu/aeromit
/src/pengguna/services/get_me.rs
UTF-8
2,118
3.125
3
[ "CC0-1.0" ]
permissive
//! # Module Get Me Service //! //! Module ini digunakan untuk membaca data pengguna sendiri berdasarkan token untuk //! digunakan di `handlers`. //! //! <br /> //! //! # Contoh //! //! ```rust //! use crate::pengguna::services::get_me::{...} //! ``` use std::env; use actix_web::web; use mongodb::{ Database, bson::{self, doc, document::Document} }; use jsonwebtoken::{decode, DecodingKey, Validation}; use crate::app::errors::AppErrors; use crate::pengguna::{ models::Pengguna, helpers::{PenggunaHelpersTrait, PenggunaHelpers}, }; use crate::app::helpers::{AppHelpers, AppHelpersTrait}; use crate::pengguna::models::Klaim; /// # Fungsi by_token /// /// Fungsi ini untuk melihat data `Pengguna` sesuai token. /// /// <br /> /// /// # Masukan /// /// * `req` - HttpRequest untuk ambil token. /// * `db` - mongodb Database type yang dishare melalui _application state_. /// /// <br /> /// /// # Keluaran /// /// * `Result<Option<Pengguna>, AppErrors>` - keluaran berupa _enum_ `Result` yang terdiri dari /// `Pengguna` dan _Enum_ `AppErrors`. pub async fn by_token( req: web::HttpRequest, db: web::Data<Database> ) -> Result<Pengguna, AppErrors> { let headers = req.headers().get("authorization"); let token = <AppHelpers as AppHelpersTrait>::get_token(headers)?; if !token.is_empty() { let secret = env::var("APP_SECRET")?; let klaim = decode::<Klaim>( &token, &DecodingKey::from_secret(secret.as_bytes()), &Validation::default() )?; let email = klaim.claims.get_email(); let collection = db.collection("pengguna"); let result = collection .find_one(doc! {"email": email}, None) .await?; match result { Some(document) => { let dok = bson::from_document::<Document>(document)?; let peg = <PenggunaHelpers as PenggunaHelpersTrait>::doc_to_pengguna(dok)?; Ok(peg) } None => Err(AppErrors::UnauthorizeUser) } } else { Err(AppErrors::UnauthorizeUser) } }
true
e7de6c571b491a4b530fff913a1419457bc4c5be
Rust
drbawb/shellac
/resin/src/bin/test_echo.rs
UTF-8
291
2.71875
3
[ "BSD-3-Clause" ]
permissive
use std::io::{self, Write}; fn main() { loop { let mut buf = String::new(); io::stdin().read_line(&mut buf) .expect("could not read line"); if buf.starts_with("exit") { std::process::exit(0); } io::stdout().write(&buf.as_bytes()) .expect("could not write line"); } }
true
e8caad44a3b9ac27ee168b51a2f8b9a71ff2f3d5
Rust
zhongsp/code-kata
/LeetCode/rs/1-50/valid_parentheses.rs
UTF-8
1,498
3.71875
4
[]
no_license
//! struct Solution(); #[allow(dead_code)] impl Solution { pub fn is_valid(s: String) -> bool { let mut stack = vec![]; let mut s = s; for _ in 0..s.len() { let char = s.remove(0); match char { ')' => { if stack.pop() != Some('(') { return false; } } ']' => { if stack.pop() != Some('[') { return false; } } '}' => { if stack.pop() != Some('{') { return false; } } _ => stack.push(char), } } stack.len() == 0 } } #[cfg(test)] mod test { use super::*; #[test] fn is_valid0() { assert_eq!(Solution::is_valid(String::from("([{}])")), true) } #[test] fn is_valid1() { assert_eq!(Solution::is_valid(String::from("([}])")), false) } #[test] fn is_valid2() { assert_eq!(Solution::is_valid(String::from(")[}])")), false) } #[test] fn is_valid3() { assert_eq!(Solution::is_valid(String::from("()[]{}")), true) } #[test] fn is_valid4() { assert_eq!(Solution::is_valid(String::from("(]")), false) } #[test] fn is_valid5() { assert_eq!(Solution::is_valid(String::from("]")), false) } }
true
0bad8541d7735cfbec2c9956de51bd1ff5e9e3e9
Rust
vvvy/zgw
/zrest/src/error.rs
UTF-8
4,126
2.546875
3
[ "Apache-2.0" ]
permissive
use std::{self, borrow::Cow, error::Error, fmt::Display}; use hyper; use hyper_tls; use mime; use serde_json; use http; use uri_scanner; #[derive(Debug)] pub enum ZError { Hyper(hyper::error::Error), HyperHeaderToStr(hyper::header::ToStrError), HyperTls(hyper_tls::Error), MimeFromStr(mime::FromStrError), SerdeJson(serde_json::Error), Http(http::Error), Io(std::io::Error), UriScanner(uri_scanner::SErr), InvalidUri(http::uri::InvalidUri), InvalidUriParts(http::uri::InvalidUriParts), AppHttp(http::StatusCode, Cow<'static, str>), Other(Cow<'static, str>) } impl Error for ZError { fn cause(&self) -> Option<&dyn Error> { match self { ZError::Hyper(e) => e.cause(), ZError::HyperHeaderToStr(e) => e.cause(), ZError::HyperTls(e) => e.cause(), ZError::MimeFromStr(e) => e.cause(), ZError::SerdeJson(e) => e.cause(), ZError::Http(e) => e.cause(), ZError::Io(e) => e.cause(), ZError::UriScanner(e) => e.cause(), ZError::InvalidUri(e) => e.cause(), ZError::InvalidUriParts(e) => e.cause(), ZError::AppHttp(..) => None, ZError::Other(_) => None } } } impl Display for ZError { fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> Result<(), std::fmt::Error> { match self { ZError::Hyper(e) => write!(f, "(Hyper): ").and_then(|_| e.fmt(f)), ZError::HyperHeaderToStr(e) => write!(f, "(HyperHeaderToStr): ").and_then(|_| e.fmt(f)), ZError::HyperTls(e) => write!(f, "(HyperTls): ").and_then(|_| e.fmt(f)), ZError::MimeFromStr(e) => write!(f, "(MimeFromStr): ").and_then(|_| e.fmt(f)), ZError::SerdeJson(e) => write!(f, "(SerdeJson): ").and_then(|_| e.fmt(f)), ZError::Http(e) => write!(f, "(Http): ").and_then(|_| e.fmt(f)), ZError::Io(e) => write!(f, "(Io): ").and_then(|_| e.fmt(f)), ZError::UriScanner(e) => write!(f, "(UriScanner): ").and_then(|_| e.fmt(f)), ZError::InvalidUri(e) => write!(f, "(InvalidUri): ").and_then(|_| e.fmt(f)), ZError::InvalidUriParts(e) => write!(f, "(InvalidUriParts): ").and_then(|_| e.fmt(f)), ZError::AppHttp(s, m) => write!(f, "(AppHttp): {} {}", s, m), ZError::Other(s) => write!(f, "(Other): {}", s) } } } impl From<hyper::error::Error> for ZError { fn from(e: hyper::error::Error) -> Self { ZError::Hyper(e) } } impl From<http::Error> for ZError { fn from(e: http::Error) -> Self { ZError::Http(e) } } impl From<mime::FromStrError> for ZError { fn from(e: mime::FromStrError) -> Self { ZError::MimeFromStr(e) } } impl From<hyper::header::ToStrError> for ZError { fn from(e: hyper::header::ToStrError) -> Self { ZError::HyperHeaderToStr(e) } } impl From<hyper_tls::Error> for ZError { fn from(e: hyper_tls::Error) -> Self { ZError::HyperTls(e) } } impl From<serde_json::Error> for ZError { fn from(e: serde_json::Error) -> Self { ZError::SerdeJson(e) } } impl From<std::io::Error> for ZError { fn from(e: std::io::Error) -> Self { ZError::Io(e) } } impl From<uri_scanner::SErr> for ZError { fn from(e: uri_scanner::SErr) -> Self { ZError::UriScanner(e) } } impl From<http::uri::InvalidUri> for ZError { fn from(e: http::uri::InvalidUri) -> Self { ZError::InvalidUri(e) } } impl From<http::uri::InvalidUriParts> for ZError { fn from(e: http::uri::InvalidUriParts) -> Self { ZError::InvalidUriParts(e) } } #[macro_export] macro_rules! rest_error { {other $e:expr} => { ZError::Other(std::borrow::Cow::from($e)) }; {other $($es:expr),+} => { ZError::Other(std::borrow::Cow::from(format!($($es),+))) }; {http $sc:ident $es:expr} => { ZError::AppHttp(http::StatusCode::$sc, std::borrow::Cow::from($es)) }; {http $sc:ident $($es:expr),+} => { ZError::AppHttp(http::StatusCode::$sc, std::borrow::Cow::from(format!($($es),+))) }; }
true
52492a0879f77dea3bbbd139484132f500d7adf3
Rust
gbip/rust-render-engine
/src/filter/filters.rs
UTF-8
3,626
2.9375
3
[]
no_license
use color_float::LinearColor; use renderer::Pixel; use math::{Vector2, Vector2f}; use filter::Filter; /** Les paramètres standard d'un filtre de Mitchell-Netravali. * Le filtre à un rayon de 1 pixel : il ne regarde que les samples dans le pixel actuel*/ pub struct MitchellFilter { b: f32, c: f32, image_size: Vector2<u32>, } impl MitchellFilter { fn weight_contribution(&self, coords: Vector2f) -> f32 { self.polynome(coords.x * 2.0) * self.polynome(coords.y * 2.0) } /** x doit appartenir à [-2,2] */ fn polynome(&self, x: f32) -> f32 { let abs_x = f32::abs(x); if abs_x < 1.0 { (1.0 / 6.0) * ((12.0 - 9.0 * self.b - 6.0 * self.c) * f32::powi(abs_x, 3) + (-18.0 + 12.0 * self.b + 6.0 * self.c) * f32::powi(abs_x, 2) + (6.0 - 2.0 * self.b)) } else if abs_x >= 1.0 && abs_x <= 2.0 { (1.0 / 6.0) * ((-self.b - 6.0 * self.c) * f32::powi(abs_x, 3) + (6.0 * self.b + 30.0 * self.c) * f32::powi(abs_x, 2) + (-12.0 * self.b - 48.0 * self.c) * abs_x + (8.0 * self.b + 24.0 * self.c)) } else { 0.0 } } pub fn set_image_size(&mut self, x: u32, y: u32) { self.image_size = Vector2::new(x, y); } } impl Default for MitchellFilter { fn default() -> Self { MitchellFilter { b: 1.0 / 3.0, c: 1.0 / 3.0, image_size: Vector2::new(0, 0), } } } impl Filter for MitchellFilter { // TODO : Accélerer ce calcul ? fn compute_color(&self, data: &Pixel, pixel_position: (u32, u32)) -> LinearColor { let mut result: LinearColor = LinearColor::new_black(); let mut weight_sum: f32 = 0.0; // On calcule les contributions de chaque sample for sample in data.samples() { // La position exprimée dans le système de coordonnée de l'image let absolute_sample_pos = sample.position(); // On ramène la valeur pour la mettre au centre du pixel concerné let relative_sample_pixel_pos = Vector2f::new(absolute_sample_pos.x - data.x() as f32 - pixel_position.0 as f32 - 0.5, absolute_sample_pos.y - data.y() as f32 - pixel_position.1 as f32 - 0.5); weight_sum += self.weight_contribution(relative_sample_pixel_pos); } for sample in data.samples() { // La position exprimée dans le système de coordonnée de l'image let absolute_sample_pos = sample.position(); // On ramène la valeur pour la mettre au centre du pixel concerné let relative_sample_pixel_pos = Vector2f::new(absolute_sample_pos.x - data.x() as f32 - pixel_position.0 as f32 - 0.5, absolute_sample_pos.y - data.y() as f32 - pixel_position.1 as f32 - 0.5); let weight = self.weight_contribution(relative_sample_pixel_pos); result += &(sample.color * (weight / weight_sum)); } result } } #[derive(Default)] pub struct BoxFilter {} impl Filter for BoxFilter { fn compute_color(&self, data: &Pixel, _: (u32, u32)) -> LinearColor { let mut result: LinearColor = LinearColor::new_black(); let sum: u32 = data.samples().fold(0, |acc, _| acc + 1); for sample in data.samples() { result += &(sample.color / sum as f32); } result } }
true
42f3fb2595c7f35627a9cca5fb585e0c48def6cd
Rust
josecm/exercism-rust
/rna-transcription/src/lib.rs
UTF-8
930
3.25
3
[]
no_license
use std::collections::HashMap; #[derive(Debug, PartialEq)] pub struct Dna(String); #[derive(Debug, PartialEq)] pub struct Rna(String); impl Dna { const NUCLEOTIDES: &'static str = "ACGT"; pub fn new(dna: &str) -> Result<Dna, usize> { match dna.chars().position(|c| !Dna::NUCLEOTIDES.contains(c)) { None => Ok(Dna(String::from(dna))), Some(n) => Err(n), } } pub fn into_rna(self) -> Rna { let map: HashMap<char, char> = vec![('G', 'C'), ('C', 'G'), ('T', 'A'), ('A', 'U')] .into_iter() .collect(); Rna(self.0.chars().map(|c| map[&c]).collect()) } } impl Rna { const NUCLEOTIDES: &'static str = "CGAU"; pub fn new(rna: &str) -> Result<Rna, usize> { match rna.chars().position(|c| !Rna::NUCLEOTIDES.contains(c)) { None => Ok(Rna(String::from(rna))), Some(n) => Err(n), } } }
true
8870fc60e7f47e130a0cfc681b22f45922f642b8
Rust
awsdocs/aws-doc-sdk-examples
/rust_dev_preview/examples/iam/src/bin/create-role.rs
UTF-8
3,422
2.890625
3
[ "Apache-2.0", "MIT" ]
permissive
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #![allow(clippy::result_large_err)] use aws_config::meta::region::RegionProviderChain; use aws_sdk_iam::{config::Region, meta::PKG_VERSION, Client, Error}; use clap::Parser; use std::fs; #[derive(Debug, Parser)] struct Opt { /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// The name of the role. #[structopt(short, long)] name: String, /// The name of the file containing the policy document. #[structopt(short, long)] policy_file: String, /// Whether to display additional information. #[structopt(short, long)] verbose: bool, } // Creates a role. // snippet-start:[iam.rust.create-role] async fn make_role(client: &Client, policy: &str, name: &str) -> String { let resp = client .create_role() .assume_role_policy_document(policy) .role_name(name) .send() .await; match resp { Ok(output) => { format!( "Created role with ARN {}", output.role().unwrap().arn().unwrap() ) } Err(err) => format!("Error creating role: {:?}", err), } } // snippet-end:[iam.rust.create-role] /// Creates an IAM role in the Region. /// /// # Arguments /// /// * `-a ACCOUNT-ID` - Your account ID. /// * `-b BUCKET` - The name of the bucket where Config stores information about resources. /// * `-n NAME` - The name of the role. /// * `-p POLICY-NAME` - The name of the JSON file containing the policy document. /// * `[-r REGION]` - The Region in which the client is created. /// If not supplied, uses the value of the **AWS_REGION** environment variable. /// If the environment variable is not set, defaults to **us-west-2**. /// * `[-v]` - Whether to display information. #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt::init(); let Opt { name, policy_file, region, verbose, } = Opt::parse(); let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_provider() .or_else(Region::new("us-west-2")); println!(); if verbose { println!("IAM client version: {}", PKG_VERSION); println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!("Role name: {}", &name); println!("Policy doc filename {}", &policy_file); println!(); } let shared_config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&shared_config); // Read policy doc from file as a string let policy_doc = fs::read_to_string(policy_file).expect("Unable to read file"); let response = make_role(&client, policy_doc.as_str(), &name).await; println!("{response}"); Ok(()) } #[cfg(test)] mod test { use crate::make_role; #[tokio::test] async fn test_make_role() { let client = sdk_examples_test_utils::single_shot_client!( sdk: aws_sdk_iam, request: "request body", status: 500, response: "error body" ); let response = make_role(&client, "{}", "test_role").await; assert!(response.starts_with("Error creating role: ")); } }
true
df528ba890df56b0d808c7c28a3dce2b044d917e
Rust
leejw51/RustTutorial
/code/src/stack.rs
UTF-8
479
3.390625
3
[ "Apache-2.0" ]
permissive
fn setup(numbers:&mut [i32;20]) { let mut i:i32 =0 ; for i in 0.. numbers.len() { numbers[i]= 2000-(i as i32)*200; } } fn make() -> [i32;20] { let mut numbers: [i32;20]=[5;20]; setup(&mut numbers); let b= &numbers; println!("pointer {:?}",b as *const i32); return numbers; } fn main() { let numbers = make(); let b= &numbers; println!("pointer {:?}",b as *const i32); for i in &numbers { print!("{} ",i); } }
true
f3ddc13782351e3e596de9362141db39105ae79e
Rust
udoprog/rune
/crates/rune/src/compile/ir/mod.rs
UTF-8
15,255
2.828125
3
[ "Apache-2.0", "MIT" ]
permissive
//! Intermediate representation of Rune that can be evaluated in constant //! contexts. //! //! This is part of the [Rune Language](https://rune-rs.github.io). pub(crate) mod compile; pub(crate) use self::compile::IrCompiler; mod error; pub use self::error::{IrError, IrErrorKind}; mod eval; pub(crate) use self::eval::{eval_ir, IrEvalOutcome}; mod interpreter; pub(crate) use self::interpreter::{IrBudget, IrInterpreter}; mod value; pub use self::value::IrValue; use crate::ast::{Span, Spanned}; use crate::compile::ast; use crate::compile::ir; use crate::compile::ir::eval::IrEvalBreak; use crate::compile::ItemMeta; use crate::hir; use crate::query::Used; /// Context used for [IrEval]. pub struct IrEvalContext<'a> { pub(crate) c: IrCompiler<'a>, pub(crate) item: &'a ItemMeta, } /// The trait for a type that can be compiled into intermediate representation. /// /// This is primarily used through [MacroContext::eval][crate::macros::MacroContext::eval]. pub trait IrEval { /// Evaluate the current value as a constant expression and return its value /// through its intermediate representation [IrValue]. fn eval(&self, ctx: &mut IrEvalContext<'_>) -> Result<IrValue, IrError>; } impl IrEval for ast::Expr { fn eval(&self, ctx: &mut IrEvalContext<'_>) -> Result<IrValue, IrError> { let ir = { // TODO: avoid this arena? let arena = crate::hir::Arena::new(); let hir_ctx = crate::hir::lowering::Ctx::new(&arena, ctx.c.q.borrow()); let hir = crate::hir::lowering::expr(&hir_ctx, self)?; compile::expr(&hir, &mut ctx.c)? }; let mut ir_interpreter = IrInterpreter { budget: IrBudget::new(1_000_000), scopes: Default::default(), module: ctx.item.module, item: ctx.item.item, q: ctx.c.q.borrow(), }; ir_interpreter.eval_value(&ir, Used::Used) } } macro_rules! decl_kind { ( $(#[$meta:meta])* $vis:vis enum $name:ident { $($(#[$field_meta:meta])* $variant:ident($ty:ty)),* $(,)? } ) => { $(#[$meta])* $vis enum $name { $($(#[$field_meta])* $variant($ty),)* } $( impl From<$ty> for $name { fn from(value: $ty) -> $name { $name::$variant(value) } } )* } } /// A single operation in the Rune intermediate language. #[derive(Debug, Clone, Spanned)] pub struct Ir { #[rune(span)] pub(crate) span: Span, pub(crate) kind: IrKind, } impl Ir { /// Construct a new intermediate instruction. pub(crate) fn new<S, K>(spanned: S, kind: K) -> Self where S: Spanned, IrKind: From<K>, { Self { span: spanned.span(), kind: IrKind::from(kind), } } } /// The target of a set operation. #[derive(Debug, Clone, Spanned)] pub struct IrTarget { /// Span of the target. #[rune(span)] pub(crate) span: Span, /// Kind of the target. pub(crate) kind: IrTargetKind, } /// The kind of the target. #[derive(Debug, Clone)] pub enum IrTargetKind { /// A variable. Name(Box<str>), /// A field target. Field(Box<IrTarget>, Box<str>), /// An index target. Index(Box<IrTarget>, usize), } decl_kind! { /// The kind of an intermediate operation. #[derive(Debug, Clone)] pub enum IrKind { /// Push a scope with the given instructions. Scope(IrScope), /// A binary operation. Binary(IrBinary), /// Declare a local variable with the value of the operand. Decl(IrDecl), /// Set the given target. Set(IrSet), /// Assign the given target. Assign(IrAssign), /// A template. Template(IrTemplate), /// A named value. Name(Box<str>), /// A local name. Could either be a local variable or a reference to /// something else, like another const declaration. Target(IrTarget), /// A constant value. Value(IrValue), /// A sequence of conditional branches. Branches(IrBranches), /// A loop. Loop(IrLoop), /// A break to the given target. Break(IrBreak), /// Constructing a vector. Vec(IrVec), /// Constructing a tuple. Tuple(IrTuple), /// Constructing an object. Object(IrObject), /// A call. Call(IrCall), } } /// An interpeted function. #[derive(Debug, Clone, Spanned)] pub struct IrFn { /// The span of the function. #[rune(span)] pub(crate) span: Span, /// The number of arguments the function takes and their names. pub(crate) args: Vec<Box<str>>, /// The scope for the function. pub(crate) ir: Ir, } impl IrFn { pub(crate) fn compile_ast( hir: &hir::ItemFn<'_>, c: &mut IrCompiler<'_>, ) -> Result<Self, IrError> { let mut args = Vec::new(); for arg in hir.args { if let hir::FnArg::Pat(hir::Pat { kind: hir::PatKind::PatPath(path), .. }) = arg { if let Some(ident) = path.try_as_ident() { args.push(c.resolve(ident)?.into()); continue; } } return Err(IrError::msg(arg, "unsupported argument in const fn")); } let ir_scope = compile::block(hir.body, c)?; Ok(ir::IrFn { span: hir.span(), args, ir: ir::Ir::new(hir.span(), ir_scope), }) } } /// Definition of a new variable scope. #[derive(Debug, Clone, Spanned)] pub struct IrScope { /// The span of the scope. #[rune(span)] pub(crate) span: Span, /// Instructions in the scope. pub(crate) instructions: Vec<Ir>, /// The implicit value of the scope. pub(crate) last: Option<Box<Ir>>, } /// A binary operation. #[derive(Debug, Clone, Spanned)] pub struct IrBinary { /// The span of the binary op. #[rune(span)] pub(crate) span: Span, /// The binary operation. pub(crate) op: IrBinaryOp, /// The left-hand side of the binary op. pub(crate) lhs: Box<Ir>, /// The right-hand side of the binary op. pub(crate) rhs: Box<Ir>, } /// A local variable declaration. #[derive(Debug, Clone, Spanned)] pub struct IrDecl { /// The span of the declaration. #[rune(span)] pub(crate) span: Span, /// The name of the variable. pub(crate) name: Box<str>, /// The value of the variable. pub(crate) value: Box<Ir>, } /// Set a target. #[derive(Debug, Clone, Spanned)] pub struct IrSet { /// The span of the set operation. #[rune(span)] pub(crate) span: Span, /// The target to set. pub(crate) target: IrTarget, /// The value to set the target. pub(crate) value: Box<Ir>, } /// Assign a target. #[derive(Debug, Clone, Spanned)] pub struct IrAssign { /// The span of the set operation. #[rune(span)] pub(crate) span: Span, /// The name of the target to assign. pub(crate) target: IrTarget, /// The value to assign. pub(crate) value: Box<Ir>, /// The assign operation. pub(crate) op: IrAssignOp, } /// A string template. #[derive(Debug, Clone, Spanned)] pub struct IrTemplate { /// The span of the template. #[rune(span)] pub(crate) span: Span, /// Template components. pub(crate) components: Vec<IrTemplateComponent>, } /// A string template. #[derive(Debug, Clone)] pub enum IrTemplateComponent { /// An ir expression. Ir(Ir), /// A literal string. String(Box<str>), } /// Branch conditions in intermediate representation. #[derive(Debug, Clone, Spanned)] pub struct IrBranches { /// Span associated with branches. #[rune(span)] pub span: Span, /// branches and their associated conditions. pub(crate) branches: Vec<(IrCondition, IrScope)>, /// The default fallback branch. pub(crate) default_branch: Option<IrScope>, } /// The condition for a branch. #[derive(Debug, Clone, Spanned)] pub enum IrCondition { /// A simple conditiona ir expression. Ir(Ir), /// A pattern match. Let(IrLet), } /// A pattern match. #[derive(Debug, Clone, Spanned)] pub struct IrLet { /// The span of the let condition. #[rune(span)] pub(crate) span: Span, /// The pattern. pub(crate) pat: IrPat, /// The expression the pattern is evaluated on. pub(crate) ir: Ir, } /// A pattern. #[derive(Debug, Clone)] pub enum IrPat { /// An ignore pattern `_`. Ignore, /// A named binding. Binding(Box<str>), } impl IrPat { fn compile_ast(hir: &hir::Pat<'_>, c: &mut IrCompiler<'_>) -> Result<Self, IrError> { match hir.kind { hir::PatKind::PatIgnore => return Ok(ir::IrPat::Ignore), hir::PatKind::PatPath(path) => { if let Some(ident) = path.try_as_ident() { let name = c.resolve(ident)?; return Ok(ir::IrPat::Binding(name.into())); } } _ => (), } Err(IrError::msg(hir, "pattern not supported yet")) } fn matches<S>( &self, interp: &mut IrInterpreter<'_>, value: IrValue, spanned: S, ) -> Result<bool, IrEvalOutcome> where S: Spanned, { match self { IrPat::Ignore => Ok(true), IrPat::Binding(name) => { interp.scopes.decl(name, value, spanned)?; Ok(true) } } } } /// A loop with an optional condition. #[derive(Debug, Clone, Spanned)] pub struct IrLoop { /// The span of the loop. #[rune(span)] pub(crate) span: Span, /// The label of the loop. pub(crate) label: Option<Box<str>>, /// The condition of the loop. pub(crate) condition: Option<Box<IrCondition>>, /// The body of the loop. pub(crate) body: IrScope, } /// A break operation. #[derive(Debug, Clone, Spanned)] pub struct IrBreak { /// The span of the break. #[rune(span)] pub(crate) span: Span, /// The kind of the break. pub(crate) kind: IrBreakKind, } impl IrBreak { fn compile_ast( span: Span, c: &mut IrCompiler<'_>, hir: Option<&hir::ExprBreakValue>, ) -> Result<Self, IrError> { let kind = match hir { Some(expr) => match *expr { hir::ExprBreakValue::Expr(e) => ir::IrBreakKind::Ir(Box::new(compile::expr(e, c)?)), hir::ExprBreakValue::Label(label) => { ir::IrBreakKind::Label(c.resolve(label)?.into()) } }, None => ir::IrBreakKind::Inherent, }; Ok(ir::IrBreak { span, kind }) } /// Evaluate the break into an [IrEvalOutcome]. fn as_outcome(&self, interp: &mut IrInterpreter<'_>, used: Used) -> IrEvalOutcome { let span = self.span(); if let Err(e) = interp.budget.take(span) { return e.into(); } match &self.kind { IrBreakKind::Ir(ir) => match ir::eval_ir(ir, interp, used) { Ok(value) => IrEvalOutcome::Break(span, IrEvalBreak::Value(value)), Err(err) => err, }, IrBreakKind::Label(label) => { IrEvalOutcome::Break(span, IrEvalBreak::Label(label.clone())) } IrBreakKind::Inherent => IrEvalOutcome::Break(span, IrEvalBreak::Inherent), } } } /// The kind of a break expression. #[derive(Debug, Clone)] pub enum IrBreakKind { /// Break to the next loop. Inherent, /// Break to the given label. Label(Box<str>), /// Break with the value acquired from evaluating the ir. Ir(Box<Ir>), } /// Tuple expression. #[derive(Debug, Clone, Spanned)] pub struct IrTuple { /// Span of the tuple. #[rune(span)] pub(crate) span: Span, /// Arguments to construct the tuple. pub(crate) items: Box<[Ir]>, } /// Object expression. #[derive(Debug, Clone, Spanned)] pub struct IrObject { /// Span of the object. #[rune(span)] pub(crate) span: Span, /// Field initializations. pub(crate) assignments: Box<[(Box<str>, Ir)]>, } /// Call expressions. #[derive(Debug, Clone, Spanned)] pub struct IrCall { /// Span of the call. #[rune(span)] pub(crate) span: Span, /// The target of the call. pub(crate) target: Box<str>, /// Arguments to the call. pub(crate) args: Vec<Ir>, } /// Vector expression. #[derive(Debug, Clone, Spanned)] pub struct IrVec { /// Span of the vector. #[rune(span)] pub(crate) span: Span, /// Arguments to construct the vector. pub(crate) items: Box<[Ir]>, } /// A binary operation. #[derive(Debug, Clone, Copy)] pub enum IrBinaryOp { /// Add `+`. Add, /// Subtract `-`. Sub, /// Multiplication `*`. Mul, /// Division `/`. Div, /// `<<`. Shl, /// `>>`. Shr, /// `<`, Lt, /// `<=`, Lte, /// `==`, Eq, /// `>`, Gt, /// `>=`, Gte, } /// An assign operation. #[derive(Debug, Clone, Copy)] pub enum IrAssignOp { /// `+=`. Add, /// `-=`. Sub, /// `*=`. Mul, /// `/=`. Div, /// `<<=`. Shl, /// `>>=`. Shr, } impl IrAssignOp { /// Perform the given assign operation. pub(crate) fn assign<S>( self, spanned: S, target: &mut IrValue, operand: IrValue, ) -> Result<(), IrError> where S: Copy + Spanned, { if let IrValue::Integer(target) = target { if let IrValue::Integer(operand) = operand { return self.assign_int(spanned, target, operand); } } Err(IrError::msg(spanned, "unsupported operands")) } /// Perform the given assign operation. fn assign_int<S>( self, spanned: S, target: &mut num::BigInt, operand: num::BigInt, ) -> Result<(), IrError> where S: Copy + Spanned, { use std::ops::{AddAssign, MulAssign, ShlAssign, ShrAssign, SubAssign}; match self { IrAssignOp::Add => { target.add_assign(operand); } IrAssignOp::Sub => { target.sub_assign(operand); } IrAssignOp::Mul => { target.mul_assign(operand); } IrAssignOp::Div => { *target = target .checked_div(&operand) .ok_or_else(|| IrError::msg(spanned, "division by zero"))?; } IrAssignOp::Shl => { let operand = u32::try_from(operand).map_err(|_| IrError::msg(spanned, "bad operand"))?; target.shl_assign(operand); } IrAssignOp::Shr => { let operand = u32::try_from(operand).map_err(|_| IrError::msg(spanned, "bad operand"))?; target.shr_assign(operand); } } Ok(()) } }
true
54225ea4aaed6a80c6edbebd8cfff3f66363b88d
Rust
iCodeIN/miro
/src/config.rs
UTF-8
5,661
3.25
3
[ "MIT" ]
permissive
//! Configuration for the gui portion of the terminal use failure::Error; use std; use std::fs; use std::io::prelude::*; use toml; use term; use term::color::RgbColor; #[derive(Debug, Deserialize, Clone)] pub struct Config { /// The font size, measured in points #[serde(default = "default_font_size")] pub font_size: f64, /// The DPI to assume #[serde(default = "default_dpi")] pub dpi: f64, /// The baseline font to use #[serde(default)] pub font: TextStyle, /// An optional set of style rules to select the font based /// on the cell attributes #[serde(default)] pub font_rules: Vec<StyleRule>, /// The color palette pub colors: Option<Palette>, /// How many lines of scrollback you want to retain pub scrollback_lines: Option<usize>, } fn default_font_size() -> f64 { 10.0 } fn default_dpi() -> f64 { 96.0 } impl Default for Config { fn default() -> Self { Self { font_size: default_font_size(), dpi: default_dpi(), font: TextStyle::default(), font_rules: Vec::new(), colors: None, scrollback_lines: None, } } } /// Represents textual styling. /// TODO: I want to add some rules so that a user can specify the font /// and colors to use in some situations. For example, xterm has /// a bold color option; I'd like to be able to express something /// like "when text is bold, use this font pattern and set the text /// color to X". There are some interesting possibilities here; /// instead of just setting the color to a specific value we could /// apply a transform to the color attribute and make it X% brighter. #[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)] pub struct TextStyle { /// A font config pattern to parse to locate the font. /// Note that the dpi and current font_size for the terminal /// will be set on the parsed result. pub fontconfig_pattern: String, /// If set, when rendering text that is set to the default /// foreground color, use this color instead. This is most /// useful in a `[[font_rules]]` section to implement changing /// the text color for eg: bold text. pub foreground: Option<RgbColor>, } impl Default for TextStyle { fn default() -> Self { Self { fontconfig_pattern: "monospace".into(), foreground: None } } } /// Defines a rule that can be used to select a TextStyle given /// an input CellAttributes value. The logic that applies the /// matching can be found in src/font/mod.rs. The concept is that /// the user can specify something like this: /// /// ``` /// [[font_rules]] /// italic = true /// font = { fontconfig_pattern = "Operator Mono SSm Lig:style=Italic" } /// ``` /// /// The above is translated as: "if the CellAttributes have the italic bit /// set, then use the italic style of font rather than the default", and /// stop processing further font rules. #[derive(Debug, Deserialize, Clone)] pub struct StyleRule { /// If present, this rule matches when CellAttributes::intensity holds /// a value that matches this rule. Valid values are "Bold", "Normal", /// "Half". pub intensity: Option<term::Intensity>, /// If present, this rule matches when CellAttributes::underline holds /// a value that matches this rule. Valid values are "None", "Single", /// "Double". pub underline: Option<term::Underline>, /// If present, this rule matches when CellAttributes::italic holds /// a value that matches this rule. pub italic: Option<bool>, /// If present, this rule matches when CellAttributes::blink holds /// a value that matches this rule. pub blink: Option<bool>, /// If present, this rule matches when CellAttributes::reverse holds /// a value that matches this rule. pub reverse: Option<bool>, /// If present, this rule matches when CellAttributes::strikethrough holds /// a value that matches this rule. pub strikethrough: Option<bool>, /// If present, this rule matches when CellAttributes::invisible holds /// a value that matches this rule. pub invisible: Option<bool>, /// When this rule matches, `font` specifies the styling to be used. pub font: TextStyle, } #[derive(Debug, Deserialize, Clone)] pub struct Palette { /// The text color to use when the attributes are reset to default pub foreground: Option<RgbColor>, /// The background color to use when the attributes are reset to default pub background: Option<RgbColor>, /// The color of the cursor pub cursor: Option<RgbColor>, /// A list of 8 colors corresponding to the basic ANSI palette pub ansi: Option<[RgbColor; 8]>, /// A list of 8 colors corresponding to bright versions of the /// ANSI palette pub brights: Option<[RgbColor; 8]>, } impl From<Palette> for term::color::ColorPalette { fn from(cfg: Palette) -> term::color::ColorPalette { let mut p = term::color::ColorPalette::default(); if let Some(foreground) = cfg.foreground { p.foreground = foreground; } if let Some(background) = cfg.background { p.background = background; } if let Some(cursor) = cfg.cursor { p.cursor = cursor; } if let Some(ansi) = cfg.ansi { for (idx, col) in ansi.iter().enumerate() { p.colors[idx] = *col; } } if let Some(brights) = cfg.brights { for (idx, col) in brights.iter().enumerate() { p.colors[idx + 8] = *col; } } p } }
true
eab30fbf433a93ec3e398a04826a8fc86639c090
Rust
hkws/exercism-rust
/tournament/src/lib.rs
UTF-8
3,573
3.609375
4
[]
no_license
#[derive(Clone)] struct TeamScore { name: String, won: u32, drawn: u32, lost: u32, } impl TeamScore { pub fn new(name: String) -> Self { Self { name: name, won: 0, drawn: 0, lost: 0 } } pub fn won(&mut self){ self.won += 1; } pub fn drawn(&mut self){ self.drawn += 1; } pub fn lost(&mut self){ self.lost += 1; } pub fn get_mp(&self) -> u32 { self.won+self.drawn+self.lost } pub fn get_point(&self) -> u32 { self.won*3+self.drawn } pub fn stringify(&self) -> String { format!("{: <31}| {} | {} | {} | {} | {}", &self.name, self.get_mp(), self.won, self.drawn, self.lost, self.get_point()) } } use std::collections::HashMap; pub fn tally(match_results: &str) -> String { let mut table = HashMap::new(); for line in match_results.lines() { let tokens: Vec<&str> = line.split(';').collect(); let (teama, teamb, result) = (tokens[0], tokens[1], tokens[2]); // 本当はlet (teama, teamb, result) = line.split(',').collect();がしたいが // let tokens: Vec<&str> = line.split(';').collect(); // let (teama, teamb, result) = (tokens[0], tokens[1], tokens[2]); // しかなさそう table.entry(teama).or_insert(TeamScore::new(teama.to_string())); table.entry(teamb).or_insert(TeamScore::new(teamb.to_string())); match result { "win" => { table.get_mut(teama).unwrap().won(); table.get_mut(teamb).unwrap().lost(); }, "loss" => { table.get_mut(teama).unwrap().lost(); table.get_mut(teamb).unwrap().won(); }, "draw" => { table.get_mut(teama).unwrap().drawn(); table.get_mut(teamb).unwrap().drawn(); }, _ => unimplemented!() } } let mut teamscores: Vec<TeamScore> = table.values().cloned().collect::<Vec<TeamScore>>(); // cloneせずにsortする方法が知りたい // let mut teamscores: Vec<&TeamScore> = table.values().collect::<Vec<&TeamScore>>(); // これで行けた、参照さえ取得すれば十分。たしかに。 teamscores.sort_by_key(|k| k.name.clone()); teamscores.reverse(); teamscores.sort_by_key(|k| k.get_point()); teamscores.reverse(); // 名前でsortした後pointでsortができない。。。 // teamscores.sort_by(|a, b| b.get_point().cmp(&a.get_point()). // then_with(|| a.name.cmp(&b.name))); // これでいけるみたい。sort_byとthen_with。 let mut result_table: String = "Team | MP | W | D | L | P".to_string(); for team in teamscores { result_table += "\n"; result_table += &team.stringify(); // 自前のstringifyはあんまrustっぽくない気がする // rust的に書くなら // impl From<&TeamScore> for String { // fn from(origin: &TeamScore) -> String { // format!("{: <31}| {} | {} | {} | {} | {}", &self.name, self.get_mp(), self.won, self.drawn, self.lost, self.get_point()) // } // } // このように、型どうしの変換を実装するときは、From<変換元> for 変換先をimplする // 逆変換としてIntoがあり、これはFromを実装したら自動で使えるようになる } result_table }
true
15502df188af1f21d6c8d8c17b60807e243faa63
Rust
binh-vu/semantic-modeling
/rdb2rdf/src/models/semantic_model.rs
UTF-8
2,419
2.734375
3
[ "MIT" ]
permissive
use serde_json::{ Value, from_value }; use serde::Deserialize; use serde::Deserializer; use algorithm::data_structure::graph::Graph; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct SemanticType { #[serde(rename = "domain")] pub class_uri: String, #[serde(rename = "type")] pub predicate: String, #[serde(rename = "confidence_score")] pub score: f32 } #[derive(Serialize, Deserialize, Clone)] pub struct Attribute { pub id: usize, pub label: String, pub semantic_types: Vec<SemanticType> } #[derive(Serialize, Clone)] pub struct SemanticModel { #[serde(rename = "name")] pub id: String, pub attrs: Vec<Attribute>, pub graph: Graph, #[serde(skip)] id2attrs: Vec<usize> } impl SemanticModel { pub fn new(id: String, attrs: Vec<Attribute>, graph: Graph) -> SemanticModel { let mut id2attrs: Vec<usize> = vec![attrs.len() + 100; graph.n_nodes]; for (i, attr) in attrs.iter().enumerate() { id2attrs[attr.id] = i; } SemanticModel { id, attrs, graph, id2attrs } } pub fn empty(id: String) -> SemanticModel { SemanticModel { attrs: Vec::new(), graph: Graph::new(id.clone(), true, true, true), id2attrs: Vec::new(), id, } } pub fn get_attr_by_label(&self, lbl: &str) -> &Attribute { &self.attrs[self.id2attrs[self.graph.get_first_node_by_label(lbl).id]] } } impl<'de> Deserialize<'de> for SemanticModel { fn deserialize<D>(deserializer: D) -> Result<SemanticModel, D::Error> where D: Deserializer<'de> { let result = Value::deserialize(deserializer); match result { Err(e) => Err(e), Ok(mut val) => { let attrs: Vec<Attribute> = from_value(val["attrs"].take()).unwrap(); let graph: Graph = Graph::from_dict(&val["graph"]); let mut id2attrs: Vec<usize> = vec![attrs.len() + 100; graph.n_nodes]; for (i, attr) in attrs.iter().enumerate() { id2attrs[attr.id] = i; } Ok(SemanticModel { id: val["name"].as_str().unwrap().to_owned(), attrs, graph, id2attrs }) }, } } }
true
52338cf30d86a2900022c0fb481b67e0293dea53
Rust
orsenkucher/.spacemacs.d
/home/sources-for-rust-analyzer/crates/vfs-notify/src/include.rs
UTF-8
1,336
3.390625
3
[ "MIT", "Apache-2.0" ]
permissive
//! See `Include`. use std::convert::TryFrom; use globset::{Glob, GlobSet, GlobSetBuilder}; use paths::{RelPath, RelPathBuf}; /// `Include` is the opposite of .gitignore. /// /// It describes the set of files inside some directory. /// /// The current implementation is very limited, it allows white-listing file /// globs and black-listing directories. #[derive(Debug, Clone)] pub(crate) struct Include { include_files: GlobSet, exclude_dirs: Vec<RelPathBuf>, } impl Include { pub(crate) fn new(include: Vec<String>) -> Include { let mut include_files = GlobSetBuilder::new(); let mut exclude_dirs = Vec::new(); for glob in include { if glob.starts_with("!/") { if let Ok(path) = RelPathBuf::try_from(&glob["!/".len()..]) { exclude_dirs.push(path) } } else { include_files.add(Glob::new(&glob).unwrap()); } } let include_files = include_files.build().unwrap(); Include { include_files, exclude_dirs } } pub(crate) fn include_file(&self, path: &RelPath) -> bool { self.include_files.is_match(path) } pub(crate) fn exclude_dir(&self, path: &RelPath) -> bool { self.exclude_dirs.iter().any(|excluded| path.starts_with(excluded)) } }
true
cc6fa04c9f29a35485349493bb97cfbbe1555cc9
Rust
lazka/cargo-c
/src/install_paths.rs
UTF-8
1,400
2.859375
3
[ "MIT" ]
permissive
use std::path::PathBuf; use structopt::clap::ArgMatches; #[derive(Debug)] pub struct InstallPaths { pub destdir: PathBuf, pub prefix: PathBuf, pub libdir: PathBuf, pub includedir: PathBuf, pub bindir: PathBuf, pub pkgconfigdir: PathBuf, } impl InstallPaths { pub fn from_matches(args: &ArgMatches<'_>) -> Self { let destdir = args .value_of("destdir") .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from("/")); let prefix = args .value_of("prefix") .map(PathBuf::from) .unwrap_or_else(|| "/usr/local".into()); let libdir = args .value_of("libdir") .map(PathBuf::from) .unwrap_or_else(|| prefix.join("lib")); let includedir = args .value_of("includedir") .map(PathBuf::from) .unwrap_or_else(|| prefix.join("include")); let bindir = args .value_of("bindir") .map(PathBuf::from) .unwrap_or_else(|| prefix.join("bin")); let pkgconfigdir = args .value_of("pkgconfigdir") .map(PathBuf::from) .unwrap_or_else(|| libdir.join("pkgconfig")); InstallPaths { destdir, prefix, libdir, includedir, bindir, pkgconfigdir, } } }
true
a0b25ec8d0421f6d9bd06e747b906e5ca7a8fbf3
Rust
masonium/art-util
/tests/frustum.rs
UTF-8
2,584
2.78125
3
[]
no_license
#[cfg(test)] mod test { use art_util::Frustum; use assert_approx_eq::assert_approx_eq; use na::{Vector3, Vector4}; use nalgebra as na; use nalgebra_glm as glm; #[test] fn test_frustum_ortho() { let frustum: Frustum<f64> = Frustum::from_clip_matrix(&glm::ortho_rh(-1.0, 1.0, -1.0, 1.0, 0.0, 1.0)); let target_planes: Vec<_> = [ Vector4::new(1.0, 0.0, 0.0, 1.0), Vector4::new(-1.0, 0.0, 0.0, 1.0), Vector4::new(0.0, 1.0, 0.0, 1.0), Vector4::new(0.0, -1.0, 0.0, 1.0), Vector4::new(0.0, 0.0, -1.0, 0.0), Vector4::new(0.0, 0.0, 1.0, 1.0), ] .iter() .map(|x| x.normalize()) .collect(); for i in 0..6 { assert_approx_eq!(frustum.planes[i].normalize().dot(&target_planes[i]), 1.0); } } #[test] fn test_frustum_ortho_shift() { // If we move the eye 2 units the right, the left and right planes should shift. let view = glm::look_at_rh( &Vector3::new(2.0, 0.0, 0.0), &Vector3::new(2.0, 0.0, -1.0), &Vector3::new(0.0, 1.0, 0.0), ); let frustum: Frustum<f64> = Frustum::from_clip_matrix(&(glm::ortho_rh(-1.0, 1.0, -1.0, 1.0, 0.0, 1.0) * view)); let target_planes: Vec<_> = [ Vector4::new(1.0, 0.0, 0.0, -1.0), Vector4::new(-1.0, 0.0, 0.0, 3.0), Vector4::new(0.0, 1.0, 0.0, 1.0), Vector4::new(0.0, -1.0, 0.0, 1.0), Vector4::new(0.0, 0.0, -1.0, 0.0), Vector4::new(0.0, 0.0, 1.0, 1.0), ] .iter() .map(|x| x.normalize()) .collect(); for i in 0..6 { assert_approx_eq!(frustum.planes[i].normalize().dot(&target_planes[i]), 1.0); } } #[test] fn test_frustum_perspective() { let frustum: Frustum<f64> = Frustum::from_clip_matrix( &(glm::perspective_rh(1.0, std::f64::consts::FRAC_PI_2, 0.01, 1.0)), ); let target_planes: Vec<_> = [ Vector4::new(1.0, 0.0, -1.0, 0.0), Vector4::new(-1.0, 0.0, -1.0, 0.0), Vector4::new(0.0, 1.0, -1.0, 0.0), Vector4::new(0.0, -1.0, -1.0, 0.0), Vector4::new(0.0, 0.0, -1.0, -0.01), Vector4::new(0.0, 0.0, 1.0, 1.0), ] .iter() .map(|x| x.normalize()) .collect(); for i in 0..6 { assert_approx_eq!(frustum.planes[i].normalize().dot(&target_planes[i]), 1.0); } } }
true
2823cc24bcc82216626e22b99d94f28ee082a762
Rust
irauta/htgl
/src/bin/app.rs
UTF-8
5,316
2.53125
3
[ "Apache-2.0" ]
permissive
// Copyright 2015 Ilkka Rauta // // 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. extern crate glfw; extern crate htgl; use glfw::Context; use htgl::{VertexAttributeType, RenderOption, ShaderType, PrimitiveMode, SimpleUniformTypeFloat}; #[allow(dead_code)] #[repr(packed)] struct Vec3 { x: f32, y: f32, z: f32, } #[allow(dead_code)] #[repr(packed)] struct Rgba { r: u8, g: u8, b: u8, a: u8, } #[allow(dead_code)] #[repr(packed)] struct Vertex { position: Vec3, color: Rgba } impl Vertex { fn new(x: f32, y: f32, z: f32, r: u8, g: u8, b: u8, a: u8) -> Vertex { Vertex { position: Vec3 { x: x, y: y, z: z }, color: Rgba { r: r, g: g, b: b, a: a } } } } static VS_SOURCE: &'static str = " #version 330 core layout(location = 0) in vec3 position; layout(location = 1) in vec4 color; uniform float scale; out vec4 v_color; void main() { gl_Position.xyz = position * scale; gl_Position.w = 1.0; v_color = color; } "; static FS_SOURCE: &'static str = " #version 330 core in vec4 v_color; out vec3 color; void main() { color = v_color.rgb; } "; fn main() { let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true)); // Create a windowed mode window and its OpenGL context let (mut window, events) = glfw.create_window(300, 300, "Hello this is window", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window."); window.set_key_polling(true); window.make_current(); htgl::load_with(|s| window.get_proc_address(s)); let mut ctx = htgl::Context::new(); println!("{:?}", ctx.get_info()); ctx.renderer().set_option(RenderOption::ClearColor(1f32, 1f32, 1f32, 1f32)); ctx.renderer().set_option(RenderOption::DepthTest(false)); ctx.renderer().set_option(RenderOption::CullingEnabled(true)); let vbo = ctx.new_buffer(); let vertices = [ Vertex::new(-0.5f32, -0.5f32, 0f32, 255, 0, 0, 0), Vertex::new(0.5f32, -0.5f32, 0f32, 0, 255, 0, 0), Vertex::new(0f32, 0.5f32, 0f32, 0, 0, 255, 0), ]; ctx.edit_vertex_buffer(&vbo).data(&vertices); let ibo = ctx.new_buffer(); let vao = ctx.new_vertex_array_simple(&[(3, VertexAttributeType::Float, false), (4, VertexAttributeType::UnsignedByte, true)], vbo, Some(ibo)); if let Some(mut editor) = ctx.edit_index_buffer(&vao) { let indices = [0u16, 1u16, 2u16]; editor.data(&indices); } let vs = ctx.new_shader(ShaderType::VertexShader, VS_SOURCE); if !ctx.shader_info(&vs).get_compile_status() { panic!(ctx.shader_info(&vs).get_info_log()) } let fs = ctx.new_shader(ShaderType::FragmentShader, FS_SOURCE); if !ctx.shader_info(&fs).get_compile_status() { panic!(ctx.shader_info(&fs).get_info_log()) } let program = ctx.new_program(&[vs, fs]); if !ctx.program_info(&program).get_link_status() { panic!(ctx.program_info(&program).get_info_log()) } { let program_editor = ctx.edit_program(&program); let program_info = program_editor.program_info(); let uniform_info = program_info.get_uniform_info(); let scale_location = uniform_info.get_global_uniform("scale").map(|u| u.location).unwrap_or(-1); program_editor.uniform_f32(scale_location, 1, SimpleUniformTypeFloat::Uniform1f, &[1.5]); for uniform in uniform_info.globals.iter() { println!("{:?}", uniform); } for block in uniform_info.blocks.iter() { println!("InterfaceBlock {{ name: {}, index: {}, data_size: {} }}", block.name, block.index, block.data_size); for uniform in block.uniforms.iter() { println!(" {:?}", uniform); } } for attribute in program_info.get_attribute_info().attributes.iter() { println!("{:?}", attribute) } } while !window.should_close() { glfw.poll_events(); for (_, event) in glfw::flush_messages(&events) { handle_window_event(&mut window, event); } let mut renderer = ctx.renderer(); renderer.clear(); renderer.use_vertex_array(&vao); renderer.use_program(&program); renderer.draw_elements_u16(PrimitiveMode::Triangles, 3, 0); window.swap_buffers(); // break; } } fn handle_window_event(window: &mut glfw::Window, event: glfw::WindowEvent) { match event { glfw::WindowEvent::Key(glfw::Key::Escape, _, glfw::Action::Press, _) => { window.set_should_close(true) } _ => {} } }
true
3cdcfdc44937132391a5466c760a513943591c80
Rust
maciejhirsz/logos
/logos-cli/src/main.rs
UTF-8
2,856
2.921875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
use std::{ fmt::Write, io, path::PathBuf, process::{Command, Stdio}, }; use anyhow::{Context, Result}; use clap::Parser; use fs_err as fs; use proc_macro2::{LexError, TokenStream}; /// Logos as a CLI! #[derive(Parser)] #[clap(author, version, about, long_about = None)] pub struct Args { /// Input file to process #[clap(parse(from_os_str))] input: PathBuf, /// Path to write output. By default output is printed to stdout. #[clap(long, short, parse(from_os_str))] output: Option<PathBuf>, /// Checks whether the output file is up-to-date instead of writing to it. Requires --output to be specified. #[clap(long, requires = "output")] check: bool, /// Invokes `rustfmt` on the generated code. `rustfmt` must be in $PATH. #[clap(long)] format: bool, } pub fn main() -> Result<()> { let args = Args::parse(); let input = fs::read_to_string(args.input)?; let mut output = codegen(input).context("failed to run rustfmt")?; if args.format { output = rustfmt(output)?; } if let Some(output_path) = args.output { let changed = match fs::read_to_string(&output_path) { Ok(existing_output) => !eq_ignore_newlines(&existing_output, &output), Err(err) if err.kind() == io::ErrorKind::NotFound => true, Err(err) => return Err(err.into()), }; if !changed { Ok(()) } else if args.check { Err(anyhow::format_err!( "contents of {} differed from generated code", output_path.display() )) } else { fs::write(output_path, output)?; Ok(()) } } else { println!("{}", output); Ok(()) } } fn codegen(input: String) -> Result<String> { let input_tokens: TokenStream = input .parse() .map_err(|err: LexError| anyhow::Error::msg(err.to_string())) .context("failed to parse input as rust code")?; let mut output = String::new(); write!( output, "{}", logos_codegen::strip_attributes(input_tokens.clone()) )?; write!(output, "{}", logos_codegen::generate(input_tokens))?; Ok(output) } fn rustfmt(input: String) -> Result<String> { let mut command = Command::new("rustfmt") .stdin(Stdio::piped()) .stderr(Stdio::inherit()) .stdout(Stdio::piped()) .spawn()?; io::Write::write_all(&mut command.stdin.take().unwrap(), input.as_bytes())?; let output = command.wait_with_output()?; if !output.status.success() { anyhow::bail!("rustfmt returned unsuccessful exit code"); } String::from_utf8(output.stdout).context("failed to parse rustfmt output as utf-8") } fn eq_ignore_newlines(lhs: &str, rhs: &str) -> bool { lhs.lines().eq(rhs.lines()) }
true
f5460cc137d1423c140c71be7104d2c6af14bfc6
Rust
sphynx/rt
/src/main.rs
UTF-8
4,647
2.9375
3
[]
no_license
//! This is directly based on Peter Shirley's "Ray Tracing in One //! Weekend". use rand::prelude::*; use rayon::prelude::*; use rt::MaterialResponse::*; use rt::*; use std::f32; use std::sync::Arc; fn color<T: Hitable + ?Sized>(ray: &Ray, world: &T, depth: u32) -> Vec3 { if let Some(hit) = world.hit(ray, 0.001, f32::MAX) { if depth < 50 { match hit.material.scatter(ray, &hit) { Absorbed => Vec3::zero(), Scattered { attenuation, ray } => attenuation * color(&ray, world, depth + 1), } } else { Vec3::zero() } } else { // Draw gradient background. let unit_direction = Vec3::unit_vector(ray.direction()); let t = 0.5 * (unit_direction.y() + 1.0); let white = Vec3(1.0, 1.0, 1.0); let blue = Vec3(0.5, 0.7, 1.0); // Interpolate between white and "blue". (1.0 - t) * white + t * blue } } fn random_scene() -> Vec<Sphere> { let mut scene = Vec::with_capacity(500); scene.push(Sphere { center: Vec3(0.0, -1000.0, 0.0), radius: 1000.0, material: Arc::new(Lambertian::new(Vec3(0.5, 0.5, 0.5))), }); let mut rng = rand::thread_rng(); for a in -11..11_i16 { for b in -11..11_i16 { let choose_mat: f32 = rng.gen(); let mut rnd = || rng.gen::<f32>(); let center = Vec3(f32::from(a) + 0.9 * rnd(), 0.2, f32::from(b) + 0.9 * rnd()); if (center - Vec3(4.0, 0.2, 0.0)).length() > 0.9 { let material: Arc<dyn Material + Send + Sync>; if choose_mat < 0.8 { // Diffuse. let albedo = Vec3(rnd() * rnd(), rnd() * rnd(), rnd() * rnd()); material = Arc::new(Lambertian::new(albedo)); } else if choose_mat < 0.95 { // Metal. let albedo = Vec3( 0.5 * (1.0 + rnd()), 0.5 * (1.0 + rnd()), 0.5 * (1.0 + rnd()), ); let fuzz = 0.5 * rnd(); material = Arc::new(Metal::new(albedo, fuzz)); } else { // Glass. let refr_index = 1.5; material = Arc::new(Dielectric::new(refr_index)); } scene.push(Sphere { center, radius: 0.2, material, }); } } } scene.push(Sphere { center: Vec3(0.0, 1.0, 0.0), radius: 1.0, material: Arc::new(Dielectric::new(1.5)), }); scene.push(Sphere { center: Vec3(-4.0, 1.0, 0.0), radius: 1.0, material: Arc::new(Lambertian::new(Vec3(0.4, 0.2, 0.1))), }); scene.push(Sphere { center: Vec3(4.0, 1.0, 0.0), radius: 1.0, material: Arc::new(Metal::new(Vec3(0.7, 0.6, 0.5), 0.0)), }); scene } fn main() { let nx = 1200_i16; let ny = 800_i16; let ns = 20_i16; println!("P3 {} {} 255", nx, ny); let world = random_scene(); let aspect = f32::from(nx) / f32::from(ny); let look_from = Vec3(13.0, 2.0, 3.0); let look_at = Vec3(0.0, 0.0, 0.0); let camera = Camera::new(CameraSettings { look_from, look_at, v_up: Vec3(0.0, 1.0, 0.0), v_fov: 20.0, aspect, aperture: 0.1, focus_dist: 10.0, }); let rows: Vec<Vec<Vec3>> = (0..ny) .into_par_iter() .rev() .map(|j| { (0..nx) .into_par_iter() .map(|i| { let mut rng = rand::thread_rng(); let mut pixel_color = Vec3::zero(); // Antialiasing by averaging of random samples. for _ in 0..ns { let u = (f32::from(i) + rng.gen::<f32>()) / f32::from(nx); let v = (f32::from(j) + rng.gen::<f32>()) / f32::from(ny); let r = camera.get_ray(u, v); pixel_color += color(&r, &world[..], 0); } pixel_color /= f32::from(ns); pixel_color.sqrt_coords(); // Basic gamma correction. pixel_color *= 255.99; pixel_color }) .collect() }) .collect(); for r in rows { for col in r { println!("{} {} {}", col.r() as u32, col.g() as u32, col.b() as u32); } } }
true
aa62782b460b8df10ba73eb52ca949e98ab3b9ed
Rust
Isaac-Lozano/rusty_chess_ai
/src/color.rs
UTF-8
1,664
3.640625
4
[]
no_license
#![allow(dead_code)] pub enum Color { Black = 0, Red = 1, Green = 2, Yellow = 3, Blue = 4, Magenta = 5, Cyan = 6, White = 7, } pub fn get_color_escape_code(foreground_color: Color, background_color: Color) -> String { let foreground_color_code = get_foreground_color_code(foreground_color); let background_color_code = get_background_color_code(background_color); format!("\x1b[1;{};{}m", foreground_color_code, background_color_code) } pub fn get_color_reset_code() -> String { String::from("\x1b[0m") } fn get_foreground_color_code(color: Color) -> u32 { const FOREGROUND_COLOR_BASE: u32 = 30; FOREGROUND_COLOR_BASE + (color as u32) } fn get_background_color_code(color: Color) -> u32 { const BACKGROUND_COLOR_BASE: u32 = 40; BACKGROUND_COLOR_BASE + (color as u32) } #[test] fn test_get_color_escape_code() { assert_eq!("\x1b[1;31;40m", get_color_escape_code(Color::Red, Color::Black)); assert_eq!("\x1b[1;32;44m", get_color_escape_code(Color::Green, Color::Blue)); } #[test] fn test_get_color_reset_code() { assert_eq!("\x1b[0m", get_color_reset_code()); } #[test] fn test_get_foreground_color_code() { assert_eq!(30, get_foreground_color_code(Color::Black)); assert_eq!(33, get_foreground_color_code(Color::Yellow)); assert_eq!(37, get_foreground_color_code(Color::White)); } #[test] fn test_get_background_color_code() { assert_eq!(40, get_background_color_code(Color::Black)); assert_eq!(43, get_background_color_code(Color::Yellow)); assert_eq!(47, get_background_color_code(Color::White)); }
true
6821253247bebe627ee426bbceafe800f76133b2
Rust
Lapz/tox
/semant/src/infer/binary.rs
UTF-8
2,842
2.640625
3
[ "MIT" ]
permissive
use crate::{ hir::{BinOp, ExprId, FunctionAstMap}, infer::{InferDataCollector, Type, TypeCon}, typed, util::Span, HirDatabase, }; impl<'a, DB> InferDataCollector<&'a DB> where DB: HirDatabase, { pub(crate) fn infer_binary( &mut self, id: &Span<ExprId>, lhs: &Span<ExprId>, op: &BinOp, rhs: &Span<ExprId>, map: &FunctionAstMap, ) -> typed::Typed<typed::Expr> { let inferred_lhs = self.infer_expr(map, lhs); let lhs_ty = inferred_lhs.ty.clone(); let inferred_rhs = self.infer_expr(map, rhs); let rhs_ty = inferred_rhs.ty.clone(); // TODO check if doing operations on ints and floats only let ty = match op { BinOp::Plus | BinOp::Minus | BinOp::Mult | BinOp::Div => { self.unify( &lhs_ty, &rhs_ty, id.as_reporter_span(), Some("`+`,`-`,`*`,`/` operators only works on i32 and f32".into()), true, ); lhs_ty } BinOp::And | BinOp::Or => { self.unify( &Type::Con(TypeCon::Bool), &lhs_ty, lhs.as_reporter_span(), Some("Expected a bool".into()), true, ); self.unify( &Type::Con(TypeCon::Bool), &rhs_ty, rhs.as_reporter_span(), Some("Expected a bool".into()), true, ); Type::Con(TypeCon::Bool) } BinOp::LessThan | BinOp::GreaterThan | BinOp::GreaterThanEqual | BinOp::LessThanEqual => { self.unify( &lhs_ty, &rhs_ty, id.as_reporter_span(), Some("Comparison operators only work on numbers".into()), true, ); Type::Con(TypeCon::Bool) } BinOp::Equal => { self.unify(&lhs_ty, &rhs_ty, id.as_reporter_span(), None, true); rhs_ty } BinOp::EqualEqual | BinOp::NotEqual => Type::Con(TypeCon::Bool), BinOp::PlusEqual | BinOp::MinusEqual | BinOp::MultEqual | BinOp::DivEqual => { self.unify(&lhs_ty, &rhs_ty, id.as_reporter_span(), None, true); rhs_ty } }; typed::Typed::new( typed::Expr::Binary { lhs: Box::new(inferred_lhs), op: *op, rhs: Box::new(inferred_rhs), }, ty, (id.start, id.end), ) } }
true
cf2442d3f1b9b0ea2b599224353d59bb8c053741
Rust
cshung/Competition
/rust_competition/src/leetcode/jump_game_ii.rs
UTF-8
849
3.03125
3
[]
no_license
use std::cmp; impl Solution { pub fn jump(nums: Vec<i32>) -> i32 { let n = nums.len(); let mut dp = vec![None; n]; dp[n - 1] = Some(0); for j in 0..(n - 1) { let i = n - 2 - j; let k = cmp::min(i + nums[i] as usize, n - 1); for d in (i + 1)..(k + 1) { if let Some(cost) = dp[d] { if let Some(cur) = dp[i] { if cur > (1 + cost) { dp[i] = Some(1 + cost); } } else { dp[i] = Some(1 + cost); } } } } return dp[0].unwrap(); } } struct Solution {} pub fn jump_game_ii() { let answer = Solution::jump(vec![2, 3, 1, 1, 4]); println!("{}", answer); }
true
afd1a538c0fb58c1245ccceb00fcccbc236cd875
Rust
andrew749/log-query
/src/output/handlebars_output_generator.rs
UTF-8
1,676
3.203125
3
[]
no_license
use std::fs; use handlebars::Handlebars; use crate::output::output_generator::OutputGenerator; use crate::parser::log_line_parse_result::LogLineParseResult; use simple_error::{try_with, SimpleError}; pub struct HandlebarsOutputGenerator<'a> { registry: Handlebars<'a>, } impl<'a> HandlebarsOutputGenerator<'a> { pub fn new(template: &str) -> Result<HandlebarsOutputGenerator<'a>, SimpleError> { let mut registry = Handlebars::new(); try_with!(registry.register_template_string("default", template), "Unable to register template"); Ok(HandlebarsOutputGenerator { registry, }) } pub fn from_file(path: &str) -> Result<Box<dyn OutputGenerator>, SimpleError> { let data = fs::read_to_string(path).expect("Unable to read file"); let generator = try_with!(HandlebarsOutputGenerator::new(data.as_ref()), "Unable to construct parser"); Ok(Box::new(generator)) } } impl<'a> OutputGenerator for HandlebarsOutputGenerator<'a> { fn get_str(&self, log_line: &dyn LogLineParseResult) -> String { self.registry.render("default", log_line.get_content()).unwrap() } } #[cfg(test)] mod tests { use super::*; use crate::parser::default_log_line_parse_result::DefaultLogLineParseResult; #[test] fn test_simple_handlebars_templating() -> Result<(), SimpleError> { let output_generator = HandlebarsOutputGenerator::new("{{test}}")?; let log_line = DefaultLogLineParseResult::new(vec![(String::from("test"), String::from("test value"))].into_iter().collect()); assert_eq!(output_generator.get_str(&log_line), "test value"); Ok(()) } }
true
67b60988fa5720b88de4b43873e85b2db0bd4bcd
Rust
vojta7/pra-lang
/src/bin.rs
UTF-8
1,957
2.984375
3
[]
no_license
use mylib::ast::{ArgList, VarVal}; use mylib::{execute, parse, Buildins}; use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::path::Path; fn buildins() -> Buildins<'static> { let mut f: Buildins = HashMap::new(); f.insert( "print".to_owned(), Box::from(|args: ArgList| { for arg in args.args { match arg { VarVal::I32(Some(v)) => print!("{}", v), VarVal::BOOL(Some(v)) => print!("{}", v), VarVal::STRING(Some(v)) => print!("{}", v), VarVal::UNIT => print!("()"), _ => (), } } println!(); VarVal::UNIT }), ); f } fn usage() { eprintln!("program <file>"); } fn load_program(file_path: &Path) -> Result<String, std::io::Error> { let mut file = File::open(file_path)?; let mut input = String::new(); file.read_to_string(&mut input)?; Ok(input) } fn main() { let mut args = std::env::args(); let file = args.nth(1).unwrap_or_else(|| { usage(); std::process::exit(1) }); let file_path = Path::new(&file); //let res = load_program(&file_path) // .map(|program| parse(&program).map(|ast| execute(&ast, &mut HashMap::new()))); //if let Err(e) = res { // eprintln!("{:#?}", e); //} match load_program(&file_path) { Ok(input) => { match parse(&input) { Ok(program) => { //println!("{:#?}", program); match execute(&program, &mut HashMap::new(), &mut buildins()) { Ok(_) => (), Err(e) => eprintln!("Runtime error: {:#?}", e), } } Err(e) => eprintln!("Runtime error: {:#?}", e), } } Err(e) => eprintln!("OS error: {:#?}", e), } }
true
3e77889b1b5e70b966a035bc36749c0357c68aa8
Rust
rust-lang/rust-analyzer
/crates/syntax/test_data/parser/fuzz-failures/0001.rs
UTF-8
3,542
2.734375
3
[ "Apache-2.0", "MIT" ]
permissive
use syntax::{ File, TextRange, SyntaxNodeRef, TextUnit, SyntaxKind::*, algo::{find_leaf_at_offset, LeafAtOffset, find_covering_node, ancestors, Direction, siblings}, }; pub fn extend_selection(file: &File, range: TextRange) -> Option<TextRange> { let syntax = file.syntax(); extend(syntax.borrowed(), range) } pub(crate) fn extend(root: SyntaxNodeRef, range: TextRange) -> Option<TextRange> { if range.is_empty() { let offset = range.start(); let mut leaves = find_leaf_at_offset(root, offset); if leaves.clone().all(|it| it.kind() == WHITESPACE) { return Some(extend_ws(root, leaves.next()?, offset)); } let leaf = match leaves { LeafAtOffset::None => return None, LeafAtOffset::Single(l) => l, LeafAtOffset::Between(l, r) => pick_best(l, r), }; return Some(leaf.range()); }; let node = find_covering_node(root, range); if node.kind() == COMMENT && range == node.range() { if let Some(range) = extend_comments(node) { return Some(range); } } match ancestors(node).skip_while(|n| n.range() == range).next() { None => None, Some(parent) => Some(parent.range()), } } fn extend_ws(root: SyntaxNodeRef, ws: SyntaxNodeRef, offset: TextUnit) -> TextRange { let ws_text = ws.leaf_text().unwrap(); let suffix = TextRange::from_to(offset, ws.range().end()) - ws.range().start(); let prefix = TextRange::from_to(ws.range().start(), offset) - ws.range().start(); let ws_suffix = &ws_text.as_str()[suffix]; let ws_prefix = &ws_text.as_str()[prefix]; if ws_text.contains("\n") && !ws_suffix.contains("\n") { if let Some(node) = ws.next_sibling() { let start = match ws_prefix.rfind('\n') { Some(idx) => ws.range().start() + TextUnit::from((idx + 1) as u32), None => node.range().start() }; let end = if root.text().char_at(node.range().end()) == Some('\n') { node.range().end() + TextUnit::of_char('\n') } else { node.range().end() }; return TextRange::from_to(start, end); } } ws.range() } fn pick_best<'a>(l: SyntaxNodeRef<'a>, r: Syntd[axNodeRef<'a>) -> SyntaxNodeRef<'a> { return if priority(r) > priority(l) { r } else { l }; fn priority(n: SyntaxNodeRef) -> usize { match n.kind() { WHITESPACE => 0, IDENT | SELF_KW | SUPER_KW | CRATE_KW => 2, _ => 1, } } } fn extend_comments(node: SyntaxNodeRef) -> Option<TextRange> { let left = adj_com[ments(node, Direction::Backward); let right = adj_comments(node, Direction::Forward); if left != right { Some(TextRange::from_to( left.range().start(), right.range().end(), )) } else { None } } fn adj_comments(node: SyntaxNodeRef, dir: Direction) -> SyntaxNodeRef { let mut res = node; for node in siblings(node, dir) { match node.kind() { COMMENT => res = node, WHITESPACE if !node.leaf_text().unwrap().as_str().contains("\n\n") => (), _ => break } } res } #[cfg(test)] mod tests { use super::*; use test_utils::extract_offset; fn do_check(before: &str, afters: &[&str]) { let (cursor, before) = extract_offset(before); let file = File::parse(&before); let mut range = TextRange::of
true
5cc674f774cc5cfc100afd1826f7b0f5cd24f59f
Rust
Dynisious/double-ratchet
/double-ratchet/src/message.rs
UTF-8
707
2.765625
3
[]
no_license
//! Defines `Message` types. //! //! Author -- daniel.bechaz@gmail.com //! Last Moddified --- 2019-05-12 mod serde; /// A `Message` is a message [Header] and associated data. #[derive(PartialEq, Eq, Clone, Debug,)] pub struct Message { /// The `Message` [Header]. pub header: Header, /// The `Message` data. pub data: Box<[u8]>, } /// The headers tagged with a message. #[derive(PartialEq, Eq, Clone, Copy, Debug, Default,)] pub struct Header { /// The `PublicKey` of the communication partner. pub public_key: [u8; 32], /// The index of this message in the current step. pub message_index: u32, /// The number of messages in the previous step. pub previous_step: u32, }
true