lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/pagetree.rs
manuel-rhdt/lemon_pdf
e85d52d391a6dbc34fe4b33e437d788e62fd12a0
use std::collections::HashMap; use std::f64::consts::SQRT_2; use std::io::Result; use crate as lemon_pdf; use lemon_pdf_derive::PdfFormat; use crate::array::Array; use crate::content::PageContext; use crate::document::DocumentContext; use crate::font::Font; use crate::object::{IndirectReference, Object, Value}; use crate::stream::{Stream, StreamEncoder, StreamFilter}; use crate::Pt; #[derive(Debug, Clone, PdfFormat)] pub struct Pages { count: i64, #[skip_if("Option::is_none")] parent: Option<IndirectReference<Pages>>, kids: Vec<Object<PageTreeNode>>, } impl Default for Pages { fn default() -> Self { Pages { kids: Vec::new(), parent: None, count: -1, } } } #[derive(Clone, Debug, PdfFormat)] enum PageTreeNode { Tree(Pages), Page(Page), } impl Pages { pub fn new() -> Self { Default::default() } #[allow(unused)] pub fn add_pagetree(&mut self, tree: Pages) { self.kids.push(Object::Direct(PageTreeNode::Tree(tree))) } pub fn add_page(&mut self, page: Page) { self.kids.push(Object::Direct(PageTreeNode::Page(page))) } pub fn write_to_context( mut self, context: &mut DocumentContext, ) -> Result<IndirectReference<Pages>> { context.write_object_fn(|context, self_reference| { let mut array = Vec::new(); for child in self.kids { match child { Object::Direct(PageTreeNode::Tree(mut tree)) => { tree.parent = Some(self_reference); let tree_obj = tree.write_to_context(context)?; array.push(tree_obj.convert().into()) } Object::Direct(PageTreeNode::Page(mut page)) => { page.set_parent(self_reference); let page_obj = context.write_object(page)?; array.push(page_obj.convert().into()); } _ => unreachable!(), } } self.kids = array; self.count = self.kids.len() as i64; Ok(self) }) } } #[derive(Clone, Debug, Default, PartialEq, PdfFormat)] #[omit_type(true)] pub struct ResourceDictionary { pub font: HashMap<String, IndirectReference<Font>>, } #[derive(Clone, Debug, PdfFormat)] pub struct Page { pub resources: Option<ResourceDictionary>, pub media_box: [Pt; 4], #[skip_if("Option::is_none")] pub parent: Option<IndirectReference<Pages>>, pub contents: Vec<IndirectReference<Stream>>, } impl Page { pub fn new() -> Self { Page { resources: None, media_box: MediaBox::paper_din_a(4).as_array(), parent: None, contents: Vec::new(), } } pub fn set_media_box(&mut self, media_box: MediaBox) { self.media_box = media_box.as_array() } fn get_context<'context, 'borrow>( &mut self, context: &'borrow mut DocumentContext<'context>, stream_filter: Option<StreamFilter>, ) -> PageContext<'_, 'context, 'borrow> { PageContext { fonts: HashMap::new(), page: self, content_stream: StreamEncoder::new(stream_filter), pdf_context: context, } } pub fn add_content<'context, 'borrow>( &mut self, context: &mut DocumentContext<'context>, stream_filter: Option<StreamFilter>, content_f: impl FnOnce(&mut PageContext<'_, 'context, '_>) -> Result<()>, ) -> Result<()> { let mut page_context = self.get_context(context, stream_filter); content_f(&mut page_context)?; page_context.finish()?; Ok(()) } pub(crate) fn set_parent(&mut self, parent: IndirectReference<Pages>) { self.parent = Some(parent) } } #[derive(Debug, Copy, Clone, PartialEq)] pub struct MediaBox { pub xmin: Pt, pub ymin: Pt, pub xmax: Pt, pub ymax: Pt, } impl MediaBox { pub fn new(xmin: Pt, ymin: Pt, xmax: Pt, ymax: Pt) -> Self { MediaBox { xmin, ymin, xmax, ymax, } } pub fn paper_din_a(num: i32) -> Self { const A_AREA: f64 = 1.0; const M_TO_PT: f64 = 2834.65; let height = M_TO_PT * (A_AREA * SQRT_2).sqrt() / SQRT_2.powi(num); MediaBox::new(Pt(0.0), Pt(0.0), Pt(height / SQRT_2), Pt(height)) } pub fn as_array(self) -> [Pt; 4] { [self.xmin, self.ymin, self.xmax, self.ymax] } } impl Default for Page { fn default() -> Self { Page::new() } } impl From<MediaBox> for Object<Value> { fn from(mediabox: MediaBox) -> Object<Value> { let mut array = Array::new(); array.push(Object::Direct(mediabox.xmin.0.into())); array.push(Object::Direct(mediabox.ymin.0.into())); array.push(Object::Direct(mediabox.xmax.0.into())); array.push(Object::Direct(mediabox.ymax.0.into())); Object::Direct(array.into()) } }
use std::collections::HashMap; use std::f64::consts::SQRT_2; use std::io::Result; use crate as lemon_pdf; use lemon_pdf_derive::PdfFormat; use crate::array::Array; use crate::content::PageContext; use crate::document::DocumentContext; use crate::font::Font; use crate::object::{IndirectReference, Object, Value}; use crate::stream::{Stream, StreamEncoder, StreamFilter}; use crate::Pt; #[derive(Debug, Clone, PdfFormat)] pub struct Pages { count: i64, #[skip_if("Option::is_none")] parent: Option<IndirectReference<Pages>>, kids: Vec<Object<PageTreeNode>>, } impl Default for Pages { fn default() -> Self { Pages { kids: Vec::new(), parent: None, count: -1, } } } #[derive(Clone, Debug, PdfFormat)] enum PageTreeNode { Tree(Pages), Page(Page), } impl Pages { pub fn new() -> Self { Default::default() } #[allow(unused)] pub fn add_pagetree(&mut self, tree: Pages) { self.kids.push(Object::Direct(PageTreeNode::Tree(tree))) } pub fn add_page(&mut self, page: Page) { self.kids.push(Object::Direct(PageTreeNode::Page(page))) } pub fn write_to_context( mut self, context: &mut DocumentContext, ) -> Result<IndirectReference<Pages>> { context.write_object_fn(|context, self_reference| { let mut array = Vec::new(); for child in self.kids { match child { Object::Direct(PageTreeNode::Tree(mut tree)) => { tree.parent = Some(self_reference); let tree_obj = tree.write_to_context(context)?; array.push(tree_obj.convert().into()) } Object::Direct(PageTreeNode::Page(mut page)) => { page.set_parent(self_reference); let page_obj = context.write_object(page)?; array.push(page_obj.convert().into()); } _ => unreachable!(), } } self.kids = array; self.count = self.kids.len() as i64; Ok(self) }) } } #[derive(Clone, Debug, Default, PartialEq, PdfFormat)] #[omit_type(true)] pub struct ResourceDictionary { pub font: HashMap<String, IndirectReference<Font>>, } #[derive(Clone, Debug, PdfFormat)] pub struct Page { pub resources: Option<ResourceDictionary>, pub media_box: [Pt; 4], #[skip_if("Option::is_none")] pub parent: Option<IndirectReference<Pages>>, pub contents: Vec<IndirectReference<Stream>>, } impl Page {
pub fn set_media_box(&mut self, media_box: MediaBox) { self.media_box = media_box.as_array() } fn get_context<'context, 'borrow>( &mut self, context: &'borrow mut DocumentContext<'context>, stream_filter: Option<StreamFilter>, ) -> PageContext<'_, 'context, 'borrow> { PageContext { fonts: HashMap::new(), page: self, content_stream: StreamEncoder::new(stream_filter), pdf_context: context, } } pub fn add_content<'context, 'borrow>( &mut self, context: &mut DocumentContext<'context>, stream_filter: Option<StreamFilter>, content_f: impl FnOnce(&mut PageContext<'_, 'context, '_>) -> Result<()>, ) -> Result<()> { let mut page_context = self.get_context(context, stream_filter); content_f(&mut page_context)?; page_context.finish()?; Ok(()) } pub(crate) fn set_parent(&mut self, parent: IndirectReference<Pages>) { self.parent = Some(parent) } } #[derive(Debug, Copy, Clone, PartialEq)] pub struct MediaBox { pub xmin: Pt, pub ymin: Pt, pub xmax: Pt, pub ymax: Pt, } impl MediaBox { pub fn new(xmin: Pt, ymin: Pt, xmax: Pt, ymax: Pt) -> Self { MediaBox { xmin, ymin, xmax, ymax, } } pub fn paper_din_a(num: i32) -> Self { const A_AREA: f64 = 1.0; const M_TO_PT: f64 = 2834.65; let height = M_TO_PT * (A_AREA * SQRT_2).sqrt() / SQRT_2.powi(num); MediaBox::new(Pt(0.0), Pt(0.0), Pt(height / SQRT_2), Pt(height)) } pub fn as_array(self) -> [Pt; 4] { [self.xmin, self.ymin, self.xmax, self.ymax] } } impl Default for Page { fn default() -> Self { Page::new() } } impl From<MediaBox> for Object<Value> { fn from(mediabox: MediaBox) -> Object<Value> { let mut array = Array::new(); array.push(Object::Direct(mediabox.xmin.0.into())); array.push(Object::Direct(mediabox.ymin.0.into())); array.push(Object::Direct(mediabox.xmax.0.into())); array.push(Object::Direct(mediabox.ymax.0.into())); Object::Direct(array.into()) } }
pub fn new() -> Self { Page { resources: None, media_box: MediaBox::paper_din_a(4).as_array(), parent: None, contents: Vec::new(), } }
function_block-full_function
[ { "content": "pub trait PdfFormat: std::fmt::Debug {\n\n fn write(&self, output: &mut Formatter) -> Result<()>;\n\n}\n\n\n\nimpl<'a> PdfFormat for &'a str {\n\n fn write(&self, output: &mut Formatter) -> Result<()> {\n\n // TODO: proper escaping\n\n write!(output, \"/{}\", self)\n\n }\n\n...
Rust
src/interpreter/stdlib/special_forms/_match.rs
emirayka/nia_interpreter_core
8b212e44fdede3d49cd75eddb255091a1d67b0e5
use crate::interpreter::environment::EnvironmentId; use crate::interpreter::error::Error; use crate::interpreter::interpreter::Interpreter; use crate::interpreter::value::Value; use crate::interpreter::library; pub fn _match( interpreter: &mut Interpreter, environment_id: EnvironmentId, values: Vec<Value>, ) -> Result<Value, Error> { if values.len() < 1 { return Error::invalid_argument_count_error("").into(); } let mut values = values; let expression = values.remove(0); let clauses = values; let value_to_match = interpreter .execute_value(environment_id, expression) .map_err(|err| { Error::generic_execution_error_caused( "Cannot evaluate value in the `match' special form.", err, ) })?; let mut child_environment_id = None; let mut code_to_execute = None; for clause in clauses { let cons_id = library::read_as_cons_id(clause)?; let mut clause = interpreter.list_to_vec(cons_id)?; let pattern = clause.remove(0); let evaluated_pattern = interpreter.execute_value(environment_id, pattern)?; match library::match_value( interpreter, environment_id, evaluated_pattern, value_to_match, ) { Ok(environment_id) => { child_environment_id = Some(environment_id); let forms = clause; code_to_execute = Some(forms); break; } _ => {} } } match child_environment_id { Some(environment_id) => library::evaluate_forms_return_last( interpreter, environment_id, &code_to_execute.unwrap(), ), _ => Error::generic_execution_error("").into(), } } #[cfg(test)] mod tests { use super::*; #[allow(unused_imports)] use nia_basic_assertions::*; #[allow(unused_imports)] use crate::utils; #[test] fn executes_forms() { let mut interpreter = Interpreter::new(); let pairs = vec![ ("(match () ('()))", interpreter.intern_nil_symbol_value()), ("(match () ('() 1))", Value::Integer(1)), ("(match () ('() 1 2))", Value::Integer(2)), ("(match () ('() 1 2 3))", Value::Integer(3)), ]; utils::assert_results_are_correct(&mut interpreter, pairs); } #[test] fn able_to_destructurize_lists() { let mut interpreter = Interpreter::new(); let pairs = vec![ ("(match '() ('() nil))", "nil"), ("(match '(1) ('(a) (list:new a)))", "(list:new 1)"), ("(match '(1 2) ('(a b) (list:new a b)))", "(list:new 1 2)"), ( "(match '(1 2 3) ('(a b c) (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); } #[test] fn able_to_destructurize_inner_lists() { let mut interpreter = Interpreter::new(); let pairs = vec![ ("(match '(1) ('(a) (list:new a)))", "(list:new 1)"), ("(match '((1)) ('((a)) (list:new a)))", "(list:new 1)"), ("(match '(((1))) ('(((a))) (list:new a)))", "(list:new 1)"), ("(match '(1) ('(a) (list:new a)))", "(list:new 1)"), ( "(match '((1) 2) ('((a) b) (list:new a b)))", "(list:new 1 2)", ), ( "(match '(((1) 2) 3) ('(((a) b) c) (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); } #[test] fn able_to_use_different_patterns() { let mut interpreter = Interpreter::new(); let pairs = vec![ ( "(match '() (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "()", ), ( "(match '(1) (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "(list:new 1)", ), ( "(match '(1 2) (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "(list:new 1 2)", ), ( "(match '(1 2 3) (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); } #[test] fn able_to_destructurize_objects() { let mut interpreter = Interpreter::new(); let pairs = vec![ ( "(match {:a 1 :b 2 :c 3} (#{:a} (list:new a)))", "(list:new 1)", ), ( "(match {:a 1 :b 2 :c 3} (#{:a :b} (list:new a b)))", "(list:new 1 2)", ), ( "(match {:a 1 :b 2 :c 3} (#{:a :b :c} (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); } }
use crate::interpreter::environment::EnvironmentId; use crate::interpreter::error::Error; use crate::interpreter::interpreter::Interpreter; use crate::interpreter::value::Value; use crate::interpreter::library; pub fn _match( interpreter: &mut Interpreter, environment_id: EnvironmentId, values: Vec<Value>, ) -> Result<Value, Error> { if values.len() < 1 { return Error::invalid_argument_count_error("").into(); } let mut values = values; let expression = values.remove(0); let clauses = values; let value_to_match = interpreter .execute_value(environment_id, expression) .map_err(|err| { Error::generic_execution_error_caused( "Cannot evaluate value in the `match' special form.", err, ) })?; let mut child_environment_id = None; let mut code_to_execute = None; for clause in clauses { let cons_id = library::read_as_cons_id(clause)?; let mut clause = interpreter.list_to_vec(cons_id)?; let pattern = clause.remove(0); let evaluated_pattern = interpreter.execute_value(environment_id, pattern)?; match library::match_value( interpreter, environment_id, evaluated_pattern, value_to_match, ) { Ok(environment_id) => { child_environment_id = Some(environment_id); let forms = clause; code_to_execute = Some(forms); break; } _ => {} } } match child_environment_id { Some(environment_id) => library::evaluate_forms_return_last( interpreter, environment_id, &code_to_execute.unwrap(), ), _ => Error::generic_execution_error("").into(), } } #[cfg(test)] mod tests { use super::*; #[allow(unused_imports)] use nia_basic_assertions::*; #[allow(unused_imports)] use crate::utils; #[test] fn executes_forms() { let mut interpreter = Interpreter::new(); let pairs = vec![ ("(match () ('()))", interpreter.intern_nil_symbol_value()), ("(match () ('() 1))", Value::Integer(1)), ("(match () ('() 1 2))", Value::Integer(2)), ("(match () ('() 1 2 3))", Value::Integer(3)), ]; utils::assert_results_are_correct(&mut interpreter, pairs); } #[test] fn able_to_destructurize_lists() { let mut interpreter = Interpreter::new(); let pairs = vec![ ("(match '() ('() nil))", "nil"), ("(match '(1) ('(a) (list:new a)))", "(list:new 1)"), ("(match '(1 2) ('(a b) (list:new a b)))", "(list:new 1 2)"), ( "(match '(1 2 3) ('(a b c) (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); } #[test] fn able_to_destructurize_inner_lists() { let mut interpreter = Interpreter::new(); let pairs = vec![ ("(match '(1) ('(a) (list:new a)))", "(list:new 1)"), ("(match '((1)) ('((a)) (list:new a)))", "(list:new 1)"), ("(match '(((1))) ('(((a))) (list:new a)))", "(list:new 1)"), ("(match '(1) ('(a) (list:new a)))", "(list:new 1)"), ( "(match '((1) 2) ('((a) b) (list:new a b)))", "(list:new 1 2)", ), ( "(match '(((1) 2) 3) ('(((a) b) c) (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); } #[test] fn able_to_use_different_patterns() { let mut in
#[test] fn able_to_destructurize_objects() { let mut interpreter = Interpreter::new(); let pairs = vec![ ( "(match {:a 1 :b 2 :c 3} (#{:a} (list:new a)))", "(list:new 1)", ), ( "(match {:a 1 :b 2 :c 3} (#{:a :b} (list:new a b)))", "(list:new 1 2)", ), ( "(match {:a 1 :b 2 :c 3} (#{:a :b :c} (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); } }
terpreter = Interpreter::new(); let pairs = vec![ ( "(match '() (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "()", ), ( "(match '(1) (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "(list:new 1)", ), ( "(match '(1 2) (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "(list:new 1 2)", ), ( "(match '(1 2 3) (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); }
function_block-function_prefixed
[ { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let pairs: Vec<(&str, SpecialFormFunctionType)> = vec![\n\n (\"and\", and::and),\n\n (\"call-with-this\", call_with_this::call_with_this),\n\n (\"cond\", cond::cond),\n\n (\"quote\", quote::quote...
Rust
krapao/src/state.rs
shigedangao/jiemi
beffe848cb5606a4bee02647f8a6743e09301e45
use std::sync::{Arc, Mutex}; use std::fs; use std::collections::HashMap; use dirs::home_dir; use serde::{Serialize, Deserialize}; use crate::repo::config::GitConfig; use crate::err::Error; use crate::helper; const REPO_FILE_PATH: &str = "list.json"; const REPO_PATH: &str = "workspace/repo"; pub type State = Arc<Mutex<HashMap<String, GitConfig>>>; #[derive(Debug, Serialize, Deserialize, Default)] struct List { repositories: Option<HashMap<String, GitConfig>> } impl List { fn read_persistent_state() -> Result<List, Error> { let mut file_path = home_dir().unwrap_or_default(); file_path.push(REPO_PATH); file_path.push(REPO_FILE_PATH); let saved_state = fs::read(&file_path)?; let list: List = serde_json::from_slice(&saved_state)?; Ok(list) } fn create_new_empty_state() -> Result<List, Error> { let default = List::default(); default.save_list_to_persistent_state()?; Ok(default) } fn save_list_to_persistent_state(&self) -> Result<(), Error> { let mut file_path = home_dir().unwrap_or_default(); file_path.push(REPO_PATH); file_path.push(REPO_FILE_PATH); let json = serde_json::to_string_pretty(&self)?; fs::write(file_path, json)?; Ok(()) } } pub fn create_state() -> Result<State, Error> { let mut workspace_dir = home_dir().unwrap_or_default(); workspace_dir.push(REPO_PATH); helper::create_path(&workspace_dir)?; let saved_state = match List::read_persistent_state() { Ok(res) => res, Err(_) => { List::create_new_empty_state()? } }; if let Some(existing_state) = saved_state.repositories { return Ok(Arc::new(Mutex::new(existing_state))); } Ok(Arc::new(Mutex::new(HashMap::new()))) } pub fn save_new_repo_in_persistent_state(config: GitConfig) -> Result<(), Error> { let mut list: List = List::read_persistent_state()?; if let Some(existing_state) = list.repositories.as_mut() { existing_state.insert(config.repo_uri.clone(), config); } else { let mut map = HashMap::new(); map.insert(config.repo_uri.clone(), config); list.repositories = Some(map); } list.save_list_to_persistent_state() } pub fn remove_repo_from_persistent_state(key: &str) -> Result<(), Error> { let mut list: List = List::read_persistent_state()?; if let Some(existing_state) = list.repositories.as_mut() { existing_state.remove(key); } list.save_list_to_persistent_state() } #[cfg(test)] mod tests { use std::path::PathBuf; use crate::repo::config::Credentials; use super::*; #[test] fn expect_to_create_state() { let state = create_state(); assert!(state.is_ok()); let list = List::read_persistent_state(); assert!(list.is_ok()); } #[test] fn expect_to_save_new_config() { let repo_uri = "https://github.com/shigedangao/maskiedoc.git"; let credentials = Credentials::Empty; let config = GitConfig::new( credentials, repo_uri, PathBuf::new() ).unwrap(); let res = save_new_repo_in_persistent_state(config); assert!(res.is_ok()); let list = List::read_persistent_state().unwrap(); let repos = list.repositories.unwrap(); let maskiedoc = repos.get(repo_uri); assert!(maskiedoc.is_some()); let res = remove_repo_from_persistent_state(repo_uri); assert!(res.is_ok()); } }
use std::sync::{Arc, Mutex}; use std::fs; use std::collections::HashMap; use dirs::home_dir; use serde::{Serialize, Deserialize}; use crate::repo::config::GitConfig; use crate::err::Error; use crate::helper; const REPO_FILE_PATH: &str = "list.json"; const REPO_PATH: &str = "workspace/repo"; pub type State = Arc<Mutex<HashMap<String, GitConfig>>>; #[derive(Debug, Serialize, Deserialize, Default)] struct List { repositories: Option<HashMap<String, GitConfig>> } impl List { fn read_persistent_state() -> Result<List, Error> { let mut file_path = home_dir().unwrap_or_default(); file_path.push(REPO_PATH); file_path.push(REPO_FILE_PATH); let saved_state = fs::read(&file_path)?; let list: List = serde_json::from_slice(&saved_state)?; Ok(list) } fn create_new_empty_state() -> Result<List, Error> { let default = List::default(); default.save_list_to_persistent_state()?; Ok(default) }
} pub fn create_state() -> Result<State, Error> { let mut workspace_dir = home_dir().unwrap_or_default(); workspace_dir.push(REPO_PATH); helper::create_path(&workspace_dir)?; let saved_state = match List::read_persistent_state() { Ok(res) => res, Err(_) => { List::create_new_empty_state()? } }; if let Some(existing_state) = saved_state.repositories { return Ok(Arc::new(Mutex::new(existing_state))); } Ok(Arc::new(Mutex::new(HashMap::new()))) } pub fn save_new_repo_in_persistent_state(config: GitConfig) -> Result<(), Error> { let mut list: List = List::read_persistent_state()?; if let Some(existing_state) = list.repositories.as_mut() { existing_state.insert(config.repo_uri.clone(), config); } else { let mut map = HashMap::new(); map.insert(config.repo_uri.clone(), config); list.repositories = Some(map); } list.save_list_to_persistent_state() } pub fn remove_repo_from_persistent_state(key: &str) -> Result<(), Error> { let mut list: List = List::read_persistent_state()?; if let Some(existing_state) = list.repositories.as_mut() { existing_state.remove(key); } list.save_list_to_persistent_state() } #[cfg(test)] mod tests { use std::path::PathBuf; use crate::repo::config::Credentials; use super::*; #[test] fn expect_to_create_state() { let state = create_state(); assert!(state.is_ok()); let list = List::read_persistent_state(); assert!(list.is_ok()); } #[test] fn expect_to_save_new_config() { let repo_uri = "https://github.com/shigedangao/maskiedoc.git"; let credentials = Credentials::Empty; let config = GitConfig::new( credentials, repo_uri, PathBuf::new() ).unwrap(); let res = save_new_repo_in_persistent_state(config); assert!(res.is_ok()); let list = List::read_persistent_state().unwrap(); let repos = list.repositories.unwrap(); let maskiedoc = repos.get(repo_uri); assert!(maskiedoc.is_some()); let res = remove_repo_from_persistent_state(repo_uri); assert!(res.is_ok()); } }
fn save_list_to_persistent_state(&self) -> Result<(), Error> { let mut file_path = home_dir().unwrap_or_default(); file_path.push(REPO_PATH); file_path.push(REPO_FILE_PATH); let json = serde_json::to_string_pretty(&self)?; fs::write(file_path, json)?; Ok(()) }
function_block-full_function
[ { "content": "/// Delete an item in the state. This case is used when a CRD is delete. w/o removing the item, when a crd containing the sma\n\n/// name is applied. The crd might not take into account the update\n\n/// \n\n/// # Arguments\n\n/// * `state` - State\n\n/// * `key` - &str\n\npub fn delete_item_in_st...
Rust
src/windows.rs
chadbrewbaker/filebuffer
38193fc0c9cb54363a8dcf59c303a6605e2ba8c5
use std::fs; use std::io; use std::mem; use std::os::windows::io::AsRawHandle; use std::ptr; extern crate winapi; #[derive(Debug)] pub struct PlatformData { #[allow(dead_code)] file: fs::File, mapping_handle: winapi::um::winnt::HANDLE, } impl Drop for PlatformData { fn drop (&mut self) { if self.mapping_handle != ptr::null_mut() { let success = unsafe { winapi::um::handleapi::CloseHandle(self.mapping_handle) }; assert!(success != 0); } } } pub fn map_file(file: fs::File) -> io::Result<(*const u8, usize, PlatformData)> { let file_handle = file.as_raw_handle(); let length = try!(file.metadata()).len(); if length > usize::max_value() as u64 { return Err(io::Error::new(io::ErrorKind::Other, "file is larger than address space")); } let mut platform_data = PlatformData { file: file, mapping_handle: ptr::null_mut(), }; if length == 0 { return Ok((ptr::null(), 0, platform_data)); } platform_data.mapping_handle = unsafe { winapi::um::memoryapi::CreateFileMappingW( file_handle as *mut winapi::ctypes::c_void, ptr::null_mut(), winapi::um::winnt::PAGE_READONLY, 0, 0, ptr::null_mut() ) }; if platform_data.mapping_handle == ptr::null_mut() { return Err(io::Error::last_os_error()); } let result = unsafe { winapi::um::memoryapi::MapViewOfFile( platform_data.mapping_handle, winapi::um::memoryapi::FILE_MAP_READ, 0, 0, length as winapi::shared::basetsd::SIZE_T ) }; if result == ptr::null_mut() { Err(io::Error::last_os_error()) } else { Ok((result as *const u8, length as usize, platform_data)) } } pub fn unmap_file(buffer: *const u8, _length: usize) { let success = unsafe { winapi::um::memoryapi::UnmapViewOfFile(buffer as *mut winapi::ctypes::c_void) }; assert!(success != 0); } pub fn get_resident(_buffer: *const u8, _length: usize, residency: &mut [bool]) { for x in residency { *x = true; } } pub fn prefetch(buffer: *const u8, length: usize) { let mut entry = winapi::um::memoryapi::WIN32_MEMORY_RANGE_ENTRY { VirtualAddress: buffer as *mut winapi::ctypes::c_void, NumberOfBytes: length as winapi::shared::basetsd::SIZE_T, }; unsafe { let current_process_handle = winapi::um::processthreadsapi::GetCurrentProcess(); winapi::um::memoryapi::PrefetchVirtualMemory( current_process_handle, 1, &mut entry, 0 ); } } pub fn get_page_size() -> usize { let mut sysinfo: winapi::um::sysinfoapi::SYSTEM_INFO = unsafe { mem::zeroed() }; unsafe { winapi::um::sysinfoapi::GetSystemInfo(&mut sysinfo); } sysinfo.dwPageSize as usize }
use std::fs; use std::io; use std::mem; use std::os::windows::io::AsRawHandle; use std::ptr; extern crate winapi; #[derive(Debug)] pub struct PlatformData { #[allow(dead_code)] file: fs::File, mapping_handle: winapi::um::winnt::HANDLE, } impl Drop for PlatformData { fn drop (&mut self) { if self.mapping_handle != ptr::null_mut() { let success = unsafe { winapi::um::handleapi::CloseHandle(self.mapping_handle) }; assert!(success != 0); } } } pub fn map_file(file: fs::File) -> io::Result<(*const u8, usize, PlatformData)> { let file_handle = file.as_raw_handle(); let length = try!(file.metadata()).len(); if length > usize::max_value() as u64 { return Err(io::Error::new(io::ErrorKind::Other, "file is larger than address space")); } let mut platform_data = PlatformData { file: file, mapping_handle: ptr::null_mut(), }; if length == 0 { return Ok((ptr::null(), 0, platform_data)); } platform_data.mapping_handle = unsafe { winapi::um::memoryapi::CreateFileMappingW( file_handle as *mut winapi::ctypes::c_void, ptr::null_mut(), winapi::um::winnt::PAGE_READONLY, 0, 0, ptr::null_mut() ) }; if platform_data.mapping_handle == ptr::null_mut() { return Err(io::Error::last_os_error()); } let result = unsafe { winapi::um::memoryapi::MapViewOfFile( platform_data.mapping_handle, winapi::um::memoryapi::FILE_MAP_READ, 0, 0, length as winapi::shared::basetsd::SIZE_T ) }; if result == ptr::null_mut() { Err(io::Error::last_os_error()) } else { Ok((result as *const u8, length as usize, platform_data)) } } pub fn unmap_file(buffer: *const u8, _length: usize) { let success = unsafe { winapi::um::memoryapi::UnmapViewOfFile(buffer as *mut winapi::ctypes::c_void) }; assert!(success != 0); } pub fn get_resident(_buffer: *const u8, _length: usize, residency: &mut [bool]) { for x in residency { *x = true; } } pub fn prefetch(buffer: *const u8, length: usize) { let mut entry = winapi::um::memoryapi::WIN32_MEMORY_RANGE_ENTRY { VirtualAddress: buffer as *mut winapi::ctypes::c_void, NumberOfBytes: length as winapi::shared::basetsd::SIZE_T, }; unsafe { let current_process_handle = winapi::um::processthreadsapi::GetCurrentProcess(); winapi::um::memoryapi::PrefetchVirtualMemory( current_process_handle, 1, &mut entry, 0 ); } } pub fn get_page_size() -> usiz
e { let mut sysinfo: winapi::um::sysinfoapi::SYSTEM_INFO = unsafe { mem::zeroed() }; unsafe { winapi::um::sysinfoapi::GetSystemInfo(&mut sysinfo); } sysinfo.dwPageSize as usize }
function_block-function_prefixed
[ { "content": "/// Writes whether the pages in the range starting at `buffer` with a length of `length` bytes\n\n/// are resident in physical memory into `residency`. The size of `residency` must be at least\n\n/// `length / page_size`. Both `buffer` and `length` must be a multiple of the page size.\n\npub fn ge...
Rust
src/browser/url/search.rs
AlterionX/seed
ba2d8d36c68feda991d73a961ddc630fb67df949
use crate::browser::url::Url; use serde::{Deserialize, Serialize}; use std::{borrow::Cow, collections::BTreeMap, fmt}; #[allow(clippy::module_name_repetitions)] #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct UrlSearch { search: BTreeMap<String, Vec<String>>, pub(super) invalid_components: Vec<String>, } impl UrlSearch { pub fn new() -> Self { Self { search: BTreeMap::new(), invalid_components: Vec::new(), } } pub fn contains_key(&self, key: impl AsRef<str>) -> bool { self.search.contains_key(key.as_ref()) } pub fn get(&self, key: impl AsRef<str>) -> Option<&Vec<String>> { self.search.get(key.as_ref()) } pub fn get_mut(&mut self, key: impl AsRef<str>) -> Option<&mut Vec<String>> { self.search.get_mut(key.as_ref()) } pub fn push_value<'a>(&mut self, key: impl Into<Cow<'a, str>>, value: String) { let key = key.into(); if self.search.contains_key(key.as_ref()) { self.search.get_mut(key.as_ref()).unwrap().push(value); } else { self.search.insert(key.into_owned(), vec![value]); } } pub fn insert(&mut self, key: String, values: Vec<String>) -> Option<Vec<String>> { self.search.insert(key, values) } pub fn remove(&mut self, key: impl AsRef<str>) -> Option<Vec<String>> { self.search.remove(key.as_ref()) } pub fn iter(&self) -> impl Iterator<Item = (&String, &Vec<String>)> { self.search.iter() } pub fn invalid_components(&self) -> &[String] { &self.invalid_components } pub fn invalid_components_mut(&mut self) -> &mut Vec<String> { &mut self.invalid_components } } impl fmt::Display for UrlSearch { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let params = web_sys::UrlSearchParams::new().expect("create a new UrlSearchParams"); for (key, values) in &self.search { for value in values { params.append(key, value); } } write!(fmt, "{}", String::from(params.to_string())) } } impl From<web_sys::UrlSearchParams> for UrlSearch { fn from(params: web_sys::UrlSearchParams) -> Self { let mut url_search = Self::default(); let mut invalid_components = Vec::<String>::new(); for param in js_sys::Array::from(&params).to_vec() { let key_value_pair = js_sys::Array::from(&param).to_vec(); let key = key_value_pair .get(0) .expect("get UrlSearchParams key from key-value pair") .as_string() .expect("cast UrlSearchParams key to String"); let value = key_value_pair .get(1) .expect("get UrlSearchParams value from key-value pair") .as_string() .expect("cast UrlSearchParams value to String"); let key = match Url::decode_uri_component(&key) { Ok(decoded_key) => decoded_key, Err(_) => { invalid_components.push(key.clone()); key } }; let value = match Url::decode_uri_component(&value) { Ok(decoded_value) => decoded_value, Err(_) => { invalid_components.push(value.clone()); value } }; url_search.push_value(key, value) } url_search.invalid_components = invalid_components; url_search } } impl<K, V, VS> std::iter::FromIterator<(K, VS)> for UrlSearch where K: Into<String>, V: Into<String>, VS: IntoIterator<Item = V>, { fn from_iter<I: IntoIterator<Item = (K, VS)>>(iter: I) -> Self { let search = iter .into_iter() .map(|(k, vs)| { let k = k.into(); let v: Vec<_> = vs.into_iter().map(Into::into).collect(); (k, v) }) .collect(); Self { search, invalid_components: Vec::new(), } } } impl<'iter, K, V, VS> std::iter::FromIterator<&'iter (K, VS)> for UrlSearch where K: Into<String> + Copy + 'iter, V: Into<String> + Copy + 'iter, VS: IntoIterator<Item = V> + 'iter, { fn from_iter<I: IntoIterator<Item = &'iter (K, VS)>>(iter: I) -> Self { iter.into_iter().collect() } }
use crate::browser::url::Url; use serde::{Deserialize, Serialize}; use std::{borrow::Cow, collections::BTreeMap, fmt}; #[allow(clippy::module_name_repetitions)] #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct UrlSearch { search: BTreeMap<String, Vec<String>>, pub(super) invalid_components: Vec<String>, } impl UrlSearch { pub fn new() -> Self { Self { search: BTreeMap::new(), invalid_components: Vec::new(), } } pub fn contains_key(&self, key: impl AsRef<str>) -> bool { self.search.contains_key(key.as_ref()) } pub fn get(&self, key: impl AsRef<str>) -> Option<&Vec<String>> { self.search.get(key.as_ref()) } pub fn get_mut(&mut self, key: impl AsRef<str>) -> Option<&mut Vec<String>> { self.search.get_mut(key.as_ref()) } pub fn push_value<'a>(&mut self, key: impl Into<Cow<'a, str>>, value: String) {
pub fn insert(&mut self, key: String, values: Vec<String>) -> Option<Vec<String>> { self.search.insert(key, values) } pub fn remove(&mut self, key: impl AsRef<str>) -> Option<Vec<String>> { self.search.remove(key.as_ref()) } pub fn iter(&self) -> impl Iterator<Item = (&String, &Vec<String>)> { self.search.iter() } pub fn invalid_components(&self) -> &[String] { &self.invalid_components } pub fn invalid_components_mut(&mut self) -> &mut Vec<String> { &mut self.invalid_components } } impl fmt::Display for UrlSearch { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let params = web_sys::UrlSearchParams::new().expect("create a new UrlSearchParams"); for (key, values) in &self.search { for value in values { params.append(key, value); } } write!(fmt, "{}", String::from(params.to_string())) } } impl From<web_sys::UrlSearchParams> for UrlSearch { fn from(params: web_sys::UrlSearchParams) -> Self { let mut url_search = Self::default(); let mut invalid_components = Vec::<String>::new(); for param in js_sys::Array::from(&params).to_vec() { let key_value_pair = js_sys::Array::from(&param).to_vec(); let key = key_value_pair .get(0) .expect("get UrlSearchParams key from key-value pair") .as_string() .expect("cast UrlSearchParams key to String"); let value = key_value_pair .get(1) .expect("get UrlSearchParams value from key-value pair") .as_string() .expect("cast UrlSearchParams value to String"); let key = match Url::decode_uri_component(&key) { Ok(decoded_key) => decoded_key, Err(_) => { invalid_components.push(key.clone()); key } }; let value = match Url::decode_uri_component(&value) { Ok(decoded_value) => decoded_value, Err(_) => { invalid_components.push(value.clone()); value } }; url_search.push_value(key, value) } url_search.invalid_components = invalid_components; url_search } } impl<K, V, VS> std::iter::FromIterator<(K, VS)> for UrlSearch where K: Into<String>, V: Into<String>, VS: IntoIterator<Item = V>, { fn from_iter<I: IntoIterator<Item = (K, VS)>>(iter: I) -> Self { let search = iter .into_iter() .map(|(k, vs)| { let k = k.into(); let v: Vec<_> = vs.into_iter().map(Into::into).collect(); (k, v) }) .collect(); Self { search, invalid_components: Vec::new(), } } } impl<'iter, K, V, VS> std::iter::FromIterator<&'iter (K, VS)> for UrlSearch where K: Into<String> + Copy + 'iter, V: Into<String> + Copy + 'iter, VS: IntoIterator<Item = V> + 'iter, { fn from_iter<I: IntoIterator<Item = &'iter (K, VS)>>(iter: I) -> Self { iter.into_iter().collect() } }
let key = key.into(); if self.search.contains_key(key.as_ref()) { self.search.get_mut(key.as_ref()).unwrap().push(value); } else { self.search.insert(key.into_owned(), vec![value]); } }
function_block-function_prefix_line
[ { "content": "/// Attach given `key` to the `El`.\n\n///\n\n/// The keys are used by the diffing algorithm to determine the correspondence between old and\n\n/// new elements and helps to optimize the insertion, removal and reordering of elements.\n\npub fn el_key(key: &impl ToString) -> ElKey {\n\n ElKey(ke...
Rust
src/node.rs
pmuens/anova
c7d160b5df49bd3d6fbf9cf664025836997f12ab
use crate::{ block::Block, chain::Chain, transaction::Transaction, utils::{Keccak256, Sender}, }; use crate::{mempool::Mempool, utils::hash}; use rand::prelude::SliceRandom; pub struct Node { chain: Chain, mempool: Mempool, nonce: u64, } impl Node { pub fn new() -> Self { let chain = Chain::new(1000); let mempool = Mempool::new(); Node { chain, mempool, nonce: 1, } } pub fn create_transaction(&mut self) { let mut rng = rand::thread_rng(); let mut numbers: Vec<u8> = (1..100).collect(); numbers.shuffle(&mut rng); let sender: Sender = hash(numbers); let tx = Transaction::new(sender, self.nonce); self.add_transaction(tx); self.nonce += 1; } pub fn add_transaction(&mut self, transaction: Transaction) { let index = self.generate_transaction_index(&transaction); self.mempool.insert(index, transaction); } pub fn add_transactions(&mut self, transactions: Vec<Transaction>) { transactions .into_iter() .for_each(|tx| self.add_transaction(tx)); } pub fn propose_block(&self) -> Option<Block> { if let Some(transactions) = self.mempool.get_all_transactions() { let mut prev_block_id = None; if let Some(block) = self.chain.last() { prev_block_id = Some(block.id.clone()); } return Some(Block::new(transactions, prev_block_id)); } None } pub fn finalize_block(&mut self, block: Block) { let tx_indexes: Vec<Keccak256> = block .transactions .iter() .map(|tx| self.generate_transaction_index(tx)) .collect(); self.chain.append(block); self.mempool.remove_transactions(tx_indexes); if let Some(transactions) = self.mempool.get_all_transactions() { self.mempool.clear(); transactions.into_iter().for_each(|tx| { let index = self.generate_transaction_index(&tx); self.mempool.insert(index, tx); }); } } fn generate_transaction_index(&self, transaction: &Transaction) -> Keccak256 { let mut block_id = None; if let Some(block) = self.chain.last() { block_id = Some(block.id.clone()); } let data = bincode::serialize(&(transaction.id.clone(), block_id)).unwrap(); hash(data) } } #[cfg(test)] mod tests { use super::*; #[test] fn new_node() { let node = Node::new(); assert_eq!(node.mempool.get_all_transactions(), None); assert_eq!(node.chain.height(), None); assert_eq!(node.nonce, 1); } #[test] fn create_transaction() { let mut node = Node::new(); node.create_transaction(); assert_eq!(node.mempool.len(), 1); assert_eq!(node.nonce, 2); } #[test] fn add_transaction() { let mut node = Node::new(); let tx = Transaction::new(vec![0, 1, 2, 3, 4], 1); node.add_transaction(tx); assert_eq!(node.mempool.len(), 1); assert_eq!(node.nonce, 1); } #[test] fn add_transactions() { let mut node = Node::new(); let tx_1 = Transaction::new(vec![0, 1, 2, 3, 4], 1); let tx_2 = Transaction::new(vec![5, 6, 7, 8, 9], 1); let transactions = vec![tx_1, tx_2]; node.add_transactions(transactions); assert_eq!(node.mempool.len(), 2); assert_eq!(node.nonce, 1); } #[test] fn propose_block() { let mut node = Node::new(); let block = node.propose_block(); assert_eq!(block, None); node.create_transaction(); let block = node.propose_block(); assert!(block.is_some()); let block = block.unwrap(); assert_eq!(block.transactions.len(), 1); assert_eq!(block.get_previous_block_id(), None); } #[test] fn finalize_single_block() { let mut node = Node::new(); node.create_transaction(); let block_proposal = node.propose_block().unwrap(); node.finalize_block(block_proposal.clone()); assert_eq!(node.chain.height(), Some(0)); assert_eq!(node.chain.last(), Some(&block_proposal)); assert_eq!(node.mempool.get_all_transactions(), None); } #[test] fn finalize_multiple_blocks() { let mut node = Node::new(); node.create_transaction(); let first_block = node.propose_block().unwrap(); node.finalize_block(first_block.clone()); node.create_transaction(); let second_block = node.propose_block().unwrap(); node.finalize_block(second_block.clone()); assert_eq!(node.chain.height(), Some(1)); assert_eq!(node.chain.last(), Some(&second_block)); assert_eq!(node.mempool.len(), 0); assert_eq!(node.mempool.get_all_transactions(), None); } #[test] fn finalize_block_pending_transactions() { let mut node = Node::new(); node.create_transaction(); let block_proposal = node.propose_block().unwrap(); node.create_transaction(); node.create_transaction(); node.finalize_block(block_proposal.clone()); assert_eq!(node.chain.height(), Some(0)); assert_eq!(node.chain.last(), Some(&block_proposal)); assert_eq!(node.mempool.len(), 2); } #[test] fn lifecycle() { let mut node = Node::new(); assert_eq!(node.chain.height(), None); node.create_transaction(); let first_block = node.propose_block().unwrap(); node.finalize_block(first_block.clone()); assert_eq!(first_block.transactions.len(), 1); assert_eq!(first_block.get_previous_block_id(), None); assert_eq!(node.chain.get(0), Some(&first_block)); assert_eq!(node.chain.height(), Some(0)); assert_eq!(node.mempool.len(), 0); node.create_transaction(); node.create_transaction(); let second_block = node.propose_block().unwrap(); node.finalize_block(second_block.clone()); assert_eq!(second_block.transactions.len(), 2); assert_eq!(second_block.get_previous_block_id(), Some(&first_block.id)); assert_eq!(node.chain.get(1), Some(&second_block)); assert_eq!(node.chain.height(), Some(1)); assert_eq!(node.mempool.len(), 0); node.create_transaction(); node.create_transaction(); node.create_transaction(); let third_block = node.propose_block().unwrap(); node.create_transaction(); node.create_transaction(); node.finalize_block(third_block.clone()); assert_eq!(third_block.transactions.len(), 3); assert_eq!(third_block.get_previous_block_id(), Some(&second_block.id)); assert_eq!(node.chain.get(2), Some(&third_block)); assert_eq!(node.chain.height(), Some(2)); assert_eq!(node.mempool.len(), 2); let tx_1 = Transaction::new(vec![0, 1, 2, 3, 4], 1); let tx_2 = Transaction::new(vec![5, 6, 7, 8, 9], 1); let transactions = vec![tx_1, tx_2]; node.add_transactions(transactions); let fourth_block = node.propose_block().unwrap(); node.finalize_block(fourth_block.clone()); assert_eq!(fourth_block.transactions.len(), 4); assert_eq!(fourth_block.get_previous_block_id(), Some(&third_block.id)); assert_eq!(node.chain.get(3), Some(&fourth_block)); assert_eq!(node.chain.height(), Some(3)); assert_eq!(node.mempool.len(), 0); } #[test] fn generate_transaction_index() { let mut node = Node::new(); let tx = Transaction::new(vec![0, 1, 2, 3, 4], 1); let index = node.generate_transaction_index(&tx); assert_eq!( index, vec![ 131, 104, 201, 189, 46, 213, 139, 247, 167, 5, 96, 68, 185, 137, 240, 74, 88, 236, 236, 163, 205, 63, 31, 84, 42, 72, 102, 49, 96, 111, 237, 138 ] ); let block = Block::new(vec![tx.clone()], None); node.chain.append(block); let index = node.generate_transaction_index(&tx); assert_eq!( index, vec![ 207, 58, 24, 227, 9, 92, 25, 41, 58, 138, 229, 70, 116, 80, 222, 43, 52, 244, 40, 144, 108, 8, 75, 38, 81, 216, 33, 89, 84, 248, 102, 53 ] ) } }
use crate::{ block::Block, chain::Chain, transaction::Transaction, utils::{Keccak256, Sender}, }; use crate::{mempool::Mempool, utils::hash}; use rand::prelude::SliceRandom; pub struct Node { chain: Chain, mempool: Mempool, nonce: u64, } impl Node { pub fn new() -> Self { let chain = Chain::new(1000); let mempool = Mempool::new(); Node { chain, mempool, nonce: 1, } } pub fn create_transaction(&mut self) { let mut rng = rand::thread_rng(); let mut numbers: Vec<u8> = (1..100).collect(); numbers.shuffle(&mut rng); let sender: Sender = hash(numbers); let tx = Transaction::new(sender, self.nonce); self.add_transaction(tx); self.nonce += 1; } pub fn add_transaction(&mut self, transaction: Transaction) { let index = self.generate_transaction_index(&transaction); self.mempool.insert(index, transaction); } pub fn add_transactions(&mut self, transactions: Vec<Transaction>) { transactions .into_iter() .for_each(|tx| self.add_transaction(tx)); } pub fn propose_block(&self) -> Option<Block> { if let Some(transactions) = self.mempool.get_all_transactions() { let mut prev_block_id = None; if let Some(block) = self.chain.last() { prev_block_id = Some(block.id.clone()); } return Some(Block::new(transactions, prev_block_id)); } None } pub fn finalize_block(&mut self, block: Block) { let tx_indexes: Vec<Keccak256> = block .transactions .iter() .map(|tx| self.generate_transaction_index(tx)) .collect(); self.chain.append(block); self.mempool.remove_transactions(tx_indexes); if let Some(transactions) = self.mempool.get_all_transactions() { self.mempool.clear(); transactions.into_iter().for_each(|tx| { let index = self.generate_transaction_index(&tx); self.mempool.insert(index, tx); }); } } fn generate_transaction_index(&self, transaction: &Transaction) -> Keccak256 { let mut block_id = None; if let Some(block) = self.chain.last() { block_id = Some(block.id.clone()); } let data = bincode::serialize(&(transaction.id.clone(), block_id)).unwrap(); hash(data) } } #[cfg(test)] mod tests { use super::*; #[test] fn new_node() { let node = Node::new(); assert_eq!(node.mempool.get_all_transactions(), None); assert_eq!(node.chain.height(), None); assert_eq!(node.nonce, 1); } #[test] fn create_transaction() { let mut node = Node::new(); node.create_transaction(); assert_eq!(node.mempool.len(), 1); assert_eq!(node.nonce, 2); } #[test] fn add_transaction() { let mut node = Node::new(); let tx = Transaction::new(vec![0, 1, 2, 3, 4],
#[test] fn add_transactions() { let mut node = Node::new(); let tx_1 = Transaction::new(vec![0, 1, 2, 3, 4], 1); let tx_2 = Transaction::new(vec![5, 6, 7, 8, 9], 1); let transactions = vec![tx_1, tx_2]; node.add_transactions(transactions); assert_eq!(node.mempool.len(), 2); assert_eq!(node.nonce, 1); } #[test] fn propose_block() { let mut node = Node::new(); let block = node.propose_block(); assert_eq!(block, None); node.create_transaction(); let block = node.propose_block(); assert!(block.is_some()); let block = block.unwrap(); assert_eq!(block.transactions.len(), 1); assert_eq!(block.get_previous_block_id(), None); } #[test] fn finalize_single_block() { let mut node = Node::new(); node.create_transaction(); let block_proposal = node.propose_block().unwrap(); node.finalize_block(block_proposal.clone()); assert_eq!(node.chain.height(), Some(0)); assert_eq!(node.chain.last(), Some(&block_proposal)); assert_eq!(node.mempool.get_all_transactions(), None); } #[test] fn finalize_multiple_blocks() { let mut node = Node::new(); node.create_transaction(); let first_block = node.propose_block().unwrap(); node.finalize_block(first_block.clone()); node.create_transaction(); let second_block = node.propose_block().unwrap(); node.finalize_block(second_block.clone()); assert_eq!(node.chain.height(), Some(1)); assert_eq!(node.chain.last(), Some(&second_block)); assert_eq!(node.mempool.len(), 0); assert_eq!(node.mempool.get_all_transactions(), None); } #[test] fn finalize_block_pending_transactions() { let mut node = Node::new(); node.create_transaction(); let block_proposal = node.propose_block().unwrap(); node.create_transaction(); node.create_transaction(); node.finalize_block(block_proposal.clone()); assert_eq!(node.chain.height(), Some(0)); assert_eq!(node.chain.last(), Some(&block_proposal)); assert_eq!(node.mempool.len(), 2); } #[test] fn lifecycle() { let mut node = Node::new(); assert_eq!(node.chain.height(), None); node.create_transaction(); let first_block = node.propose_block().unwrap(); node.finalize_block(first_block.clone()); assert_eq!(first_block.transactions.len(), 1); assert_eq!(first_block.get_previous_block_id(), None); assert_eq!(node.chain.get(0), Some(&first_block)); assert_eq!(node.chain.height(), Some(0)); assert_eq!(node.mempool.len(), 0); node.create_transaction(); node.create_transaction(); let second_block = node.propose_block().unwrap(); node.finalize_block(second_block.clone()); assert_eq!(second_block.transactions.len(), 2); assert_eq!(second_block.get_previous_block_id(), Some(&first_block.id)); assert_eq!(node.chain.get(1), Some(&second_block)); assert_eq!(node.chain.height(), Some(1)); assert_eq!(node.mempool.len(), 0); node.create_transaction(); node.create_transaction(); node.create_transaction(); let third_block = node.propose_block().unwrap(); node.create_transaction(); node.create_transaction(); node.finalize_block(third_block.clone()); assert_eq!(third_block.transactions.len(), 3); assert_eq!(third_block.get_previous_block_id(), Some(&second_block.id)); assert_eq!(node.chain.get(2), Some(&third_block)); assert_eq!(node.chain.height(), Some(2)); assert_eq!(node.mempool.len(), 2); let tx_1 = Transaction::new(vec![0, 1, 2, 3, 4], 1); let tx_2 = Transaction::new(vec![5, 6, 7, 8, 9], 1); let transactions = vec![tx_1, tx_2]; node.add_transactions(transactions); let fourth_block = node.propose_block().unwrap(); node.finalize_block(fourth_block.clone()); assert_eq!(fourth_block.transactions.len(), 4); assert_eq!(fourth_block.get_previous_block_id(), Some(&third_block.id)); assert_eq!(node.chain.get(3), Some(&fourth_block)); assert_eq!(node.chain.height(), Some(3)); assert_eq!(node.mempool.len(), 0); } #[test] fn generate_transaction_index() { let mut node = Node::new(); let tx = Transaction::new(vec![0, 1, 2, 3, 4], 1); let index = node.generate_transaction_index(&tx); assert_eq!( index, vec![ 131, 104, 201, 189, 46, 213, 139, 247, 167, 5, 96, 68, 185, 137, 240, 74, 88, 236, 236, 163, 205, 63, 31, 84, 42, 72, 102, 49, 96, 111, 237, 138 ] ); let block = Block::new(vec![tx.clone()], None); node.chain.append(block); let index = node.generate_transaction_index(&tx); assert_eq!( index, vec![ 207, 58, 24, 227, 9, 92, 25, 41, 58, 138, 229, 70, 116, 80, 222, 43, 52, 244, 40, 144, 108, 8, 75, 38, 81, 216, 33, 89, 84, 248, 102, 53 ] ) } }
1); node.add_transaction(tx); assert_eq!(node.mempool.len(), 1); assert_eq!(node.nonce, 1); }
function_block-function_prefixed
[ { "content": "use bincode;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::utils;\n\nuse super::utils::{BinEncoding, Keccak256, Sender};\n\n\n\n/// A Transaction which includes a reference to its sender and a nonce.\n\n#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]\n\npub struct Transactio...
Rust
cli/src/command/list/list.rs
bennyboer/worklog
bce3c3954c3a14cca7c029caf2641ec1f5af4478
use std::collections::HashMap; use cmd_args::{arg, option, Group}; use colorful::Colorful; use persistence::calc::{Status, WorkItem}; use crate::command::command::Command; use std::ops::Sub; pub struct ListCommand {} impl Command for ListCommand { fn build(&self) -> Group { Group::new( Box::new(|args, options| execute(args, options)), "List work items", ) .add_option(option::Descriptor::new( "all", option::Type::Bool { default: false }, "Show all available log entries", )) .add_option(option::Descriptor::new( "filter", option::Type::Str { default: String::from("today"), }, "Filter by a date ('today' (default), 'yesterday', '2020-02-20' (yyyy-MM-dd)) or work item ID", )) } fn aliases(&self) -> Option<Vec<&str>> { Some(vec!["ls"]) } fn name(&self) -> &str { "list" } } fn execute(_args: &Vec<arg::Value>, options: &HashMap<&str, option::Value>) { let all: bool = options.get("all").map_or(false, |v| v.bool().unwrap()); let mut entries = match all { true => persistence::list_items().unwrap(), false => { let filter: &str = options.get("filter").map_or("today", |v| v.str().unwrap()); match filter.parse::<i32>() { Ok(id) => persistence::find_item_by_id(id) .unwrap() .map_or(Vec::new(), |v| vec![v]), Err(_) => { let (from_timestamp, to_timestamp) = filter_keyword_to_time_range(filter); persistence::find_items_by_timerange(from_timestamp, to_timestamp).unwrap() } } } }; let found_str: String = format!("| Found {} log entries |", entries.len()); println!(" {} ", "-".repeat(found_str.len() - 2)); println!("{}", found_str); println!(" {} ", "-".repeat(found_str.len() - 2)); entries.sort_by_key(|v| i64::max_value() - v.created_timestamp()); let mut items_per_day = Vec::new(); items_per_day.push(Vec::new()); let mut last_date_option: Option<chrono::Date<_>> = None; for item in &entries { let date_time = shared::time::get_local_date_time(item.created_timestamp()); let is_another_day = match last_date_option { Some(last_date) => date_time.date().sub(last_date).num_days().abs() >= 1, None => false, }; if is_another_day { items_per_day.push(Vec::new()); } let current_day_items = items_per_day.last_mut().unwrap(); current_day_items.push(item); last_date_option = Some(date_time.date()); } for items in items_per_day { if !items.is_empty() { print_date_header(&items); for item in items { println!(" • {}", format_item(item)); } } } println!(); } fn print_date_header(items: &[&WorkItem]) { let first = *items.first().unwrap(); let date_time = shared::time::get_local_date_time(first.created_timestamp()); println!(); println!( "{}", format!( "# {} ({})", date_time.format("%A - %d. %B %Y"), shared::time::format_duration((calculate_total_work_time(items) / 1000) as u32) ) .underlined() ); println!(); } pub(crate) fn calculate_total_work_time(items: &[&WorkItem]) -> i64 { let mut time_events: Vec<shared::calc::TimeEvent> = items .iter() .flat_map(|i| { i.events() .iter() .map(|e| shared::calc::TimeEvent::new(e.is_start(), e.timestamp())) }) .collect(); for item in items { if let Status::InProgress = item.status() { time_events.push(shared::calc::TimeEvent::new( false, chrono::Utc::now().timestamp_millis(), )); } } shared::calc::calculate_unique_total_time(&mut time_events) } fn format_item(item: &WorkItem) -> String { let id_str = format!( "#{}", item.id().expect("Work item must have an ID at this point!") ) .color(colorful::Color::DodgerBlue3); let time_str = shared::time::get_local_date_time(item.created_timestamp()) .format("%H:%M") .to_string() .color(colorful::Color::DeepPink1a); let description = item.description(); let duration_str = shared::time::format_duration((item.time_taken() / 1000) as u32) .color(colorful::Color::Orange1); let status_str = match item.status() { Status::Done => duration_str, Status::InProgress => { format!("IN PROGRESS ({})", duration_str).color(colorful::Color::GreenYellow) } Status::Paused => format!("PAUSED ({})", duration_str).color(colorful::Color::Red), }; let tags_formatted: Vec<_> = item.tags().iter().map(|s| format!("#{}", s)).collect(); let tags_str = tags_formatted .join(", ") .color(colorful::Color::DarkSlateGray1); format!( "{} [{}] {} - {} ({})", id_str, time_str, description, status_str, tags_str ) } pub(crate) fn filter_keyword_to_time_range(keyword: &str) -> (i64, i64) { match keyword { "today" => { let today = chrono::Utc::today(); let from_timestamp = today.and_hms(0, 0, 0).timestamp_millis(); let to_timestamp = today.succ().and_hms(0, 0, 0).timestamp_millis(); (from_timestamp, to_timestamp) } "yesterday" => { let yesterday = chrono::Utc::today().pred(); let from_timestamp = yesterday.and_hms(0, 0, 0).timestamp_millis(); let to_timestamp = yesterday.succ().and_hms(0, 0, 0).timestamp_millis(); (from_timestamp, to_timestamp) } str => { let date = chrono::NaiveDate::parse_from_str(str, "%Y-%m-%d") .expect("Expected date format to be in form 'YYYY-MM-dd'"); let from_timestamp = date.and_hms(0, 0, 0).timestamp_millis(); let to_timestamp = date.succ().and_hms(0, 0, 0).timestamp_millis(); (from_timestamp, to_timestamp) } } }
use std::collections::HashMap; use cmd_args::{arg, option, Group}; use colorful::Colorful; use persistence::calc::{Status, WorkItem}; use crate::command::command::Command; use std::ops::Sub; pub struct ListCommand {} impl Command for ListCommand { fn build(&self) -> Group { Group::new( Box::new(|args, options| execute(args, options)), "List work items", ) .add_option(option::Descriptor::new( "all", option::Type::Bool { default: false }, "Show all available log entries", )) .add_option(option::Descriptor::new( "filter", option::Type::Str { default: String::from("today"), }, "Filter by a date ('today' (default), 'yesterday', '2020-02-20' (yyyy-MM-dd)) or work item ID", )) } fn aliases(&self) -> Option<Vec<&str>> { Some(vec!["ls"]) } fn name(&self) -> &str { "list" } } fn execute(_args: &Vec<arg::Value>, options: &HashMap<&str, option::Value>) { let all: bool = options.get("all").map_or(false, |v| v.bool().unwrap()); let mut entries = match all { true => persistence::list_items().unwrap(), false => { let filter: &str = options.get("filter").map_or("today", |v| v.str().unwrap()); match filter.parse::<i32>() { Ok(id) => persistence::find_item_by_id(id) .unwrap() .map_or(Vec::new(), |v| vec![v]), Err(_) => { let (from_timestamp, to_timestamp) = filter_keyword_to_time_range(filter); persistence::find_items_by_timerange(from_timestamp, to_timestamp).unwrap() } } } }; let found_str: String = format!("| Found {} log entries |", entries.len()); println!(" {} ", "-".repeat(found_str.len() - 2)); println!("{}", found_str); println!(" {} ", "-".repeat(found_str.len() - 2)); entries.sort_by_key(|v| i64::max_value() - v.created_timestamp()); let mut items_per_day = Vec::new(); items_per_day.push(Vec::new()); let mut last_date_option: Option<chrono::Date<_>> = None; for item in &entries { let date_time = shared::time::get_local_date_time(item.created_timestamp()); let is_another_day = match last_date_option { Some(last_date) => date_time.date().sub(last_date).num_days().abs() >= 1, None => false, }; if is_another_day { items_per_day.push(Vec::new()); } let current_day_items = items_per_day.last_mut().unwrap(); current_day_items.push(item); last_date_option = Some(date_time.date()); } for items in items_per_day { if !items.is_empty() { print_date_header(&items); for item in items { println!(" • {}", format_item(item)); } } } println!(); } fn print_date_header(items: &[&WorkItem]) { let first = *items.first().unwrap(); let date_time = shared::time::get_local_date_time(first.created_timestamp()); println!(); println!( "{}", format!( "# {} ({})", date_time.format("%A - %d. %B %Y"), shared::time::format_duration((calculate_total_work_time(items) / 1000) as u32) ) .underlined() ); println!(); }
fn format_item(item: &WorkItem) -> String { let id_str = format!( "#{}", item.id().expect("Work item must have an ID at this point!") ) .color(colorful::Color::DodgerBlue3); let time_str = shared::time::get_local_date_time(item.created_timestamp()) .format("%H:%M") .to_string() .color(colorful::Color::DeepPink1a); let description = item.description(); let duration_str = shared::time::format_duration((item.time_taken() / 1000) as u32) .color(colorful::Color::Orange1); let status_str = match item.status() { Status::Done => duration_str, Status::InProgress => { format!("IN PROGRESS ({})", duration_str).color(colorful::Color::GreenYellow) } Status::Paused => format!("PAUSED ({})", duration_str).color(colorful::Color::Red), }; let tags_formatted: Vec<_> = item.tags().iter().map(|s| format!("#{}", s)).collect(); let tags_str = tags_formatted .join(", ") .color(colorful::Color::DarkSlateGray1); format!( "{} [{}] {} - {} ({})", id_str, time_str, description, status_str, tags_str ) } pub(crate) fn filter_keyword_to_time_range(keyword: &str) -> (i64, i64) { match keyword { "today" => { let today = chrono::Utc::today(); let from_timestamp = today.and_hms(0, 0, 0).timestamp_millis(); let to_timestamp = today.succ().and_hms(0, 0, 0).timestamp_millis(); (from_timestamp, to_timestamp) } "yesterday" => { let yesterday = chrono::Utc::today().pred(); let from_timestamp = yesterday.and_hms(0, 0, 0).timestamp_millis(); let to_timestamp = yesterday.succ().and_hms(0, 0, 0).timestamp_millis(); (from_timestamp, to_timestamp) } str => { let date = chrono::NaiveDate::parse_from_str(str, "%Y-%m-%d") .expect("Expected date format to be in form 'YYYY-MM-dd'"); let from_timestamp = date.and_hms(0, 0, 0).timestamp_millis(); let to_timestamp = date.succ().and_hms(0, 0, 0).timestamp_millis(); (from_timestamp, to_timestamp) } } }
pub(crate) fn calculate_total_work_time(items: &[&WorkItem]) -> i64 { let mut time_events: Vec<shared::calc::TimeEvent> = items .iter() .flat_map(|i| { i.events() .iter() .map(|e| shared::calc::TimeEvent::new(e.is_start(), e.timestamp())) }) .collect(); for item in items { if let Status::InProgress = item.status() { time_events.push(shared::calc::TimeEvent::new( false, chrono::Utc::now().timestamp_millis(), )); } } shared::calc::calculate_unique_total_time(&mut time_events) }
function_block-full_function
[ { "content": "/// Format a duration given in seconds in the form \"Xh Xm Xs\".\n\npub fn format_duration(mut seconds: u32) -> String {\n\n let hours = seconds / 60 / 60;\n\n seconds -= hours * 60 * 60;\n\n\n\n let minutes = seconds / 60;\n\n seconds -= minutes * 60;\n\n\n\n let mut result = Vec::...
Rust
nachricht-serde/src/ser.rs
yasammez/nachricht
846d60dec1da1ddd5ffa2c1fa1ab7ec5d7386bce
use serde::ser::{self, Serialize, Impossible}; use nachricht::{EncodeError, Header, Refable}; use std::io::Write; use crate::error::{Error, Result}; pub struct Serializer<W> { symbols: Vec<(Refable, String)>, output: W, } pub fn to_bytes<T: Serialize>(value: &T) -> Result<Vec<u8>> { let buf = Vec::new(); let mut serializer = Serializer { output: buf, symbols: Vec::new() }; value.serialize(&mut serializer)?; Ok(serializer.output()) } pub fn to_writer<T: Serialize, W: Write>(writer: W, value: &T) -> Result<()> { let mut serializer = Serializer { output: writer, symbols: Vec::new() }; value.serialize(&mut serializer)?; Ok(()) } impl Serializer<Vec<u8>> { fn output(self) -> Vec<u8> { self.output } } impl<W: Write> Serializer<W> { fn serialize_refable(&mut self, key: &str, kind: Refable) -> Result<()> { match self.symbols.iter().enumerate().find(|(_, (k, v))| *k == kind && v == key) { Some((i, _)) => { Header::Ref(i).encode(&mut self.output)?; }, None => { self.symbols.push((kind, key.to_owned())); match kind { Refable::Key => Header::Key(key.len()), Refable::Sym => Header::Sym(key.len()) }.encode(&mut self.output)?; self.output.write_all(key.as_bytes()).map_err(EncodeError::from)?; } } Ok(()) } } impl<'a, W: Write> ser::Serializer for &'a mut Serializer<W> { type Ok = (); type Error = Error; type SerializeSeq = Self; type SerializeTuple = Self; type SerializeTupleStruct = Self; type SerializeTupleVariant = Self; type SerializeMap = Self; type SerializeStruct = Self; type SerializeStructVariant = Self; fn serialize_bool(self, v: bool) -> Result<()> { match v { true => Header::True, false => Header::False }.encode(&mut self.output)?; Ok(()) } fn serialize_i8(self, v: i8) -> Result<()> { self.serialize_i64(i64::from(v)) } fn serialize_i16(self, v: i16) -> Result<()> { self.serialize_i64(i64::from(v)) } fn serialize_i32(self, v: i32) -> Result<()> { self.serialize_i64(i64::from(v)) } fn serialize_i64(self, v: i64) -> Result<()> { if v < 0 { Header::Neg(v.abs() as u64) } else { Header::Pos(v as u64) }.encode(&mut self.output)?; Ok(()) } fn serialize_u8(self, v: u8) -> Result<()> { self.serialize_u64(u64::from(v)) } fn serialize_u16(self, v: u16) -> Result<()> { self.serialize_u64(u64::from(v)) } fn serialize_u32(self, v: u32) -> Result<()> { self.serialize_u64(u64::from(v)) } fn serialize_u64(self, v: u64) -> Result<()> { Header::Pos(v).encode(&mut self.output)?; Ok(()) } fn serialize_f32(self, v: f32) -> Result<()> { Header::F32.encode(&mut self.output)?; self.output.write_all(&v.to_be_bytes()).map_err(EncodeError::from)?; Ok(()) } fn serialize_f64(self, v: f64) -> Result<()> { Header::F64.encode(&mut self.output)?; self.output.write_all(&v.to_be_bytes()).map_err(EncodeError::from)?; Ok(()) } fn serialize_char(self, v: char) -> Result<()> { self.serialize_str(&v.to_string()) } fn serialize_str(self, v: &str) -> Result<()> { Header::Str(v.len()).encode(&mut self.output)?; self.output.write_all(v.as_bytes()).map_err(EncodeError::from)?; Ok(()) } fn serialize_bytes(self, v: &[u8]) -> Result<()> { Header::Bin(v.len()).encode(&mut self.output)?; self.output.write_all(v).map_err(EncodeError::from)?; Ok(()) } fn serialize_none(self) -> Result<()> { Header::Null.encode(&mut self.output)?; Ok(()) } fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<()> { value.serialize(self) } fn serialize_unit(self) -> Result<()> { Header::Null.encode(&mut self.output)?; Ok(()) } fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { self.serialize_unit() } fn serialize_unit_variant(self, _name: &'static str, _index: u32, variant: &'static str) -> Result<()> { self.serialize_refable(variant, Refable::Sym) } fn serialize_newtype_struct<T: ?Sized + Serialize>(self, _name: &'static str, value: &T) -> Result<()> { value.serialize(self) } fn serialize_newtype_variant<T: ?Sized + Serialize>(self, _name: &'static str, _index: u32, variant: &'static str, value: &T) -> Result<()> { Header::Bag(1).encode(&mut self.output)?; self.serialize_refable(variant, Refable::Key)?; value.serialize(self)?; Ok(()) } fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> { match len { Some(l) => { Header::Bag(l).encode(&mut self.output)?; Ok(self) }, None => Err(Error::Length), } } fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> { self.serialize_seq(Some(len)) } fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeTupleStruct> { self.serialize_seq(Some(len)) } fn serialize_tuple_variant(self, _name: &'static str, _index: u32, variant: &'static str, len: usize) -> Result<Self::SerializeTupleVariant> { Header::Bag(1).encode(&mut self.output)?; self.serialize_refable(variant, Refable::Key)?; Header::Bag(len).encode(&mut self.output)?; Ok(self) } fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> { match len { Some(len) => { Header::Bag(len).encode(&mut self.output)?; Ok(self) }, None => Err(Error::Length) } } fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> { Header::Bag(len).encode(&mut self.output)?; Ok(self) } fn serialize_struct_variant(self, name: &'static str, index: u32, variant: &'static str, len: usize) -> Result<Self::SerializeStructVariant> { self.serialize_tuple_variant(name, index, variant, len) } } impl<'a, W: Write> ser::SerializeSeq for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeTuple for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeTupleStruct for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeTupleVariant for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeMap for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<()> { key.serialize(MapKeySerializer { ser: self }) } fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeStruct for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<()> { self.serialize_refable(key, Refable::Key)?; value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeStructVariant for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<()> { self.serialize_refable(key, Refable::Key)?; value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } struct MapKeySerializer<'a, W: 'a> { ser: &'a mut Serializer<W>, } impl<'a, W: Write> ser::Serializer for MapKeySerializer<'a, W> { type Ok = (); type Error = Error; type SerializeSeq = Impossible<(), Error>; type SerializeTuple = Impossible<(), Error>; type SerializeTupleStruct = Impossible<(), Error>; type SerializeTupleVariant = Impossible<(), Error>; type SerializeMap = Impossible<(), Error>; type SerializeStruct = Impossible<(), Error>; type SerializeStructVariant = Impossible<(), Error>; fn serialize_bool(self, v: bool) -> Result<()> { self.ser.serialize_refable(match v { true => "true", false => "false" }, Refable::Key) } fn serialize_i8(self, v: i8) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_i16(self, v: i16) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_i32(self, v: i32) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_i64(self, v: i64) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u8(self, v: u8) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u16(self, v: u16) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u32(self, v: u32) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u64(self, v: u64) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_f32(self, _v: f32) -> Result<()> { Err(Error::KeyType) } fn serialize_f64(self, _v: f64) -> Result<()> { Err(Error::KeyType) } fn serialize_char(self, v: char) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_str(self, v: &str) -> Result<()> { self.ser.serialize_refable(v, Refable::Key) } fn serialize_bytes(self, _v: &[u8]) -> Result<()> { Err(Error::KeyType) } fn serialize_none(self) -> Result<()> { Err(Error::KeyType) } fn serialize_some<T: ?Sized + Serialize>(self, _v: &T) -> Result<()> { Err(Error::KeyType) } fn serialize_unit(self) -> Result<()> { Err(Error::KeyType) } fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { Err(Error::KeyType) } fn serialize_unit_variant(self, _name: &'static str, _index: u32, variant: &'static str) -> Result<()> { self.ser.serialize_refable(variant, Refable::Key) } fn serialize_newtype_struct<T: ?Sized + Serialize>(self, _name: &'static str, value: &T) -> Result<()> { value.serialize(self) } fn serialize_newtype_variant<T: ?Sized + Serialize>(self, _name: &'static str, _index: u32, _variant: &'static str, _value: &T) -> Result<()> { Err(Error::KeyType) } fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> { Err(Error::KeyType) } fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { Err(Error::KeyType) } fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> { Err(Error::KeyType) } fn serialize_tuple_variant(self, _name: &'static str, _index: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeTupleVariant> { Err(Error::KeyType) } fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> { Err(Error::KeyType) } fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> { Err(Error::KeyType) } fn serialize_struct_variant(self, _name: &'static str, _index: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeStructVariant> { Err(Error::KeyType) } }
use serde::ser::{self, Serialize, Impossible}; use nachricht::{EncodeError, Header, Refable}; use std::io::Write; use crate::error::{Error, Result}; pub struct Serializer<W> { symbols: Vec<(Refable, String)>, output: W, } pub fn to_bytes<T: Serialize>(value: &T) -> Result<Vec<u8>> { let buf = Vec::new(); let mut serializer = Serializer { output: buf, symbols: Vec::new() }; value.serialize(&mut serializer)?; Ok(serializer.output()) } pub fn to_writer<T: Serialize, W: Write>(writer: W, value: &T) -> Result<()> { let mut serializer = Serializer { output: writer, symbols: Vec::new() }; value.serialize(&mut serializer)?; Ok(()) } impl Serializer<Vec<u8>> { fn output(self) -> Vec<u8> { self.output } } impl<W: Write> Serializer<W> { fn serialize_refable(&mut self, key: &str, kind: Refable) -> Result<()> { match self.symbols.iter().enumerate().find(|(_, (k, v))| *k == kind && v == key) { Some((i, _)) => { Header::Ref(i).encode(&mut self.output)?; }, None => { self.symbols.push((kind, key.to_owned())); match kind { Refable::Key => Header::Key(key.len()), Refable::Sym => Header::Sym(key.len()) }.encode(&mut self.output)?; self.output.write_all(key.as_bytes()).map_err(EncodeError::from)?; } } Ok(()) } } impl<'a, W: Write> ser::Serializer for &'a mut Serializer<W> { type Ok = (); type Error = Error; type SerializeSeq = Self; type SerializeTuple = Self; type SerializeTupleStruct = Self; type SerializeTupleVariant = Self; type SerializeMap = Self; type SerializeStruct = Self; type SerializeStructVariant = Self; fn serialize_bool(self, v: bool) -> Result<()> { match v { true => Header::True, false => Header::False }.encode(&mut self.output)?; Ok(()) } fn serialize_i8(self, v: i8) -> Result<()> { self.serialize_i64(i64::from(v)) } fn serialize_i16(self, v: i16) -> Result<()> { self.serialize_i64(i64::from(v)) } fn serialize_i32(self, v: i32) -> Result<()> { self.serialize_i64(i64::from(v)) } fn serialize_i64(self, v: i64) -> Result<()> { if v < 0 { Header::Neg(v.abs() as u64) } else { Header::Pos(v as u64) }.encode(&mut self.output)?; Ok(()) } fn serialize_u8(self, v: u8) -> Result<()> { self.serialize_u64(u64::from(v)) } fn serialize_u16(self, v: u16) -> Result<()> { self.serialize_u64(u64::from(v)) } fn serialize_u32(self, v: u32) -> Result<()> { self.serialize_u64(u64::from(v)) } fn serialize_u64(self, v: u64) -> Result<()> { Header::Pos(v).encode(&mut self.output)?; Ok(()) } fn serialize_f32(self, v: f32) -> Result<()> { Header::F32.encode(&mut self.output)?; self.output.write_all(&v.to_be_bytes()).map_err(EncodeError::from)?; Ok(()) } fn serialize_f64(self, v: f64) -> Result<()> { Header::F64.encode(&mut self.output)?; self.output.write_all(&v.to_be_bytes()).map_err(EncodeError::from)?; Ok(()) } fn serialize_char(self, v: char) -> Result<()> { self.serialize_str(&v.to_string()) } fn serialize_str(self, v: &str) -> Result<()> { Header::Str(v.len()).encode(&mut self.output)?; self.output.write_all(v.as_bytes()).map_err(EncodeError::from)?; Ok(()) } fn serialize_bytes(self, v: &[u8]) -> Result<()> { Header::Bin(v.len()).encode(&mut self.output)?; self.output.write_all(v).map_err(EncodeError::from)?; Ok(()) } fn serialize_none(self) -> Result<()> { Header::Null.encode(&mut self.output)?; Ok(()) } fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<()> { value.serialize(self) } fn serialize_unit(self) -> Result<()> { Header::Null.encode(&mut self.output)?; Ok(()) } fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { self.serialize_unit() } fn serialize_unit_variant(self, _name: &'static str, _index: u32, variant: &'static str) -> Result<()> { self.serialize_refable(variant, Refable::Sym) } fn serialize_newtype_struct<T: ?Sized + Serialize>(self, _name: &'static str, value: &T) -> Result<()> { value.serialize(self) } fn serialize_newtype_variant<T: ?Sized + Serialize>(self, _name: &'static str, _index: u32, variant: &'static str, value: &T) -> Result<()> { Header::Bag(1).encode(&mut self.output)?; self.serialize_refable(variant, Refable::Key)?; value.serialize(self)?; Ok(()) } fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> { match len { Some(l) => { Header::Bag(l).encode(&mut self.output)?; Ok(self) }, None => Err(Error::Length), } } fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> { self.serialize_seq(Some(len)) } fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeTupleStruct> { self.serialize_seq(Some(len)) } fn serialize_tuple_variant(self, _name: &'static str, _index: u32, variant: &'static str, len: usize) -> Result<Self::SerializeTupleVariant> { Header::Bag(1).encode(&mut self.outpu
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> { match len { Some(len) => { Header::Bag(len).encode(&mut self.output)?; Ok(self) }, None => Err(Error::Length) } } fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> { Header::Bag(len).encode(&mut self.output)?; Ok(self) } fn serialize_struct_variant(self, name: &'static str, index: u32, variant: &'static str, len: usize) -> Result<Self::SerializeStructVariant> { self.serialize_tuple_variant(name, index, variant, len) } } impl<'a, W: Write> ser::SerializeSeq for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeTuple for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeTupleStruct for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeTupleVariant for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeMap for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<()> { key.serialize(MapKeySerializer { ser: self }) } fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeStruct for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<()> { self.serialize_refable(key, Refable::Key)?; value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeStructVariant for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<()> { self.serialize_refable(key, Refable::Key)?; value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } struct MapKeySerializer<'a, W: 'a> { ser: &'a mut Serializer<W>, } impl<'a, W: Write> ser::Serializer for MapKeySerializer<'a, W> { type Ok = (); type Error = Error; type SerializeSeq = Impossible<(), Error>; type SerializeTuple = Impossible<(), Error>; type SerializeTupleStruct = Impossible<(), Error>; type SerializeTupleVariant = Impossible<(), Error>; type SerializeMap = Impossible<(), Error>; type SerializeStruct = Impossible<(), Error>; type SerializeStructVariant = Impossible<(), Error>; fn serialize_bool(self, v: bool) -> Result<()> { self.ser.serialize_refable(match v { true => "true", false => "false" }, Refable::Key) } fn serialize_i8(self, v: i8) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_i16(self, v: i16) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_i32(self, v: i32) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_i64(self, v: i64) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u8(self, v: u8) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u16(self, v: u16) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u32(self, v: u32) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u64(self, v: u64) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_f32(self, _v: f32) -> Result<()> { Err(Error::KeyType) } fn serialize_f64(self, _v: f64) -> Result<()> { Err(Error::KeyType) } fn serialize_char(self, v: char) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_str(self, v: &str) -> Result<()> { self.ser.serialize_refable(v, Refable::Key) } fn serialize_bytes(self, _v: &[u8]) -> Result<()> { Err(Error::KeyType) } fn serialize_none(self) -> Result<()> { Err(Error::KeyType) } fn serialize_some<T: ?Sized + Serialize>(self, _v: &T) -> Result<()> { Err(Error::KeyType) } fn serialize_unit(self) -> Result<()> { Err(Error::KeyType) } fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { Err(Error::KeyType) } fn serialize_unit_variant(self, _name: &'static str, _index: u32, variant: &'static str) -> Result<()> { self.ser.serialize_refable(variant, Refable::Key) } fn serialize_newtype_struct<T: ?Sized + Serialize>(self, _name: &'static str, value: &T) -> Result<()> { value.serialize(self) } fn serialize_newtype_variant<T: ?Sized + Serialize>(self, _name: &'static str, _index: u32, _variant: &'static str, _value: &T) -> Result<()> { Err(Error::KeyType) } fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> { Err(Error::KeyType) } fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { Err(Error::KeyType) } fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> { Err(Error::KeyType) } fn serialize_tuple_variant(self, _name: &'static str, _index: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeTupleVariant> { Err(Error::KeyType) } fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> { Err(Error::KeyType) } fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> { Err(Error::KeyType) } fn serialize_struct_variant(self, _name: &'static str, _index: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeStructVariant> { Err(Error::KeyType) } }
t)?; self.serialize_refable(variant, Refable::Key)?; Header::Bag(len).encode(&mut self.output)?; Ok(self) }
function_block-function_prefixed
[ { "content": "fn symbol(i: &str) -> IResult<&str, String> {\n\n alt((\n\n map(tuple((tag(\"#\"), identifier)), |(_,i)| String::from(i)),\n\n map(tuple((tag(\"#\"), escaped_string)), |(_,i)| i)\n\n ))(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 1, "s...
Rust
packages/connector/src/cf.rs
hahnlee/canter
274f0ccb55892b6b8387007f0ea24f2187da5648
use core_foundation::base::{ kCFAllocatorDefault, Boolean, CFGetTypeID, CFIndex, CFRange, ToVoid, }; use core_foundation::boolean::{kCFBooleanTrue, CFBooleanGetTypeID, CFBooleanRef}; use core_foundation::data::{ CFDataCreate, CFDataGetBytePtr, CFDataGetLength, CFDataGetTypeID, CFDataRef, }; use core_foundation::dictionary::{ kCFTypeDictionaryKeyCallBacks, kCFTypeDictionaryValueCallBacks, CFDictionaryAddValue, CFDictionaryCreateMutable, CFDictionaryGetCount, CFDictionaryGetKeysAndValues, CFDictionaryGetTypeID, CFDictionaryRef, CFMutableDictionaryRef, }; use core_foundation::number::{ kCFNumberSInt64Type, CFNumber, CFNumberGetType, CFNumberGetTypeID, CFNumberGetValue, CFNumberRef, }; use core_foundation::string::{ kCFStringEncodingUTF8, CFString, CFStringGetBytes, CFStringGetCStringPtr, CFStringGetLength, CFStringGetTypeID, CFStringRef, }; use libc::c_void; use napi::{Env, JsBoolean, JsFunction, JsNumber, JsObject, JsString, JsUnknown, ValueType}; pub fn set_cf_dict( dict_ref: CFMutableDictionaryRef, key: *const c_void, unknown: JsUnknown, env: &Env, ) { let object_type = unknown.get_type().unwrap(); if object_type == ValueType::String { let cf_string = CFString::new( unknown .coerce_to_string() .unwrap() .into_utf8() .unwrap() .as_str() .unwrap(), ); unsafe { CFDictionaryAddValue(dict_ref, key, cf_string.to_void()); } return; }; if object_type == ValueType::Object { if unknown.is_typedarray().unwrap() { let object = unknown.coerce_to_object().unwrap(); let properties = object.get_property_names().unwrap(); let length = properties.get_array_length_unchecked().unwrap(); let mut data: Vec<u8> = vec![]; for i in 0..length { let elem_value = object.get_element::<JsNumber>(i).unwrap(); let value = (elem_value.get_uint32().unwrap() & 0xff) as u8; data.push(value); } let cf_data = unsafe { CFDataCreate(kCFAllocatorDefault, data.as_mut_ptr(), data.len() as isize) }; unsafe { CFDictionaryAddValue(dict_ref, key, cf_data.to_void()); } return; } let new_dict_ref = unsafe { CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks, ) }; let object = unknown.coerce_to_object().unwrap(); let properties = object.get_property_names().unwrap(); let length = properties.get_array_length_unchecked().unwrap(); for i in 0..length { let elem_key = properties.get_element::<JsString>(i).unwrap(); let value = object .get_property::<JsString, JsUnknown>(elem_key) .unwrap(); let ns_key = CFString::new(elem_key.into_utf8().unwrap().as_str().unwrap()); set_cf_dict(new_dict_ref, ns_key.to_void(), value, env); } unsafe { CFDictionaryAddValue(dict_ref, key, new_dict_ref as *const c_void); } return; } if object_type == ValueType::Number { let value = unknown.coerce_to_number().unwrap(); let cf_number = to_cf_number(value, env); unsafe { CFDictionaryAddValue(dict_ref, key, cf_number.to_void()); } } } fn to_cf_number(value: JsNumber, env: &Env) -> CFNumber { let number_object = env .get_global() .unwrap() .get_property::<JsString, JsFunction>(env.create_string("Number").unwrap()) .unwrap() .coerce_to_object() .unwrap(); let is_integer_fn = number_object .get_property::<JsString, JsFunction>(env.create_string("isInteger").unwrap()) .unwrap(); let is_integer = unsafe { is_integer_fn .call(None, &[value]) .unwrap() .cast::<JsBoolean>() .get_value() .unwrap() }; if is_integer { CFNumber::from(value.get_int32().unwrap()) } else { CFNumber::from(value.get_double().unwrap()) } } pub fn to_cf_dictionary(object: JsObject, env: &Env) -> CFMutableDictionaryRef { let properties = object.get_property_names().unwrap(); let length = properties.get_array_length_unchecked().unwrap(); let dict_ref = unsafe { CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks, ) }; for i in 0..length { let key = properties.get_element::<JsString>(i).unwrap(); let value = object.get_property::<JsString, JsUnknown>(key).unwrap(); let ns_key = CFString::new(key.into_utf8().unwrap().as_str().unwrap()); set_cf_dict(dict_ref, ns_key.to_void(), value, env); } dict_ref } fn to_string(string_ref: CFStringRef) -> String { unsafe { let char_ptr = CFStringGetCStringPtr(string_ref, kCFStringEncodingUTF8); if !char_ptr.is_null() { let c_str = std::ffi::CStr::from_ptr(char_ptr); return String::from(c_str.to_str().unwrap()); } let char_len = CFStringGetLength(string_ref); let mut bytes_required: CFIndex = 0; CFStringGetBytes( string_ref, CFRange { location: 0, length: char_len, }, kCFStringEncodingUTF8, 0, false as Boolean, std::ptr::null_mut(), 0, &mut bytes_required, ); let mut buffer = vec![b'\x00'; bytes_required as usize]; let mut bytes_used: CFIndex = 0; CFStringGetBytes( string_ref, CFRange { location: 0, length: char_len, }, kCFStringEncodingUTF8, 0, false as Boolean, buffer.as_mut_ptr(), buffer.len() as CFIndex, &mut bytes_used, ); return String::from_utf8_unchecked(buffer); } } pub fn from_object(env: &Env, dict_ref: CFDictionaryRef) -> JsObject { let length = unsafe { CFDictionaryGetCount(dict_ref) as usize }; let (keys, values) = get_keys_and_values(dict_ref, length); let mut obj = env.create_object().unwrap(); for i in 0..length { let key = to_string(keys[i] as CFStringRef); let value = values[i]; set_obj(env, &mut obj, &key, value); } obj } fn set_obj(env: &Env, obj: &mut JsObject, key: &str, value: *const c_void) { let cf_type = unsafe { CFGetTypeID(value) }; let js_key = env.create_string(key).unwrap(); if cf_type == unsafe { CFStringGetTypeID() } { let value = to_string(value as CFStringRef); let value = env.create_string(&value).unwrap(); obj.set_property(js_key, value).unwrap(); return; } if cf_type == unsafe { CFDictionaryGetTypeID() } { let value = value as CFDictionaryRef; let length = unsafe { CFDictionaryGetCount(value) as usize }; let (keys, values) = get_keys_and_values(value, length); let mut dict = env.create_object().unwrap(); for i in 0..length { let value_key = to_string(keys[i] as CFStringRef); set_obj(env, &mut dict, &value_key, values[i]); } obj.set_property(js_key, dict).unwrap(); return; } if cf_type == unsafe { CFBooleanGetTypeID() } { let value = value as CFBooleanRef; let value = unsafe { value == kCFBooleanTrue }; let value = env.get_boolean(value).unwrap(); obj.set_property(js_key, value).unwrap(); return; } if cf_type == unsafe { CFNumberGetTypeID() } { let value = value as CFNumberRef; let number_type = unsafe { CFNumberGetType(value) }; if number_type == kCFNumberSInt64Type { let mut num: i64 = 100; let number_ptr: *mut i64 = &mut num; unsafe { CFNumberGetValue(value, kCFNumberSInt64Type, number_ptr as *mut c_void); } let number = unsafe { *number_ptr }; obj.set_property(js_key, env.create_int64(number).unwrap()) .unwrap(); return; } } if cf_type == unsafe { CFDataGetTypeID() } { let value = value as CFDataRef; let ptr = unsafe { CFDataGetBytePtr(value) }; let length = unsafe { CFDataGetLength(value) }; let slice = unsafe { std::slice::from_raw_parts(ptr, length as usize) }; obj.set_property( js_key, env.create_arraybuffer_with_data(slice.to_vec()) .unwrap() .into_raw(), ) .unwrap() } } fn get_keys_and_values( dict_ref: CFDictionaryRef, length: usize, ) -> (Vec<*const c_void>, Vec<*const c_void>) { let mut keys = Vec::with_capacity(length); let mut values = Vec::with_capacity(length); unsafe { CFDictionaryGetKeysAndValues(dict_ref, keys.as_mut_ptr(), values.as_mut_ptr()); keys.set_len(length); values.set_len(length); } (keys, values) }
use core_foundation::base::{ kCFAllocatorDefault, Boolean, CFGetTypeID, CFIndex, CFRange, ToVoid, }; use core_foundation::boolean::{kCFBooleanTrue, CFBooleanGetTypeID, CFBooleanRef}; use core_foundation::data::{ CFDataCreate, CFDataGetBytePtr, CFDataGetLength, CFDataGetTypeID, CFDataRef, }; use core_foundation::dictionary::{ kCFTypeDictionaryKeyCallBacks, kCFTypeDictionaryValueCallBacks, CFDictionaryAddValue, CFDictionaryCreateMutable, CFDictionaryGetCount, CFDictionaryGetKeysAndValues, CFDictionaryGetTypeID, CFDictionaryRef, CFMutableDictionaryRef, }; use core_foundation::number::{ kCFNumberSInt64Type, CFNumber, CFNumberGetType, CFNumberGetTypeID, CFNumberGetValue, CFNumberRef, }; use core_foundation::string::{ kCFStringEncodingUTF8, CFString, CFStringGetBytes, CFStringGetCStringPtr, CFStringGetLength, CFStringGetTypeID, CFStringRef, }; use libc::c_void; use napi::{Env, JsBoolean, JsFunction, JsNumber, JsObject, JsString, JsUnknown, ValueType}; pub fn set_cf_dict( dict_ref: CFMutableDictionaryRef, key: *const c_void, unknown: JsUnknown, env: &Env, ) { let object_type = unknown.get_type().unwrap(); if object_type == ValueType::String { let cf_string = CFString::new( unknown .coerce_to_string() .unwrap() .into_utf8() .unwrap() .as_str() .unwrap(), ); unsafe { CFDictionaryAddValue(dict_ref, key, cf_string.to_void()); } return; }; if object_type == ValueType
return; } if object_type == ValueType::Number { let value = unknown.coerce_to_number().unwrap(); let cf_number = to_cf_number(value, env); unsafe { CFDictionaryAddValue(dict_ref, key, cf_number.to_void()); } } } fn to_cf_number(value: JsNumber, env: &Env) -> CFNumber { let number_object = env .get_global() .unwrap() .get_property::<JsString, JsFunction>(env.create_string("Number").unwrap()) .unwrap() .coerce_to_object() .unwrap(); let is_integer_fn = number_object .get_property::<JsString, JsFunction>(env.create_string("isInteger").unwrap()) .unwrap(); let is_integer = unsafe { is_integer_fn .call(None, &[value]) .unwrap() .cast::<JsBoolean>() .get_value() .unwrap() }; if is_integer { CFNumber::from(value.get_int32().unwrap()) } else { CFNumber::from(value.get_double().unwrap()) } } pub fn to_cf_dictionary(object: JsObject, env: &Env) -> CFMutableDictionaryRef { let properties = object.get_property_names().unwrap(); let length = properties.get_array_length_unchecked().unwrap(); let dict_ref = unsafe { CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks, ) }; for i in 0..length { let key = properties.get_element::<JsString>(i).unwrap(); let value = object.get_property::<JsString, JsUnknown>(key).unwrap(); let ns_key = CFString::new(key.into_utf8().unwrap().as_str().unwrap()); set_cf_dict(dict_ref, ns_key.to_void(), value, env); } dict_ref } fn to_string(string_ref: CFStringRef) -> String { unsafe { let char_ptr = CFStringGetCStringPtr(string_ref, kCFStringEncodingUTF8); if !char_ptr.is_null() { let c_str = std::ffi::CStr::from_ptr(char_ptr); return String::from(c_str.to_str().unwrap()); } let char_len = CFStringGetLength(string_ref); let mut bytes_required: CFIndex = 0; CFStringGetBytes( string_ref, CFRange { location: 0, length: char_len, }, kCFStringEncodingUTF8, 0, false as Boolean, std::ptr::null_mut(), 0, &mut bytes_required, ); let mut buffer = vec![b'\x00'; bytes_required as usize]; let mut bytes_used: CFIndex = 0; CFStringGetBytes( string_ref, CFRange { location: 0, length: char_len, }, kCFStringEncodingUTF8, 0, false as Boolean, buffer.as_mut_ptr(), buffer.len() as CFIndex, &mut bytes_used, ); return String::from_utf8_unchecked(buffer); } } pub fn from_object(env: &Env, dict_ref: CFDictionaryRef) -> JsObject { let length = unsafe { CFDictionaryGetCount(dict_ref) as usize }; let (keys, values) = get_keys_and_values(dict_ref, length); let mut obj = env.create_object().unwrap(); for i in 0..length { let key = to_string(keys[i] as CFStringRef); let value = values[i]; set_obj(env, &mut obj, &key, value); } obj } fn set_obj(env: &Env, obj: &mut JsObject, key: &str, value: *const c_void) { let cf_type = unsafe { CFGetTypeID(value) }; let js_key = env.create_string(key).unwrap(); if cf_type == unsafe { CFStringGetTypeID() } { let value = to_string(value as CFStringRef); let value = env.create_string(&value).unwrap(); obj.set_property(js_key, value).unwrap(); return; } if cf_type == unsafe { CFDictionaryGetTypeID() } { let value = value as CFDictionaryRef; let length = unsafe { CFDictionaryGetCount(value) as usize }; let (keys, values) = get_keys_and_values(value, length); let mut dict = env.create_object().unwrap(); for i in 0..length { let value_key = to_string(keys[i] as CFStringRef); set_obj(env, &mut dict, &value_key, values[i]); } obj.set_property(js_key, dict).unwrap(); return; } if cf_type == unsafe { CFBooleanGetTypeID() } { let value = value as CFBooleanRef; let value = unsafe { value == kCFBooleanTrue }; let value = env.get_boolean(value).unwrap(); obj.set_property(js_key, value).unwrap(); return; } if cf_type == unsafe { CFNumberGetTypeID() } { let value = value as CFNumberRef; let number_type = unsafe { CFNumberGetType(value) }; if number_type == kCFNumberSInt64Type { let mut num: i64 = 100; let number_ptr: *mut i64 = &mut num; unsafe { CFNumberGetValue(value, kCFNumberSInt64Type, number_ptr as *mut c_void); } let number = unsafe { *number_ptr }; obj.set_property(js_key, env.create_int64(number).unwrap()) .unwrap(); return; } } if cf_type == unsafe { CFDataGetTypeID() } { let value = value as CFDataRef; let ptr = unsafe { CFDataGetBytePtr(value) }; let length = unsafe { CFDataGetLength(value) }; let slice = unsafe { std::slice::from_raw_parts(ptr, length as usize) }; obj.set_property( js_key, env.create_arraybuffer_with_data(slice.to_vec()) .unwrap() .into_raw(), ) .unwrap() } } fn get_keys_and_values( dict_ref: CFDictionaryRef, length: usize, ) -> (Vec<*const c_void>, Vec<*const c_void>) { let mut keys = Vec::with_capacity(length); let mut values = Vec::with_capacity(length); unsafe { CFDictionaryGetKeysAndValues(dict_ref, keys.as_mut_ptr(), values.as_mut_ptr()); keys.set_len(length); values.set_len(length); } (keys, values) }
::Object { if unknown.is_typedarray().unwrap() { let object = unknown.coerce_to_object().unwrap(); let properties = object.get_property_names().unwrap(); let length = properties.get_array_length_unchecked().unwrap(); let mut data: Vec<u8> = vec![]; for i in 0..length { let elem_value = object.get_element::<JsNumber>(i).unwrap(); let value = (elem_value.get_uint32().unwrap() & 0xff) as u8; data.push(value); } let cf_data = unsafe { CFDataCreate(kCFAllocatorDefault, data.as_mut_ptr(), data.len() as isize) }; unsafe { CFDictionaryAddValue(dict_ref, key, cf_data.to_void()); } return; } let new_dict_ref = unsafe { CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks, ) }; let object = unknown.coerce_to_object().unwrap(); let properties = object.get_property_names().unwrap(); let length = properties.get_array_length_unchecked().unwrap(); for i in 0..length { let elem_key = properties.get_element::<JsString>(i).unwrap(); let value = object .get_property::<JsString, JsUnknown>(elem_key) .unwrap(); let ns_key = CFString::new(elem_key.into_utf8().unwrap().as_str().unwrap()); set_cf_dict(new_dict_ref, ns_key.to_void(), value, env); } unsafe { CFDictionaryAddValue(dict_ref, key, new_dict_ref as *const c_void); }
random
[ { "content": "pub fn receive_message(\n\n connection_ref: bridge::AMDServiceConnectionRef,\n\n) -> Result<CFDictionaryRef, i32> {\n\n unsafe {\n\n let response: CFDictionaryRef = std::ptr::null_mut();\n\n let code = bridge::AMDServiceConnectionReceiveMessage(\n\n connection_ref,\n...
Rust
rootfm-core/src/envelope.rs
Kintaro/rootfm
0c535d8c108a94bae144d6d146778f93bb4626e4
use crate::{MINIMUM_LEVEL, SAMPLE_RATE}; use libm::{fmaxf, logf}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum State { Start, Delay, Attack, Hold, Decay, Sustain, Release, Off, } impl Default for State { fn default() -> State { State::Start } } impl State { fn next(&self) -> State { match self { State::Start => State::Delay, State::Delay => State::Attack, State::Attack => State::Hold, State::Hold => State::Decay, State::Decay => State::Sustain, State::Sustain => State::Release, State::Release => State::Off, State::Off => State::Off, } } } #[derive(Copy, Clone, Debug)] pub struct EnvelopeSettings { delay: f32, attack: f32, hold: f32, decay: f32, sustain: f32, release: f32, } impl EnvelopeSettings { pub const fn new( delay: f32, attack: f32, hold: f32, decay: f32, sustain: f32, release: f32, ) -> EnvelopeSettings { EnvelopeSettings { delay, attack, hold, decay, sustain, release, } } } impl EnvelopeSettings { fn value_for_state(&self, state: State) -> f32 { match state { State::Start => 0.0, State::Delay => self.delay, State::Attack => self.attack, State::Hold => self.hold, State::Decay => self.decay, State::Sustain => self.sustain, State::Release => self.release, State::Off => 0.0, } } } #[derive(Copy, Clone, Debug)] pub struct Envelope { state: State, current_level: f32, multiplier: f32, current_sample_index: f32, next_state_sample_index: f32, } impl Envelope { pub const fn new() -> Envelope { Envelope { state: State::Start, current_level: MINIMUM_LEVEL, multiplier: 1.0, current_sample_index: 0.0, next_state_sample_index: 0.0, } } pub const fn output_level(&self) -> f32 { self.current_level } pub fn is_finished(&self) -> bool { self.state == State::Off } pub fn compute(&mut self, settings: &EnvelopeSettings) -> f32 { if self.state == State::Off || self.state == State::Sustain { return self.current_level; } if self.current_sample_index >= self.next_state_sample_index { self.enter_state(settings, self.state.next()); } self.current_level *= self.multiplier; self.current_sample_index += 1.0; self.current_level } pub fn enter_state(&mut self, settings: &EnvelopeSettings, state: State) { let next_sample_index = if state == State::Off || state == State::Sustain { 0.0 } else { settings.value_for_state(state) * SAMPLE_RATE }; let (current_level, multiplier) = match state { State::Off => (0.0, 1.0), State::Start => (MINIMUM_LEVEL, 1.0), State::Delay => (MINIMUM_LEVEL, 1.0), State::Attack => ( MINIMUM_LEVEL, Envelope::multiplier(MINIMUM_LEVEL, 1.0, next_sample_index), ), State::Hold => (1.0, 1.0), State::Decay => ( 1.0, Envelope::multiplier( 1.0, fmaxf(MINIMUM_LEVEL, settings.value_for_state(State::Sustain)), next_sample_index, ), ), State::Sustain => (settings.value_for_state(State::Sustain), 1.0), State::Release => ( self.current_level, Envelope::multiplier(self.current_level, MINIMUM_LEVEL, next_sample_index), ), }; self.state = state; self.current_level = current_level; self.multiplier = multiplier; self.current_sample_index = 0.0; self.next_state_sample_index = next_sample_index; } fn multiplier(start_level: f32, end_level: f32, samples: f32) -> f32 { 1.0 + (logf(end_level) - logf(fmaxf(start_level, MINIMUM_LEVEL))) / samples } }
use crate::{MINIMUM_LEVEL, SAMPLE_RATE}; use libm::{fmaxf, logf}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum State { Start, Delay, Attack, Hold, Decay, Sustain, Release, Off, } impl Default for State { fn default() -> State { State::Start } } impl State { fn next(&self) -> State { match self { State::Start => State::Delay, State::Delay => State::Attack, State::Attack => State::Hold, State::Hold => State::Decay, State::Decay => State::Sustain, State::Sustain => State::Release, State::Release => State::Off, State::Off => State::Off, } } } #[derive(Copy, Clone, Debug)] pub struct EnvelopeSettings { delay: f32, attack: f32, hold: f32, decay: f32, sustain: f32, release: f32, } impl EnvelopeSettings {
} impl EnvelopeSettings { fn value_for_state(&self, state: State) -> f32 { match state { State::Start => 0.0, State::Delay => self.delay, State::Attack => self.attack, State::Hold => self.hold, State::Decay => self.decay, State::Sustain => self.sustain, State::Release => self.release, State::Off => 0.0, } } } #[derive(Copy, Clone, Debug)] pub struct Envelope { state: State, current_level: f32, multiplier: f32, current_sample_index: f32, next_state_sample_index: f32, } impl Envelope { pub const fn new() -> Envelope { Envelope { state: State::Start, current_level: MINIMUM_LEVEL, multiplier: 1.0, current_sample_index: 0.0, next_state_sample_index: 0.0, } } pub const fn output_level(&self) -> f32 { self.current_level } pub fn is_finished(&self) -> bool { self.state == State::Off } pub fn compute(&mut self, settings: &EnvelopeSettings) -> f32 { if self.state == State::Off || self.state == State::Sustain { return self.current_level; } if self.current_sample_index >= self.next_state_sample_index { self.enter_state(settings, self.state.next()); } self.current_level *= self.multiplier; self.current_sample_index += 1.0; self.current_level } pub fn enter_state(&mut self, settings: &EnvelopeSettings, state: State) { let next_sample_index = if state == State::Off || state == State::Sustain { 0.0 } else { settings.value_for_state(state) * SAMPLE_RATE }; let (current_level, multiplier) = match state { State::Off => (0.0, 1.0), State::Start => (MINIMUM_LEVEL, 1.0), State::Delay => (MINIMUM_LEVEL, 1.0), State::Attack => ( MINIMUM_LEVEL, Envelope::multiplier(MINIMUM_LEVEL, 1.0, next_sample_index), ), State::Hold => (1.0, 1.0), State::Decay => ( 1.0, Envelope::multiplier( 1.0, fmaxf(MINIMUM_LEVEL, settings.value_for_state(State::Sustain)), next_sample_index, ), ), State::Sustain => (settings.value_for_state(State::Sustain), 1.0), State::Release => ( self.current_level, Envelope::multiplier(self.current_level, MINIMUM_LEVEL, next_sample_index), ), }; self.state = state; self.current_level = current_level; self.multiplier = multiplier; self.current_sample_index = 0.0; self.next_state_sample_index = next_sample_index; } fn multiplier(start_level: f32, end_level: f32, samples: f32) -> f32 { 1.0 + (logf(end_level) - logf(fmaxf(start_level, MINIMUM_LEVEL))) / samples } }
pub const fn new( delay: f32, attack: f32, hold: f32, decay: f32, sustain: f32, release: f32, ) -> EnvelopeSettings { EnvelopeSettings { delay, attack, hold, decay, sustain, release, } }
function_block-full_function
[ { "content": "fn number_samples_from_ms(delay: f32) -> f32 {\n\n SAMPLE_RATE * delay * 0.001\n\n}\n\n\n\nimpl DelayLine {\n\n pub fn new(delay: f32) -> DelayLine {\n\n let samples = delay as f32 * 0.001 * SAMPLE_RATE;\n\n let fraction = floorf(number_samples_from_ms(delay) - samples);\n\n ...
Rust
models/src/input.rs
alsacoin/alsacoin
389ae5aef90011414f545fa8575b5137731adc55
use crate::account::Account; use crate::address::Address; use crate::error::Error; use crate::result::Result; use crate::transaction::Transaction; use crypto::ecc::ed25519::{KeyPair, PublicKey, SecretKey, Signature}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; #[derive(Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default, Serialize, Deserialize)] pub struct Input { pub account: Account, pub signatures: BTreeMap<PublicKey, Signature>, pub amount: u64, pub distance: u64, } impl Input { pub fn new(account: &Account, distance: u64, amount: u64) -> Result<Input> { account.validate()?; if account.amount < amount { let err = Error::InvalidAmount; return Err(err); } if distance == 0 { let err = Error::InvalidDistance; return Err(err); } let mut input = Input::default(); input.account = account.to_owned(); input.amount = amount; input.distance = distance; Ok(input) } pub fn address(&self) -> Address { self.account.address() } pub fn from_transaction(account: &Account, transaction: &Transaction) -> Result<Input> { account.validate()?; transaction.validate()?; if account.stage != transaction.stage { let err = Error::InvalidStage; return Err(err); } if account.time > transaction.time { let err = Error::InvalidTimestamp; return Err(err); } let output = transaction.get_output(&account.address())?; let distance = transaction.distance; let amount = output.amount; let mut account = account.clone(); account.locktime = transaction.locktime; account.amount = amount; account.transaction_id = Some(transaction.id); account.counter += 1; Input::new(&account, distance, amount) } pub fn signature_message(&self, seed: &[u8]) -> Result<Vec<u8>> { let mut clone = self.clone(); clone.signatures = BTreeMap::default(); let mut msg = Vec::new(); msg.extend_from_slice(seed); msg.extend_from_slice(&clone.to_bytes()?); Ok(msg) } pub fn calc_signature(&self, secret_key: &SecretKey, seed: &[u8]) -> Result<Signature> { let kp = KeyPair::from_secret(secret_key)?; if !self.account.signers.lookup(&kp.public_key) { let err = Error::NotFound; return Err(err); } let msg = self.signature_message(seed)?; kp.sign(&msg).map_err(|e| e.into()) } pub fn sign(&mut self, secret_key: &SecretKey, msg: &[u8]) -> Result<()> { let public_key = secret_key.to_public(); if !self.account.signers.lookup(&public_key) { let err = Error::NotFound; return Err(err); } let signature = self.calc_signature(secret_key, msg)?; self.signatures.insert(public_key, signature); Ok(()) } pub fn verify_signature(&self, public_key: &PublicKey, seed: &[u8]) -> Result<()> { if !self.account.signers.lookup(&public_key) { let err = Error::NotFound; return Err(err); } let signature = self.signatures.get(public_key).unwrap(); let msg = self.signature_message(seed)?; public_key.verify(&signature, &msg).map_err(|e| e.into()) } pub fn is_signed(&self) -> bool { let signatures_len = self.signatures.len(); let pks_len = self .signatures .keys() .filter(|pk| self.account.signers.lookup(&pk)) .count(); signatures_len != 0 && pks_len == signatures_len } pub fn is_fully_signed(&self) -> Result<bool> { let res = self.is_signed() && self.signatures_weight()? >= self.account.signers.threshold; Ok(res) } pub fn validate(&self) -> Result<()> { self.account.validate()?; if self.account.amount < self.amount { let err = Error::InvalidAmount; return Err(err); } if self.distance == 0 { let err = Error::InvalidDistance; return Err(err); } for pk in self.signatures.keys() { if !self.account.signers.lookup(&pk) { let err = Error::InvalidPublicKey; return Err(err); } } Ok(()) } pub fn verify_signatures(&self, seed: &[u8]) -> Result<()> { if !self.is_signed() { let err = Error::NotSigned; return Err(err); } for pk in self.signatures.keys() { if !self.account.signers.lookup(&pk) { let err = Error::InvalidPublicKey; return Err(err); } self.verify_signature(&pk, seed)?; } Ok(()) } pub fn verify_fully_signed(&self, seed: &[u8]) -> Result<()> { if !self.is_fully_signed()? { let err = Error::NotFullySigned; return Err(err); } self.verify_signatures(seed) } pub fn signatures_weight(&self) -> Result<u64> { self.validate()?; let mut sigs_weight = 0; for pk in self.signatures.keys() { let signer = self.account.signers.get(&pk)?; sigs_weight += signer.weight; } Ok(sigs_weight) } pub fn to_bytes(&self) -> Result<Vec<u8>> { serde_cbor::to_vec(self).map_err(|e| e.into()) } pub fn from_bytes(b: &[u8]) -> Result<Input> { serde_cbor::from_slice(b).map_err(|e| e.into()) } pub fn to_json(&self) -> Result<String> { serde_json::to_string(self).map_err(|e| e.into()) } pub fn from_json(s: &str) -> Result<Input> { serde_json::from_str(s).map_err(|e| e.into()) } } #[test] fn test_input_new() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let res = Input::new(&account, distance, amount); assert!(res.is_ok()); let input = res.unwrap(); let res = input.validate(); assert!(res.is_ok()); } #[test] fn test_input_sign() { use crate::signer::Signer; use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); let secret_key_a = SecretKey::random().unwrap(); let public_key_a = secret_key_a.to_public(); let secret_key_b = SecretKey::random().unwrap(); let public_key_b = secret_key_b.to_public(); let msg_len = 1000; let msg = Random::bytes(msg_len).unwrap(); let weight = 10; let signer_a = Signer { public_key: public_key_a, weight, }; let signer_b = Signer { public_key: public_key_b, weight, }; let mut signers = Signers::new().unwrap(); signers.threshold = 20; signers.add(&signer_a).unwrap(); signers.add(&signer_b).unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let mut input = Input::new(&account, distance, amount).unwrap(); let is_signed = input.is_signed(); assert!(!is_signed); let res = input.sign(&secret_key_a, &msg); assert!(res.is_ok()); let is_signed = input.is_signed(); assert!(is_signed); let res = input.verify_signature(&public_key_a, &msg); assert!(res.is_ok()); let res = input.signatures_weight(); assert!(res.is_ok()); let sigs_weight = res.unwrap(); assert_eq!(sigs_weight, signer_a.weight); let res = input.is_fully_signed(); assert!(res.is_ok()); assert!(!res.unwrap()); let res = input.sign(&secret_key_b, &msg); assert!(res.is_ok()); let sigs_weight = input.signatures_weight().unwrap(); assert_eq!(sigs_weight, input.account.signers.threshold); let res = input.is_fully_signed(); assert!(res.is_ok()); assert!(res.unwrap()); } #[test] fn test_input_validate() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let mut input = Input::new(&account, distance, amount).unwrap(); let res = input.validate(); assert!(res.is_ok()); input.distance = 0; let res = input.validate(); assert!(res.is_err()); input.distance += 1; let mut invalid_public_key = PublicKey::random().unwrap(); while input.account.signers.lookup(&invalid_public_key) { invalid_public_key = PublicKey::random().unwrap(); } let invalid_signature = Signature::default(); input .signatures .insert(invalid_public_key, invalid_signature); let res = input.validate(); assert!(res.is_err()); } #[test] fn test_input_serialize_bytes() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); for _ in 0..10 { let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let input_a = Input::new(&account, distance, amount).unwrap(); let res = input_a.to_bytes(); assert!(res.is_ok()); let cbor = res.unwrap(); let res = Input::from_bytes(&cbor); assert!(res.is_ok()); let input_b = res.unwrap(); assert_eq!(input_a, input_b) } } #[test] fn test_input_serialize_json() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); for _ in 0..10 { let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let input_a = Input::new(&account, distance, amount).unwrap(); let res = input_a.to_json(); assert!(res.is_ok()); let json = res.unwrap(); let res = Input::from_json(&json); assert!(res.is_ok()); let input_b = res.unwrap(); assert_eq!(input_a, input_b) } }
use crate::account::Account; use crate::address::Address; use crate::error::Error; use crate::result::Result; use crate::transaction::Transaction; use crypto::ecc::ed25519::{KeyPair, PublicKey, SecretKey, Signature}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; #[derive(Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default, Serialize, Deserialize)] pub struct Input { pub account: Account, pub signatures: BTreeMap<PublicKey, Signature>, pub amount: u64, pub distance: u64, } impl Input { pub fn new(account: &Account, distance: u64, amount: u64) -> Result<Input> { account.validate()?; if account.amount < amount { let err = Error::InvalidAmount; return Err(err); } if distance == 0 { let err = Error::InvalidDistance; return Err(err); } let mut input = Input::default(); input.account = account.to_owned(); input.amount = amount; input.distance = distance; Ok(input) } pub fn address(&self) -> Address { self.account.address() } pub fn from_transaction(account: &Account, transaction: &Transaction) -> Result<Input> { account.validate()?; transaction.validate()?; if account.stage != transaction.stage { let err = Error::InvalidStage; return Err(err); } if account.time > transaction.time { let err = Error::InvalidTimestamp; return Err(err); } let output = transaction.get_output(&account.address())?; let distance = transaction.distance; let amount = output.amount; let mut account = account.clone(); account.locktime = transaction.locktime; account.amount = amount; account.transaction_id = Some(transaction.id); account.counter += 1; Input::new(&account, distance, amount) } pub fn signature_message(&self, seed: &[u8]) -> Result<Vec<u8>> { let mut clone = self.clone(); clone.signatures = BTreeMap::default(); let mut msg = Vec::new(); msg.extend_from_slice(seed); msg.extend_from_slice(&clone.to_bytes()?); Ok(msg) }
pub fn sign(&mut self, secret_key: &SecretKey, msg: &[u8]) -> Result<()> { let public_key = secret_key.to_public(); if !self.account.signers.lookup(&public_key) { let err = Error::NotFound; return Err(err); } let signature = self.calc_signature(secret_key, msg)?; self.signatures.insert(public_key, signature); Ok(()) } pub fn verify_signature(&self, public_key: &PublicKey, seed: &[u8]) -> Result<()> { if !self.account.signers.lookup(&public_key) { let err = Error::NotFound; return Err(err); } let signature = self.signatures.get(public_key).unwrap(); let msg = self.signature_message(seed)?; public_key.verify(&signature, &msg).map_err(|e| e.into()) } pub fn is_signed(&self) -> bool { let signatures_len = self.signatures.len(); let pks_len = self .signatures .keys() .filter(|pk| self.account.signers.lookup(&pk)) .count(); signatures_len != 0 && pks_len == signatures_len } pub fn is_fully_signed(&self) -> Result<bool> { let res = self.is_signed() && self.signatures_weight()? >= self.account.signers.threshold; Ok(res) } pub fn validate(&self) -> Result<()> { self.account.validate()?; if self.account.amount < self.amount { let err = Error::InvalidAmount; return Err(err); } if self.distance == 0 { let err = Error::InvalidDistance; return Err(err); } for pk in self.signatures.keys() { if !self.account.signers.lookup(&pk) { let err = Error::InvalidPublicKey; return Err(err); } } Ok(()) } pub fn verify_signatures(&self, seed: &[u8]) -> Result<()> { if !self.is_signed() { let err = Error::NotSigned; return Err(err); } for pk in self.signatures.keys() { if !self.account.signers.lookup(&pk) { let err = Error::InvalidPublicKey; return Err(err); } self.verify_signature(&pk, seed)?; } Ok(()) } pub fn verify_fully_signed(&self, seed: &[u8]) -> Result<()> { if !self.is_fully_signed()? { let err = Error::NotFullySigned; return Err(err); } self.verify_signatures(seed) } pub fn signatures_weight(&self) -> Result<u64> { self.validate()?; let mut sigs_weight = 0; for pk in self.signatures.keys() { let signer = self.account.signers.get(&pk)?; sigs_weight += signer.weight; } Ok(sigs_weight) } pub fn to_bytes(&self) -> Result<Vec<u8>> { serde_cbor::to_vec(self).map_err(|e| e.into()) } pub fn from_bytes(b: &[u8]) -> Result<Input> { serde_cbor::from_slice(b).map_err(|e| e.into()) } pub fn to_json(&self) -> Result<String> { serde_json::to_string(self).map_err(|e| e.into()) } pub fn from_json(s: &str) -> Result<Input> { serde_json::from_str(s).map_err(|e| e.into()) } } #[test] fn test_input_new() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let res = Input::new(&account, distance, amount); assert!(res.is_ok()); let input = res.unwrap(); let res = input.validate(); assert!(res.is_ok()); } #[test] fn test_input_sign() { use crate::signer::Signer; use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); let secret_key_a = SecretKey::random().unwrap(); let public_key_a = secret_key_a.to_public(); let secret_key_b = SecretKey::random().unwrap(); let public_key_b = secret_key_b.to_public(); let msg_len = 1000; let msg = Random::bytes(msg_len).unwrap(); let weight = 10; let signer_a = Signer { public_key: public_key_a, weight, }; let signer_b = Signer { public_key: public_key_b, weight, }; let mut signers = Signers::new().unwrap(); signers.threshold = 20; signers.add(&signer_a).unwrap(); signers.add(&signer_b).unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let mut input = Input::new(&account, distance, amount).unwrap(); let is_signed = input.is_signed(); assert!(!is_signed); let res = input.sign(&secret_key_a, &msg); assert!(res.is_ok()); let is_signed = input.is_signed(); assert!(is_signed); let res = input.verify_signature(&public_key_a, &msg); assert!(res.is_ok()); let res = input.signatures_weight(); assert!(res.is_ok()); let sigs_weight = res.unwrap(); assert_eq!(sigs_weight, signer_a.weight); let res = input.is_fully_signed(); assert!(res.is_ok()); assert!(!res.unwrap()); let res = input.sign(&secret_key_b, &msg); assert!(res.is_ok()); let sigs_weight = input.signatures_weight().unwrap(); assert_eq!(sigs_weight, input.account.signers.threshold); let res = input.is_fully_signed(); assert!(res.is_ok()); assert!(res.unwrap()); } #[test] fn test_input_validate() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let mut input = Input::new(&account, distance, amount).unwrap(); let res = input.validate(); assert!(res.is_ok()); input.distance = 0; let res = input.validate(); assert!(res.is_err()); input.distance += 1; let mut invalid_public_key = PublicKey::random().unwrap(); while input.account.signers.lookup(&invalid_public_key) { invalid_public_key = PublicKey::random().unwrap(); } let invalid_signature = Signature::default(); input .signatures .insert(invalid_public_key, invalid_signature); let res = input.validate(); assert!(res.is_err()); } #[test] fn test_input_serialize_bytes() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); for _ in 0..10 { let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let input_a = Input::new(&account, distance, amount).unwrap(); let res = input_a.to_bytes(); assert!(res.is_ok()); let cbor = res.unwrap(); let res = Input::from_bytes(&cbor); assert!(res.is_ok()); let input_b = res.unwrap(); assert_eq!(input_a, input_b) } } #[test] fn test_input_serialize_json() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); for _ in 0..10 { let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let input_a = Input::new(&account, distance, amount).unwrap(); let res = input_a.to_json(); assert!(res.is_ok()); let json = res.unwrap(); let res = Input::from_json(&json); assert!(res.is_ok()); let input_b = res.unwrap(); assert_eq!(input_a, input_b) } }
pub fn calc_signature(&self, secret_key: &SecretKey, seed: &[u8]) -> Result<Signature> { let kp = KeyPair::from_secret(secret_key)?; if !self.account.signers.lookup(&kp.public_key) { let err = Error::NotFound; return Err(err); } let msg = self.signature_message(seed)?; kp.sign(&msg).map_err(|e| e.into()) }
function_block-full_function
[ { "content": "/// `address_to_bytes` converts a SocketAddrV4 to a vector of bytes.\n\npub fn address_to_bytes(address: &SocketAddrV4) -> Result<Vec<u8>> {\n\n let mut buf = Vec::new();\n\n\n\n for n in &address.ip().octets() {\n\n buf.write_u8(*n)?;\n\n }\n\n\n\n buf.write_u16::<BigEndian>(ad...
Rust
src/test_md.rs
puru1761/kcapi-sys
ef3a7e91e6fb5e355fb41e75464322dd13b69349
/* * $Id$ * * Copyright (c) 2021, Purushottam A. Kulkarni. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and * or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE * */ #[cfg(test)] mod tests { use std::convert::TryInto; use std::ffi::CString; use crate::{ kcapi_handle, kcapi_md_digest, kcapi_md_digestsize, kcapi_md_hmac_sha1, kcapi_md_hmac_sha224, kcapi_md_hmac_sha256, kcapi_md_hmac_sha384, kcapi_md_hmac_sha512, kcapi_md_init, kcapi_md_setkey, kcapi_md_sha1, kcapi_md_sha224, kcapi_md_sha256, kcapi_md_sha384, kcapi_md_sha512, }; const SIZE_SHA1: usize = 20; const SIZE_SHA224: usize = 28; const SIZE_SHA256: usize = 32; const SIZE_SHA384: usize = 48; const SIZE_SHA512: usize = 64; #[test] fn test_md_init() { let ret: i32; let alg = CString::new("sha1").expect("Failed to convert CString"); unsafe { let mut handle = Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle; ret = kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0); } assert_eq!(ret, 0); } #[test] fn test_md_digest() { let inp = [0x41u8; 16]; let mut out = [0u8; SIZE_SHA256]; let alg = std::ffi::CString::new("sha256").expect("Failed to convert to CString"); let out_exp = [ 0x99, 0x12, 0x4, 0xfb, 0xa2, 0xb6, 0x21, 0x6d, 0x47, 0x62, 0x82, 0xd3, 0x75, 0xab, 0x88, 0xd2, 0xe, 0x61, 0x8, 0xd1, 0x9, 0xae, 0xcd, 0xed, 0x97, 0xef, 0x42, 0x4d, 0xdd, 0x11, 0x47, 0x6, ]; let mut ret: i64; unsafe { let mut handle = Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle; ret = (kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0)) .try_into() .expect("Failed to convert i32 to i64"); assert_eq!(ret, 0); ret = (kcapi_md_digestsize(handle)) .try_into() .expect("Failed to convert i32 into i64"); assert_eq!(ret, SIZE_SHA256 as i64); ret = kcapi_md_digest( handle, inp.as_ptr(), inp.len() as u64, out.as_mut_ptr(), out.len() as u64, ); assert_eq!(ret, SIZE_SHA256 as i64); } assert_eq!(out_exp, out); } #[test] fn test_md_keyed_digest() { let inp = [0x41u8; 16]; let mut out = [0u8; SIZE_SHA256]; let key = [0u8; 16]; let alg = std::ffi::CString::new("hmac(sha256)").expect("Failed to convert to CString"); let out_exp = [ 0x4a, 0x81, 0xd6, 0x13, 0xb0, 0xe, 0x91, 0x9e, 0x8a, 0xd9, 0x63, 0x78, 0x88, 0xe6, 0xa4, 0xfe, 0x8, 0x22, 0x4a, 0xb6, 0x48, 0x4b, 0xa, 0x37, 0x47, 0xa6, 0xa6, 0x62, 0xb6, 0xa2, 0x99, 0xd, ]; let mut ret: i64; unsafe { let mut handle = Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle; ret = (kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0)) .try_into() .expect("Failed to convert i32 to i64"); assert_eq!(ret, 0); ret = (kcapi_md_digestsize(handle)) .try_into() .expect("Failed to convert i32 into i64"); assert_eq!(ret, SIZE_SHA256 as i64); ret = (kcapi_md_setkey(handle, key.as_ptr(), key.len() as u32)) .try_into() .expect("Failed to convert i32 to i64"); assert_eq!(ret, 0); ret = kcapi_md_digest( handle, inp.as_ptr(), inp.len() as u64, out.as_mut_ptr(), out.len() as u64, ); assert_eq!(ret, SIZE_SHA256 as i64); } assert_eq!(out_exp, out); } #[test] fn test_sha1() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA1]; let out_exp = [ 0x19, 0xb1, 0x92, 0x8d, 0x58, 0xa2, 0x3, 0xd, 0x8, 0x2, 0x3f, 0x3d, 0x70, 0x54, 0x51, 0x6d, 0xbc, 0x18, 0x6f, 0x20, ]; let ret: i64; unsafe { ret = kcapi_md_sha1( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA1 as i64); } #[test] fn test_sha224() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA224]; let out_exp = [ 0xcb, 0xa2, 0x25, 0xbd, 0x2d, 0xed, 0x28, 0xf5, 0xb9, 0xb3, 0xfa, 0xee, 0x8e, 0xca, 0xed, 0x82, 0xba, 0x8, 0xd2, 0xbb, 0x5a, 0xee, 0x2c, 0x37, 0x40, 0xe7, 0xff, 0x8a, ]; let ret: i64; unsafe { ret = kcapi_md_sha224( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA224 as i64); } #[test] fn test_sha256() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA256]; let out_exp = [ 0x99, 0x12, 0x4, 0xfb, 0xa2, 0xb6, 0x21, 0x6d, 0x47, 0x62, 0x82, 0xd3, 0x75, 0xab, 0x88, 0xd2, 0xe, 0x61, 0x8, 0xd1, 0x9, 0xae, 0xcd, 0xed, 0x97, 0xef, 0x42, 0x4d, 0xdd, 0x11, 0x47, 0x6, ]; let ret: i64; unsafe { ret = kcapi_md_sha256( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA256 as i64); } #[test] fn test_sha384() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA384]; let out_exp = [ 0x62, 0x5e, 0x92, 0x3, 0x4, 0x7c, 0x52, 0xa1, 0xe2, 0x90, 0x18, 0x9b, 0xd1, 0x5a, 0xbf, 0x17, 0xe, 0xd8, 0x86, 0xa3, 0x31, 0x90, 0x80, 0x3e, 0x4, 0x40, 0x2f, 0x4d, 0x48, 0xb1, 0xf, 0xe0, 0x5a, 0xb1, 0x21, 0x97, 0xf9, 0xca, 0xc2, 0x53, 0x74, 0x9a, 0x5f, 0xde, 0x8, 0x22, 0xc7, 0x34, ]; let ret: i64; unsafe { ret = kcapi_md_sha384( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA384 as i64); } #[test] fn test_sha512() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA512]; let out_exp = [ 0x67, 0x3a, 0x88, 0x7f, 0xe1, 0x68, 0xc, 0x26, 0xd8, 0x1d, 0x46, 0xd2, 0x76, 0xe6, 0xb, 0x4d, 0xfd, 0x9c, 0x16, 0x60, 0x34, 0xe7, 0x2f, 0x69, 0xd6, 0x8a, 0x77, 0xf4, 0xb0, 0xf7, 0x41, 0x21, 0xd4, 0x4b, 0x79, 0x68, 0xde, 0x8f, 0x55, 0xba, 0x26, 0x15, 0xf6, 0xe7, 0x20, 0xa2, 0xc7, 0x43, 0x99, 0x9c, 0xbc, 0xc0, 0x7a, 0x4, 0x36, 0x6d, 0x9f, 0x36, 0x46, 0xbc, 0xbc, 0x11, 0x98, 0xce, ]; let ret: i64; unsafe { ret = kcapi_md_sha512( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA512 as i64); } #[test] fn test_hmac_sha1() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA1]; let out_exp = [ 0x41, 0x85, 0xf6, 0xa4, 0xc3, 0xab, 0x30, 0xf9, 0xa8, 0x5, 0x96, 0x45, 0x6f, 0x5d, 0x61, 0x18, 0xd4, 0xfe, 0xe0, 0xd6, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha1( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA1 as i64); } #[test] fn test_hmac_sha224() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA224]; let out_exp = [ 0x5d, 0x8c, 0x6c, 0x1f, 0xf2, 0x97, 0xbf, 0x59, 0x3f, 0x59, 0x1c, 0xf3, 0x4d, 0x3c, 0x96, 0x36, 0xde, 0x33, 0x11, 0x5f, 0xb1, 0x3e, 0xa5, 0x75, 0x8c, 0xfc, 0xdc, 0x6, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha224( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA224 as i64); } #[test] fn test_hmac_sha256() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA256]; let out_exp = [ 0x4a, 0x81, 0xd6, 0x13, 0xb0, 0xe, 0x91, 0x9e, 0x8a, 0xd9, 0x63, 0x78, 0x88, 0xe6, 0xa4, 0xfe, 0x8, 0x22, 0x4a, 0xb6, 0x48, 0x4b, 0xa, 0x37, 0x47, 0xa6, 0xa6, 0x62, 0xb6, 0xa2, 0x99, 0xd, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha256( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA256 as i64); } #[test] fn test_hmac_sha384() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA384]; let out_exp = [ 0x1b, 0xcc, 0x5, 0x6f, 0x74, 0xc9, 0x34, 0xce, 0x5f, 0xe, 0xc4, 0xf5, 0x45, 0x3d, 0x1c, 0xef, 0x7c, 0x1b, 0x8d, 0xae, 0xa7, 0x6d, 0xe7, 0xc7, 0x9e, 0x7e, 0xe, 0x68, 0x4e, 0x95, 0x6d, 0xd8, 0x52, 0x11, 0x20, 0xd, 0x99, 0x93, 0x63, 0x89, 0x4f, 0xfd, 0x37, 0xc, 0xdd, 0x27, 0x75, 0xc8, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha384( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA384 as i64); } #[test] fn test_hmac_sha512() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA512]; let out_exp = [ 0x44, 0xdb, 0xf1, 0xae, 0x7d, 0xcd, 0xc0, 0x5f, 0xa6, 0x9b, 0x30, 0x44, 0x99, 0xfa, 0x19, 0x82, 0x40, 0xb, 0x94, 0xc0, 0xe9, 0x9, 0xcb, 0xc5, 0xf5, 0x74, 0x66, 0x84, 0x45, 0x5b, 0x31, 0xf8, 0x8e, 0x94, 0x14, 0x8c, 0xe2, 0xa4, 0x7, 0xa7, 0x58, 0xd2, 0x14, 0x11, 0x85, 0x8b, 0xa4, 0x50, 0x4c, 0xaa, 0x2e, 0xa1, 0x70, 0xa3, 0x1b, 0xec, 0x87, 0xab, 0xb6, 0x54, 0xf4, 0xe9, 0xd, 0x48, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha512( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA512 as i64); } }
/* * $Id$ * * Copyright (c) 2021, Purushottam A. Kulkarni. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and * or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE * */ #[cfg(test)] mod tests { use std::convert::TryInto; use std::ffi::CString; use crate::{ kcapi_handle, kcapi_md_digest, kcapi_md_digestsize, kcapi_md_hmac_sha1, kcapi_md_hmac_sha224, kcapi_md_hmac_sha256, kcapi_md_hmac_sha384, kcapi_md_hmac_sha512, kcapi_md_init, kcapi_md_setkey, kcapi_md_sha1, kcapi_md_sha224, kcapi_md_sha256, kcapi_md_sha384, kcapi_md_sha512, }; const SIZE_SHA1: usize = 20; const SIZE_SHA224: usize = 28; const SIZE_SHA256: usize = 32; const SIZE_SHA384: usize = 48; const SIZE_SHA512: usize = 64; #[test] fn test_md_init() { let ret: i32; let alg = CString::new("sha1").expect("Failed to convert CString"); unsafe { let mut handle = Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle; ret = kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0); } assert_eq!(ret, 0); } #[test] fn test_md_digest() { let inp = [0x41u8; 16]; let mut out = [0u8; SIZE_SHA256]; let alg = std::ffi::CString::new("sha256").expect("Failed to convert to CString"); let out_exp = [ 0x99, 0x12, 0x4, 0xfb, 0xa2, 0xb6, 0x21, 0x6d, 0x47, 0x62, 0x82, 0xd3, 0x75, 0xab, 0x88, 0xd2, 0xe, 0x61, 0x8, 0xd1, 0x9, 0xae, 0xcd, 0xed, 0x97, 0xef, 0x42, 0x4d, 0xdd, 0x11, 0x47, 0x6, ]; let mut ret: i64; unsafe { let mut handle = Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle; ret = (kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0)) .try_into() .expect("Failed to convert i32 to i64"); assert_eq!(ret, 0); ret = (kcapi_md_digestsize(handle)) .try_into() .expect("Failed to convert i32 into i64"); assert_eq!(ret, SIZE_SHA256 as i64); ret = kcapi_md_digest( handle, inp.as_ptr(), inp.len() as u64, out.as_mut_ptr(), out.len() as u64, ); assert_eq!(ret, SIZE_SHA256 as i64); } assert_eq!(out_exp, out); } #[test] fn test_md_keyed_digest() { let inp = [0x41u8; 16]; let mut out = [0u8; SIZE_SHA256]; let key = [0u8; 16]; let alg = std::ffi::CString::new("hmac(sha256)").expect("Failed to convert to CString"); let out_exp = [ 0x4a, 0x81, 0xd6, 0x13, 0xb0, 0xe, 0x91, 0x9e, 0x8a, 0xd9, 0x63, 0x78, 0x88, 0xe6, 0xa4, 0xfe, 0x8, 0x22, 0x4a, 0xb6, 0x48, 0x4b, 0xa, 0x37, 0x47, 0xa6, 0xa6, 0x62, 0xb6, 0xa2, 0x99, 0xd, ]; let mut ret: i64; unsafe { let mut handle = Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle; ret = (kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0)) .try_into() .expect("Failed to convert i32 to i64"); assert_eq!(ret, 0); ret = (kcapi_md_digestsize(handle)) .try_into() .expect("Failed to convert i32 into i64"); assert_eq!(ret, SIZE_SHA256 as i64); ret = (kcapi_md_setkey(handle, key.as_ptr(), key.len() as u32)) .try_into() .expect("Failed to convert i32 to i64"); assert_eq!(ret, 0); ret = kcapi_md_digest( handle, inp.as_ptr(), inp.len() as u64, out.as_mut_ptr(), out.len() as u64, ); assert_eq!(ret, SIZE_SHA256 as i64); } assert_eq!(out_exp, out); } #[test] fn test_sha1() {
#[test] fn test_sha224() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA224]; let out_exp = [ 0xcb, 0xa2, 0x25, 0xbd, 0x2d, 0xed, 0x28, 0xf5, 0xb9, 0xb3, 0xfa, 0xee, 0x8e, 0xca, 0xed, 0x82, 0xba, 0x8, 0xd2, 0xbb, 0x5a, 0xee, 0x2c, 0x37, 0x40, 0xe7, 0xff, 0x8a, ]; let ret: i64; unsafe { ret = kcapi_md_sha224( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA224 as i64); } #[test] fn test_sha256() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA256]; let out_exp = [ 0x99, 0x12, 0x4, 0xfb, 0xa2, 0xb6, 0x21, 0x6d, 0x47, 0x62, 0x82, 0xd3, 0x75, 0xab, 0x88, 0xd2, 0xe, 0x61, 0x8, 0xd1, 0x9, 0xae, 0xcd, 0xed, 0x97, 0xef, 0x42, 0x4d, 0xdd, 0x11, 0x47, 0x6, ]; let ret: i64; unsafe { ret = kcapi_md_sha256( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA256 as i64); } #[test] fn test_sha384() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA384]; let out_exp = [ 0x62, 0x5e, 0x92, 0x3, 0x4, 0x7c, 0x52, 0xa1, 0xe2, 0x90, 0x18, 0x9b, 0xd1, 0x5a, 0xbf, 0x17, 0xe, 0xd8, 0x86, 0xa3, 0x31, 0x90, 0x80, 0x3e, 0x4, 0x40, 0x2f, 0x4d, 0x48, 0xb1, 0xf, 0xe0, 0x5a, 0xb1, 0x21, 0x97, 0xf9, 0xca, 0xc2, 0x53, 0x74, 0x9a, 0x5f, 0xde, 0x8, 0x22, 0xc7, 0x34, ]; let ret: i64; unsafe { ret = kcapi_md_sha384( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA384 as i64); } #[test] fn test_sha512() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA512]; let out_exp = [ 0x67, 0x3a, 0x88, 0x7f, 0xe1, 0x68, 0xc, 0x26, 0xd8, 0x1d, 0x46, 0xd2, 0x76, 0xe6, 0xb, 0x4d, 0xfd, 0x9c, 0x16, 0x60, 0x34, 0xe7, 0x2f, 0x69, 0xd6, 0x8a, 0x77, 0xf4, 0xb0, 0xf7, 0x41, 0x21, 0xd4, 0x4b, 0x79, 0x68, 0xde, 0x8f, 0x55, 0xba, 0x26, 0x15, 0xf6, 0xe7, 0x20, 0xa2, 0xc7, 0x43, 0x99, 0x9c, 0xbc, 0xc0, 0x7a, 0x4, 0x36, 0x6d, 0x9f, 0x36, 0x46, 0xbc, 0xbc, 0x11, 0x98, 0xce, ]; let ret: i64; unsafe { ret = kcapi_md_sha512( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA512 as i64); } #[test] fn test_hmac_sha1() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA1]; let out_exp = [ 0x41, 0x85, 0xf6, 0xa4, 0xc3, 0xab, 0x30, 0xf9, 0xa8, 0x5, 0x96, 0x45, 0x6f, 0x5d, 0x61, 0x18, 0xd4, 0xfe, 0xe0, 0xd6, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha1( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA1 as i64); } #[test] fn test_hmac_sha224() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA224]; let out_exp = [ 0x5d, 0x8c, 0x6c, 0x1f, 0xf2, 0x97, 0xbf, 0x59, 0x3f, 0x59, 0x1c, 0xf3, 0x4d, 0x3c, 0x96, 0x36, 0xde, 0x33, 0x11, 0x5f, 0xb1, 0x3e, 0xa5, 0x75, 0x8c, 0xfc, 0xdc, 0x6, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha224( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA224 as i64); } #[test] fn test_hmac_sha256() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA256]; let out_exp = [ 0x4a, 0x81, 0xd6, 0x13, 0xb0, 0xe, 0x91, 0x9e, 0x8a, 0xd9, 0x63, 0x78, 0x88, 0xe6, 0xa4, 0xfe, 0x8, 0x22, 0x4a, 0xb6, 0x48, 0x4b, 0xa, 0x37, 0x47, 0xa6, 0xa6, 0x62, 0xb6, 0xa2, 0x99, 0xd, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha256( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA256 as i64); } #[test] fn test_hmac_sha384() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA384]; let out_exp = [ 0x1b, 0xcc, 0x5, 0x6f, 0x74, 0xc9, 0x34, 0xce, 0x5f, 0xe, 0xc4, 0xf5, 0x45, 0x3d, 0x1c, 0xef, 0x7c, 0x1b, 0x8d, 0xae, 0xa7, 0x6d, 0xe7, 0xc7, 0x9e, 0x7e, 0xe, 0x68, 0x4e, 0x95, 0x6d, 0xd8, 0x52, 0x11, 0x20, 0xd, 0x99, 0x93, 0x63, 0x89, 0x4f, 0xfd, 0x37, 0xc, 0xdd, 0x27, 0x75, 0xc8, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha384( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA384 as i64); } #[test] fn test_hmac_sha512() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA512]; let out_exp = [ 0x44, 0xdb, 0xf1, 0xae, 0x7d, 0xcd, 0xc0, 0x5f, 0xa6, 0x9b, 0x30, 0x44, 0x99, 0xfa, 0x19, 0x82, 0x40, 0xb, 0x94, 0xc0, 0xe9, 0x9, 0xcb, 0xc5, 0xf5, 0x74, 0x66, 0x84, 0x45, 0x5b, 0x31, 0xf8, 0x8e, 0x94, 0x14, 0x8c, 0xe2, 0xa4, 0x7, 0xa7, 0x58, 0xd2, 0x14, 0x11, 0x85, 0x8b, 0xa4, 0x50, 0x4c, 0xaa, 0x2e, 0xa1, 0x70, 0xa3, 0x1b, 0xec, 0x87, 0xab, 0xb6, 0x54, 0xf4, 0xe9, 0xd, 0x48, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha512( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA512 as i64); } }
let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA1]; let out_exp = [ 0x19, 0xb1, 0x92, 0x8d, 0x58, 0xa2, 0x3, 0xd, 0x8, 0x2, 0x3f, 0x3d, 0x70, 0x54, 0x51, 0x6d, 0xbc, 0x18, 0x6f, 0x20, ]; let ret: i64; unsafe { ret = kcapi_md_sha1( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA1 as i64); }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let out_path = PathBuf::from(env::var(\"OUT_DIR\").unwrap());\n\n let include_path = out_path.join(\"include\");\n\n let wrapper_h_path = include_path.join(\"wrapper.h\");\n\n let build_path = out_path.join(\"libkcapi\");\n\n\n\n /*\n\n * Copy the libkcapi source...
Rust
web_glitz_macros/src/resources.rs
RSSchermer/web_glitz.rs
a2e26ef0156705f0b5ac7707c4fc24a4a994d84b
use proc_macro2::{Span, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; use syn::spanned::Spanned; use syn::{Attribute, Data, DeriveInput, Field, Ident, Lit, Meta, NestedMeta, Type}; use crate::util::ErrorLog; pub fn expand_derive_resources(input: &DeriveInput) -> Result<TokenStream, String> { if let Data::Struct(ref data) = input.data { let struct_name = &input.ident; let mod_path = quote!(web_glitz::pipeline::resources); let mut log = ErrorLog::new(); let mut resource_fields: Vec<ResourceField> = Vec::new(); for (position, field) in data.fields.iter().enumerate() { match ResourcesField::from_ast(field, position, &mut log) { ResourcesField::Resource(resource_field) => { for field in resource_fields.iter() { if field.binding == resource_field.binding { log.log_error(format!( "Fields `{}` and `{}` cannot both use binding `{}`.", field.name, resource_field.name, field.binding )); } } resource_fields.push(resource_field); } ResourcesField::Excluded => (), }; } let resource_slot_descriptors = resource_fields.iter().map(|field| { let ty = &field.ty; let slot_identifier = &field.name; let slot_index = field.binding as u32; let span = field.span; quote_spanned! {span=> #mod_path::TypedResourceSlotDescriptor { slot_identifier: #mod_path::ResourceSlotIdentifier::Static(#slot_identifier), slot_index: #slot_index, slot_type: <#ty as #mod_path::Resource>::TYPE } } }); let resource_types = resource_fields.iter().map(|field| { let ty = &field.ty; quote! { <#ty as #mod_path::Resource>::Encoding } }); let resource_encodings = resource_fields.iter().map(|field| { let field_name = field .ident .clone() .map(|i| i.into_token_stream()) .unwrap_or(field.position.into_token_stream()); let binding = field.binding as u32; quote! { let encoder = self.#field_name.encode(#binding, encoder); } }); let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let len = resource_fields.len(); let impl_block = quote! { #[automatically_derived] unsafe impl #impl_generics #mod_path::Resources for #struct_name #ty_generics #where_clause { type Encoding = (#(#resource_types,)*); const LAYOUT: &'static [#mod_path::TypedResourceSlotDescriptor] = &[ #(#resource_slot_descriptors,)* ]; fn encode_bind_group( self, context: &mut #mod_path::BindGroupEncodingContext, ) -> #mod_path::BindGroupEncoding<Self::Encoding> { let encoder = #mod_path::BindGroupEncoder::new(context, Some(#len)); #(#resource_encodings)* encoder.finish() } } }; let suffix = struct_name.to_string().trim_start_matches("r#").to_owned(); let dummy_const = Ident::new( &format!("_IMPL_RESOURCES_FOR_{}", suffix), Span::call_site(), ); let generated = quote! { #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] const #dummy_const: () = { #[allow(unknown_lints)] #[cfg_attr(feature = "cargo-clippy", allow(useless_attribute))] #[allow(rust_2018_idioms)] use #mod_path::Resource; #impl_block }; }; log.compile().map(|_| generated) } else { Err("`Resources` can only be derived for a struct.".into()) } } enum ResourcesField { Resource(ResourceField), Excluded, } impl ResourcesField { pub fn from_ast(ast: &Field, position: usize, log: &mut ErrorLog) -> Self { let field_name = ast .ident .clone() .map(|i| i.to_string()) .unwrap_or(position.to_string()); let mut iter = ast.attrs.iter().filter(|a| is_resource_attribute(a)); if let Some(attr) = iter.next() { if iter.next().is_some() { log.log_error(format!( "Cannot add more than 1 #[resource] attribute to field `{}`.", field_name )); return ResourcesField::Excluded; } let meta_items: Vec<NestedMeta> = match attr.parse_meta() { Ok(Meta::List(list)) => list.nested.iter().cloned().collect(), Ok(Meta::Path(path)) if path.is_ident("resource") => Vec::new(), _ => { log.log_error(format!( "Malformed #[resource] attribute for field `{}`.", field_name )); Vec::new() } }; let mut binding = None; let mut name = ast.ident.clone().map(|i| i.to_string()); for meta_item in meta_items.into_iter() { match meta_item { NestedMeta::Meta(Meta::NameValue(m)) if m.path.is_ident("binding") => { if let Lit::Int(i) = &m.lit { if let Ok(value) = i.base10_parse::<u32>() { binding = Some(value); } else { log.log_error(format!( "Malformed #[resource] attribute for field `{}`: \ expected `binding` to be representable as a u32.", field_name )); } } else { log.log_error(format!( "Malformed #[resource] attribute for field `{}`: \ expected `binding` to be a positive integer.", field_name )); }; } NestedMeta::Meta(Meta::NameValue(ref m)) if m.path.is_ident("name") => { if let Lit::Str(n) = &m.lit { name = Some(n.value()); } else { log.log_error(format!( "Malformed #[resource] attribute for field `{}`: \ expected `name` to be a string.", field_name )); }; } _ => log.log_error(format!( "Malformed #[resource] attribute for field `{}`: unrecognized \ option `{}`.", field_name, meta_item.into_token_stream() )), } } if binding.is_none() { log.log_error(format!( "Field `{}` is marked with #[resource], but does not declare a `binding` \ index.", field_name )); } if name.is_none() { log.log_error(format!( "Field `{}` is marked with #[resource], but does not declare a slot name.", field_name )); } if binding.is_some() && name.is_some() { let binding = binding.unwrap(); let name = name.unwrap(); ResourcesField::Resource(ResourceField { ident: ast.ident.clone(), ty: ast.ty.clone(), position, binding, name, span: ast.span(), }) } else { ResourcesField::Excluded } } else { ResourcesField::Excluded } } } struct ResourceField { ident: Option<Ident>, ty: Type, position: usize, binding: u32, name: String, span: Span, } fn is_resource_attribute(attribute: &Attribute) -> bool { attribute.path.segments[0].ident == "resource" }
use proc_macro2::{Span, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; use syn::spanned::Spanned; use syn::{Attribute, Data, DeriveInput, Field, Ident, Lit, Meta, NestedMeta, Type}; use crate::util::ErrorLog; pub fn expand_derive_resources(input: &DeriveInput) -> Result<TokenStream, String> { if let Data::Struct(ref data) = input.data { let struct_name = &input.ident; let mod_path = quote!(web_glitz::pipeline::resources); let mut log = ErrorLog::new();
enum ResourcesField { Resource(ResourceField), Excluded, } impl ResourcesField { pub fn from_ast(ast: &Field, position: usize, log: &mut ErrorLog) -> Self { let field_name = ast .ident .clone() .map(|i| i.to_string()) .unwrap_or(position.to_string()); let mut iter = ast.attrs.iter().filter(|a| is_resource_attribute(a)); if let Some(attr) = iter.next() { if iter.next().is_some() { log.log_error(format!( "Cannot add more than 1 #[resource] attribute to field `{}`.", field_name )); return ResourcesField::Excluded; } let meta_items: Vec<NestedMeta> = match attr.parse_meta() { Ok(Meta::List(list)) => list.nested.iter().cloned().collect(), Ok(Meta::Path(path)) if path.is_ident("resource") => Vec::new(), _ => { log.log_error(format!( "Malformed #[resource] attribute for field `{}`.", field_name )); Vec::new() } }; let mut binding = None; let mut name = ast.ident.clone().map(|i| i.to_string()); for meta_item in meta_items.into_iter() { match meta_item { NestedMeta::Meta(Meta::NameValue(m)) if m.path.is_ident("binding") => { if let Lit::Int(i) = &m.lit { if let Ok(value) = i.base10_parse::<u32>() { binding = Some(value); } else { log.log_error(format!( "Malformed #[resource] attribute for field `{}`: \ expected `binding` to be representable as a u32.", field_name )); } } else { log.log_error(format!( "Malformed #[resource] attribute for field `{}`: \ expected `binding` to be a positive integer.", field_name )); }; } NestedMeta::Meta(Meta::NameValue(ref m)) if m.path.is_ident("name") => { if let Lit::Str(n) = &m.lit { name = Some(n.value()); } else { log.log_error(format!( "Malformed #[resource] attribute for field `{}`: \ expected `name` to be a string.", field_name )); }; } _ => log.log_error(format!( "Malformed #[resource] attribute for field `{}`: unrecognized \ option `{}`.", field_name, meta_item.into_token_stream() )), } } if binding.is_none() { log.log_error(format!( "Field `{}` is marked with #[resource], but does not declare a `binding` \ index.", field_name )); } if name.is_none() { log.log_error(format!( "Field `{}` is marked with #[resource], but does not declare a slot name.", field_name )); } if binding.is_some() && name.is_some() { let binding = binding.unwrap(); let name = name.unwrap(); ResourcesField::Resource(ResourceField { ident: ast.ident.clone(), ty: ast.ty.clone(), position, binding, name, span: ast.span(), }) } else { ResourcesField::Excluded } } else { ResourcesField::Excluded } } } struct ResourceField { ident: Option<Ident>, ty: Type, position: usize, binding: u32, name: String, span: Span, } fn is_resource_attribute(attribute: &Attribute) -> bool { attribute.path.segments[0].ident == "resource" }
let mut resource_fields: Vec<ResourceField> = Vec::new(); for (position, field) in data.fields.iter().enumerate() { match ResourcesField::from_ast(field, position, &mut log) { ResourcesField::Resource(resource_field) => { for field in resource_fields.iter() { if field.binding == resource_field.binding { log.log_error(format!( "Fields `{}` and `{}` cannot both use binding `{}`.", field.name, resource_field.name, field.binding )); } } resource_fields.push(resource_field); } ResourcesField::Excluded => (), }; } let resource_slot_descriptors = resource_fields.iter().map(|field| { let ty = &field.ty; let slot_identifier = &field.name; let slot_index = field.binding as u32; let span = field.span; quote_spanned! {span=> #mod_path::TypedResourceSlotDescriptor { slot_identifier: #mod_path::ResourceSlotIdentifier::Static(#slot_identifier), slot_index: #slot_index, slot_type: <#ty as #mod_path::Resource>::TYPE } } }); let resource_types = resource_fields.iter().map(|field| { let ty = &field.ty; quote! { <#ty as #mod_path::Resource>::Encoding } }); let resource_encodings = resource_fields.iter().map(|field| { let field_name = field .ident .clone() .map(|i| i.into_token_stream()) .unwrap_or(field.position.into_token_stream()); let binding = field.binding as u32; quote! { let encoder = self.#field_name.encode(#binding, encoder); } }); let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let len = resource_fields.len(); let impl_block = quote! { #[automatically_derived] unsafe impl #impl_generics #mod_path::Resources for #struct_name #ty_generics #where_clause { type Encoding = (#(#resource_types,)*); const LAYOUT: &'static [#mod_path::TypedResourceSlotDescriptor] = &[ #(#resource_slot_descriptors,)* ]; fn encode_bind_group( self, context: &mut #mod_path::BindGroupEncodingContext, ) -> #mod_path::BindGroupEncoding<Self::Encoding> { let encoder = #mod_path::BindGroupEncoder::new(context, Some(#len)); #(#resource_encodings)* encoder.finish() } } }; let suffix = struct_name.to_string().trim_start_matches("r#").to_owned(); let dummy_const = Ident::new( &format!("_IMPL_RESOURCES_FOR_{}", suffix), Span::call_site(), ); let generated = quote! { #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] const #dummy_const: () = { #[allow(unknown_lints)] #[cfg_attr(feature = "cargo-clippy", allow(useless_attribute))] #[allow(rust_2018_idioms)] use #mod_path::Resource; #impl_block }; }; log.compile().map(|_| generated) } else { Err("`Resources` can only be derived for a struct.".into()) } }
function_block-function_prefix_line
[ { "content": "pub fn expand_derive_vertex(input: &DeriveInput) -> Result<TokenStream, String> {\n\n if let Data::Struct(ref data) = input.data {\n\n let struct_name = &input.ident;\n\n let mod_path = quote!(web_glitz::pipeline::graphics);\n\n let mut log = ErrorLog::new();\n\n\n\n ...
Rust
src/components/memory.rs
rust-motd/rust-motd
d9fdf32019993f7abc10bb01c0bdf7ef8224f44e
use serde::Deserialize; use systemstat::{saturating_sub_bytes, Platform, System}; use termion::{color, style}; use thiserror::Error; use crate::constants::{GlobalSettings, INDENT_WIDTH}; #[derive(Error, Debug)] pub enum MemoryError { #[error("Could not find memory quantity {quantity:?}")] MemoryNotFound { quantity: String }, #[error(transparent)] IO(#[from] std::io::Error), } #[derive(Debug, Deserialize)] pub struct MemoryCfg { swap_pos: SwapPosition, } #[derive(Debug, Deserialize, PartialEq)] enum SwapPosition { #[serde(alias = "beside")] Beside, #[serde(alias = "below")] Below, #[serde(alias = "none")] None, } struct MemoryUsage { name: String, used: String, total: String, used_ratio: f64, } impl MemoryUsage { fn get_by_name( name: String, sys: &System, free_name: &str, total_name: &str, ) -> Result<Self, MemoryError> { let memory = sys.memory()?; let total = memory .platform_memory .meminfo .get(total_name) .ok_or(MemoryError::MemoryNotFound { quantity: total_name.to_string(), })?; let free = memory .platform_memory .meminfo .get(free_name) .ok_or(MemoryError::MemoryNotFound { quantity: free_name.to_string(), })?; let used = saturating_sub_bytes(*total, *free); Ok(MemoryUsage { name, used: used.to_string(), total: total.to_string(), used_ratio: used.as_u64() as f64 / total.as_u64() as f64, }) } } fn print_bar( global_settings: &GlobalSettings, full_color: String, bar_full: usize, bar_empty: usize, ) { print!( "{}", [ " ".repeat(INDENT_WIDTH), global_settings.progress_prefix.to_string(), full_color, global_settings .progress_full_character .to_string() .repeat(bar_full), color::Fg(color::LightBlack).to_string(), global_settings .progress_empty_character .to_string() .repeat(bar_empty), style::Reset.to_string(), global_settings.progress_suffix.to_string(), ] .join("") ); } fn full_color(ratio: f64) -> String { match (ratio * 100.) as usize { 0..=75 => color::Fg(color::Green).to_string(), 76..=95 => color::Fg(color::Yellow).to_string(), _ => color::Fg(color::Red).to_string(), } } pub fn disp_memory( config: MemoryCfg, global_settings: &GlobalSettings, sys: &System, size_hint: Option<usize>, ) -> Result<(), MemoryError> { let size_hint = size_hint.unwrap_or(global_settings.progress_width - INDENT_WIDTH); let ram_usage = MemoryUsage::get_by_name("RAM".to_string(), sys, "MemAvailable", "MemTotal")?; println!("Memory"); match config.swap_pos { SwapPosition::Below => { let swap_usage = MemoryUsage::get_by_name("Swap".to_string(), sys, "SwapFree", "SwapTotal")?; let entries = vec![ram_usage, swap_usage]; let bar_width = size_hint - global_settings.progress_prefix.len() - global_settings.progress_suffix.len(); for entry in entries { let full_color = full_color(entry.used_ratio); let bar_full = ((bar_width as f64) * entry.used_ratio) as usize; let bar_empty = bar_width - bar_full; println!( "{}{}: {} / {}", " ".repeat(INDENT_WIDTH), entry.name, entry.used, entry.total ); print_bar(global_settings, full_color, bar_full, bar_empty); println!(); } } SwapPosition::Beside => { let swap_usage = MemoryUsage::get_by_name("Swap".to_string(), sys, "SwapFree", "SwapTotal")?; let bar_width = ((size_hint - global_settings.progress_prefix.len() - global_settings.progress_suffix.len()) / 2) - INDENT_WIDTH; let ram_label = format!( "{}: {} / {}", ram_usage.name, ram_usage.used, ram_usage.total ); let swap_label = format!( "{}: {} / {}", swap_usage.name, swap_usage.used, swap_usage.total ); println!( "{}{}{}{}", " ".repeat(INDENT_WIDTH), ram_label, " ".repeat(bar_width - ram_label.len() + 2 * INDENT_WIDTH), swap_label ); let bar_color = full_color(ram_usage.used_ratio); let bar_full = ((bar_width as f64) * ram_usage.used_ratio) as usize; let bar_empty = bar_width - bar_full; print_bar(global_settings, bar_color, bar_full, bar_empty); let bar_color = full_color(swap_usage.used_ratio); let bar_full = ((bar_width as f64) * swap_usage.used_ratio) as usize; let bar_empty = bar_width - bar_full; print_bar(global_settings, bar_color, bar_full, bar_empty); println!(); } SwapPosition::None => { let bar_width = size_hint - global_settings.progress_prefix.len() - global_settings.progress_suffix.len(); let full_color = full_color(ram_usage.used_ratio); let bar_full = ((bar_width as f64) * ram_usage.used_ratio) as usize; let bar_empty = bar_width - bar_full; println!( "{}{}: {} / {}", " ".repeat(INDENT_WIDTH), ram_usage.name, ram_usage.used, ram_usage.total ); print_bar(global_settings, full_color, bar_full, bar_empty); println!(); } } Ok(()) }
use serde::Deserialize; use systemstat::{saturating_sub_bytes, Platform, System}; use termion::{color, style}; use thiserror::Error; use crate::constants::{GlobalSettings, INDENT_WIDTH}; #[derive(Error, Debug)] pub enum MemoryError { #[error("Could not find memory quantity {quantity:?}")] MemoryNotFound { quantity: String }, #[error(transparent)] IO(#[from] std::io::Error), } #[derive(Debug, Deserialize)] pub struct MemoryCfg { swap_pos: SwapPosition, } #[derive(Debug, Deserialize, PartialEq)] enum SwapPosition { #[serde(alias = "beside")] Beside, #[serde(alias = "below")] Below, #[serde(alias = "none")] None, } struct MemoryUsage { name: String, used: String, total: String, used_ratio: f64, } impl MemoryUsage { fn get_by_name( name: String, sys: &System, free_name: &str, total_name: &str, ) -> Result<Self, MemoryError> { let memory = sys.memory()?; let total = memory .platform_memory .meminfo .get(total_name) .ok_or(MemoryError::MemoryNotFound { quantity: total_name.to_string(), })?; let free = memory .platform_memory .meminfo .get(free_name) .ok_or(MemoryError::MemoryNotFound { quantity: free_name.to_string(), })?; let used = saturating_sub_bytes(*total, *free); Ok(MemoryUsage { name, used: used.to_string(), total: total.to_string(), used_ratio: used.as_u64() as f64 / total.as_u64() as f64, }) } }
fn full_color(ratio: f64) -> String { match (ratio * 100.) as usize { 0..=75 => color::Fg(color::Green).to_string(), 76..=95 => color::Fg(color::Yellow).to_string(), _ => color::Fg(color::Red).to_string(), } } pub fn disp_memory( config: MemoryCfg, global_settings: &GlobalSettings, sys: &System, size_hint: Option<usize>, ) -> Result<(), MemoryError> { let size_hint = size_hint.unwrap_or(global_settings.progress_width - INDENT_WIDTH); let ram_usage = MemoryUsage::get_by_name("RAM".to_string(), sys, "MemAvailable", "MemTotal")?; println!("Memory"); match config.swap_pos { SwapPosition::Below => { let swap_usage = MemoryUsage::get_by_name("Swap".to_string(), sys, "SwapFree", "SwapTotal")?; let entries = vec![ram_usage, swap_usage]; let bar_width = size_hint - global_settings.progress_prefix.len() - global_settings.progress_suffix.len(); for entry in entries { let full_color = full_color(entry.used_ratio); let bar_full = ((bar_width as f64) * entry.used_ratio) as usize; let bar_empty = bar_width - bar_full; println!( "{}{}: {} / {}", " ".repeat(INDENT_WIDTH), entry.name, entry.used, entry.total ); print_bar(global_settings, full_color, bar_full, bar_empty); println!(); } } SwapPosition::Beside => { let swap_usage = MemoryUsage::get_by_name("Swap".to_string(), sys, "SwapFree", "SwapTotal")?; let bar_width = ((size_hint - global_settings.progress_prefix.len() - global_settings.progress_suffix.len()) / 2) - INDENT_WIDTH; let ram_label = format!( "{}: {} / {}", ram_usage.name, ram_usage.used, ram_usage.total ); let swap_label = format!( "{}: {} / {}", swap_usage.name, swap_usage.used, swap_usage.total ); println!( "{}{}{}{}", " ".repeat(INDENT_WIDTH), ram_label, " ".repeat(bar_width - ram_label.len() + 2 * INDENT_WIDTH), swap_label ); let bar_color = full_color(ram_usage.used_ratio); let bar_full = ((bar_width as f64) * ram_usage.used_ratio) as usize; let bar_empty = bar_width - bar_full; print_bar(global_settings, bar_color, bar_full, bar_empty); let bar_color = full_color(swap_usage.used_ratio); let bar_full = ((bar_width as f64) * swap_usage.used_ratio) as usize; let bar_empty = bar_width - bar_full; print_bar(global_settings, bar_color, bar_full, bar_empty); println!(); } SwapPosition::None => { let bar_width = size_hint - global_settings.progress_prefix.len() - global_settings.progress_suffix.len(); let full_color = full_color(ram_usage.used_ratio); let bar_full = ((bar_width as f64) * ram_usage.used_ratio) as usize; let bar_empty = bar_width - bar_full; println!( "{}{}: {} / {}", " ".repeat(INDENT_WIDTH), ram_usage.name, ram_usage.used, ram_usage.total ); print_bar(global_settings, full_color, bar_full, bar_empty); println!(); } } Ok(()) }
fn print_bar( global_settings: &GlobalSettings, full_color: String, bar_full: usize, bar_empty: usize, ) { print!( "{}", [ " ".repeat(INDENT_WIDTH), global_settings.progress_prefix.to_string(), full_color, global_settings .progress_full_character .to_string() .repeat(bar_full), color::Fg(color::LightBlack).to_string(), global_settings .progress_empty_character .to_string() .repeat(bar_empty), style::Reset.to_string(), global_settings.progress_suffix.to_string(), ] .join("") ); }
function_block-full_function
[ { "content": "fn print_row<'a>(items: [&str; 6], column_sizes: impl IntoIterator<Item = &'a usize>) {\n\n println!(\n\n \"{}\",\n\n Itertools::intersperse(\n\n items\n\n .iter()\n\n .zip(column_sizes.into_iter())\n\n .map(|(name, size)| fo...
Rust
task-scheduler-rust/src/apply.rs
gyuho/task-scheduler-examples
bd9475b90679d060fdcb9bf856e5a81ed15917c2
use std::{ io, io::{Error, ErrorKind}, string::String, sync::Arc, time::{Duration, Instant}, }; use tokio::{ select, sync::mpsc, task::{self, JoinHandle}, time::timeout, }; use crate::echo; use crate::id; use crate::notify; #[derive(Debug)] pub struct Request { pub echo_request: Option<echo::Request>, } impl Request { pub fn new() -> Self { Self { echo_request: None } } } pub struct Applier { request_timeout: Duration, request_id_generator: id::Generator, notifier: Arc<notify::Notifier>, request_tx: mpsc::UnboundedSender<(u64, Request)>, stop_tx: mpsc::Sender<()>, } impl Applier { pub fn new(req_timeout: Duration) -> (Self, JoinHandle<io::Result<()>>) { let member_id = rand::random::<u64>(); let (request_ch_tx, request_ch_rx) = mpsc::unbounded_channel(); let (stop_ch_tx, stop_ch_rx) = mpsc::channel(1); let notifier = Arc::new(notify::Notifier::new()); let notifier_clone = notifier.clone(); let echo_manager = echo::Manager::new(); let handle = task::spawn(async move { apply_async(notifier_clone, request_ch_rx, stop_ch_rx, echo_manager).await }); ( Self { request_timeout: req_timeout, request_id_generator: id::Generator::new(member_id, Instant::now().elapsed()), notifier, request_tx: request_ch_tx, stop_tx: stop_ch_tx, }, handle, ) } pub async fn stop(&self) -> io::Result<()> { println!("stopping applier"); match self.stop_tx.send(()).await { Ok(()) => println!("sent stop_tx"), Err(e) => { println!("failed to send stop_tx: {}", e); return Err(Error::new(ErrorKind::Other, format!("failed to send"))); } } println!("stopped applier"); Ok(()) } pub async fn apply(&self, req: Request) -> io::Result<String> { let req_id = self.request_id_generator.next(); let resp_rx = self.notifier.register(req_id)?; match self.request_tx.send((req_id, req)) { Ok(_) => println!("scheduled a request"), Err(e) => { self.notifier .trigger(req_id, format!("failed to schedule {} {}", req_id, e))?; } } let msg = timeout(self.request_timeout, resp_rx) .await .map_err(|_| Error::new(ErrorKind::Other, "timeout"))?; let rs = msg.map_err(|e| Error::new(ErrorKind::Other, format!("failed to apply {}", e)))?; Ok(rs) } } pub async fn apply_async( notifier: Arc<notify::Notifier>, mut request_rx: mpsc::UnboundedReceiver<(u64, Request)>, mut stop_rx: mpsc::Receiver<()>, mut echo_manager: echo::Manager, ) -> io::Result<()> { println!("running apply loop"); 'outer: loop { let (req_id, req) = select! { Some(v) = request_rx.recv() => v, _ = stop_rx.recv() => { println!("received stop_rx"); break 'outer; } }; match req.echo_request { Some(v) => match echo_manager.apply(&v) { Ok(rs) => match notifier.trigger(req_id, rs) { Ok(_) => {} Err(e) => println!("failed to trigger {}", e), }, Err(e) => { println!("failed to apply {}", e); match notifier.trigger(req_id, format!("failed {}", e)) { Ok(_) => {} Err(e) => println!("failed to trigger {}", e), } } }, None => {} } } Ok(()) }
use std::{ io, io::{Error, ErrorKind}, string::String, sync::Arc, time::{Duration, Instant}, }; use tokio::{ select, sync::mpsc, task::{self, JoinHandle}, time::timeout, }; use crate::echo; use crate::id; use crate::notify; #[derive(Debug)] pub struct Request { pub echo_request: Option<echo::Request>, } impl Request { pub fn new() -> Self { Self { echo_request: None } } } pub struct Applier { request_timeout: Duration, request_id_generator: id::Generator, notifier: Arc<notify::Notifier>, request_tx: mpsc::UnboundedSender<(u64, Request)>, stop_tx: mpsc::Sender<()>, } impl Applier { pub fn new(req_timeout: Duration) -> (Self, JoinHandle<io::Result<()>>) { let member_id = rand::random::<u64>(); let (request_ch_tx, request_ch_rx) = mpsc::unbounded_channel(); let (stop_ch_tx, stop_ch_rx) = mpsc::channel(1); let notifier = Arc::new(notify::Notifier::new()); let notifier_clone = notifier.clone(); let echo_manager = echo::Manager::new(); let handle = task::spawn(async move { apply_async(notifier_clone, request_ch_rx, stop_ch_rx, echo_manager).await }); ( Self { request_timeout: req_timeout, request_id_generator: id::Generator::new(member_id, Instant::now().elapsed()), notifier, request_tx: request_ch_tx, stop_tx: stop_ch_tx, }, handle, ) } pub async fn stop(&self) -> io::Result<()> { println!("stopping applier"); match self.stop_tx.send(()).await { Ok(()) => println!("sent stop_tx"), Err(e) => { println!("failed to send stop_tx: {}", e); return Err(Error::new(ErrorKind::Other, format!("failed to send"))); } } println!("stopped applier"); Ok(()) } pub async fn apply(&self, req: Request) -> io::Result<String> { let req_id = self.request_id_generator.next(); let resp_rx = self.notifier.register(req_id)?; match self.request_tx.send((req_id, req)) { Ok(_) => println!("scheduled a request"), Err(e) => { self.notifier .trigger(req_id, format!("failed to schedule {} {}", req_id, e))?; } } let msg = timeout(self.request_timeout, resp_rx) .await .map_err(|_| Error::new(ErrorKind::Other, "timeout"))?; let rs = msg.map_err(|e| Error::new(ErrorKind::Other, format!("failed to apply {}", e)))?; Ok(rs) } }
pub async fn apply_async( notifier: Arc<notify::Notifier>, mut request_rx: mpsc::UnboundedReceiver<(u64, Request)>, mut stop_rx: mpsc::Receiver<()>, mut echo_manager: echo::Manager, ) -> io::Result<()> { println!("running apply loop"); 'outer: loop { let (req_id, req) = select! { Some(v) = request_rx.recv() => v, _ = stop_rx.recv() => { println!("received stop_rx"); break 'outer; } }; match req.echo_request { Some(v) => match echo_manager.apply(&v) { Ok(rs) => match notifier.trigger(req_id, rs) { Ok(_) => {} Err(e) => println!("failed to trigger {}", e), }, Err(e) => { println!("failed to apply {}", e); match notifier.trigger(req_id, format!("failed {}", e)) { Ok(_) => {} Err(e) => println!("failed to trigger {}", e), } } }, None => {} } } Ok(()) }
function_block-full_function
[ { "content": "pub fn parse_request(b: &[u8]) -> io::Result<Request> {\n\n serde_json::from_slice(b).map_err(|e| {\n\n return Error::new(ErrorKind::InvalidInput, format!(\"invalid JSON: {}\", e));\n\n })\n\n}\n\n\n", "file_path": "task-scheduler-rust/src/echo.rs", "rank": 0, "score": 142...
Rust
src/discord_client/serenity_discord_client.rs
Hammatt/tougou_bot
47f0457f66ef3815791d2d47e0eb503c7a72f996
use crate::discord_client::{CommandHandler, DiscordClient}; use log; use serenity::{ client, model::{channel::Message, gateway::Ready}, prelude::*, }; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread; type BoxedThreadsafeCommandHandler = Box<Arc<Mutex<CommandHandler + Send>>>; pub struct SerenityDiscordClient { command_callbacks: Arc<Mutex<HashMap<String, BoxedThreadsafeCommandHandler>>>, } struct SerenityDiscordHandler { command_callbacks: Arc<Mutex<HashMap<String, BoxedThreadsafeCommandHandler>>>, command_prefix: &'static str, } impl DiscordClient for SerenityDiscordClient { fn new(token: &str) -> Self { log::info!("valid token: {}", client::validate_token(token).is_ok()); let command_callbacks = Arc::new(Mutex::new(HashMap::new())); let serenity_handler = SerenityDiscordHandler { command_callbacks: command_callbacks.clone(), command_prefix: "!", }; let serenity_client = Arc::new(Mutex::new( Client::new(token, serenity_handler).expect("Error creating serenity client"), )); log::info!("created client"); let thread_serenity_client = serenity_client.clone(); thread::spawn(move || { if let Err(why) = thread_serenity_client.lock().unwrap().start() { log::error!("An error occurred while running the client: {:?}", why); } }); log::info!("started connection"); SerenityDiscordClient { command_callbacks: command_callbacks.clone(), } } fn register_command<T>( &self, command: &str, command_handler: Arc<Mutex<T>>, ) -> Result<(), Box<std::error::Error>> where T: CommandHandler + Send + 'static, { if self .command_callbacks .lock() .unwrap() .insert(command.to_string(), Box::new(command_handler)) .is_some() { panic!("command was entered twice for {}", command); } Ok(()) } } impl SerenityDiscordHandler { fn get_command_name(&self, full_command: &str) -> Option<String> { let mut result: Option<String> = None; if full_command.starts_with(self.command_prefix) { if let Some(command_with_prefix) = full_command.split_whitespace().nth(0) { if let Some(command) = command_with_prefix .chars() .next() .map(|c| &command_with_prefix[c.len_utf8()..]) { result = Some(command.to_string()); } } } result } } impl EventHandler for SerenityDiscordHandler { fn message(&self, ctx: Context, msg: Message) { if let Some(command) = self.get_command_name(&msg.content) { if let Some(command_handler) = self.command_callbacks.lock().unwrap().get(&command) { if let Err(err) = command_handler.lock().unwrap().process_command( &msg.content, msg.guild_id.unwrap().0, &|output| { if let Err(err) = msg.channel_id.say(&ctx.http, output) { log::error!("Error sending message: {:?}", err); } }, ) { log::error!("Error processing command: {:?}", err); } }; }; } fn ready(&self, _: Context, ready: Ready) { log::info!("{} is connected!", ready.user.name); } } #[cfg(test)] mod tests { use super::*; #[test] fn test_get_command_name() { let command_callbacks = Arc::new(Mutex::new(HashMap::new())); let handler = SerenityDiscordHandler { command_callbacks: command_callbacks.clone(), command_prefix: "!", }; assert_eq!( Some(String::from("ping")), handler.get_command_name("!ping") ); assert_eq!(Some(String::from("pic")), handler.get_command_name("!pic")); assert_eq!( Some(String::from("pic")), handler.get_command_name("!pic tag1 tag2 tag3") ); assert_eq!( Some(String::from("pic")), handler.get_command_name("!pic ももよ まじこい") ); assert_eq!( Some(String::from("辞書")), handler.get_command_name("!辞書") ); assert_eq!( Some(String::from("辞書")), handler.get_command_name("!辞書 勉強") ); } }
use crate::discord_client::{CommandHandler, DiscordClient}; use log; use serenity::{ client, model::{channel::Message, gateway::Ready}, prelude::*, }; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread; type BoxedThreadsafeCommandHandler = Box<Arc<Mutex<CommandHandler + Send>>>; pub struct SerenityDiscordClient { command_callbacks: Arc<Mutex<HashMap<String, BoxedThreadsafeCommandHandler>>>, } struct SerenityDiscordHandler { command_callbacks: Arc<Mutex<HashMap<String, BoxedThreadsafeCommandHandler>>>, command_prefix: &'static str, } impl DiscordClient for SerenityDiscordClient { fn new(token: &str) -> Self { log::info!("valid token: {}", client::validate_token(token).is_ok()); let command_callbacks = Arc::new(Mutex::new(HashMap::new())); let serenity_handler = SerenityDiscordHandler { command_callbacks: command_callbacks.clone(), command_prefix: "!", }; let serenity_client = Arc::new(Mutex::new( Client::new(token, serenity_handler).expect("Error creating serenity client"), )); log::info!("created client"); let thread_serenity_client = serenity_client.clone(); thread::spawn(move || { if let Err(why) = thread_serenity_client.lock().unwrap().start() { log::error!("An error occurred while running the client: {:?}", why); } }); log::info!("started connection"); SerenityDiscordClient { command_callbacks: command_callbacks.clone(), } } fn register_command<T>( &self, command: &str, command_handler: Arc<Mutex<T>>, ) -> Result<(), Box<std::error::Error>> where T: CommandHandler + Send + 'static, { if self .command_callbacks .lock() .unwrap() .insert(command.to_string(), Box::new(command_handler)) .is_some() { panic!("command was entered twice for {}", command); } Ok(()) } } impl SerenityDiscordHandler { fn get_command_name(&self, full_command: &str) -> Option<String> { let mut result: Option<String> = None; if full_command.starts_with(self.command_prefix) { if let Some(command_with_prefix) = full_command.split_whitespace().nth(0) { if let Some(command) = command_with_prefix .chars() .next() .map(|c| &command_with_prefix[c.len_utf
} impl EventHandler for SerenityDiscordHandler { fn message(&self, ctx: Context, msg: Message) { if let Some(command) = self.get_command_name(&msg.content) { if let Some(command_handler) = self.command_callbacks.lock().unwrap().get(&command) { if let Err(err) = command_handler.lock().unwrap().process_command( &msg.content, msg.guild_id.unwrap().0, &|output| { if let Err(err) = msg.channel_id.say(&ctx.http, output) { log::error!("Error sending message: {:?}", err); } }, ) { log::error!("Error processing command: {:?}", err); } }; }; } fn ready(&self, _: Context, ready: Ready) { log::info!("{} is connected!", ready.user.name); } } #[cfg(test)] mod tests { use super::*; #[test] fn test_get_command_name() { let command_callbacks = Arc::new(Mutex::new(HashMap::new())); let handler = SerenityDiscordHandler { command_callbacks: command_callbacks.clone(), command_prefix: "!", }; assert_eq!( Some(String::from("ping")), handler.get_command_name("!ping") ); assert_eq!(Some(String::from("pic")), handler.get_command_name("!pic")); assert_eq!( Some(String::from("pic")), handler.get_command_name("!pic tag1 tag2 tag3") ); assert_eq!( Some(String::from("pic")), handler.get_command_name("!pic ももよ まじこい") ); assert_eq!( Some(String::from("辞書")), handler.get_command_name("!辞書") ); assert_eq!( Some(String::from("辞書")), handler.get_command_name("!辞書 勉強") ); } }
8()..]) { result = Some(command.to_string()); } } } result }
function_block-function_prefixed
[ { "content": "fn parse_command(command: &str) -> Vec<&str> {\n\n command.split_ascii_whitespace().skip(1).collect()\n\n}\n\n\n\nimpl JishoCommand {\n\n pub fn new(jisho_repository: Box<JishoRepository + Send>) -> JishoCommand {\n\n JishoCommand { jisho_repository }\n\n }\n\n}\n\n\n\nimpl Command...
Rust
src/search.rs
dskleingeld/minimal_timeseries
0d03039ec4663a918a8adbe7a78fee2237dfe69a
use byteorder::{ByteOrder, LittleEndian}; use chrono::{DateTime, Utc}; use std::io::{Read, Seek, SeekFrom}; use crate::data::FullTime; use crate::header::SearchBounds; use crate::ByteSeries; use crate::Error; #[derive(thiserror::Error, Debug)] pub enum SeekError { #[error("could not find timestamp in this series")] NotFound, #[error("data file is empty")] EmptyFile, #[error("no data to return as the start time is after the last time in the data")] StartAfterData, #[error("no data to return as the stop time is before the data")] StopBeforeData, #[error("error while searching through data")] Io(#[from] std::io::Error), } #[derive(Debug)] pub struct TimeSeek { pub start: u64, pub stop: u64, pub curr: u64, pub full_time: FullTime, } impl TimeSeek { pub fn new( series: &mut ByteSeries, start: chrono::DateTime<Utc>, stop: chrono::DateTime<Utc>, ) -> Result<Self, Error> { let (start, stop, full_time) = series.get_bounds(start, stop)?; Ok(TimeSeek { start, stop, curr: start, full_time, }) } pub fn lines(&self, series: &ByteSeries) -> u64 { (self.stop - self.start) / (series.full_line_size as u64) } } impl ByteSeries { fn find_read_start( &mut self, start_time: DateTime<Utc>, start: u64, stop: u64, ) -> Result<u64, SeekError> { let mut buf = vec![0u8; (stop - start) as usize]; self.data.seek(SeekFrom::Start(start))?; self.data.read_exact(&mut buf)?; for line_start in (0..buf.len().saturating_sub(2)).step_by(self.full_line_size) { if LittleEndian::read_u16(&buf[line_start..line_start + 2]) >= start_time.timestamp() as u16 { log::debug!("setting start_byte from liniar search, pos: {}", line_start); let start_byte = start + line_start as u64; return Ok(start_byte); } } Ok(stop) } pub fn get_bounds( &mut self, start_time: DateTime<Utc>, end_time: DateTime<Utc>, ) -> Result<(u64, u64, FullTime), SeekError> { if self.data_size == 0 { return Err(SeekError::EmptyFile); } if start_time.timestamp() >= self.last_time_in_data.unwrap() { return Err(SeekError::StartAfterData); } if end_time.timestamp() <= self.first_time_in_data.unwrap() { return Err(SeekError::StopBeforeData); } let (start_bound, stop_bound, full_time) = self .header .search_bounds(start_time.timestamp(), end_time.timestamp()); let start_byte = match start_bound { SearchBounds::Found(pos) => pos, SearchBounds::Clipped => 0, SearchBounds::TillEnd(start) => { let end = self.data_size; self.find_read_start(start_time, start, end)? } SearchBounds::Window(start, stop) => self.find_read_start(start_time, start, stop)?, }; let stop_byte = match stop_bound { SearchBounds::Found(pos) => pos, SearchBounds::TillEnd(pos) => { let end = self.data_size; self.find_read_stop(end_time, pos, end)? } SearchBounds::Window(start, stop) => self.find_read_stop(end_time, start, stop)?, SearchBounds::Clipped => panic!("should never occur"), }; Ok((start_byte, stop_byte, full_time)) } fn find_read_stop( &mut self, end_time: DateTime<Utc>, start: u64, stop: u64, ) -> Result<u64, SeekError> { let mut buf = vec![0u8; (stop - start) as usize]; self.data.seek(SeekFrom::Start(start))?; self.data.read_exact(&mut buf)?; for line_start in (0..buf.len() - self.full_line_size + 1) .rev() .step_by(self.full_line_size) { if LittleEndian::read_u16(&buf[line_start..line_start + 2]) <= end_time.timestamp() as u16 { let stop_byte = start + line_start as u64; return Ok(stop_byte + self.full_line_size as u64); } } Ok(stop) } }
use byteorder::{ByteOrder, LittleEndian}; use chrono::{DateTime, Utc}; use std::io::{Read, Seek, SeekFrom}; use crate::data::FullTime; use crate::header::SearchBounds; use crate::ByteSeries; use crate::Error; #[derive(thiserror::Error, Debug)] pub enum SeekError { #[error("could not find timestamp in this series")] NotFound, #[error("data file is empty")] EmptyFile, #[error("no data to return as the start time is after the last time in the data")] StartAfterData, #[error("no data to return as the stop time is before the data")] StopBeforeData, #[error("error while searching through data")] Io(#[from] std::io::Error), } #[derive(Debug)] pub struct TimeSeek { pub start: u64, pub stop: u64, pub curr: u64, pub full_time: FullTime, } impl TimeSeek { pub fn new( series: &mut ByteSeries, start: chrono::DateTime<Utc>, stop: chrono::DateTime<Utc>, ) -> Result<Self, Error> { let (start, stop, full_time) = series.get_bounds(start, stop)?; Ok(TimeSeek { start, stop, curr: start, full_time, }) } pub fn lines(&self, series: &ByteSeries) -> u64 { (self.stop - self.start) / (series.full_line_size as u64) } } impl ByteSeries { fn find_read_start( &mut self, start_time: DateTime<Utc>, start: u64, stop: u64, ) -> Result<u64, SeekError> { let mut buf = vec![0u8; (stop - start) as usize];
pub fn get_bounds( &mut self, start_time: DateTime<Utc>, end_time: DateTime<Utc>, ) -> Result<(u64, u64, FullTime), SeekError> { if self.data_size == 0 { return Err(SeekError::EmptyFile); } if start_time.timestamp() >= self.last_time_in_data.unwrap() { return Err(SeekError::StartAfterData); } if end_time.timestamp() <= self.first_time_in_data.unwrap() { return Err(SeekError::StopBeforeData); } let (start_bound, stop_bound, full_time) = self .header .search_bounds(start_time.timestamp(), end_time.timestamp()); let start_byte = match start_bound { SearchBounds::Found(pos) => pos, SearchBounds::Clipped => 0, SearchBounds::TillEnd(start) => { let end = self.data_size; self.find_read_start(start_time, start, end)? } SearchBounds::Window(start, stop) => self.find_read_start(start_time, start, stop)?, }; let stop_byte = match stop_bound { SearchBounds::Found(pos) => pos, SearchBounds::TillEnd(pos) => { let end = self.data_size; self.find_read_stop(end_time, pos, end)? } SearchBounds::Window(start, stop) => self.find_read_stop(end_time, start, stop)?, SearchBounds::Clipped => panic!("should never occur"), }; Ok((start_byte, stop_byte, full_time)) } fn find_read_stop( &mut self, end_time: DateTime<Utc>, start: u64, stop: u64, ) -> Result<u64, SeekError> { let mut buf = vec![0u8; (stop - start) as usize]; self.data.seek(SeekFrom::Start(start))?; self.data.read_exact(&mut buf)?; for line_start in (0..buf.len() - self.full_line_size + 1) .rev() .step_by(self.full_line_size) { if LittleEndian::read_u16(&buf[line_start..line_start + 2]) <= end_time.timestamp() as u16 { let stop_byte = start + line_start as u64; return Ok(stop_byte + self.full_line_size as u64); } } Ok(stop) } }
self.data.seek(SeekFrom::Start(start))?; self.data.read_exact(&mut buf)?; for line_start in (0..buf.len().saturating_sub(2)).step_by(self.full_line_size) { if LittleEndian::read_u16(&buf[line_start..line_start + 2]) >= start_time.timestamp() as u16 { log::debug!("setting start_byte from liniar search, pos: {}", line_start); let start_byte = start + line_start as u64; return Ok(start_byte); } } Ok(stop) }
function_block-function_prefix_line
[ { "content": "fn insert_vector(ts: &mut Series, t_start: DateTime<Utc>, t_end: DateTime<Utc>, data: &[f32]) {\n\n let dt = (t_end - t_start) / (data.len() as i32);\n\n let mut time = t_start;\n\n\n\n for x in data {\n\n ts.append(time, &x.to_be_bytes()).unwrap();\n\n time = time + dt;\n\n...
Rust
src/synth_ui/widgets.rs
GorgeousMooseNipple/beep-boop
834cdea5a011be9c992ecbcb55c433cf341c2667
use std::sync::MutexGuard; use druid::widget::prelude::*; use druid::widget::{Flex, Slider, CrossAxisAlignment}; use druid::Code as KeyCode; use druid::KeyEvent; use super::{ model::{SynthUIData, SynthUIEvent, OscSettings, EnvSettings}, layout::{slider_log, LOG_SCALE_BASE}, constants::{WAVEFORMS, DefaultParameter}, }; use crate::synth::{Synth, WaveForm, ADSRParam}; fn round_float(f: f32, accuracy: i32) -> f32 { let base = 10f32.powi(accuracy); (f * base).round() / base } fn get_note(key: &KeyCode) -> Option<f32> { let freq = match key { KeyCode::KeyZ => 130.81, KeyCode::KeyS => 138.59, KeyCode::KeyX => 146.83, KeyCode::KeyD => 155.56, KeyCode::KeyC => 164.81, KeyCode::KeyV => 174.61, KeyCode::KeyG => 185.00, KeyCode::KeyB => 196.00, KeyCode::KeyH => 207.65, KeyCode::KeyN => 220.00, KeyCode::KeyJ => 233.08, KeyCode::KeyM => 246.94, _ => return None, }; Some(freq) } #[derive(Clone)] pub struct WaveFormUI { pub name: &'static str, pub waveform: WaveForm, } pub struct SynthUI { pub root: Flex<SynthUIData>, } impl SynthUI { pub fn new() -> Self { Self { root: Flex::row().cross_axis_alignment(CrossAxisAlignment::Start) } } fn handle_key_press(&self, key: &KeyCode, data: &mut SynthUIData) { match key { KeyCode::ArrowLeft => { let modified = round_float(data.octave_modifier / 2.0, 3); if modified <= 1.0 / 4.0 { } else { data.octave_modifier = modified } } KeyCode::ArrowRight => { let modified = round_float(data.octave_modifier * 2.0, 3); if modified >= 16.0 { } else { data.octave_modifier = modified } } KeyCode::ArrowUp => {} KeyCode::ArrowDown => {} KeyCode::KeyU => {} _ => match get_note(key) { None => {} Some(freq) => { let mut synth = data.synth.lock().unwrap(); if !synth.playing() { data.event_sender.send(SynthUIEvent::NewNotes).unwrap(); } synth.note_on(freq * data.octave_modifier, *key) } } } } fn handle_key_release(&self, key: &KeyCode, data: &mut SynthUIData) { if let Some(_) = get_note(key) { data.synth.lock().unwrap().note_off(*key); } } fn update_osc(&self, synth: &mut MutexGuard<Synth<i16>>, new: &OscSettings, old: &OscSettings) { if new.volume != old.volume { synth.set_osc_volume(new.id, new.volume as f32); } if new.wave_idx != old.wave_idx { synth.set_waveform(new.id, &WAVEFORMS[new.wave_idx as usize].waveform); } if new.transpose != old.transpose { synth.set_transpose(new.id, new.transpose as i8); } if new.tune != old.tune { synth.set_tune(new.id, new.tune as i8); } if new.unisons != old.unisons { synth.set_unisons(new.id, new.unisons.round() as usize); } if new.env_idx != old.env_idx { synth.set_env(new.id, new.env_idx.round() as usize); } } fn update_env(&self, synth: &mut MutexGuard<Synth<i16>>, new: &EnvSettings, old: &EnvSettings) { if new.attack != old.attack { synth.set_env_parameter(new.id, ADSRParam::Attack(LOG_SCALE_BASE.powf(new.attack).round() as f32)) } if new.decay != old.decay { synth.set_env_parameter(new.id, ADSRParam::Decay(LOG_SCALE_BASE.powf(new.decay).round() as f32)) } if new.sustain != old.sustain { synth.set_env_parameter(new.id, ADSRParam::Sustain(new.sustain as f32)) } if new.release != old.release { synth.set_env_parameter(new.id, ADSRParam::Release(LOG_SCALE_BASE.powf(new.release).round() as f32)) } } } impl Widget<SynthUIData> for SynthUI { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut SynthUIData, env: &Env) { match event { Event::WindowConnected => { if !ctx.is_focused() { ctx.request_focus() } } Event::KeyDown(KeyEvent { code, repeat, .. }) => { if *code == KeyCode::Escape { ctx.window().close() } else if !repeat { self.handle_key_press(code, data) } } Event::KeyUp(KeyEvent { code, repeat, .. }) => { if !repeat { self.handle_key_release(code, data) } } event => self.root.event(ctx, event, data, env), } } fn lifecycle( &mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &SynthUIData, env: &Env, ) { match event { LifeCycle::WidgetAdded => ctx.register_for_focus(), _ => {} } self.root.lifecycle(ctx, event, data, env) } fn update( &mut self, ctx: &mut UpdateCtx, old: &SynthUIData, new: &SynthUIData, env: &Env, ) { if !new.same(old) { if !new.osc1.same(&old.osc1) { let mut synth = new.synth.lock().unwrap(); self.update_osc(&mut synth, &new.osc1, &old.osc1); } if !new.osc2.same(&old.osc2) { let mut synth = new.synth.lock().unwrap(); self.update_osc(&mut synth, &new.osc2, &old.osc2); } if new.volume_db != old.volume_db { new.synth.lock().unwrap().set_volume(new.volume_db as i32).unwrap(); } if !new.env1.same(&old.env1) { let mut synth = new.synth.lock().unwrap(); self.update_env(&mut synth, &new.env1, &old.env1); } if !new.env2.same(&old.env2) { let mut synth = new.synth.lock().unwrap(); self.update_env(&mut synth, &new.env2, &old.env2); } } self.root.update(ctx, old, new, env); } fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &SynthUIData, env: &Env, ) -> Size { self.root.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &SynthUIData, env: &Env) { self.root.paint(ctx, data, env); } } pub struct DefaultSlider { slider: Slider, parameter: DefaultParameter, } impl DefaultSlider { pub fn new(slider: Slider, parameter: DefaultParameter) -> Self { Self { slider, parameter, } } } impl Widget<f64> for DefaultSlider { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut f64, env: &Env) { match event { Event::MouseDown(e) => { if e.button.is_left() && e.mods.ctrl() { match self.parameter { DefaultParameter::EnvAttack | DefaultParameter::EnvDecay | DefaultParameter::EnvRelease => { *data = slider_log(self.parameter.default_val() as f32); }, _ => *data = self.parameter.default_val(), } return } }, _ => {}, } self.slider.event(ctx, event, data, env) } fn lifecycle( &mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &f64, env: &Env, ) { self.slider.lifecycle(ctx, event, data, env) } fn update( &mut self, ctx: &mut UpdateCtx, old: &f64, new: &f64, env: &Env, ) { self.slider.update(ctx, old, new, env) } fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &f64, env: &Env, ) -> Size { self.slider.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &f64, env: &Env) { self.slider.paint(ctx, data, env) } }
use std::sync::MutexGuard; use druid::widget::prelude::*; use druid::widget::{Flex, Slider, CrossAxisAlignment}; use druid::Code as KeyCode; use druid::KeyEvent; use super::{ model::{SynthUIData, SynthUIEvent, OscSettings, EnvSettings}, layout::{slider_log, LOG_SCALE_BASE}, constants::{WAVEFORMS, DefaultParameter}, }; use crate::synth::{Synth, WaveForm, ADSRParam}; fn round_float(f: f32, accuracy: i32) -> f32 { let base = 10f32.powi(accuracy); (f * base).round() / base } fn get_note(key: &KeyCode) -> Option<f32> { let freq = match key { KeyCode::KeyZ => 130.81, KeyCode::KeyS => 138.59, KeyCode::KeyX => 146.83, KeyCode::KeyD => 155.56, KeyCode::KeyC => 164.81, KeyCode::KeyV => 174.61, KeyCode::KeyG => 185.00, KeyCode::KeyB => 196.00, KeyCode::KeyH => 207.65, KeyCode::KeyN => 220.00, KeyCode::KeyJ => 233.08, KeyCode::KeyM => 246.94, _ => return None, }; Some(freq) } #[derive(Clone)] pub struct WaveFormUI { pub name: &'static str, pub waveform: WaveForm, } pub struct SynthUI { pub root: Flex<SynthUIData>, } impl SynthUI { pub fn new() -> Self { Self { root: Flex::row().cross_axis_alignment(CrossAxisAlignment::Start) } } fn handle_key_press(&self, key: &KeyCode, data: &mut SynthUIData) { match key { KeyCode::ArrowLeft => { let modified = round_float(data.octave_modifier / 2.0, 3); if modified <= 1.0 / 4.0 { } else { data.octave_modifier = modified } } KeyCode::ArrowRight => { let modified = round_float(data.octave_modifier * 2.0, 3); if modified >= 16.0 { } else { data.octave_modifier = modified } } KeyCode::ArrowUp => {} KeyCode::ArrowDown => {} KeyCode::KeyU => {} _ => match get_note(key) { None => {} Some(freq) => { let mut synth = data.synth.lock().unwrap(); if !synth.playing() { data.event_sender.send(SynthUIEvent::NewNotes).unwrap(); } synth.note_on(freq * data.octave_modifier, *key) } } } } fn handle_key_release(&self, key: &KeyCode, data: &mut SynthUIData) { if let Some(_) = get_note(key) { data.synth.lock().unwrap().note_off(*key); } } fn update_osc(&self, synth: &mut MutexGuard<Synth<i16>>, new: &OscSettings, old: &OscSettings) { if new.volume != old.volume { synth.set_osc_volume(new.id, new.volume as f32); } if new.wave_idx != old.wave_idx { synth.set_waveform(new.id, &WAVEFORMS[new.wave_idx as usize].waveform); } if new.transpose != old.transpose { synth.set_transpose(new.id, new.transpose as i8); } if new.tune != old.tune { synth.set_tune(new.id, new.tune as i8); } if new.unisons != old.unisons { synth.set_unisons(new.id, new.unisons.round() as usize); } if new.env_idx != old.env_idx { synth.set_env(new.id, new.env_idx.round() as usize); } } fn update_env(&self, synth: &mut MutexGuard<Synth<i16>>, new: &EnvSettings, old: &EnvSettings) {
if new.decay != old.decay { synth.set_env_parameter(new.id, ADSRParam::Decay(LOG_SCALE_BASE.powf(new.decay).round() as f32)) } if new.sustain != old.sustain { synth.set_env_parameter(new.id, ADSRParam::Sustain(new.sustain as f32)) } if new.release != old.release { synth.set_env_parameter(new.id, ADSRParam::Release(LOG_SCALE_BASE.powf(new.release).round() as f32)) } } } impl Widget<SynthUIData> for SynthUI { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut SynthUIData, env: &Env) { match event { Event::WindowConnected => { if !ctx.is_focused() { ctx.request_focus() } } Event::KeyDown(KeyEvent { code, repeat, .. }) => { if *code == KeyCode::Escape { ctx.window().close() } else if !repeat { self.handle_key_press(code, data) } } Event::KeyUp(KeyEvent { code, repeat, .. }) => { if !repeat { self.handle_key_release(code, data) } } event => self.root.event(ctx, event, data, env), } } fn lifecycle( &mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &SynthUIData, env: &Env, ) { match event { LifeCycle::WidgetAdded => ctx.register_for_focus(), _ => {} } self.root.lifecycle(ctx, event, data, env) } fn update( &mut self, ctx: &mut UpdateCtx, old: &SynthUIData, new: &SynthUIData, env: &Env, ) { if !new.same(old) { if !new.osc1.same(&old.osc1) { let mut synth = new.synth.lock().unwrap(); self.update_osc(&mut synth, &new.osc1, &old.osc1); } if !new.osc2.same(&old.osc2) { let mut synth = new.synth.lock().unwrap(); self.update_osc(&mut synth, &new.osc2, &old.osc2); } if new.volume_db != old.volume_db { new.synth.lock().unwrap().set_volume(new.volume_db as i32).unwrap(); } if !new.env1.same(&old.env1) { let mut synth = new.synth.lock().unwrap(); self.update_env(&mut synth, &new.env1, &old.env1); } if !new.env2.same(&old.env2) { let mut synth = new.synth.lock().unwrap(); self.update_env(&mut synth, &new.env2, &old.env2); } } self.root.update(ctx, old, new, env); } fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &SynthUIData, env: &Env, ) -> Size { self.root.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &SynthUIData, env: &Env) { self.root.paint(ctx, data, env); } } pub struct DefaultSlider { slider: Slider, parameter: DefaultParameter, } impl DefaultSlider { pub fn new(slider: Slider, parameter: DefaultParameter) -> Self { Self { slider, parameter, } } } impl Widget<f64> for DefaultSlider { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut f64, env: &Env) { match event { Event::MouseDown(e) => { if e.button.is_left() && e.mods.ctrl() { match self.parameter { DefaultParameter::EnvAttack | DefaultParameter::EnvDecay | DefaultParameter::EnvRelease => { *data = slider_log(self.parameter.default_val() as f32); }, _ => *data = self.parameter.default_val(), } return } }, _ => {}, } self.slider.event(ctx, event, data, env) } fn lifecycle( &mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &f64, env: &Env, ) { self.slider.lifecycle(ctx, event, data, env) } fn update( &mut self, ctx: &mut UpdateCtx, old: &f64, new: &f64, env: &Env, ) { self.slider.update(ctx, old, new, env) } fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &f64, env: &Env, ) -> Size { self.slider.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &f64, env: &Env) { self.slider.paint(ctx, data, env) } }
if new.attack != old.attack { synth.set_env_parameter(new.id, ADSRParam::Attack(LOG_SCALE_BASE.powf(new.attack).round() as f32)) }
if_condition
[ { "content": "pub fn build_ui() -> impl Widget<SynthUIData> {\n\n let mut synth_ui = SynthUI::new();\n\n\n\n synth_ui.root.add_child(Flex::column()\n\n .cross_axis_alignment(CrossAxisAlignment::Center)\n\n .with_child(oscillator_layout(\"Osc1\", SynthUIData::o...
Rust
vendor/dwrote/src/font_face.rs
vcapra1/alacritty
64026e22f889004c04297dfece71b2a65edb7f38
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::cell::UnsafeCell; use std::mem::{self, zeroed}; use std::ptr; use std::slice; use winapi::ctypes::c_void; use winapi::shared::minwindef::{BOOL, FALSE, TRUE}; use winapi::shared::winerror::S_OK; use winapi::um::dcommon::DWRITE_MEASURING_MODE; use winapi::um::dwrite::IDWriteRenderingParams; use winapi::um::dwrite::DWRITE_FONT_FACE_TYPE_TRUETYPE; use winapi::um::dwrite::{IDWriteFontFace, IDWriteFontFile}; use winapi::um::dwrite::{DWRITE_FONT_FACE_TYPE_BITMAP, DWRITE_FONT_FACE_TYPE_CFF}; use winapi::um::dwrite::{DWRITE_FONT_FACE_TYPE_RAW_CFF, DWRITE_FONT_FACE_TYPE_TYPE1}; use winapi::um::dwrite::{DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION, DWRITE_FONT_FACE_TYPE_VECTOR}; use winapi::um::dwrite::{DWRITE_FONT_SIMULATIONS, DWRITE_GLYPH_METRICS}; use winapi::um::dwrite::{DWRITE_GLYPH_OFFSET, DWRITE_MATRIX, DWRITE_RENDERING_MODE}; use winapi::um::dwrite::{DWRITE_RENDERING_MODE_DEFAULT, DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC}; use winapi::um::dwrite_1::IDWriteFontFace1; use winapi::um::dwrite_3::{IDWriteFontFace5, IDWriteFontResource, DWRITE_FONT_AXIS_VALUE}; use wio::com::ComPtr; use super::{DWriteFactory, DefaultDWriteRenderParams, FontFile, FontMetrics}; use crate::com_helpers::Com; use crate::geometry_sink_impl::GeometrySinkImpl; use crate::outline_builder::OutlineBuilder; pub struct FontFace { native: UnsafeCell<ComPtr<IDWriteFontFace>>, face5: UnsafeCell<Option<ComPtr<IDWriteFontFace5>>>, } impl FontFace { pub fn take(native: ComPtr<IDWriteFontFace>) -> FontFace { let cell = UnsafeCell::new(native); FontFace { native: cell, face5: UnsafeCell::new(None), } } pub unsafe fn as_ptr(&self) -> *mut IDWriteFontFace { (*self.native.get()).as_raw() } unsafe fn get_raw_files(&self) -> Vec<*mut IDWriteFontFile> { let mut number_of_files: u32 = 0; let hr = (*self.native.get()).GetFiles(&mut number_of_files, ptr::null_mut()); assert!(hr == 0); let mut file_ptrs: Vec<*mut IDWriteFontFile> = vec![ptr::null_mut(); number_of_files as usize]; let hr = (*self.native.get()).GetFiles(&mut number_of_files, file_ptrs.as_mut_ptr()); assert!(hr == 0); file_ptrs } pub fn get_files(&self) -> Vec<FontFile> { unsafe { let file_ptrs = self.get_raw_files(); file_ptrs .iter() .map(|p| FontFile::take(ComPtr::from_raw(*p))) .collect() } } pub fn create_font_face_with_simulations( &self, simulations: DWRITE_FONT_SIMULATIONS, ) -> FontFace { unsafe { let file_ptrs = self.get_raw_files(); let face_type = (*self.native.get()).GetType(); let face_index = (*self.native.get()).GetIndex(); let mut face: *mut IDWriteFontFace = ptr::null_mut(); let hr = (*DWriteFactory()).CreateFontFace( face_type, file_ptrs.len() as u32, file_ptrs.as_ptr(), face_index, simulations, &mut face, ); for p in file_ptrs { let _ = ComPtr::<IDWriteFontFile>::from_raw(p); } assert!(hr == 0); FontFace::take(ComPtr::from_raw(face)) } } pub fn get_glyph_count(&self) -> u16 { unsafe { (*self.native.get()).GetGlyphCount() } } pub fn metrics(&self) -> FontMetrics { unsafe { let font_1: Option<ComPtr<IDWriteFontFace1>> = (*self.native.get()).cast().ok(); match font_1 { None => { let mut metrics = mem::zeroed(); (*self.native.get()).GetMetrics(&mut metrics); FontMetrics::Metrics0(metrics) } Some(font_1) => { let mut metrics_1 = mem::zeroed(); font_1.GetMetrics(&mut metrics_1); FontMetrics::Metrics1(metrics_1) } } } } pub fn get_glyph_indices(&self, code_points: &[u32]) -> Vec<u16> { unsafe { let mut glyph_indices: Vec<u16> = vec![0; code_points.len()]; let hr = (*self.native.get()).GetGlyphIndices( code_points.as_ptr(), code_points.len() as u32, glyph_indices.as_mut_ptr(), ); assert!(hr == 0); glyph_indices } } pub fn get_design_glyph_metrics( &self, glyph_indices: &[u16], is_sideways: bool, ) -> Vec<DWRITE_GLYPH_METRICS> { unsafe { let mut metrics: Vec<DWRITE_GLYPH_METRICS> = vec![zeroed(); glyph_indices.len()]; let hr = (*self.native.get()).GetDesignGlyphMetrics( glyph_indices.as_ptr(), glyph_indices.len() as u32, metrics.as_mut_ptr(), is_sideways as BOOL, ); assert!(hr == 0); metrics } } pub fn get_gdi_compatible_glyph_metrics( &self, em_size: f32, pixels_per_dip: f32, transform: *const DWRITE_MATRIX, use_gdi_natural: bool, glyph_indices: &[u16], is_sideways: bool, ) -> Vec<DWRITE_GLYPH_METRICS> { unsafe { let mut metrics: Vec<DWRITE_GLYPH_METRICS> = vec![zeroed(); glyph_indices.len()]; let hr = (*self.native.get()).GetGdiCompatibleGlyphMetrics( em_size, pixels_per_dip, transform, use_gdi_natural as BOOL, glyph_indices.as_ptr(), glyph_indices.len() as u32, metrics.as_mut_ptr(), is_sideways as BOOL, ); assert!(hr == 0); metrics } } pub fn get_font_table(&self, opentype_table_tag: u32) -> Option<Vec<u8>> { unsafe { let mut table_data_ptr: *const u8 = ptr::null_mut(); let mut table_size: u32 = 0; let mut table_context: *mut c_void = ptr::null_mut(); let mut exists: BOOL = FALSE; let hr = (*self.native.get()).TryGetFontTable( opentype_table_tag, &mut table_data_ptr as *mut *const _ as *mut *const c_void, &mut table_size, &mut table_context, &mut exists, ); assert!(hr == 0); if exists == FALSE { return None; } let table_bytes = slice::from_raw_parts(table_data_ptr, table_size as usize).to_vec(); (*self.native.get()).ReleaseFontTable(table_context); Some(table_bytes) } } pub fn get_recommended_rendering_mode( &self, em_size: f32, pixels_per_dip: f32, measure_mode: DWRITE_MEASURING_MODE, rendering_params: *mut IDWriteRenderingParams, ) -> DWRITE_RENDERING_MODE { unsafe { let mut render_mode: DWRITE_RENDERING_MODE = DWRITE_RENDERING_MODE_DEFAULT; let hr = (*self.native.get()).GetRecommendedRenderingMode( em_size, pixels_per_dip, measure_mode, rendering_params, &mut render_mode, ); if hr != 0 { return DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC; } render_mode } } pub fn get_recommended_rendering_mode_default_params( &self, em_size: f32, pixels_per_dip: f32, measure_mode: DWRITE_MEASURING_MODE, ) -> DWRITE_RENDERING_MODE { self.get_recommended_rendering_mode( em_size, pixels_per_dip, measure_mode, DefaultDWriteRenderParams(), ) } pub fn get_glyph_run_outline( &self, em_size: f32, glyph_indices: &[u16], glyph_advances: Option<&[f32]>, glyph_offsets: Option<&[DWRITE_GLYPH_OFFSET]>, is_sideways: bool, is_right_to_left: bool, outline_builder: Box<dyn OutlineBuilder>, ) { unsafe { let glyph_advances = match glyph_advances { None => ptr::null(), Some(glyph_advances) => { assert_eq!(glyph_advances.len(), glyph_indices.len()); glyph_advances.as_ptr() } }; let glyph_offsets = match glyph_offsets { None => ptr::null(), Some(glyph_offsets) => { assert_eq!(glyph_offsets.len(), glyph_indices.len()); glyph_offsets.as_ptr() } }; let is_sideways = if is_sideways { TRUE } else { FALSE }; let is_right_to_left = if is_right_to_left { TRUE } else { FALSE }; let geometry_sink = GeometrySinkImpl::new(outline_builder); let geometry_sink = geometry_sink.into_interface(); let hr = (*self.native.get()).GetGlyphRunOutline( em_size, glyph_indices.as_ptr(), glyph_advances, glyph_offsets, glyph_indices.len() as u32, is_sideways, is_right_to_left, geometry_sink, ); assert_eq!(hr, S_OK); } } #[inline] pub fn get_type(&self) -> FontFaceType { unsafe { match (*self.native.get()).GetType() { DWRITE_FONT_FACE_TYPE_CFF => FontFaceType::Cff, DWRITE_FONT_FACE_TYPE_RAW_CFF => FontFaceType::RawCff, DWRITE_FONT_FACE_TYPE_TRUETYPE => FontFaceType::TrueType, DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION => FontFaceType::TrueTypeCollection, DWRITE_FONT_FACE_TYPE_TYPE1 => FontFaceType::Type1, DWRITE_FONT_FACE_TYPE_VECTOR => FontFaceType::Vector, DWRITE_FONT_FACE_TYPE_BITMAP => FontFaceType::Bitmap, _ => FontFaceType::Unknown, } } } #[inline] pub fn get_index(&self) -> u32 { unsafe { (*self.native.get()).GetIndex() } } #[inline] unsafe fn get_face5(&self) -> Option<ComPtr<IDWriteFontFace5>> { if (*self.face5.get()).is_none() { *self.face5.get() = (*self.native.get()).cast().ok() } (*self.face5.get()).clone() } pub fn has_variations(&self) -> bool { unsafe { match self.get_face5() { Some(face5) => face5.HasVariations() == TRUE, None => false, } } } pub fn create_font_face_with_variations( &self, simulations: DWRITE_FONT_SIMULATIONS, axis_values: &[DWRITE_FONT_AXIS_VALUE], ) -> Option<FontFace> { unsafe { if let Some(face5) = self.get_face5() { let mut resource: *mut IDWriteFontResource = ptr::null_mut(); let hr = face5.GetFontResource(&mut resource); if hr == S_OK && !resource.is_null() { let resource = ComPtr::from_raw(resource); let mut var_face: *mut IDWriteFontFace5 = ptr::null_mut(); let hr = resource.CreateFontFace( simulations, axis_values.as_ptr(), axis_values.len() as u32, &mut var_face, ); if hr == S_OK && !var_face.is_null() { let var_face = ComPtr::from_raw(var_face).cast().unwrap(); return Some(FontFace::take(var_face)); } } } None } } } impl Clone for FontFace { fn clone(&self) -> FontFace { unsafe { FontFace { native: UnsafeCell::new((*self.native.get()).clone()), face5: UnsafeCell::new(None), } } } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum FontFaceType { Unknown, Cff, RawCff, TrueType, TrueTypeCollection, Type1, Vector, Bitmap, }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::cell::UnsafeCell; use std::mem::{self, zeroed}; use std::ptr; use std::slice; use winapi::ctypes::c_void; use winapi::shared::minwindef::{BOOL, FALSE, TRUE}; use winapi::shared::winerror::S_OK; use winapi::um::dcommon::DWRITE_MEASURING_MODE; use winapi::um::dwrite::IDWriteRenderingParams; use winapi::um::dwrite::DWRITE_FONT_FACE_TYPE_TRUETYPE; use winapi::um::dwrite::{IDWriteFontFace, IDWriteFontFile}; use winapi::um::dwrite::{DWRITE_FONT_FACE_TYPE_BITMAP, DWRITE_FONT_FACE_TYPE_CFF}; use winapi::um::dwrite::{DWRITE_FONT_FACE_TYPE_RAW_CFF, DWRITE_FONT_FACE_TYPE_TYPE1}; use winapi::um::dwrite::{DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION, DWRITE_FONT_FACE_TYPE_VECTOR}; use winapi::um::dwrite::{DWRITE_FONT_SIMULATIONS, DWRITE_GLYPH_METRICS}; use winapi::um::dwrite::{DWRITE_GLYPH_OFFSET, DWRITE_MATRIX, DWRITE_RENDERING_MODE}; use winapi::um::dwrite::{DWRITE_RENDERING_MODE_DEFAULT, DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC}; use winapi::um::dwrite_1::IDWriteFontFace1; use winapi::um::dwrite_3::{IDWriteFontFace5, IDWriteFontResource, DWRITE_FONT_AXIS_VALUE}; use wio::com::ComPtr; use super::{DWriteFactory, DefaultDWriteRenderParams, FontFile, FontMetrics}; use crate::com_helpers::Com; use crate::geometry_sink_impl::GeometrySinkImpl; use crate::outline_builder::OutlineBuilder; pub struct FontFace { native: UnsafeCell<ComPtr<IDWriteFontFace>>, face5: UnsafeCell<Option<ComPtr<IDWriteFontFace5>>>, } impl FontFace { pub fn take(native: ComPtr<IDWriteFontFace>) -> FontFace { let cell = UnsafeCell::new(native); FontFace { native: cell, face5: UnsafeCell::new(None), } } pub unsafe fn as_ptr(&self) -> *mut IDWriteFontFace { (*self.native.get()).as_raw() } unsafe fn get_raw_files(&self) -> Vec<*mut IDWriteFontFile> { let mut number_of_files: u32 = 0; let hr = (*self.native.get()).GetFiles(&mut number_of_files, ptr::null_mut()); assert!(hr == 0); let mut file_ptrs: Vec<*mut IDWriteFontFile> = vec![ptr::null_mut(); number_of_files as usize]; let hr = (*self.native.get()).GetFiles(&mut number_of_files, file_ptrs.as_mut_ptr()); assert!(hr == 0); file_ptrs } pub fn get_files(&self) -> Vec<FontFile> { unsafe { let file_ptrs = self.get_raw_files(); file_ptrs .iter() .map(|p| FontFile::take(ComPtr::from_raw(*p))) .collect() } } pub fn create_font_face_with_simulations( &self, simulations: DWRITE_FONT_SIMULATIONS, ) -> FontFace { unsafe { let file_ptrs = self.get_raw_files(); let face_type = (*self.native.get()).GetType(); let face_index = (*self.native.get()).GetIndex(); let mut face: *mut IDWriteFontFace = ptr::null_mut(); let hr = (*DWriteFactory()).CreateFontFace( face_type, file_ptrs.len() as u32, file_ptrs.as_ptr(), face_index, simulations, &mut face, ); for p in file_ptrs { let _ = ComPtr::<IDWriteFontFile>::from_raw(p); } assert!(hr == 0); FontFace::take(ComPtr::from_raw(face)) } } pub fn get_glyph_count(&self) -> u16 { unsafe { (*self.native.get()).GetGlyphCount() } } pub fn metrics(&self) -> FontMetrics { unsafe { let font_1: Option<ComPtr<IDWriteFontFace1>> = (*self.native.get()).cast().ok(); match font_1 { None => { let mut metrics = mem::zeroed(); (*self.native.get()).GetMetrics(&mut metrics); FontMetrics::Metrics0(metrics) } Some(font_1) => { let mut metrics_1 = mem::zeroed(); font_1.GetMetrics(&mut metrics_1); FontMetrics::Metrics1(metrics_1) } } } } pub fn get_glyph_indices(&self, code_points: &[u32]) -> Vec<u16> { unsafe { let mut glyph_indices: Vec<u16> = vec![0; code_points.len()]; let hr = (*self.native.get()).GetGlyphIndices( code_points.as_ptr(), code_points.len() as u32, glyph_indices.as_mut_ptr(), ); assert!(hr == 0); glyph_indices } } pub fn get_design_glyph_metrics( &self, glyph_indices: &[u16], is_sideways: bool, ) -> Vec<DWRITE_GLYPH_METRICS> { unsafe { let mut metrics: Vec<DWRITE_GLYPH_METRICS> = vec![zeroed(); glyph_indices.len()]; let hr = (*self.native.get()).GetDesignGlyphMetrics( glyph_indices.as_ptr(), glyph_indices.len() as u32, metrics.as_mut_ptr(), is_sideways as BOOL, ); assert!(hr == 0); metrics } } pub fn get_gdi_compatible_glyph_metrics( &self, em_size: f32, pixels_per_dip: f3
pub fn get_font_table(&self, opentype_table_tag: u32) -> Option<Vec<u8>> { unsafe { let mut table_data_ptr: *const u8 = ptr::null_mut(); let mut table_size: u32 = 0; let mut table_context: *mut c_void = ptr::null_mut(); let mut exists: BOOL = FALSE; let hr = (*self.native.get()).TryGetFontTable( opentype_table_tag, &mut table_data_ptr as *mut *const _ as *mut *const c_void, &mut table_size, &mut table_context, &mut exists, ); assert!(hr == 0); if exists == FALSE { return None; } let table_bytes = slice::from_raw_parts(table_data_ptr, table_size as usize).to_vec(); (*self.native.get()).ReleaseFontTable(table_context); Some(table_bytes) } } pub fn get_recommended_rendering_mode( &self, em_size: f32, pixels_per_dip: f32, measure_mode: DWRITE_MEASURING_MODE, rendering_params: *mut IDWriteRenderingParams, ) -> DWRITE_RENDERING_MODE { unsafe { let mut render_mode: DWRITE_RENDERING_MODE = DWRITE_RENDERING_MODE_DEFAULT; let hr = (*self.native.get()).GetRecommendedRenderingMode( em_size, pixels_per_dip, measure_mode, rendering_params, &mut render_mode, ); if hr != 0 { return DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC; } render_mode } } pub fn get_recommended_rendering_mode_default_params( &self, em_size: f32, pixels_per_dip: f32, measure_mode: DWRITE_MEASURING_MODE, ) -> DWRITE_RENDERING_MODE { self.get_recommended_rendering_mode( em_size, pixels_per_dip, measure_mode, DefaultDWriteRenderParams(), ) } pub fn get_glyph_run_outline( &self, em_size: f32, glyph_indices: &[u16], glyph_advances: Option<&[f32]>, glyph_offsets: Option<&[DWRITE_GLYPH_OFFSET]>, is_sideways: bool, is_right_to_left: bool, outline_builder: Box<dyn OutlineBuilder>, ) { unsafe { let glyph_advances = match glyph_advances { None => ptr::null(), Some(glyph_advances) => { assert_eq!(glyph_advances.len(), glyph_indices.len()); glyph_advances.as_ptr() } }; let glyph_offsets = match glyph_offsets { None => ptr::null(), Some(glyph_offsets) => { assert_eq!(glyph_offsets.len(), glyph_indices.len()); glyph_offsets.as_ptr() } }; let is_sideways = if is_sideways { TRUE } else { FALSE }; let is_right_to_left = if is_right_to_left { TRUE } else { FALSE }; let geometry_sink = GeometrySinkImpl::new(outline_builder); let geometry_sink = geometry_sink.into_interface(); let hr = (*self.native.get()).GetGlyphRunOutline( em_size, glyph_indices.as_ptr(), glyph_advances, glyph_offsets, glyph_indices.len() as u32, is_sideways, is_right_to_left, geometry_sink, ); assert_eq!(hr, S_OK); } } #[inline] pub fn get_type(&self) -> FontFaceType { unsafe { match (*self.native.get()).GetType() { DWRITE_FONT_FACE_TYPE_CFF => FontFaceType::Cff, DWRITE_FONT_FACE_TYPE_RAW_CFF => FontFaceType::RawCff, DWRITE_FONT_FACE_TYPE_TRUETYPE => FontFaceType::TrueType, DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION => FontFaceType::TrueTypeCollection, DWRITE_FONT_FACE_TYPE_TYPE1 => FontFaceType::Type1, DWRITE_FONT_FACE_TYPE_VECTOR => FontFaceType::Vector, DWRITE_FONT_FACE_TYPE_BITMAP => FontFaceType::Bitmap, _ => FontFaceType::Unknown, } } } #[inline] pub fn get_index(&self) -> u32 { unsafe { (*self.native.get()).GetIndex() } } #[inline] unsafe fn get_face5(&self) -> Option<ComPtr<IDWriteFontFace5>> { if (*self.face5.get()).is_none() { *self.face5.get() = (*self.native.get()).cast().ok() } (*self.face5.get()).clone() } pub fn has_variations(&self) -> bool { unsafe { match self.get_face5() { Some(face5) => face5.HasVariations() == TRUE, None => false, } } } pub fn create_font_face_with_variations( &self, simulations: DWRITE_FONT_SIMULATIONS, axis_values: &[DWRITE_FONT_AXIS_VALUE], ) -> Option<FontFace> { unsafe { if let Some(face5) = self.get_face5() { let mut resource: *mut IDWriteFontResource = ptr::null_mut(); let hr = face5.GetFontResource(&mut resource); if hr == S_OK && !resource.is_null() { let resource = ComPtr::from_raw(resource); let mut var_face: *mut IDWriteFontFace5 = ptr::null_mut(); let hr = resource.CreateFontFace( simulations, axis_values.as_ptr(), axis_values.len() as u32, &mut var_face, ); if hr == S_OK && !var_face.is_null() { let var_face = ComPtr::from_raw(var_face).cast().unwrap(); return Some(FontFace::take(var_face)); } } } None } } } impl Clone for FontFace { fn clone(&self) -> FontFace { unsafe { FontFace { native: UnsafeCell::new((*self.native.get()).clone()), face5: UnsafeCell::new(None), } } } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum FontFaceType { Unknown, Cff, RawCff, TrueType, TrueTypeCollection, Type1, Vector, Bitmap, }
2, transform: *const DWRITE_MATRIX, use_gdi_natural: bool, glyph_indices: &[u16], is_sideways: bool, ) -> Vec<DWRITE_GLYPH_METRICS> { unsafe { let mut metrics: Vec<DWRITE_GLYPH_METRICS> = vec![zeroed(); glyph_indices.len()]; let hr = (*self.native.get()).GetGdiCompatibleGlyphMetrics( em_size, pixels_per_dip, transform, use_gdi_natural as BOOL, glyph_indices.as_ptr(), glyph_indices.len() as u32, metrics.as_mut_ptr(), is_sideways as BOOL, ); assert!(hr == 0); metrics } }
function_block-function_prefixed
[]
Rust
src/options/new_Session/tests.rs
hugo-k-m/tmux-session-generator
dcde680cc5f2128004ea94691f6fa17f14ab23de
use super::*; use crate::options::Opts; use lib::{ dir::create_dir, err::ScriptError, produce_script_error, test::{TestObject, TestSessionDir, TestSessionDirGroupScript, TestTmuxHomeDir}, }; use std::fs; #[test] fn create_session_script_success() -> CustomResult<()> { const SESSION_NAME: &str = "new_session"; let content = "test content".to_owned(); let group_option = false; let tsg_test = TestTmuxHomeDir::setup()?; let tsg_home_dir = tsg_test.test_tmuxsg_path; let session_dir = PathBuf::from(&format!("{}/{}", tsg_home_dir.display(), SESSION_NAME)); let script_path_expected = PathBuf::from(&format!("{}/{}.sh", session_dir.display(), SESSION_NAME)); create_session_script(content, SESSION_NAME, tsg_home_dir, group_option)?; assert!(script_path_expected.is_file()); Ok(()) } #[test] fn session_script_already_exists() -> CustomResult<()> { let session_name = "test_session"; let tsg_test = TestSessionDir::setup()?; let session_dir = tsg_test.test_session_path; assert!(create_script(session_dir, session_name).is_err()); Ok(()) } #[test] fn create_session_directory_success() -> CustomResult<()> { let session_name = "new_session".to_owned(); let tsg_test = TestTmuxHomeDir::setup()?; let tsg_home_dir_path = tsg_test.test_tmuxsg_path; let s_dir_expected = PathBuf::from(&format!( "{}/{}", &tsg_home_dir_path.display(), session_name )); create_dir(tsg_home_dir_path, session_name)?; assert!(s_dir_expected.is_dir()); Ok(()) } #[test] fn session_script_content_attach_test() -> CustomResult<()> { let attach_test_session_content = test_session_content( "~".to_owned(), false, None, "attach_test_session".to_owned(), None, None, None, )?; let test_content = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join( "resources/test/script_content_checks/\ session/attach_test_session.sh", ); let expected_test_session_content = fs::read_to_string(test_content)?; assert_eq!(attach_test_session_content, expected_test_session_content); Ok(()) } #[test] fn session_script_content_detach_test() -> CustomResult<()> { let detach_test_session_content = test_session_content( "~".to_owned(), true, None, "detach_test_session".to_owned(), None, None, None, )?; let test_content = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join( "resources/test/script_content_checks/\ session/detach_test_session.sh", ); let expected_test_session_content = fs::read_to_string(test_content)?; assert_eq!(detach_test_session_content, expected_test_session_content); Ok(()) } #[test] fn session_script_content_window_name_test() -> CustomResult<()> { let detach_test_session_content = test_session_content( "~".to_owned(), true, Some("window_name".to_owned()), "window_name_test_session".to_owned(), None, None, None, )?; let test_content = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join( "resources/test/script_content_checks/\ session/name_window_option_test_session.sh", ); let expected_test_session_content = fs::read_to_string(test_content)?; assert_eq!(detach_test_session_content, expected_test_session_content); Ok(()) } #[test] fn session_group_option_script_creation_success() -> CustomResult<()> { let group_option = false; let tsg_test = TestSessionDir::setup()?; let session_dir = tsg_test.test_session_path; let expected_group_script = session_dir.join("__session_group_option.sh"); set_session_group_option(&session_dir, group_option)?; assert!(expected_group_script.is_file()); Ok(()) } #[test] fn group_script_creation_fails_if_exists() -> CustomResult<()> { let group_option = false; let tsg_test = TestSessionDirGroupScript::setup()?; let session_dir = tsg_test.test_session_path; let expected_group_script = session_dir.join("__session_group_option.sh"); assert!(expected_group_script.is_file()); assert!(set_session_group_option(&session_dir, group_option).is_err()); Ok(()) } fn test_session_content( command: String, detach: bool, name_window: Option<String>, session_name: String, target_session: Option<String>, x: Option<usize>, y: Option<usize>, ) -> CustomResult<String> { let error = "Session content related".to_owned(); let detach_test_session = Opts::NewSession { command, detach, name_window, session_name, target_session, x, y, }; let test_session_content = if let Opts::NewSession { command, detach, name_window, session_name, target_session, x, y, } = detach_test_session { session_script_content( &command, &detach, &name_window, &session_name, &target_session, &x, &y, ) } else { produce_script_error!(error); }; Ok(test_session_content) }
use super::*; use crate::options::Opts; use lib::{ dir::create_dir, err::ScriptError, produce_script_error, test::{TestObject, TestSessionDir, TestSessionDirGroupScript, TestTmuxHomeDir}, }; use std::fs; #[test] fn create_session_script_success() -> CustomResult<()> { const SESSION_NAME: &str = "new_session"; let content = "test content".to_owned(); let group_option = false; let tsg_test = TestTmuxHomeDir::setup()?; let tsg_home_dir = tsg_test.test_tmuxsg_path; let session_dir = PathBuf::from(&format!("{}/{}", tsg_home_dir.display(), SESSION_NAME)); let script_path_expected = PathBuf::from(&format!("{}/{}.sh", session_dir.display(), SESSION_NAME)); create_session_script(content, SESSION_NAME, tsg_home_dir, group_option)?; assert!(script_path_expected.is_file()); Ok(()) } #[test] fn session_script_alrea
#[test] fn create_session_directory_success() -> CustomResult<()> { let session_name = "new_session".to_owned(); let tsg_test = TestTmuxHomeDir::setup()?; let tsg_home_dir_path = tsg_test.test_tmuxsg_path; let s_dir_expected = PathBuf::from(&format!( "{}/{}", &tsg_home_dir_path.display(), session_name )); create_dir(tsg_home_dir_path, session_name)?; assert!(s_dir_expected.is_dir()); Ok(()) } #[test] fn session_script_content_attach_test() -> CustomResult<()> { let attach_test_session_content = test_session_content( "~".to_owned(), false, None, "attach_test_session".to_owned(), None, None, None, )?; let test_content = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join( "resources/test/script_content_checks/\ session/attach_test_session.sh", ); let expected_test_session_content = fs::read_to_string(test_content)?; assert_eq!(attach_test_session_content, expected_test_session_content); Ok(()) } #[test] fn session_script_content_detach_test() -> CustomResult<()> { let detach_test_session_content = test_session_content( "~".to_owned(), true, None, "detach_test_session".to_owned(), None, None, None, )?; let test_content = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join( "resources/test/script_content_checks/\ session/detach_test_session.sh", ); let expected_test_session_content = fs::read_to_string(test_content)?; assert_eq!(detach_test_session_content, expected_test_session_content); Ok(()) } #[test] fn session_script_content_window_name_test() -> CustomResult<()> { let detach_test_session_content = test_session_content( "~".to_owned(), true, Some("window_name".to_owned()), "window_name_test_session".to_owned(), None, None, None, )?; let test_content = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join( "resources/test/script_content_checks/\ session/name_window_option_test_session.sh", ); let expected_test_session_content = fs::read_to_string(test_content)?; assert_eq!(detach_test_session_content, expected_test_session_content); Ok(()) } #[test] fn session_group_option_script_creation_success() -> CustomResult<()> { let group_option = false; let tsg_test = TestSessionDir::setup()?; let session_dir = tsg_test.test_session_path; let expected_group_script = session_dir.join("__session_group_option.sh"); set_session_group_option(&session_dir, group_option)?; assert!(expected_group_script.is_file()); Ok(()) } #[test] fn group_script_creation_fails_if_exists() -> CustomResult<()> { let group_option = false; let tsg_test = TestSessionDirGroupScript::setup()?; let session_dir = tsg_test.test_session_path; let expected_group_script = session_dir.join("__session_group_option.sh"); assert!(expected_group_script.is_file()); assert!(set_session_group_option(&session_dir, group_option).is_err()); Ok(()) } fn test_session_content( command: String, detach: bool, name_window: Option<String>, session_name: String, target_session: Option<String>, x: Option<usize>, y: Option<usize>, ) -> CustomResult<String> { let error = "Session content related".to_owned(); let detach_test_session = Opts::NewSession { command, detach, name_window, session_name, target_session, x, y, }; let test_session_content = if let Opts::NewSession { command, detach, name_window, session_name, target_session, x, y, } = detach_test_session { session_script_content( &command, &detach, &name_window, &session_name, &target_session, &x, &y, ) } else { produce_script_error!(error); }; Ok(test_session_content) }
dy_exists() -> CustomResult<()> { let session_name = "test_session"; let tsg_test = TestSessionDir::setup()?; let session_dir = tsg_test.test_session_path; assert!(create_script(session_dir, session_name).is_err()); Ok(()) }
function_block-function_prefixed
[ { "content": "/// Creates the script and opens it in write-only mode.\n\npub fn create_script(session_dir: PathBuf, script_name: &str) -> CustomResult<File> {\n\n let script_path = session_dir.join(&format!(\"{}.sh\", script_name));\n\n\n\n if script_path.is_file() {\n\n produce_script_error!(forma...
Rust
db/tests/unit/collection_items.rs
taritom/bn-api
6fbf05bf426c4ddd3d5f50378ac9b51f3ebf2a3f
use db::dev::TestProject; use db::prelude::*; #[test] fn commit() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); assert_eq!(collection_item1.collectible_id, collectible_id1); assert_eq!(collection_item1.collection_id, collection1.id); } #[test] fn new_collection_item_collision() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1_collectible1 = CollectionItem::create(collection1.id, collectible_id1).commit(conn); let collection_item1_collectible2 = CollectionItem::create(collection1.id, collectible_id2).commit(conn); let collectible1_dup = CollectionItem::create(collection1.id, collectible_id1).commit(conn); assert!(collection_item1_collectible1.is_ok()); assert!(collection_item1_collectible2.is_ok()); assert!(collectible1_dup.is_err()); let er = collectible1_dup.unwrap_err(); assert_eq!(er.code, errors::get_error_message(&ErrorCode::DuplicateKeyError).0); } #[test] fn find() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); let found_item = CollectionItem::find(collection_item1.id, conn).unwrap(); assert_eq!(collection_item1, found_item); } #[test] fn find_for_collection_with_num_owned() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); CollectionItem::create(collection1.id, collectible_id2) .commit(conn) .unwrap(); let found_items = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .number_owned, 2 ); assert_eq!( found_items .iter() .find(|&i| i.collectible_id == collectible_id2) .unwrap() .number_owned, 1 ); } #[test] fn update() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1_collectible1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); let collection_item1_collectible1_clone1 = collection_item1_collectible1.clone(); let collection_item1_collectible1_clone2 = collection_item1_collectible1.clone(); let collection_item1_collectible2 = CollectionItem::create(collection1.id, collectible_id2) .commit(conn) .unwrap(); let update1 = UpdateCollectionItemAttributes { next_collection_item_id: Some(Some(collection_item1_collectible2.id)), }; CollectionItem::update(collection_item1_collectible1, update1, conn).unwrap(); let found_items1 = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items1 .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .next_collection_item_id .unwrap(), collection_item1_collectible2.id ); let update2 = UpdateCollectionItemAttributes { next_collection_item_id: None, }; CollectionItem::update(collection_item1_collectible1_clone1, update2, conn).unwrap(); let found_items2 = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items2 .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .next_collection_item_id .unwrap(), collection_item1_collectible2.id ); let update3 = UpdateCollectionItemAttributes { next_collection_item_id: Some(None), }; CollectionItem::update(collection_item1_collectible1_clone2, update3, conn).unwrap(); let found_items3 = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items3 .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .next_collection_item_id, None ); } #[test] fn destroy() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1_collectible1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); CollectionItem::create(collection1.id, collectible_id2) .commit(conn) .unwrap(); CollectionItem::destroy(collection_item1_collectible1, conn).unwrap(); let found_items = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!(found_items.len(), 1); }
use db::dev::TestProject; use db::prelude::*; #[test] fn commit() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); assert_eq!(collection_item1.collectible_id, collectible_id1); assert_eq!(collection_item1.collection_id, collection1.id); } #[test] fn new_collection_item_collision() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1_collectible1 = CollectionItem::create(collection1.id, collectible_id1).commit(conn); le
#[test] fn find() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); let found_item = CollectionItem::find(collection_item1.id, conn).unwrap(); assert_eq!(collection_item1, found_item); } #[test] fn find_for_collection_with_num_owned() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); CollectionItem::create(collection1.id, collectible_id2) .commit(conn) .unwrap(); let found_items = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .number_owned, 2 ); assert_eq!( found_items .iter() .find(|&i| i.collectible_id == collectible_id2) .unwrap() .number_owned, 1 ); } #[test] fn update() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1_collectible1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); let collection_item1_collectible1_clone1 = collection_item1_collectible1.clone(); let collection_item1_collectible1_clone2 = collection_item1_collectible1.clone(); let collection_item1_collectible2 = CollectionItem::create(collection1.id, collectible_id2) .commit(conn) .unwrap(); let update1 = UpdateCollectionItemAttributes { next_collection_item_id: Some(Some(collection_item1_collectible2.id)), }; CollectionItem::update(collection_item1_collectible1, update1, conn).unwrap(); let found_items1 = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items1 .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .next_collection_item_id .unwrap(), collection_item1_collectible2.id ); let update2 = UpdateCollectionItemAttributes { next_collection_item_id: None, }; CollectionItem::update(collection_item1_collectible1_clone1, update2, conn).unwrap(); let found_items2 = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items2 .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .next_collection_item_id .unwrap(), collection_item1_collectible2.id ); let update3 = UpdateCollectionItemAttributes { next_collection_item_id: Some(None), }; CollectionItem::update(collection_item1_collectible1_clone2, update3, conn).unwrap(); let found_items3 = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items3 .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .next_collection_item_id, None ); } #[test] fn destroy() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1_collectible1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); CollectionItem::create(collection1.id, collectible_id2) .commit(conn) .unwrap(); CollectionItem::destroy(collection_item1_collectible1, conn).unwrap(); let found_items = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!(found_items.len(), 1); }
t collection_item1_collectible2 = CollectionItem::create(collection1.id, collectible_id2).commit(conn); let collectible1_dup = CollectionItem::create(collection1.id, collectible_id1).commit(conn); assert!(collection_item1_collectible1.is_ok()); assert!(collection_item1_collectible2.is_ok()); assert!(collectible1_dup.is_err()); let er = collectible1_dup.unwrap_err(); assert_eq!(er.code, errors::get_error_message(&ErrorCode::DuplicateKeyError).0); }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn commit() {\n\n let project = TestProject::new();\n\n let name = \"Name\";\n\n let connection = project.get_connection();\n\n let venue = Venue::create(name.clone(), None, \"America/Los_Angeles\".into())\n\n .commit(connection)\n\n .unwrap();\n\n let stage...
Rust
ciborium-ll/src/dec.rs
roman-kashitsyn/ciborium
b6d9ae284ece285011f48d7a70456d5d93da0cdc
use super::*; use ciborium_io::Read; #[derive(Debug)] pub enum Error<T> { Io(T), Syntax(usize), } impl<T> From<T> for Error<T> { #[inline] fn from(value: T) -> Self { Self::Io(value) } } pub struct Decoder<R: Read> { reader: R, offset: usize, buffer: Option<Title>, } impl<R: Read> From<R> for Decoder<R> { #[inline] fn from(value: R) -> Self { Self { reader: value, offset: 0, buffer: None, } } } impl<R: Read> Read for Decoder<R> { type Error = R::Error; #[inline] fn read_exact(&mut self, data: &mut [u8]) -> Result<(), Self::Error> { assert!(self.buffer.is_none()); self.reader.read_exact(data)?; self.offset += data.len(); Ok(()) } } impl<R: Read> Decoder<R> { #[inline] fn pull_title(&mut self) -> Result<Title, Error<R::Error>> { if let Some(title) = self.buffer.take() { self.offset += title.1.as_ref().len() + 1; return Ok(title); } let mut prefix = [0u8; 1]; self.read_exact(&mut prefix[..])?; let major = match prefix[0] >> 5 { 0 => Major::Positive, 1 => Major::Negative, 2 => Major::Bytes, 3 => Major::Text, 4 => Major::Array, 5 => Major::Map, 6 => Major::Tag, 7 => Major::Other, _ => unreachable!(), }; let mut minor = match prefix[0] & 0b00011111 { x if x < 24 => Minor::This(x), 24 => Minor::Next1([0; 1]), 25 => Minor::Next2([0; 2]), 26 => Minor::Next4([0; 4]), 27 => Minor::Next8([0; 8]), 31 => Minor::More, _ => return Err(Error::Syntax(self.offset - 1)), }; self.read_exact(minor.as_mut())?; Ok(Title(major, minor)) } #[inline] fn push_title(&mut self, item: Title) { assert!(self.buffer.is_none()); self.buffer = Some(item); self.offset -= item.1.as_ref().len() + 1; } #[inline] pub fn pull(&mut self) -> Result<Header, Error<R::Error>> { let offset = self.offset; self.pull_title()? .try_into() .map_err(|_| Error::Syntax(offset)) } #[inline] pub fn push(&mut self, item: Header) { self.push_title(Title::from(item)) } #[inline] pub fn offset(&mut self) -> usize { self.offset } #[inline] pub fn bytes(&mut self, len: Option<usize>) -> Segments<R, crate::seg::Bytes> { self.push(Header::Bytes(len)); Segments::new(self, |header| match header { Header::Bytes(len) => Ok(len), _ => Err(()), }) } #[inline] pub fn text(&mut self, len: Option<usize>) -> Segments<R, crate::seg::Text> { self.push(Header::Text(len)); Segments::new(self, |header| match header { Header::Text(len) => Ok(len), _ => Err(()), }) } }
use super::*; use ciborium_io::Read; #[derive(Debug)] pub enum Error<T> { Io(T), Syntax(usize), } impl<T> From<T> for Error<T> { #[inline] fn from(value: T) -> Self { Self::Io(value) } } pub struct Decoder<R: Read> { reader: R, offset: usize, buffer: Option<Title>, } impl<R: Read> From<R> for Decoder<R> { #[inline] fn from(value: R) -> Self { Self { reader: value, offset: 0, buffer: None, } } } impl<R: Read> Read for Decoder<R> { type Error = R::Error; #[inline] fn read_exact(&mut self, data: &mut [u8]) -> Result<(), Self::Error> { asse
} impl<R: Read> Decoder<R> { #[inline] fn pull_title(&mut self) -> Result<Title, Error<R::Error>> { if let Some(title) = self.buffer.take() { self.offset += title.1.as_ref().len() + 1; return Ok(title); } let mut prefix = [0u8; 1]; self.read_exact(&mut prefix[..])?; let major = match prefix[0] >> 5 { 0 => Major::Positive, 1 => Major::Negative, 2 => Major::Bytes, 3 => Major::Text, 4 => Major::Array, 5 => Major::Map, 6 => Major::Tag, 7 => Major::Other, _ => unreachable!(), }; let mut minor = match prefix[0] & 0b00011111 { x if x < 24 => Minor::This(x), 24 => Minor::Next1([0; 1]), 25 => Minor::Next2([0; 2]), 26 => Minor::Next4([0; 4]), 27 => Minor::Next8([0; 8]), 31 => Minor::More, _ => return Err(Error::Syntax(self.offset - 1)), }; self.read_exact(minor.as_mut())?; Ok(Title(major, minor)) } #[inline] fn push_title(&mut self, item: Title) { assert!(self.buffer.is_none()); self.buffer = Some(item); self.offset -= item.1.as_ref().len() + 1; } #[inline] pub fn pull(&mut self) -> Result<Header, Error<R::Error>> { let offset = self.offset; self.pull_title()? .try_into() .map_err(|_| Error::Syntax(offset)) } #[inline] pub fn push(&mut self, item: Header) { self.push_title(Title::from(item)) } #[inline] pub fn offset(&mut self) -> usize { self.offset } #[inline] pub fn bytes(&mut self, len: Option<usize>) -> Segments<R, crate::seg::Bytes> { self.push(Header::Bytes(len)); Segments::new(self, |header| match header { Header::Bytes(len) => Ok(len), _ => Err(()), }) } #[inline] pub fn text(&mut self, len: Option<usize>) -> Segments<R, crate::seg::Text> { self.push(Header::Text(len)); Segments::new(self, |header| match header { Header::Text(len) => Ok(len), _ => Err(()), }) } }
rt!(self.buffer.is_none()); self.reader.read_exact(data)?; self.offset += data.len(); Ok(()) }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn from_reader<'de, T: de::Deserialize<'de>, R: Read>(reader: R) -> Result<T, Error<R::Error>>\n\nwhere\n\n R::Error: core::fmt::Debug,\n\n{\n\n let mut scratch = [0; 4096];\n\n\n\n let mut reader = Deserializer {\n\n decoder: reader.into(),\n\n scratch: &mu...
Rust
kimchi/src/tests/lookup.rs
chee-chyuan/proof-systems
b883501b06375da79fc9965c1c17e02a72e9ded7
use super::framework::{print_witness, TestFramework}; use crate::circuits::{ gate::{CircuitGate, GateType}, lookup::{ runtime_tables::{RuntimeTable, RuntimeTableCfg, RuntimeTableSpec}, tables::LookupTable, }, polynomial::COLUMNS, wires::Wire, }; use ark_ff::Zero; use array_init::array_init; use mina_curves::pasta::fp::Fp; fn setup_lookup_proof(use_values_from_table: bool, num_lookups: usize, table_sizes: Vec<usize>) { let lookup_table_values: Vec<Vec<_>> = table_sizes .iter() .map(|size| (0..*size).map(|_| rand::random()).collect()) .collect(); let lookup_tables = lookup_table_values .iter() .enumerate() .map(|(id, lookup_table_values)| { let index_column = (0..lookup_table_values.len() as u64) .map(Into::into) .collect(); LookupTable { id: id as i32, data: vec![index_column, lookup_table_values.clone()], } }) .collect(); let gates = (0..num_lookups) .map(|i| CircuitGate { typ: GateType::Lookup, coeffs: vec![], wires: Wire::new(i), }) .collect(); let witness = { let mut lookup_table_ids = Vec::with_capacity(num_lookups); let mut lookup_indexes: [_; 3] = array_init(|_| Vec::with_capacity(num_lookups)); let mut lookup_values: [_; 3] = array_init(|_| Vec::with_capacity(num_lookups)); let unused = || vec![Fp::zero(); num_lookups]; let num_tables = table_sizes.len(); let mut tables_used = std::collections::HashSet::new(); for _ in 0..num_lookups { let table_id = rand::random::<usize>() % num_tables; tables_used.insert(table_id); let lookup_table_values: &Vec<Fp> = &lookup_table_values[table_id]; lookup_table_ids.push((table_id as u64).into()); for i in 0..3 { let index = rand::random::<usize>() % lookup_table_values.len(); let value = if use_values_from_table { lookup_table_values[index] } else { rand::random() }; lookup_indexes[i].push((index as u64).into()); lookup_values[i].push(value); } } assert!(tables_used.len() >= 2 || table_sizes.len() <= 1); let [lookup_indexes0, lookup_indexes1, lookup_indexes2] = lookup_indexes; let [lookup_values0, lookup_values1, lookup_values2] = lookup_values; [ lookup_table_ids, lookup_indexes0, lookup_values0, lookup_indexes1, lookup_values1, lookup_indexes2, lookup_values2, unused(), unused(), unused(), unused(), unused(), unused(), unused(), unused(), ] }; TestFramework::default() .gates(gates) .witness(witness) .lookup_tables(lookup_tables) .setup() .prove_and_verify(); } #[test] fn lookup_gate_proving_works() { setup_lookup_proof(true, 500, vec![256]) } #[test] #[should_panic] fn lookup_gate_rejects_bad_lookups() { setup_lookup_proof(false, 500, vec![256]) } #[test] fn lookup_gate_proving_works_multiple_tables() { setup_lookup_proof(true, 500, vec![100, 50, 50, 2, 2]) } #[test] #[should_panic] fn lookup_gate_rejects_bad_lookups_multiple_tables() { setup_lookup_proof(false, 500, vec![100, 50, 50, 2, 2]) } fn runtime_table(num: usize, indexed: bool) { let mut runtime_tables_setup = vec![]; for table_id in 0..num { let cfg = if indexed { RuntimeTableCfg::Indexed(RuntimeTableSpec { id: table_id as i32, len: 5, }) } else { RuntimeTableCfg::Custom { id: table_id as i32, first_column: [8u32, 9, 8, 7, 1].into_iter().map(Into::into).collect(), } }; runtime_tables_setup.push(cfg); } let data: Vec<Fp> = [0u32, 2, 3, 4, 5].into_iter().map(Into::into).collect(); let runtime_tables: Vec<RuntimeTable<Fp>> = runtime_tables_setup .iter() .map(|cfg| RuntimeTable { id: cfg.id(), data: data.clone(), }) .collect(); let mut gates = vec![]; for row in 0..20 { gates.push(CircuitGate { typ: GateType::Lookup, wires: Wire::new(row), coeffs: vec![], }); } let witness = { let mut cols: [_; COLUMNS] = array_init(|_col| vec![Fp::zero(); gates.len()]); let (lookup_cols, _rest) = cols.split_at_mut(7); for row in 0..20 { lookup_cols[0][row] = 0u32.into(); let lookup_cols = &mut lookup_cols[1..]; for chunk in lookup_cols.chunks_mut(2) { chunk[0][row] = if indexed { 1u32.into() } else { 9u32.into() }; chunk[1][row] = 2u32.into(); } } cols }; print_witness(&witness, 0, 20); TestFramework::default() .gates(gates) .witness(witness) .runtime_tables_setup(runtime_tables_setup) .setup() .runtime_tables(runtime_tables) .prove_and_verify(); } #[test] fn test_indexed_runtime_table() { runtime_table(5, true); } #[test] fn test_custom_runtime_table() { runtime_table(5, false); }
use super::framework::{print_witness, TestFramework}; use crate::circuits::{ gate::{CircuitGate, GateType}, lookup::{ runtime_tables::{RuntimeTable, RuntimeTableCfg, RuntimeTableSpec}, tables::LookupTable, }, polynomial::COLUMNS, wires::Wire, }; use ark_ff::Zero; use array_init::array_init; use mina_curves::pasta::fp::Fp; fn setup_lookup_proof(use_values_from_table: bool, num_lookups: usize, table_sizes: Vec<usize>) { let lookup_table_values: Vec<Vec<_>> = table_sizes .iter() .map(|size| (0..*size).map(|_| rand::random()).collect()) .collect(); let lookup_tables = lookup_table_values .iter() .enumerate() .map(|(id, lookup_table_values)| { let index_column = (0..lookup_table_values.len() as u64) .map(Into::into) .collect(); LookupTable { id: id as i32, data: vec![index_column, lookup_table_values.clone()], } }) .collect(); let gates = (0..num_lookups) .map(|i| CircuitGate { typ: GateType::Lookup, coeffs: vec![], wires: Wire::new(i), }) .collect(); let witness = { let mut lookup_table_ids = Vec::with_capacity(num_lookups); let mut lookup_indexes: [_; 3] = array_init(|_| Vec::with_capacity(num_lookups)); let mut lookup_values: [_; 3] = array_init(|_| Vec::with_capacity(num_lookups)); let unused = || vec![Fp::zero(); num_lookups]; let num_tables = table_sizes.len(); let mut tables_used = std::collections::HashSet::new(); for _ in 0..num_lookups { let table_id = rand::random::<usize>() % num_tables; tables_used.insert(table_id); let lookup_table_values: &Vec<Fp> = &lookup_table_values[table_id]; lookup_table_ids.push((table_id as u64).into()); for i in 0..3 { let index = rand::random::<usize>() % lookup_table_values.len(); let value = if use_values_from_table { lookup_table_values[index] } else { rand::random() }; lookup_indexes[i].push((index as u64).into()); lookup_values[i].push(value); } } assert!(tables_used.len() >= 2 || table_sizes.len() <= 1); let [lookup_indexes0, lookup_indexes1, lookup_indexes2] = lookup_indexes; let [lookup_values0, lookup_values1, lookup_values2] = lookup_values; [ lookup_table_ids, lookup_indexes0, lookup_values0, lookup_indexes1, lookup_values1, lookup_indexes2, lookup_values2, unused(), unused(), unused(), unused(), unused(), unused(), unused(), unused(), ] }; TestFramework::default() .gates(gates) .witness(witness) .lookup_tables(lookup_tables) .setup() .prove_and_verify(); } #[test] fn lookup_gate_proving_works() { setup_lookup_proof(true, 500, vec![256]) } #[test] #[should_panic] fn lookup_gate_rejects_bad_lookups() { setup_lookup_proof(false, 500, vec![256]) } #[test] fn lookup_gate_proving_works_multiple_tables() { setup_lookup_proof(true, 500, vec![100, 50, 50, 2, 2]) } #[test] #[should_panic] fn lookup_gate_rejects_bad_lookups_multiple_tables() { setup_lookup_proof(false, 500, vec![100, 50, 50, 2, 2]) } fn runtime_table(num: usize, indexed: bool) { let mut runtime_tables_setup = vec![]; for table_id in 0..num { let cfg = if indexed { RuntimeTableCfg::Indexed(RuntimeTableSpec { id: table_id as i32, len: 5, }) } else { RuntimeTableCfg::Custom { id: table_id as i3
#[test] fn test_indexed_runtime_table() { runtime_table(5, true); } #[test] fn test_custom_runtime_table() { runtime_table(5, false); }
2, first_column: [8u32, 9, 8, 7, 1].into_iter().map(Into::into).collect(), } }; runtime_tables_setup.push(cfg); } let data: Vec<Fp> = [0u32, 2, 3, 4, 5].into_iter().map(Into::into).collect(); let runtime_tables: Vec<RuntimeTable<Fp>> = runtime_tables_setup .iter() .map(|cfg| RuntimeTable { id: cfg.id(), data: data.clone(), }) .collect(); let mut gates = vec![]; for row in 0..20 { gates.push(CircuitGate { typ: GateType::Lookup, wires: Wire::new(row), coeffs: vec![], }); } let witness = { let mut cols: [_; COLUMNS] = array_init(|_col| vec![Fp::zero(); gates.len()]); let (lookup_cols, _rest) = cols.split_at_mut(7); for row in 0..20 { lookup_cols[0][row] = 0u32.into(); let lookup_cols = &mut lookup_cols[1..]; for chunk in lookup_cols.chunks_mut(2) { chunk[0][row] = if indexed { 1u32.into() } else { 9u32.into() }; chunk[1][row] = 2u32.into(); } } cols }; print_witness(&witness, 0, 20); TestFramework::default() .gates(gates) .witness(witness) .runtime_tables_setup(runtime_tables_setup) .setup() .runtime_tables(runtime_tables) .prove_and_verify(); }
function_block-function_prefixed
[ { "content": "fn chacha_setup_bad_lookup(table_id: i32) {\n\n // circuit gates: one 'real' ChaCha0 and one 'fake' one.\n\n let gates = vec![\n\n GateType::ChaCha0,\n\n GateType::Zero,\n\n GateType::ChaCha0,\n\n GateType::Zero,\n\n ];\n\n let gates: Vec<CircuitGate<Fp>> = ...
Rust
crates/notion-core/src/distro/yarn.rs
acorncom/notion
6458f41a8c32b2e0618a6c4dd8eb5eca31ba0cd7
use std::fs::{rename, File}; use std::path::PathBuf; use std::string::ToString; use super::{Distro, Fetched}; use archive::{Archive, Tarball}; use distro::error::DownloadError; use distro::DistroVersion; use fs::ensure_containing_dir_exists; use inventory::YarnCollection; use path; use style::{progress_bar, Action}; use tool::ToolSpec; use version::VersionSpec; use notion_fail::{Fallible, ResultExt}; use semver::Version; #[cfg(feature = "mock-network")] use mockito; cfg_if! { if #[cfg(feature = "mock-network")] { fn public_yarn_server_root() -> String { mockito::SERVER_URL.to_string() } } else { fn public_yarn_server_root() -> String { "https://github.com/yarnpkg/yarn/releases/download".to_string() } } } pub struct YarnDistro { archive: Box<Archive>, version: Version, } fn distro_is_valid(file: &PathBuf) -> bool { if file.is_file() { if let Ok(file) = File::open(file) { match Tarball::load(file) { Ok(_) => return true, Err(_) => return false, } } } false } impl Distro for YarnDistro { fn public(version: Version) -> Fallible<Self> { let version_str = version.to_string(); let distro_file_name = path::yarn_distro_file_name(&version_str); let url = format!( "{}/v{}/{}", public_yarn_server_root(), version_str, distro_file_name ); YarnDistro::remote(version, &url) } fn remote(version: Version, url: &str) -> Fallible<Self> { let distro_file_name = path::yarn_distro_file_name(&version.to_string()); let distro_file = path::yarn_inventory_dir()?.join(&distro_file_name); if distro_is_valid(&distro_file) { return YarnDistro::local(version, File::open(distro_file).unknown()?); } ensure_containing_dir_exists(&distro_file)?; Ok(YarnDistro { archive: Tarball::fetch(url, &distro_file).with_context(DownloadError::for_tool( ToolSpec::Yarn(VersionSpec::exact(&version)), url.to_string(), ))?, version: version, }) } fn local(version: Version, file: File) -> Fallible<Self> { Ok(YarnDistro { archive: Tarball::load(file).unknown()?, version: version, }) } fn version(&self) -> &Version { &self.version } fn fetch(self, collection: &YarnCollection) -> Fallible<Fetched<DistroVersion>> { if collection.contains(&self.version) { return Ok(Fetched::Already(DistroVersion::Yarn(self.version))); } let dest = path::yarn_image_root_dir()?; let bar = progress_bar( Action::Fetching, &format!("v{}", self.version), self.archive .uncompressed_size() .unwrap_or(self.archive.compressed_size()), ); self.archive .unpack(&dest, &mut |_, read| { bar.inc(read as u64); }) .unknown()?; let version_string = self.version.to_string(); rename( dest.join(path::yarn_archive_root_dir_name(&version_string)), path::yarn_image_dir(&version_string)?, ) .unknown()?; bar.finish_and_clear(); Ok(Fetched::Now(DistroVersion::Yarn(self.version))) } }
use std::fs::{rename, File}; use std::path::PathBuf; use std::string::ToString; use super::{Distro, Fetched}; use archive::{Archive, Tarball}; use distro::error::DownloadError; use distro::DistroVersion; use fs::ensure_containing_dir_exists; use inventory::YarnCollection; use path; use style::{progress_bar, Action}; use tool::ToolSpec; use version::VersionSpec; use notion_fail::{Fallible, ResultExt}; use semver::Version; #[cfg(feature = "mock-network")] use mockito; cfg_if! { if #[cfg(feature = "mock-network")] { fn public_yarn_server_root() -> String { mockito::SERVER_URL.to_string() } } else { fn public_yarn_server_root() -> String { "https://github.com/yarnpkg/yarn/releases/download".to_string() } } } pub struct YarnDistro { archive: Box<Archive>, version: Version, } fn distro_is_valid(file: &PathBuf) -> bool { if file.is_file() { if let Ok(file) = File::open(file) { match Tarball::load(file) { Ok(_) => return true, Err(_) => return false, } } } false } impl Distro for YarnDistro { fn public(version: Version) -> Fallible<Self> { let version_str = version.to_string(); let distro_file_name = path::yarn_distro_file_name(&version_str); let url = fo
fn remote(version: Version, url: &str) -> Fallible<Self> { let distro_file_name = path::yarn_distro_file_name(&version.to_string()); let distro_file = path::yarn_inventory_dir()?.join(&distro_file_name); if distro_is_valid(&distro_file) { return YarnDistro::local(version, File::open(distro_file).unknown()?); } ensure_containing_dir_exists(&distro_file)?; Ok(YarnDistro { archive: Tarball::fetch(url, &distro_file).with_context(DownloadError::for_tool( ToolSpec::Yarn(VersionSpec::exact(&version)), url.to_string(), ))?, version: version, }) } fn local(version: Version, file: File) -> Fallible<Self> { Ok(YarnDistro { archive: Tarball::load(file).unknown()?, version: version, }) } fn version(&self) -> &Version { &self.version } fn fetch(self, collection: &YarnCollection) -> Fallible<Fetched<DistroVersion>> { if collection.contains(&self.version) { return Ok(Fetched::Already(DistroVersion::Yarn(self.version))); } let dest = path::yarn_image_root_dir()?; let bar = progress_bar( Action::Fetching, &format!("v{}", self.version), self.archive .uncompressed_size() .unwrap_or(self.archive.compressed_size()), ); self.archive .unpack(&dest, &mut |_, read| { bar.inc(read as u64); }) .unknown()?; let version_string = self.version.to_string(); rename( dest.join(path::yarn_archive_root_dir_name(&version_string)), path::yarn_image_dir(&version_string)?, ) .unknown()?; bar.finish_and_clear(); Ok(Fetched::Now(DistroVersion::Yarn(self.version))) } }
rmat!( "{}/v{}/{}", public_yarn_server_root(), version_str, distro_file_name ); YarnDistro::remote(version, &url) }
function_block-function_prefixed
[ { "content": "pub fn yarn_distro_file_name(version: &str) -> String {\n\n format!(\"{}.tar.gz\", yarn_archive_root_dir_name(version))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 0, "score": 365902.2436720986 }, { "content": "pub fn node_distro_file_name(version...
Rust
src/clock_gettime.rs
GoCodeIT-Inc/cpu-time
d36927e013565bd3cf1a06813e45e764558cf30a
use std::io::{Result, Error}; use std::marker::PhantomData; use std::rc::Rc; use std::time::Duration; use libc::{clock_gettime, timespec}; use libc::{CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID}; #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] pub struct ProcessTime(Duration); #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] pub struct ThreadTime( Duration, PhantomData<Rc<()>>, ); impl ProcessTime { pub fn try_now() -> Result<Self> { let mut time = timespec { tv_sec: 0, tv_nsec: 0, }; if unsafe { clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &mut time) } == -1 { return Err(Error::last_os_error()); } Ok(ProcessTime(Duration::new( time.tv_sec as u64, time.tv_nsec as u32, ))) } pub fn now() -> Self { Self::try_now().expect("CLOCK_PROCESS_CPUTIME_ID unsupported") } pub fn try_elapsed(&self) -> Result<Duration> { Ok(Self::try_now()?.duration_since(*self)) } pub fn elapsed(&self) -> Duration { Self::now().duration_since(*self) } pub fn duration_since(&self, timestamp: Self) -> Duration { self.0 - timestamp.0 } pub fn as_duration(&self) -> Duration { self.0 } } impl ThreadTime { pub fn try_now() -> Result<Self> { let mut time = timespec { tv_sec: 0, tv_nsec: 0, }; if unsafe { clock_gettime(CLOCK_THREAD_CPUTIME_ID, &mut time) } == -1 { return Err(Error::last_os_error()); } Ok(ThreadTime( Duration::new(time.tv_sec as u64, time.tv_nsec as u32), PhantomData, )) } pub fn now() -> Self { Self::try_now().expect("CLOCK_PROCESS_CPUTIME_ID unsupported") } pub fn try_elapsed(&self) -> Result<Duration> { Ok(ThreadTime::try_now()?.duration_since(*self)) } pub fn elapsed(&self) -> Duration { Self::now().duration_since(*self) } pub fn duration_since(&self, timestamp: ThreadTime) -> Duration { self.0 - timestamp.0 } pub fn as_duration(&self) -> Duration { self.0 } }
use std::io::{Result, Error}; use std::marker::PhantomData; use std::rc::Rc; use std::time::Duration; use libc::{clock_gettime, timespec}; use libc::{CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID}; #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] pub struct ProcessTime(Duration); #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] pub struct ThreadTime( Duration, PhantomData<Rc<()>>, ); impl ProcessTime { pub fn try_now() -> Result<Self> { let mut time = times
pub fn now() -> Self { Self::try_now().expect("CLOCK_PROCESS_CPUTIME_ID unsupported") } pub fn try_elapsed(&self) -> Result<Duration> { Ok(Self::try_now()?.duration_since(*self)) } pub fn elapsed(&self) -> Duration { Self::now().duration_since(*self) } pub fn duration_since(&self, timestamp: Self) -> Duration { self.0 - timestamp.0 } pub fn as_duration(&self) -> Duration { self.0 } } impl ThreadTime { pub fn try_now() -> Result<Self> { let mut time = timespec { tv_sec: 0, tv_nsec: 0, }; if unsafe { clock_gettime(CLOCK_THREAD_CPUTIME_ID, &mut time) } == -1 { return Err(Error::last_os_error()); } Ok(ThreadTime( Duration::new(time.tv_sec as u64, time.tv_nsec as u32), PhantomData, )) } pub fn now() -> Self { Self::try_now().expect("CLOCK_PROCESS_CPUTIME_ID unsupported") } pub fn try_elapsed(&self) -> Result<Duration> { Ok(ThreadTime::try_now()?.duration_since(*self)) } pub fn elapsed(&self) -> Duration { Self::now().duration_since(*self) } pub fn duration_since(&self, timestamp: ThreadTime) -> Duration { self.0 - timestamp.0 } pub fn as_duration(&self) -> Duration { self.0 } }
pec { tv_sec: 0, tv_nsec: 0, }; if unsafe { clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &mut time) } == -1 { return Err(Error::last_os_error()); } Ok(ProcessTime(Duration::new( time.tv_sec as u64, time.tv_nsec as u32, ))) }
function_block-function_prefixed
[ { "content": "fn to_duration(kernel_time: FILETIME, user_time: FILETIME) -> Duration {\n\n // resolution: 100ns\n\n let kns100 = ((kernel_time.dwHighDateTime as u64) << 32) + kernel_time.dwLowDateTime as u64;\n\n let uns100 = ((user_time.dwHighDateTime as u64) << 32) + user_time.dwLowDateTime as u64;\n...
Rust
cli/src/opts.rs
djKooks/Viceroy
6462271f1c9176f79ac059cc87bfdde61d65ac62
use { std::net::{IpAddr, Ipv4Addr}, std::{ net::SocketAddr, path::{Path, PathBuf}, }, structopt::StructOpt, viceroy_lib::Error, }; #[derive(Debug, StructOpt)] #[structopt(name = "viceroy", author)] pub struct Opts { #[structopt(long = "addr")] socket_addr: Option<SocketAddr>, #[structopt(parse(try_from_str = check_module))] input: PathBuf, #[structopt(short = "C", long = "config")] config_path: Option<PathBuf>, #[structopt(long = "log-stdout")] log_stdout: bool, #[structopt(long = "log-stderr")] log_stderr: bool, #[structopt(short = "v", parse(from_occurrences))] verbosity: usize, } impl Opts { pub fn addr(&self) -> SocketAddr { self.socket_addr .unwrap_or_else(|| SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7878)) } pub fn input(&self) -> &Path { self.input.as_ref() } pub fn config_path(&self) -> Option<&Path> { self.config_path.as_deref() } pub fn log_stdout(&self) -> bool { self.log_stdout } pub fn log_stderr(&self) -> bool { self.log_stderr } pub fn verbosity(&self) -> usize { self.verbosity } } fn check_module(s: &str) -> Result<PathBuf, Error> { let path = PathBuf::from(s); let contents = std::fs::read(&path)?; match wat::parse_bytes(&contents) { Ok(_) => Ok(path), _ => Err(Error::FileFormat), } } #[cfg(test)] mod opts_tests { use { super::Opts, std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, std::path::PathBuf, structopt::{ clap::{Error, ErrorKind}, StructOpt, }, }; fn test_file(name: &str) -> String { let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("tests") .join("wasm"); path.push(name); assert!(path.exists(), "test file does not exist"); path.into_os_string().into_string().unwrap() } type TestResult = Result<(), anyhow::Error>; #[test] fn default_addr_works() -> TestResult { let empty_args = &["dummy-program-name", &test_file("minimal.wat")]; let opts = Opts::from_iter_safe(empty_args)?; let expected = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7878); assert_eq!(opts.addr(), expected); Ok(()) } #[test] fn invalid_addrs_are_rejected() -> TestResult { let args_with_bad_addr = &[ "dummy-program-name", "--addr", "999.0.0.1:7878", &test_file("minimal.wat"), ]; match Opts::from_iter_safe(args_with_bad_addr) { Err(Error { kind: ErrorKind::ValueValidation, message, .. }) if message.contains("invalid IP address syntax") => Ok(()), res => panic!("unexpected result: {:?}", res), } } #[test] fn ipv6_addrs_are_accepted() -> TestResult { let args_with_ipv6_addr = &[ "dummy-program-name", "--addr", "[::1]:7878", &test_file("minimal.wat"), ]; let opts = Opts::from_iter_safe(args_with_ipv6_addr)?; let addr_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); let expected = SocketAddr::new(addr_v6, 7878); assert_eq!(opts.addr(), expected); Ok(()) } #[test] fn nonexistent_file_is_rejected() -> TestResult { let args_with_nonexistent_file = &["dummy-program-name", "path/to/a/nonexistent/file"]; match Opts::from_iter_safe(args_with_nonexistent_file) { Err(Error { kind: ErrorKind::ValueValidation, message, .. }) if message.contains("No such file or directory") || message.contains("cannot find the path specified") => { Ok(()) } res => panic!("unexpected result: {:?}", res), } } #[test] fn invalid_file_is_rejected() -> TestResult { let args_with_invalid_file = &["dummy-program-name", &test_file("invalid.wat")]; let expected_msg = format!("{}", viceroy_lib::Error::FileFormat); match Opts::from_iter_safe(args_with_invalid_file) { Err(Error { kind: ErrorKind::ValueValidation, message, .. }) if message.contains(&expected_msg) => Ok(()), res => panic!("unexpected result: {:?}", res), } } #[test] fn text_format_is_accepted() -> TestResult { let args = &["dummy-program-name", &test_file("minimal.wat")]; match Opts::from_iter_safe(args) { Ok(_) => Ok(()), res => panic!("unexpected result: {:?}", res), } } #[test] fn binary_format_is_accepted() -> TestResult { let args = &["dummy-program-name", &test_file("minimal.wasm")]; match Opts::from_iter_safe(args) { Ok(_) => Ok(()), res => panic!("unexpected result: {:?}", res), } } }
use { std::net::{IpAddr, Ipv4Addr}, std::{ net::SocketAddr, path::{Path, PathBuf}, }, structopt::StructOpt, viceroy_lib::Error, }; #[derive(Debug, StructOpt)] #[structopt(name = "viceroy", author)] pub struct Opts { #[structopt(long = "addr")] socket_addr: Option<SocketAddr>, #[structopt(parse(try_from_str = check_module))] input: PathBuf, #[structopt(short = "C", long = "config")] config_path: Option<PathBuf>, #[structopt(long = "log-stdout")] log_stdout: bool, #[structopt(long = "log-stderr")] log_stderr: bool, #[structopt(short = "v", parse(from_occurrences))] verbosity: usize, } impl Opts { pub fn addr(&self) -> SocketAddr { self.socket_addr .unwrap_or_else(|| SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7878)) } pub fn input(&self) -> &Path { self.input.as_ref() } pub fn config_path(&self) -> Option<&Path> { self.config_path.as_deref() } pub fn log_stdout(&self) -> bool { self.log_stdout } pub fn log_stderr(&self) -> bool { self.log_stderr } pub fn verbosity(&self) -> usize { self.verbosity } } fn check_module(s: &str) -> Result<PathBuf, Error> { let path = PathBuf::from(s); let contents = std::fs::read(&path)?; match wat::parse_bytes(&contents) { Ok(_) => Ok(path), _ => Err(Error::FileFormat), } } #[cfg(test)] mod opts_tests { use { super::Opts, std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, std::path::PathBuf, structopt::{ clap::{Error, ErrorKind}, StructOpt, }, }; fn test_file(name: &str) -> String { let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("tests") .join("wasm"); path.push(name); assert!(path.exists(), "test file does not exist"); path.into_os_string().into_string().unwrap() } type TestResult = Result<(), anyhow::Error>; #[test] fn default_addr_works() -> TestResult { let empty_args = &["dummy-program-name", &test_file("minimal.wat")]; let opts = Opts::from_iter_safe(empty_args)?; let expected = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7878); assert_eq!(opts.addr(), expected); Ok(()) } #[test] fn invalid_addrs_are_rejected() -> TestResult { let args_with_bad_addr = &[ "dummy-program-name", "--addr", "999.0.0.1:7878", &test_file("minimal.wat"), ]; match Opts::from_iter_safe(args_with_bad_addr) { Err(Error { kind: ErrorKind::ValueValidation, message, .. }) if message.contains("invalid IP address syntax") => Ok(()), res => panic!("unexpected result: {:?}", res), } } #[test] fn ipv6_addrs_are_accepted() -> TestResult { let args_with_ipv6_addr = &[ "dummy-program-name", "--addr", "[::1]:7878", &test_file("minimal.wat"), ]; let opts = Opts::from_iter_safe(args_with_ipv6_addr)?; let addr_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); let expected = SocketAddr::new(addr_v6, 7878); assert_eq!(opts.addr(), expected); Ok(()) } #[test] fn nonexistent_file_is_rejected() -> TestResult { let args_with_nonexistent_file = &["dummy-program-name", "path/to/a/nonexistent/file"]; match Opts::from_iter_safe(args_with_nonexistent_file) { Err(Error { kind: ErrorKind::ValueValidation, message, .. }) if message.contains("No such file or directory") || message.contains("cannot find the path specified") => { Ok(()) } res => panic!("unexpected result: {:?}", res), } } #[test] fn invalid_file_is_rejected() -> TestResult { let args_with_invalid_file = &["dummy-program-name", &test_file("invalid.wat")]; let expected_msg = format!("{}", viceroy_lib::Error::FileFormat); match Opts::from_iter_safe(args_with_invalid_file) { Err(Error { kind: ErrorKind::ValueValidation, message, .. }) if message.contains(&expected_msg) => Ok(()), res => panic!("unexpected result: {:?}", res), } } #[test] fn text_format_is_accepted() -> TestResult { let arg
#[test] fn binary_format_is_accepted() -> TestResult { let args = &["dummy-program-name", &test_file("minimal.wasm")]; match Opts::from_iter_safe(args) { Ok(_) => Ok(()), res => panic!("unexpected result: {:?}", res), } } }
s = &["dummy-program-name", &test_file("minimal.wat")]; match Opts::from_iter_safe(args) { Ok(_) => Ok(()), res => panic!("unexpected result: {:?}", res), } }
function_block-function_prefixed
[]
Rust
src/xor_repair.rs
sc2021anonym/slp-ec
e8afdff36311f4897f73b4e6c1593b8211e10282
use crate::bitmatrix::*; use crate::fast_repair::SortOrder; use crate::repair::{bitvec_distance, bitvec_xor}; use crate::slp::*; use crate::*; fn replace_by(m: &mut SLP, a: usize, b: usize, v: usize) { for i in 0..m.height() { if m[i][a] && m[i][b] { m[i][a] = false; m[i][b] = false; m[i][v] = true; } } } fn count_occurences2(i: usize, j: usize, slp: &SLP) -> usize { let mut count = 0; for def in 0..slp.height() { if slp[def][i] && slp[def][j] { count += 1 } } count } fn gen_forward_iter(start: usize, end: usize) -> Vec<usize> { (start..end).collect() } fn gen_rev_iter(start: usize, end: usize) -> Vec<usize> { (start..end).rev().collect() } fn build_syntax( valuation: &SLP, goal: &[bool], gen_iter: fn(usize, usize) -> Vec<usize>, ) -> (Vec<bool>, Vec<bool>) { let mut depends: Vec<bool> = vec![false; valuation.height() + valuation.num_of_original_constants()]; let mut rest = goal.to_vec(); loop { let mut which_var = None; let mut current_min = popcount(&rest); for var in gen_iter(0, valuation.height()) { let value = &valuation[var]; let count = bitvec_distance(&value, &rest); if count < current_min { which_var = Some(var); current_min = count; } } if let Some(var) = which_var { depends[valuation.num_of_original_constants() + var] = true; rest = bitvec_xor(&rest, &valuation[var]); } else { for idx in 0..rest.len() { if rest[idx] { depends[idx] = true; } } break; } } (depends, rest) } fn xor_pair_finder( valuation: &SLP, slp: &SLP, program: &mut SLP, gen_iter: fn(usize, usize) -> Vec<usize>, order: &SortOrder, ) -> Option<(Term, Term)> { use std::cmp::Ordering; let mut count_max = 0; let mut candidates = Vec::new(); for i in 0..slp.num_of_variables() { let goal = &slp[i]; let (depends, _) = build_syntax(valuation, &goal, gen_iter); if popcount(&depends) < popcount(&program[i]) { program[i] = depends; } } for i in 0..program.width() { for j in i + 1..program.width() { let count = count_occurences2(i, j, &program); match count_max.cmp(&count) { Ordering::Equal => { candidates.push((i, j)); } Ordering::Less => { candidates = vec![(i, j)]; count_max = count; } _ => {} } } } match order { SortOrder::LexSmall => { candidates.sort_by(|(a1, a2), (b1, b2)| a1.cmp(b1).then(a2.cmp(b2))); } SortOrder::LexLarge => { candidates.sort_by(|(a1, a2), (b1, b2)| a1.cmp(b1).then(a2.cmp(b2)).reverse()); } } if let Some((i, j)) = candidates.pop() { Some((valuation.index_to_term(i), valuation.index_to_term(j))) } else { None } } fn get_valuation(valuation: &SLP, left: &Term, right: &Term) -> Vec<bool> { let mut val: Vec<bool> = vec![false; valuation.num_of_original_constants()]; match left { Term::Cst(c) => { val[*c] ^= true; } Term::Var(v) => { val = valuation[*v].clone(); } } match right { Term::Cst(c) => { val[*c] ^= true; } Term::Var(v) => { val = bitvec_xor(&val, &valuation[*v]); } } val } pub fn run_xor_repair_forward(goal: &SLP, order: SortOrder) -> Vec<(Term, Term, Term)> { run_xor_repair(goal, gen_forward_iter, order) } pub fn run_xor_repair_reverse(goal: &SLP, order: SortOrder) -> Vec<(Term, Term, Term)> { run_xor_repair(goal, gen_rev_iter, order) } fn run_xor_repair( goal: &SLP, gen_iter: fn(usize, usize) -> Vec<usize>, order: SortOrder, ) -> Vec<(Term, Term, Term)> { let mut defs = Vec::new(); let mut slp = goal.clone(); let mut program = slp.clone(); let mut valuation = SLP::new( BitMatrix::new(0, goal.num_of_original_constants()), goal.num_of_original_constants(), 0, ); loop { let candidate = xor_pair_finder(&valuation, &slp, &mut program, gen_iter, &order); if let Some((left, right)) = candidate { let fresh = defs.len(); let new_var = Term::Var(fresh); let new_val = get_valuation(&valuation, &left, &right); program.add_column(); { let left = slp.term_to_index(&left); let right = slp.term_to_index(&right); let new = slp.term_to_index(&new_var); replace_by(&mut program, left, right, new); valuation.add_var(new_val); } defs.push((new_var, left, right)); } else { panic!("bug!"); } remove_achieved_goal(&valuation, &mut program, &mut slp); if slp.height() == 0 { return defs; } } } fn remove_achieved_goal(valuation: &SLP, program: &mut SLP, slp: &mut SLP) { let num_of_variables = valuation.height(); let latest_var = &valuation[num_of_variables - 1]; for i in (0..slp.height()).rev() { let val = &slp[i]; if val == latest_var { program.remove_row(i); slp.remove_row(i); break; } } }
use crate::bitmatrix::*; use crate::fast_repair::SortOrder; use crate::repair::{bitvec_distance, bitvec_xor}; use crate::slp::*; use crate::*; fn replace_by(m: &mut SLP, a: usize, b: usize, v: usize) { for i in 0..m.height() { if m[i][a] && m[i][b] { m[i][a] = false; m[i][b] = false; m[i][v] = true; } } } fn count_occurences2(i: usize, j: usize, slp: &SLP) -> usize { let mut count = 0; for def in 0..slp.height() { if slp[def][i] && slp[def][j] { count += 1 } } count } fn gen_forward_iter(start: usize, end: usize) -> Vec<usize> { (start..end).collect() } fn gen_rev_iter(start: usize, end: usize) -> Vec<usize> { (start..end).rev().collect() } fn build_syntax( valuation: &SLP, goal: &[bool], gen_iter: fn(usize, usize) -> Vec<usize>, ) -> (Vec<bool>, Vec<bool>) { let mut depends: Vec<bool> = vec![false; valuation.height() + valuation.num_of_original_constants()]; let mut rest = goal.to_vec(); loop { let mut which_var = None; let mut current_min = popcount(&rest); for var in gen_iter(0, valuation.height()) { let value = &valuation[var]; let count = bitvec_distance(&value, &rest); if count < current_min {
candidates.push((i, j)); } Ordering::Less => { candidates = vec![(i, j)]; count_max = count; } _ => {} } } } match order { SortOrder::LexSmall => { candidates.sort_by(|(a1, a2), (b1, b2)| a1.cmp(b1).then(a2.cmp(b2))); } SortOrder::LexLarge => { candidates.sort_by(|(a1, a2), (b1, b2)| a1.cmp(b1).then(a2.cmp(b2)).reverse()); } } if let Some((i, j)) = candidates.pop() { Some((valuation.index_to_term(i), valuation.index_to_term(j))) } else { None } } fn get_valuation(valuation: &SLP, left: &Term, right: &Term) -> Vec<bool> { let mut val: Vec<bool> = vec![false; valuation.num_of_original_constants()]; match left { Term::Cst(c) => { val[*c] ^= true; } Term::Var(v) => { val = valuation[*v].clone(); } } match right { Term::Cst(c) => { val[*c] ^= true; } Term::Var(v) => { val = bitvec_xor(&val, &valuation[*v]); } } val } pub fn run_xor_repair_forward(goal: &SLP, order: SortOrder) -> Vec<(Term, Term, Term)> { run_xor_repair(goal, gen_forward_iter, order) } pub fn run_xor_repair_reverse(goal: &SLP, order: SortOrder) -> Vec<(Term, Term, Term)> { run_xor_repair(goal, gen_rev_iter, order) } fn run_xor_repair( goal: &SLP, gen_iter: fn(usize, usize) -> Vec<usize>, order: SortOrder, ) -> Vec<(Term, Term, Term)> { let mut defs = Vec::new(); let mut slp = goal.clone(); let mut program = slp.clone(); let mut valuation = SLP::new( BitMatrix::new(0, goal.num_of_original_constants()), goal.num_of_original_constants(), 0, ); loop { let candidate = xor_pair_finder(&valuation, &slp, &mut program, gen_iter, &order); if let Some((left, right)) = candidate { let fresh = defs.len(); let new_var = Term::Var(fresh); let new_val = get_valuation(&valuation, &left, &right); program.add_column(); { let left = slp.term_to_index(&left); let right = slp.term_to_index(&right); let new = slp.term_to_index(&new_var); replace_by(&mut program, left, right, new); valuation.add_var(new_val); } defs.push((new_var, left, right)); } else { panic!("bug!"); } remove_achieved_goal(&valuation, &mut program, &mut slp); if slp.height() == 0 { return defs; } } } fn remove_achieved_goal(valuation: &SLP, program: &mut SLP, slp: &mut SLP) { let num_of_variables = valuation.height(); let latest_var = &valuation[num_of_variables - 1]; for i in (0..slp.height()).rev() { let val = &slp[i]; if val == latest_var { program.remove_row(i); slp.remove_row(i); break; } } }
which_var = Some(var); current_min = count; } } if let Some(var) = which_var { depends[valuation.num_of_original_constants() + var] = true; rest = bitvec_xor(&rest, &valuation[var]); } else { for idx in 0..rest.len() { if rest[idx] { depends[idx] = true; } } break; } } (depends, rest) } fn xor_pair_finder( valuation: &SLP, slp: &SLP, program: &mut SLP, gen_iter: fn(usize, usize) -> Vec<usize>, order: &SortOrder, ) -> Option<(Term, Term)> { use std::cmp::Ordering; let mut count_max = 0; let mut candidates = Vec::new(); for i in 0..slp.num_of_variables() { let goal = &slp[i]; let (depends, _) = build_syntax(valuation, &goal, gen_iter); if popcount(&depends) < popcount(&program[i]) { program[i] = depends; } } for i in 0..program.width() { for j in i + 1..program.width() { let count = count_occurences2(i, j, &program); match count_max.cmp(&count) { Ordering::Equal => {
random
[ { "content": "fn execute_slp_rec(slp: &SLP, var: usize, valuation: &mut HashMap<usize, Vec<bool>>) {\n\n if valuation.contains_key(&var) {\n\n // already visited\n\n return;\n\n }\n\n\n\n let num_constants = slp.num_of_original_constants();\n\n let mut val: Vec<bool> = vec![false; num_...
Rust
netidx-netproto/src/glob.rs
dtolnay-contrib/netidx
40fd1189d0d6df684e3b575421186e135e9c3208
use anyhow::Result; use bytes::{Buf, BufMut}; use globset; use netidx_core::{ chars::Chars, pack::{Pack, PackError}, path::Path, pool::{Pool, Pooled}, utils, }; use std::{ cmp::{Eq, PartialEq}, ops::Deref, result, sync::Arc, }; use arcstr::ArcStr; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Scope { Subtree, Finite(usize), } impl Scope { pub fn contains(&self, levels: usize) -> bool { match self { Scope::Subtree => true, Scope::Finite(n) => levels <= *n, } } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Glob { raw: Chars, base: Path, scope: Scope, glob: globset::Glob, } impl Glob { pub fn is_glob(mut s: &str) -> bool { loop { if s.is_empty() { break false; } else { match s.find(&['?', '*', '{', '['][..]) { None => break false, Some(i) => { if utils::is_escaped(s, '\\', i) { s = &s[i + 1..]; } else { break true; } } } } } } pub fn new(raw: Chars) -> Result<Glob> { if !Path::is_absolute(&raw) { bail!("glob paths must be absolute") } let base = { let mut cur = "/"; let mut iter = Path::dirnames(&raw); loop { match iter.next() { None => break cur, Some(p) => { if Glob::is_glob(p) { break cur; } else { cur = p; } } } } }; let lvl = Path::levels(base); let base = Path::from(ArcStr::from(base)); let scope = if Path::dirnames(&raw).skip(lvl).any(|p| Path::basename(p) == Some("**")) { Scope::Subtree } else { Scope::Finite(Path::levels(&raw)) }; let glob = globset::Glob::new(&*raw)?; Ok(Glob { raw, base, scope, glob }) } pub fn base(&self) -> &str { &self.base } pub fn scope(&self) -> &Scope { &self.scope } pub fn glob(&self) -> &globset::Glob { &self.glob } pub fn into_glob(self) -> globset::Glob { self.glob } } impl Pack for Glob { fn encoded_len(&self) -> usize { <Chars as Pack>::encoded_len(&self.raw) } fn encode(&self, buf: &mut impl BufMut) -> result::Result<(), PackError> { <Chars as Pack>::encode(&self.raw, buf) } fn decode(buf: &mut impl Buf) -> result::Result<Self, PackError> { Glob::new(<Chars as Pack>::decode(buf)?).map_err(|_| PackError::InvalidFormat) } } #[derive(Debug)] struct GlobSetInner { raw: Pooled<Vec<Glob>>, published_only: bool, glob: globset::GlobSet, } #[derive(Debug, Clone)] pub struct GlobSet(Arc<GlobSetInner>); impl PartialEq for GlobSet { fn eq(&self, other: &Self) -> bool { &self.0.raw == &other.0.raw } } impl Eq for GlobSet {} impl GlobSet { pub fn new( published_only: bool, globs: impl IntoIterator<Item = Glob>, ) -> Result<GlobSet> { lazy_static! { static ref GLOB: Pool<Vec<Glob>> = Pool::new(10, 100); } let mut builder = globset::GlobSetBuilder::new(); let mut raw = GLOB.take(); for glob in globs { builder.add(glob.glob.clone()); raw.push(glob); } raw.sort_unstable_by(|g0, g1| g0.base().cmp(g1.base())); Ok(GlobSet(Arc::new(GlobSetInner { raw, published_only, glob: builder.build()?, }))) } pub fn is_match(&self, path: &Path) -> bool { self.0.glob.is_match(path.as_ref()) } pub fn published_only(&self) -> bool { self.0.published_only } } impl Deref for GlobSet { type Target = Vec<Glob>; fn deref(&self) -> &Self::Target { &*self.0.raw } } impl Pack for GlobSet { fn encoded_len(&self) -> usize { <bool as Pack>::encoded_len(&self.0.published_only) + <Pooled<Vec<Glob>> as Pack>::encoded_len(&self.0.raw) } fn encode(&self, buf: &mut impl BufMut) -> result::Result<(), PackError> { <bool as Pack>::encode(&self.0.published_only, buf)?; <Pooled<Vec<Glob>> as Pack>::encode(&self.0.raw, buf) } fn decode(buf: &mut impl Buf) -> result::Result<Self, PackError> { let published_only = <bool as Pack>::decode(buf)?; let mut raw = <Pooled<Vec<Glob>> as Pack>::decode(buf)?; let mut builder = globset::GlobSetBuilder::new(); for glob in raw.iter() { builder.add(glob.glob.clone()); } raw.sort_unstable_by(|g0, g1| g0.base().cmp(g1.base())); let glob = builder.build().map_err(|_| PackError::InvalidFormat)?; Ok(GlobSet(Arc::new(GlobSetInner { raw, published_only, glob }))) } }
use anyhow::Result; use bytes::{Buf, BufMut}; use globset; use netidx_core::{ chars::Chars, pack::{Pack, PackError}, path::Path, pool::{Pool, Pooled}, utils, }; use std::{ cmp::{Eq, PartialEq}, ops::Deref, result, sync::Arc, }; use arcstr::ArcStr; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Scope { Subtree, Finite(usize), } impl Scope { pub fn contains(&self, levels: usize) -> bool { match self { Scope::Subtree => true, Scope::Finite(n) => levels <= *n, } } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Glob { raw: Chars, base: Path, scope: Scope, glob: globset::Glob, } impl Glob { pub fn is_glob(mut s: &str) -> bool { loop { if s.is_empty() { break false; } else { match s.find(&['?', '*', '{', '['][..]) { None => break false, Some(i) => {
} } } } } pub fn new(raw: Chars) -> Result<Glob> { if !Path::is_absolute(&raw) { bail!("glob paths must be absolute") } let base = { let mut cur = "/"; let mut iter = Path::dirnames(&raw); loop { match iter.next() { None => break cur, Some(p) => { if Glob::is_glob(p) { break cur; } else { cur = p; } } } } }; let lvl = Path::levels(base); let base = Path::from(ArcStr::from(base)); let scope = if Path::dirnames(&raw).skip(lvl).any(|p| Path::basename(p) == Some("**")) { Scope::Subtree } else { Scope::Finite(Path::levels(&raw)) }; let glob = globset::Glob::new(&*raw)?; Ok(Glob { raw, base, scope, glob }) } pub fn base(&self) -> &str { &self.base } pub fn scope(&self) -> &Scope { &self.scope } pub fn glob(&self) -> &globset::Glob { &self.glob } pub fn into_glob(self) -> globset::Glob { self.glob } } impl Pack for Glob { fn encoded_len(&self) -> usize { <Chars as Pack>::encoded_len(&self.raw) } fn encode(&self, buf: &mut impl BufMut) -> result::Result<(), PackError> { <Chars as Pack>::encode(&self.raw, buf) } fn decode(buf: &mut impl Buf) -> result::Result<Self, PackError> { Glob::new(<Chars as Pack>::decode(buf)?).map_err(|_| PackError::InvalidFormat) } } #[derive(Debug)] struct GlobSetInner { raw: Pooled<Vec<Glob>>, published_only: bool, glob: globset::GlobSet, } #[derive(Debug, Clone)] pub struct GlobSet(Arc<GlobSetInner>); impl PartialEq for GlobSet { fn eq(&self, other: &Self) -> bool { &self.0.raw == &other.0.raw } } impl Eq for GlobSet {} impl GlobSet { pub fn new( published_only: bool, globs: impl IntoIterator<Item = Glob>, ) -> Result<GlobSet> { lazy_static! { static ref GLOB: Pool<Vec<Glob>> = Pool::new(10, 100); } let mut builder = globset::GlobSetBuilder::new(); let mut raw = GLOB.take(); for glob in globs { builder.add(glob.glob.clone()); raw.push(glob); } raw.sort_unstable_by(|g0, g1| g0.base().cmp(g1.base())); Ok(GlobSet(Arc::new(GlobSetInner { raw, published_only, glob: builder.build()?, }))) } pub fn is_match(&self, path: &Path) -> bool { self.0.glob.is_match(path.as_ref()) } pub fn published_only(&self) -> bool { self.0.published_only } } impl Deref for GlobSet { type Target = Vec<Glob>; fn deref(&self) -> &Self::Target { &*self.0.raw } } impl Pack for GlobSet { fn encoded_len(&self) -> usize { <bool as Pack>::encoded_len(&self.0.published_only) + <Pooled<Vec<Glob>> as Pack>::encoded_len(&self.0.raw) } fn encode(&self, buf: &mut impl BufMut) -> result::Result<(), PackError> { <bool as Pack>::encode(&self.0.published_only, buf)?; <Pooled<Vec<Glob>> as Pack>::encode(&self.0.raw, buf) } fn decode(buf: &mut impl Buf) -> result::Result<Self, PackError> { let published_only = <bool as Pack>::decode(buf)?; let mut raw = <Pooled<Vec<Glob>> as Pack>::decode(buf)?; let mut builder = globset::GlobSetBuilder::new(); for glob in raw.iter() { builder.add(glob.glob.clone()); } raw.sort_unstable_by(|g0, g1| g0.base().cmp(g1.base())); let glob = builder.build().map_err(|_| PackError::InvalidFormat)?; Ok(GlobSet(Arc::new(GlobSetInner { raw, published_only, glob }))) } }
if utils::is_escaped(s, '\\', i) { s = &s[i + 1..]; } else { break true; }
if_condition
[ { "content": "pub fn is_escaped(s: &str, esc: char, i: usize) -> bool {\n\n let b = s.as_bytes();\n\n !s.is_char_boundary(i) || {\n\n let mut res = false;\n\n for j in (0..i).rev() {\n\n if s.is_char_boundary(j) && b[j] == (esc as u8) {\n\n res = !res;\n\n ...
Rust
src/vendor/h3c/reply.rs
jiegec/netconf-rs
ea67624060fcf7f1ff29e58d38bfbd010297c1c0
use serde_derive::Deserialize; #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct RpcReply { pub data: Data, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Data { pub top: Option<Top>, #[serde(rename = "netconf-state")] pub netconf_state: Option<NetconfState>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Top { #[serde(rename = "Ifmgr")] pub ifmgr: Option<Ifmgr>, #[serde(rename = "MAC")] pub mac: Option<Mac>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Ifmgr { #[serde(rename = "Interfaces")] pub interfaces: Interfaces, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Interfaces { #[serde(rename = "Interface")] pub interface: Vec<Interface>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Interface { #[serde(rename = "IfIndex")] pub index: usize, #[serde(rename = "Description")] pub description: Option<String>, #[serde(rename = "PVID")] pub port_vlan_id: Option<usize>, #[serde(rename = "ConfigMTU")] pub mtu: Option<usize>, #[serde(rename = "LinkType")] pub link_type: Option<usize>, #[serde(rename = "PortLayer")] pub port_layer: Option<usize>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct NetconfState { pub capabilities: Capabilities, pub schemas: Schemas, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Capabilities { pub capability: Vec<String>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Schemas { pub schema: Vec<Schema>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Schema { pub identifier: String, pub version: String, pub format: String, pub namespace: String, pub location: String, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Mac { #[serde(rename = "MacUnicastTable")] pub table: MacUnicastTable, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct MacUnicastTable { #[serde(rename = "Unicast")] pub unicast: Vec<Unicast>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Unicast { #[serde(rename = "VLANID")] pub vlan_id: usize, #[serde(rename = "MacAddress")] pub mac_address: String, #[serde(rename = "PortIndex")] pub port_index: usize, #[serde(rename = "Status")] pub status: usize, #[serde(rename = "Aging")] pub aging: bool, } #[cfg(test)] mod tests { use super::*; use serde_xml_rs::from_str; #[test] fn parse_mac_table() { let resp = r#" <?xml version="1.0" encoding="UTF-8"?> <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="100"> <data> <top xmlns="http://www.h3c.com/netconf/data:1.0"> <MAC> <MacUnicastTable> <Unicast> <VLANID>1</VLANID> <MacAddress>12-34-56-78-90-AB</MacAddress> <PortIndex>634</PortIndex> <Status>2</Status> <Aging>true</Aging> </Unicast> <Unicast> <VLANID>2</VLANID> <MacAddress>11-11-11-11-11-11</MacAddress> <PortIndex>10</PortIndex> <Status>2</Status> <Aging>true</Aging> </Unicast> </MacUnicastTable> </MAC> </top> </data> </rpc-reply> "#; let reply: RpcReply = from_str(&resp).unwrap(); assert_eq!( reply, RpcReply { data: Data { top: Some(Top { ifmgr: None, mac: Some(Mac { table: MacUnicastTable { unicast: vec![ Unicast { vlan_id: 1, mac_address: String::from("12-34-56-78-90-AB"), port_index: 634, status: 2, aging: true }, Unicast { vlan_id: 2, mac_address: String::from("11-11-11-11-11-11"), port_index: 10, status: 2, aging: true } ] } }) }), netconf_state: None } } ); } }
use serde_derive::Deserialize; #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct RpcReply { pub data: Data, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Data { pub top: Option<Top>, #[serde(rename = "netconf-state")] pub netconf_state: Option<NetconfState>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Top { #[serde(rename = "Ifmgr")] pub ifmgr: Option<Ifmgr>, #[serde(rename = "MAC")] pub mac: Option<Mac>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Ifmgr { #[serde(rename = "Interfaces")] pub interfaces: Interfaces, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Interfaces { #[serde(rename = "Interface")] pub interface: Vec<Interface>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Interface { #[serde(rename = "IfIndex")] pub index: usize, #[serde(rename = "Description")] pub description: Option<String>, #[serde(rename = "PVID")] pub port_vlan_id: Option<usize>, #[serde(rename = "ConfigMTU")] pub mtu: Option<usize>, #[serde(rename = "LinkType")] pub link_type: Option<usize>, #[serde(rename = "PortLayer")] pub port_layer: Option<usize>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct NetconfState { pub capabilities: Capabilities, pub schemas: Schemas, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Capabilities { pub capability: Vec<String>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Schemas { pub schema: Vec<Schema>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Schema { pub identifier: String, pub version: String, pub format: String, pub namespace: String, pub location: String, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Mac { #[serde(rename = "MacUnicastTable")] pub table: MacUnicastTable, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct MacUnicastTable { #[serde(rename = "Unicast")] pub unicast: Vec<Unicast>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Unicast { #[serde(rename = "VLANID")] pub vlan_id: usize, #[serde(rename = "MacAddress")] pub mac_address: String, #[serde(rename = "PortIndex")] pub port_index: usize, #[serde(rename = "Status")] pub status: usize, #[serde(rename = "Aging")] pub aging: bool, } #[cfg(test)] mod tests { use super::*; use serde_xml_rs::from_str; #[test] fn parse_mac_table() { let resp = r#" <?xml version="1.0" encoding="UTF-8"?> <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="100"> <data> <top xmlns="http://www.h3c.com/netconf/data:1.0"> <MAC> <MacUnicastTable> <Unicast> <VLANID>1</VLANID> <MacAddress>12-34-56-78-90-AB</MacAddress> <PortIndex>634</PortIndex> <Status>2</Status> <Aging>true</Aging> </Unicast> <Unicast> <VLANID>2</VLANID> <MacAddress>11-11-11-11-11-11</MacAddress> <PortIndex>10</PortIndex> <Status>2</Status> <Aging>true</Aging> </Unicast> </MacUnicastTable> </MAC> </top> </data> </rpc-reply> "#; let reply: RpcReply = from_str(&resp).unwrap(); assert_eq!( reply, RpcReply { data: Data { top: Some(Top { ifmgr: None, mac: Some(Mac { table: MacUnicastTable { unicast: vec![ Unicast { vlan_id:
}
1, mac_address: String::from("12-34-56-78-90-AB"), port_index: 634, status: 2, aging: true }, Unicast { vlan_id: 2, mac_address: String::from("11-11-11-11-11-11"), port_index: 10, status: 2, aging: true } ] } }) }), netconf_state: None } } ); }
function_block-function_prefixed
[ { "content": "#[derive(Debug, Deserialize)]\n\nstruct Capabilities {\n\n pub capability: Vec<String>,\n\n}\n\n\n\n/// A connection to NETCONF server\n\npub struct Connection {\n\n pub(crate) transport: Box<dyn Transport + Send + 'static>,\n\n}\n\n\n\nimpl Connection {\n\n pub fn new(transport: impl Tra...
Rust
src/triple.rs
MattsSe/nom-sparql
c0ea67ba8c5aed5ebed46bb9f1bb6257c6c64d06
use nom::{ branch::alt, bytes::complete::{escaped, tag, tag_no_case, take_while1, take_while_m_n}, character::complete::char, character::is_digit, combinator::map_res, combinator::{map, opt}, multi::{many0, many1, separated_nonempty_list}, sequence::{delimited, pair, separated_pair, tuple}, sequence::{preceded, terminated}, IResult, }; use crate::{ expression::ArgList, graph::graph_node, node::{Collection, ObjectList, PropertyList, TriplesNode}, path::{triples_same_subject_path, TriplesSameSubjectPath}, terminals::{bracketted, sp, sp_enc, sp_sep, sp_sep1}, var::{var_or_iri, var_or_term, verb, VarOrIri, VarOrTerm, Verb, VerbList}, }; #[derive(Debug, Clone, Eq, PartialEq)] pub enum TriplesSameSubject { Term { var_or_term: VarOrTerm, property_list: PropertyList, }, Node { triples_node: TriplesNode, property_list: Option<PropertyList>, }, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct ConstructTriples { pub first_triples: TriplesSameSubject, pub further_triples: Vec<TriplesSameSubject>, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct TriplesBlock(pub Vec<TriplesSameSubjectPath>); pub type TriplesTemplate = Vec<TriplesSameSubject>; pub(crate) fn blank_node_property_list(i: &str) -> IResult<&str, PropertyList> { delimited( terminated(char('['), sp), property_list_not_empty, preceded(sp, char(']')), )(i) } pub(crate) fn collection(i: &str) -> IResult<&str, Collection> { map(bracketted(many1(sp_enc(graph_node))), Collection)(i) } pub(crate) fn object_list(i: &str) -> IResult<&str, ObjectList> { map( separated_nonempty_list(sp_enc(tag(",")), graph_node), ObjectList, )(i) } pub(crate) fn property_list_not_empty(i: &str) -> IResult<&str, PropertyList> { map( terminated( separated_nonempty_list( sp_enc(many1(sp_enc(char(';')))), map(separated_pair(verb, sp, object_list), |(v, l)| { VerbList::new(v, l) }), ), many0(preceded(sp, char(';'))), ), PropertyList, )(i) } #[inline] pub(crate) fn property_list(i: &str) -> IResult<&str, Option<PropertyList>> { opt(property_list_not_empty)(i) } pub(crate) fn triples_node(i: &str) -> IResult<&str, TriplesNode> { alt(( map(collection, TriplesNode::Collection), map(blank_node_property_list, TriplesNode::BlankNodePropertyList), ))(i) } pub(crate) fn triples_block(i: &str) -> IResult<&str, TriplesBlock> { map( separated_nonempty_list(many1(sp_enc(char('.'))), triples_same_subject_path), TriplesBlock, )(i) } pub(crate) fn triples_template(i: &str) -> IResult<&str, TriplesTemplate> { terminated( separated_nonempty_list(many1(sp_enc(char('.'))), triples_same_subject), opt(preceded(sp, char('.'))), )(i) } pub(crate) fn triples_same_subject(i: &str) -> IResult<&str, TriplesSameSubject> { alt(( map( sp_sep(triples_node, property_list), |(triples_node, property_list)| TriplesSameSubject::Node { triples_node, property_list, }, ), map( sp_sep1(var_or_term, property_list_not_empty), |(var_or_term, property_list)| TriplesSameSubject::Term { var_or_term, property_list, }, ), ))(i) } #[cfg(test)] mod tests { use super::*; use crate::graph::{GraphNode, GraphTerm}; #[test] fn is_triple_same_subject() { assert_eq!( triples_same_subject("() a true,()"), Ok(( "", TriplesSameSubject::Term { var_or_term: VarOrTerm::Term(GraphTerm::Nil), property_list: PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(true))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )]) } )) ); assert_eq!( triples_same_subject("(()())"), Ok(( "", TriplesSameSubject::Node { triples_node: TriplesNode::Collection(Collection(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)) ])), property_list: None } )) ); assert_eq!( triples_same_subject("[ a (),()\t] a false,()"), Ok(( "", TriplesSameSubject::Node { triples_node: TriplesNode::BlankNodePropertyList(PropertyList(vec![ VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), ) ])), property_list: Some(PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(false))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )])) } )) ); } #[test] fn is_triples_node() { assert_eq!( triples_node("(true ())"), Ok(( "", TriplesNode::Collection(Collection(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(true))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)) ])) )) ); assert_eq!( triples_node("[\na false,() \n]"), Ok(( "", TriplesNode::BlankNodePropertyList(PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(false))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )])) )) ); } #[test] fn is_triples_template() { let nil = TriplesSameSubject::Node { triples_node: TriplesNode::Collection(Collection(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(true))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ])), property_list: None, }; assert_eq!(triples_template("(true())."), Ok(("", vec![nil.clone()]))); assert_eq!( triples_template("(true()).(true())"), Ok(("", vec![nil.clone(), nil.clone()])) ); assert_eq!( triples_template("(true()).[ a (),()\t] a false,()"), Ok(( "", vec![ nil.clone(), TriplesSameSubject::Node { triples_node: TriplesNode::BlankNodePropertyList(PropertyList(vec![ VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), ) ])), property_list: Some(PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral( false ))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )])) } ] )) ); } }
use nom::{ branch::alt, bytes::complete::{escaped, tag, tag_no_case, take_while1, take_while_m_n}, character::complete::char, character::is_digit, combinator::map_res, combinator::{map, opt}, multi::{many0, many1, separated_nonempty_list}, sequence::{delimited, pair, separated_pair, tuple}, sequence::{preceded, terminated}, IResult, }; use crate::{ expression::ArgList, graph::graph_node, node::{Collection, ObjectList, PropertyList, TriplesNode}, path::{triples_same_subject_path, TriplesSameSubjectPath}, terminals::{bracketted, sp, sp_enc, sp_sep, sp_sep1}, var::{var_or_iri, var_or_term, verb, VarOrIri, VarOrTerm, Verb, VerbList}, }; #[derive(Debug, Clone, Eq, PartialEq)] pub enum TriplesSameSubject { Term { var_or_term: VarOrTerm, property_list: PropertyList, }, Node { triples_node: TriplesNode, property_list: Option<PropertyList>, }, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct ConstructTriples { pub first_triples: TriplesSameSubject, pub further_triples: Vec<TriplesSameSubject>, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct TriplesBlock(pub Vec<TriplesSameSubjectPath>); pub type TriplesTemplate = Vec<TriplesSameSubject>; pub(crate) fn blank_node_property_list(i: &str) -> IResult<&str, PropertyList> { delimited( terminated(char('['), sp), property_list_not_empty, preceded(sp, char(']')), )(i) } pub(crate) fn collection(i: &str) -> IResult<&str, Collection> { map(bracketted(many1(sp_enc(graph_node))), Collection)(i) } pub(crate) fn object_list(i: &str) -> IResult<&str, ObjectList> { map( separated_nonempty_list(sp_enc(tag(",")), graph_node), ObjectList, )(i) } pub(crate) fn property_list_not_empty(i: &str) -> IResult<&str, PropertyList> { map( terminated( separated_nonempty_list( sp_enc(many1(sp_enc(char(';')))), map(separated_pair(verb, sp, object_list), |(v, l)| { VerbList::new(v, l) }), ), many0(preceded(sp, char(';'))), ), PropertyList, )(i) } #[inline] pub(crate) fn property_list(i: &str) -> IResult<&str, Option<PropertyList>> { opt(property_list_not_empty)(i) } pub(crate) fn triples_node(i: &str) -> IResult<&str, TriplesNode> { alt(( map(collection, TriplesNode::Collection), map(blank_node_property_list, TriplesNode::BlankNodePropertyList), ))(i) } pub(crate) fn triples_block(i: &str) -> IResult<&str, TriplesBlock> { map( separated_nonempty_list(many1(sp_enc(char('.'))), triples_same_subject_path), TriplesBlock, )(i) } pub(crate) fn triples_template(i: &str) -> IResult<&str, TriplesTemplate> { terminated( separated_nonempty_list(many1(sp_enc(char('.'))), triples_same_subject), opt(preceded(sp, char('.'))), )(i) } pub(crate) fn triples_same_subject(i: &str) -> IResult<&str, TriplesSameSubject> { alt(( map( sp_sep(triples_node, property_list), |(triples_node, property_list)| TriplesSameSubject::Node { triples_node, property_list, }, ), map( sp_sep1(var_or_term, property_list_not_empty), |(var_or_term, property_list)| TriplesSameSubject::Term { var_or_term, property_list, }, ), ))(i) } #[cfg(test)] mod tests { use super::*; use crate::graph::{GraphNode, GraphTerm}; #[test] fn is_triple_same_subject() { assert_eq!( triples_same_subject("() a true,()"), Ok(( "", TriplesSameSubject::Term { var_or_term: VarOrTerm::Term(GraphTerm::Nil), property_list: PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(true))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )]) } )) ); assert_eq!( triples_same_subject("(()())"), Ok(( "", TriplesSameSubject::Node { triples_node: TriplesNode::Collection(Collection(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)) ])), property_list: None } )) ); assert_eq!( triples_same_subject("[ a (),()\t] a false,()"), Ok(( "", TriplesSameSubject::Node { triples_node: TriplesNode::BlankNodePropertyList(PropertyList(vec![ VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), ) ])), property_list: Some(PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(false))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )])) } )) ); } #[test] fn is_triples_node() { assert_eq!( triples_node("(true ())"), Ok(( "", TriplesNode::Collection(Collection(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(true))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)) ])) )) ); assert_eq!( triples_node("[\na false,() \n]"), Ok(( "", TriplesNode::BlankNodePropertyList(PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(false))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )])) )) ); } #[test] fn is_triples_template() {
assert_eq!(triples_template("(true())."), Ok(("", vec![nil.clone()]))); assert_eq!( triples_template("(true()).(true())"), Ok(("", vec![nil.clone(), nil.clone()])) ); assert_eq!( triples_template("(true()).[ a (),()\t] a false,()"), Ok(( "", vec![ nil.clone(), TriplesSameSubject::Node { triples_node: TriplesNode::BlankNodePropertyList(PropertyList(vec![ VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), ) ])), property_list: Some(PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral( false ))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )])) } ] )) ); } }
let nil = TriplesSameSubject::Node { triples_node: TriplesNode::Collection(Collection(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(true))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ])), property_list: None, };
assignment_statement
[ { "content": "fn plx(i: &str) -> IResult<&str, &str> {\n\n recognize(alt((\n\n pair(tag(\"%\"), hex_primary),\n\n pair(tag(\"\\\\\"), recognize(one_of(\"_~.-!$&'()*+,;=/?#@%\"))),\n\n )))(i)\n\n}\n\n\n\npub(crate) fn pn_local(i: &str) -> IResult<&str, &str> {\n\n recognize(pair(\n\n ...
Rust
basis-universal/src/transcoding/transcoding_tests.rs
fintelia/basis-universal-rs
4a23939034479de8119d52fd0eb1737cad5e46ee
use super::*; #[test] fn test_get_bytes_per_block_or_pixel() { assert_eq!( TranscoderTextureFormat::BC1_RGB.bytes_per_block_or_pixel(), 8 ); } #[test] fn test_get_format_name() { assert_eq!(TranscoderTextureFormat::BC1_RGB.format_name(), "BC1_RGB"); } #[test] fn test_transcoder_format_has_alpha() { assert_eq!(TranscoderTextureFormat::BC1_RGB.has_alpha(), false); assert_eq!(TranscoderTextureFormat::BC7_RGBA.has_alpha(), true); } #[test] fn test_get_texture_type_name() { assert_eq!(BasisTextureType::TextureType2D.texture_type_name(), "2D"); } #[test] fn test_new_transcoder() { let transcoder = Transcoder::new(); std::mem::drop(transcoder); } #[test] fn test_transcoder_get_total_images() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); assert_eq!(transcoder.image_count(basis_file), 1); std::mem::drop(transcoder); } #[test] fn test_transcoder_info() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); let file_info = transcoder.file_info(basis_file).unwrap(); assert!(transcoder.image_info(basis_file, 0).is_some()); assert!(transcoder .image_level_description(basis_file, 0, 0) .is_some()); assert!(transcoder.image_level_info(basis_file, 0, 0).is_some()); assert!(transcoder .image_info(basis_file, file_info.m_total_images + 1) .is_none()); assert!(transcoder .image_level_description(basis_file, file_info.m_total_images + 1, 0) .is_none()); assert!(transcoder .image_level_info(basis_file, file_info.m_total_images + 1, 0) .is_none()); assert!(transcoder .image_level_description(basis_file, 0, 100) .is_none()); assert!(transcoder.image_level_info(basis_file, 0, 100).is_none()); std::mem::drop(transcoder); } #[test] fn test_transcoder_get_tex_format() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); assert_eq!( transcoder.basis_texture_format(basis_file), BasisTextureFormat::ETC1S ); std::mem::drop(transcoder); let basis_file = include_bytes!("../../test_assets/rust-logo-uastc.basis"); let transcoder = Transcoder::new(); assert_eq!( transcoder.basis_texture_format(basis_file), BasisTextureFormat::UASTC4x4 ); std::mem::drop(transcoder); } #[test] fn test_transcoder_get_total_image_levels() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); assert_eq!(transcoder.image_level_count(basis_file, 0), 7); std::mem::drop(transcoder); } #[test] fn test_transcoder_transcode_etc() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); do_test_transcoder_transcode(basis_file, "test_assets/test_transcode_image_etc.png"); } #[test] fn test_transcoder_transcode_uastc() { let basis_file = include_bytes!("../../test_assets/rust-logo-uastc.basis"); do_test_transcoder_transcode(basis_file, "test_assets/test_transcode_image_uastc.png"); } fn do_test_transcoder_transcode( basis_file: &[u8], _out_path: &str, ) { let mut transcoder = Transcoder::new(); transcoder.prepare_transcoding(basis_file).unwrap(); transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::ETC1_RGB, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap(); transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::ASTC_4x4_RGBA, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap(); if transcoder.basis_texture_format(basis_file) == BasisTextureFormat::ETC1S { transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::FXT1_RGB, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap(); } let _result = transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::RGBA32, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap(); transcoder.end_transcoding(); std::mem::drop(transcoder); }
use super::*; #[test] fn test_get_bytes_per_block_or_pixel() { assert_eq!( TranscoderTextureFormat::BC1_RGB.bytes_per_block_or_pixel(), 8 ); } #[test] fn test_get_format_name() { assert_eq!(TranscoderTextureFormat::BC1_RGB.format_name(), "BC1_RGB"); } #[test] fn test_transcoder_format_has_alpha() { assert_eq!(TranscoderTextureFormat::BC1_RGB.has_alpha(), false); assert_eq!(TranscoderTextureFormat::BC7_RGBA.has_alpha(), true); } #[test] fn test_get_texture_type_name() { assert_eq!(BasisTextureType::TextureType2D.texture_type_name(), "2D"); } #[test] fn test_new_transcoder() { let transcoder = Transcoder::new(); std::mem::drop(transcoder); } #[test] fn test_transcoder_get_total_images() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); assert_eq!(transcoder.image_count(basis_file), 1); std::mem::drop(transcoder); } #[test] fn test_transcoder_info() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); let file_info = transcoder.file_info(basis_file).unwrap(); assert!(transcoder.image_info(basis_file, 0).is_some()); assert!(transcoder .image_level_description(basis_file, 0, 0) .is_some()); assert!(transcoder.image_level_info(basis_file, 0, 0).is_some()); assert!(transcoder .image_info(basis_file, file_info.m_total_images + 1) .is_none()); assert!(transcoder .image_level_description(basis_file, file_info.m_total_images + 1, 0) .is_none()); assert!(transcoder .image_level_info(basis_file, file_info.m_total_images + 1, 0) .is_none()); assert!(transcoder .image_level_description(basis_file, 0, 100) .is_none()); assert!(transcoder.image_level_info(basis_file, 0, 100).is_none()); std::mem::drop(transcoder); } #[test] fn test_transcoder_get_tex_format() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); assert_eq!( transcoder.basis_texture_format(basis_file), BasisTextureFormat::ETC1S ); std::mem::drop(transcoder); let basis_file = include_bytes!("../../test_assets/rust-logo-uastc.basis"); let transcoder = Transcoder::new(); assert_eq!( transcoder.basis_texture_format(basis_file), BasisTextureFormat::UASTC4x4 ); std::mem::drop(transcoder); } #[test] fn test_transcoder_get_total_image_levels() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); assert_eq!(transcoder.image_level_count(basis_file, 0), 7); std::mem::drop(transcoder); } #[test] fn test_transcoder_transcode_etc() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); do_test_transcoder_transcode(basis_file, "test_assets/test_transcode_image_etc.png"); } #[test] fn test_transcoder_transcode_uastc() { let basis_file = include_bytes!("../../test_assets/rust-logo-uastc.basis"); do_test_transcoder_transcode(basis_file, "test_assets/test_transcode_image_uastc.png"); } fn do_test_transcoder_transcode( basis_file: &[u8], _out_path: &str, ) { let mut transcoder = Transcoder::new(); transcoder.prepare_transcoding(basis_file).unwrap(); transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::ETC1_RGB, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap(); transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::ASTC_4x4_RGBA, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap();
let _result = transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::RGBA32, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap(); transcoder.end_transcoding(); std::mem::drop(transcoder); }
if transcoder.basis_texture_format(basis_file) == BasisTextureFormat::ETC1S { transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::FXT1_RGB, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap(); }
if_condition
[ { "content": "#[test]\n\nfn bindgen_test_layout_Transcoder() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Transcoder>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(Transcoder))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Transcoder>(),\n\n 8usize,\n\n ...
Rust
src/macros.rs
activeledger/SDK-Rust-TxBuilder
505e9a7a4b2240a08dcb01786bcf7d92d7f60a49
/* * MIT License (MIT) * Copyright (c) 2019 Activeledger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! input_str { ($e:expr) => { $crate::PacketValue::String($e.to_string()) }; } #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! input_array { ($e:expr) => { $crate::PacketValue::Array($e) }; } #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! input_map { ($e:expr) => { $crate::PacketValue::Object($e) }; } #[macro_export] macro_rules! signees { [$({$streamid: expr => $key:expr}),+] => {{ let mut signees = $crate::Signees::new(); $( signees.add($key, $streamid); )* signees }}; ($key:expr) => {{ let mut s = $crate::Signees::new(); s.add_selfsign($key); s.clone() }}; () => {{ let s = $crate::Signees::new(); s.clone() }}; } #[macro_export(local_inner_macros)] macro_rules! packet_data { ($($data:tt)+) => { packet_data_internal!($($data)+) }; } #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! packet_data_internal { (@object $object:ident () () ()) => {}; (@object $object:ident [$($key:tt)+] ($value:expr), $($tail:tt)*) => { let _ = $object.insert(($($key)+).into(), $value); packet_data_internal!(@object $object () ($($tail)*) ($($tail)*)); }; (@object $object:ident [$($key:tt)+] ($value:expr)) => { let _ = $object.insert(($($key)+).into(), $value); }; (@object $object:ident ($($key:tt)+) (: {$($map:tt)*} $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!({$($map)*})) $($tail)*); }; (@object $object:ident ($($key:tt)+) (: [$($array:tt)*] $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!([$($array)*])) $($tail)*); }; (@object $object:ident ($($key:tt)+) (: $value:expr, $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!($value)) , $($tail)*); }; (@object $object:ident ($($key:tt)+) (: $value:expr) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!($value))); }; (@object $object:ident () (($key:expr) : $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object ($key) (: $($tail)*) (: $($tail)*)); }; (@object $object:ident ($($key:tt)*) ($data:tt $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object ($($key)* $data) ($($tail)*) ($($tail)*)); }; (@object $object:ident [$($key:tt)+] ($value:expr) $unexpected:tt $($tail:tt)*) => { input_unexpected!($unexpected); }; (@array [$($elems:expr,)*]) => { packet_data_internal_vec![$($elems,)*] }; (@array [$($elems:expr),*]) => { packet_data_internal_vec![$($elems),*] }; (@array [$($elems:expr,)*] $next:expr, $($tail:tt)*) => { packet_data_internal!(@array [$($elems,)* packet_data_internal!($next),] $($tail)*) }; (@array [$($elems:expr,)*] $last:expr) => { packet_data_internal!(@array [$($elems,)* packet_data_internal!($last)]) }; (@array [$($elems:expr,)*] , $($tail:tt)*) => { packet_data_internal!(@array [$($elems,)*] $($tail:tt)*) }; (@array [$($elems:expr),*] $unexpected:tt $($tail:tt)*) => { input_unexpected!($unexpected) }; ({}) => {{ $crate::PacketValue::Object(std::collections::HashMap::new()) }}; ({ $($data:tt)+ }) => { $crate::PacketValue::Object({ let mut object = std::collections::HashMap::new(); packet_data_internal!(@object object () ($($data)+) ($($data)+)); object }) }; ([]) => { $crate::PacketValue::Array(packet_data_internal_vec![]) }; ([ $($data:tt)+ ]) => { $crate::PacketValue::Array(packet_data_internal!(@array [] $($data)+)) }; ($other:expr) => { input_str!(&$other) } } #[macro_export] #[doc(hidden)] macro_rules! packet_data_internal_vec { ($($data:tt)*) => { vec![$($data)*] }; } #[macro_export] #[doc(hidden)] macro_rules! input_unexpected { () => {}; }
/* * MIT License (MIT) * Copyright (c) 2019 Activeledger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! input_str { ($e:expr) => { $crate::PacketValue::String($e.to_string()) }; } #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! input_array { ($e:expr) => { $crate::PacketValue::Array($e) }; } #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! input_map { ($e:
c![$($data)*] }; } #[macro_export] #[doc(hidden)] macro_rules! input_unexpected { () => {}; }
expr) => { $crate::PacketValue::Object($e) }; } #[macro_export] macro_rules! signees { [$({$streamid: expr => $key:expr}),+] => {{ let mut signees = $crate::Signees::new(); $( signees.add($key, $streamid); )* signees }}; ($key:expr) => {{ let mut s = $crate::Signees::new(); s.add_selfsign($key); s.clone() }}; () => {{ let s = $crate::Signees::new(); s.clone() }}; } #[macro_export(local_inner_macros)] macro_rules! packet_data { ($($data:tt)+) => { packet_data_internal!($($data)+) }; } #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! packet_data_internal { (@object $object:ident () () ()) => {}; (@object $object:ident [$($key:tt)+] ($value:expr), $($tail:tt)*) => { let _ = $object.insert(($($key)+).into(), $value); packet_data_internal!(@object $object () ($($tail)*) ($($tail)*)); }; (@object $object:ident [$($key:tt)+] ($value:expr)) => { let _ = $object.insert(($($key)+).into(), $value); }; (@object $object:ident ($($key:tt)+) (: {$($map:tt)*} $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!({$($map)*})) $($tail)*); }; (@object $object:ident ($($key:tt)+) (: [$($array:tt)*] $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!([$($array)*])) $($tail)*); }; (@object $object:ident ($($key:tt)+) (: $value:expr, $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!($value)) , $($tail)*); }; (@object $object:ident ($($key:tt)+) (: $value:expr) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!($value))); }; (@object $object:ident () (($key:expr) : $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object ($key) (: $($tail)*) (: $($tail)*)); }; (@object $object:ident ($($key:tt)*) ($data:tt $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object ($($key)* $data) ($($tail)*) ($($tail)*)); }; (@object $object:ident [$($key:tt)+] ($value:expr) $unexpected:tt $($tail:tt)*) => { input_unexpected!($unexpected); }; (@array [$($elems:expr,)*]) => { packet_data_internal_vec![$($elems,)*] }; (@array [$($elems:expr),*]) => { packet_data_internal_vec![$($elems),*] }; (@array [$($elems:expr,)*] $next:expr, $($tail:tt)*) => { packet_data_internal!(@array [$($elems,)* packet_data_internal!($next),] $($tail)*) }; (@array [$($elems:expr,)*] $last:expr) => { packet_data_internal!(@array [$($elems,)* packet_data_internal!($last)]) }; (@array [$($elems:expr,)*] , $($tail:tt)*) => { packet_data_internal!(@array [$($elems,)*] $($tail:tt)*) }; (@array [$($elems:expr),*] $unexpected:tt $($tail:tt)*) => { input_unexpected!($unexpected) }; ({}) => {{ $crate::PacketValue::Object(std::collections::HashMap::new()) }}; ({ $($data:tt)+ }) => { $crate::PacketValue::Object({ let mut object = std::collections::HashMap::new(); packet_data_internal!(@object object () ($($data)+) ($($data)+)); object }) }; ([]) => { $crate::PacketValue::Array(packet_data_internal_vec![]) }; ([ $($data:tt)+ ]) => { $crate::PacketValue::Array(packet_data_internal!(@array [] $($data)+)) }; ($other:expr) => { input_str!(&$other) } } #[macro_export] #[doc(hidden)] macro_rules! packet_data_internal_vec { ($($data:tt)*) => { ve
random
[ { "content": "# Activeledger - Transaction Helper\n\n\n\n<img src=\"https://www.activeledger.io/wp-content/uploads/2018/09/Asset-23.png\" alt=\"Activeledger\" width=\"300\"/>\n\n\n\nActiveledger is a powerful distributed ledger technology.\n\nThink about it as a single ledger, which is updated simultaneously in...
Rust
src/librand/distributions/normal.rs
oxidation/rust
f1bb6c2f46f08c1d7b6d695f5b3cf93142cb8860
use core::num::Float; use {Rng, Rand, Open01}; use distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample}; #[derive(Copy)] pub struct StandardNormal(pub f64); impl Rand for StandardNormal { fn rand<R:Rng>(rng: &mut R) -> StandardNormal { #[inline] fn pdf(x: f64) -> f64 { (-x*x/2.0).exp() } #[inline] fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 { let mut x = 1.0f64; let mut y = 0.0f64; while -2.0 * y < x * x { let Open01(x_) = rng.gen::<Open01<f64>>(); let Open01(y_) = rng.gen::<Open01<f64>>(); x = x_.ln() / ziggurat_tables::ZIG_NORM_R; y = y_.ln(); } if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x } } StandardNormal(ziggurat( rng, true, &ziggurat_tables::ZIG_NORM_X, &ziggurat_tables::ZIG_NORM_F, pdf, zero_case)) } } #[derive(Copy)] pub struct Normal { mean: f64, std_dev: f64, } impl Normal { pub fn new(mean: f64, std_dev: f64) -> Normal { assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); Normal { mean: mean, std_dev: std_dev } } } impl Sample<f64> for Normal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Normal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(n) = rng.gen::<StandardNormal>(); self.mean + self.std_dev * n } } #[derive(Copy)] pub struct LogNormal { norm: Normal } impl LogNormal { pub fn new(mean: f64, std_dev: f64) -> LogNormal { assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0"); LogNormal { norm: Normal::new(mean, std_dev) } } } impl Sample<f64> for LogNormal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for LogNormal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.norm.ind_sample(rng).exp() } } #[cfg(test)] mod tests { use std::prelude::v1::*; use distributions::{Sample, IndependentSample}; use super::{Normal, LogNormal}; #[test] fn test_normal() { let mut norm = Normal::new(10.0, 10.0); let mut rng = ::test::rng(); for _ in 0..1000 { norm.sample(&mut rng); norm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_normal_invalid_sd() { Normal::new(10.0, -1.0); } #[test] fn test_log_normal() { let mut lnorm = LogNormal::new(10.0, 10.0); let mut rng = ::test::rng(); for _ in 0..1000 { lnorm.sample(&mut rng); lnorm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_log_normal_invalid_sd() { LogNormal::new(10.0, -1.0); } } #[cfg(test)] mod bench { extern crate test; use std::prelude::v1::*; use self::test::Bencher; use std::mem::size_of; use distributions::{Sample}; use super::Normal; #[bench] fn rand_normal(b: &mut Bencher) { let mut rng = ::test::weak_rng(); let mut normal = Normal::new(-2.71828, 3.14159); b.iter(|| { for _ in 0..::RAND_BENCH_N { normal.sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } }
use core::num::Float; use {Rng, Rand, Open01}; use distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample}; #[derive(Copy)] pub struct StandardNormal(pub f64); impl Rand for StandardNormal { fn rand<R:Rng>(rng: &mut R) -> StandardNormal { #[inline] fn pdf(
} #[derive(Copy)] pub struct Normal { mean: f64, std_dev: f64, } impl Normal { pub fn new(mean: f64, std_dev: f64) -> Normal { assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); Normal { mean: mean, std_dev: std_dev } } } impl Sample<f64> for Normal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Normal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(n) = rng.gen::<StandardNormal>(); self.mean + self.std_dev * n } } #[derive(Copy)] pub struct LogNormal { norm: Normal } impl LogNormal { pub fn new(mean: f64, std_dev: f64) -> LogNormal { assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0"); LogNormal { norm: Normal::new(mean, std_dev) } } } impl Sample<f64> for LogNormal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for LogNormal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.norm.ind_sample(rng).exp() } } #[cfg(test)] mod tests { use std::prelude::v1::*; use distributions::{Sample, IndependentSample}; use super::{Normal, LogNormal}; #[test] fn test_normal() { let mut norm = Normal::new(10.0, 10.0); let mut rng = ::test::rng(); for _ in 0..1000 { norm.sample(&mut rng); norm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_normal_invalid_sd() { Normal::new(10.0, -1.0); } #[test] fn test_log_normal() { let mut lnorm = LogNormal::new(10.0, 10.0); let mut rng = ::test::rng(); for _ in 0..1000 { lnorm.sample(&mut rng); lnorm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_log_normal_invalid_sd() { LogNormal::new(10.0, -1.0); } } #[cfg(test)] mod bench { extern crate test; use std::prelude::v1::*; use self::test::Bencher; use std::mem::size_of; use distributions::{Sample}; use super::Normal; #[bench] fn rand_normal(b: &mut Bencher) { let mut rng = ::test::weak_rng(); let mut normal = Normal::new(-2.71828, 3.14159); b.iter(|| { for _ in 0..::RAND_BENCH_N { normal.sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } }
x: f64) -> f64 { (-x*x/2.0).exp() } #[inline] fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 { let mut x = 1.0f64; let mut y = 0.0f64; while -2.0 * y < x * x { let Open01(x_) = rng.gen::<Open01<f64>>(); let Open01(y_) = rng.gen::<Open01<f64>>(); x = x_.ln() / ziggurat_tables::ZIG_NORM_R; y = y_.ln(); } if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x } } StandardNormal(ziggurat( rng, true, &ziggurat_tables::ZIG_NORM_X, &ziggurat_tables::ZIG_NORM_F, pdf, zero_case)) }
function_block-function_prefixed
[ { "content": "/// Randomly sample up to `amount` elements from an iterator.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust\n\n/// use std::rand::{thread_rng, sample};\n\n///\n\n/// let mut rng = thread_rng();\n\n/// let sample = sample(&mut rng, 1..100, 5);\n\n/// println!(\"{:?}\", sample);\n\n/// ```\n\npub fn...
Rust
fuzzy_log_packets/src/storeables.rs
JLockerman/delos-rust
400a458c28524040b790e33f8e58809c60a948c5
use std::{mem, ptr, slice}; pub trait Storeable { fn size(&self) -> usize; unsafe fn ref_to_bytes(&self) -> &u8; unsafe fn ref_to_slice(&self) -> &[u8]; unsafe fn bytes_to_ref(&u8, usize) -> &Self; unsafe fn slice_to_ref(val: &[u8], size: usize) -> &Self; unsafe fn bytes_to_mut(&mut u8, usize) -> &mut Self; unsafe fn clone_box(&self) -> Box<Self>; unsafe fn copy_to_mut(&self, &mut Self) -> usize; } pub trait UnStoreable: Storeable { fn size_from_bytes(bytes: &u8) -> usize; fn size_from_slice(bytes: &[u8]) -> usize; unsafe fn unstore(bytes: &[u8]) -> &Self { let size = <Self as UnStoreable>::size_from_slice(bytes); <Self as Storeable>::slice_to_ref(bytes, size) } unsafe fn unstore_mut(bytes: &mut u8) -> &mut Self { let size = <Self as UnStoreable>::size_from_bytes(bytes); <Self as Storeable>::bytes_to_mut(bytes, size) } } impl<V> Storeable for V { fn size(&self) -> usize { mem::size_of::<Self>() } unsafe fn ref_to_bytes(&self) -> &u8 { mem::transmute(self) } unsafe fn ref_to_slice(&self) -> &[u8] { let ptr = self as *const V as *const u8; let size = self.size(); slice::from_raw_parts(ptr, size) } unsafe fn bytes_to_ref(val: &u8, _size: usize) -> &Self { mem::transmute(val) } unsafe fn slice_to_ref(val: &[u8], size: usize) -> &Self { assert_eq!(val.len(), size); mem::transmute(val.as_ptr()) } unsafe fn bytes_to_mut(val: &mut u8, size: usize) -> &mut Self { assert_eq!(size, mem::size_of::<Self>()); mem::transmute(val) } unsafe fn clone_box(&self) -> Box<Self> { let mut b = Box::new(mem::uninitialized()); ptr::copy_nonoverlapping(self, &mut *b, 1); b } unsafe fn copy_to_mut(&self, out: &mut Self) -> usize { ptr::copy(self, out, 1); mem::size_of::<Self>() } } impl<V> Storeable for [V] { fn size(&self) -> usize { mem::size_of::<V>() * self.len() } unsafe fn ref_to_bytes(&self) -> &u8 { mem::transmute(self.as_ptr()) } unsafe fn ref_to_slice(&self) -> &[u8] { let ptr = self as *const _ as *const u8; let size = self.size(); slice::from_raw_parts(ptr, size) } unsafe fn bytes_to_ref(val: &u8, size: usize) -> &Self { assert_eq!(size % mem::size_of::<V>(), 0); slice::from_raw_parts(val as *const _ as *const _, size / mem::size_of::<V>()) } unsafe fn slice_to_ref(val: &[u8], size: usize) -> &Self { assert_eq!(size % mem::size_of::<V>(), 0); assert_eq!(val.len(), size); slice::from_raw_parts(val.as_ptr() as *const V, size / mem::size_of::<V>()) } unsafe fn bytes_to_mut(val: &mut u8, size: usize) -> &mut Self { assert_eq!(size % mem::size_of::<V>(), 0); slice::from_raw_parts_mut(val as *mut _ as *mut _, size / mem::size_of::<V>()) } unsafe fn clone_box(&self) -> Box<Self> { let mut v = Vec::with_capacity(self.len()); v.set_len(self.len()); let mut b = v.into_boxed_slice(); ptr::copy_nonoverlapping(self.as_ptr(), b.as_mut_ptr(), self.len()); b } unsafe fn copy_to_mut(&self, out: &mut Self) -> usize { let to_copy = ::std::cmp::min(self.len(), out.len()); ptr::copy(self.as_ptr(), out.as_mut_ptr(), to_copy); to_copy * mem::size_of::<V>() } } impl<V> UnStoreable for V { fn size_from_bytes(_: &u8) -> usize { mem::size_of::<Self>() } fn size_from_slice(_: &[u8]) -> usize { mem::size_of::<Self>() } } impl<V> UnStoreable for [V] { fn size_from_bytes(_: &u8) -> usize { unimplemented!() } fn size_from_slice(bytes: &[u8]) -> usize { bytes.len() } } #[test] fn store_u8() { unsafe { assert_eq!(32u8.ref_to_slice(), &[32]); assert_eq!(0u8.ref_to_slice(), &[0]); assert_eq!(255u8.ref_to_slice(), &[255]); } } #[test] fn round_u32() { unsafe { assert_eq!(32u32.ref_to_slice().len(), 4); assert_eq!(0u32.ref_to_slice().len(), 4); assert_eq!(255u32.ref_to_slice().len(), 4); assert_eq!(0xff0fbedu32.ref_to_slice().len(), 4); assert_eq!(u32::unstore(&32u32.ref_to_slice()), &32); assert_eq!(u32::unstore(&0u32.ref_to_slice()), &0); assert_eq!(u32::unstore(&255u32.ref_to_slice()), &255); assert_eq!(u32::unstore(&0xff0fbedu32.ref_to_slice()), &0xff0fbedu32); } }
use std::{mem, ptr, slice}; pub trait Storeable { fn size(&self) -> usize; unsafe fn ref_to_bytes(&self) -> &u8; unsafe fn ref_to_slice(&self) -> &[u8]; unsafe fn bytes_to_ref(&u8, usize) -> &Self; unsafe fn slice_to_ref(val: &[u8], size: usize) -> &Self; unsafe fn bytes_to_mut(&mut u8, usize) -> &mut Self; unsafe fn clone_box(&self) -> Box<Self>; unsafe fn copy_to_mut(&self, &mut Self) -> usize; } pub trait UnStoreable: Storeable { fn size_from_bytes(bytes: &u8) -> usize; fn size_from_slice(bytes: &[u8]) -> usize; unsafe fn unstore(bytes: &[u8]) -> &Self { let size = <Self as UnStoreable>::size_from_slice(bytes); <Self as Storeable>::slice_to_ref(bytes, size) } unsafe fn unstore_mut(bytes: &mut u8) -> &mut Self { let size = <Self as UnStoreable>::size_from_bytes(bytes);
pl<V> Storeable for [V] { fn size(&self) -> usize { mem::size_of::<V>() * self.len() } unsafe fn ref_to_bytes(&self) -> &u8 { mem::transmute(self.as_ptr()) } unsafe fn ref_to_slice(&self) -> &[u8] { let ptr = self as *const _ as *const u8; let size = self.size(); slice::from_raw_parts(ptr, size) } unsafe fn bytes_to_ref(val: &u8, size: usize) -> &Self { assert_eq!(size % mem::size_of::<V>(), 0); slice::from_raw_parts(val as *const _ as *const _, size / mem::size_of::<V>()) } unsafe fn slice_to_ref(val: &[u8], size: usize) -> &Self { assert_eq!(size % mem::size_of::<V>(), 0); assert_eq!(val.len(), size); slice::from_raw_parts(val.as_ptr() as *const V, size / mem::size_of::<V>()) } unsafe fn bytes_to_mut(val: &mut u8, size: usize) -> &mut Self { assert_eq!(size % mem::size_of::<V>(), 0); slice::from_raw_parts_mut(val as *mut _ as *mut _, size / mem::size_of::<V>()) } unsafe fn clone_box(&self) -> Box<Self> { let mut v = Vec::with_capacity(self.len()); v.set_len(self.len()); let mut b = v.into_boxed_slice(); ptr::copy_nonoverlapping(self.as_ptr(), b.as_mut_ptr(), self.len()); b } unsafe fn copy_to_mut(&self, out: &mut Self) -> usize { let to_copy = ::std::cmp::min(self.len(), out.len()); ptr::copy(self.as_ptr(), out.as_mut_ptr(), to_copy); to_copy * mem::size_of::<V>() } } impl<V> UnStoreable for V { fn size_from_bytes(_: &u8) -> usize { mem::size_of::<Self>() } fn size_from_slice(_: &[u8]) -> usize { mem::size_of::<Self>() } } impl<V> UnStoreable for [V] { fn size_from_bytes(_: &u8) -> usize { unimplemented!() } fn size_from_slice(bytes: &[u8]) -> usize { bytes.len() } } #[test] fn store_u8() { unsafe { assert_eq!(32u8.ref_to_slice(), &[32]); assert_eq!(0u8.ref_to_slice(), &[0]); assert_eq!(255u8.ref_to_slice(), &[255]); } } #[test] fn round_u32() { unsafe { assert_eq!(32u32.ref_to_slice().len(), 4); assert_eq!(0u32.ref_to_slice().len(), 4); assert_eq!(255u32.ref_to_slice().len(), 4); assert_eq!(0xff0fbedu32.ref_to_slice().len(), 4); assert_eq!(u32::unstore(&32u32.ref_to_slice()), &32); assert_eq!(u32::unstore(&0u32.ref_to_slice()), &0); assert_eq!(u32::unstore(&255u32.ref_to_slice()), &255); assert_eq!(u32::unstore(&0xff0fbedu32.ref_to_slice()), &0xff0fbedu32); } }
<Self as Storeable>::bytes_to_mut(bytes, size) } } impl<V> Storeable for V { fn size(&self) -> usize { mem::size_of::<Self>() } unsafe fn ref_to_bytes(&self) -> &u8 { mem::transmute(self) } unsafe fn ref_to_slice(&self) -> &[u8] { let ptr = self as *const V as *const u8; let size = self.size(); slice::from_raw_parts(ptr, size) } unsafe fn bytes_to_ref(val: &u8, _size: usize) -> &Self { mem::transmute(val) } unsafe fn slice_to_ref(val: &[u8], size: usize) -> &Self { assert_eq!(val.len(), size); mem::transmute(val.as_ptr()) } unsafe fn bytes_to_mut(val: &mut u8, size: usize) -> &mut Self { assert_eq!(size, mem::size_of::<Self>()); mem::transmute(val) } unsafe fn clone_box(&self) -> Box<Self> { let mut b = Box::new(mem::uninitialized()); ptr::copy_nonoverlapping(self, &mut *b, 1); b } unsafe fn copy_to_mut(&self, out: &mut Self) -> usize { ptr::copy(self, out, 1); mem::size_of::<Self>() } } im
random
[ { "content": "pub fn slice_to_multi(bytes: &mut [u8]) {\n\n bytes[0] = unsafe { ::std::mem::transmute(EntryKind::Multiput) };\n\n unsafe { debug_assert!(EntryContents::try_ref(bytes).is_ok()) }\n\n}\n\n\n", "file_path": "fuzzy_log_packets/src/lib.rs", "rank": 0, "score": 302795.3422425555 },...
Rust
crates/ra_ide_api_light/src/typing.rs
hdhoang/rust-analyzer
da3802b2ce4796461a9fff22f4e9c6fd890879b2
use ra_syntax::{ AstNode, SourceFile, SyntaxKind::*, SyntaxNode, TextUnit, TextRange, algo::{find_node_at_offset, find_leaf_at_offset, LeafAtOffset}, ast::{self, AstToken}, }; use crate::{LocalEdit, TextEditBuilder, formatting::leading_indent}; pub fn on_enter(file: &SourceFile, offset: TextUnit) -> Option<LocalEdit> { let comment = find_leaf_at_offset(file.syntax(), offset) .left_biased() .and_then(ast::Comment::cast)?; if let ast::CommentFlavor::Multiline = comment.flavor() { return None; } let prefix = comment.prefix(); if offset < comment.syntax().range().start() + TextUnit::of_str(prefix) + TextUnit::from(1) { return None; } let indent = node_indent(file, comment.syntax())?; let inserted = format!("\n{}{} ", indent, prefix); let cursor_position = offset + TextUnit::of_str(&inserted); let mut edit = TextEditBuilder::default(); edit.insert(offset, inserted); Some(LocalEdit { label: "on enter".to_string(), edit: edit.finish(), cursor_position: Some(cursor_position), }) } fn node_indent<'a>(file: &'a SourceFile, node: &SyntaxNode) -> Option<&'a str> { let ws = match find_leaf_at_offset(file.syntax(), node.range().start()) { LeafAtOffset::Between(l, r) => { assert!(r == node); l } LeafAtOffset::Single(n) => { assert!(n == node); return Some(""); } LeafAtOffset::None => unreachable!(), }; if ws.kind() != WHITESPACE { return None; } let text = ws.leaf_text().unwrap(); let pos = text.as_str().rfind('\n').map(|it| it + 1).unwrap_or(0); Some(&text[pos..]) } pub fn on_eq_typed(file: &SourceFile, eq_offset: TextUnit) -> Option<LocalEdit> { assert_eq!(file.syntax().text().char_at(eq_offset), Some('=')); let let_stmt: &ast::LetStmt = find_node_at_offset(file.syntax(), eq_offset)?; if let_stmt.has_semi() { return None; } if let Some(expr) = let_stmt.initializer() { let expr_range = expr.syntax().range(); if expr_range.contains(eq_offset) && eq_offset != expr_range.start() { return None; } if file .syntax() .text() .slice(eq_offset..expr_range.start()) .contains('\n') { return None; } } else { return None; } let offset = let_stmt.syntax().range().end(); let mut edit = TextEditBuilder::default(); edit.insert(offset, ";".to_string()); Some(LocalEdit { label: "add semicolon".to_string(), edit: edit.finish(), cursor_position: None, }) } pub fn on_dot_typed(file: &SourceFile, dot_offset: TextUnit) -> Option<LocalEdit> { assert_eq!(file.syntax().text().char_at(dot_offset), Some('.')); let whitespace = find_leaf_at_offset(file.syntax(), dot_offset) .left_biased() .and_then(ast::Whitespace::cast)?; let current_indent = { let text = whitespace.text(); let newline = text.rfind('\n')?; &text[newline + 1..] }; let current_indent_len = TextUnit::of_str(current_indent); let field_expr = whitespace .syntax() .parent() .and_then(ast::FieldExpr::cast)?; let prev_indent = leading_indent(field_expr.syntax())?; let target_indent = format!(" {}", prev_indent); let target_indent_len = TextUnit::of_str(&target_indent); if current_indent_len == target_indent_len { return None; } let mut edit = TextEditBuilder::default(); edit.replace( TextRange::from_to(dot_offset - current_indent_len, dot_offset), target_indent.into(), ); let res = LocalEdit { label: "reindent dot".to_string(), edit: edit.finish(), cursor_position: Some( dot_offset + target_indent_len - current_indent_len + TextUnit::of_char('.'), ), }; Some(res) } #[cfg(test)] mod tests { use crate::test_utils::{add_cursor, assert_eq_text, extract_offset}; use super::*; #[test] fn test_on_eq_typed() { fn type_eq(before: &str, after: &str) { let (offset, before) = extract_offset(before); let mut edit = TextEditBuilder::default(); edit.insert(offset, "=".to_string()); let before = edit.finish().apply(&before); let file = SourceFile::parse(&before); if let Some(result) = on_eq_typed(&file, offset) { let actual = result.edit.apply(&before); assert_eq_text!(after, &actual); } else { assert_eq_text!(&before, after) }; } type_eq( r" fn foo() { let foo <|> 1 + 1 } ", r" fn foo() { let foo = 1 + 1; } ", ); } fn type_dot(before: &str, after: &str) { let (offset, before) = extract_offset(before); let mut edit = TextEditBuilder::default(); edit.insert(offset, ".".to_string()); let before = edit.finish().apply(&before); let file = SourceFile::parse(&before); if let Some(result) = on_dot_typed(&file, offset) { let actual = result.edit.apply(&before); assert_eq_text!(after, &actual); } else { assert_eq_text!(&before, after) }; } #[test] fn indents_new_chain_call() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) . } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) . } ", ) } #[test] fn indents_new_chain_call_with_semi() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|>; } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .; } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|>; } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .; } ", ) } #[test] fn indents_continued_chain_call() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() . } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() . } ", ); } #[test] fn indents_middle_of_chain_call() { type_dot( r" fn source_impl() { let var = enum_defvariant_list().unwrap() <|> .nth(92) .unwrap(); } ", r" fn source_impl() { let var = enum_defvariant_list().unwrap() . .nth(92) .unwrap(); } ", ); type_dot( r" fn source_impl() { let var = enum_defvariant_list().unwrap() <|> .nth(92) .unwrap(); } ", r" fn source_impl() { let var = enum_defvariant_list().unwrap() . .nth(92) .unwrap(); } ", ); } #[test] fn dont_indent_freestanding_dot() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { . } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { . } ", ); } #[test] fn test_on_enter() { fn apply_on_enter(before: &str) -> Option<String> { let (offset, before) = extract_offset(before); let file = SourceFile::parse(&before); let result = on_enter(&file, offset)?; let actual = result.edit.apply(&before); let actual = add_cursor(&actual, result.cursor_position.unwrap()); Some(actual) } fn do_check(before: &str, after: &str) { let actual = apply_on_enter(before).unwrap(); assert_eq_text!(after, &actual); } fn do_check_noop(text: &str) { assert!(apply_on_enter(text).is_none()) } do_check( r" /// Some docs<|> fn foo() { } ", r" /// Some docs /// <|> fn foo() { } ", ); do_check( r" impl S { /// Some<|> docs. fn foo() {} } ", r" impl S { /// Some /// <|> docs. fn foo() {} } ", ); do_check_noop(r"<|>//! docz"); } }
use ra_syntax::{ AstNode, SourceFile, SyntaxKind::*, SyntaxNode, TextUnit, TextRange, algo::{find_node_at_offset, find_leaf_at_offset, LeafAtOffset}, ast::{self, AstToken}, }; use crate::{LocalEdit, TextEditBuilder, formatting::leading_indent}; pub fn on_enter(file: &SourceFile, offset: TextUnit) -> Option<LocalEdit> { let comment = find_leaf_at_offset(file.syntax(), offset) .left_biased() .and_then(ast::Comment::cast)?; if let ast::CommentFlavor::Multiline = comment.flavor() { return None; } let prefix = comment.prefix(); if offset < comment.syntax().range().start() + TextUnit::of_str(prefix) + TextUnit::from(1) { return None; } let indent = node_indent(file, comment.syntax())?; let inserted = format!("\n{}{} ", indent, prefix); let cursor_position = offset + TextUnit::of_str(&inserted); let mut edit = TextEditBuilder::default(); edit.insert(offset, inserted); Some(LocalEdit { label: "on enter".to_string(), edit: edit.finish(), cursor_position: Some(cursor_position), }) } fn node_indent<'a>(file: &'a SourceFile, node: &SyntaxNode) -> Option<&'a str> { let ws = match find_leaf_at_offset(file.syntax(), node.range().start()) { LeafAtOffset::Between(l, r) => { assert!(r == node); l } LeafAtOffset::Single(n) => { assert!(n == node); return Some(""); } LeafAtOffset::None => unreachable!(), }; if ws.kind() != WHITESPACE { return None; } let text = ws.leaf_text().unwrap(); let pos = text.as_str().rfind('\n').map(|it| it + 1).unwrap_or(0); Some(&text[pos..]) } pub fn on_eq_typed(file: &SourceFile, eq_offset: TextUnit) -> Option<LocalEdit> { assert_eq!(file.syntax().text().char_at(eq_offset), Some('=')); let let_stmt: &ast::LetStmt = find_node_at_offset(file.syntax(), eq_offset)?; if let_stmt.has_semi() { return None; } if let Some(expr) = let_stmt.initializer() { let expr_range = expr.syntax().range(); if expr_range.contains(eq_offset) && eq_offset != expr_range.start() { return None; } if file .syntax() .text() .slice(eq_offset..expr_range.start()) .contains('\n') { return None; } } else { return None; } let offset = let_stmt.syntax().range().end(); let mut edit = TextEditBuilder::default(); edit.insert(offset, ";".to_string()); Some(LocalEdit { label: "add semicolon".to_string(), edit: edit.finish(), cursor_position: None, }) } pub fn on_dot_typed(file: &SourceFile, dot_offset: TextUnit) -> Option<LocalEdit> { assert_eq!(file.syntax().text().char_at(dot_offset), Some('.')); let whitespace = find_leaf_at_offset(file.syntax(), dot_offset) .left_biased() .and_then(ast::Whitespace::cast)?; let current_indent = { let text = whitespace.text(); let newline = text.rfind('\n')?; &text[newline + 1..] }; let current_indent_len = TextUnit::of_str(current_indent); let field_expr = whitespace .syntax() .parent() .and_then(ast::FieldExpr::cast)?; let prev_indent = leading_indent(field_expr.syntax())?; let target_indent = format!(" {}", prev_indent); let target_indent_len = TextUnit::of_str(&target_indent); if current_indent_len == target_indent_len { return None; } let mut edit = TextEditBuilder::default(); edit.replace( TextRange::from_to(dot_offset - current_indent_len, dot_offset), target_indent.into(), ); let res = LocalEdit { label: "reindent dot".to_string(), edit: edit.finish(), cursor_position: Some( dot_offset + target_indent_len - current_indent_len + TextUnit::of_char('.'), ), }; Some(res) } #[cfg(test)] mod tests { use crate::test_utils::{add_cursor, assert_eq_text, extract_offset}; use super::*; #[test] fn test_on_eq_typed() { fn type_eq(before: &str, after: &str) { let (offset, before) = extract_offset(before); let mut edit = TextEditBuilder::default(); edit.insert(offset, "=".to_string()); let before = edit.finish().apply(&before); let file = SourceFile::parse(&before); if let Some(result) = on_eq_typed(&file, offset) { let actual = result.edit.apply(&before); assert_eq_text!(after, &actual); } else { assert_eq_text!(&before, after) }; } type_eq( r" fn foo() { let foo <|> 1 + 1 } ", r" fn foo() { let foo = 1 + 1; } ", ); } fn type_dot(before: &str, after: &str) { let (offset, before) = extract_offset(before); let mut edit = TextEditBuilder::default(); edit.insert(offset, ".".to_string()); let before = edit.finish().apply(&before); let file = SourceFile::parse(&before); if let Some(result) = on_dot_typed(&file, offset) { let actual = result.edit.apply(&before); assert_eq_text!(after, &actual); } else { assert_eq_text!(&before, after) }; } #[test] fn indents_new_chain_call() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) . } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) . } ", ) } #[test] fn indents_new_chain_call_with_semi() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|>; } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .; } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|>; } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .; } ", ) } #[test]
#[test] fn indents_middle_of_chain_call() { type_dot( r" fn source_impl() { let var = enum_defvariant_list().unwrap() <|> .nth(92) .unwrap(); } ", r" fn source_impl() { let var = enum_defvariant_list().unwrap() . .nth(92) .unwrap(); } ", ); type_dot( r" fn source_impl() { let var = enum_defvariant_list().unwrap() <|> .nth(92) .unwrap(); } ", r" fn source_impl() { let var = enum_defvariant_list().unwrap() . .nth(92) .unwrap(); } ", ); } #[test] fn dont_indent_freestanding_dot() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { . } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { . } ", ); } #[test] fn test_on_enter() { fn apply_on_enter(before: &str) -> Option<String> { let (offset, before) = extract_offset(before); let file = SourceFile::parse(&before); let result = on_enter(&file, offset)?; let actual = result.edit.apply(&before); let actual = add_cursor(&actual, result.cursor_position.unwrap()); Some(actual) } fn do_check(before: &str, after: &str) { let actual = apply_on_enter(before).unwrap(); assert_eq_text!(after, &actual); } fn do_check_noop(text: &str) { assert!(apply_on_enter(text).is_none()) } do_check( r" /// Some docs<|> fn foo() { } ", r" /// Some docs /// <|> fn foo() { } ", ); do_check( r" impl S { /// Some<|> docs. fn foo() {} } ", r" impl S { /// Some /// <|> docs. fn foo() {} } ", ); do_check_noop(r"<|>//! docz"); } }
fn indents_continued_chain_call() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() . } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() . } ", ); }
function_block-full_function
[]
Rust
vm_control/src/client.rs
google/crosvm
df929efce3261ca5383f66eea6c7041b3439eb77
use crate::*; use base::{info, validate_raw_descriptor, RawDescriptor, Tube, UnixSeqpacket}; use remain::sorted; use thiserror::Error; use std::fs::OpenOptions; use std::num::ParseIntError; use std::path::{Path, PathBuf}; #[sorted] #[derive(Error, Debug)] enum ModifyBatError { #[error("{0}")] BatControlErr(BatControlResult), } #[sorted] #[derive(Error, Debug)] pub enum ModifyUsbError { #[error("argument missing: {0}")] ArgMissing(&'static str), #[error("failed to parse argument {0} value `{1}`")] ArgParse(&'static str, String), #[error("failed to parse integer argument {0} value `{1}`: {2}")] ArgParseInt(&'static str, String, ParseIntError), #[error("failed to validate file descriptor: {0}")] FailedDescriptorValidate(base::Error), #[error("path `{0}` does not exist")] PathDoesNotExist(PathBuf), #[error("socket failed")] SocketFailed, #[error("unexpected response: {0}")] UnexpectedResponse(VmResponse), #[error("unknown command: `{0}`")] UnknownCommand(String), #[error("{0}")] UsbControl(UsbControlResult), } pub type ModifyUsbResult<T> = std::result::Result<T, ModifyUsbError>; fn raw_descriptor_from_path(path: &Path) -> ModifyUsbResult<RawDescriptor> { if !path.exists() { return Err(ModifyUsbError::PathDoesNotExist(path.to_owned())); } let raw_descriptor = path .file_name() .and_then(|fd_osstr| fd_osstr.to_str()) .map_or( Err(ModifyUsbError::ArgParse( "USB_DEVICE_PATH", path.to_string_lossy().into_owned(), )), |fd_str| { fd_str.parse::<libc::c_int>().map_err(|e| { ModifyUsbError::ArgParseInt("USB_DEVICE_PATH", fd_str.to_owned(), e) }) }, )?; validate_raw_descriptor(raw_descriptor).map_err(ModifyUsbError::FailedDescriptorValidate) } pub type VmsRequestResult = std::result::Result<(), ()>; pub fn vms_request(request: &VmRequest, socket_path: &Path) -> VmsRequestResult { let response = handle_request(request, socket_path)?; info!("request response was {}", response); Ok(()) } pub fn do_usb_attach( socket_path: &Path, bus: u8, addr: u8, vid: u16, pid: u16, dev_path: &Path, ) -> ModifyUsbResult<UsbControlResult> { let usb_file: File = if dev_path.parent() == Some(Path::new("/proc/self/fd")) { unsafe { File::from_raw_descriptor(raw_descriptor_from_path(dev_path)?) } } else { OpenOptions::new() .read(true) .write(true) .open(dev_path) .map_err(|_| ModifyUsbError::UsbControl(UsbControlResult::FailedToOpenDevice))? }; let request = VmRequest::UsbCommand(UsbControlCommand::AttachDevice { bus, addr, vid, pid, file: usb_file, }); let response = handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?; match response { VmResponse::UsbResponse(usb_resp) => Ok(usb_resp), r => Err(ModifyUsbError::UnexpectedResponse(r)), } } pub fn do_usb_detach(socket_path: &Path, port: u8) -> ModifyUsbResult<UsbControlResult> { let request = VmRequest::UsbCommand(UsbControlCommand::DetachDevice { port }); let response = handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?; match response { VmResponse::UsbResponse(usb_resp) => Ok(usb_resp), r => Err(ModifyUsbError::UnexpectedResponse(r)), } } pub fn do_usb_list(socket_path: &Path) -> ModifyUsbResult<UsbControlResult> { let mut ports: [u8; USB_CONTROL_MAX_PORTS] = Default::default(); for (index, port) in ports.iter_mut().enumerate() { *port = index as u8 } let request = VmRequest::UsbCommand(UsbControlCommand::ListDevice { ports }); let response = handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?; match response { VmResponse::UsbResponse(usb_resp) => Ok(usb_resp), r => Err(ModifyUsbError::UnexpectedResponse(r)), } } pub type DoModifyBatteryResult = std::result::Result<(), ()>; pub fn do_modify_battery( socket_path: &Path, battery_type: &str, property: &str, target: &str, ) -> DoModifyBatteryResult { let response = match battery_type.parse::<BatteryType>() { Ok(type_) => match BatControlCommand::new(property.to_string(), target.to_string()) { Ok(cmd) => { let request = VmRequest::BatCommand(type_, cmd); Ok(handle_request(&request, socket_path)?) } Err(e) => Err(ModifyBatError::BatControlErr(e)), }, Err(e) => Err(ModifyBatError::BatControlErr(e)), }; match response { Ok(response) => { println!("{}", response); Ok(()) } Err(e) => { println!("error {}", e); Err(()) } } } pub type HandleRequestResult = std::result::Result<VmResponse, ()>; pub fn handle_request(request: &VmRequest, socket_path: &Path) -> HandleRequestResult { match UnixSeqpacket::connect(&socket_path) { Ok(s) => { let socket = Tube::new(s); if let Err(e) = socket.send(request) { error!( "failed to send request to socket at '{:?}': {}", socket_path, e ); return Err(()); } match socket.recv() { Ok(response) => Ok(response), Err(e) => { error!( "failed to send request to socket at '{:?}': {}", socket_path, e ); Err(()) } } } Err(e) => { error!("failed to connect to socket at '{:?}': {}", socket_path, e); Err(()) } } }
use crate::*; use base::{info, validate_raw_descriptor, RawDescriptor, Tube, UnixSeqpacket}; use remain::sorted; use thiserror::Error; use std::fs::OpenOptions; use std::num::ParseIntError; use std::path::{Path, PathBuf}; #[sorted] #[derive(Error, Debug)] enum ModifyBatError { #[error("{0}")] BatControlErr(BatControlResult), } #[sorted] #[derive(Error, Debug)] pub enum ModifyUsbError { #[error("argument missing: {0}")] ArgMissing(&'static str), #[error("failed to parse argument {0} value `{1}`")] ArgParse(&'static str, String), #[error("failed to parse integer argument {0} value `{1}`: {2}")] ArgParseInt(&'static str, String, ParseIntError), #[error("failed to validate file descriptor: {0}")] FailedDescriptorValidate(base::Error), #[error("path `{0}` does not exist")] PathDoesNotExist(PathBuf), #[error("socket failed")] SocketFailed, #[error("unexpected response: {0}")] UnexpectedResponse(VmResponse), #[error("unknown command: `{0}`")] UnknownCommand(String), #[error("{0}")] UsbControl(UsbControlResult), } pub type ModifyUsbResult<T> = std::result::Result<T, ModifyUsbError>; fn raw_descriptor_from_path(path: &Path) -> ModifyUsbResult<RawDescriptor> { if !path.exists() { return Err(ModifyUsbError::PathDoesNotExist(path.to_owned())); } let raw_descriptor = path .file_name() .and_then(|fd_osstr| fd_osstr.to_str()) .map_or( Err(ModifyUsbError::ArgParse( "USB_DEVICE_PATH", path.to_string_lossy().into_owned(), )), |fd_str| { fd_str.parse::<libc::c_int>().map_err(|e| { ModifyUsbError::ArgParseInt("USB_DEVICE_PATH", fd_str.to_owned(), e) }) }, )?; validate_raw_descriptor(raw_descriptor).map_err(ModifyUsbError::FailedDescriptorValidate) } pub type VmsRequestResult = std::result::Result<(), ()>; pub fn vms_request(request: &VmRequest, socket_path: &Path) -> VmsRequestResult { let response = handle_request(request, socket_path)?; info!("request response was {}", response); Ok(()) } pub fn do_usb_attach( socket_path: &Path, bus: u8, addr: u8, vid: u16, pid: u16, dev_path: &Path, ) -> ModifyUsbResult<UsbControlResult> { let usb_file: File = if dev_path.parent() == Some(Path::new("/proc/self/fd")) { unsafe { File::from_raw_descriptor(raw_descriptor_from_path(dev_path)?) } } else { OpenOptions::new() .read(true) .write(true) .open(dev_path) .map_err(|_| ModifyUsbError::UsbControl(UsbControlResult::FailedToOpenDevice))? }; let request = VmRequest::UsbCommand(UsbControlCommand::AttachDevice { bus, addr, vid, pid, file: usb_file, }); let response = handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?; match response { VmResponse::UsbResponse(usb_resp) => Ok(usb_resp), r => Err(ModifyUsbError::UnexpectedResponse(r)), } } pub fn do_usb_detach(socket_path: &Path, port: u8) -> ModifyUsbResult<UsbControlResult> { let request = VmRequest::UsbCommand(UsbControlCommand::DetachDevice { port }); let response = handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?; match response { VmResponse::UsbResponse(usb_resp) => Ok(usb_resp), r => Err(ModifyUsbError::UnexpectedResponse(r)), } } pub fn do_usb_list(socket_path: &Path) -> ModifyUsbResult<UsbControlResult> { let mut ports: [u8; USB_CONTROL_MAX_PORTS] = Default::default(); for (index, port) in ports.iter_mut().enumerate() { *port = index as u8 } let request = VmRequest::UsbCommand(UsbControlCommand::ListDevice { ports }); let response = handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?; match response { VmResponse::UsbResponse(usb_resp) => Ok(usb_resp), r => Err(ModifyUsbError::UnexpectedResponse(r)), } } pub type DoModifyBatteryResult = std::result::Result<(), ()>; pub fn do_modify_battery( socket_path: &Path, battery_type: &str, property: &str, target: &str, ) -> DoModifyBatteryResult { let response = match battery_type.parse::<Batte
let request = VmRequest::BatCommand(type_, cmd); Ok(handle_request(&request, socket_path)?) } Err(e) => Err(ModifyBatError::BatControlErr(e)), }, Err(e) => Err(ModifyBatError::BatControlErr(e)), }; match response { Ok(response) => { println!("{}", response); Ok(()) } Err(e) => { println!("error {}", e); Err(()) } } } pub type HandleRequestResult = std::result::Result<VmResponse, ()>; pub fn handle_request(request: &VmRequest, socket_path: &Path) -> HandleRequestResult { match UnixSeqpacket::connect(&socket_path) { Ok(s) => { let socket = Tube::new(s); if let Err(e) = socket.send(request) { error!( "failed to send request to socket at '{:?}': {}", socket_path, e ); return Err(()); } match socket.recv() { Ok(response) => Ok(response), Err(e) => { error!( "failed to send request to socket at '{:?}': {}", socket_path, e ); Err(()) } } } Err(e) => { error!("failed to connect to socket at '{:?}': {}", socket_path, e); Err(()) } } }
ryType>() { Ok(type_) => match BatControlCommand::new(property.to_string(), target.to_string()) { Ok(cmd) => {
function_block-random_span
[ { "content": "pub fn win32_wide_string(value: &str) -> Vec<u16> {\n\n OsStr::new(value).encode_wide().chain(once(0)).collect()\n\n}\n\n\n\n/// Returns the length, in u16 words (*not* UTF-16 chars), of a null-terminated u16 string.\n\n/// Safe when `wide` is non-null and points to a u16 string terminated by a...
Rust
glib/src/wrapper.rs
abdulrehman-git/gtk-rs
068311ececbb9d84e3697412e789add054f33f83
#[macro_export] macro_rules! glib_wrapper { ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, } ) => { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, get_type => || $get_type_expr:expr, } ) => { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr, @get_type $get_type_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, init => |$init_arg:ident| $init_expr:expr, clear => |$clear_arg:ident| $clear_expr:expr, } ) => { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr, @init $init_arg $init_expr, @clear $clear_arg $clear_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, init => |$init_arg:ident| $init_expr:expr, clear => |$clear_arg:ident| $clear_expr:expr, get_type => || $get_type_expr:expr, } ) => { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr, @init $init_arg $init_expr, @clear $clear_arg $clear_expr, @get_type $get_type_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Shared<$ffi_name:ty>); match fn { ref => |$ref_arg:ident| $ref_expr:expr, unref => |$unref_arg:ident| $unref_expr:expr, } ) => { $crate::glib_shared_wrapper!([$($attr)*] $name, $ffi_name, @ref $ref_arg $ref_expr, @unref $unref_arg $unref_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Shared<$ffi_name:ty>); match fn { ref => |$ref_arg:ident| $ref_expr:expr, unref => |$unref_arg:ident| $unref_expr:expr, get_type => || $get_type_expr:expr, } ) => { $crate::glib_shared_wrapper!([$($attr)*] $name, $ffi_name, @ref $ref_arg $ref_expr, @unref $unref_arg $unref_expr, @get_type $get_type_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>); match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>); match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, @extends [], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>) @extends $($extends:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [$($extends),+], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>) @extends $($extends:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, @extends [$($extends),+], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>) @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>) @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, @extends [], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>) @extends $($extends:path),+, @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [$($extends),+], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>) @extends $($extends:path),+, @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, @extends [$($extends),+], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>); ) => { use glib::translate::ToGlib; $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>) @implements $($implements:path),+; ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>) @extends $($extends:path),+; ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [$($extends),+], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>) @extends $($extends:path),+, @implements $($implements:path),+; ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [$($extends),+], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Interface<$ffi_name:ty>); match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@interface [$($attr)*] $name, $ffi_name, @get_type $get_type_expr, @requires []); }; ( $(#[$attr:meta])* pub struct $name:ident(Interface<$ffi_name:ty>) @requires $($requires:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@interface [$($attr)*] $name, $ffi_name, @get_type $get_type_expr, @requires [$($requires),+]); }; }
#[macro_export] macro_rules! glib_wrapper { ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, } ) => { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, get_type => || $get_type_expr:expr, } )
name, $ffi_class_name, @get_type $get_type_expr, @extends [], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>) @extends $($extends:path),+, @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [$($extends),+], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>) @extends $($extends:path),+, @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, @extends [$($extends),+], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>); ) => { use glib::translate::ToGlib; $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>) @implements $($implements:path),+; ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>) @extends $($extends:path),+; ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [$($extends),+], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>) @extends $($extends:path),+, @implements $($implements:path),+; ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [$($extends),+], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Interface<$ffi_name:ty>); match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@interface [$($attr)*] $name, $ffi_name, @get_type $get_type_expr, @requires []); }; ( $(#[$attr:meta])* pub struct $name:ident(Interface<$ffi_name:ty>) @requires $($requires:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@interface [$($attr)*] $name, $ffi_name, @get_type $get_type_expr, @requires [$($requires),+]); }; }
=> { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr, @get_type $get_type_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, init => |$init_arg:ident| $init_expr:expr, clear => |$clear_arg:ident| $clear_expr:expr, } ) => { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr, @init $init_arg $init_expr, @clear $clear_arg $clear_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, init => |$init_arg:ident| $init_expr:expr, clear => |$clear_arg:ident| $clear_expr:expr, get_type => || $get_type_expr:expr, } ) => { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr, @init $init_arg $init_expr, @clear $clear_arg $clear_expr, @get_type $get_type_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Shared<$ffi_name:ty>); match fn { ref => |$ref_arg:ident| $ref_expr:expr, unref => |$unref_arg:ident| $unref_expr:expr, } ) => { $crate::glib_shared_wrapper!([$($attr)*] $name, $ffi_name, @ref $ref_arg $ref_expr, @unref $unref_arg $unref_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Shared<$ffi_name:ty>); match fn { ref => |$ref_arg:ident| $ref_expr:expr, unref => |$unref_arg:ident| $unref_expr:expr, get_type => || $get_type_expr:expr, } ) => { $crate::glib_shared_wrapper!([$($attr)*] $name, $ffi_name, @ref $ref_arg $ref_expr, @unref $unref_arg $unref_expr, @get_type $get_type_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>); match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>); match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, @extends [], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>) @extends $($extends:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [$($extends),+], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>) @extends $($extends:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, @extends [$($extends),+], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>) @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>) @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_
random
[ { "content": "/// Same as [`set_prgname()`].\n\n///\n\n/// [`set_prgname()`]: fn.set_prgname.html\n\npub fn set_program_name(name: Option<&str>) {\n\n set_prgname(name)\n\n}\n\n\n", "file_path": "glib/src/utils.rs", "rank": 0, "score": 251826.54139678564 }, { "content": "pub fn accelerato...
Rust
src/parser/values.rs
ithinuel/async-gcode
0f7ee3efc4fa0023766e3f436472573ef1fb0f5b
#![allow(clippy::useless_conversion)] use futures::{Stream, StreamExt}; #[cfg(all(not(feature = "std"), feature = "string-value"))] use alloc::string::String; use crate::{ stream::PushBackable, types::{Literal, ParseResult}, utils::skip_whitespaces, Error, }; #[cfg(not(feature = "parse-expressions"))] use crate::types::RealValue; #[cfg(any(feature = "parse-parameters", feature = "parse-expressions"))] pub use crate::types::expressions::{Expression, Operator}; pub(crate) async fn parse_number<S, E>(input: &mut S) -> Option<Result<(u32, u32), E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let mut n = 0; let mut order = 1; let res = loop { let b = match input.next().await? { Ok(b) => b, Err(e) => return Some(Err(e)), }; match b { b'0'..=b'9' => { let digit = u32::from(b - b'0'); n = n * 10 + digit; order *= 10; } _ => { input.push_back(b); break Ok((n, order)); } } }; Some(res) } async fn parse_real_literal<S, E>(input: &mut S) -> Option<ParseResult<f64, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let mut b = try_result!(input.next()); let mut negativ = false; if b == b'-' || b == b'+' { negativ = b == b'-'; try_result!(skip_whitespaces(input)); b = try_result!(input.next()); } let int = if b != b'.' { input.push_back(b); let (v, _) = try_result!(parse_number(input)); try_result!(skip_whitespaces(input)); b = try_result!(input.next()); Some(v) } else { None }; let dec = if b == b'.' { try_result!(skip_whitespaces(input)); Some(try_result!(parse_number(input))) } else { input.push_back(b); None }; let res = if int.is_none() && dec.is_none() { ParseResult::Parsing(Error::BadNumberFormat.into()) } else { let int = int.map(f64::from).unwrap_or(0.); let (dec, ord) = dec .map(|(dec, ord)| (dec.into(), ord.into())) .unwrap_or((0., 1.)); ParseResult::Ok((if negativ { -1. } else { 1. }) * (int + dec / ord)) }; Some(res) } #[cfg(feature = "string-value")] async fn parse_string_literal<S, E>(input: &mut S) -> Option<ParseResult<String, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { #[cfg(not(feature = "std"))] use alloc::vec::Vec; let mut array = Vec::new(); loop { match try_result!(input.next()) { b'"' => break, b'\\' => { array.push(try_result!(input.next())); } b => array.push(b), } } match String::from_utf8(array) { Ok(string) => Some(ParseResult::Ok(string)), Err(_) => Some(Error::InvalidUTF8String.into()), } } pub(crate) async fn parse_literal<S, E>(input: &mut S) -> Option<ParseResult<Literal, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let b = try_result!(input.next()); Some(match b { b'+' | b'-' | b'.' | b'0'..=b'9' => { input.push_back(b); ParseResult::Ok(Literal::from(try_parse!(parse_real_literal(input)))) } #[cfg(feature = "string-value")] b'"' => ParseResult::Ok(Literal::from(try_parse!(parse_string_literal(input)))), _ => Error::UnexpectedByte(b).into(), }) } #[cfg(not(feature = "parse-expressions"))] pub(crate) async fn parse_real_value<S, E>(input: &mut S) -> Option<ParseResult<RealValue, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let b = try_result!(input.next()); let res = match b { b'+' | b'-' | b'.' | b'0'..=b'9' => { input.push_back(b); ParseResult::Ok(RealValue::from(try_parse!(parse_literal(input)))) } #[cfg(feature = "string-value")] b'"' => { input.push_back(b); ParseResult::Ok(RealValue::from(try_parse!(parse_literal(input)))) } #[cfg(feature = "parse-parameters")] b'#' => { #[cfg(not(feature = "std"))] use alloc::vec::Vec; let mut n = 1; let literal = loop { try_result!(skip_whitespaces(input)); let b = try_result!(input.next()); if b != b'#' { input.push_back(b); break try_parse!(parse_literal(input)); } n += 1; }; let vec: Vec<_> = core::iter::once(literal.into()) .chain(core::iter::repeat(Operator::GetParameter.into()).take(n)) .collect(); ParseResult::Ok(Expression(vec).into()) } #[cfg(feature = "optional-value")] b => { input.push_back(b); ParseResult::Ok(RealValue::None) } #[cfg(not(feature = "optional-value"))] b => Error::UnexpectedByte(b).into(), }; Some(res) }
#![allow(clippy::useless_conversion)] use futures::{Stream, StreamExt}; #[cfg(all(not(feature = "std"), feature = "string-value"))] use alloc::string::String; use crate::{ stream::PushBackable, types::{Literal, ParseResult}, utils::skip_whitespaces, Error, }; #[cfg(not(feature = "parse-expressions"))] use crate::types::RealValue; #[cfg(any(feature = "parse-parameters", feature = "parse-expressions"))] pub use crate::types::expressions::{Expression, Operator};
async fn parse_real_literal<S, E>(input: &mut S) -> Option<ParseResult<f64, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let mut b = try_result!(input.next()); let mut negativ = false; if b == b'-' || b == b'+' { negativ = b == b'-'; try_result!(skip_whitespaces(input)); b = try_result!(input.next()); } let int = if b != b'.' { input.push_back(b); let (v, _) = try_result!(parse_number(input)); try_result!(skip_whitespaces(input)); b = try_result!(input.next()); Some(v) } else { None }; let dec = if b == b'.' { try_result!(skip_whitespaces(input)); Some(try_result!(parse_number(input))) } else { input.push_back(b); None }; let res = if int.is_none() && dec.is_none() { ParseResult::Parsing(Error::BadNumberFormat.into()) } else { let int = int.map(f64::from).unwrap_or(0.); let (dec, ord) = dec .map(|(dec, ord)| (dec.into(), ord.into())) .unwrap_or((0., 1.)); ParseResult::Ok((if negativ { -1. } else { 1. }) * (int + dec / ord)) }; Some(res) } #[cfg(feature = "string-value")] async fn parse_string_literal<S, E>(input: &mut S) -> Option<ParseResult<String, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { #[cfg(not(feature = "std"))] use alloc::vec::Vec; let mut array = Vec::new(); loop { match try_result!(input.next()) { b'"' => break, b'\\' => { array.push(try_result!(input.next())); } b => array.push(b), } } match String::from_utf8(array) { Ok(string) => Some(ParseResult::Ok(string)), Err(_) => Some(Error::InvalidUTF8String.into()), } } pub(crate) async fn parse_literal<S, E>(input: &mut S) -> Option<ParseResult<Literal, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let b = try_result!(input.next()); Some(match b { b'+' | b'-' | b'.' | b'0'..=b'9' => { input.push_back(b); ParseResult::Ok(Literal::from(try_parse!(parse_real_literal(input)))) } #[cfg(feature = "string-value")] b'"' => ParseResult::Ok(Literal::from(try_parse!(parse_string_literal(input)))), _ => Error::UnexpectedByte(b).into(), }) } #[cfg(not(feature = "parse-expressions"))] pub(crate) async fn parse_real_value<S, E>(input: &mut S) -> Option<ParseResult<RealValue, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let b = try_result!(input.next()); let res = match b { b'+' | b'-' | b'.' | b'0'..=b'9' => { input.push_back(b); ParseResult::Ok(RealValue::from(try_parse!(parse_literal(input)))) } #[cfg(feature = "string-value")] b'"' => { input.push_back(b); ParseResult::Ok(RealValue::from(try_parse!(parse_literal(input)))) } #[cfg(feature = "parse-parameters")] b'#' => { #[cfg(not(feature = "std"))] use alloc::vec::Vec; let mut n = 1; let literal = loop { try_result!(skip_whitespaces(input)); let b = try_result!(input.next()); if b != b'#' { input.push_back(b); break try_parse!(parse_literal(input)); } n += 1; }; let vec: Vec<_> = core::iter::once(literal.into()) .chain(core::iter::repeat(Operator::GetParameter.into()).take(n)) .collect(); ParseResult::Ok(Expression(vec).into()) } #[cfg(feature = "optional-value")] b => { input.push_back(b); ParseResult::Ok(RealValue::None) } #[cfg(not(feature = "optional-value"))] b => Error::UnexpectedByte(b).into(), }; Some(res) }
pub(crate) async fn parse_number<S, E>(input: &mut S) -> Option<Result<(u32, u32), E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let mut n = 0; let mut order = 1; let res = loop { let b = match input.next().await? { Ok(b) => b, Err(e) => return Some(Err(e)), }; match b { b'0'..=b'9' => { let digit = u32::from(b - b'0'); n = n * 10 + digit; order *= 10; } _ => { input.push_back(b); break Ok((n, order)); } } }; Some(res) }
function_block-full_function
[ { "content": "#[derive(Debug)]\n\nenum Error {\n\n Io(std::io::Error),\n\n Parse(async_gcode::Error),\n\n}\n\nimpl From<async_gcode::Error> for Error {\n\n fn from(f: async_gcode::Error) -> Self {\n\n Self::Parse(f)\n\n }\n\n}\n", "file_path": "examples/cli.rs", "rank": 0, "score"...
Rust
core/src/snapshot_packager_service.rs
glottologist/solana
770bdec924481038ed93962bd79da6ccc0e799bf
use solana_gossip::cluster_info::{ClusterInfo, MAX_SNAPSHOT_HASHES}; use solana_runtime::{ snapshot_archive_info::SnapshotArchiveInfoGetter, snapshot_package::PendingSnapshotPackage, snapshot_utils, }; use solana_sdk::{clock::Slot, hash::Hash}; use std::{ sync::{ atomic::{AtomicBool, Ordering}, Arc, }, thread::{self, Builder, JoinHandle}, time::Duration, }; pub struct SnapshotPackagerService { t_snapshot_packager: JoinHandle<()>, } impl SnapshotPackagerService { pub fn new( pending_snapshot_package: PendingSnapshotPackage, starting_snapshot_hash: Option<(Slot, Hash)>, exit: &Arc<AtomicBool>, cluster_info: &Arc<ClusterInfo>, maximum_snapshots_to_retain: usize, ) -> Self { let exit = exit.clone(); let cluster_info = cluster_info.clone(); let t_snapshot_packager = Builder::new() .name("snapshot-packager".to_string()) .spawn(move || { let mut hashes = vec![]; if let Some(starting_snapshot_hash) = starting_snapshot_hash { hashes.push(starting_snapshot_hash); } cluster_info.push_snapshot_hashes(hashes.clone()); loop { if exit.load(Ordering::Relaxed) { break; } let snapshot_package = pending_snapshot_package.lock().unwrap().take(); if snapshot_package.is_none() { std::thread::sleep(Duration::from_millis(100)); continue; } let snapshot_package = snapshot_package.unwrap(); snapshot_utils::archive_snapshot_package( &snapshot_package, maximum_snapshots_to_retain, ) .expect("failed to archive snapshot package"); hashes.push((snapshot_package.slot(), *snapshot_package.hash())); while hashes.len() > MAX_SNAPSHOT_HASHES { hashes.remove(0); } cluster_info.push_snapshot_hashes(hashes.clone()); } }) .unwrap(); Self { t_snapshot_packager, } } pub fn join(self) -> thread::Result<()> { self.t_snapshot_packager.join() } } #[cfg(test)] mod tests { use super::*; use bincode::serialize_into; use solana_runtime::{ accounts_db::AccountStorageEntry, bank::BankSlotDelta, snapshot_archive_info::SnapshotArchiveInfo, snapshot_package::{SnapshotPackage, SnapshotType}, snapshot_utils::{self, ArchiveFormat, SnapshotVersion, SNAPSHOT_STATUS_CACHE_FILE_NAME}, }; use solana_sdk::hash::Hash; use std::{ fs::{self, remove_dir_all, OpenOptions}, io::Write, path::{Path, PathBuf}, }; use tempfile::TempDir; fn make_tmp_dir_path() -> PathBuf { let out_dir = std::env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string()); let path = PathBuf::from(format!("{}/tmp/test_package_snapshots", out_dir)); let _ignored = std::fs::remove_dir_all(&path); let _ignored = std::fs::remove_file(&path); path } #[test] fn test_package_snapshots_relative_ledger_path() { let temp_dir = make_tmp_dir_path(); create_and_verify_snapshot(&temp_dir); remove_dir_all(temp_dir).expect("should remove tmp dir"); } #[test] fn test_package_snapshots() { create_and_verify_snapshot(TempDir::new().unwrap().path()) } fn create_and_verify_snapshot(temp_dir: &Path) { let accounts_dir = temp_dir.join("accounts"); let snapshots_dir = temp_dir.join("snapshots"); let snapshot_archives_dir = temp_dir.join("snapshots_output"); fs::create_dir_all(&snapshot_archives_dir).unwrap(); fs::create_dir_all(&accounts_dir).unwrap(); let storage_entries: Vec<_> = (0..5) .map(|i| Arc::new(AccountStorageEntry::new(&accounts_dir, 0, i, 10))) .collect(); let snapshots_paths: Vec<_> = (0..5) .map(|i| { let snapshot_file_name = format!("{}", i); let snapshots_dir = snapshots_dir.join(&snapshot_file_name); fs::create_dir_all(&snapshots_dir).unwrap(); let fake_snapshot_path = snapshots_dir.join(&snapshot_file_name); let mut fake_snapshot_file = OpenOptions::new() .read(true) .write(true) .create(true) .open(&fake_snapshot_path) .unwrap(); fake_snapshot_file.write_all(b"Hello, world!").unwrap(); fake_snapshot_path }) .collect(); let link_snapshots_dir = tempfile::tempdir_in(&temp_dir).unwrap(); for snapshots_path in snapshots_paths { let snapshot_file_name = snapshots_path.file_name().unwrap(); let link_snapshots_dir = link_snapshots_dir.path().join(snapshot_file_name); fs::create_dir_all(&link_snapshots_dir).unwrap(); let link_path = link_snapshots_dir.join(snapshot_file_name); fs::hard_link(&snapshots_path, &link_path).unwrap(); } let slot = 42; let hash = Hash::default(); let archive_format = ArchiveFormat::TarBzip2; let output_tar_path = snapshot_utils::build_full_snapshot_archive_path( snapshot_archives_dir, slot, &hash, archive_format, ); let snapshot_package = SnapshotPackage { snapshot_archive_info: SnapshotArchiveInfo { path: output_tar_path.clone(), slot, hash, archive_format, }, block_height: slot, slot_deltas: vec![], snapshot_links: link_snapshots_dir, snapshot_storages: vec![storage_entries], snapshot_version: SnapshotVersion::default(), snapshot_type: SnapshotType::FullSnapshot, }; snapshot_utils::archive_snapshot_package( &snapshot_package, snapshot_utils::DEFAULT_MAX_FULL_SNAPSHOT_ARCHIVES_TO_RETAIN, ) .unwrap(); let dummy_slot_deltas: Vec<BankSlotDelta> = vec![]; snapshot_utils::serialize_snapshot_data_file( &snapshots_dir.join(SNAPSHOT_STATUS_CACHE_FILE_NAME), |stream| { serialize_into(stream, &dummy_slot_deltas)?; Ok(()) }, ) .unwrap(); snapshot_utils::verify_snapshot_archive( output_tar_path, snapshots_dir, accounts_dir, archive_format, ); } }
use solana_gossip::cluster_info::{ClusterInfo, MAX_SNAPSHOT_HASHES}; use solana_runtime::{ snapshot_archive_info::SnapshotArchiveInfoGetter, snapshot_package::PendingSnapshotPackage, snapshot_utils, }; use solana_sdk::{clock::Slot, hash::Hash}; use std::{ sync::{ atomic::{AtomicBool, Ordering}, Arc, }, thread::{self, Builder, JoinHandle}, time::Duration, }; pub struct SnapshotPackagerService { t_snapshot_packager: JoinHandle<()>, } impl SnapshotPackagerService { pub fn new( pending_snapshot_package: PendingSnapshotPackage, starting_snapshot_hash: Option<(Slot, Hash)>, exit: &Arc<AtomicBool>, cluster_info: &Arc<ClusterInfo>, maximum_snapshots_to_retain: usize, ) -> Self { let exit = exit.clone(); let cluster_info = cluster_info.clone(); let t_snapshot_packager = Builder::new() .name("snapshot-packager".to_string()) .spawn(move || { let mut hashes = vec![];
cluster_info.push_snapshot_hashes(hashes.clone()); loop { if exit.load(Ordering::Relaxed) { break; } let snapshot_package = pending_snapshot_package.lock().unwrap().take(); if snapshot_package.is_none() { std::thread::sleep(Duration::from_millis(100)); continue; } let snapshot_package = snapshot_package.unwrap(); snapshot_utils::archive_snapshot_package( &snapshot_package, maximum_snapshots_to_retain, ) .expect("failed to archive snapshot package"); hashes.push((snapshot_package.slot(), *snapshot_package.hash())); while hashes.len() > MAX_SNAPSHOT_HASHES { hashes.remove(0); } cluster_info.push_snapshot_hashes(hashes.clone()); } }) .unwrap(); Self { t_snapshot_packager, } } pub fn join(self) -> thread::Result<()> { self.t_snapshot_packager.join() } } #[cfg(test)] mod tests { use super::*; use bincode::serialize_into; use solana_runtime::{ accounts_db::AccountStorageEntry, bank::BankSlotDelta, snapshot_archive_info::SnapshotArchiveInfo, snapshot_package::{SnapshotPackage, SnapshotType}, snapshot_utils::{self, ArchiveFormat, SnapshotVersion, SNAPSHOT_STATUS_CACHE_FILE_NAME}, }; use solana_sdk::hash::Hash; use std::{ fs::{self, remove_dir_all, OpenOptions}, io::Write, path::{Path, PathBuf}, }; use tempfile::TempDir; fn make_tmp_dir_path() -> PathBuf { let out_dir = std::env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string()); let path = PathBuf::from(format!("{}/tmp/test_package_snapshots", out_dir)); let _ignored = std::fs::remove_dir_all(&path); let _ignored = std::fs::remove_file(&path); path } #[test] fn test_package_snapshots_relative_ledger_path() { let temp_dir = make_tmp_dir_path(); create_and_verify_snapshot(&temp_dir); remove_dir_all(temp_dir).expect("should remove tmp dir"); } #[test] fn test_package_snapshots() { create_and_verify_snapshot(TempDir::new().unwrap().path()) } fn create_and_verify_snapshot(temp_dir: &Path) { let accounts_dir = temp_dir.join("accounts"); let snapshots_dir = temp_dir.join("snapshots"); let snapshot_archives_dir = temp_dir.join("snapshots_output"); fs::create_dir_all(&snapshot_archives_dir).unwrap(); fs::create_dir_all(&accounts_dir).unwrap(); let storage_entries: Vec<_> = (0..5) .map(|i| Arc::new(AccountStorageEntry::new(&accounts_dir, 0, i, 10))) .collect(); let snapshots_paths: Vec<_> = (0..5) .map(|i| { let snapshot_file_name = format!("{}", i); let snapshots_dir = snapshots_dir.join(&snapshot_file_name); fs::create_dir_all(&snapshots_dir).unwrap(); let fake_snapshot_path = snapshots_dir.join(&snapshot_file_name); let mut fake_snapshot_file = OpenOptions::new() .read(true) .write(true) .create(true) .open(&fake_snapshot_path) .unwrap(); fake_snapshot_file.write_all(b"Hello, world!").unwrap(); fake_snapshot_path }) .collect(); let link_snapshots_dir = tempfile::tempdir_in(&temp_dir).unwrap(); for snapshots_path in snapshots_paths { let snapshot_file_name = snapshots_path.file_name().unwrap(); let link_snapshots_dir = link_snapshots_dir.path().join(snapshot_file_name); fs::create_dir_all(&link_snapshots_dir).unwrap(); let link_path = link_snapshots_dir.join(snapshot_file_name); fs::hard_link(&snapshots_path, &link_path).unwrap(); } let slot = 42; let hash = Hash::default(); let archive_format = ArchiveFormat::TarBzip2; let output_tar_path = snapshot_utils::build_full_snapshot_archive_path( snapshot_archives_dir, slot, &hash, archive_format, ); let snapshot_package = SnapshotPackage { snapshot_archive_info: SnapshotArchiveInfo { path: output_tar_path.clone(), slot, hash, archive_format, }, block_height: slot, slot_deltas: vec![], snapshot_links: link_snapshots_dir, snapshot_storages: vec![storage_entries], snapshot_version: SnapshotVersion::default(), snapshot_type: SnapshotType::FullSnapshot, }; snapshot_utils::archive_snapshot_package( &snapshot_package, snapshot_utils::DEFAULT_MAX_FULL_SNAPSHOT_ARCHIVES_TO_RETAIN, ) .unwrap(); let dummy_slot_deltas: Vec<BankSlotDelta> = vec![]; snapshot_utils::serialize_snapshot_data_file( &snapshots_dir.join(SNAPSHOT_STATUS_CACHE_FILE_NAME), |stream| { serialize_into(stream, &dummy_slot_deltas)?; Ok(()) }, ) .unwrap(); snapshot_utils::verify_snapshot_archive( output_tar_path, snapshots_dir, accounts_dir, archive_format, ); } }
if let Some(starting_snapshot_hash) = starting_snapshot_hash { hashes.push(starting_snapshot_hash); }
if_condition
[ { "content": "#[cfg(feature = \"full\")]\n\npub fn new_rand<R: ?Sized>(rng: &mut R) -> Hash\n\nwhere\n\n R: rand::Rng,\n\n{\n\n let mut buf = [0u8; HASH_BYTES];\n\n rng.fill(&mut buf);\n\n Hash::new(&buf)\n\n}\n", "file_path": "sdk/src/hash.rs", "rank": 0, "score": 337905.97106482985 }...
Rust
src/client.rs
thallada/BazaarRealmClient
dffe435c5908045b4e20de01b01125b1f6d9fddf
use std::{ffi::CStr, ffi::CString, os::raw::c_char, path::Path}; use anyhow::Result; use log::LevelFilter; use reqwest::{blocking::Response, Url}; use uuid::Uuid; #[cfg(not(test))] use log::{error, info}; #[cfg(test)] use std::{println as info, println as error}; use crate::{ error::extract_error_from_response, log_server_error, result::{FFIError, FFIResult}, }; #[no_mangle] pub extern "C" fn init() -> bool { match dirs::document_dir() { Some(mut log_dir) => { log_dir.push(Path::new( r#"My Games\Skyrim Special Edition\SKSE\BazaarRealmClient.log"#, )); match simple_logging::log_to_file(log_dir, LevelFilter::Info) { Ok(_) => true, Err(_) => false, } } None => false, } } #[no_mangle] pub extern "C" fn status_check(api_url: *const c_char) -> FFIResult<bool> { let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy(); info!("status_check api_url: {:?}", api_url); fn inner(api_url: &str) -> Result<()> { #[cfg(not(test))] let api_url = Url::parse(api_url)?.join("v1/status")?; #[cfg(test)] let api_url = Url::parse(&mockito::server_url())?.join("v1/status")?; let resp = reqwest::blocking::get(api_url)?; let status = resp.status(); let bytes = resp.bytes()?; if status.is_success() { Ok(()) } else { Err(extract_error_from_response(status, &bytes)) } } match inner(&api_url) { Ok(()) => { info!("status_check ok"); FFIResult::Ok(true) } Err(err) => { error!("status_check failed. {}", err); FFIResult::Err(FFIError::from(err)) } } } #[no_mangle] pub unsafe extern "C" fn generate_api_key() -> *mut c_char { let uuid = CString::new(format!("{}", Uuid::new_v4())) .expect("could not create CString") .into_raw(); info!("generate_api_key successful"); uuid } #[cfg(test)] mod tests { use super::*; use mockito::mock; #[test] fn test_status_check() { let mock = mock("GET", "/v1/status").with_status(200).create(); let api_url = CString::new("url").unwrap().into_raw(); let result = status_check(api_url); mock.assert(); match result { FFIResult::Ok(success) => { assert_eq!(success, true); } FFIResult::Err(error) => panic!( "status_check returned error: {:?}", match error { FFIError::Server(server_error) => format!("{} {}", server_error.status, unsafe { CStr::from_ptr(server_error.title).to_string_lossy() }), FFIError::Network(network_error) => unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(), } ), } } #[test] fn test_status_check_server_error() { let mock = mock("GET", "/v1/status") .with_status(500) .with_body("Internal Server Error") .create(); let api_url = CString::new("url").unwrap().into_raw(); let result = status_check(api_url); mock.assert(); match result { FFIResult::Ok(success) => panic!("status_check returned Ok result: {:?}", success), FFIResult::Err(error) => match error { FFIError::Server(server_error) => { assert_eq!(server_error.status, 500); assert_eq!( unsafe { CStr::from_ptr(server_error.title).to_string_lossy() }, "Internal Server Error" ); } _ => panic!("status_check did not return a server error"), }, } } }
use std::{ffi::CStr, ffi::CString, os::raw::c_char, path::Path}; use anyhow::Result; use log::LevelFilter; use reqwest::{blocking::Response, Url}; use uuid::Uuid; #[cfg(not(test))] use log::{error, info}; #[cfg(test)] use std::{println as info, println as error}; use crate::{ error::extract_error_from_response, log_server_error, result::{FFIError, FFIResult}, }; #[no_mangle] pub extern "C" fn init() -> bool { match dirs::document_di
#[no_mangle] pub extern "C" fn status_check(api_url: *const c_char) -> FFIResult<bool> { let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy(); info!("status_check api_url: {:?}", api_url); fn inner(api_url: &str) -> Result<()> { #[cfg(not(test))] let api_url = Url::parse(api_url)?.join("v1/status")?; #[cfg(test)] let api_url = Url::parse(&mockito::server_url())?.join("v1/status")?; let resp = reqwest::blocking::get(api_url)?; let status = resp.status(); let bytes = resp.bytes()?; if status.is_success() { Ok(()) } else { Err(extract_error_from_response(status, &bytes)) } } match inner(&api_url) { Ok(()) => { info!("status_check ok"); FFIResult::Ok(true) } Err(err) => { error!("status_check failed. {}", err); FFIResult::Err(FFIError::from(err)) } } } #[no_mangle] pub unsafe extern "C" fn generate_api_key() -> *mut c_char { let uuid = CString::new(format!("{}", Uuid::new_v4())) .expect("could not create CString") .into_raw(); info!("generate_api_key successful"); uuid } #[cfg(test)] mod tests { use super::*; use mockito::mock; #[test] fn test_status_check() { let mock = mock("GET", "/v1/status").with_status(200).create(); let api_url = CString::new("url").unwrap().into_raw(); let result = status_check(api_url); mock.assert(); match result { FFIResult::Ok(success) => { assert_eq!(success, true); } FFIResult::Err(error) => panic!( "status_check returned error: {:?}", match error { FFIError::Server(server_error) => format!("{} {}", server_error.status, unsafe { CStr::from_ptr(server_error.title).to_string_lossy() }), FFIError::Network(network_error) => unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(), } ), } } #[test] fn test_status_check_server_error() { let mock = mock("GET", "/v1/status") .with_status(500) .with_body("Internal Server Error") .create(); let api_url = CString::new("url").unwrap().into_raw(); let result = status_check(api_url); mock.assert(); match result { FFIResult::Ok(success) => panic!("status_check returned Ok result: {:?}", success), FFIResult::Err(error) => match error { FFIError::Server(server_error) => { assert_eq!(server_error.status, 500); assert_eq!( unsafe { CStr::from_ptr(server_error.title).to_string_lossy() }, "Internal Server Error" ); } _ => panic!("status_check did not return a server error"), }, } } }
r() { Some(mut log_dir) => { log_dir.push(Path::new( r#"My Games\Skyrim Special Edition\SKSE\BazaarRealmClient.log"#, )); match simple_logging::log_to_file(log_dir, LevelFilter::Info) { Ok(_) => true, Err(_) => false, } } None => false, } }
function_block-function_prefixed
[ { "content": "pub fn log_server_error(resp: Response) {\n\n let status = resp.status();\n\n if let Ok(text) = resp.text() {\n\n error!(\"Server error: {} {}\", status, text);\n\n }\n\n error!(\"Server error: {}\", status);\n\n}\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn free_string(ptr: *mut ...
Rust
capsules/src/nrf51822_serialization.rs
jettr/tock
419f293f649989bf208af731f343886ff0fe3748
use core::cmp; use kernel::common::cells::{OptionalCell, TakeCell}; use kernel::hil; use kernel::hil::uart; use kernel::{ CommandReturn, Driver, ErrorCode, Grant, ProcessId, ReadOnlyProcessBuffer, ReadWriteProcessBuffer, ReadableProcessBuffer, WriteableProcessBuffer, }; use crate::driver; pub const DRIVER_NUM: usize = driver::NUM::Nrf51822Serialization as usize; #[derive(Default)] pub struct App { tx_buffer: ReadOnlyProcessBuffer, rx_buffer: ReadWriteProcessBuffer, } pub static mut WRITE_BUF: [u8; 600] = [0; 600]; pub static mut READ_BUF: [u8; 600] = [0; 600]; pub struct Nrf51822Serialization<'a> { uart: &'a dyn uart::UartAdvanced<'a>, reset_pin: &'a dyn hil::gpio::Pin, apps: Grant<App, 1>, active_app: OptionalCell<ProcessId>, tx_buffer: TakeCell<'static, [u8]>, rx_buffer: TakeCell<'static, [u8]>, } impl<'a> Nrf51822Serialization<'a> { pub fn new( uart: &'a dyn uart::UartAdvanced<'a>, grant: Grant<App, 1>, reset_pin: &'a dyn hil::gpio::Pin, tx_buffer: &'static mut [u8], rx_buffer: &'static mut [u8], ) -> Nrf51822Serialization<'a> { Nrf51822Serialization { uart: uart, reset_pin: reset_pin, apps: grant, active_app: OptionalCell::empty(), tx_buffer: TakeCell::new(tx_buffer), rx_buffer: TakeCell::new(rx_buffer), } } pub fn initialize(&self) { let _ = self.uart.configure(uart::Parameters { baud_rate: 250000, width: uart::Width::Eight, stop_bits: uart::StopBits::One, parity: uart::Parity::Even, hw_flow_control: true, }); } pub fn reset(&self) { self.reset_pin.make_output(); self.reset_pin.clear(); for _ in 0..10 { self.reset_pin.clear(); } self.reset_pin.set(); } } impl Driver for Nrf51822Serialization<'_> { fn allow_readwrite( &self, appid: ProcessId, allow_type: usize, mut slice: ReadWriteProcessBuffer, ) -> Result<ReadWriteProcessBuffer, (ReadWriteProcessBuffer, ErrorCode)> { let res = match allow_type { 0 => { self.active_app.set(appid); self.apps .enter(appid, |app, _| { core::mem::swap(&mut app.rx_buffer, &mut slice); }) .map_err(ErrorCode::from) } _ => Err(ErrorCode::NOSUPPORT), }; if let Err(e) = res { Err((slice, e)) } else { Ok(slice) } } fn allow_readonly( &self, appid: ProcessId, allow_type: usize, mut slice: ReadOnlyProcessBuffer, ) -> Result<ReadOnlyProcessBuffer, (ReadOnlyProcessBuffer, ErrorCode)> { let res = match allow_type { 0 => { self.active_app.set(appid); self.apps .enter(appid, |app, _| { core::mem::swap(&mut app.tx_buffer, &mut slice) }) .map_err(ErrorCode::from) } _ => Err(ErrorCode::NOSUPPORT), }; if let Err(e) = res { Err((slice, e)) } else { Ok(slice) } } fn command( &self, command_type: usize, arg1: usize, _: usize, appid: ProcessId, ) -> CommandReturn { match command_type { 0 /* check if present */ => CommandReturn::success(), 1 => { self.apps.enter(appid, |app, _| { app.tx_buffer.enter(|slice| { let write_len = slice.len(); self.tx_buffer.take().map_or(CommandReturn::failure(ErrorCode::FAIL), |buffer| { for (i, c) in slice.iter().enumerate() { buffer[i] = c.get(); } let _ = self.uart.transmit_buffer(buffer, write_len); CommandReturn::success() }) }).unwrap_or(CommandReturn::failure(ErrorCode::FAIL)) }).unwrap_or(CommandReturn::failure(ErrorCode::FAIL)) } 2 => { self.rx_buffer.take().map_or(CommandReturn::failure(ErrorCode::RESERVE), |buffer| { let len = arg1; if len > buffer.len() { CommandReturn::failure(ErrorCode::SIZE) } else { let _ = self.uart.receive_automatic(buffer, len, 250); CommandReturn::success_u32(len as u32) } }) } 3 => { self.reset(); CommandReturn::success() } _ => CommandReturn::failure(ErrorCode::NOSUPPORT), } } fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::procs::Error> { self.apps.enter(processid, |_, _| {}) } } impl uart::TransmitClient for Nrf51822Serialization<'_> { fn transmitted_buffer( &self, buffer: &'static mut [u8], _tx_len: usize, _rcode: Result<(), ErrorCode>, ) { self.tx_buffer.replace(buffer); self.active_app.map(|appid| { let _ = self.apps.enter(*appid, |_app, upcalls| { upcalls.schedule_upcall(0, 1, 0, 0).ok(); }); }); } fn transmitted_word(&self, _rcode: Result<(), ErrorCode>) {} } impl uart::ReceiveClient for Nrf51822Serialization<'_> { fn received_buffer( &self, buffer: &'static mut [u8], rx_len: usize, _rcode: Result<(), ErrorCode>, _error: uart::Error, ) { self.rx_buffer.replace(buffer); self.active_app.map(|appid| { let _ = self.apps.enter(*appid, |app, upcalls| { let len = app .rx_buffer .mut_enter(|rb| { let max_len = cmp::min(rx_len, rb.len()); self.rx_buffer.map_or(0, |buffer| { for idx in 0..max_len { rb[idx].set(buffer[idx]); } max_len }) }) .unwrap_or(0); upcalls.schedule_upcall(0, 4, rx_len, len).ok(); }); }); self.rx_buffer.take().map(|buffer| { let len = buffer.len(); let _ = self.uart.receive_automatic(buffer, len, 250); }); } fn received_word(&self, _word: u32, _rcode: Result<(), ErrorCode>, _err: uart::Error) {} }
use core::cmp; use kernel::common::cells::{OptionalCell, TakeCell}; use kernel::hil; use kernel::hil::uart; use kernel::{ CommandReturn, Driver, ErrorCode, Grant, ProcessId, ReadOnlyProcessBuffer, ReadWriteProcessBuffer, ReadableProcessBuffer, WriteableProcessBuffer, }; use crate::driver; pub const DRIVER_NUM: usize = driver::NUM::Nrf51822Serialization as usize; #[derive(Default)] pub struct App { tx_buffer: ReadOnlyProcessBuffer, rx_buffer: ReadWriteProcessBuffer, } pub static mut WRITE_BUF: [u8; 600] = [0; 600]; pub static mut READ_BUF: [u8; 600] = [0; 600]; pub struct Nrf51822Serialization<'a> { uart: &'a dyn uart::UartAdvanced<'a>, reset_pin: &'a dyn hil::gpio::Pin, apps: Grant<App, 1>, active_app: OptionalCell<ProcessId>, tx_buffer: TakeCell<'static, [u8]>, rx_buffer: TakeCell<'static, [u8]>, } impl<'a> Nrf51822Serialization<'a> { pub fn new( uart: &'a dyn uart::UartAdvanced<'a>, grant: Grant<App, 1>, reset_pin: &'a dyn hil::gpio::Pin, tx_buffer: &'static mut [u8], rx_buffer: &'static mut [u8], ) -> Nrf51822Serialization<'a> { Nrf51822Serialization { uart: uart, reset_pin: reset_pin, apps: grant, active_app: OptionalCell::empty(), tx_buffer: TakeCell::new(tx_buffer), rx_buffer: TakeCell::new(rx_buffer), } } pub fn initialize(&self) { let _ = self.uart.configure(uart::Parameters { baud_rate: 250000, width: uart::Width::Eight, stop_bits: uart::StopBits::One, parity: uart::Parity::Even, hw_flow_control: true, }); } pub fn reset(&self) { self.reset_pin.make_output(); self.reset_pin.clear(); for _ in 0..10 { self.reset_pin.clear(); } self.reset_pin.set(); } } impl Driver for Nrf51822Serialization<'_> { fn allow_readwrite( &self, appid: ProcessId, allow_type: usize, mut slice: ReadWriteProcessBuffer, ) -> Result<ReadWriteProcessBuffer, (ReadWriteProcessBuffer, ErrorCode)> { let res = match allow_type { 0 => { self.active_app.set(appid); self.apps .enter(appid, |app, _| { core::mem::swap(&mut app.rx_buffer, &mut slice); }) .map_err(ErrorCode::from) } _ => Err(ErrorCode::NOSUPPORT), }; if let Err(e) = res { Err((slice, e)) } else { Ok(slice) } } fn allow_readonly( &self, appid: ProcessId, allow_type: usize, mut slice: ReadOnlyProcessBuffer, ) -> Result<ReadOnlyProcessBuffer, (ReadOnlyProcessBuffer, ErrorCode)> { let res = match allow_type { 0 => { self.active_app.set(appid); self.apps .enter(appid, |app, _| { core::mem::swap(&mut app.tx_buffer, &mut slic
fn command( &self, command_type: usize, arg1: usize, _: usize, appid: ProcessId, ) -> CommandReturn { match command_type { 0 /* check if present */ => CommandReturn::success(), 1 => { self.apps.enter(appid, |app, _| { app.tx_buffer.enter(|slice| { let write_len = slice.len(); self.tx_buffer.take().map_or(CommandReturn::failure(ErrorCode::FAIL), |buffer| { for (i, c) in slice.iter().enumerate() { buffer[i] = c.get(); } let _ = self.uart.transmit_buffer(buffer, write_len); CommandReturn::success() }) }).unwrap_or(CommandReturn::failure(ErrorCode::FAIL)) }).unwrap_or(CommandReturn::failure(ErrorCode::FAIL)) } 2 => { self.rx_buffer.take().map_or(CommandReturn::failure(ErrorCode::RESERVE), |buffer| { let len = arg1; if len > buffer.len() { CommandReturn::failure(ErrorCode::SIZE) } else { let _ = self.uart.receive_automatic(buffer, len, 250); CommandReturn::success_u32(len as u32) } }) } 3 => { self.reset(); CommandReturn::success() } _ => CommandReturn::failure(ErrorCode::NOSUPPORT), } } fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::procs::Error> { self.apps.enter(processid, |_, _| {}) } } impl uart::TransmitClient for Nrf51822Serialization<'_> { fn transmitted_buffer( &self, buffer: &'static mut [u8], _tx_len: usize, _rcode: Result<(), ErrorCode>, ) { self.tx_buffer.replace(buffer); self.active_app.map(|appid| { let _ = self.apps.enter(*appid, |_app, upcalls| { upcalls.schedule_upcall(0, 1, 0, 0).ok(); }); }); } fn transmitted_word(&self, _rcode: Result<(), ErrorCode>) {} } impl uart::ReceiveClient for Nrf51822Serialization<'_> { fn received_buffer( &self, buffer: &'static mut [u8], rx_len: usize, _rcode: Result<(), ErrorCode>, _error: uart::Error, ) { self.rx_buffer.replace(buffer); self.active_app.map(|appid| { let _ = self.apps.enter(*appid, |app, upcalls| { let len = app .rx_buffer .mut_enter(|rb| { let max_len = cmp::min(rx_len, rb.len()); self.rx_buffer.map_or(0, |buffer| { for idx in 0..max_len { rb[idx].set(buffer[idx]); } max_len }) }) .unwrap_or(0); upcalls.schedule_upcall(0, 4, rx_len, len).ok(); }); }); self.rx_buffer.take().map(|buffer| { let len = buffer.len(); let _ = self.uart.receive_automatic(buffer, len, 250); }); } fn received_word(&self, _word: u32, _rcode: Result<(), ErrorCode>, _err: uart::Error) {} }
e) }) .map_err(ErrorCode::from) } _ => Err(ErrorCode::NOSUPPORT), }; if let Err(e) = res { Err((slice, e)) } else { Ok(slice) } }
function_block-function_prefixed
[ { "content": "pub fn u16_to_network_slice(short: u16, slice: &mut [u8]) {\n\n slice[0] = (short >> 8) as u8;\n\n slice[1] = (short & 0xff) as u8;\n\n}\n", "file_path": "capsules/src/net/util.rs", "rank": 0, "score": 343884.3090572432 }, { "content": "/// This test should be called with...
Rust
engine/src/graphics/mod.rs
arcana-engine/arcana
e641ecfdf48c2844cf886834ad3aa981d3be7168
#[macro_export] macro_rules! vertex_location { ($offset:ident, $elem:ty as $semantics:literal) => { VertexLocation { format: <$elem as $crate::graphics::FormatElement>::FORMAT, semantics: $crate::graphics::Semantics::new($semantics), offset: { let offset = $offset; #[allow(unused_assignments)] { $offset += ::core::mem::size_of::<$elem>() as u32; } offset }, } }; ($offset:ident, $va:ty) => { VertexLocation { format: <$va as $crate::graphics::VertexAttribute>::FORMAT, semantics: <$va as $crate::graphics::VertexAttribute>::SEMANTICS, offset: { let offset = $offset; #[allow(unused_assignments)] { $offset += ::core::mem::size_of::<$va>() as u32; } offset }, } }; } #[macro_export] macro_rules! define_vertex_attribute { ($( $(#[$meta:meta])* $vis:vis struct $va:ident as $semantics:tt ($fvis:vis $ft:ty); )*) => {$( $(#[$meta])* #[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)] #[repr(transparent)] $vis struct $va($fvis $ft); unsafe impl bytemuck::Zeroable for $va {} unsafe impl bytemuck::Pod for $va {} impl $crate::graphics::VertexAttribute for $va { const FORMAT: $crate::sierra::Format = <$ft as $crate::graphics::FormatElement>::FORMAT; const SEMANTICS: $crate::graphics::Semantics = $semantics; } impl<T> From<T> for $va where T: Into<$ft> { fn from(t: T) -> $va { $va(t.into()) } } )*}; } #[macro_export] macro_rules! define_vertex_type { ($( $(#[$meta:meta])* $vis:vis struct $vt:ident as $rate:ident { $( $van:ident: $vat:ty $(as $semantics:literal)? ),* $(,)? } )*) => {$( $(#[$meta])* #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] $vis struct $vt { $( $van: $vat, )* } unsafe impl bytemuck::Zeroable for $vt {} unsafe impl bytemuck::Pod for $vt {} impl $crate::graphics::VertexType for $vt { const LOCATIONS: &'static [$crate::graphics::VertexLocation] = { let mut offset = 0; $( let $van = $crate::vertex_location!(offset, $vat as $semantics ); )* &[$($van,)*] }; const RATE: $crate::graphics::VertexInputRate = $crate::graphics::VertexInputRate::$rate; } )*}; } pub mod node; pub mod renderer; mod format; mod material; mod scale; mod texture; mod upload; mod vertex; #[cfg(feature = "3d")] mod mesh; use std::{ collections::hash_map::{Entry, HashMap}, hash::Hash, ops::Deref, }; use bitsetium::{BitEmpty, BitSearch, BitUnset, Bits1024}; use bytemuck::Pod; use raw_window_handle::HasRawWindowHandle; use scoped_arena::Scope; use sierra::{ AccessFlags, Buffer, BufferInfo, CommandBuffer, CreateSurfaceError, Device, Encoder, Extent3d, Fence, Format, Image, ImageInfo, ImageUsage, Layout, Offset3d, OutOfMemory, PipelineStageFlags, PresentOk, Queue, Semaphore, SingleQueueQuery, SubresourceLayers, Surface, SwapchainImage, }; use self::upload::Uploader; pub use self::{format::*, material::*, scale::*, texture::*, vertex::*}; #[cfg(feature = "3d")] pub use self::mesh::*; pub struct Graphics { uploader: Uploader, queue: Queue, device: Device, } impl Graphics { pub fn new() -> eyre::Result<Self> { let graphics = sierra::Graphics::get_or_init()?; let physical = graphics .devices()? .into_iter() .max_by_key(|d| d.info().kind) .ok_or_else(|| eyre::eyre!("Failed to find physical device"))?; let (device, queue) = physical.create_device( &[ sierra::Feature::SurfacePresentation, sierra::Feature::ShaderSampledImageDynamicIndexing, sierra::Feature::ShaderSampledImageNonUniformIndexing, sierra::Feature::RuntimeDescriptorArray, sierra::Feature::ScalarBlockLayout, ], SingleQueueQuery::GRAPHICS, )?; Ok(Graphics { uploader: Uploader::new(&device)?, device, queue, }) } } impl Graphics { #[tracing::instrument(skip(self, window))] pub fn create_surface( &self, window: &impl HasRawWindowHandle, ) -> Result<Surface, CreateSurfaceError> { self.device.graphics().create_surface(window) } #[inline] #[tracing::instrument(skip(self, data))] pub fn upload_buffer<T>( &mut self, buffer: &Buffer, offset: u64, data: &[T], ) -> Result<(), OutOfMemory> where T: Pod, { self.uploader .upload_buffer(&self.device, buffer, offset, data) } #[inline] #[tracing::instrument(skip(self, data))] pub fn upload_buffer_with<'a, T>( &self, buffer: &'a Buffer, offset: u64, data: &'a [T], encoder: &mut Encoder<'a>, ) -> Result<(), OutOfMemory> where T: Pod, { self.uploader .upload_buffer_with(&self.device, buffer, offset, data, encoder) } #[inline] #[tracing::instrument(skip(self, data))] pub fn upload_image<T>(&mut self, upload: UploadImage, data: &[T]) -> Result<(), OutOfMemory> where T: Pod, { self.uploader.upload_image(&self.device, upload, data) } #[tracing::instrument(skip(self, data))] pub fn upload_image_with<'a, T>( &self, upload: UploadImage, data: &[T], encoder: &mut Encoder<'a>, ) -> Result<(), OutOfMemory> where T: Pod, { self.uploader .upload_image_with(&self.device, upload, data, encoder) } #[tracing::instrument(skip(self, data))] pub fn create_fast_buffer_static<T>( &mut self, info: BufferInfo, data: &[T], ) -> Result<Buffer, OutOfMemory> where T: Pod, { let buffer = self.device.create_buffer(info)?; self.upload_buffer(&buffer, 0, data)?; Ok(buffer) } #[tracing::instrument(skip(self, data))] pub fn create_image_static<T>( &mut self, mut info: ImageInfo, layout: Layout, data: &[T], format: Format, row_length: u32, image_height: u32, ) -> Result<Image, OutOfMemory> where T: Pod, { info.usage |= ImageUsage::TRANSFER_DST; let layers = SubresourceLayers::all_layers(&info, 0); let image = self.device.create_image(info)?; self.upload_image( UploadImage { image: &image, offset: Offset3d::ZERO, extent: info.extent.into_3d(), layers, old_layout: None, new_layout: layout, old_access: AccessFlags::empty(), new_access: AccessFlags::all(), format, row_length, image_height, }, data, )?; Ok(image) } pub fn create_encoder<'a>(&mut self, scope: &'a Scope<'a>) -> Result<Encoder<'a>, OutOfMemory> { self.queue.create_encoder(scope) } pub fn submit( &mut self, wait: &mut [(PipelineStageFlags, &mut Semaphore)], cbufs: impl IntoIterator<Item = CommandBuffer>, signal: &mut [&mut Semaphore], fence: Option<&mut Fence>, scope: &Scope<'_>, ) -> Result<(), OutOfMemory> { self.flush_uploads(scope)?; self.queue.submit(wait, cbufs, signal, fence, scope); Ok(()) } pub fn present(&mut self, image: SwapchainImage) -> Result<PresentOk, OutOfMemory> { self.queue.present(image) } fn flush_uploads(&mut self, scope: &Scope<'_>) -> Result<(), OutOfMemory> { self.uploader .flush_uploads(&self.device, &mut self.queue, scope) } } impl Drop for Graphics { fn drop(&mut self) { if !std::thread::panicking() { self.wait_idle(); } } } impl Deref for Graphics { type Target = Device; #[inline(always)] fn deref(&self) -> &Device { &self.device } } pub struct SparseDescriptors<T> { resources: HashMap<T, u32>, bitset: Bits1024, next: u32, } impl<T> Default for SparseDescriptors<T> { #[inline] fn default() -> Self { SparseDescriptors::new() } } impl<T> SparseDescriptors<T> { #[inline] pub fn new() -> Self { SparseDescriptors { resources: HashMap::new(), bitset: BitEmpty::empty(), next: 0, } } pub fn index(&mut self, resource: T) -> (u32, bool) where T: Hash + Eq, { match self.resources.entry(resource) { Entry::Occupied(entry) => (*entry.get(), false), Entry::Vacant(entry) => { if let Some(index) = self.bitset.find_first_set(0) { self.bitset.unset(index); (*entry.insert(index as u32), true) } else { self.next += 1; (*entry.insert(self.next - 1), true) } } } } } #[derive(Debug)] pub struct UploadImage<'a> { pub image: &'a Image, pub offset: Offset3d, pub extent: Extent3d, pub layers: SubresourceLayers, pub old_layout: Option<Layout>, pub new_layout: Layout, pub old_access: AccessFlags, pub new_access: AccessFlags, pub format: Format, pub row_length: u32, pub image_height: u32, }
#[macro_export] macro_rules! vertex_location { ($offset:ident, $elem:ty as $semantics:literal) => { VertexLocation { format: <$elem as $crate::graphics::FormatElement>::FORMAT, semantics: $crate::graphics::Semantics::new($semantics), offset: { let offset = $offset; #[allow(unused_assignments)] { $offset += ::core::mem::size_of::<$elem>() as u32; } offset }, } }; ($offset:ident, $va:ty) => { VertexLocation { format: <$va as $crate::graphics::VertexAttribute>::FORMAT, semantics: <$va as $crate::graphics::VertexAttribute>::SEMANTICS, offset: { let offset = $offset; #[allow(unused_assignments)] { $offset += ::core::mem::size_of::<$va>() as u32; } offset }, } }; } #[macro_export] macro_rules! define_vertex_attribute { ($( $(#[$meta:meta])* $vis:vis struct $va:ident as $semantics:tt ($fvis:vis $ft:ty); )*) => {$( $(#[$meta])* #[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)] #[repr(transparent)] $vis struct $va($fvis $ft); unsafe impl bytemuck::Zeroable for $va {} unsafe impl bytemuck::Pod for $va {} impl $crate::graphics::VertexAttribute for $va { const FORMAT: $crate::sierra::Format = <$ft as $crate::graphics::FormatElement>::FORMAT; const SEMANTICS: $crate::graphics::Semantics = $semantics; } impl<T> From<T> for $va where T: Into<$ft> { fn from(t: T) -> $va { $va(t.into()) } } )*}; } #[macro_export] macro_rules! define_vertex_type { ($( $(#[$meta:meta])* $vis:vis struct $vt:ident as $rate:ident { $( $van:ident: $vat:ty $(as $semantics:literal)? ),* $(,)? } )*) => {$( $(#[$meta])* #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] $vis struct $vt { $( $van: $vat, )* } unsafe impl bytemuck::Zeroable for $vt {} unsafe impl bytemuck::Pod for $vt {} impl $crate::graphics::VertexType for $vt { const LOCATIONS: &'static [$crate::graphics::VertexLocation] = { let mut offset = 0; $( let $van = $crate::vertex_location!(offset, $vat as $semantics ); )* &[$($van,)*] }; const RATE: $crate::graphics::VertexInputRate = $crate::graphics::VertexInputRate::$rate; } )*}; } pub mod node; pub mod renderer; mod format; mod material; mod scale; mod texture; mod upload; mod vertex; #[cfg(feature = "3d")] mod mesh; use std::{ collections::hash_map::{Entry, HashMap}, hash::Hash, ops::Deref, }; use bitsetium::{BitEmpty, BitSearch, BitUnset, Bits1024}; use bytemuck::Pod; use raw_window_handle::HasRawWindowHandle; use scoped_arena::Scope; use sierra::{ AccessFlags, Buffer, BufferInfo, CommandBuffer, CreateSurfaceError, Device, Encoder, Extent3d, Fence, Format, Image, ImageInfo, ImageUsage, Layout, Offset3d, OutOfMemory, PipelineStageFlags, PresentOk, Queue, Semaphore, SingleQueueQuery, SubresourceLayers, Surface, SwapchainImage, }; use self::upload::Uploader; pub use self::{format::*, material::*, scale::*, texture::*, vertex::*}; #[cfg(feature = "3d")] pub use self::mesh::*; pub struct Graphics { uploader: Uploader, queue: Queue, device: Device, } impl Graphics { pub fn new() -> eyre::Result<Self> { let graphics = sierra::Graphics::get_or_init()?; let physical = graphics .devices()? .into_iter() .max_by_key(|d| d.info().kind) .ok_or_else(|| eyre::eyre!("Failed to find physical device"))?; let (device, queue) = physical.create_device( &[ sierra::Feature::SurfacePresentation, sierra::Feature::ShaderSampledImageDynamicIndexing, sierra::Feature::ShaderSampledImageNonUniformIndexing, sierra::Feature::RuntimeDescriptorArray, sierra::Feature::ScalarBlockLayout, ], SingleQueueQuery::GRAPHICS, )?; Ok(Graphics { uploader: Uploader::new(&device)?, device, queue, }) } } impl Graphics { #[tracing::instrument(skip(self, window))]
#[inline] #[tracing::instrument(skip(self, data))] pub fn upload_buffer<T>( &mut self, buffer: &Buffer, offset: u64, data: &[T], ) -> Result<(), OutOfMemory> where T: Pod, { self.uploader .upload_buffer(&self.device, buffer, offset, data) } #[inline] #[tracing::instrument(skip(self, data))] pub fn upload_buffer_with<'a, T>( &self, buffer: &'a Buffer, offset: u64, data: &'a [T], encoder: &mut Encoder<'a>, ) -> Result<(), OutOfMemory> where T: Pod, { self.uploader .upload_buffer_with(&self.device, buffer, offset, data, encoder) } #[inline] #[tracing::instrument(skip(self, data))] pub fn upload_image<T>(&mut self, upload: UploadImage, data: &[T]) -> Result<(), OutOfMemory> where T: Pod, { self.uploader.upload_image(&self.device, upload, data) } #[tracing::instrument(skip(self, data))] pub fn upload_image_with<'a, T>( &self, upload: UploadImage, data: &[T], encoder: &mut Encoder<'a>, ) -> Result<(), OutOfMemory> where T: Pod, { self.uploader .upload_image_with(&self.device, upload, data, encoder) } #[tracing::instrument(skip(self, data))] pub fn create_fast_buffer_static<T>( &mut self, info: BufferInfo, data: &[T], ) -> Result<Buffer, OutOfMemory> where T: Pod, { let buffer = self.device.create_buffer(info)?; self.upload_buffer(&buffer, 0, data)?; Ok(buffer) } #[tracing::instrument(skip(self, data))] pub fn create_image_static<T>( &mut self, mut info: ImageInfo, layout: Layout, data: &[T], format: Format, row_length: u32, image_height: u32, ) -> Result<Image, OutOfMemory> where T: Pod, { info.usage |= ImageUsage::TRANSFER_DST; let layers = SubresourceLayers::all_layers(&info, 0); let image = self.device.create_image(info)?; self.upload_image( UploadImage { image: &image, offset: Offset3d::ZERO, extent: info.extent.into_3d(), layers, old_layout: None, new_layout: layout, old_access: AccessFlags::empty(), new_access: AccessFlags::all(), format, row_length, image_height, }, data, )?; Ok(image) } pub fn create_encoder<'a>(&mut self, scope: &'a Scope<'a>) -> Result<Encoder<'a>, OutOfMemory> { self.queue.create_encoder(scope) } pub fn submit( &mut self, wait: &mut [(PipelineStageFlags, &mut Semaphore)], cbufs: impl IntoIterator<Item = CommandBuffer>, signal: &mut [&mut Semaphore], fence: Option<&mut Fence>, scope: &Scope<'_>, ) -> Result<(), OutOfMemory> { self.flush_uploads(scope)?; self.queue.submit(wait, cbufs, signal, fence, scope); Ok(()) } pub fn present(&mut self, image: SwapchainImage) -> Result<PresentOk, OutOfMemory> { self.queue.present(image) } fn flush_uploads(&mut self, scope: &Scope<'_>) -> Result<(), OutOfMemory> { self.uploader .flush_uploads(&self.device, &mut self.queue, scope) } } impl Drop for Graphics { fn drop(&mut self) { if !std::thread::panicking() { self.wait_idle(); } } } impl Deref for Graphics { type Target = Device; #[inline(always)] fn deref(&self) -> &Device { &self.device } } pub struct SparseDescriptors<T> { resources: HashMap<T, u32>, bitset: Bits1024, next: u32, } impl<T> Default for SparseDescriptors<T> { #[inline] fn default() -> Self { SparseDescriptors::new() } } impl<T> SparseDescriptors<T> { #[inline] pub fn new() -> Self { SparseDescriptors { resources: HashMap::new(), bitset: BitEmpty::empty(), next: 0, } } pub fn index(&mut self, resource: T) -> (u32, bool) where T: Hash + Eq, { match self.resources.entry(resource) { Entry::Occupied(entry) => (*entry.get(), false), Entry::Vacant(entry) => { if let Some(index) = self.bitset.find_first_set(0) { self.bitset.unset(index); (*entry.insert(index as u32), true) } else { self.next += 1; (*entry.insert(self.next - 1), true) } } } } } #[derive(Debug)] pub struct UploadImage<'a> { pub image: &'a Image, pub offset: Offset3d, pub extent: Extent3d, pub layers: SubresourceLayers, pub old_layout: Option<Layout>, pub new_layout: Layout, pub old_access: AccessFlags, pub new_access: AccessFlags, pub format: Format, pub row_length: u32, pub image_height: u32, }
pub fn create_surface( &self, window: &impl HasRawWindowHandle, ) -> Result<Surface, CreateSurfaceError> { self.device.graphics().create_surface(window) }
function_block-full_function
[ { "content": "pub trait FormatElement: Clone + Copy + Debug + Default + PartialEq + PartialOrd + Pod {\n\n const FORMAT: Format;\n\n}\n\n\n\n#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\n#[cfg_attr(feature = \"serde-1\", derive(serde::Serialize, serde::Deserialize))]\n\n#[cf...
Rust
15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu.rs
TomaszWaszczyk/rust-raspberrypi-OS-tutorials
b1c438dc6693431885e597890daeb5536a991e0b
use crate::{ bsp, memory, memory::{mmu::TranslationGranule, Address, Physical, Virtual}, }; use core::intrinsics::unlikely; use cortex_a::{asm::barrier, registers::*}; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; struct MemoryManagementUnit; pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; #[allow(dead_code)] pub mod mair { pub const DEVICE: u64 = 0; pub const NORMAL: u64 = 1; } static MMU: MemoryManagementUnit = MemoryManagementUnit; impl<const AS_SIZE: usize> memory::mmu::AddressSpace<AS_SIZE> { pub const fn arch_address_space_size_sanity_checks() { assert!((AS_SIZE % Granule512MiB::SIZE) == 0); assert!(AS_SIZE <= (1 << 48)); } } impl MemoryManagementUnit { fn set_up_mair(&self) { MAIR_EL1.write( MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, ); } fn configure_translation_control(&self) { let t0sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; TCR_EL1.write( TCR_EL1::TBI0::Used + TCR_EL1::IPS::Bits_40 + TCR_EL1::TG0::KiB_64 + TCR_EL1::SH0::Inner + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::EPD0::EnableTTBR0Walks + TCR_EL1::A1::TTBR0 + TCR_EL1::T0SZ.val(t0sz) + TCR_EL1::EPD1::DisableTTBR1Walks, ); } } pub fn mmu() -> &'static impl memory::mmu::interface::MMU { &MMU } use memory::mmu::{MMUEnableError, TranslationError}; impl memory::mmu::interface::MMU for MemoryManagementUnit { unsafe fn enable_mmu_and_caching( &self, phys_tables_base_addr: Address<Physical>, ) -> Result<(), MMUEnableError> { if unlikely(self.is_enabled()) { return Err(MMUEnableError::AlreadyEnabled); } if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { return Err(MMUEnableError::Other( "Translation granule not supported in HW", )); } self.set_up_mair(); TTBR0_EL1.set_baddr(phys_tables_base_addr.into_usize() as u64); self.configure_translation_control(); barrier::isb(barrier::SY); SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); barrier::isb(barrier::SY); Ok(()) } #[inline(always)] fn is_enabled(&self) -> bool { SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) } fn try_virt_to_phys( &self, virt: Address<Virtual>, ) -> Result<Address<Physical>, TranslationError> { if !self.is_enabled() { return Err(TranslationError::MMUDisabled); } let addr = virt.into_usize() as u64; unsafe { asm!( "AT S1E1R, {0}", in(reg) addr, options(readonly, nostack, preserves_flags) ); } let par_el1 = PAR_EL1.extract(); if par_el1.matches_all(PAR_EL1::F::TranslationAborted) { return Err(TranslationError::Aborted); } let phys_addr = (par_el1.read(PAR_EL1::PA) << 12) | (addr & 0xFFF); Ok(Address::new(phys_addr as usize)) } }
use crate::{ bsp, memory, memory::{mmu::TranslationGranule, Address, Physical, Virtual}, }; use core::intrinsics::unlikely; use cortex_a::{asm::barrier, registers::*}; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; struct MemoryManagementUnit; pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; #[allow(dead_code)] pub mod mair { pub const DEVICE: u64 = 0; pub const NORMAL: u64 = 1; } static MMU: MemoryManagementUnit = MemoryManagementUnit; impl<const AS_SIZE: usize> memory::mmu::AddressSpace<AS_SIZE> { pub const fn arch_address_space_size_sanity_checks() { assert!((AS_SIZE % Granule512MiB::SIZE) == 0); assert!(AS_SIZE <= (1 << 48)); } } impl MemoryManagementUnit {
fn configure_translation_control(&self) { let t0sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; TCR_EL1.write( TCR_EL1::TBI0::Used + TCR_EL1::IPS::Bits_40 + TCR_EL1::TG0::KiB_64 + TCR_EL1::SH0::Inner + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::EPD0::EnableTTBR0Walks + TCR_EL1::A1::TTBR0 + TCR_EL1::T0SZ.val(t0sz) + TCR_EL1::EPD1::DisableTTBR1Walks, ); } } pub fn mmu() -> &'static impl memory::mmu::interface::MMU { &MMU } use memory::mmu::{MMUEnableError, TranslationError}; impl memory::mmu::interface::MMU for MemoryManagementUnit { unsafe fn enable_mmu_and_caching( &self, phys_tables_base_addr: Address<Physical>, ) -> Result<(), MMUEnableError> { if unlikely(self.is_enabled()) { return Err(MMUEnableError::AlreadyEnabled); } if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { return Err(MMUEnableError::Other( "Translation granule not supported in HW", )); } self.set_up_mair(); TTBR0_EL1.set_baddr(phys_tables_base_addr.into_usize() as u64); self.configure_translation_control(); barrier::isb(barrier::SY); SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); barrier::isb(barrier::SY); Ok(()) } #[inline(always)] fn is_enabled(&self) -> bool { SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) } fn try_virt_to_phys( &self, virt: Address<Virtual>, ) -> Result<Address<Physical>, TranslationError> { if !self.is_enabled() { return Err(TranslationError::MMUDisabled); } let addr = virt.into_usize() as u64; unsafe { asm!( "AT S1E1R, {0}", in(reg) addr, options(readonly, nostack, preserves_flags) ); } let par_el1 = PAR_EL1.extract(); if par_el1.matches_all(PAR_EL1::F::TranslationAborted) { return Err(TranslationError::Aborted); } let phys_addr = (par_el1.read(PAR_EL1::PA) << 12) | (addr & 0xFFF); Ok(Address::new(phys_addr as usize)) } }
fn set_up_mair(&self) { MAIR_EL1.write( MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, ); }
function_block-full_function
[ { "content": "/// Return a reference to the MMU instance.\n\npub fn mmu() -> &'static impl memory::mmu::interface::MMU {\n\n &MMU\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//---------------------------------------------------------...
Rust
src/gens/csharp/mod.rs
fizruk/trans-gen
9a5b4635b39a18e9844a4bf40e8ca582fc3ffca2
use super::*; fn conv(name: &str) -> String { name.replace("Int32", "Int") .replace("Int64", "Long") .replace("Float32", "Float") .replace("Float64", "Double") .replace("Params", "Parameters") } pub struct Generator { main_namespace: String, files: HashMap<String, String>, } fn new_var(var: &str, suffix: &str) -> String { let var = match var.find('.') { Some(index) => &var[index + 1..], None => var, }; let indexing_count = var.chars().filter(|&c| c == '[').count(); let var = match var.find('[') { Some(index) => &var[..index], None => var, }; let mut var = var.to_owned(); for _ in 0..indexing_count { var.push_str("Element"); } var.push_str(suffix); Name::new(var).mixed_case(conv) } fn is_null(var: &str, schema: &Schema) -> String { if nullable(schema) { format!("{} == null", var) } else { format!("!{}.HasValue", var) } } fn option_unwrap(var: &str, schema: &Schema) -> String { if nullable(schema) { var.to_owned() } else { format!("{}.Value", var) } } fn nullable(schema: &Schema) -> bool { match schema { Schema::Bool | Schema::Int32 | Schema::Int64 | Schema::Float32 | Schema::Float64 | Schema::Enum { .. } | Schema::Struct { .. } => false, Schema::String | Schema::Option(_) | Schema::Vec(_) | Schema::Map(_, _) | Schema::OneOf { .. } => true, } } fn type_name(schema: &Schema) -> String { format!( "{}{}", type_name_prearray(schema), type_name_postarray(schema), ) } fn type_name_prearray(schema: &Schema) -> String { match schema { Schema::Bool => "bool".to_owned(), Schema::Int32 => "int".to_owned(), Schema::Int64 => "long".to_owned(), Schema::Float32 => "float".to_owned(), Schema::Float64 => "double".to_owned(), Schema::String => "string".to_owned(), Schema::Struct { .. } | Schema::OneOf { .. } | Schema::Enum { .. } => name_path(schema), Schema::Option(inner) => { if nullable(inner) { type_name(inner) } else { format!("{}?", type_name(inner)) } } Schema::Vec(inner) => type_name_prearray(inner), Schema::Map(key, value) => format!( "System.Collections.Generic.IDictionary<{}, {}>", type_name(key), type_name(value) ), } } fn type_name_postarray(schema: &Schema) -> String { match schema { Schema::Vec(inner) => format!("[]{}", type_name_postarray(inner)), _ => String::new(), } } fn doc_comment(documentation: &Documentation) -> String { let mut result = String::new(); result.push_str("/// <summary>\n"); for line in documentation.get("en").unwrap().lines() { result.push_str("/// "); result.push_str(line); result.push('\n'); } result.push_str("/// </summary>\n"); result.trim().to_owned() } fn doc_read_from(name: &str) -> String { format!("/// <summary> Read {} from reader </summary>", name) } fn doc_write_to(name: &str) -> String { format!("/// <summary> Write {} to writer </summary>", name) } fn doc_to_string(name: &str) -> String { format!( "/// <summary> Get string representation of {} </summary>", name, ) } fn read_var(var: &str, schema: &Schema) -> String { include_templing!("src/gens/csharp/read_var.templing") } fn write_var(var: &str, schema: &Schema) -> String { include_templing!("src/gens/csharp/write_var.templing") } fn var_to_string(var: &str, schema: &Schema) -> String { include_templing!("src/gens/csharp/var_to_string.templing") } fn struct_impl(definition: &Struct, base: Option<(&Name, usize)>) -> String { include_templing!("src/gens/csharp/struct_impl.templing") } fn namespace_path(namespace: &Namespace) -> String { namespace .parts .iter() .map(|name| name.camel_case(conv)) .collect::<Vec<_>>() .join(".") } fn namespace_path_suffix(namespace: &Namespace) -> String { let namespace_path = namespace_path(namespace); if namespace_path.is_empty() { namespace_path } else { format!(".{}", namespace_path) } } fn name_path(schema: &Schema) -> String { match schema { Schema::Enum { namespace, base_name: name, .. } | Schema::Struct { namespace, definition: Struct { name, .. }, .. } | Schema::OneOf { namespace, base_name: name, .. } => { let namespace_path = namespace_path(namespace); if namespace_path.is_empty() { name.camel_case(conv) } else { format!("{}.{}", namespace_path, name.camel_case(conv)) } } _ => unreachable!(), } } impl crate::Generator for Generator { const NAME: &'static str = "C#"; type Options = (); fn new(name: &str, _version: &str, _: ()) -> Self { let name = Name::new(name.to_owned()); let mut files = HashMap::new(); files.insert( format!("{}.csproj", name.camel_case(conv)), include_str!("project.csproj").to_owned(), ); Self { main_namespace: name.camel_case(conv), files, } } fn generate(mut self, extra_files: Vec<File>) -> GenResult { for file in extra_files { self.files.insert(file.path, file.content); } self.files.into() } fn add_only(&mut self, schema: &Schema) { match schema { Schema::Enum { namespace, documentation, base_name, variants, } => { self.files.insert( format!("{}.cs", name_path(schema).replace('.', "/")), include_templing!("src/gens/csharp/enum.templing"), ); } Schema::Struct { namespace, definition, } => { self.files.insert( format!("{}.cs", name_path(schema).replace('.', "/")), include_templing!("src/gens/csharp/struct.templing"), ); } Schema::OneOf { namespace, documentation, base_name, variants, } => { self.files.insert( format!("{}.cs", name_path(schema).replace('.', "/")), include_templing!("src/gens/csharp/oneof.templing"), ); } Schema::Bool | Schema::Int32 | Schema::Int64 | Schema::Float32 | Schema::Float64 | Schema::String | Schema::Option(_) | Schema::Vec(_) | Schema::Map(_, _) => {} } } } impl RunnableGenerator for Generator { fn build_local(path: &Path, verbose: bool) -> anyhow::Result<()> { command("dotnet") .current_dir(path) .arg("publish") .arg("-c") .arg("Release") .arg("-o") .arg(".") .show_output(verbose) .run() } fn run_local(path: &Path) -> anyhow::Result<Command> { fn project_name(path: &Path) -> anyhow::Result<String> { for file in std::fs::read_dir(path)? { let file = file?; if file.path().extension() == Some("csproj".as_ref()) { return Ok(file .path() .file_stem() .unwrap() .to_str() .unwrap() .to_owned()); } } anyhow::bail!("Failed to determine project name") } let mut command = command("dotnet"); command .arg(format!("{}.dll", project_name(path)?)) .current_dir(path); Ok(command) } } impl<D: Trans + PartialEq + Debug> TestableGenerator<testing::FileReadWrite<D>> for Generator { fn extra_files(&self, test: &testing::FileReadWrite<D>) -> Vec<File> { let schema = Schema::of::<D>(&test.version); let schema: &Schema = &schema; vec![File { path: "Runner.cs".to_owned(), content: include_templing!("src/gens/csharp/FileReadWrite.cs.templing"), }] } } impl<D: Trans + PartialEq + Debug> TestableGenerator<testing::TcpReadWrite<D>> for Generator { fn extra_files(&self, test: &testing::TcpReadWrite<D>) -> Vec<File> { let schema = Schema::of::<D>(&test.version); let schema: &Schema = &schema; vec![File { path: "Runner.cs".to_owned(), content: include_templing!("src/gens/csharp/TcpReadWrite.cs.templing"), }] } }
use super::*; fn conv(name: &str) -> String { name.replace("Int32", "Int") .replace("Int64", "Long") .replace("Float32", "Float") .replace("Float64", "Double") .replace("Params", "Parameters") } pub struct Generator { main_namespace: String, files: HashMap<String, String>, } fn new_var(var: &str, suffix: &str) -> String { let var = match var.find('.') { Some(index) => &var[index + 1..], None => var, }; let indexing_count = var.chars().filter(|&c| c == '[').count(); let var = match var.find('[') { Some(index) => &var[..index], None => var, }; let mut var = var.to_owned(); for _ in 0..indexing_count { var.push_str("Element"); } var.push_str(suffix); Name::new(var).mixed_case(conv) } fn is_null(var: &str, schema: &Schema) -> String { if nullable(schema) { format!("{} == null", var) } else { format!("!{}.HasValue", var) } } fn option_unwrap(var: &str, schema: &Schema) -> String { if nullable(schema) { var.to_owned() } else { format!("{}.Value", var) } } fn nullable(schema: &Schema) -> bool { match schema { Schema::Bool | Schema::Int32 | Schema::Int64 | Schema::Float32 | Schema::Float64 | Schema::Enum { .. } | Schema::Struct { .. } => false, Schema::String | Schema::Option(_) | Schema::Vec(_) | Schema::Map(_, _) | Schema::OneOf { .. } => true, } } fn type_name(schema: &Schema) -> String { format!( "{}{}", type_name_prearray(schema), type_name_postarray(schema), ) } fn type_name_prearray(schema: &Schema) -> String { match schema { Schema::Bool => "bool".to_owned(), Schema::Int32 => "int".to_owned(), Schema::Int64 => "long".to_owned(), Schema::Float32 => "float".to_owned(), Schema::Float64 => "double".to_owned(), Schema::String => "string".to_owned(), Schema::Struct { .. } | Schema::OneOf { .. } | Schema::Enum { .. } => name_path(schema), Schema::Option(inner) => { if nullable(inner) { type_name(inner) } else { format!("{}?", type_name(inner)) } } Schema::Vec(inner) => type_name_prearray(inner), Schema::Map(key, value) => format!( "System.Collections.Generic.IDictionary<{}, {}>", type_name(key), type_name(value) ), } } fn type_name_postarray(schema: &Schema) -> String { match schema { Schema::Vec(inner) => format!("[]{}", type_name_postarray(inner)), _ => String::new(), } } fn doc_comment(documentation: &Documentation) -> String { let mut result = String::new(); result.push_str("/// <summary>\n"); for line in documentation.get("en").unwrap().lines() { result.push_str("/// "); result.push_str(line); result.push('\n'); } result.push_str("/// </summary>\n"); result.trim().to_owned() } fn doc_read_from(name: &str) -> String { format!("/// <summary> Read {} from reader </summary>", name) } fn doc_write_to(name: &str) -> String { format!("/// <summary> Write {} to writer </summary>", name) } fn doc_to_string(name: &str) -> String { format!( "/// <summary> Get string representation of {} </summary>", name, ) } fn read_var(var: &str, schema: &Schema) -> String { include_templing!("src/gens/csharp/read_var.templing") } fn write_var(var: &str, schema: &Schema) -> String { include_templing!("src/gens/csharp/write_var.templing") } fn var_to_string(var: &str, schema: &Schema) -> String { include_templing!("src/gens/csharp/var_to_string.templing") } fn struct_impl(definition: &Struct, base: Option<(&Name, usize)>) -> String { include_templing!("src/gens/csharp/struct_impl.templing") } fn namespace_path(namespace: &Namespace) -> String { namespace .parts .iter() .map(|name| name.camel_case(conv)) .collect::<Vec<_>>() .join(".") } fn namespace_path_suffix(namespace: &Namespace) -> String { let namespace_path = namespace_path(namespace); if namespace_path.is_empty() { namespace_path } else { format!(".{}", namespace_path) } } fn name_path(schema: &Schema) -> String { match schema { Schema::Enum { namespace, base_name: name, .. } | Schema::Struct { namespace, definition: Struct { name, .. }, .. } | Schema::OneOf { namespace, base_name: name, .. } => { let namespace_path = namespace_path(namespace); if namespace_path.is_empty() { name.camel_case(conv) } else { format!("{}.{}", namespace_path, name.camel_case(conv)) } } _ => unreachable!(), } } impl crate::Generator for Generator { const NAME: &'static str = "C#"; type Options = (); fn new(name: &str, _version: &str, _: ()) -> Self { let name = Name::new(name.to_owned()); let mut files = HashMap::new(); files.insert( format!("{}.csproj", name.camel_case(conv)), include_str!("project.csproj").to_owned(), ); Self { main_namespace: name.camel_case(conv), files, } } fn generate(mut self, extra_files: Vec<File>) -> GenResult { for file in extra_files { self.files.insert(file.path, file.content); } self.files.into() } fn add_only(&mut self, schema: &Schema) { match schema { Schema::Enum { namespace, documentation, base_name, variants, } => { self.files.insert( format!("{}.cs", name_path(schema).replace('.', "/")), include_templing!("src/gens/csharp/enum.templing"), ); } Schema::Struct { namespace, definition, } => { self.files.insert( format!("{}.cs", name_path(schema).replace('.', "/")), include_templing!("src/gens/csharp/struct.templing"), ); } Schema::OneOf { namespace, documentation, base_name, variants, } => { self.files.insert( format!("{}.cs", name_path(schema).replace('.', "/")), include_templing!("src/gens/csharp/oneof.templing"), ); } Schema::Bool | Schema::Int32 | Schema::Int64 | Schema::Float32 | Schema::Float64 | Schema::String | Schema::Option(_) | Schema::Vec(_) | Schema::Map(_, _) => {} } } } impl RunnableGenerator for Generator { fn build_local(path: &Path, verbose: bool) -> anyhow::Result<()> { command("dotnet") .current_dir(path) .arg("publish") .arg("-c") .arg("Release") .arg("-o") .arg(".") .show_output(verbose) .run() } fn run_local(path: &Path) -> anyhow::Result<Command> { fn project_name(path: &Path) -> anyhow::Result<String> { for file in std::fs::read_dir(path)? { let file = file?; if file.path().extension() == Some("csproj".as_ref()) { return Ok(file .path() .file_stem() .unwrap() .to_str() .unwrap() .to_owned()); } } anyhow::bail!("Failed to determine project name") } let mut command = command("dotnet"); command .arg(format!("{}.dll", project_name(path)?)) .current_dir(path); Ok(command) } } impl<D: Trans + PartialEq + Debug> TestableGenerator<testing::FileReadWrite<D>> for Generator { fn extra_files(&self, test: &testing::FileReadWrite<D>) -> Vec<File> { let schema = Schema::of::<D>(&test.version); let schema: &Schema = &schema; vec![File { path: "Runner.cs".to_owned(), content: include_templing!("src/gens/csharp/FileReadWrite.cs.templing"), }] } } impl<D: Trans + PartialEq + Debug> TestableGenerator<testing::TcpReadWrite<D>> for Generator { fn extra_files(&self, test: &testing::TcpReadWrite<D>) -> Vec<File> { let schema = Schema::of::<D>(&test.version);
}
let schema: &Schema = &schema; vec![File { path: "Runner.cs".to_owned(), content: include_templing!("src/gens/csharp/TcpReadWrite.cs.templing"), }] }
function_block-function_prefix_line
[ { "content": "fn struct_impl(definition: &Struct, base: Option<(&Name, usize)>) -> String {\n\n include_templing!(\"src/gens/python/struct_impl.templing\")\n\n}\n\n\n", "file_path": "src/gens/python/mod.rs", "rank": 0, "score": 497748.56248176645 }, { "content": "fn struct_impl(definition...
Rust
src/rust/grapl-observe/src/statsd_formatter.rs
alexjmacdonald/grapl
44d5fcabef02d11548018742c3dc00785ca7b571
use crate::metric_error::MetricError; use crate::metric_error::MetricError::{MetricInvalidCharacterError, MetricInvalidSampleRateError}; use crate::metric_reporter::TagPair; use lazy_static::lazy_static; use regex::Regex; use std::fmt::Write; lazy_static! { static ref INVALID_CHARS: Regex = Regex::new("[|#,=:]").unwrap(); } pub fn reject_invalid_chars(s: &str) -> Result<(), MetricError> { let matched = INVALID_CHARS.is_match(s); if matched { Err(MetricInvalidCharacterError()) } else { Ok(()) } } pub enum MetricType { Gauge, Counter, Histogram, } const GAUGE_STR: &'static str = "g"; const COUNTER_STR: &'static str = "c"; const HISTOGRAM_STR: &'static str = "h"; impl MetricType { fn statsd_type(&self) -> &'static str { match self { MetricType::Gauge => GAUGE_STR, MetricType::Counter => COUNTER_STR, MetricType::Histogram => HISTOGRAM_STR, } } } /** Don't call statsd_format directly; instead, prefer the public functions of MetricClient. To go from a formatted string to usable data again, use the 'statsd-parser' crate. */ #[allow(dead_code)] pub fn statsd_format( buf: &mut String, metric_name: &str, value: f64, metric_type: MetricType, sample_rate: impl Into<Option<f64>>, tags: &[TagPair], ) -> Result<(), MetricError> { buf.clear(); reject_invalid_chars(metric_name)?; write!( buf, "{metric_name}:{value}|{metric_type}", metric_name = metric_name, value = value, metric_type = metric_type.statsd_type() )?; match (metric_type, sample_rate.into()) { (MetricType::Counter, Some(rate)) => { if rate >= 0.0 && rate < 1.0 { write!(buf, "|@{sample_rate}", sample_rate = rate)?; } else { return Err(MetricInvalidSampleRateError()); } } _ => {} } let mut first_tag: bool = true; if !tags.is_empty() { write!(buf, "|#")?; for pair in tags { if !first_tag { write!(buf, ",")?; } else { first_tag = false; } pair.write_to_buf(buf)?; } } Ok(()) } #[cfg(test)] mod tests { use crate::metric_error::MetricError; use crate::statsd_formatter::{reject_invalid_chars, statsd_format, MetricType, TagPair}; const INVALID_STRS: [&str; 5] = [ "some|metric", "some#metric", "some,metric", "some:metric", "some=metric", ]; const VALID_STR: &str = "some_str"; const VALID_VALUE: f64 = 12345.6; fn make_tags() -> Vec<TagPair<'static>> { vec![ TagPair("some_key", "some_value"), TagPair("some_key_2", "some_value_2"), ] } fn make_empty_tags() -> [TagPair<'static>; 0] { let empty_slice: [TagPair<'static>; 0] = []; return empty_slice; } #[test] fn test_reject_invalid_chars() -> Result<(), String> { for invalid_str in INVALID_STRS.iter() { let result = reject_invalid_chars(invalid_str); match result.expect_err("else panic") { MetricError::MetricInvalidCharacterError() => Ok(()), _ => Err(String::from("expected invalid character error")), }? } assert!(reject_invalid_chars(VALID_STR).is_ok()); Ok(()) } #[test] fn test_statsd_format_basic_counter() -> Result<(), MetricError> { let mut buf: String = String::with_capacity(256); statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, None, &make_empty_tags(), )?; assert_eq!(buf, "some_str:12345.6|c"); Ok(()) } #[test] fn test_statsd_format_specify_rate() -> Result<(), MetricError> { let mut buf: String = String::with_capacity(256); statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, 0.5, &make_empty_tags(), )?; assert_eq!(buf, "some_str:12345.6|c|@0.5"); Ok(()) } #[test] fn test_statsd_format_specify_bad_rate() -> Result<(), String> { let mut buf: String = String::with_capacity(256); let result = statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, 1.5, &make_empty_tags(), ); match result.expect_err("") { MetricError::MetricInvalidSampleRateError() => Ok(()), _ => Err(String::from("unexpected err")), } } #[test] fn test_statsd_format_tags() -> Result<(), MetricError> { let mut buf: String = String::with_capacity(256); statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, None, &make_tags(), )?; assert_eq!( buf, "some_str:12345.6|c|#some_key:some_value,some_key_2:some_value_2" ); Ok(()) } #[test] fn test_statsd_format_bad_tags() -> Result<(), String> { let mut buf: String = String::with_capacity(256); let result = statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, None, &[TagPair("some|key", "val")], ); match result.expect_err("") { MetricError::MetricInvalidCharacterError() => Ok(()), _ => Err(String::from("unexpected err")), } } }
use crate::metric_error::MetricError; use crate::metric_error::MetricError::{MetricInvalidCharacterError, MetricInvalidSampleRateError}; use crate::metric_reporter::TagPair; use lazy_static::lazy_static; use regex::Regex; use std::fmt::Write; lazy_static! { static ref INVALID_CHARS: Regex = Regex::new("[|#,=:]").unwrap(); } pub fn reject_invalid_chars(s: &str) -> Result<(), MetricError> { let matched = INVALID_CHARS.is_match(s); if matched { Err(MetricInvalidCharacterError()) } else { Ok(()) } } pub enum MetricType { Gauge, Counter, Histogram, } const GAUGE_STR: &'static str = "g"; const COUNTER_STR: &'static str = "c"; const HISTOGRAM_STR: &'static str = "h"; impl MetricType { fn statsd_type(&self) -> &'static str { match self { MetricType::Gauge => GAUGE_STR, MetricType::Counter => COUNTER_STR, MetricType::Histogram => HISTOGRAM_STR, } } } /** Don't call statsd_format directly; instead, prefer the public functions of MetricClient. To go from a formatted string to usable data again, use the 'statsd-parser' crate. */ #[allow(dead_code)] pub fn statsd_format( buf: &mut String, metric_name: &str, value: f64, metric_type: MetricType, sample_rate: impl Into<Option<f64>>, tags: &[TagPair], ) -> Result<(), MetricError> { buf.clear(); reject_invalid_chars(metric_name)?; write!( buf, "{metric_name}:{value}|{metric_type}", metric_name = metric_name, value = value, metric_type = metric_type.statsd_type() )?; match (metric_type, sample_rate.into()) { (MetricType::Counter, Some(rate)) => { if rate >= 0.0 && rate < 1.0 { write!(buf, "|@{sample_rate}", sample_rate = rate)?; } else { return Err(MetricInvalidSampleRateError()); } } _ => {} } let mut first_tag: bool = true; if !tags.is_empty() { write!(buf, "|#")?; for pair in tags { if !first_tag { write!(buf, ",")?; } else { first_tag = false; } pair.write_to_buf(buf)?; } } Ok(()) } #[cfg(test)] mod tests { use crate::metric_error::MetricError; use crate::statsd_formatter::{reject_invalid_chars, statsd_format, MetricType, TagPair}; const INVALID_STRS: [&str; 5] = [ "some|metric", "some#metric", "some,metric", "some:metric", "some=metric", ]; const VALID_STR: &str = "some_str"; const VALID_VALUE: f64 = 12345.6; fn make_tags() -> Vec<TagPair<'static>> { vec![ TagPair("some_key", "some_value"), TagPair("some_key_2", "some_value_2"), ] } fn make_empty_tags() -> [TagPair<'static>; 0] { let empty_slice: [TagPair<'static>; 0] = []; return empty_slice; } #[test] fn test_reject_invalid_chars() -> Result<(), String> { for invalid_str in INVALID_STRS.iter() { let result = reject_invalid_chars(invalid_str); match result.expect_err("else panic") { MetricError::MetricInvalidCharacterError() => Ok(()), _ => Err(String::from("expected invalid character error")), }? } assert!(reject_invalid_chars(VALID_STR).is_ok()); Ok(()) } #[test] fn test_statsd_format_basic_counter() -> Result<(), MetricError> { let mut buf: String = String::with_capacity(256); statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, None, &make_empty_tags(), )?; assert_eq!(buf, "some_str:12345.6|c"); Ok(()) } #[test] fn test_statsd_format_specify_rate() -> Result<(), MetricError> { let mut buf: String = String::with_capacity(256); statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, 0.5, &make_empty_tags(), )?; assert_eq!(buf, "some_str:12345.6|c|@0.5"); Ok(()) } #[test]
#[test] fn test_statsd_format_tags() -> Result<(), MetricError> { let mut buf: String = String::with_capacity(256); statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, None, &make_tags(), )?; assert_eq!( buf, "some_str:12345.6|c|#some_key:some_value,some_key_2:some_value_2" ); Ok(()) } #[test] fn test_statsd_format_bad_tags() -> Result<(), String> { let mut buf: String = String::with_capacity(256); let result = statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, None, &[TagPair("some|key", "val")], ); match result.expect_err("") { MetricError::MetricInvalidCharacterError() => Ok(()), _ => Err(String::from("unexpected err")), } } }
fn test_statsd_format_specify_bad_rate() -> Result<(), String> { let mut buf: String = String::with_capacity(256); let result = statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, 1.5, &make_empty_tags(), ); match result.expect_err("") { MetricError::MetricInvalidSampleRateError() => Ok(()), _ => Err(String::from("unexpected err")), } }
function_block-full_function
[ { "content": "/// Converts a Sysmon UTC string to UNIX Epoch time\n\n///\n\n/// If the provided string is not parseable as a UTC timestamp, an error is returned.\n\npub fn utc_to_epoch(utc: &str) -> Result<u64, Error> {\n\n let dt = NaiveDateTime::parse_from_str(utc, \"%Y-%m-%d %H:%M:%S%.3f\")?;\n\n\n\n l...
Rust
src/distribution/internal.rs
Twister915/statrs
c5536a8c916852259832b2064a9b845b68751c8f
pub fn is_valid_multinomial(arr: &[f64], incl_zero: bool) -> bool { let mut sum = 0.0; for &elt in arr { if incl_zero && elt < 0.0 || !incl_zero && elt <= 0.0 || elt.is_nan() { return false; } sum += elt; } sum != 0.0 } #[cfg(test)] pub mod tests { use super::is_valid_multinomial; use crate::consts::ACC; use crate::distribution::{Continuous, ContinuousCDF, Discrete, DiscreteCDF}; fn check_integrate_pdf_is_cdf<D: ContinuousCDF<f64, f64> + Continuous<f64, f64>>( dist: &D, x_min: f64, x_max: f64, step: f64, ) { let mut prev_x = x_min; let mut prev_density = dist.pdf(x_min); let mut sum = 0.0; loop { let x = prev_x + step; let density = dist.pdf(x); assert!(density >= 0.0); let ln_density = dist.ln_pdf(x); assert_almost_eq!(density.ln(), ln_density, 1e-10); sum += (prev_density + density) * step / 2.0; let cdf = dist.cdf(x); if (sum - cdf).abs() > 1e-3 { println!("Integral of pdf doesn't equal cdf!"); println!("Integration from {} by {} to {} = {}", x_min, step, x, sum); println!("cdf = {}", cdf); panic!(); } if x >= x_max { break; } else { prev_x = x; prev_density = density; } } assert!(sum > 0.99); assert!(sum <= 1.001); } fn check_sum_pmf_is_cdf<D: DiscreteCDF<u64, f64> + Discrete<u64, f64>>(dist: &D, x_max: u64) { let mut sum = 0.0; for i in 0..x_max + 3 { let prob = dist.pmf(i); assert!(prob >= 0.0); assert!(prob <= 1.0); sum += prob; if i == x_max { assert!(sum > 0.99); } assert_almost_eq!(sum, dist.cdf(i), 1e-10); } assert!(sum > 0.99); assert!(sum <= 1.0 + 1e-10); } pub fn check_continuous_distribution<D: ContinuousCDF<f64, f64> + Continuous<f64, f64>>( dist: &D, x_min: f64, x_max: f64, ) { assert_eq!(dist.pdf(f64::NEG_INFINITY), 0.0); assert_eq!(dist.pdf(f64::INFINITY), 0.0); assert_eq!(dist.ln_pdf(f64::NEG_INFINITY), f64::NEG_INFINITY); assert_eq!(dist.ln_pdf(f64::INFINITY), f64::NEG_INFINITY); assert_eq!(dist.cdf(f64::NEG_INFINITY), 0.0); assert_eq!(dist.cdf(f64::INFINITY), 1.0); check_integrate_pdf_is_cdf(dist, x_min, x_max, (x_max - x_min) / 100000.0); } pub fn check_discrete_distribution<D: DiscreteCDF<u64, f64> + Discrete<u64, f64>>( dist: &D, x_max: u64, ) { check_sum_pmf_is_cdf(dist, x_max); } #[test] fn test_is_valid_multinomial() { use std::f64; let invalid = [1.0, f64::NAN, 3.0]; assert!(!is_valid_multinomial(&invalid, true)); let invalid2 = [-2.0, 5.0, 1.0, 6.2]; assert!(!is_valid_multinomial(&invalid2, true)); let invalid3 = [0.0, 0.0, 0.0]; assert!(!is_valid_multinomial(&invalid3, true)); let valid = [5.2, 0.0, 1e-15, 1000000.12]; assert!(is_valid_multinomial(&valid, true)); } #[test] fn test_is_valid_multinomial_no_zero() { let invalid = [5.2, 0.0, 1e-15, 1000000.12]; assert!(!is_valid_multinomial(&invalid, false)); } }
pub fn is_valid_multinomial(arr: &[f64], incl_zero: bool) -> bool { let mut sum = 0.0; for &elt in arr { if incl_zero && elt < 0.0 || !incl_zero && elt <= 0.0 || elt.is_nan() { return false; } sum += elt; } sum != 0.0 } #[cfg(test)] pub mod tests { use super::is_valid_multinomial; use crate::consts::ACC; use crate::distribution::{Continuous, ContinuousCDF, Discrete, DiscreteCDF};
fn check_sum_pmf_is_cdf<D: DiscreteCDF<u64, f64> + Discrete<u64, f64>>(dist: &D, x_max: u64) { let mut sum = 0.0; for i in 0..x_max + 3 { let prob = dist.pmf(i); assert!(prob >= 0.0); assert!(prob <= 1.0); sum += prob; if i == x_max { assert!(sum > 0.99); } assert_almost_eq!(sum, dist.cdf(i), 1e-10); } assert!(sum > 0.99); assert!(sum <= 1.0 + 1e-10); } pub fn check_continuous_distribution<D: ContinuousCDF<f64, f64> + Continuous<f64, f64>>( dist: &D, x_min: f64, x_max: f64, ) { assert_eq!(dist.pdf(f64::NEG_INFINITY), 0.0); assert_eq!(dist.pdf(f64::INFINITY), 0.0); assert_eq!(dist.ln_pdf(f64::NEG_INFINITY), f64::NEG_INFINITY); assert_eq!(dist.ln_pdf(f64::INFINITY), f64::NEG_INFINITY); assert_eq!(dist.cdf(f64::NEG_INFINITY), 0.0); assert_eq!(dist.cdf(f64::INFINITY), 1.0); check_integrate_pdf_is_cdf(dist, x_min, x_max, (x_max - x_min) / 100000.0); } pub fn check_discrete_distribution<D: DiscreteCDF<u64, f64> + Discrete<u64, f64>>( dist: &D, x_max: u64, ) { check_sum_pmf_is_cdf(dist, x_max); } #[test] fn test_is_valid_multinomial() { use std::f64; let invalid = [1.0, f64::NAN, 3.0]; assert!(!is_valid_multinomial(&invalid, true)); let invalid2 = [-2.0, 5.0, 1.0, 6.2]; assert!(!is_valid_multinomial(&invalid2, true)); let invalid3 = [0.0, 0.0, 0.0]; assert!(!is_valid_multinomial(&invalid3, true)); let valid = [5.2, 0.0, 1e-15, 1000000.12]; assert!(is_valid_multinomial(&valid, true)); } #[test] fn test_is_valid_multinomial_no_zero() { let invalid = [5.2, 0.0, 1e-15, 1000000.12]; assert!(!is_valid_multinomial(&invalid, false)); } }
fn check_integrate_pdf_is_cdf<D: ContinuousCDF<f64, f64> + Continuous<f64, f64>>( dist: &D, x_min: f64, x_max: f64, step: f64, ) { let mut prev_x = x_min; let mut prev_density = dist.pdf(x_min); let mut sum = 0.0; loop { let x = prev_x + step; let density = dist.pdf(x); assert!(density >= 0.0); let ln_density = dist.ln_pdf(x); assert_almost_eq!(density.ln(), ln_density, 1e-10); sum += (prev_density + density) * step / 2.0; let cdf = dist.cdf(x); if (sum - cdf).abs() > 1e-3 { println!("Integral of pdf doesn't equal cdf!"); println!("Integration from {} by {} to {} = {}", x_min, step, x, sum); println!("cdf = {}", cdf); panic!(); } if x >= x_max { break; } else { prev_x = x; prev_density = density; } } assert!(sum > 0.99); assert!(sum <= 1.001); }
function_block-full_function
[ { "content": "/// Computes the inverse of the regularized incomplete beta function\n\n//\n\n// This code is based on the implementation in the [\"special\"][1] crate,\n\n// which in turn is based on a [C implementation][2] by John Burkardt. The\n\n// original algorithm was published in Applied Statistics and is...
Rust
gensokyo/src/config/core/device.rs
Usami-Renko/hakurei
cccc69fe71d6efd75089d1c03c9c49fefde8e2ca
use toml; use serde_derive::Deserialize; use crate::config::engine::ConfigMirror; use crate::error::{ GsResult, GsError }; use gsvk::core::device::DeviceConfig; use gsvk::core::device::QueueRequestStrategy; use crate::utils::time::TimePeriod; use std::time::Duration; #[derive(Deserialize)] pub(crate) struct DeviceConfigMirror { queue_request_strategy: String, transfer_time_out: String, transfer_duration: u64, print_device_name : bool, print_device_api : bool, print_device_type : bool, print_device_queues: bool, } impl Default for DeviceConfigMirror { fn default() -> DeviceConfigMirror { DeviceConfigMirror { queue_request_strategy: String::from("SingleFamilySingleQueue"), transfer_time_out: String::from("Infinite"), transfer_duration: 1000_u64, print_device_name : false, print_device_api : false, print_device_type : false, print_device_queues: false, } } } impl ConfigMirror for DeviceConfigMirror { type ConfigType = DeviceConfig; fn into_config(self) -> GsResult<Self::ConfigType> { let config = DeviceConfig { queue_request_strategy: vk_raw2queue_request_strategy(&self.queue_request_strategy)?, transfer_wait_time : vk_raw2transfer_wait_time(&self.transfer_time_out, self.transfer_duration)?.vulkan_time(), print_device_name : self.print_device_name, print_device_api : self.print_device_api, print_device_type : self.print_device_type, print_device_queues: self.print_device_queues, }; Ok(config) } fn parse(&mut self, toml: &toml::Value) -> GsResult<()> { if let Some(v) = toml.get("queue_request_strategy") { self.queue_request_strategy = v.as_str() .ok_or(GsError::config("core.device.queue_request_strategy"))?.to_owned(); } if let Some(v) = toml.get("transfer_time_out") { self.transfer_time_out = v.as_str() .ok_or(GsError::config("core.device.transfer_time_out"))?.to_owned(); } if let Some(v) = toml.get("transfer_duration") { self.transfer_duration = v.as_integer() .ok_or(GsError::config("core.device.transfer_duration"))?.to_owned() as u64; } if let Some(v) = toml.get("print") { if let Some(v) = v.get("device_name") { self.print_device_name = v.as_bool() .ok_or(GsError::config("core.device.print.device_name"))?.to_owned(); } if let Some(v) = v.get("device_api_version") { self.print_device_api = v.as_bool() .ok_or(GsError::config("core.device.print.device_api_version"))?.to_owned(); } if let Some(v) = v.get("device_type") { self.print_device_type = v.as_bool() .ok_or(GsError::config("core.device.print.device_type"))?.to_owned(); } if let Some(v) = v.get("device_queues") { self.print_device_queues = v.as_bool() .ok_or(GsError::config("core.device.print.device_queues"))?.to_owned(); } } Ok(()) } } fn vk_raw2queue_request_strategy(raw: &String) -> GsResult<QueueRequestStrategy> { let strategy = match raw.as_str() { | "SingleFamilySingleQueue" => QueueRequestStrategy::SingleFamilySingleQueue, | "SingleFamilyMultiQueues" => QueueRequestStrategy::SingleFamilyMultiQueues, | _ => return Err(GsError::config(raw)), }; Ok(strategy) } fn vk_raw2transfer_wait_time(time_out: &String, duration: u64) -> GsResult<TimePeriod> { let time = match time_out.as_str() { | "Infinite" => TimePeriod::Infinite, | "Immediate" => TimePeriod::Immediate, | "Timing" => TimePeriod::Time(Duration::from_millis(duration)), | _ => return Err(GsError::config(time_out)), }; Ok(time) }
use toml; use serde_derive::Deserialize; use crate::config::engine::ConfigMirror; use crate::error::{ GsResult, GsError }; use gsvk::core::device::DeviceConfig; use gsvk::core::device::QueueRequestStrategy; use crate::utils::time::TimePeriod; use std::time::Duration; #[derive(Deserialize)] pub(crate) struct DeviceConfigMirror { queue_request_strategy: String, transfer_time_out: String, transfer_duration: u64, print_device_name : bool, print_device_api : bool, print_device_type : bool, print_device_queues: bool, } impl Default for DeviceConfigMirror { fn default() -> DeviceConfigMirror { DeviceConfigMirror { queue_request_strategy: String::from("SingleFamilySingleQueue"), transfer_time_out: String::from("Infinite"), transfer_duration: 1000_u64, print_device_name : false, print_device_api : false, print_device_type : false, print_device_queues: false, } } } impl ConfigMirror for DeviceConfigMirror { type ConfigType = DeviceConfig; fn into_config(self) -> GsResult<Self::ConfigType> { let config = DeviceConfig { queue_request_strategy: vk_raw2queue_request_strategy(&self.queue_request_strategy)?, transfer_wait_time : vk_raw2transfer_wait_time(&self.transfer_time_out, self.transfer_duration)?.vulkan_time(), print_device_name : self.print_device_name, print_device_api : self.print_device_api, print_device_type : self.print_device_type, print_device_queues: self.print_device_queues, }; Ok(config) } fn parse(&mut self, toml: &toml::Value) -> GsResult<()> { if let Some(v) = toml.get("queue_request_strategy") { self.queue_request_strategy = v.as_str() .ok_or(GsError::config("core.device.queue_request_strategy"))?.to_owned(); } if let Some(v) = toml.get("transfer_time_out") { self.transfer_time_out = v.as_str() .ok_or(GsError::config("core.device.transfer_time_out"))?.to_owned(); } if let Some(v) = toml.get("transfer_duration") { self.transfer_duration = v.as_integer() .ok_or(GsError::config("core.device.transfer_duration"))?.to_owned() as u64; } if let Some(v) = toml.get("print") { if let Some(v) = v.get("device_name") { self.print_device_name = v.as_bool() .ok_or(GsError::config("core.device.print.devic
e = match time_out.as_str() { | "Infinite" => TimePeriod::Infinite, | "Immediate" => TimePeriod::Immediate, | "Timing" => TimePeriod::Time(Duration::from_millis(duration)), | _ => return Err(GsError::config(time_out)), }; Ok(time) }
e_name"))?.to_owned(); } if let Some(v) = v.get("device_api_version") { self.print_device_api = v.as_bool() .ok_or(GsError::config("core.device.print.device_api_version"))?.to_owned(); } if let Some(v) = v.get("device_type") { self.print_device_type = v.as_bool() .ok_or(GsError::config("core.device.print.device_type"))?.to_owned(); } if let Some(v) = v.get("device_queues") { self.print_device_queues = v.as_bool() .ok_or(GsError::config("core.device.print.device_queues"))?.to_owned(); } } Ok(()) } } fn vk_raw2queue_request_strategy(raw: &String) -> GsResult<QueueRequestStrategy> { let strategy = match raw.as_str() { | "SingleFamilySingleQueue" => QueueRequestStrategy::SingleFamilySingleQueue, | "SingleFamilyMultiQueues" => QueueRequestStrategy::SingleFamilyMultiQueues, | _ => return Err(GsError::config(raw)), }; Ok(strategy) } fn vk_raw2transfer_wait_time(time_out: &String, duration: u64) -> GsResult<TimePeriod> { let tim
random
[]
Rust
src/config.rs
meltinglava/rust-osauth
aef0567d48508d98686c7c000b62311564f691f6
use std::collections::HashMap; use std::env; use std::fs::File; use std::path::{Path, PathBuf}; use dirs; use log::warn; use serde::Deserialize; use serde_yaml; use super::identity::Password; use super::{Error, ErrorKind, Session}; use osproto::identity::IdOrName; #[derive(Debug, Deserialize)] struct Auth { auth_url: String, password: String, #[serde(default)] project_name: Option<String>, #[serde(default)] project_domain_name: Option<String>, username: String, #[serde(default)] user_domain_name: Option<String>, } #[derive(Debug, Deserialize)] struct Cloud { auth: Auth, #[serde(default)] region_name: Option<String>, } #[derive(Debug, Deserialize)] struct Clouds { #[serde(flatten)] clouds: HashMap<String, Cloud>, } #[derive(Debug, Deserialize)] struct Root { clouds: Clouds, } fn find_config() -> Option<PathBuf> { let current = Path::new("./clouds.yaml"); if current.is_file() { match current.canonicalize() { Ok(val) => return Some(val), Err(e) => warn!("Cannot canonicalize {:?}: {}", current, e), } } if let Some(mut home) = dirs::home_dir() { home.push(".config/openstack/clouds.yaml"); if home.is_file() { return Some(home); } } else { warn!("Cannot find home directory"); } let abs = PathBuf::from("/etc/openstack/clouds.yaml"); if abs.is_file() { Some(abs) } else { None } } pub fn from_config<S: AsRef<str>>(cloud_name: S) -> Result<Session, Error> { let path = find_config().ok_or_else(|| { Error::new( ErrorKind::InvalidConfig, "clouds.yaml was not found in any location", ) })?; let file = File::open(path).map_err(|e| { Error::new( ErrorKind::InvalidConfig, format!("Cannot read config.yaml: {}", e), ) })?; let mut clouds_root: Root = serde_yaml::from_reader(file).map_err(|e| { Error::new( ErrorKind::InvalidConfig, format!("Cannot parse clouds.yaml: {}", e), ) })?; let name = cloud_name.as_ref(); let cloud = clouds_root.clouds.clouds.remove(name).ok_or_else(|| { Error::new(ErrorKind::InvalidConfig, format!("No such cloud: {}", name)) })?; let auth = cloud.auth; let user_domain = auth .user_domain_name .unwrap_or_else(|| String::from("Default")); let project_domain = auth .project_domain_name .unwrap_or_else(|| String::from("Default")); let mut id = Password::new(&auth.auth_url, auth.username, auth.password, user_domain)?; if let Some(project_name) = auth.project_name { id.set_project_scope(IdOrName::Name(project_name), IdOrName::Name(project_domain)); } if let Some(region) = cloud.region_name { id.set_region(region) } Ok(Session::new(id)) } const MISSING_ENV_VARS: &str = "Not all required environment variables were provided"; #[inline] fn _get_env(name: &str) -> Result<String, Error> { env::var(name).map_err(|_| Error::new(ErrorKind::InvalidInput, MISSING_ENV_VARS)) } pub fn from_env() -> Result<Session, Error> { if let Ok(cloud_name) = env::var("OS_CLOUD") { from_config(cloud_name) } else { let auth_url = _get_env("OS_AUTH_URL")?; let user_name = _get_env("OS_USERNAME")?; let password = _get_env("OS_PASSWORD")?; let user_domain = env::var("OS_USER_DOMAIN_NAME").unwrap_or_else(|_| String::from("Default")); let id = Password::new(&auth_url, user_name, password, user_domain)?; let project = _get_env("OS_PROJECT_ID") .map(IdOrName::Id) .or_else(|_| _get_env("OS_PROJECT_NAME").map(IdOrName::Name))?; let project_domain = _get_env("OS_PROJECT_DOMAIN_ID") .map(IdOrName::Id) .or_else(|_| _get_env("OS_PROJECT_DOMAIN_NAME").map(IdOrName::Name)) .ok(); let mut session = Session::new(id.with_project_scope(project, project_domain)); if let Ok(interface) = env::var("OS_INTERFACE") { session.set_endpoint_interface(interface) } Ok(session) } }
use std::collections::HashMap; use std::env; use std::fs::File; use std::path::{Path, PathBuf}; use dirs; use log::
r("OS_CLOUD") { from_config(cloud_name) } else { let auth_url = _get_env("OS_AUTH_URL")?; let user_name = _get_env("OS_USERNAME")?; let password = _get_env("OS_PASSWORD")?; let user_domain = env::var("OS_USER_DOMAIN_NAME").unwrap_or_else(|_| String::from("Default")); let id = Password::new(&auth_url, user_name, password, user_domain)?; let project = _get_env("OS_PROJECT_ID") .map(IdOrName::Id) .or_else(|_| _get_env("OS_PROJECT_NAME").map(IdOrName::Name))?; let project_domain = _get_env("OS_PROJECT_DOMAIN_ID") .map(IdOrName::Id) .or_else(|_| _get_env("OS_PROJECT_DOMAIN_NAME").map(IdOrName::Name)) .ok(); let mut session = Session::new(id.with_project_scope(project, project_domain)); if let Ok(interface) = env::var("OS_INTERFACE") { session.set_endpoint_interface(interface) } Ok(session) } }
warn; use serde::Deserialize; use serde_yaml; use super::identity::Password; use super::{Error, ErrorKind, Session}; use osproto::identity::IdOrName; #[derive(Debug, Deserialize)] struct Auth { auth_url: String, password: String, #[serde(default)] project_name: Option<String>, #[serde(default)] project_domain_name: Option<String>, username: String, #[serde(default)] user_domain_name: Option<String>, } #[derive(Debug, Deserialize)] struct Cloud { auth: Auth, #[serde(default)] region_name: Option<String>, } #[derive(Debug, Deserialize)] struct Clouds { #[serde(flatten)] clouds: HashMap<String, Cloud>, } #[derive(Debug, Deserialize)] struct Root { clouds: Clouds, } fn find_config() -> Option<PathBuf> { let current = Path::new("./clouds.yaml"); if current.is_file() { match current.canonicalize() { Ok(val) => return Some(val), Err(e) => warn!("Cannot canonicalize {:?}: {}", current, e), } } if let Some(mut home) = dirs::home_dir() { home.push(".config/openstack/clouds.yaml"); if home.is_file() { return Some(home); } } else { warn!("Cannot find home directory"); } let abs = PathBuf::from("/etc/openstack/clouds.yaml"); if abs.is_file() { Some(abs) } else { None } } pub fn from_config<S: AsRef<str>>(cloud_name: S) -> Result<Session, Error> { let path = find_config().ok_or_else(|| { Error::new( ErrorKind::InvalidConfig, "clouds.yaml was not found in any location", ) })?; let file = File::open(path).map_err(|e| { Error::new( ErrorKind::InvalidConfig, format!("Cannot read config.yaml: {}", e), ) })?; let mut clouds_root: Root = serde_yaml::from_reader(file).map_err(|e| { Error::new( ErrorKind::InvalidConfig, format!("Cannot parse clouds.yaml: {}", e), ) })?; let name = cloud_name.as_ref(); let cloud = clouds_root.clouds.clouds.remove(name).ok_or_else(|| { Error::new(ErrorKind::InvalidConfig, format!("No such cloud: {}", name)) })?; let auth = cloud.auth; let user_domain = auth .user_domain_name .unwrap_or_else(|| String::from("Default")); let project_domain = auth .project_domain_name .unwrap_or_else(|| String::from("Default")); let mut id = Password::new(&auth.auth_url, auth.username, auth.password, user_domain)?; if let Some(project_name) = auth.project_name { id.set_project_scope(IdOrName::Name(project_name), IdOrName::Name(project_domain)); } if let Some(region) = cloud.region_name { id.set_region(region) } Ok(Session::new(id)) } const MISSING_ENV_VARS: &str = "Not all required environment variables were provided"; #[inline] fn _get_env(name: &str) -> Result<String, Error> { env::var(name).map_err(|_| Error::new(ErrorKind::InvalidInput, MISSING_ENV_VARS)) } pub fn from_env() -> Result<Session, Error> { if let Ok(cloud_name) = env::va
random
[ { "content": "use log::{debug, trace};\n\nuse reqwest::header::HeaderMap;\n\nuse reqwest::r#async::{RequestBuilder, Response};\n\nuse reqwest::{Method, Url};\n\nuse serde::de::DeserializeOwned;\n\nuse serde::Serialize;\n\n\n\nuse super::cache;\n\nuse super::protocol::ServiceInfo;\n\nuse super::request;\n\nuse s...
Rust
src/query/iter/iter.rs
LechintanTudor/sparsey
024d4e7997172d6144f7ae59a255b20694ef3fa9
use crate::query::iter::{DenseIter, SparseIter}; use crate::query::{self, EntityIterator, Query}; use crate::storage::Entity; pub enum Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { Sparse(SparseIter<'a, G, I, E>), Dense(DenseIter<'a, G>), } impl<'a, G, I, E> Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { pub(crate) fn new(get: G, include: I, exclude: E) -> Self { let get_info = get.group_info(); let include_info = include.group_info(); let exclude_info = exclude.group_info(); match query::group_range(get_info, include_info, exclude_info) { Some(range) => { let (entities, components) = get.split_dense(); unsafe { let components = G::offset_component_ptrs(components, range.start as isize); let entities = &entities .unwrap_or_else(|| { include.into_any_entities().expect("Cannot iterate empty Query") }) .get_unchecked(range); Self::Dense(DenseIter::new(entities, components)) } } None => { let (get_entities, sparse, components) = get.split_sparse(); let (sparse_entities, include) = include.split_filter(); let (_, exclude) = exclude.split_filter(); let entities = match (get_entities, sparse_entities) { (Some(e1), Some(e2)) => { if e1.len() <= e2.len() { e1 } else { e2 } } (Some(e1), None) => e1, (None, Some(e2)) => e2, (None, None) => panic!("Cannot iterate empty Query"), }; unsafe { Self::Sparse(SparseIter::new(entities, sparse, include, exclude, components)) } } } } pub fn is_sparse(&self) -> bool { matches!(self, Self::Sparse(_)) } pub fn is_dense(&self) -> bool { matches!(self, Self::Dense(_)) } } impl<'a, G, I, E> Iterator for Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { type Item = G::Item; fn next(&mut self) -> Option<Self::Item> { match self { Self::Sparse(sparse) => sparse.next(), Self::Dense(dense) => dense.next(), } } fn fold<B, F>(self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, Self::Item) -> B, { match self { Self::Sparse(sparse) => sparse.fold(init, f), Self::Dense(dense) => dense.fold(init, f), } } } impl<'a, G, I, E> EntityIterator for Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { fn next_with_entity(&mut self) -> Option<(Entity, Self::Item)> { match self { Self::Sparse(sparse) => sparse.next_with_entity(), Self::Dense(dense) => dense.next_with_entity(), } } fn fold_with_entity<B, F>(self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, (Entity, Self::Item)) -> B, { match self { Self::Sparse(sparse) => sparse.fold_with_entity(init, f), Self::Dense(dense) => dense.fold_with_entity(init, f), } } }
use crate::query::iter::{DenseIter, SparseIter}; use crate::query::{self, EntityIterator, Query}; use crate::storage::Entity; pub enum Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { Sparse(SparseIter<'a, G, I, E>), Dense(DenseIter<'a, G>), } impl<'a, G, I, E> Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { pub(crate) fn new(get: G, include: I, exclude: E) -> Self { let get_info = get.group_info(); let include_info = include.group_info(); let exclude_info = exclude.group_info(); match query::group_range(get_info, include_info, exclude_info) { Some(range) => { let (entities, components) = get.split_dense(); unsafe { let components = G::offset_component_ptrs(components, range.start as isize); let entities = &entities .unwrap_or_else(|| { include.into_any_entities().expect("Cannot iterate empty Query") }) .get_unchecked(range); Self::Dense(DenseIter::new(entities, components)) } } None => { let (get_entities, sparse, components) = get.split_sparse(); let (sparse_entities, include) = include.split_filter(); let (_, exclude) = exclude.split_filter(); let entities =
; unsafe { Self::Sparse(SparseIter::new(entities, sparse, include, exclude, components)) } } } } pub fn is_sparse(&self) -> bool { matches!(self, Self::Sparse(_)) } pub fn is_dense(&self) -> bool { matches!(self, Self::Dense(_)) } } impl<'a, G, I, E> Iterator for Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { type Item = G::Item; fn next(&mut self) -> Option<Self::Item> { match self { Self::Sparse(sparse) => sparse.next(), Self::Dense(dense) => dense.next(), } } fn fold<B, F>(self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, Self::Item) -> B, { match self { Self::Sparse(sparse) => sparse.fold(init, f), Self::Dense(dense) => dense.fold(init, f), } } } impl<'a, G, I, E> EntityIterator for Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { fn next_with_entity(&mut self) -> Option<(Entity, Self::Item)> { match self { Self::Sparse(sparse) => sparse.next_with_entity(), Self::Dense(dense) => dense.next_with_entity(), } } fn fold_with_entity<B, F>(self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, (Entity, Self::Item)) -> B, { match self { Self::Sparse(sparse) => sparse.fold_with_entity(init, f), Self::Dense(dense) => dense.fold_with_entity(init, f), } } }
match (get_entities, sparse_entities) { (Some(e1), Some(e2)) => { if e1.len() <= e2.len() { e1 } else { e2 } } (Some(e1), None) => e1, (None, Some(e2)) => e2, (None, None) => panic!("Cannot iterate empty Query"), }
if_condition
[ { "content": "#[doc(hidden)]\n\npub trait EntityIterator: Iterator {\n\n fn next_with_entity(&mut self) -> Option<(Entity, Self::Item)>;\n\n\n\n fn fold_with_entity<B, F>(mut self, mut init: B, mut f: F) -> B\n\n where\n\n Self: Sized,\n\n F: FnMut(B, (Entity, Self::Item)) -> B,\n\n {\...
Rust
src/techblox/parsing_tools.rs
NGnius/libfj
2b1033449e50086c2768e3bbd4dafc0d5bb257f6
use std::io::{Read, Write}; use crate::techblox::Parsable; use half::f16; pub fn parse_header_u32(reader: &mut dyn Read) -> std::io::Result<u32> { let mut u32_buf = [0; 4]; reader.read(&mut u32_buf)?; Ok(u32::from_le_bytes(u32_buf)) } pub fn parse_u8(reader: &mut dyn Read) -> std::io::Result<u8> { let mut u8_buf = [0; 1]; reader.read(&mut u8_buf)?; Ok(u8_buf[0]) } pub fn parse_u32(reader: &mut dyn Read) -> std::io::Result<u32> { let mut u32_buf = [0; 4]; reader.read(&mut u32_buf)?; Ok(u32::from_le_bytes(u32_buf)) } pub fn parse_i32(reader: &mut dyn Read) -> std::io::Result<i32> { let mut i32_buf = [0; 4]; reader.read(&mut i32_buf)?; Ok(i32::from_le_bytes(i32_buf)) } pub fn parse_u64(reader: &mut dyn Read) -> std::io::Result<u64> { let mut u64_buf = [0; 8]; reader.read(&mut u64_buf)?; Ok(u64::from_le_bytes(u64_buf)) } pub fn parse_i64(reader: &mut dyn Read) -> std::io::Result<i64> { let mut i64_buf = [0; 8]; reader.read(&mut i64_buf)?; Ok(i64::from_le_bytes(i64_buf)) } pub fn parse_f32(reader: &mut dyn Read) -> std::io::Result<f32> { let mut f32_buf = [0; 4]; reader.read(&mut f32_buf)?; Ok(f32::from_le_bytes(f32_buf)) } pub fn dump_u8(data: u8, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_u32(data: u32, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_i32(data: i32, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_u64(data: u64, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_i64(data: i64, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_f32(data: f32, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } impl Parsable for u8 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 1]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for u32 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 4]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for i32 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 4]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for u64 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 8]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for i64 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 8]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for f32 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 4]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for f16 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 2]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } }
use std::io::{Read, Write}; use crate::techblox::Parsable; use half::f16; pub fn parse_header_u32(reader: &mut dyn Read) -> std::i
pub fn parse_u8(reader: &mut dyn Read) -> std::io::Result<u8> { let mut u8_buf = [0; 1]; reader.read(&mut u8_buf)?; Ok(u8_buf[0]) } pub fn parse_u32(reader: &mut dyn Read) -> std::io::Result<u32> { let mut u32_buf = [0; 4]; reader.read(&mut u32_buf)?; Ok(u32::from_le_bytes(u32_buf)) } pub fn parse_i32(reader: &mut dyn Read) -> std::io::Result<i32> { let mut i32_buf = [0; 4]; reader.read(&mut i32_buf)?; Ok(i32::from_le_bytes(i32_buf)) } pub fn parse_u64(reader: &mut dyn Read) -> std::io::Result<u64> { let mut u64_buf = [0; 8]; reader.read(&mut u64_buf)?; Ok(u64::from_le_bytes(u64_buf)) } pub fn parse_i64(reader: &mut dyn Read) -> std::io::Result<i64> { let mut i64_buf = [0; 8]; reader.read(&mut i64_buf)?; Ok(i64::from_le_bytes(i64_buf)) } pub fn parse_f32(reader: &mut dyn Read) -> std::io::Result<f32> { let mut f32_buf = [0; 4]; reader.read(&mut f32_buf)?; Ok(f32::from_le_bytes(f32_buf)) } pub fn dump_u8(data: u8, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_u32(data: u32, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_i32(data: i32, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_u64(data: u64, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_i64(data: i64, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_f32(data: f32, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } impl Parsable for u8 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 1]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for u32 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 4]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for i32 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 4]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for u64 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 8]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for i64 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 8]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for f32 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 4]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for f16 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 2]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } }
o::Result<u32> { let mut u32_buf = [0; 4]; reader.read(&mut u32_buf)?; Ok(u32::from_le_bytes(u32_buf)) }
function_block-function_prefixed
[ { "content": "pub fn lookup_hashname(hash: u32, data: &mut dyn Read) ->\n\n std::io::Result<Box<dyn Block>> {\n\n Ok(match hash {\n\n 1357220432 /*StandardBlockEntityDescriptorV4*/ => Box::new(BlockEntity::parse(data)?),\n\n 2281299333 /*PilotSeatEntityDescriptorV4*/ => Box::new(PilotSeatEnt...
Rust
fork-off/src/fetching.rs
aleph-zero-foundation/aleph-node
7c4e6a4948e661cbe46d8957cf0e0eab901d8ed3
use std::{collections::HashMap, sync::Arc}; use crate::Storage; use futures::future::join_all; use log::info; use parking_lot::Mutex; use reqwest::Client; use serde_json::Value; use crate::types::{BlockHash, Get, StorageKey, StorageValue}; const KEYS_BATCH_SIZE: u32 = 1000; pub struct StateFetcher { client: Client, http_rpc_endpoint: String, } async fn make_request_and_parse_result<T: serde::de::DeserializeOwned>( client: &Client, endpoint: &str, body: Value, ) -> T { let mut response: Value = client .post(endpoint) .json(&body) .send() .await .expect("Storage request has failed") .json() .await .expect("Could not deserialize response as JSON"); let result = response["result"].take(); serde_json::from_value(result).expect("Incompatible type of the result") } fn construct_json_body(method_name: &str, params: Value) -> Value { serde_json::json!({ "jsonrpc": "2.0", "id": 1, "method": method_name, "params": params }) } fn block_hash_body(block_num: Option<u32>) -> Value { let params = serde_json::json!([block_num]); construct_json_body("chain_getBlockHash", params) } fn get_storage_value_body(key: StorageKey, block_hash: Option<BlockHash>) -> Value { let params = serde_json::json!([key.get(), block_hash.map(Get::get)]); construct_json_body("state_getStorage", params) } fn get_keys_paged_body( prefix: StorageKey, count: u32, start_key: Option<StorageKey>, block_hash: Option<BlockHash>, ) -> Value { let params = serde_json::json!([ prefix.get(), count, start_key.map(Get::get), block_hash.map(Get::get) ]); construct_json_body("state_getKeysPaged", params) } impl StateFetcher { pub fn new(http_rpc_endpoint: String) -> Self { StateFetcher { client: Client::new(), http_rpc_endpoint, } } async fn value_fetching_worker( http_rpc_endpoint: String, id: usize, block: BlockHash, input: Arc<Mutex<Vec<StorageKey>>>, output: Arc<Mutex<Storage>>, ) { const LOG_PROGRESS_FREQUENCY: usize = 500; let fetcher = StateFetcher::new(http_rpc_endpoint); loop { let maybe_key = { let mut keys = input.lock(); keys.pop() }; let key = match maybe_key { Some(key) => key, None => break, }; let value = fetcher.get_value(key.clone(), block.clone()).await; let mut output_guard = output.lock(); output_guard.insert(key, value); if output_guard.len() % LOG_PROGRESS_FREQUENCY == 0 { info!("Fetched {} values", output_guard.len()); } } info!("Worker {:?} finished", id); } async fn make_request<T: serde::de::DeserializeOwned>(&self, body: Value) -> T { make_request_and_parse_result::<T>(&self.client, &self.http_rpc_endpoint, body).await } pub async fn get_most_recent_block(&self) -> BlockHash { let body = block_hash_body(None); let block: String = self.make_request(body).await; BlockHash::new(&block) } async fn get_keys_range( &self, count: u32, start_key: Option<StorageKey>, block_hash: Option<BlockHash>, ) -> Vec<StorageKey> { let prefix = StorageKey::new(""); let body = get_keys_paged_body(prefix, count, start_key, block_hash); let keys: Vec<StorageKey> = self.make_request(body).await; keys } async fn get_all_keys(&self, block_hash: BlockHash) -> Vec<StorageKey> { let mut last_key_fetched = None; let mut all_keys = Vec::new(); loop { let new_keys = self .get_keys_range(KEYS_BATCH_SIZE, last_key_fetched, Some(block_hash.clone())) .await; all_keys.extend_from_slice(&new_keys); info!( "Got {} new keys and have {} in total", new_keys.len(), all_keys.len() ); if new_keys.len() < KEYS_BATCH_SIZE as usize { break; } last_key_fetched = Some(new_keys.last().unwrap().clone()); } all_keys } async fn get_value(&self, key: StorageKey, block_hash: BlockHash) -> StorageValue { let body = get_storage_value_body(key, Some(block_hash)); self.make_request(body).await } async fn get_values( &self, keys: Vec<StorageKey>, block_hash: BlockHash, num_workers: u32, ) -> Storage { let n_keys = keys.len(); let input = Arc::new(Mutex::new(keys)); let output = Arc::new(Mutex::new(HashMap::with_capacity(n_keys))); let mut workers = Vec::new(); for id in 0..(num_workers as usize) { workers.push(StateFetcher::value_fetching_worker( self.http_rpc_endpoint.clone(), id, block_hash.clone(), input.clone(), output.clone(), )); } info!("Started {} workers to download values.", workers.len()); join_all(workers).await; assert!(input.lock().is_empty(), "Not all keys were fetched"); let mut guard = output.lock(); std::mem::take(&mut guard) } pub async fn get_full_state_at( &self, num_workers: u32, fetch_block: Option<BlockHash>, ) -> Storage { let block = if let Some(block) = fetch_block { block } else { self.get_most_recent_block().await }; info!("Fetching state at block {:?}", block); let keys = self.get_all_keys(block.clone()).await; self.get_values(keys, block, num_workers).await } pub async fn get_full_state_at_best_block(&self, num_workers: u32) -> Storage { self.get_full_state_at(num_workers, None).await } }
use std::{collections::HashMap, sync::Arc}; use crate::Storage; use futures::future::join_all; use log::info; use parking_lot::Mutex; use reqwest::Client; use serde_json::Value; use crate::types::{BlockHash, Get, StorageKey, StorageValue}; const KEYS_BATCH_SIZE: u32 = 1000; pub struct StateFetcher { client: Client, http_rpc_endpoint: String, } async fn make_request_and_parse_result<T: serde::de::DeserializeOwned>( client: &Client, endpoint: &str, body: Value, ) -> T { let mut response: Value = client .post(endpoint) .json(&body) .send() .await .expect("Storage request has failed") .json() .await .expect("Could not deserialize response as JSON"); let result = response["result"].take(); serde_json::from_value(result).expect("Incompatible type of the result") } fn construct_json_body(method_name: &str, params: Value) -> Value { serde_json::json!({ "jsonrpc": "2.0", "id": 1, "method": method_name, "params": params }) } fn block_hash_body(block_num: Option<u32>) -> Value { let params = serde_json::json!([block_num]); construct_json_body("chain_getBlockHash", params) } fn get_storage_value_body(key: StorageKey, block_hash: Option<BlockHash>) -> Value { let params = serde_json::json!([key.get(), block_hash.map(Get::get)]); construct_json_body("state_getStorage", params) } fn get_keys_paged_body( prefix: StorageKey, count: u32, start_key: Option<StorageKey>, block_hash: Option<BlockHash>, ) -> Value { let params = serde_json::json!([ prefix.get(), count, start_key.map(Get::get), block_hash.map(Get::get) ]); construct_json_body("state_getKeysPaged", params) } impl StateFetcher { pub fn new(http_rpc_endpoint: String) -> Self { StateFetcher { client: Client::new(), http_rpc_endpoint, } } async fn value_fetching_worker( http_rpc_endpoint: String, id: usize, block: BlockHash, input: Arc<Mutex<Vec<StorageKey>>>, output: Arc<Mutex<Storage>>, ) { const LOG_PROGRESS_FREQUENCY: usize = 500; let fetcher = StateFetcher::new(http_rpc_endpoint); loop { let maybe_key = { let mut keys = input.lock(); keys.pop() }; let key = match maybe_key { Some(key) => key, None => break, }; let value = fetcher.get_value(key.clone(), block.clone()).await; let mut output_guard
, output_guard.len()); } } info!("Worker {:?} finished", id); } async fn make_request<T: serde::de::DeserializeOwned>(&self, body: Value) -> T { make_request_and_parse_result::<T>(&self.client, &self.http_rpc_endpoint, body).await } pub async fn get_most_recent_block(&self) -> BlockHash { let body = block_hash_body(None); let block: String = self.make_request(body).await; BlockHash::new(&block) } async fn get_keys_range( &self, count: u32, start_key: Option<StorageKey>, block_hash: Option<BlockHash>, ) -> Vec<StorageKey> { let prefix = StorageKey::new(""); let body = get_keys_paged_body(prefix, count, start_key, block_hash); let keys: Vec<StorageKey> = self.make_request(body).await; keys } async fn get_all_keys(&self, block_hash: BlockHash) -> Vec<StorageKey> { let mut last_key_fetched = None; let mut all_keys = Vec::new(); loop { let new_keys = self .get_keys_range(KEYS_BATCH_SIZE, last_key_fetched, Some(block_hash.clone())) .await; all_keys.extend_from_slice(&new_keys); info!( "Got {} new keys and have {} in total", new_keys.len(), all_keys.len() ); if new_keys.len() < KEYS_BATCH_SIZE as usize { break; } last_key_fetched = Some(new_keys.last().unwrap().clone()); } all_keys } async fn get_value(&self, key: StorageKey, block_hash: BlockHash) -> StorageValue { let body = get_storage_value_body(key, Some(block_hash)); self.make_request(body).await } async fn get_values( &self, keys: Vec<StorageKey>, block_hash: BlockHash, num_workers: u32, ) -> Storage { let n_keys = keys.len(); let input = Arc::new(Mutex::new(keys)); let output = Arc::new(Mutex::new(HashMap::with_capacity(n_keys))); let mut workers = Vec::new(); for id in 0..(num_workers as usize) { workers.push(StateFetcher::value_fetching_worker( self.http_rpc_endpoint.clone(), id, block_hash.clone(), input.clone(), output.clone(), )); } info!("Started {} workers to download values.", workers.len()); join_all(workers).await; assert!(input.lock().is_empty(), "Not all keys were fetched"); let mut guard = output.lock(); std::mem::take(&mut guard) } pub async fn get_full_state_at( &self, num_workers: u32, fetch_block: Option<BlockHash>, ) -> Storage { let block = if let Some(block) = fetch_block { block } else { self.get_most_recent_block().await }; info!("Fetching state at block {:?}", block); let keys = self.get_all_keys(block.clone()).await; self.get_values(keys, block, num_workers).await } pub async fn get_full_state_at_best_block(&self, num_workers: u32) -> Storage { self.get_full_state_at(num_workers, None).await } }
= output.lock(); output_guard.insert(key, value); if output_guard.len() % LOG_PROGRESS_FREQUENCY == 0 { info!("Fetched {} values"
function_block-random_span
[ { "content": "fn json_req(method: &str, params: Value, id: u32) -> Value {\n\n json!({\n\n \"method\": method,\n\n \"params\": params,\n\n \"jsonrpc\": \"2.0\",\n\n \"id\": id.to_string(),\n\n })\n\n}\n\n\n", "file_path": "aleph-client/src/rpc.rs", "rank": 0, "score...
Rust
src/language_features/hover.rs
jcai849/kak-lsp
9444ad4bcb7019c1ff34c2b2ac8493b0ff2aba08
use crate::context::*; use crate::markup::*; use crate::types::*; use crate::util::*; use itertools::Itertools; use lsp_types::request::*; use lsp_types::*; use serde::Deserialize; use url::Url; pub fn text_document_hover(meta: EditorMeta, params: EditorParams, ctx: &mut Context) { let params = PositionParams::deserialize(params).unwrap(); let req_params = HoverParams { text_document_position_params: TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri: Url::from_file_path(&meta.buffile).unwrap(), }, position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(), }, work_done_progress_params: Default::default(), }; ctx.call::<HoverRequest, _>(meta, req_params, move |ctx: &mut Context, meta, result| { editor_hover(meta, params, result, ctx) }); } pub fn editor_hover( meta: EditorMeta, params: PositionParams, result: Option<Hover>, ctx: &mut Context, ) { let diagnostics = ctx.diagnostics.get(&meta.buffile); let pos = get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(); let diagnostics = diagnostics .map(|x| { x.iter() .filter(|x| { let start = x.range.start; let end = x.range.end; (start.line < pos.line && pos.line < end.line) || (start.line == pos.line && pos.line == end.line && start.character <= pos.character && pos.character <= end.character) || (start.line == pos.line && pos.line <= end.line && start.character <= pos.character) || (start.line <= pos.line && end.line == pos.line && pos.character <= end.character) }) .filter_map(|x| { let face = x .severity .map(|sev| match sev { DiagnosticSeverity::ERROR => FACE_INFO_DIAGNOSTIC_ERROR, DiagnosticSeverity::WARNING => FACE_INFO_DIAGNOSTIC_WARNING, DiagnosticSeverity::INFORMATION => FACE_INFO_DIAGNOSTIC_INFO, DiagnosticSeverity::HINT => FACE_INFO_DIAGNOSTIC_HINT, _ => { warn!("Unexpected DiagnosticSeverity: {:?}", sev); FACE_INFO_DEFAULT } }) .unwrap_or(FACE_INFO_DEFAULT); if !x.message.is_empty() { Some(format!( "• {{{}}}{}{{{}}}", face, escape_brace(x.message.trim()) .replace("\n", "\n "), FACE_INFO_DEFAULT, )) } else { None } }) .join("\n") }) .unwrap_or_else(String::new); let force_plaintext = ctx .config .language .get(&ctx.language_id) .and_then(|l| l.workaround_server_sends_plaintext_labeled_as_markdown) .unwrap_or(false); let contents = match result { None => "".to_string(), Some(result) => match result.contents { HoverContents::Scalar(contents) => { marked_string_to_kakoune_markup(contents, force_plaintext) } HoverContents::Array(contents) => contents .into_iter() .map(|md| marked_string_to_kakoune_markup(md, force_plaintext)) .filter(|markup| !markup.is_empty()) .join(&format!( "\n{{{}}}---{{{}}}\n", FACE_INFO_RULE, FACE_INFO_DEFAULT )), HoverContents::Markup(contents) => match contents.kind { MarkupKind::Markdown => markdown_to_kakoune_markup(contents.value, force_plaintext), MarkupKind::PlainText => contents.value, }, }, }; if contents.is_empty() && diagnostics.is_empty() { return; } let command = format!( "lsp-show-hover {} %§{}§ %§{}§", params.position, contents.replace("§", "§§"), diagnostics.replace("§", "§§") ); ctx.exec(meta, command); } trait PlainText { fn plaintext(self) -> String; } impl PlainText for MarkedString { fn plaintext(self) -> String { match self { MarkedString::String(contents) => contents, MarkedString::LanguageString(contents) => contents.value, } } }
use crate::context::*; use crate::markup::*; use crate::types::*; use crate::util::*; use itertools::Itertools; use lsp_types::request::*; use lsp_types::*; use serde::Deserialize; use url::Url; pub fn text_document_hover(meta: EditorMeta, params: EditorParams, ctx: &mut Context) { let params = PositionParams::deserialize(params).unwrap(); let req_params = HoverParams { text_document_position_params: TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri: Url::from_file_path(&meta.buffile).unwrap(), }, position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(), }, work_done_progress_params: Default::default(), }; ctx.call::<HoverRequest, _>(meta, req_params, move |ctx: &mut Context, meta, result| { editor_hover(meta, params, result, ctx) }); } pub fn editor_hover( meta: EditorMeta, params: PositionParams, result: Option<Hover>, ctx: &mut Context, ) { let diagnostics = ctx.diagnostics.get(&meta.buffile); let pos = get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(); let diagnostics = diagnostics .map(|x| { x.iter() .filter(|x| { let start = x.range.start; let end = x.range.end; (start.line < pos.line && pos.line < end.line) || (start.line == pos.line && pos.line == end.line && start.character <= pos.character && pos.character <= end.character) || (start.line == pos.line && pos.line <= end.line && start.character <= pos.character) || (start.line <= pos.line && end.line == pos.line && pos.character <= end.character) }) .filter_map(|x| { let face = x .severity .map(|sev| match sev { DiagnosticSeverity::ERROR => FACE_INFO_DIAGNOSTIC_ERROR, DiagnosticSeverity::WARNING => FACE_INFO_DIAGNOSTIC_WARNING, DiagnosticSeverity::INFORMATION => FACE_INFO_DIAGNOSTIC_INFO, DiagnosticSeverity::HINT => FACE_INFO_DIAGNOSTIC_HINT, _ => { warn!("Unexpected DiagnosticSeverity: {:?}", sev); FACE_INFO_DEFAULT } }) .unwrap_or(FACE_INFO_DEFAULT); if !x.message.is_empty() { Some(format!( "• {{{}}}{}{{{}}}", face, escape_brace(x.message.trim()) .replace("\n", "\n "), FACE_INFO_DEFAULT, )) } else { None } }) .join("\n") }) .unwrap_or_else(String::new); let force_plaintext = ctx .config .language .get(&ctx.language_id) .and_then(|l| l.workaround_server_sends_plaintext_labeled_as_markdown) .unwrap_or(false); let contents = match result { None => "".to_string(), Some(result) => match result.contents { HoverContents::Scalar(contents) => { marked_string_to_kakoune_markup(contents, force_plaintext) } HoverContents::Array(contents) => contents .into_iter() .map(|md| marked_string_to_kakoune_markup(md, force_plaintext)) .filter(|markup| !markup.is_empty()) .join(&format!( "\n{{{}}}---{{{}}}\n", FACE_INFO_RULE, FACE_INFO_DEFAULT )), HoverContents::Markup(contents) => match contents.kind { MarkupKind::Markdown => markdown_to_kakoune_markup(contents.value, force_plaintext), MarkupKind::PlainText => contents.value, }, }, }; if contents.is_empty() && diagnostics.is_empty() { return; } let command = format!( "lsp-show-hover {} %§{}§ %§{}§", params.position, contents.replace("§", "§§"), diagnostics.replace("§", "§§") ); ctx.exec(meta, command); } trait PlainText { fn plaintext(self) -> String; } impl PlainText for MarkedString {
}
fn plaintext(self) -> String { match self { MarkedString::String(contents) => contents, MarkedString::LanguageString(contents) => contents.value, } }
function_block-full_function
[ { "content": "pub fn text_document_formatting(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = FormattingOptions::deserialize(params)\n\n .expect(\"Params should follow FormattingOptions structure\");\n\n let req_params = DocumentFormattingParams {\n\n text_docum...
Rust
crates/storage/src/traits/impls/tuples.rs
tetcoin/ink
8609b374ed19d23a48382393caee8c02bcf5f86a
use crate::traits::{ KeyPtr, PackedLayout, SpreadLayout, }; use pro_primitives::Key; macro_rules! impl_layout_for_tuple { ( $($frag:ident),* $(,)? ) => { impl<$($frag),*> SpreadLayout for ($($frag),* ,) where $( $frag: SpreadLayout, )* { const FOOTPRINT: u64 = 0 $(+ <$frag as SpreadLayout>::FOOTPRINT)*; const REQUIRES_DEEP_CLEAN_UP: bool = false $(|| <$frag as SpreadLayout>::REQUIRES_DEEP_CLEAN_UP)*; fn push_spread(&self, ptr: &mut KeyPtr) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as SpreadLayout>::push_spread($frag, ptr); )* } fn clear_spread(&self, ptr: &mut KeyPtr) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as SpreadLayout>::clear_spread($frag, ptr); )* } fn pull_spread(ptr: &mut KeyPtr) -> Self { ( $( <$frag as SpreadLayout>::pull_spread(ptr), )* ) } } impl<$($frag),*> PackedLayout for ($($frag),* ,) where $( $frag: PackedLayout, )* { #[inline] fn push_packed(&self, at: &Key) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as PackedLayout>::push_packed($frag, at); )* } #[inline] fn clear_packed(&self, at: &Key) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as PackedLayout>::clear_packed($frag, at); )* } #[inline] fn pull_packed(&mut self, at: &Key) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as PackedLayout>::pull_packed($frag, at); )* } } } } impl_layout_for_tuple!(A); impl_layout_for_tuple!(A, B); impl_layout_for_tuple!(A, B, C); impl_layout_for_tuple!(A, B, C, D); impl_layout_for_tuple!(A, B, C, D, E); impl_layout_for_tuple!(A, B, C, D, E, F); impl_layout_for_tuple!(A, B, C, D, E, F, G); impl_layout_for_tuple!(A, B, C, D, E, F, G, H); impl_layout_for_tuple!(A, B, C, D, E, F, G, H, I); impl_layout_for_tuple!(A, B, C, D, E, F, G, H, I, J); #[cfg(test)] mod tests { use crate::push_pull_works_for_primitive; type TupleSix = (i32, u32, String, u8, bool, Box<Option<i32>>); push_pull_works_for_primitive!( TupleSix, [ ( -1, 1, String::from("foobar"), 13, true, Box::new(Some(i32::MIN)) ), ( i32::MIN, u32::MAX, String::from("❤ ♡ ❤ ♡ ❤"), Default::default(), false, Box::new(Some(i32::MAX)) ), ( Default::default(), Default::default(), Default::default(), Default::default(), Default::default(), Default::default() ) ] ); }
use crate::traits::{ KeyPtr, PackedLayout, SpreadLayout, }; use pro_primitives::Key; macro_rules! impl_layout_for_tuple { ( $($frag:ident),* $(,)? ) => { impl<$($frag),*> SpreadLayout for ($($frag),* ,) where $( $frag: SpreadLayout, )* { const FOOTPRINT: u64 = 0 $(+ <$frag as SpreadLayout>::FOOTPRINT)*; const REQUIRES_DEEP_CLEAN_UP: bool = false $(|| <$frag as SpreadLayout>::REQUIRES_DEEP_CLEAN_UP)*; fn push_spread(&self, ptr: &mut KeyPtr) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as SpreadLayout>::push_spread($frag, ptr
Default::default() ) ] ); }
); )* } fn clear_spread(&self, ptr: &mut KeyPtr) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as SpreadLayout>::clear_spread($frag, ptr); )* } fn pull_spread(ptr: &mut KeyPtr) -> Self { ( $( <$frag as SpreadLayout>::pull_spread(ptr), )* ) } } impl<$($frag),*> PackedLayout for ($($frag),* ,) where $( $frag: PackedLayout, )* { #[inline] fn push_packed(&self, at: &Key) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as PackedLayout>::push_packed($frag, at); )* } #[inline] fn clear_packed(&self, at: &Key) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as PackedLayout>::clear_packed($frag, at); )* } #[inline] fn pull_packed(&mut self, at: &Key) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as PackedLayout>::pull_packed($frag, at); )* } } } } impl_layout_for_tuple!(A); impl_layout_for_tuple!(A, B); impl_layout_for_tuple!(A, B, C); impl_layout_for_tuple!(A, B, C, D); impl_layout_for_tuple!(A, B, C, D, E); impl_layout_for_tuple!(A, B, C, D, E, F); impl_layout_for_tuple!(A, B, C, D, E, F, G); impl_layout_for_tuple!(A, B, C, D, E, F, G, H); impl_layout_for_tuple!(A, B, C, D, E, F, G, H, I); impl_layout_for_tuple!(A, B, C, D, E, F, G, H, I, J); #[cfg(test)] mod tests { use crate::push_pull_works_for_primitive; type TupleSix = (i32, u32, String, u8, bool, Box<Option<i32>>); push_pull_works_for_primitive!( TupleSix, [ ( -1, 1, String::from("foobar"), 13, true, Box::new(Some(i32::MIN)) ), ( i32::MIN, u32::MAX, String::from("❤ ♡ ❤ ♡ ❤"), Default::default(), false, Box::new(Some(i32::MAX)) ), ( Default::default(), Default::default(), Default::default(), Default::default(), Default::default(),
random
[ { "content": "/// Asserts that the given `footprint` is below `FOOTPRINT_CLEANUP_THRESHOLD`.\n\nfn assert_footprint_threshold(footprint: u64) {\n\n let footprint_threshold = crate::traits::FOOTPRINT_CLEANUP_THRESHOLD;\n\n assert!(\n\n footprint <= footprint_threshold,\n\n \"cannot clean-up a...
Rust
crates/api/src/event/mouse.rs
michalsieron/orbtk
f0d53cd645f55f632173a89aee2fa85edbd9e96f
use std::rc::Rc; use crate::{ prelude::*, proc_macros::{Event, IntoHandler}, shell::MouseButton, utils::*, }; pub fn check_mouse_condition(mouse_position: Point, widget: &WidgetContainer<'_>) -> bool { let enabled = widget.get::<bool>("enabled"); if !enabled { return false; } let bounds = widget.get::<Rectangle>("bounds"); let position = widget.get::<Point>("position"); let mut rect = Rectangle::new((0.0, 0.0), bounds.width(), bounds.height()); rect.set_x(position.x()); rect.set_y(position.y()); rect.contains(mouse_position) } #[derive(Event)] pub struct MouseMoveEvent { pub position: Point, } #[derive(Event)] pub struct ScrollEvent { pub delta: Point, } #[derive(Debug, Copy, Clone)] pub struct Mouse { pub button: MouseButton, pub position: Point, } #[derive(Event)] pub struct MouseUpEvent { pub button: MouseButton, pub position: Point, } #[derive(Event)] pub struct ClickEvent { pub position: Point, } #[derive(Event)] pub struct MouseDownEvent { pub button: MouseButton, pub position: Point, } #[derive(Event)] pub struct GlobalMouseUpEvent { pub button: MouseButton, pub position: Point, } pub type MouseHandlerFunction = dyn Fn(&mut StatesContext, Mouse) -> bool + 'static; pub type PositionHandlerFunction = dyn Fn(&mut StatesContext, Point) -> bool + 'static; pub type GlobalMouseHandlerFunction = dyn Fn(&mut StatesContext, Mouse) + 'static; pub struct ClickEventHandler { handler: Rc<PositionHandlerFunction>, } impl Into<Rc<dyn EventHandler>> for ClickEventHandler { fn into(self) -> Rc<dyn EventHandler> { Rc::new(self) } } impl EventHandler for ClickEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<ClickEvent>() .ok() .map_or(false, |event| (self.handler)(state_context, event.position)) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<ClickEvent>() } } #[derive(IntoHandler)] pub struct MouseDownEventHandler { handler: Rc<MouseHandlerFunction>, } impl EventHandler for MouseDownEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<MouseDownEvent>() .ok() .map_or(false, |event| { (self.handler)( state_context, Mouse { button: event.button, position: event.position, }, ) }) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<MouseDownEvent>() } } #[derive(IntoHandler)] pub struct GlobalMouseUpEventHandler { handler: Rc<GlobalMouseHandlerFunction>, } impl EventHandler for GlobalMouseUpEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<GlobalMouseUpEvent>() .ok() .map_or(false, |event| { (self.handler)( state_context, Mouse { button: event.button, position: event.position, }, ); false }) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<GlobalMouseUpEvent>() } } #[derive(IntoHandler)] pub struct MouseUpEventHandler { handler: Rc<MouseHandlerFunction>, } impl EventHandler for MouseUpEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<MouseUpEvent>() .ok() .map_or(false, |event| { (self.handler)( state_context, Mouse { button: event.button, position: event.position, }, ) }) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<MouseUpEvent>() } } #[derive(IntoHandler)] pub struct MouseMoveEventHandler { handler: Rc<PositionHandlerFunction>, } impl EventHandler for MouseMoveEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<MouseMoveEvent>() .ok() .map_or(false, |event| (self.handler)(state_context, event.position)) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<MouseMoveEvent>() } } #[derive(IntoHandler)] pub struct ScrollEventHandler { handler: Rc<PositionHandlerFunction>, } impl EventHandler for ScrollEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<ScrollEvent>() .ok() .map_or(false, |event| (self.handler)(state_context, event.delta)) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<ScrollEvent>() } } pub trait MouseHandler: Sized + Widget { fn on_click<H: Fn(&mut StatesContext, Point) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(ClickEventHandler { handler: Rc::new(handler), }) } fn on_mouse_down<H: Fn(&mut StatesContext, Mouse) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(MouseDownEventHandler { handler: Rc::new(handler), }) } fn on_mouse_up<H: Fn(&mut StatesContext, Mouse) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(MouseUpEventHandler { handler: Rc::new(handler), }) } fn on_global_mouse_up<H: Fn(&mut StatesContext, Mouse) + 'static>(self, handler: H) -> Self { self.insert_handler(GlobalMouseUpEventHandler { handler: Rc::new(handler), }) } fn on_mouse_move<H: Fn(&mut StatesContext, Point) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(MouseMoveEventHandler { handler: Rc::new(handler), }) } fn on_scroll<H: Fn(&mut StatesContext, Point) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(ScrollEventHandler { handler: Rc::new(handler), }) } }
use std::rc::Rc; use crate::{ prelude::*, proc_macros::{Event, IntoHandler}, shell::MouseButton, utils::*, }; pub fn check_mouse_condition(mouse_position: Point, widget: &WidgetContainer<'_>) -> bool { let enabled = widget.get::<bool>("enabled"); if !enabled { return false; } let bounds = widget.get::<Rectangle>("bounds"); let position = widget.get::<Point>("position"); let mut rect = Rectangle::new((0.0, 0.0), bounds.width(), bounds.height()); rect.set_x(position.x()); rect.set_y(position.y()); rect.contains(mouse_position) } #[derive(Event)] pub struct MouseMoveEvent { pub position: Point, } #[derive(Event)] pub struct ScrollEvent { pub delta: Point, } #[derive(Debug, Copy, Clone)] pub struct Mouse { pub button: MouseButton, pub position: Point, } #[derive(Event)] pub struct MouseUpEvent { pub button: MouseButton, pub position: Point, } #[derive(Event)] pub struct ClickEvent { pub position: Point, } #[derive(Event)] pub struct MouseDownEvent { pub button: MouseButton, pub position: Point, } #[derive(Event)] pub struct GlobalMouseUpEvent { pub button: MouseButton, pub position: Point, } pub type MouseHandlerFunction = dyn Fn(&mut StatesContext, Mouse) -> bool + 'static; pub type PositionHandlerFunction = dyn Fn(&mut StatesContext, Point) -> bool + 'static; pub type GlobalMouseHandlerFunction = dyn Fn(&mut StatesContext, Mouse) + 'static; pub struct ClickEventHandler { handler: Rc<PositionHandlerFunction>, } impl Into<Rc<dyn EventHandler>> for ClickEventHandler { fn into(self) -> Rc<dyn EventHandler> { Rc::new(self) } } impl EventHandler for ClickEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<ClickEvent>() .ok() .map_or(false, |event| (self.handler)(state_context, event.position)) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<ClickEvent>() } } #[derive(IntoHandler)] pub struct MouseDownEventHandler { handler: Rc<MouseHandlerFunction>, } impl EventHandler for MouseDownEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<MouseDownEvent>() .ok() .map_or(false, |event| { (self.handler)( state_context, Mouse { button: event.button, position: event.position, }, ) }) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<MouseDownEvent>() } } #[derive(IntoHandler)] pub struct GlobalMouseUpEventHandler { handler: Rc<GlobalMouseHandlerFunction>, } impl EventHandler for GlobalMouseUpEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<GlobalMouseUpEvent>() .ok() .map_or(false, |event| { (self.handler)( state_context, Mouse { button: event.button, position: event.position, }, ); false }) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<GlobalMouseUpEvent>() } } #[derive(IntoHandler)] pub struct MouseUpEventHandler { handler: Rc<MouseHandlerFunction>, } impl EventHandler for MouseUpEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<MouseUpEvent>() .ok() .map_or(false, |event| { (self.handler)( state_context, Mouse { button: event.button, position: event.position, }, ) }) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<MouseUpEvent>() } } #[derive(IntoHandler)] pub struct MouseMoveEventHandler { handler: Rc<PositionHandlerFunction>, } impl EventHandler for MouseMoveEventHandler {
fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<MouseMoveEvent>() } } #[derive(IntoHandler)] pub struct ScrollEventHandler { handler: Rc<PositionHandlerFunction>, } impl EventHandler for ScrollEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<ScrollEvent>() .ok() .map_or(false, |event| (self.handler)(state_context, event.delta)) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<ScrollEvent>() } } pub trait MouseHandler: Sized + Widget { fn on_click<H: Fn(&mut StatesContext, Point) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(ClickEventHandler { handler: Rc::new(handler), }) } fn on_mouse_down<H: Fn(&mut StatesContext, Mouse) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(MouseDownEventHandler { handler: Rc::new(handler), }) } fn on_mouse_up<H: Fn(&mut StatesContext, Mouse) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(MouseUpEventHandler { handler: Rc::new(handler), }) } fn on_global_mouse_up<H: Fn(&mut StatesContext, Mouse) + 'static>(self, handler: H) -> Self { self.insert_handler(GlobalMouseUpEventHandler { handler: Rc::new(handler), }) } fn on_mouse_move<H: Fn(&mut StatesContext, Point) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(MouseMoveEventHandler { handler: Rc::new(handler), }) } fn on_scroll<H: Fn(&mut StatesContext, Point) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(ScrollEventHandler { handler: Rc::new(handler), }) } }
fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<MouseMoveEvent>() .ok() .map_or(false, |event| (self.handler)(state_context, event.position)) }
function_block-full_function
[ { "content": "fn get_mouse_button(button: event::MouseButton) -> MouseButton {\n\n match button {\n\n event::MouseButton::Wheel => MouseButton::Middle,\n\n event::MouseButton::Right => MouseButton::Right,\n\n _ => MouseButton::Left,\n\n }\n\n}\n\n\n", "file_path": "crates/shell/sr...
Rust
day10/src/main.rs
jtempest/advent_of_code_2019-rs
d1da25c963428fe1d1cb8a26bf80cc777979c110
use aoc::geom::{Dimensions, Vector2D}; use std::collections::HashSet; use std::fmt; #[derive(Debug)] struct AsteroidField { asteroids: HashSet<Vector2D>, dimensions: Dimensions, } impl AsteroidField { fn new(input: &str) -> AsteroidField { let lines = input.trim().lines(); let dimensions = Dimensions { width: lines.clone().next().unwrap().len(), height: lines.clone().count(), }; let asteroids = lines .enumerate() .flat_map(|(y, li)| { assert_eq!(li.len(), dimensions.width); li.trim() .chars() .enumerate() .filter(|(_, c)| *c == '#') .map(move |(x, _)| Vector2D { x: x as i64, y: y as i64, }) }) .collect(); AsteroidField { asteroids, dimensions, } } fn find_best_monitoring_asteroid(&self) -> (Vector2D, usize) { self.asteroids .iter() .copied() .map(|a| (a, self.num_visible_asteroids(a))) .max_by(|a, b| a.1.cmp(&b.1)) .unwrap() } fn num_visible_asteroids(&self, pos: Vector2D) -> usize { self.asteroids .iter() .copied() .map(|t| t - pos) .filter(|offset| *offset != Vector2D::zero()) .map(clock_position) .collect::<HashSet<_>>() .len() } fn vaporisation_order(&self, station_pos: Vector2D) -> Vec<Vector2D> { assert!(self.asteroids.contains(&station_pos)); let mut offsets = self .asteroids .iter() .map(|a| *a - station_pos) .filter(|o| *o != Vector2D::zero()) .map(|o| (clock_position(o) as u32, o)) .collect::<Vec<_>>(); offsets.sort_by(|a, b| { a.0.cmp(&b.0) .then(a.1.manhattan_length().cmp(&b.1.manhattan_length())) }); const FULL_ROTATION: u32 = std::u16::MAX as u32; let mut all_angles = HashSet::new(); for (angle, _) in offsets.iter_mut() { while all_angles.contains(angle) { *angle += FULL_ROTATION; } all_angles.insert(*angle); } offsets.sort_by(|a, b| a.0.cmp(&b.0)); offsets.into_iter().map(|(_, o)| o + station_pos).collect() } } impl fmt::Display for AsteroidField { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for coord in self.dimensions.iter() { if coord.x == 0 { writeln!(f)?; } let is_roid = self.asteroids.contains(&coord); let c = if is_roid { '#' } else { '.' }; write!(f, "{}", c)?; } Ok(()) } } fn clock_position(offset: Vector2D) -> u16 { use std::f64::consts::PI; const TWO_PI: f64 = PI * 2.0; let angle = (-offset.x as f64).atan2(offset.y as f64); let dist = (angle + PI) / TWO_PI; ((dist * std::u16::MAX as f64) + 1.0) as u16 } fn day10() -> (usize, usize) { const DAY10_INPUT: &str = include_str!("day10_input.txt"); let field = AsteroidField::new(DAY10_INPUT); let best = field.find_best_monitoring_asteroid(); let part1 = best.1; let order = field.vaporisation_order(best.0); let target = order[199]; let part2 = ((target.x * 100) + target.y) as usize; (part1, part2) } fn main() { let (part1, part2) = day10(); println!("part1 = {}", part1); println!("part1 = {}", part2); } #[cfg(test)] mod test { use super::*; #[test] fn test_clock_position() { assert_eq!(clock_position(Vector2D { x: 0, y: -1 }), 0); assert_eq!(clock_position(Vector2D { x: 1, y: 0 }), 16384); assert_eq!(clock_position(Vector2D { x: 0, y: 1 }), 32768); assert_eq!(clock_position(Vector2D { x: -1, y: 0 }), 49152); let clockwise = [ Vector2D { x: 0, y: -1 }, Vector2D { x: 1, y: -1 }, Vector2D { x: 1, y: 0 }, Vector2D { x: 1, y: 1 }, Vector2D { x: 0, y: 1 }, Vector2D { x: -1, y: 1 }, Vector2D { x: -1, y: 0 }, Vector2D { x: -1, y: -1 }, ]; for i in 0..(clockwise.len() - 1) { assert!(clock_position(clockwise[i]) < clock_position(clockwise[i + 1])); } } const EXAMPLE_FIELDS: [&str; 5] = [ include_str!("day10_example1.txt"), include_str!("day10_example2.txt"), include_str!("day10_example3.txt"), include_str!("day10_example4.txt"), include_str!("day10_example5.txt"), ]; #[test] fn test_find_best_monitoring_asteroid() { check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[0], (Vector2D { x: 3, y: 4 }, 8)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[1], (Vector2D { x: 5, y: 8 }, 33)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[2], (Vector2D { x: 1, y: 2 }, 35)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[3], (Vector2D { x: 6, y: 3 }, 41)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[4], (Vector2D { x: 11, y: 13 }, 210)); } fn check_find_best_monitoring_asteroid(input: &str, expected: (Vector2D, usize)) { let best = AsteroidField::new(input).find_best_monitoring_asteroid(); assert_eq!(best, expected); } #[test] fn test_vaporisation_order() { let field = AsteroidField::new(EXAMPLE_FIELDS[4]); let pos = field.find_best_monitoring_asteroid().0; let order = field.vaporisation_order(pos); assert_eq!(order.len(), 299); assert_eq!(order[0], Vector2D { x: 11, y: 12 }); assert_eq!(order[1], Vector2D { x: 12, y: 1 }); assert_eq!(order[2], Vector2D { x: 12, y: 2 }); assert_eq!(order[9], Vector2D { x: 12, y: 8 }); assert_eq!(order[19], Vector2D { x: 16, y: 0 }); assert_eq!(order[49], Vector2D { x: 16, y: 9 }); assert_eq!(order[99], Vector2D { x: 10, y: 16 }); assert_eq!(order[198], Vector2D { x: 9, y: 6 }); assert_eq!(order[199], Vector2D { x: 8, y: 2 }); assert_eq!(order[200], Vector2D { x: 10, y: 9 }); assert_eq!(order[298], Vector2D { x: 11, y: 1 }); } #[test] fn test_day10() { let (part1, part2) = day10(); assert_eq!(part1, 292); assert_eq!(part2, 317); } }
use aoc::geom::{Dimensions, Vector2D}; use std::collections::HashSet; use std::fmt; #[derive(Debug)] struct AsteroidField { asteroids: HashSet<Vector2D>, dimensions: Dimensions, } impl AsteroidField { fn new(input: &str) -> AsteroidField { let lines = input.trim().lines(); let dimensions = Dimensions { width: lines.clone().next().unwrap().len(), height: lines.clone().count(), }; let asteroids = lines .enumerate() .flat_map(|(y, li)| { assert_eq!(li.len(), dimensions.width); li.trim() .chars() .enumerate() .filter(|(_, c)| *c == '#') .map(move |(x, _)| Vector2D { x: x as i64, y: y as i64, }) }) .collect(); AsteroidField { asteroids, dimensions, } } fn find_best_monitoring_asteroid(&self) -> (Vector2D, usize) { self.asteroids .iter() .copied() .map(|a| (a, self.num_visible_asteroids(a))) .max_by(|a, b| a.1.cmp(&b.1)) .unwrap() } fn num_visible_asteroids(&self, pos: Vector2D) -> usize { self.asteroids .iter() .copied() .map(|t| t - pos) .filter(|offset| *offset != Vector2D::zero()) .map(clock_position) .collect::<HashSet<_>>() .len() } fn vaporisation_order(&self, station_pos: Vector2D) -> Vec<Vector2D> { assert!(self.asteroids.contains(&station_pos)); let mut offsets = self .asteroids .iter() .map(|a| *a - station_pos) .filter(|o| *o != Vector2D::zero()) .map(|o| (clock_position(o) as u32, o)) .collect::<Vec<_>>(); offsets.sort_by(|a, b| { a.0.cmp(&b.0) .then(a.1.manhattan_length().cmp(&b.1.manhattan_length())) }); const FULL_ROTATION: u32 = std::u16::MAX as u32; let mut all_angles = HashSet::new(); for (angle, _) in offsets.iter_mut() { while all_angles.contains(angle) { *angle += FULL_ROTATION; } all_angles.insert(*angle); } offsets.sort_by(|a, b| a.0.cmp(&b.0)); offsets.into_iter().map(|(_, o)| o + station_pos).collect() } } impl fmt::Display for AsteroidField { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for coord in self.dimensions.iter() { if coord.x == 0 { writeln!(f)?; } let is_roid = self.asteroids.contains(&coord); let c = if is_roid { '#' } else { '.' }; write!(f, "{}", c)?; } Ok(()) } } fn clock_position(offset: Vector2D) -> u16 { use std::f64::consts::PI; const TWO_PI: f64 = PI * 2.0; let angle = (-offset.x as f64).atan2(offset.y as f64); let dist = (angle + PI) / TWO_PI; ((dist * std::u16::MAX as f64) + 1.0) as u16 } fn day10() -> (usize, usize) { const DAY10_INPUT: &str = include_str!("day10_input.txt"); let field = AsteroidField::new(DAY10_INPUT); let best = field.find_best_monitoring_asteroid(); let part1 = best.1; let order = field.vaporisation_order(best.0); let target = order[199]; let part2 = ((target.x * 100) + target.y) as usize; (part1, part2) } fn main() { let (part1, part2) = day10(); println!("part1 = {}", part1); println!("part1 = {}", part2); } #[cfg(test)] mod test { use super::*; #[test] fn test_clock_position() { assert_eq!(clock_position(Vector2D { x: 0, y: -1 }), 0); assert_eq!(clock_position(Vector2D { x: 1, y: 0 }), 16384); assert_eq!(clock_position(Vector2D { x: 0, y: 1 }), 32768); assert_eq!(clock_position(Vector2D { x: -1, y: 0 }), 49152); let clockwise = [ Vector2D { x: 0, y: -1 }, Vector2D { x: 1, y: -1 }, Vector2D { x: 1, y: 0 }, Vector2D { x: 1, y: 1 }, Vector2D { x: 0, y: 1 }, Vector2D { x: -1, y: 1 }, Vector2D { x: -1, y: 0 }, Vector2D { x: -1, y: -1 }, ]; for i in 0..(clockwise.len() - 1) { assert!(clock_position(clockwise[i]) < clock_position(clockwise[i + 1])); } } const EXAMPLE_FIELDS: [&str; 5] = [ include_str!("day10_example1.txt"), include_str!("day10_example2.txt"), include_str!("day10_example3.txt"), include_str!("day10_example4.txt"), include_str!("day10_example5.txt"), ]; #[test] fn test_find_best_monitoring_asteroid() { check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[0], (Vector2D { x: 3, y: 4 }, 8)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[1], (Vector2D { x: 5, y: 8 }, 33)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[2], (Vector2D { x: 1, y: 2 }, 35)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[3], (Vector2D { x: 6, y: 3 }, 41)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[4], (Vector2D { x: 11, y: 13 }, 210)); } fn check_find_best_monitoring_asteroid(input: &str, expected: (Vector2D, usize)) { let best = AsteroidField::new(input).find_best_monitoring_asteroid(); assert_eq!(best, expected); } #[test] fn test_vaporisation_order() { let field = AsteroidField::new(EXAMPLE_FIELDS[4]); let pos = field.find_best_monitoring_asteroid().0; let order = field.vaporisation_order(pos); assert_eq!(order.len(), 299); assert_eq!(order[0], Vector2D { x: 11, y: 12 }); assert_eq!(order[1], Vector2D { x: 12, y: 1 }); assert_eq!(order[2], Vector2D { x: 12, y: 2 }); assert_eq!(order[9], Vector2D { x: 12, y: 8 }); assert_eq!(order[19], Vector2D { x: 16, y: 0 }); assert_eq!(order[49], Vector2D { x: 16, y: 9 });
#[test] fn test_day10() { let (part1, part2) = day10(); assert_eq!(part1, 292); assert_eq!(part2, 317); } }
assert_eq!(order[99], Vector2D { x: 10, y: 16 }); assert_eq!(order[198], Vector2D { x: 9, y: 6 }); assert_eq!(order[199], Vector2D { x: 8, y: 2 }); assert_eq!(order[200], Vector2D { x: 10, y: 9 }); assert_eq!(order[298], Vector2D { x: 11, y: 1 }); }
function_block-function_prefix_line
[ { "content": "fn max_signal<R: Iterator<Item = i64>, F: Fn(&mut Amplifier) -> i64>(\n\n program: &Program,\n\n settings: R,\n\n run_func: F,\n\n) -> i64 {\n\n let num_settings = settings.size_hint().1.unwrap();\n\n (settings)\n\n .permutations(num_settings)\n\n .fold(0, |max, settin...
Rust
crates/server/src/ctrl/gateway/ready.rs
Lantern-chat/server
7dfc00130dd4f8ee6a7b9efac9b7866ebf067e6d
use futures::{StreamExt, TryStreamExt}; use hashbrown::{hash_map::Entry, HashMap}; use schema::Snowflake; use thorn::pg::Json; use crate::{ ctrl::{auth::Authorization, util::encrypted_asset::encrypt_snowflake_opt, Error, SearchMode}, permission_cache::PermMute, ServerState, }; pub async fn ready( state: ServerState, conn_id: Snowflake, auth: Authorization, ) -> Result<sdk::models::events::Ready, Error> { use sdk::models::*; log::trace!("Processing Ready Event for {}", auth.user_id); let db = state.db.read.get().await?; let perms_future = async { state.perm_cache.add_reference(auth.user_id).await; super::refresh::refresh_room_perms(&state, &db, auth.user_id).await }; let user_future = async { let row = db .query_one_cached_typed( || { use schema::*; use thorn::*; Query::select() .and_where(AggUsers::Id.equals(Var::of(Users::Id))) .cols(&[ /* 0*/ AggUsers::Username, /* 1*/ AggUsers::Discriminator, /* 2*/ AggUsers::Flags, /* 3*/ AggUsers::Email, /* 4*/ AggUsers::CustomStatus, /* 5*/ AggUsers::Biography, /* 6*/ AggUsers::Preferences, /* 7*/ AggUsers::AvatarId, ]) .from_table::<AggUsers>() .limit_n(1) }, &[&auth.user_id], ) .await?; Ok::<_, Error>(User { id: auth.user_id, username: row.try_get(0)?, discriminator: row.try_get(1)?, flags: UserFlags::from_bits_truncate(row.try_get(2)?), email: Some(row.try_get(3)?), avatar: encrypt_snowflake_opt(&state, row.try_get(7)?), status: row.try_get(4)?, bio: row.try_get(5)?, preferences: { let value: Option<Json<_>> = row.try_get(6)?; value.map(|v| v.0) }, }) }; let parties_future = async { let rows = db .query_cached_typed( || { use schema::*; use thorn::*; Query::select() .cols(&[ /* 0*/ Party::Id, /* 1*/ Party::OwnerId, /* 2*/ Party::Name, /* 3*/ Party::AvatarId, /* 4*/ Party::Description, /* 5*/ Party::DefaultRoom, ]) .col(/*6*/ PartyMember::Position) .from( Party::left_join_table::<PartyMember>() .on(PartyMember::PartyId.equals(Party::Id)), ) .and_where(PartyMember::UserId.equals(Var::of(Users::Id))) .and_where(Party::DeletedAt.is_null()) }, &[&auth.user_id], ) .await?; let mut parties = HashMap::with_capacity(rows.len()); let mut ids = Vec::with_capacity(rows.len()); for row in rows { let id = row.try_get(0)?; ids.push(id); parties.insert( id, Party { partial: PartialParty { id, name: row.try_get(2)?, description: row.try_get(4)?, }, owner: row.try_get(1)?, security: SecurityFlags::empty(), roles: Vec::new(), emotes: Vec::new(), avatar: encrypt_snowflake_opt(&state, row.try_get(3)?), position: row.try_get(6)?, default_room: row.try_get(5)?, }, ); } let (roles, emotes) = futures::future::join( async { crate::ctrl::party::roles::get_roles_raw(&db, state.clone(), SearchMode::Many(&ids)) .await? .try_collect::<Vec<_>>() .await }, async { crate::ctrl::party::emotes::get_custom_emotes_raw(&db, SearchMode::Many(&ids)) .await? .try_collect::<Vec<_>>() .await }, ) .await; let (roles, emotes) = (roles?, emotes?); for role in roles { if let Some(party) = parties.get_mut(&role.party_id) { party.roles.push(role); } } for emote in emotes { if let Some(party) = parties.get_mut(&emote.party_id) { party.emotes.push(Emote::Custom(emote)); } } Ok::<_, Error>(parties.into_iter().map(|(_, v)| v).collect()) }; let (user, parties) = match tokio::join!(user_future, parties_future, perms_future) { (Ok(user), Ok(parties), Ok(())) => (user, parties), (Err(e), _, _) | (_, Err(e), _) | (_, _, Err(e)) => { log::warn!("Error during ready event: {e}"); state.perm_cache.remove_reference(auth.user_id).await; return Err(e); } }; Ok(events::Ready { user, dms: Vec::new(), parties, session: conn_id, }) } /* fn select_members() -> impl AnyQuery { use schema::*; Query::select() .and_where(PartyMember::PartyId.equals(Builtin::any(Var::of(SNOWFLAKE_ARRAY)))) .cols(&[PartyMember::PartyId, PartyMember::Nickname]) .cols(&[ Users::Id, Users::Username, Users::Discriminator, Users::Flags, ]) .col(RoleMembers::RoleId) .from( RoleMembers::right_join( Users::left_join_table::<PartyMember>().on(Users::Id.equals(PartyMember::UserId)), ) .on(RoleMembers::UserId.equals(Users::Id)), ) } fn select_members_old() -> impl AnyQuery { use schema::*; Query::select() .and_where(PartyMember::PartyId.equals(Builtin::any(Var::of(SNOWFLAKE_ARRAY)))) .cols(&[PartyMember::PartyId, PartyMember::Nickname]) .cols(&[ Users::Id, Users::Username, Users::Discriminator, Users::Flags, ]) .expr( Query::select() .from_table::<RoleMembers>() .expr(Builtin::array_agg(RoleMembers::RoleId)) .and_where(RoleMembers::UserId.equals(Users::Id)) .as_value(), ) .from(Users::left_join_table::<PartyMember>().on(Users::Id.equals(PartyMember::UserId))) } fn select_emotes() -> impl AnyQuery { use schema::*; Query::select() } */
use futures::{StreamExt, TryStreamExt}; use hashbrown::{hash_map::Entry, HashMap}; use schema::Snowflake; use thorn::pg::Json; use crate::{ ctrl::{auth::Authorization, util::encrypted_ass
async { crate::ctrl::party::emotes::get_custom_emotes_raw(&db, SearchMode::Many(&ids)) .await? .try_collect::<Vec<_>>() .await }, ) .await; let (roles, emotes) = (roles?, emotes?); for role in roles { if let Some(party) = parties.get_mut(&role.party_id) { party.roles.push(role); } } for emote in emotes { if let Some(party) = parties.get_mut(&emote.party_id) { party.emotes.push(Emote::Custom(emote)); } } Ok::<_, Error>(parties.into_iter().map(|(_, v)| v).collect()) }; let (user, parties) = match tokio::join!(user_future, parties_future, perms_future) { (Ok(user), Ok(parties), Ok(())) => (user, parties), (Err(e), _, _) | (_, Err(e), _) | (_, _, Err(e)) => { log::warn!("Error during ready event: {e}"); state.perm_cache.remove_reference(auth.user_id).await; return Err(e); } }; Ok(events::Ready { user, dms: Vec::new(), parties, session: conn_id, }) } /* fn select_members() -> impl AnyQuery { use schema::*; Query::select() .and_where(PartyMember::PartyId.equals(Builtin::any(Var::of(SNOWFLAKE_ARRAY)))) .cols(&[PartyMember::PartyId, PartyMember::Nickname]) .cols(&[ Users::Id, Users::Username, Users::Discriminator, Users::Flags, ]) .col(RoleMembers::RoleId) .from( RoleMembers::right_join( Users::left_join_table::<PartyMember>().on(Users::Id.equals(PartyMember::UserId)), ) .on(RoleMembers::UserId.equals(Users::Id)), ) } fn select_members_old() -> impl AnyQuery { use schema::*; Query::select() .and_where(PartyMember::PartyId.equals(Builtin::any(Var::of(SNOWFLAKE_ARRAY)))) .cols(&[PartyMember::PartyId, PartyMember::Nickname]) .cols(&[ Users::Id, Users::Username, Users::Discriminator, Users::Flags, ]) .expr( Query::select() .from_table::<RoleMembers>() .expr(Builtin::array_agg(RoleMembers::RoleId)) .and_where(RoleMembers::UserId.equals(Users::Id)) .as_value(), ) .from(Users::left_join_table::<PartyMember>().on(Users::Id.equals(PartyMember::UserId))) } fn select_emotes() -> impl AnyQuery { use schema::*; Query::select() } */
et::encrypt_snowflake_opt, Error, SearchMode}, permission_cache::PermMute, ServerState, }; pub async fn ready( state: ServerState, conn_id: Snowflake, auth: Authorization, ) -> Result<sdk::models::events::Ready, Error> { use sdk::models::*; log::trace!("Processing Ready Event for {}", auth.user_id); let db = state.db.read.get().await?; let perms_future = async { state.perm_cache.add_reference(auth.user_id).await; super::refresh::refresh_room_perms(&state, &db, auth.user_id).await }; let user_future = async { let row = db .query_one_cached_typed( || { use schema::*; use thorn::*; Query::select() .and_where(AggUsers::Id.equals(Var::of(Users::Id))) .cols(&[ /* 0*/ AggUsers::Username, /* 1*/ AggUsers::Discriminator, /* 2*/ AggUsers::Flags, /* 3*/ AggUsers::Email, /* 4*/ AggUsers::CustomStatus, /* 5*/ AggUsers::Biography, /* 6*/ AggUsers::Preferences, /* 7*/ AggUsers::AvatarId, ]) .from_table::<AggUsers>() .limit_n(1) }, &[&auth.user_id], ) .await?; Ok::<_, Error>(User { id: auth.user_id, username: row.try_get(0)?, discriminator: row.try_get(1)?, flags: UserFlags::from_bits_truncate(row.try_get(2)?), email: Some(row.try_get(3)?), avatar: encrypt_snowflake_opt(&state, row.try_get(7)?), status: row.try_get(4)?, bio: row.try_get(5)?, preferences: { let value: Option<Json<_>> = row.try_get(6)?; value.map(|v| v.0) }, }) }; let parties_future = async { let rows = db .query_cached_typed( || { use schema::*; use thorn::*; Query::select() .cols(&[ /* 0*/ Party::Id, /* 1*/ Party::OwnerId, /* 2*/ Party::Name, /* 3*/ Party::AvatarId, /* 4*/ Party::Description, /* 5*/ Party::DefaultRoom, ]) .col(/*6*/ PartyMember::Position) .from( Party::left_join_table::<PartyMember>() .on(PartyMember::PartyId.equals(Party::Id)), ) .and_where(PartyMember::UserId.equals(Var::of(Users::Id))) .and_where(Party::DeletedAt.is_null()) }, &[&auth.user_id], ) .await?; let mut parties = HashMap::with_capacity(rows.len()); let mut ids = Vec::with_capacity(rows.len()); for row in rows { let id = row.try_get(0)?; ids.push(id); parties.insert( id, Party { partial: PartialParty { id, name: row.try_get(2)?, description: row.try_get(4)?, }, owner: row.try_get(1)?, security: SecurityFlags::empty(), roles: Vec::new(), emotes: Vec::new(), avatar: encrypt_snowflake_opt(&state, row.try_get(3)?), position: row.try_get(6)?, default_room: row.try_get(5)?, }, ); } let (roles, emotes) = futures::future::join( async { crate::ctrl::party::roles::get_roles_raw(&db, state.clone(), SearchMode::Many(&ids)) .await? .try_collect::<Vec<_>>() .await },
random
[ { "content": "pub fn gateway(route: Route<crate::ServerState>) -> Response {\n\n let addr = match real_ip::get_real_ip(&route) {\n\n Ok(addr) => addr,\n\n Err(_) => return ApiError::bad_request().into_response(),\n\n };\n\n\n\n let query = match route.query() {\n\n Some(Ok(query)) ...
Rust
src/db/model/stardust/block/output/nft.rs
grtlr/inx-chronicle
9d9da951b97c0db2c65b66eb87e0491c653863f3
use std::str::FromStr; use bee_block_stardust::output as bee; use serde::{Deserialize, Serialize}; use super::{Feature, NativeToken, OutputAmount, UnlockCondition}; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct NftId(#[serde(with = "serde_bytes")] pub Box<[u8]>); impl NftId { pub fn from_output_id_str(s: &str) -> Result<Self, crate::db::error::Error> { Ok(bee::NftId::from(bee::OutputId::from_str(s)?).into()) } } impl From<bee::NftId> for NftId { fn from(value: bee::NftId) -> Self { Self(value.to_vec().into_boxed_slice()) } } impl TryFrom<NftId> for bee::NftId { type Error = crate::db::error::Error; fn try_from(value: NftId) -> Result<Self, Self::Error> { Ok(bee::NftId::new(value.0.as_ref().try_into()?)) } } impl FromStr for NftId { type Err = crate::db::error::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(bee::NftId::from_str(s)?.into()) } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct NftOutput { amount: OutputAmount, native_tokens: Box<[NativeToken]>, nft_id: NftId, unlock_conditions: Box<[UnlockCondition]>, features: Box<[Feature]>, immutable_features: Box<[Feature]>, } impl From<&bee::NftOutput> for NftOutput { fn from(value: &bee::NftOutput) -> Self { Self { amount: value.amount(), native_tokens: value.native_tokens().iter().map(Into::into).collect(), nft_id: (*value.nft_id()).into(), unlock_conditions: value.unlock_conditions().iter().map(Into::into).collect(), features: value.features().iter().map(Into::into).collect(), immutable_features: value.immutable_features().iter().map(Into::into).collect(), } } } impl TryFrom<NftOutput> for bee::NftOutput { type Error = crate::db::error::Error; fn try_from(value: NftOutput) -> Result<Self, Self::Error> { Ok(Self::build_with_amount(value.amount, value.nft_id.try_into()?)? .with_native_tokens( Vec::from(value.native_tokens) .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, _>>()?, ) .with_unlock_conditions( Vec::from(value.unlock_conditions) .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, _>>()?, ) .with_features( Vec::from(value.features) .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, _>>()?, ) .with_immutable_features( Vec::from(value.immutable_features) .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, _>>()?, ) .finish()?) } } #[cfg(test)] pub(crate) mod test { use mongodb::bson::{from_bson, to_bson}; use super::*; use crate::db::model::stardust::block::output::{ feature::test::{get_test_issuer_block, get_test_metadata_block, get_test_sender_block, get_test_tag_block}, native_token::test::get_test_native_token, unlock_condition::test::{ get_test_address_condition, get_test_expiration_condition, get_test_storage_deposit_return_condition, get_test_timelock_condition, }, }; #[test] fn test_nft_id_bson() { let nft_id = NftId::from(rand_nft_id()); let bson = to_bson(&nft_id).unwrap(); assert_eq!(nft_id, from_bson::<NftId>(bson).unwrap()); } #[test] fn test_nft_output_bson() { let output = get_test_nft_output(); let bson = to_bson(&output).unwrap(); assert_eq!(output, from_bson::<NftOutput>(bson).unwrap()); } pub(crate) fn rand_nft_id() -> bee::NftId { bee_test::rand::bytes::rand_bytes_array().into() } pub(crate) fn get_test_nft_output() -> NftOutput { NftOutput::from( &bee::NftOutput::build_with_amount(100, rand_nft_id()) .unwrap() .with_native_tokens(vec![get_test_native_token().try_into().unwrap()]) .with_unlock_conditions(vec![ get_test_address_condition(bee_test::rand::address::rand_address().into()) .try_into() .unwrap(), get_test_storage_deposit_return_condition(bee_test::rand::address::rand_address().into(), 1) .try_into() .unwrap(), get_test_timelock_condition(1, 1).try_into().unwrap(), get_test_expiration_condition(bee_test::rand::address::rand_address().into(), 1, 1) .try_into() .unwrap(), ]) .with_features(vec![ get_test_sender_block(bee_test::rand::address::rand_address().into()) .try_into() .unwrap(), get_test_metadata_block().try_into().unwrap(), get_test_tag_block().try_into().unwrap(), ]) .with_immutable_features(vec![ get_test_issuer_block(bee_test::rand::address::rand_address().into()) .try_into() .unwrap(), get_test_metadata_block().try_into().unwrap(), ]) .finish() .unwrap(), ) } }
use std::str::FromStr; use bee_block_stardust::output as bee; use serde::{Deserialize, Serialize}; use super::{Feature, NativeToken, OutputAmount, UnlockCondition}; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct NftId(#[serde(with = "serde_bytes")] pub Box<[u8]>); impl NftId { pub fn from_output_id_str(s: &str) -> Result<Self, crate::db::error::Error> { Ok(bee::NftId::from(bee::OutputId::from_str(s)?).into()) } } impl From<bee::NftId> for NftId { fn from(value: bee::NftId) -> Self { Self(value.to_vec().into_boxed_slice()) } } impl TryFrom<NftId> for bee::NftId { type Error = crate::db::error::Error; fn try_from(value: NftId) -> Result<Self, Self::Error> { Ok(bee::NftId::new(value.0.as_ref().try_into()?)) } } impl FromStr for NftId { type Err = crate::db::error::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(bee::NftId::from_str(s)?.into()) } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct NftOutput { amount: OutputAmount, native_tokens: Box<[NativeToken]>, nft_id: NftId, unlock_conditions: Box<[UnlockCondition]>, features: Box<[Feature]>, immutable_features: Box<[Feature]>, } impl From<&bee::NftOutput> for NftOutput { fn from(value: &bee::NftOutput) -> Self { Self { amount: value.amount(), native_tokens: value.native_tokens().iter().map(Into::into).collect(), nft_id: (*value.nft_id()).into(), unlock_conditions: value.unlock_conditions().iter().map(Into::into).collect(), features: value.features().iter().map(Into::into).collect(), immutable_features: value.immutable_features().iter().map(Into::into).collect(), } } } impl TryFrom<NftOutput> for bee::NftOutput { type Error = crate::db::error::Error; fn try_from(value: NftOutput) -> Result<Self, Self::Error> { Ok(Self::build_with_amount(value.amount, value.nft_id.try_into()?)? .with_native_tokens( Vec::from(value.native_tokens) .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, _>>()?, ) .with_unlock_conditions( Vec::from(value.unlock_conditions) .into_iter() .map(TryInto::try_into) .co
.try_into() .unwrap(), get_test_metadata_block().try_into().unwrap(), get_test_tag_block().try_into().unwrap(), ]) .with_immutable_features(vec![ get_test_issuer_block(bee_test::rand::address::rand_address().into()) .try_into() .unwrap(), get_test_metadata_block().try_into().unwrap(), ]) .finish() .unwrap(), ) } }
llect::<Result<Vec<_>, _>>()?, ) .with_features( Vec::from(value.features) .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, _>>()?, ) .with_immutable_features( Vec::from(value.immutable_features) .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, _>>()?, ) .finish()?) } } #[cfg(test)] pub(crate) mod test { use mongodb::bson::{from_bson, to_bson}; use super::*; use crate::db::model::stardust::block::output::{ feature::test::{get_test_issuer_block, get_test_metadata_block, get_test_sender_block, get_test_tag_block}, native_token::test::get_test_native_token, unlock_condition::test::{ get_test_address_condition, get_test_expiration_condition, get_test_storage_deposit_return_condition, get_test_timelock_condition, }, }; #[test] fn test_nft_id_bson() { let nft_id = NftId::from(rand_nft_id()); let bson = to_bson(&nft_id).unwrap(); assert_eq!(nft_id, from_bson::<NftId>(bson).unwrap()); } #[test] fn test_nft_output_bson() { let output = get_test_nft_output(); let bson = to_bson(&output).unwrap(); assert_eq!(output, from_bson::<NftOutput>(bson).unwrap()); } pub(crate) fn rand_nft_id() -> bee::NftId { bee_test::rand::bytes::rand_bytes_array().into() } pub(crate) fn get_test_nft_output() -> NftOutput { NftOutput::from( &bee::NftOutput::build_with_amount(100, rand_nft_id()) .unwrap() .with_native_tokens(vec![get_test_native_token().try_into().unwrap()]) .with_unlock_conditions(vec![ get_test_address_condition(bee_test::rand::address::rand_address().into()) .try_into() .unwrap(), get_test_storage_deposit_return_condition(bee_test::rand::address::rand_address().into(), 1) .try_into() .unwrap(), get_test_timelock_condition(1, 1).try_into().unwrap(), get_test_expiration_condition(bee_test::rand::address::rand_address().into(), 1, 1) .try_into() .unwrap(), ]) .with_features(vec![ get_test_sender_block(bee_test::rand::address::rand_address().into())
random
[ { "content": "/// Spawn a tokio task. The provided name will be used to configure the task if console tracing is enabled.\n\npub fn spawn_task<F>(name: &str, task: F) -> tokio::task::JoinHandle<F::Output>\n\nwhere\n\n F: 'static + Future + Send,\n\n F::Output: 'static + Send,\n\n{\n\n log::trace!(\"Spa...
Rust
route-rs-runtime/src/link/primitive/output_channel_link.rs
scgruber/route-rs
8c8cd4b3376c1c394960184b419b05acf32e30a8
use crate::link::{Link, LinkBuilder, PacketStream}; use futures::prelude::*; use futures::task::{Context, Poll}; use std::pin::Pin; #[derive(Default)] pub struct OutputChannelLink<Packet> { in_stream: Option<PacketStream<Packet>>, channel_sender: Option<crossbeam::Sender<Packet>>, } impl<Packet> OutputChannelLink<Packet> { pub fn new() -> Self { OutputChannelLink { in_stream: None, channel_sender: None, } } pub fn channel(self, channel_sender: crossbeam::Sender<Packet>) -> Self { OutputChannelLink { in_stream: self.in_stream, channel_sender: Some(channel_sender), } } } impl<Packet: Send + 'static> LinkBuilder<Packet, ()> for OutputChannelLink<Packet> { fn ingressors(self, mut in_streams: Vec<PacketStream<Packet>>) -> Self { assert_eq!( in_streams.len(), 1, "OutputChannelLink may only take 1 input stream" ); if self.in_stream.is_some() { panic!("OutputChannelLink may only take 1 input stream"); } OutputChannelLink { in_stream: Some(in_streams.remove(0)), channel_sender: self.channel_sender, } } fn ingressor(self, in_stream: PacketStream<Packet>) -> Self { if self.in_stream.is_some() { panic!("OutputChannelLink may only take 1 input stream"); } OutputChannelLink { in_stream: Some(in_stream), channel_sender: self.channel_sender, } } fn build_link(self) -> Link<()> { match (self.in_stream, self.channel_sender) { (None, _) => panic!("Cannot build link! Missing input streams"), (_, None) => panic!("Cannot build link! Missing channel"), (Some(in_stream), Some(sender)) => ( vec![Box::new(StreamToChannel { stream: in_stream, channel_sender: sender, })], vec![], ), } } } struct StreamToChannel<Packet> { stream: PacketStream<Packet>, channel_sender: crossbeam::Sender<Packet>, } impl<Packet> Future for StreamToChannel<Packet> { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { loop { if self.channel_sender.is_full() { cx.waker().clone().wake(); return Poll::Pending; } match ready!(Pin::new(&mut self.stream).poll_next(cx)) { Some(packet) => self .channel_sender .try_send(packet) .expect("OutputChannelLink::poll: try_send shouldn't fail"), None => return Poll::Ready(()), } } } } #[cfg(test)] mod tests { use super::*; use crate::utils::test::harness::{initialize_runtime, run_link}; use crate::utils::test::packet_generators::immediate_stream; use crossbeam::crossbeam_channel; use std::thread; #[test] #[should_panic] fn panics_when_built_without_ingressor() { let (s, _r) = crossbeam::unbounded(); OutputChannelLink::<()>::new().channel(s).build_link(); } #[test] #[should_panic] fn panics_when_built_without_channel() { let packet_generator = immediate_stream(vec![]); OutputChannelLink::<()>::new() .ingressor(packet_generator) .build_link(); } #[test] #[should_panic] fn panics_when_built_with_multiple_ingressors() { let (s, _r) = crossbeam::unbounded(); let packet_generator_1 = immediate_stream(vec![]); let packet_generator_2 = immediate_stream(vec![]); OutputChannelLink::<()>::new() .ingressors(vec![packet_generator_1, packet_generator_2]) .channel(s) .build_link(); } #[test] fn immediate_packets() { let mut runtime = initialize_runtime(); let packets = vec![0, 1, 2, 420, 1337, 3, 4, 5, 6, 7, 8, 9]; let results = runtime.block_on(async { let (send, recv) = crossbeam_channel::unbounded::<i32>(); let link = OutputChannelLink::new() .ingressor(immediate_stream(packets.clone())) .channel(send) .build_link(); let link_results = run_link(link).await; (link_results, recv) }); assert!(results.0.is_empty()); assert_eq!(results.1.iter().collect::<Vec<i32>>(), packets); } #[test] fn small_queue() { let packets = vec![0, 1, 2, 420, 1337, 3, 4, 5, 6, 7, 8, 9]; let mut runtime = initialize_runtime(); let results = runtime.block_on(async { let (send, recv) = crossbeam_channel::bounded::<i32>(2); let recv_thread = thread::spawn(move || { let mut outputs = vec![]; while let Ok(n) = recv.recv() { outputs.push(n); } outputs }); let link = OutputChannelLink::new() .ingressor(immediate_stream(packets.clone())) .channel(send) .build_link(); let link_results = run_link(link).await; let output_results = recv_thread.join().unwrap(); (link_results, output_results) }); assert!(results.0.is_empty()); assert_eq!(results.1, packets); } }
use crate::link::{Link, LinkBuilder, PacketStream}; use futures::prelude::*; use futures::task::{Context, Poll}; use std::pin::Pin; #[derive(Default)] pub struct OutputChannelLink<Packet> { in_stream: Option<PacketStream<Packet>>, channel_sender: Option<crossbeam::Sender<Packet>>, } impl<Packet> OutputChannelLink<Packet> { pub fn new() -> Self { OutputChannelLink { in_stream: None, channel_sender: None, } } pub fn channel(self, channel_sender: crossbeam::Sender<Packet>) -> Self { OutputChannelLink { in_stream: self.in_stream, channel_sender: Some(channel_sender), } } } impl<Packet: Send + 'static> LinkBuilder<Packet, ()> for OutputChannelLink<Packet> { fn ingressors(self, mut in_streams: Vec<PacketStream<Packet>>) -> Self { assert_eq!( in_streams.len(), 1, "OutputChannelLink may only take 1 input stream" ); if self.in_stream.is_some() { panic!("OutputChannelLink may only take 1 input stream"); } OutputChannelLink { in_stream: Some(in_streams.remove(0)), channel_sender: self.channel_sender, } } fn ingressor(self, in_stream: PacketStream<Packet>) -> Self { if self.in_stream.is_some() { panic!("OutputChannelLink may only take 1 input stream"); } OutputChannelLink { in_stream: Some(in_stream), channel_sender: self.channel_sender, } } fn build_link(self) -> Link<()> { match (self.in_stream, self.channel_sender) { (None, _) => panic!("Cannot build link! Missing input streams"), (_, None) => panic!("Cannot build link! Missing channel"), (Some(in_stream), Some(sender)) => ( vec![Box::new(StreamToChannel { stream: in_stream, channel_sender: sender, })], vec![], ), } } } struct StreamToChannel<Packet> { stream: PacketStream<Packet>, channel_sender: crossbeam::Sender<Packet>, } impl<Packet> Future for StreamToChannel<Packet> { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { loop { if self.channel_sender.is_full() { cx.waker().clone().wake(); return Poll::Pending; } match ready!(Pin::new(&mut self.stream).poll_next(cx)) { Some(packet) => self .channel_sender .try_send(packet) .expect("OutputChannelLink::poll: try_send shouldn't fail"), None => return Poll::Ready(()), } } } } #[cfg(test)] mod tests { use super::*; use crate::utils::test::harness::{initialize_runtime, run_link}; use crate::utils::test::packet_generators::immediate_stream; use crossbeam::crossbeam_channel; use std::thread; #[test] #[should_panic] fn panics_when_built_without_ingressor() { let (s, _r) = crossbeam::unbounded(); OutputChannelLink::<()>::new().channel(s).build_link(); } #[test] #[should_panic] fn panics_when_built_without_channel() { let packet_generator = immediate_stream(vec![]); OutputChannelLink::<()>::new() .ingressor(packet_generator) .build_link(); } #[test] #[should_panic] fn panics_when_built_with_multiple_ingressors() { let (s, _r) = crossbeam::unbounded(); let packet_generator_1 = immediate_stream(vec![]); let packet_generator_2 = immediate_stream(vec![]); OutputChannelLink::<()>::new() .ingressors(vec![packet_generator_1, packet_generator_2]) .channel(s) .build_link(); } #[test] fn immediate_packets() { let mut runtime = initialize_runtime(); let packets = vec![0, 1, 2, 420, 1337, 3, 4, 5, 6, 7, 8, 9]; let results = runtime.block_on(async { let (send, recv) = crossbeam_channel::unbounded::<i32>(); let link = OutputChannelLink::new() .ingressor(immediate_stream(packets.clone())) .channel(send) .build_link(); let link_results = run_link(link).await; (link_results, recv) }); assert!(results.0.is_empty()); assert_eq!(results.1.iter().collect::<Vec<i32>>(), packets); } #[test]
}
fn small_queue() { let packets = vec![0, 1, 2, 420, 1337, 3, 4, 5, 6, 7, 8, 9]; let mut runtime = initialize_runtime(); let results = runtime.block_on(async { let (send, recv) = crossbeam_channel::bounded::<i32>(2); let recv_thread = thread::spawn(move || { let mut outputs = vec![]; while let Ok(n) = recv.recv() { outputs.push(n); } outputs }); let link = OutputChannelLink::new() .ingressor(immediate_stream(packets.clone())) .channel(send) .build_link(); let link_results = run_link(link).await; let output_results = recv_thread.join().unwrap(); (link_results, output_results) }); assert!(results.0.is_empty()); assert_eq!(results.1, packets); }
function_block-full_function
[ { "content": "struct StreamFromChannel<Packet> {\n\n channel_receiver: crossbeam::Receiver<Packet>,\n\n}\n\n\n\nimpl<Packet> Unpin for StreamFromChannel<Packet> {}\n\n\n\nimpl<Packet> Stream for StreamFromChannel<Packet> {\n\n type Item = Packet;\n\n\n\n fn poll_next(self: Pin<&mut Self>, _cx: &mut Con...
Rust
libs/user-facing-errors/src/lib.rs
ever0de/prisma-engines
4c9d4edf238ad9c4a706eb5b7201ee0b4ebee93e
#![deny(warnings, rust_2018_idioms)] mod panic_hook; pub mod common; pub mod introspection_engine; pub mod migration_engine; #[cfg(feature = "sql")] pub mod quaint; pub mod query_engine; use serde::{Deserialize, Serialize}; use std::borrow::Cow; pub use panic_hook::set_panic_hook; pub trait UserFacingError: serde::Serialize { const ERROR_CODE: &'static str; fn message(&self) -> String; } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] pub struct KnownError { pub message: String, pub meta: serde_json::Value, pub error_code: Cow<'static, str>, } impl KnownError { pub fn new<T: UserFacingError>(inner: T) -> KnownError { KnownError { message: inner.message(), meta: serde_json::to_value(&inner).expect("Failed to render user facing error metadata to JSON"), error_code: Cow::from(T::ERROR_CODE), } } } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct UnknownError { pub message: String, pub backtrace: Option<String>, } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct Error { is_panic: bool, #[serde(flatten)] inner: ErrorType, } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] #[serde(untagged)] enum ErrorType { Known(KnownError), Unknown(UnknownError), } impl Error { pub fn as_known(&self) -> Option<&KnownError> { match &self.inner { ErrorType::Known(err) => Some(err), ErrorType::Unknown(_) => None, } } pub fn message(&self) -> &str { match &self.inner { ErrorType::Known(err) => &err.message, ErrorType::Unknown(err) => &err.message, } } pub fn new_non_panic_with_current_backtrace(message: String) -> Self { Error { inner: ErrorType::Unknown(UnknownError { message, backtrace: Some(format!("{:?}", backtrace::Backtrace::new())), }), is_panic: false, } } pub fn from_dyn_error(err: &dyn std::error::Error) -> Self { Error { inner: ErrorType::Unknown(UnknownError { message: err.to_string(), backtrace: None, }), is_panic: false, } } pub fn new_in_panic_hook(panic_info: &std::panic::PanicInfo<'_>) -> Self { let message = panic_info .payload() .downcast_ref::<&str>() .map(|s| -> String { (*s).to_owned() }) .or_else(|| panic_info.payload().downcast_ref::<String>().map(|s| s.to_owned())) .unwrap_or_else(|| "<unknown panic>".to_owned()); let backtrace = Some(format!("{:?}", backtrace::Backtrace::new())); let location = panic_info .location() .map(|loc| format!("{}", loc)) .unwrap_or_else(|| "<unknown location>".to_owned()); Error { inner: ErrorType::Unknown(UnknownError { message: format!("[{}] {}", location, message), backtrace, }), is_panic: true, } } pub fn new_known(err: KnownError) -> Self { Error { inner: ErrorType::Known(err), is_panic: false, } } pub fn from_panic_payload(panic_payload: Box<dyn std::any::Any + Send + 'static>) -> Self { let message = Self::extract_panic_message(panic_payload).unwrap_or_else(|| "<unknown panic>".to_owned()); Error { inner: ErrorType::Unknown(UnknownError { message, backtrace: None, }), is_panic: true, } } pub fn extract_panic_message(panic_payload: Box<dyn std::any::Any + Send + 'static>) -> Option<String> { panic_payload .downcast_ref::<&str>() .map(|s| -> String { (*s).to_owned() }) .or_else(|| panic_payload.downcast_ref::<String>().map(|s| s.to_owned())) } pub fn unwrap_known(self) -> KnownError { match self.inner { ErrorType::Known(err) => err, err @ ErrorType::Unknown(_) => panic!("Expected known error, got {:?}", err), } } } pub fn new_backtrace() -> backtrace::Backtrace { backtrace::Backtrace::new() } impl From<UnknownError> for Error { fn from(unknown_error: UnknownError) -> Self { Error { inner: ErrorType::Unknown(unknown_error), is_panic: false, } } } impl From<KnownError> for Error { fn from(known_error: KnownError) -> Self { Error { is_panic: false, inner: ErrorType::Known(known_error), } } }
#![deny(warnings, rust_2018_idioms)] mod panic_hook; pub mod common; pub mod introspection_engine; pub mod migration_engine; #[cfg(feature = "sql")] pub mod quaint; pub mod query_engine; use serde::{Deserialize, Serialize}; use std::borrow::Cow; pub use panic_hook::set_panic_hook; pub trait UserFacingError: serde::Serialize { const ERROR_CODE: &'static str; fn message(&self) -> String; } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] pub struct KnownError { pub message: String, pub meta: serde_json::Value, pub error_code: Cow<'static, str>, } impl KnownError { pub fn new<T: UserFacingError>(inner: T) -> KnownError { KnownError { message: inner.message(), meta: serde_json::to_value(&inner).expect("Failed to render user facing error metadata to JSON"), error_code: Cow::from(T::ERROR_CODE), } } } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct UnknownError { pub message: String, pub backtrace: Option<String>, } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct Error { is_panic: bool, #[serde(flatten)] inner: ErrorType, } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] #[serde(untagged)] enum ErrorType { Known(KnownError), Unknown(UnknownError), } impl Error { pub fn as_known(&self) -> Option<&KnownError> { match &self.inner { ErrorType::Known(err) => Some(err), ErrorType::Unknown(_) => None, } } pub fn message(&self) -> &str { match &self.inner { ErrorType::Known(err) => &err.message, ErrorType::Unknown(err) => &err.message, } }
pub fn from_dyn_error(err: &dyn std::error::Error) -> Self { Error { inner: ErrorType::Unknown(UnknownError { message: err.to_string(), backtrace: None, }), is_panic: false, } } pub fn new_in_panic_hook(panic_info: &std::panic::PanicInfo<'_>) -> Self { let message = panic_info .payload() .downcast_ref::<&str>() .map(|s| -> String { (*s).to_owned() }) .or_else(|| panic_info.payload().downcast_ref::<String>().map(|s| s.to_owned())) .unwrap_or_else(|| "<unknown panic>".to_owned()); let backtrace = Some(format!("{:?}", backtrace::Backtrace::new())); let location = panic_info .location() .map(|loc| format!("{}", loc)) .unwrap_or_else(|| "<unknown location>".to_owned()); Error { inner: ErrorType::Unknown(UnknownError { message: format!("[{}] {}", location, message), backtrace, }), is_panic: true, } } pub fn new_known(err: KnownError) -> Self { Error { inner: ErrorType::Known(err), is_panic: false, } } pub fn from_panic_payload(panic_payload: Box<dyn std::any::Any + Send + 'static>) -> Self { let message = Self::extract_panic_message(panic_payload).unwrap_or_else(|| "<unknown panic>".to_owned()); Error { inner: ErrorType::Unknown(UnknownError { message, backtrace: None, }), is_panic: true, } } pub fn extract_panic_message(panic_payload: Box<dyn std::any::Any + Send + 'static>) -> Option<String> { panic_payload .downcast_ref::<&str>() .map(|s| -> String { (*s).to_owned() }) .or_else(|| panic_payload.downcast_ref::<String>().map(|s| s.to_owned())) } pub fn unwrap_known(self) -> KnownError { match self.inner { ErrorType::Known(err) => err, err @ ErrorType::Unknown(_) => panic!("Expected known error, got {:?}", err), } } } pub fn new_backtrace() -> backtrace::Backtrace { backtrace::Backtrace::new() } impl From<UnknownError> for Error { fn from(unknown_error: UnknownError) -> Self { Error { inner: ErrorType::Unknown(unknown_error), is_panic: false, } } } impl From<KnownError> for Error { fn from(known_error: KnownError) -> Self { Error { is_panic: false, inner: ErrorType::Known(known_error), } } }
pub fn new_non_panic_with_current_backtrace(message: String) -> Self { Error { inner: ErrorType::Unknown(UnknownError { message, backtrace: Some(format!("{:?}", backtrace::Backtrace::new())), }), is_panic: false, } }
function_block-full_function
[]
Rust
vm/src/atomic_ref.rs
jazz-lang/JazzLight
a0df2f6c19efdc1b640d40d4f5680900bee59dea
#![allow(unsafe_code)] #![deny(missing_docs)] use std::cell::UnsafeCell; use std::cmp; use std::fmt; use std::fmt::Debug; use std::ops::{Deref, DerefMut}; use std::sync::atomic; use std::sync::atomic::AtomicU32; pub struct AtomicRefCell<T: ?Sized> { borrow: AtomicU32, value: UnsafeCell<T>, } impl<T> AtomicRefCell<T> { #[inline] pub fn new(value: T) -> AtomicRefCell<T> { AtomicRefCell { borrow: AtomicU32::new(0), value: UnsafeCell::new(value), } } #[inline] pub fn into_inner(self) -> T { debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0); self.value.into_inner() } } impl<T: ?Sized> AtomicRefCell<T> { #[inline] pub fn borrow(&self) -> AtomicRef<T> { AtomicRef { value: unsafe { &*self.value.get() }, borrow: AtomicBorrowRef::new(&self.borrow), } } #[inline] pub fn borrow_mut(&self) -> AtomicRefMut<T> { AtomicRefMut { value: unsafe { &mut *self.value.get() }, borrow: AtomicBorrowRefMut::new(&self.borrow), } } #[inline] pub fn as_ptr(&self) -> *mut T { self.value.get() } #[inline] pub fn get_mut(&mut self) -> &mut T { debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0); unsafe { &mut *self.value.get() } } } const HIGH_BIT: u32 = !(::std::u32::MAX >> 1); const MAX_FAILED_BORROWS: u32 = HIGH_BIT + (HIGH_BIT >> 1); struct AtomicBorrowRef<'b> { borrow: &'b AtomicU32, } impl<'b> AtomicBorrowRef<'b> { #[inline] fn new(borrow: &'b AtomicU32) -> Self { let new = borrow.fetch_add(1, atomic::Ordering::Acquire) + 1; if new & HIGH_BIT != 0 { Self::do_panic(borrow, new); } AtomicBorrowRef { borrow: borrow } } #[cold] #[inline(never)] fn do_panic(borrow: &'b AtomicU32, new: u32) { if new == HIGH_BIT { borrow.fetch_sub(1, atomic::Ordering::Release); panic!("too many immutable borrows"); } else if new >= MAX_FAILED_BORROWS { println!("Too many failed borrows"); ::std::process::exit(1); } else { panic!("already mutably borrowed"); } } } impl<'b> Drop for AtomicBorrowRef<'b> { #[inline] fn drop(&mut self) { let old = self.borrow.fetch_sub(1, atomic::Ordering::Release); debug_assert!(old & HIGH_BIT == 0); } } struct AtomicBorrowRefMut<'b> { borrow: &'b AtomicU32, } impl<'b> Drop for AtomicBorrowRefMut<'b> { #[inline] fn drop(&mut self) { self.borrow.store(0, atomic::Ordering::Release); } } impl<'b> AtomicBorrowRefMut<'b> { #[inline] fn new(borrow: &'b AtomicU32) -> AtomicBorrowRefMut<'b> { let old = match borrow.compare_exchange( 0, HIGH_BIT, atomic::Ordering::Acquire, atomic::Ordering::Relaxed, ) { Ok(x) => x, Err(x) => x, }; assert!( old == 0, "already {} borrowed", if old & HIGH_BIT == 0 { "immutably" } else { "mutably" } ); AtomicBorrowRefMut { borrow: borrow } } } unsafe impl<T: ?Sized + Send + Sync> Send for AtomicRefCell<T> {} unsafe impl<T: ?Sized + Send + Sync> Sync for AtomicRefCell<T> {} impl<T: Clone> Clone for AtomicRefCell<T> { #[inline] fn clone(&self) -> AtomicRefCell<T> { AtomicRefCell::new(self.borrow().clone()) } } impl<T: Default> Default for AtomicRefCell<T> { #[inline] fn default() -> AtomicRefCell<T> { AtomicRefCell::new(Default::default()) } } impl<T: ?Sized + PartialEq> PartialEq for AtomicRefCell<T> { #[inline] fn eq(&self, other: &AtomicRefCell<T>) -> bool { *self.borrow() == *other.borrow() } } impl<T: ?Sized + Eq> Eq for AtomicRefCell<T> {} impl<T: ?Sized + PartialOrd> PartialOrd for AtomicRefCell<T> { #[inline] fn partial_cmp(&self, other: &AtomicRefCell<T>) -> Option<cmp::Ordering> { self.borrow().partial_cmp(&*other.borrow()) } } impl<T: ?Sized + Ord> Ord for AtomicRefCell<T> { #[inline] fn cmp(&self, other: &AtomicRefCell<T>) -> cmp::Ordering { self.borrow().cmp(&*other.borrow()) } } impl<T> From<T> for AtomicRefCell<T> { fn from(t: T) -> AtomicRefCell<T> { AtomicRefCell::new(t) } } impl<'b> Clone for AtomicBorrowRef<'b> { #[inline] fn clone(&self) -> AtomicBorrowRef<'b> { AtomicBorrowRef::new(self.borrow) } } pub struct AtomicRef<'b, T: ?Sized + 'b> { value: &'b T, borrow: AtomicBorrowRef<'b>, } impl<'b, T: ?Sized> Deref for AtomicRef<'b, T> { type Target = T; #[inline] fn deref(&self) -> &T { self.value } } impl<'b, T: ?Sized> AtomicRef<'b, T> { #[inline] pub fn clone(orig: &AtomicRef<'b, T>) -> AtomicRef<'b, T> { AtomicRef { value: orig.value, borrow: orig.borrow.clone(), } } #[inline] pub fn map<U: ?Sized, F>(orig: AtomicRef<'b, T>, f: F) -> AtomicRef<'b, U> where F: FnOnce(&T) -> &U, { AtomicRef { value: f(orig.value), borrow: orig.borrow, } } } impl<'b, T: ?Sized> AtomicRefMut<'b, T> { #[inline] pub fn map<U: ?Sized, F>(orig: AtomicRefMut<'b, T>, f: F) -> AtomicRefMut<'b, U> where F: FnOnce(&mut T) -> &mut U, { AtomicRefMut { value: f(orig.value), borrow: orig.borrow, } } } pub struct AtomicRefMut<'b, T: ?Sized + 'b> { value: &'b mut T, borrow: AtomicBorrowRefMut<'b>, } impl<'b, T: ?Sized> Deref for AtomicRefMut<'b, T> { type Target = T; #[inline] fn deref(&self) -> &T { self.value } } impl<'b, T: ?Sized> DerefMut for AtomicRefMut<'b, T> { #[inline] fn deref_mut(&mut self) -> &mut T { self.value } } impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRef<'b, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.value.fmt(f) } } impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRefMut<'b, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.value.fmt(f) } } impl<T: ?Sized + Debug> Debug for AtomicRefCell<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "AtomicRefCell {{ ... }}") } }
#![allow(unsafe_code)] #![deny(missing_docs)] use std::cell::UnsafeCell; use std::cmp; use std::fmt; use std::fmt::Debug; use std::ops::{Deref, DerefMut}; use std::sync::atomic; use std::sync::atomic::AtomicU32; pub struct AtomicRefCell<T: ?Sized> { borrow: AtomicU32, value: UnsafeCell<T>, } impl<T> AtomicRefCell<T> { #[inline] pub fn new(value: T) -> AtomicRefCell<T> { AtomicRefCell { borrow: AtomicU32::new(0), value: UnsafeCell::new(value), } } #[inline] pub fn into_inner(self) -> T { debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0); self.value.into_inner() } } impl<T: ?Sized> AtomicRefCell<T> { #[inline] pub fn borrow(&self) -> AtomicRef<T> { AtomicRef { value: unsafe { &*self.value.get() }, borrow: AtomicBorrowRef::new(&self.borrow), } } #[inline]
#[inline] pub fn as_ptr(&self) -> *mut T { self.value.get() } #[inline] pub fn get_mut(&mut self) -> &mut T { debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0); unsafe { &mut *self.value.get() } } } const HIGH_BIT: u32 = !(::std::u32::MAX >> 1); const MAX_FAILED_BORROWS: u32 = HIGH_BIT + (HIGH_BIT >> 1); struct AtomicBorrowRef<'b> { borrow: &'b AtomicU32, } impl<'b> AtomicBorrowRef<'b> { #[inline] fn new(borrow: &'b AtomicU32) -> Self { let new = borrow.fetch_add(1, atomic::Ordering::Acquire) + 1; if new & HIGH_BIT != 0 { Self::do_panic(borrow, new); } AtomicBorrowRef { borrow: borrow } } #[cold] #[inline(never)] fn do_panic(borrow: &'b AtomicU32, new: u32) { if new == HIGH_BIT { borrow.fetch_sub(1, atomic::Ordering::Release); panic!("too many immutable borrows"); } else if new >= MAX_FAILED_BORROWS { println!("Too many failed borrows"); ::std::process::exit(1); } else { panic!("already mutably borrowed"); } } } impl<'b> Drop for AtomicBorrowRef<'b> { #[inline] fn drop(&mut self) { let old = self.borrow.fetch_sub(1, atomic::Ordering::Release); debug_assert!(old & HIGH_BIT == 0); } } struct AtomicBorrowRefMut<'b> { borrow: &'b AtomicU32, } impl<'b> Drop for AtomicBorrowRefMut<'b> { #[inline] fn drop(&mut self) { self.borrow.store(0, atomic::Ordering::Release); } } impl<'b> AtomicBorrowRefMut<'b> { #[inline] fn new(borrow: &'b AtomicU32) -> AtomicBorrowRefMut<'b> { let old = match borrow.compare_exchange( 0, HIGH_BIT, atomic::Ordering::Acquire, atomic::Ordering::Relaxed, ) { Ok(x) => x, Err(x) => x, }; assert!( old == 0, "already {} borrowed", if old & HIGH_BIT == 0 { "immutably" } else { "mutably" } ); AtomicBorrowRefMut { borrow: borrow } } } unsafe impl<T: ?Sized + Send + Sync> Send for AtomicRefCell<T> {} unsafe impl<T: ?Sized + Send + Sync> Sync for AtomicRefCell<T> {} impl<T: Clone> Clone for AtomicRefCell<T> { #[inline] fn clone(&self) -> AtomicRefCell<T> { AtomicRefCell::new(self.borrow().clone()) } } impl<T: Default> Default for AtomicRefCell<T> { #[inline] fn default() -> AtomicRefCell<T> { AtomicRefCell::new(Default::default()) } } impl<T: ?Sized + PartialEq> PartialEq for AtomicRefCell<T> { #[inline] fn eq(&self, other: &AtomicRefCell<T>) -> bool { *self.borrow() == *other.borrow() } } impl<T: ?Sized + Eq> Eq for AtomicRefCell<T> {} impl<T: ?Sized + PartialOrd> PartialOrd for AtomicRefCell<T> { #[inline] fn partial_cmp(&self, other: &AtomicRefCell<T>) -> Option<cmp::Ordering> { self.borrow().partial_cmp(&*other.borrow()) } } impl<T: ?Sized + Ord> Ord for AtomicRefCell<T> { #[inline] fn cmp(&self, other: &AtomicRefCell<T>) -> cmp::Ordering { self.borrow().cmp(&*other.borrow()) } } impl<T> From<T> for AtomicRefCell<T> { fn from(t: T) -> AtomicRefCell<T> { AtomicRefCell::new(t) } } impl<'b> Clone for AtomicBorrowRef<'b> { #[inline] fn clone(&self) -> AtomicBorrowRef<'b> { AtomicBorrowRef::new(self.borrow) } } pub struct AtomicRef<'b, T: ?Sized + 'b> { value: &'b T, borrow: AtomicBorrowRef<'b>, } impl<'b, T: ?Sized> Deref for AtomicRef<'b, T> { type Target = T; #[inline] fn deref(&self) -> &T { self.value } } impl<'b, T: ?Sized> AtomicRef<'b, T> { #[inline] pub fn clone(orig: &AtomicRef<'b, T>) -> AtomicRef<'b, T> { AtomicRef { value: orig.value, borrow: orig.borrow.clone(), } } #[inline] pub fn map<U: ?Sized, F>(orig: AtomicRef<'b, T>, f: F) -> AtomicRef<'b, U> where F: FnOnce(&T) -> &U, { AtomicRef { value: f(orig.value), borrow: orig.borrow, } } } impl<'b, T: ?Sized> AtomicRefMut<'b, T> { #[inline] pub fn map<U: ?Sized, F>(orig: AtomicRefMut<'b, T>, f: F) -> AtomicRefMut<'b, U> where F: FnOnce(&mut T) -> &mut U, { AtomicRefMut { value: f(orig.value), borrow: orig.borrow, } } } pub struct AtomicRefMut<'b, T: ?Sized + 'b> { value: &'b mut T, borrow: AtomicBorrowRefMut<'b>, } impl<'b, T: ?Sized> Deref for AtomicRefMut<'b, T> { type Target = T; #[inline] fn deref(&self) -> &T { self.value } } impl<'b, T: ?Sized> DerefMut for AtomicRefMut<'b, T> { #[inline] fn deref_mut(&mut self) -> &mut T { self.value } } impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRef<'b, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.value.fmt(f) } } impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRefMut<'b, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.value.fmt(f) } } impl<T: ?Sized + Debug> Debug for AtomicRefCell<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "AtomicRefCell {{ ... }}") } }
pub fn borrow_mut(&self) -> AtomicRefMut<T> { AtomicRefMut { value: unsafe { &mut *self.value.get() }, borrow: AtomicBorrowRefMut::new(&self.borrow), } }
function_block-full_function
[ { "content": "pub fn new_native_fn(x: fn(&[Value]) -> Result<Value, Value>, argc: i32) -> Value {\n\n Value::Function(Ref(Function {\n\n native: true,\n\n address: x as usize,\n\n env: Value::Null,\n\n module: None,\n\n argc,\n\n }))\n\n}\n\n\n", "file_path": "vm/src...
Rust
dao-contracts/tests/test_kyc_voter.rs
make-software/dao-contracts
aba3ed15d4c52ad411e6cd320f7daf1ef85715ac
use casper_dao_contracts::{ DaoOwnedNftContractTest, KycVoterContractTest, ReputationContractTest, VariableRepositoryContractTest, }; use casper_dao_utils::{Address, TestContract, TestEnv}; use casper_types::U256; use speculate::speculate; speculate! { use casper_types::U256; use casper_dao_utils::Error; use std::time::Duration; use casper_dao_contracts::voting::VotingId; use casper_dao_contracts::voting::Choice; before { #[allow(unused_variables, unused_mut)] let ( applicant, another_applicant, voter, second_voter, mint_amount, vote_amount, document_hash, mut kyc_token, mut reputation_token, mut variable_repo, mut contract, mut env ) = setup(); } describe "voting" { test "kyc_token_address_is_set" { assert_eq!( contract.get_kyc_token_address(), kyc_token.address() ) } context "applicant_is_not_kyced" { before { assert_eq!(kyc_token.balance_of(applicant), U256::zero()); } test "voting_creation_succeeds" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Ok(()) ); } context "voting_is_created" { before { contract.as_account(voter).create_voting(applicant, document_hash, vote_amount).unwrap(); } test "cannot_create_next_voting_for_the_same_applicant" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Err(Error::KycAlreadyInProgress) ); } test "can_create_next_voting_for_a_different_applicant" { assert_eq!( contract.as_account(voter).create_voting(another_applicant, document_hash, vote_amount), Ok(()) ); } context "informal_voting_passed" { before { let voting_id = 0.into(); let voting = contract.get_voting(voting_id).unwrap(); env.advance_block_time_by(Duration::from_secs(voting.informal_voting_time() + 1)); contract.as_account(voter).finish_voting(voting_id).unwrap(); #[allow(unused_variables)] let voting_id: VotingId = 1.into(); } test "cannot_create_next_voting_for_the_same_applicant" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Err(Error::KycAlreadyInProgress) ); } context "passed" { before { contract.as_account(second_voter).vote(voting_id, Choice::InFavor, vote_amount).unwrap(); env.advance_block_time_by(Duration::from_secs(voting.formal_voting_time() + 1)); contract.as_account(voter).finish_voting(voting_id).unwrap(); } test "applicant_owns_kyc_token" { assert_eq!( kyc_token.balance_of(applicant), U256::one() ); } } context "rejected" { before { contract.as_account(second_voter).vote(voting_id, Choice::Against, vote_amount + U256::one()).unwrap(); env.advance_block_time_by(Duration::from_secs(voting.formal_voting_time() + 1)); contract.as_account(voter).finish_voting(voting_id).unwrap(); } test "next_voting_creation_for_the_same_applicant_succeeds" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Ok(()) ); } test "applicant_does_not_own_kyc_token" { assert_eq!( kyc_token.balance_of(applicant), U256::zero() ); } } } } } context "applicant_is_kyced" { before { kyc_token.mint(applicant, 1.into()).unwrap(); } test "voting_cannot_be_created" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Err(Error::UserKycedAlready) ); } } } } fn setup() -> ( Address, Address, Address, Address, U256, U256, U256, DaoOwnedNftContractTest, ReputationContractTest, VariableRepositoryContractTest, KycVoterContractTest, TestEnv, ) { let env = TestEnv::new(); let mut kyc_token = DaoOwnedNftContractTest::new( &env, "kyc token".to_string(), "kyt".to_string(), "".to_string(), ); let mut reputation_token = ReputationContractTest::new(&env); let mut variable_repo = VariableRepositoryContractTest::new(&env); let onboarding_voter = KycVoterContractTest::new( &env, variable_repo.address(), reputation_token.address(), kyc_token.address(), ); variable_repo .change_ownership(onboarding_voter.address()) .unwrap(); reputation_token .change_ownership(onboarding_voter.address()) .unwrap(); kyc_token .change_ownership(onboarding_voter.address()) .unwrap(); let applicant = env.get_account(1); let another_applicant = env.get_account(2); let voter = env.get_account(3); let second_voter = env.get_account(4); let mint_amount = 10_000.into(); let vote_amount = 1_000.into(); reputation_token.mint(voter, mint_amount).unwrap(); reputation_token.mint(second_voter, mint_amount).unwrap(); let document_hash = 1234.into(); ( applicant, another_applicant, voter, second_voter, mint_amount, vote_amount, document_hash, kyc_token, reputation_token, variable_repo, onboarding_voter, env, ) }
use casper_dao_contracts::{ DaoOwnedNftContractTest, KycVoterContractTest, ReputationContractTest, VariableRepositoryContractTest, }; use casper_dao_utils::{Addre
get_kyc_token_address(), kyc_token.address() ) } context "applicant_is_not_kyced" { before { assert_eq!(kyc_token.balance_of(applicant), U256::zero()); } test "voting_creation_succeeds" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Ok(()) ); } context "voting_is_created" { before { contract.as_account(voter).create_voting(applicant, document_hash, vote_amount).unwrap(); } test "cannot_create_next_voting_for_the_same_applicant" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Err(Error::KycAlreadyInProgress) ); } test "can_create_next_voting_for_a_different_applicant" { assert_eq!( contract.as_account(voter).create_voting(another_applicant, document_hash, vote_amount), Ok(()) ); } context "informal_voting_passed" { before { let voting_id = 0.into(); let voting = contract.get_voting(voting_id).unwrap(); env.advance_block_time_by(Duration::from_secs(voting.informal_voting_time() + 1)); contract.as_account(voter).finish_voting(voting_id).unwrap(); #[allow(unused_variables)] let voting_id: VotingId = 1.into(); } test "cannot_create_next_voting_for_the_same_applicant" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Err(Error::KycAlreadyInProgress) ); } context "passed" { before { contract.as_account(second_voter).vote(voting_id, Choice::InFavor, vote_amount).unwrap(); env.advance_block_time_by(Duration::from_secs(voting.formal_voting_time() + 1)); contract.as_account(voter).finish_voting(voting_id).unwrap(); } test "applicant_owns_kyc_token" { assert_eq!( kyc_token.balance_of(applicant), U256::one() ); } } context "rejected" { before { contract.as_account(second_voter).vote(voting_id, Choice::Against, vote_amount + U256::one()).unwrap(); env.advance_block_time_by(Duration::from_secs(voting.formal_voting_time() + 1)); contract.as_account(voter).finish_voting(voting_id).unwrap(); } test "next_voting_creation_for_the_same_applicant_succeeds" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Ok(()) ); } test "applicant_does_not_own_kyc_token" { assert_eq!( kyc_token.balance_of(applicant), U256::zero() ); } } } } } context "applicant_is_kyced" { before { kyc_token.mint(applicant, 1.into()).unwrap(); } test "voting_cannot_be_created" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Err(Error::UserKycedAlready) ); } } } } fn setup() -> ( Address, Address, Address, Address, U256, U256, U256, DaoOwnedNftContractTest, ReputationContractTest, VariableRepositoryContractTest, KycVoterContractTest, TestEnv, ) { let env = TestEnv::new(); let mut kyc_token = DaoOwnedNftContractTest::new( &env, "kyc token".to_string(), "kyt".to_string(), "".to_string(), ); let mut reputation_token = ReputationContractTest::new(&env); let mut variable_repo = VariableRepositoryContractTest::new(&env); let onboarding_voter = KycVoterContractTest::new( &env, variable_repo.address(), reputation_token.address(), kyc_token.address(), ); variable_repo .change_ownership(onboarding_voter.address()) .unwrap(); reputation_token .change_ownership(onboarding_voter.address()) .unwrap(); kyc_token .change_ownership(onboarding_voter.address()) .unwrap(); let applicant = env.get_account(1); let another_applicant = env.get_account(2); let voter = env.get_account(3); let second_voter = env.get_account(4); let mint_amount = 10_000.into(); let vote_amount = 1_000.into(); reputation_token.mint(voter, mint_amount).unwrap(); reputation_token.mint(second_voter, mint_amount).unwrap(); let document_hash = 1234.into(); ( applicant, another_applicant, voter, second_voter, mint_amount, vote_amount, document_hash, kyc_token, reputation_token, variable_repo, onboarding_voter, env, ) }
ss, TestContract, TestEnv}; use casper_types::U256; use speculate::speculate; speculate! { use casper_types::U256; use casper_dao_utils::Error; use std::time::Duration; use casper_dao_contracts::voting::VotingId; use casper_dao_contracts::voting::Choice; before { #[allow(unused_variables, unused_mut)] let ( applicant, another_applicant, voter, second_voter, mint_amount, vote_amount, document_hash, mut kyc_token, mut reputation_token, mut variable_repo, mut contract, mut env ) = setup(); } describe "voting" { test "kyc_token_address_is_set" { assert_eq!( contract.
random
[ { "content": "fn setup() -> (TestEnv, ReputationContractTest) {\n\n let env = TestEnv::new();\n\n let contract = ReputationContractTest::new(&env);\n\n\n\n (env, contract)\n\n}\n\n\n", "file_path": "dao-contracts/tests/test_reputation.rs", "rank": 0, "score": 26852.55778664241 }, { ...
Rust
rusoto/credential/src/container.rs
svenwb/rusoto
e7a7f7c123266d82ff5a97b757d328523ff8a3e2
use std::time::Duration; use async_trait::async_trait; use hyper::{Body, Request}; use crate::request::HttpClient; use crate::{ non_empty_env_var, parse_credentials_from_aws_service, AwsCredentials, CredentialsError, ProvideAwsCredentials, }; const AWS_CREDENTIALS_PROVIDER_IP: &str = "169.254.170.2"; const AWS_CONTAINER_CREDENTIALS_RELATIVE_URI: &str = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; const AWS_CONTAINER_CREDENTIALS_FULL_URI: &str = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; const AWS_CONTAINER_AUTHORIZATION_TOKEN: &str = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; #[derive(Clone, Debug)] pub struct ContainerProvider { client: HttpClient, timeout: Duration, } impl ContainerProvider { pub fn new() -> Self { ContainerProvider { client: HttpClient::new(), timeout: Duration::from_secs(30), } } pub fn set_timeout(&mut self, timeout: Duration) { self.timeout = timeout; } } impl Default for ContainerProvider { fn default() -> Self { Self::new() } } #[async_trait] impl ProvideAwsCredentials for ContainerProvider { async fn credentials(&self) -> Result<AwsCredentials, CredentialsError> { let req = request_from_env_vars().map_err(|err| CredentialsError { message: format!( "Could not get request from environment: {}", err.to_string() ), })?; let resp = self .client .request(req, self.timeout) .await .map_err(|err| CredentialsError { message: format!( "Could not get credentials from container: {}", err.to_string() ), })?; parse_credentials_from_aws_service(&resp) } } fn request_from_env_vars() -> Result<Request<Body>, CredentialsError> { let relative_uri = non_empty_env_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) .map(|path| format!("http://{}{}", AWS_CREDENTIALS_PROVIDER_IP, path)); match relative_uri { Some(ref uri) => new_request(uri, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI), None => match non_empty_env_var(AWS_CONTAINER_CREDENTIALS_FULL_URI) { Some(ref uri) => { let mut request = new_request(uri, AWS_CONTAINER_CREDENTIALS_FULL_URI)?; if let Some(token) = non_empty_env_var(AWS_CONTAINER_AUTHORIZATION_TOKEN) { match token.parse() { Ok(parsed_token) => { request.headers_mut().insert("authorization", parsed_token); } Err(err) => { return Err(CredentialsError::new(format!( "failed to parse token: {}", err ))); } } } Ok(request) } None => Err(CredentialsError::new(format!( "Neither environment variable '{}' nor '{}' is set", AWS_CONTAINER_CREDENTIALS_FULL_URI, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI ))), }, } } fn new_request(uri: &str, env_var_name: &str) -> Result<Request<Body>, CredentialsError> { Request::get(uri).body(Body::empty()).map_err(|error| { CredentialsError::new(format!( "Error while parsing URI '{}' derived from environment variable '{}': {}", uri, env_var_name, error )) }) } #[cfg(test)] mod tests { use super::*; use crate::test_utils::lock_env; use std::env; #[test] fn request_from_relative_uri() { let path = "/xxx"; let _guard = lock_env(); env::set_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, path); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, "dummy"); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, "dummy"); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().path(), path); assert_eq!(request.headers().contains_key("authorization"), false); } #[test] fn error_from_missing_env_vars() { let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); let result = request_from_env_vars(); assert!(result.is_err()); } #[test] fn error_from_empty_env_vars() { let _guard = lock_env(); env::set_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, ""); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, ""); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, ""); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_err()); } #[test] fn request_from_full_uri_with_token() { let url = "http://localhost/xxx"; let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, url); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, "dummy"); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().to_string(), url); assert_eq!(request.headers().contains_key("authorization"), true); } #[test] fn request_from_full_uri_without_token() { let url = "http://localhost/xxx"; let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, url); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().to_string(), url); assert_eq!(request.headers().contains_key("authorization"), false); } #[test] fn request_from_full_uri_with_empty_token() { let url = "http://localhost/xxx"; let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, url); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, ""); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().to_string(), url); assert_eq!(request.headers().contains_key("authorization"), false); } }
use std::time::Duration; use async_trait::async_trait; use hyper::{Body, Request}; use crate::request::HttpClient; use crate::{ non_empty_env_var, parse_credentials_from_aws_service, AwsCredentials, CredentialsError, ProvideAwsCredentials, }; const AWS_CREDENTIALS_PROVIDER_IP: &str = "169.254.170.2"; const AWS_CONTAINER_CREDENTIALS_RELATIVE_URI: &str = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; const AWS_CONTAINER_CREDENTIALS_FULL_URI: &str = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; const AWS_CONTAINER_AUTHORIZATION_TOKEN: &str = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; #[derive(Clone, Debug)] pub struct ContainerProvider { client: HttpClient, timeout: Duration, } impl ContainerProvider { pub fn new() -> Self { ContainerProvider { client: HttpClient::new(), timeout: Duration::from_secs(30), } } pub fn set_timeout(&mut self, timeout: Duration) { self.timeout = timeout; } } impl Default for ContainerProvider { fn default() -> Self { Self::new() } } #[async_trait] impl ProvideAwsCredentials for ContainerProvider { async fn credentials(&self) -> Result<AwsCredentials, CredentialsError> { let req = request_from_env_vars().map_err(|err| CredentialsError { message: format!( "Could not get request from environment: {}", err.to_string() ), })?; let resp = self .client .request(req, self.timeout) .await .map_err(|err| CredentialsError { message: format!( "Could not get credentials from container: {}", err.to_string() ), })?; parse_credentials_from_aws_service(&resp) } } fn request_from_env_vars() -> Result<Request<Body>, CredentialsError> { let relative_uri = non_empty_env_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) .map(|path| format!("http://{}{}", AWS_CREDENTIALS_PROVIDER_IP, path)); match relative_uri { Some(ref uri) => new_request(uri, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI), None => match non_empty_env_var(AWS_CONTAINER_CREDENTIALS_FULL_URI) { Some(ref uri) => { let mut request = new_request(uri, AWS_CONTAINER_CREDENTIALS_FULL_URI)?; if let Some(token) = non_empty_env_var(AWS_CONTAINER_AUTHORIZATION_TOKEN) { match token.pars
fn new_request(uri: &str, env_var_name: &str) -> Result<Request<Body>, CredentialsError> { Request::get(uri).body(Body::empty()).map_err(|error| { CredentialsError::new(format!( "Error while parsing URI '{}' derived from environment variable '{}': {}", uri, env_var_name, error )) }) } #[cfg(test)] mod tests { use super::*; use crate::test_utils::lock_env; use std::env; #[test] fn request_from_relative_uri() { let path = "/xxx"; let _guard = lock_env(); env::set_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, path); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, "dummy"); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, "dummy"); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().path(), path); assert_eq!(request.headers().contains_key("authorization"), false); } #[test] fn error_from_missing_env_vars() { let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); let result = request_from_env_vars(); assert!(result.is_err()); } #[test] fn error_from_empty_env_vars() { let _guard = lock_env(); env::set_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, ""); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, ""); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, ""); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_err()); } #[test] fn request_from_full_uri_with_token() { let url = "http://localhost/xxx"; let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, url); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, "dummy"); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().to_string(), url); assert_eq!(request.headers().contains_key("authorization"), true); } #[test] fn request_from_full_uri_without_token() { let url = "http://localhost/xxx"; let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, url); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().to_string(), url); assert_eq!(request.headers().contains_key("authorization"), false); } #[test] fn request_from_full_uri_with_empty_token() { let url = "http://localhost/xxx"; let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, url); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, ""); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().to_string(), url); assert_eq!(request.headers().contains_key("authorization"), false); } }
e() { Ok(parsed_token) => { request.headers_mut().insert("authorization", parsed_token); } Err(err) => { return Err(CredentialsError::new(format!( "failed to parse token: {}", err ))); } } } Ok(request) } None => Err(CredentialsError::new(format!( "Neither environment variable '{}' nor '{}' is set", AWS_CONTAINER_CREDENTIALS_FULL_URI, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI ))), }, } }
function_block-function_prefixed
[ { "content": "#[inline]\n\n#[doc(hidden)]\n\npub fn encode_uri_path(uri: &str) -> String {\n\n utf8_percent_encode(uri, &STRICT_PATH_ENCODE_SET).collect::<String>()\n\n}\n\n\n", "file_path": "rusoto/signature/src/signature.rs", "rank": 1, "score": 339822.9463685929 }, { "content": "#[inli...
Rust
prost-derive/src/lib.rs
Max-Meldrum/prost
6f3c60f136be096194a3c6e0e77e25a9e1356669
#![doc(html_root_url = "https://docs.rs/prost-derive/0.6.1")] #![recursion_limit = "4096"] extern crate proc_macro; use anyhow::bail; use quote::quote; use anyhow::Error; use itertools::Itertools; use proc_macro::TokenStream; use proc_macro2::Span; use syn::{ punctuated::Punctuated, Data, DataEnum, DataStruct, DeriveInput, Expr, Fields, FieldsNamed, FieldsUnnamed, Ident, Variant, }; mod field; use crate::field::Field; fn try_message(input: TokenStream) -> Result<TokenStream, Error> { let input: DeriveInput = syn::parse(input)?; let ident = input.ident; let variant_data = match input.data { Data::Struct(variant_data) => variant_data, Data::Enum(..) => bail!("Message can not be derived for an enum"), Data::Union(..) => bail!("Message can not be derived for a union"), }; if !input.generics.params.is_empty() || input.generics.where_clause.is_some() { bail!("Message may not be derived for generic type"); } let fields = match variant_data { DataStruct { fields: Fields::Named(FieldsNamed { named: fields, .. }), .. } | DataStruct { fields: Fields::Unnamed(FieldsUnnamed { unnamed: fields, .. }), .. } => fields.into_iter().collect(), DataStruct { fields: Fields::Unit, .. } => Vec::new(), }; let mut next_tag: u32 = 1; let mut fields = fields .into_iter() .enumerate() .flat_map(|(idx, field)| { let field_ident = field .ident .unwrap_or_else(|| Ident::new(&idx.to_string(), Span::call_site())); match Field::new(field.attrs, Some(next_tag)) { Ok(Some(field)) => { next_tag = field.tags().iter().max().map(|t| t + 1).unwrap_or(next_tag); Some(Ok((field_ident, field))) } Ok(None) => None, Err(err) => Some(Err( err.context(format!("invalid message field {}.{}", ident, field_ident)) )), } }) .collect::<Result<Vec<_>, _>>()?; let unsorted_fields = fields.clone(); fields.sort_by_key(|&(_, ref field)| field.tags().into_iter().min().unwrap()); let fields = fields; let mut tags = fields .iter() .flat_map(|&(_, ref field)| field.tags()) .collect::<Vec<_>>(); let num_tags = tags.len(); tags.sort(); tags.dedup(); if tags.len() != num_tags { bail!("message {} has fields with duplicate tags", ident); } let encoded_len = fields .iter() .map(|&(ref field_ident, ref field)| field.encoded_len(quote!(self.#field_ident))); let encode = fields .iter() .map(|&(ref field_ident, ref field)| field.encode(quote!(self.#field_ident))); let merge = fields.iter().map(|&(ref field_ident, ref field)| { let merge = field.merge(quote!(value)); let tags = field .tags() .into_iter() .map(|tag| quote!(#tag)) .intersperse(quote!(|)); quote! { #(#tags)* => { let mut value = &mut self.#field_ident; #merge.map_err(|mut error| { error.push(STRUCT_NAME, stringify!(#field_ident)); error }) }, } }); let struct_name = if fields.is_empty() { quote!() } else { quote!( const STRUCT_NAME: &'static str = stringify!(#ident); ) }; let is_struct = true; let clear = fields .iter() .map(|&(ref field_ident, ref field)| field.clear(quote!(self.#field_ident))); let default = fields.iter().map(|&(ref field_ident, ref field)| { let value = field.default(); quote!(#field_ident: #value,) }); let methods = fields .iter() .flat_map(|&(ref field_ident, ref field)| field.methods(field_ident)) .collect::<Vec<_>>(); let methods = if methods.is_empty() { quote!() } else { quote! { #[allow(dead_code)] impl #ident { #(#methods)* } } }; let debugs = unsorted_fields.iter().map(|&(ref field_ident, ref field)| { let wrapper = field.debug(quote!(self.#field_ident)); let call = if is_struct { quote!(builder.field(stringify!(#field_ident), &wrapper)) } else { quote!(builder.field(&wrapper)) }; quote! { let builder = { let wrapper = #wrapper; #call }; } }); let debug_builder = if is_struct { quote!(f.debug_struct(stringify!(#ident))) } else { quote!(f.debug_tuple(stringify!(#ident))) }; let expanded = quote! { impl ::prost::Message for #ident { #[allow(unused_variables)] fn encode_raw<B>(&self, buf: &mut B) where B: ::prost::bytes::BufMut { #(#encode)* } #[allow(unused_variables)] fn merge_field<B>( &mut self, tag: u32, wire_type: ::prost::encoding::WireType, buf: &mut B, ctx: ::prost::encoding::DecodeContext, ) -> ::std::result::Result<(), ::prost::DecodeError> where B: ::prost::bytes::Buf { #struct_name match tag { #(#merge)* _ => ::prost::encoding::skip_field(wire_type, tag, buf, ctx), } } #[inline] fn encoded_len(&self) -> usize { 0 #(+ #encoded_len)* } fn clear(&mut self) { #(#clear;)* } } impl Default for #ident { fn default() -> #ident { #ident { #(#default)* } } } impl ::std::fmt::Debug for #ident { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let mut builder = #debug_builder; #(#debugs;)* builder.finish() } } #methods }; Ok(expanded.into()) } #[proc_macro_derive(Message, attributes(prost))] pub fn message(input: TokenStream) -> TokenStream { try_message(input).unwrap() } fn try_enumeration(input: TokenStream) -> Result<TokenStream, Error> { let input: DeriveInput = syn::parse(input)?; let ident = input.ident; if !input.generics.params.is_empty() || input.generics.where_clause.is_some() { bail!("Message may not be derived for generic type"); } let punctuated_variants = match input.data { Data::Enum(DataEnum { variants, .. }) => variants, Data::Struct(_) => bail!("Enumeration can not be derived for a struct"), Data::Union(..) => bail!("Enumeration can not be derived for a union"), }; let mut variants: Vec<(Ident, Expr)> = Vec::new(); for Variant { ident, fields, discriminant, .. } in punctuated_variants { match fields { Fields::Unit => (), Fields::Named(_) | Fields::Unnamed(_) => { bail!("Enumeration variants may not have fields") } } match discriminant { Some((_, expr)) => variants.push((ident, expr)), None => bail!("Enumeration variants must have a disriminant"), } } if variants.is_empty() { panic!("Enumeration must have at least one variant"); } let default = variants[0].0.clone(); let is_valid = variants .iter() .map(|&(_, ref value)| quote!(#value => true)); let from = variants.iter().map( |&(ref variant, ref value)| quote!(#value => ::std::option::Option::Some(#ident::#variant)), ); let is_valid_doc = format!("Returns `true` if `value` is a variant of `{}`.", ident); let from_i32_doc = format!( "Converts an `i32` to a `{}`, or `None` if `value` is not a valid variant.", ident ); let expanded = quote! { impl #ident { #[doc=#is_valid_doc] pub fn is_valid(value: i32) -> bool { match value { #(#is_valid,)* _ => false, } } #[doc=#from_i32_doc] pub fn from_i32(value: i32) -> ::std::option::Option<#ident> { match value { #(#from,)* _ => ::std::option::Option::None, } } } impl ::std::default::Default for #ident { fn default() -> #ident { #ident::#default } } impl ::std::convert::From<#ident> for i32 { fn from(value: #ident) -> i32 { value as i32 } } }; Ok(expanded.into()) } #[proc_macro_derive(Enumeration, attributes(prost))] pub fn enumeration(input: TokenStream) -> TokenStream { try_enumeration(input).unwrap() } fn try_oneof(input: TokenStream) -> Result<TokenStream, Error> { let input: DeriveInput = syn::parse(input)?; let ident = input.ident; let variants = match input.data { Data::Enum(DataEnum { variants, .. }) => variants, Data::Struct(..) => bail!("Oneof can not be derived for a struct"), Data::Union(..) => bail!("Oneof can not be derived for a union"), }; if !input.generics.params.is_empty() || input.generics.where_clause.is_some() { bail!("Message may not be derived for generic type"); } let mut fields: Vec<(Ident, Field)> = Vec::new(); for Variant { attrs, ident: variant_ident, fields: variant_fields, .. } in variants { let variant_fields = match variant_fields { Fields::Unit => Punctuated::new(), Fields::Named(FieldsNamed { named: fields, .. }) | Fields::Unnamed(FieldsUnnamed { unnamed: fields, .. }) => fields, }; if variant_fields.len() != 1 { bail!("Oneof enum variants must have a single field"); } match Field::new_oneof(attrs)? { Some(field) => fields.push((variant_ident, field)), None => bail!("invalid oneof variant: oneof variants may not be ignored"), } } let mut tags = fields .iter() .flat_map(|&(ref variant_ident, ref field)| -> Result<u32, Error> { if field.tags().len() > 1 { bail!( "invalid oneof variant {}::{}: oneof variants may only have a single tag", ident, variant_ident ); } Ok(field.tags()[0]) }) .collect::<Vec<_>>(); tags.sort(); tags.dedup(); if tags.len() != fields.len() { panic!("invalid oneof {}: variants have duplicate tags", ident); } let encode = fields.iter().map(|&(ref variant_ident, ref field)| { let encode = field.encode(quote!(*value)); quote!(#ident::#variant_ident(ref value) => { #encode }) }); let merge = fields.iter().map(|&(ref variant_ident, ref field)| { let tag = field.tags()[0]; let merge = field.merge(quote!(value)); quote! { #tag => { match field { ::std::option::Option::Some(#ident::#variant_ident(ref mut value)) => { #merge }, _ => { let mut owned_value = ::std::default::Default::default(); let value = &mut owned_value; #merge.map(|_| *field = ::std::option::Option::Some(#ident::#variant_ident(owned_value))) }, } } } }); let encoded_len = fields.iter().map(|&(ref variant_ident, ref field)| { let encoded_len = field.encoded_len(quote!(*value)); quote!(#ident::#variant_ident(ref value) => #encoded_len) }); let debug = fields.iter().map(|&(ref variant_ident, ref field)| { let wrapper = field.debug(quote!(*value)); quote!(#ident::#variant_ident(ref value) => { let wrapper = #wrapper; f.debug_tuple(stringify!(#variant_ident)) .field(&wrapper) .finish() }) }); let expanded = quote! { impl #ident { pub fn encode<B>(&self, buf: &mut B) where B: ::prost::bytes::BufMut { match *self { #(#encode,)* } } pub fn merge<B>( field: &mut ::std::option::Option<#ident>, tag: u32, wire_type: ::prost::encoding::WireType, buf: &mut B, ctx: ::prost::encoding::DecodeContext, ) -> ::std::result::Result<(), ::prost::DecodeError> where B: ::prost::bytes::Buf { match tag { #(#merge,)* _ => unreachable!(concat!("invalid ", stringify!(#ident), " tag: {}"), tag), } } #[inline] pub fn encoded_len(&self) -> usize { match *self { #(#encoded_len,)* } } } impl ::std::fmt::Debug for #ident { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { #(#debug,)* } } } }; Ok(expanded.into()) } #[proc_macro_derive(Oneof, attributes(prost))] pub fn oneof(input: TokenStream) -> TokenStream { try_oneof(input).unwrap() }
#![doc(html_root_url = "https://docs.rs/prost-derive/0.6.1")] #![recursion_limit = "4096"] extern crate proc_macro; use anyhow::bail; use quote::quote; use anyhow::Error; use itertools::Itertools; use proc_macro::TokenStream; use proc_macro2::Span; use syn::{ punctuated::Punctuated, Data, DataEnum, DataStruct, DeriveInput, Expr, Fields, FieldsNamed, FieldsUnnamed, Ident, Variant, }; mod field; use crate::field::Field; fn try_message(input: TokenStream) -> Result<TokenStream, Error> { let input: DeriveInput = syn::parse(input)?; let ident = input.ident; let variant_data = match input.data { Data::Struct(variant_data) => variant_data, Data::Enum(..) => bail!("Message can not be derived for an enum"), Data::Union(..) => bail!("Message can not be derived for a union"), }; if !input.generics.params.is_empty() || input.generics.where_clause.is_some() { bail!("Message may not be derived for generic type"); } let fields = match variant_data { DataStruct { fields: Fields::Named(FieldsNamed { named: fields, .. }), .. } | DataStruct { fields: Fields::Unnamed(FieldsUnnamed { unnamed: fields, .. }), .. } => fields.into_iter().collect(), DataStruct { fields: Fields::Unit, .. } => Vec::new(), }; let mut next_tag: u32 = 1; let mut fields = fields .into_iter() .enumerate() .flat_map(|(idx, field)| { let field_ident = field .ident .unwrap_or_else(|| Ident::new(&idx.to_string(), Span::call_site())); match Field::new(field.attrs, Some(next_tag)) { Ok(Some(field)) => { next_tag = field.tags().iter().max().map(|t| t + 1).unwrap_or(next_tag); Some(Ok((field_ident, field))) } Ok(None) => None, Err(err) => Some(Err( err.context(format!("invalid message field {}.{}", ident, field_ident)) )), } }) .collect::<Result<Vec<_>, _>>()?; let unsorted_fields = fields.clone(); fields.sort_by_key(|&(_, ref field)| field.tags().into_iter().min().unwrap()); let fields = fields; let mut tags = fields .iter() .flat_map(|&(_, ref field)| field.tags()) .collect::<Vec<_>>(); let num_tags = tags.len(); tags.sort(); tags.dedup(); if tags.len() != num_tags { bail!("message {} has fields with duplicate tags", ident); } let encoded_len = fields .iter() .map(|&(ref field_ident, ref field)| field.encoded_len(quote!(self.#field_ident))); let encode = fields .iter() .map(|&(ref field_ident, ref field)| field.encode(quote!(self.#field_ident))); let merge = fields.iter().map(|&(ref field_ident, ref field)| { let merge = field.merge(quote!(value)); let tags = field .tags() .into_iter() .map(|tag| quote!(#tag)) .intersperse(quote!(|)); quote! { #(#tags)* => { let mut value = &mut self.#field_ident; #merge.map_err(|mut error| { error.push(STRUCT_NAME, stringify!(#field_ident)); error }) }, } }); let struct_name = if fields.is_empty() { quote!() } else { quote!( const STRUCT_NAME: &'static str = stringify!(#ident); ) }; let is_struct = true; let clear = fields .iter() .map(|&(ref field_ident, ref field)| field.clear(quote!(self.#field_ident))); let default = fields.iter().map(|&(ref field_ident, ref field)| { let value = field.default(); quote!(#field_ident: #value,) }); let methods = fields .iter() .flat_map(|&(ref field_ident, ref field)| field.methods(field_ident)) .collect::<Vec<_>>(); let methods = if methods.is_empty() { quote!() } else { quote! { #[allow(dead_code)] impl #ident { #(#methods)* } } }; let debugs = unsorted_fields.iter().map(|&(ref field_ident, ref field)| { let wrapper = field.debug(quote!(self.#field_ident)); let call = if is_struct { quote!(builder.field(stringify!(#field_ident), &wrapper)) } else { quote!(builder.field(&wrapper)) }; quote! { let builder = { let wrapper = #wrapper; #call }; } }); let debug_builder = if is_struct { quote!(f.debug_struct(stringify!(#ident))) } else { quote!(f.debug_tuple(stringify!(#ident))) }; let expanded = quote! { impl ::prost::Message for #ident { #[allow(unused_variables)] fn encode_raw<B>(&self, buf: &mut B) where B: ::prost::bytes::BufMut { #(#encode)* } #[allow(unused_variables)] fn merge_field<B>( &mut self, tag: u32, wire_type: ::prost::encoding::WireType, buf: &mut B, ctx: ::prost::encoding::DecodeContext, ) -> ::std::result::Result<(), ::prost::DecodeError> where B: ::prost::bytes::Buf { #struct_name match tag { #(#merge)* _ => ::prost::encoding::skip_field(wire_type, tag, buf, ctx), } } #[inline] fn encoded_len(&self) -> usize { 0 #(+ #encoded_len)* } fn clear(&mut self) { #(#clear;)* } } impl Default for #ident { fn default() -> #ident { #ident { #(#default)* } } } impl ::std::fmt::Debug for #ident { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let mut builder = #debug_builder; #(#debugs;)* builder.finish() } } #methods }; Ok(expanded.into()) } #[proc_macro_derive(Message, attributes(prost))] pub fn message(input: TokenStream) -> TokenStream { try_message(input).unwrap() } fn try_enumeration(input: TokenStream) -> Result<TokenStream, Error> { let input: DeriveInput = syn::parse(input)?; let ident = input.ident; if !input.generics.params.is_empty() || input.generics.where_clause.is_some() { bail!("Message may not be derived for generic type"); } let punctuated_variants = match input.data { Data::Enum(DataEnum { variants, .. }) => variants, Data::Struct(_) => bail!("Enumeration can not be derived for a struct"), Data::Union(..) => bail!("Enumeration can not be derived for a union"), }; let mut variants: Vec<(Ident, Expr)> = Vec::new(); for Variant { ident, fields, discriminant, .. } in punctuated_var
_doc = format!("Returns `true` if `value` is a variant of `{}`.", ident); let from_i32_doc = format!( "Converts an `i32` to a `{}`, or `None` if `value` is not a valid variant.", ident ); let expanded = quote! { impl #ident { #[doc=#is_valid_doc] pub fn is_valid(value: i32) -> bool { match value { #(#is_valid,)* _ => false, } } #[doc=#from_i32_doc] pub fn from_i32(value: i32) -> ::std::option::Option<#ident> { match value { #(#from,)* _ => ::std::option::Option::None, } } } impl ::std::default::Default for #ident { fn default() -> #ident { #ident::#default } } impl ::std::convert::From<#ident> for i32 { fn from(value: #ident) -> i32 { value as i32 } } }; Ok(expanded.into()) } #[proc_macro_derive(Enumeration, attributes(prost))] pub fn enumeration(input: TokenStream) -> TokenStream { try_enumeration(input).unwrap() } fn try_oneof(input: TokenStream) -> Result<TokenStream, Error> { let input: DeriveInput = syn::parse(input)?; let ident = input.ident; let variants = match input.data { Data::Enum(DataEnum { variants, .. }) => variants, Data::Struct(..) => bail!("Oneof can not be derived for a struct"), Data::Union(..) => bail!("Oneof can not be derived for a union"), }; if !input.generics.params.is_empty() || input.generics.where_clause.is_some() { bail!("Message may not be derived for generic type"); } let mut fields: Vec<(Ident, Field)> = Vec::new(); for Variant { attrs, ident: variant_ident, fields: variant_fields, .. } in variants { let variant_fields = match variant_fields { Fields::Unit => Punctuated::new(), Fields::Named(FieldsNamed { named: fields, .. }) | Fields::Unnamed(FieldsUnnamed { unnamed: fields, .. }) => fields, }; if variant_fields.len() != 1 { bail!("Oneof enum variants must have a single field"); } match Field::new_oneof(attrs)? { Some(field) => fields.push((variant_ident, field)), None => bail!("invalid oneof variant: oneof variants may not be ignored"), } } let mut tags = fields .iter() .flat_map(|&(ref variant_ident, ref field)| -> Result<u32, Error> { if field.tags().len() > 1 { bail!( "invalid oneof variant {}::{}: oneof variants may only have a single tag", ident, variant_ident ); } Ok(field.tags()[0]) }) .collect::<Vec<_>>(); tags.sort(); tags.dedup(); if tags.len() != fields.len() { panic!("invalid oneof {}: variants have duplicate tags", ident); } let encode = fields.iter().map(|&(ref variant_ident, ref field)| { let encode = field.encode(quote!(*value)); quote!(#ident::#variant_ident(ref value) => { #encode }) }); let merge = fields.iter().map(|&(ref variant_ident, ref field)| { let tag = field.tags()[0]; let merge = field.merge(quote!(value)); quote! { #tag => { match field { ::std::option::Option::Some(#ident::#variant_ident(ref mut value)) => { #merge }, _ => { let mut owned_value = ::std::default::Default::default(); let value = &mut owned_value; #merge.map(|_| *field = ::std::option::Option::Some(#ident::#variant_ident(owned_value))) }, } } } }); let encoded_len = fields.iter().map(|&(ref variant_ident, ref field)| { let encoded_len = field.encoded_len(quote!(*value)); quote!(#ident::#variant_ident(ref value) => #encoded_len) }); let debug = fields.iter().map(|&(ref variant_ident, ref field)| { let wrapper = field.debug(quote!(*value)); quote!(#ident::#variant_ident(ref value) => { let wrapper = #wrapper; f.debug_tuple(stringify!(#variant_ident)) .field(&wrapper) .finish() }) }); let expanded = quote! { impl #ident { pub fn encode<B>(&self, buf: &mut B) where B: ::prost::bytes::BufMut { match *self { #(#encode,)* } } pub fn merge<B>( field: &mut ::std::option::Option<#ident>, tag: u32, wire_type: ::prost::encoding::WireType, buf: &mut B, ctx: ::prost::encoding::DecodeContext, ) -> ::std::result::Result<(), ::prost::DecodeError> where B: ::prost::bytes::Buf { match tag { #(#merge,)* _ => unreachable!(concat!("invalid ", stringify!(#ident), " tag: {}"), tag), } } #[inline] pub fn encoded_len(&self) -> usize { match *self { #(#encoded_len,)* } } } impl ::std::fmt::Debug for #ident { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { #(#debug,)* } } } }; Ok(expanded.into()) } #[proc_macro_derive(Oneof, attributes(prost))] pub fn oneof(input: TokenStream) -> TokenStream { try_oneof(input).unwrap() }
iants { match fields { Fields::Unit => (), Fields::Named(_) | Fields::Unnamed(_) => { bail!("Enumeration variants may not have fields") } } match discriminant { Some((_, expr)) => variants.push((ident, expr)), None => bail!("Enumeration variants must have a disriminant"), } } if variants.is_empty() { panic!("Enumeration must have at least one variant"); } let default = variants[0].0.clone(); let is_valid = variants .iter() .map(|&(_, ref value)| quote!(#value => true)); let from = variants.iter().map( |&(ref variant, ref value)| quote!(#value => ::std::option::Option::Some(#ident::#variant)), ); let is_valid
function_block-random_span
[ { "content": "pub fn skip_field<B>(wire_type: WireType, tag: u32, buf: &mut B, ctx: DecodeContext) -> Result<(), DecodeError>\n\nwhere\n\n B: Buf,\n\n{\n\n ctx.limit_reached()?;\n\n let len = match wire_type {\n\n WireType::Varint => decode_varint(buf).map(|_| 0)?,\n\n WireType::ThirtyTwo...
Rust
src/page.rs
matthiasbeyer/elefren
04dbf66451e9d93be971f3409a05d2f8a14a6e04
use super::{deserialise_blocking, Mastodon, Result}; use crate::entities::itemsiter::ItemsIter; use hyper_old_types::header::{parsing, Link, RelationType}; use reqwest::{header::LINK, Response}; use serde::Deserialize; use url::Url; macro_rules! pages { ($($direction:ident: $fun:ident),*) => { $( doc_comment::doc_comment!(concat!( "Method to retrieve the ", stringify!($direction), " page of results"), pub fn $fun(&mut self) -> Result<Option<Vec<T>>> { let url = match self.$direction.take() { Some(s) => s, None => return Ok(None), }; let response = self.mastodon.send_blocking( self.mastodon.client.get(url) )?; let (prev, next) = get_links(&response)?; self.next = next; self.prev = prev; deserialise_blocking(response) }); )* } } #[derive(Debug, Clone)] pub struct OwnedPage<T: for<'de> Deserialize<'de>> { mastodon: Mastodon, next: Option<Url>, prev: Option<Url>, pub initial_items: Vec<T>, } impl<T: for<'de> Deserialize<'de>> OwnedPage<T> { pages! { next: next_page, prev: prev_page } } impl<'a, T: for<'de> Deserialize<'de>> From<Page<'a, T>> for OwnedPage<T> { fn from(page: Page<'a, T>) -> OwnedPage<T> { OwnedPage { mastodon: page.mastodon.clone(), next: page.next, prev: page.prev, initial_items: page.initial_items, } } } #[derive(Debug, Clone)] pub struct Page<'a, T: for<'de> Deserialize<'de>> { mastodon: &'a Mastodon, next: Option<Url>, prev: Option<Url>, pub initial_items: Vec<T>, } impl<'a, T: for<'de> Deserialize<'de>> Page<'a, T> { pages! { next: next_page, prev: prev_page } pub(crate) fn new(mastodon: &'a Mastodon, response: Response) -> Result<Self> { let (prev, next) = get_links(&response)?; Ok(Page { initial_items: deserialise_blocking(response)?, next, prev, mastodon, }) } } impl<'a, T: Clone + for<'de> Deserialize<'de>> Page<'a, T> { pub fn into_owned(self) -> OwnedPage<T> { OwnedPage::from(self) } pub fn items_iter(self) -> impl Iterator<Item = T> + 'a where T: 'a, { ItemsIter::new(self) } } fn get_links(response: &Response) -> Result<(Option<Url>, Option<Url>)> { let mut prev = None; let mut next = None; if let Some(link_header) = response.headers().get(LINK) { let link_header = link_header.to_str()?; let link_header = link_header.as_bytes(); let link_header: Link = parsing::from_raw_str(&link_header)?; for value in link_header.values() { if let Some(relations) = value.rel() { if relations.contains(&RelationType::Next) { next = Some(Url::parse(value.link())?); } if relations.contains(&RelationType::Prev) { prev = Some(Url::parse(value.link())?); } } } } Ok((prev, next)) }
use super::{deserialise_blocking, Mastodon, Result}; use crate::entities::itemsiter::ItemsIter; use hyper_old_types::header::{parsing, Link, RelationType}; use reqwest::{header::LINK, Response}; use serde::Deserialize; use url::Url; macro_rules! pages { ($($direction:ident: $fun:ident),*) => { $( doc_comment::doc_comment!(concat!( "Method to retrieve the ", stringify!($direction), " page of results"), pub fn $fun(&mut self) -> Result<Option<Vec<T>>> { let url = match self.$direction.take() { Some(s) => s, None => return Ok(None), }; let response = self.mastodon.send_blocking( self.mastodon.client.get(url) )?; let (prev, next) = get_links(&response)?; self.next = next; self.prev = prev; deserialise_blocking(response) }); )* } } #[derive(Debug, Clone)] pub struct OwnedPage<T: for<'de> Deserialize<'de>> { mastodon: Mastodon, next: Option<Url>, prev: Option<Url>, pub initial_items: Vec<T>, } impl<T: for<'de> Deserialize<'de>> OwnedPage<T> { pages! { next: next_page, prev: prev_page } } impl<'a, T: for<'de> Deserialize<'de>> From<Page<'a, T>> for OwnedPage<T> { fn from(page: Page<'a, T>) -> OwnedPage<T> { OwnedPage { mastodon: page.mastodon.clone(), next: page.next, prev: page.prev, initial_items: page.initial_items, } } } #[derive(Debug, Clone)] pub struct Page<'a, T: for<'de> Deserialize<'de>> { mastodon: &'a Mastodon, next: Option<Url>, prev: Option<Url>, pub initial_items: Vec<T>, } impl<'a, T: for<'de> Deserialize<'de>> Page<'a, T> { pages! { next: next_page, prev: prev_page } pub(crate) fn new(mastodon: &'a Mastodon, response: Response) -> Result<Self> { let (prev, next) = get_links(&response)?; Ok(Page { initial_items: deserialise_blocking(response)?, next, prev, mastodon, }) } } impl<'a, T: Clone + for<'de> Deserialize<'de>> Page<'a, T> { pub fn into_owned(self) -> OwnedPage<T> { OwnedPage::from(self) } pub fn items_iter(self) -> impl Iterator<Item = T> + 'a where T: 'a, { ItemsIter::new(self) } } fn get_links(response: &Response) -> Result<(Option<Url>, Option<Url>)> { let mut prev = None; let mut next = None; if let Some(link_header) = response.headers().get(LINK) { let link_header = link_header.to_str()?; let link_header = link_header.as_bytes(); let link_header: Link = parsing::from_raw_str(&link_header)?; for value in link_header.values() { if let Some(relations) = value.rel() {
if relations.contains(&RelationType::Prev) { prev = Some(Url::parse(value.link())?); } } } } Ok((prev, next)) }
if relations.contains(&RelationType::Next) { next = Some(Url::parse(value.link())?); }
if_condition
[ { "content": "fn get_links(response: &Response) -> Result<(Option<Url>, Option<Url>)> {\n\n let mut prev = None;\n\n let mut next = None;\n\n\n\n if let Some(link_header) = response.header(LINK) {\n\n let link_header = link_header.as_str();\n\n let link_header = link_header.as_bytes();\n\...
Rust
src/writers/syslog_writer.rs
ijackson/flexi_logger
674d0b8c9f8f8291b4a2a14f53fd84b40e71e788
use crate::deferred_now::DeferredNow; use crate::writers::log_writer::LogWriter; use std::cell::RefCell; use std::ffi::OsString; use std::io::Error as IoError; use std::io::Result as IoResult; use std::io::{BufWriter, ErrorKind, Write}; use std::net::{TcpStream, ToSocketAddrs, UdpSocket}; #[cfg(target_os = "linux")] use std::path::Path; use std::sync::Mutex; #[derive(Copy, Clone, Debug)] pub enum SyslogFacility { Kernel = 0 << 3, UserLevel = 1 << 3, MailSystem = 2 << 3, SystemDaemons = 3 << 3, Authorization = 4 << 3, SyslogD = 5 << 3, LinePrinter = 6 << 3, News = 7 << 3, Uucp = 8 << 3, Clock = 9 << 3, Authorization2 = 10 << 3, Ftp = 11 << 3, Ntp = 12 << 3, LogAudit = 13 << 3, LogAlert = 14 << 3, Clock2 = 15 << 3, LocalUse0 = 16 << 3, LocalUse1 = 17 << 3, LocalUse2 = 18 << 3, LocalUse3 = 19 << 3, LocalUse4 = 20 << 3, LocalUse5 = 21 << 3, LocalUse6 = 22 << 3, LocalUse7 = 23 << 3, } #[derive(Debug)] pub enum SyslogSeverity { Emergency = 0, Alert = 1, Critical = 2, Error = 3, Warning = 4, Notice = 5, Info = 6, Debug = 7, } pub type LevelToSyslogSeverity = fn(level: log::Level) -> SyslogSeverity; fn default_mapping(level: log::Level) -> SyslogSeverity { match level { log::Level::Error => SyslogSeverity::Error, log::Level::Warn => SyslogSeverity::Warning, log::Level::Info => SyslogSeverity::Info, log::Level::Debug | log::Level::Trace => SyslogSeverity::Debug, } } pub struct SyslogWriter { hostname: OsString, process: String, pid: u32, facility: SyslogFacility, message_id: String, determine_severity: LevelToSyslogSeverity, syslog: Mutex<RefCell<SyslogConnector>>, max_log_level: log::LevelFilter, } impl SyslogWriter { pub fn try_new( facility: SyslogFacility, determine_severity: Option<LevelToSyslogSeverity>, max_log_level: log::LevelFilter, message_id: String, syslog: SyslogConnector, ) -> IoResult<Box<Self>> { Ok(Box::new(Self { hostname: hostname::get().unwrap_or_else(|_| OsString::from("<unknown_hostname>")), process: std::env::args() .next() .ok_or_else(|| IoError::new(ErrorKind::Other, "<no progname>".to_owned()))?, pid: std::process::id(), facility, max_log_level, message_id, determine_severity: determine_severity.unwrap_or_else(|| default_mapping), syslog: Mutex::new(RefCell::new(syslog)), })) } } impl LogWriter for SyslogWriter { fn write(&self, now: &mut DeferredNow, record: &log::Record) -> IoResult<()> { let mr_syslog = self.syslog.lock().unwrap(); let mut syslog = mr_syslog.borrow_mut(); let severity = (self.determine_severity)(record.level()); write!( syslog, "{}", format!( "<{}>1 {} {:?} {} {} {} - {}\n", self.facility as u8 | severity as u8, now.now() .to_rfc3339_opts(chrono::SecondsFormat::Micros, false), self.hostname, self.process, self.pid, self.message_id, &record.args() ) ) } fn flush(&self) -> IoResult<()> { let mr_syslog = self.syslog.lock().unwrap(); let mut syslog = mr_syslog.borrow_mut(); syslog.flush()?; Ok(()) } fn max_log_level(&self) -> log::LevelFilter { self.max_log_level } } #[derive(Debug)] pub enum SyslogConnector { #[cfg(target_os = "linux")] Stream(BufWriter<std::os::unix::net::UnixStream>), #[cfg(target_os = "linux")] Datagram(std::os::unix::net::UnixDatagram), Udp(UdpSocket), Tcp(BufWriter<TcpStream>), } impl SyslogConnector { #[cfg(target_os = "linux")] pub fn try_datagram<P: AsRef<Path>>(path: P) -> IoResult<SyslogConnector> { let ud = std::os::unix::net::UnixDatagram::unbound()?; ud.connect(&path)?; Ok(SyslogConnector::Datagram(ud)) } #[cfg(target_os = "linux")] pub fn try_stream<P: AsRef<Path>>(path: P) -> IoResult<SyslogConnector> { Ok(SyslogConnector::Stream(BufWriter::new( std::os::unix::net::UnixStream::connect(path)?, ))) } pub fn try_tcp<T: ToSocketAddrs>(server: T) -> IoResult<Self> { Ok(Self::Tcp(BufWriter::new(TcpStream::connect(server)?))) } pub fn try_udp<T: ToSocketAddrs>(local: T, server: T) -> IoResult<Self> { let socket = UdpSocket::bind(local)?; socket.connect(server)?; Ok(Self::Udp(socket)) } } impl Write for SyslogConnector { fn write(&mut self, message: &[u8]) -> IoResult<usize> { match *self { #[cfg(target_os = "linux")] Self::Datagram(ref ud) => { ud.send(&message[..]) } #[cfg(target_os = "linux")] Self::Stream(ref mut w) => { w.write(&message[..]) .and_then(|sz| w.write_all(&[0; 1]).map(|_| sz)) } Self::Tcp(ref mut w) => { w.write(&message[..]) } Self::Udp(ref socket) => { socket.send(&message[..]) } } } fn flush(&mut self) -> IoResult<()> { match *self { #[cfg(target_os = "linux")] Self::Datagram(_) => Ok(()), #[cfg(target_os = "linux")] Self::Stream(ref mut w) => w.flush(), Self::Udp(_) => Ok(()), Self::Tcp(ref mut w) => w.flush(), } } }
use crate::deferred_now::DeferredNow; use crate::writers::log_writer::LogWriter; use std::cell::RefCell; use std::ffi::OsString; use std::io::Error as IoError; use std::io::Result as IoResult; use std::io::{BufWriter, ErrorKind, Write}; use std::net::{TcpStream, ToSocketAddrs, UdpSocket}; #[cfg(target_os = "linux")] use std::path::Path; use std::sync::Mutex; #[derive(Copy, Clone, Debug)] pub enum SyslogFacility { Kernel = 0 << 3, UserLevel = 1 << 3, MailSystem = 2 << 3, SystemDaemons = 3 << 3, Authorization = 4 << 3, SyslogD = 5 << 3, LinePrinter = 6 << 3, News = 7 << 3, Uucp = 8 << 3, Clock = 9 << 3, Authorization2 = 10 << 3, Ftp = 11 << 3, Ntp = 12 << 3, LogAudit = 13 << 3, LogAlert = 14 << 3, Clock2 = 15 << 3, LocalUse0 = 16 << 3, LocalUse1 = 17 << 3, LocalUse2 = 18 << 3, LocalUse3 = 19 << 3, LocalUse4 = 20 << 3, LocalUse5 = 21 << 3, LocalUse6 = 22 << 3, LocalUse7 = 23 << 3, } #[derive(Debug)] pub enum SyslogSeverity { Emergency = 0, Alert = 1, Critical = 2, Error = 3, Warning = 4, Notice = 5, Info = 6, Debug = 7, } pub type LevelToSyslogSeverity = fn(level: log::Level) -> SyslogSeverity; fn default_mapping(level: log::Level) -> SyslogSeverity { match level { log::Level::Error => SyslogSeverity::Error, log::Level::Warn => SyslogSeverity::Warning, log::Level::Info => SyslogSeverity::Info, log::Level::Debug | log::Level::Trace => SyslogSeverity::Debug, } } pub struct SyslogWriter { hostname: OsString, process: String, pid: u32, facility: SyslogFacility, message_id: String, determine_severity: LevelToSyslogSeverity, syslog: Mutex<RefCell<SyslogConnec
et) => { socket.send(&message[..]) } } } fn flush(&mut self) -> IoResult<()> { match *self { #[cfg(target_os = "linux")] Self::Datagram(_) => Ok(()), #[cfg(target_os = "linux")] Self::Stream(ref mut w) => w.flush(), Self::Udp(_) => Ok(()), Self::Tcp(ref mut w) => w.flush(), } } }
tor>>, max_log_level: log::LevelFilter, } impl SyslogWriter { pub fn try_new( facility: SyslogFacility, determine_severity: Option<LevelToSyslogSeverity>, max_log_level: log::LevelFilter, message_id: String, syslog: SyslogConnector, ) -> IoResult<Box<Self>> { Ok(Box::new(Self { hostname: hostname::get().unwrap_or_else(|_| OsString::from("<unknown_hostname>")), process: std::env::args() .next() .ok_or_else(|| IoError::new(ErrorKind::Other, "<no progname>".to_owned()))?, pid: std::process::id(), facility, max_log_level, message_id, determine_severity: determine_severity.unwrap_or_else(|| default_mapping), syslog: Mutex::new(RefCell::new(syslog)), })) } } impl LogWriter for SyslogWriter { fn write(&self, now: &mut DeferredNow, record: &log::Record) -> IoResult<()> { let mr_syslog = self.syslog.lock().unwrap(); let mut syslog = mr_syslog.borrow_mut(); let severity = (self.determine_severity)(record.level()); write!( syslog, "{}", format!( "<{}>1 {} {:?} {} {} {} - {}\n", self.facility as u8 | severity as u8, now.now() .to_rfc3339_opts(chrono::SecondsFormat::Micros, false), self.hostname, self.process, self.pid, self.message_id, &record.args() ) ) } fn flush(&self) -> IoResult<()> { let mr_syslog = self.syslog.lock().unwrap(); let mut syslog = mr_syslog.borrow_mut(); syslog.flush()?; Ok(()) } fn max_log_level(&self) -> log::LevelFilter { self.max_log_level } } #[derive(Debug)] pub enum SyslogConnector { #[cfg(target_os = "linux")] Stream(BufWriter<std::os::unix::net::UnixStream>), #[cfg(target_os = "linux")] Datagram(std::os::unix::net::UnixDatagram), Udp(UdpSocket), Tcp(BufWriter<TcpStream>), } impl SyslogConnector { #[cfg(target_os = "linux")] pub fn try_datagram<P: AsRef<Path>>(path: P) -> IoResult<SyslogConnector> { let ud = std::os::unix::net::UnixDatagram::unbound()?; ud.connect(&path)?; Ok(SyslogConnector::Datagram(ud)) } #[cfg(target_os = "linux")] pub fn try_stream<P: AsRef<Path>>(path: P) -> IoResult<SyslogConnector> { Ok(SyslogConnector::Stream(BufWriter::new( std::os::unix::net::UnixStream::connect(path)?, ))) } pub fn try_tcp<T: ToSocketAddrs>(server: T) -> IoResult<Self> { Ok(Self::Tcp(BufWriter::new(TcpStream::connect(server)?))) } pub fn try_udp<T: ToSocketAddrs>(local: T, server: T) -> IoResult<Self> { let socket = UdpSocket::bind(local)?; socket.connect(server)?; Ok(Self::Udp(socket)) } } impl Write for SyslogConnector { fn write(&mut self, message: &[u8]) -> IoResult<usize> { match *self { #[cfg(target_os = "linux")] Self::Datagram(ref ud) => { ud.send(&message[..]) } #[cfg(target_os = "linux")] Self::Stream(ref mut w) => { w.write(&message[..]) .and_then(|sz| w.write_all(&[0; 1]).map(|_| sz)) } Self::Tcp(ref mut w) => { w.write(&message[..]) } Self::Udp(ref sock
random
[ { "content": "fn number_infix(idx: u32) -> String {\n\n format!(\"_r{:0>5}\", idx)\n\n}\n\n\n", "file_path": "src/writers/file_log_writer.rs", "rank": 0, "score": 146125.11405953576 }, { "content": "#[cfg(feature = \"colors\")]\n\npub fn style<T>(level: log::Level, item: T) -> Paint<T> {\...
Rust
zircon-loader/src/lib.rs
Lincyaw/zCore
152733a670e5bec222349279de238e2f37bc4a97
#![no_std] #![feature(asm)] #![feature(global_asm)] #![deny(warnings, unused_must_use)] #[macro_use] extern crate alloc; #[macro_use] extern crate log; use { alloc::{boxed::Box, sync::Arc, vec::Vec}, kernel_hal::GeneralRegs, xmas_elf::ElfFile, zircon_object::{dev::*, ipc::*, object::*, task::*, util::elf_loader::*, vm::*}, zircon_syscall::Syscall, }; mod kcounter; const K_PROC_SELF: usize = 0; const K_VMARROOT_SELF: usize = 1; const K_ROOTJOB: usize = 2; const K_ROOTRESOURCE: usize = 3; const K_ZBI: usize = 4; const K_FIRSTVDSO: usize = 5; const K_CRASHLOG: usize = 8; const K_COUNTERNAMES: usize = 9; const K_COUNTERS: usize = 10; const K_FISTINSTRUMENTATIONDATA: usize = 11; const K_HANDLECOUNT: usize = 15; pub struct Images<T: AsRef<[u8]>> { pub userboot: T, pub vdso: T, pub zbi: T, } pub fn run_userboot(images: &Images<impl AsRef<[u8]>>, cmdline: &str) -> Arc<Process> { let job = Job::root(); let proc = Process::create(&job, "userboot", 0).unwrap(); let thread = Thread::create(&proc, "userboot", 0).unwrap(); let resource = Resource::create( "root", ResourceKind::ROOT, 0, 0x1_0000_0000, ResourceFlags::empty(), ); let vmar = proc.vmar(); let (entry, userboot_size) = { let elf = ElfFile::new(images.userboot.as_ref()).unwrap(); let size = elf.load_segment_size(); let vmar = vmar .allocate(None, size, VmarFlags::CAN_MAP_RXW, PAGE_SIZE) .unwrap(); vmar.load_from_elf(&elf).unwrap(); (vmar.addr() + elf.header.pt2.entry_point() as usize, size) }; let vdso_vmo = { let elf = ElfFile::new(images.vdso.as_ref()).unwrap(); let vdso_vmo = VmObject::new_paged(images.vdso.as_ref().len() / PAGE_SIZE + 1); vdso_vmo.write(0, images.vdso.as_ref()).unwrap(); let size = elf.load_segment_size(); let vmar = vmar .allocate_at( userboot_size, size, VmarFlags::CAN_MAP_RXW | VmarFlags::SPECIFIC, PAGE_SIZE, ) .unwrap(); vmar.map_from_elf(&elf, vdso_vmo.clone()).unwrap(); #[cfg(feature = "std")] { let offset = elf .get_symbol_address("zcore_syscall_entry") .expect("failed to locate syscall entry") as usize; let syscall_entry = &(kernel_hal_unix::syscall_entry as usize).to_ne_bytes(); vdso_vmo.write(offset, syscall_entry).unwrap(); vdso_vmo.write(offset + 8, syscall_entry).unwrap(); vdso_vmo.write(offset + 16, syscall_entry).unwrap(); } vdso_vmo }; let zbi_vmo = { let vmo = VmObject::new_paged(images.zbi.as_ref().len() / PAGE_SIZE + 1); vmo.write(0, images.zbi.as_ref()).unwrap(); vmo.set_name("zbi"); vmo }; const STACK_PAGES: usize = 8; let stack_vmo = VmObject::new_paged(STACK_PAGES); let flags = MMUFlags::READ | MMUFlags::WRITE | MMUFlags::USER; let stack_bottom = vmar .map(None, stack_vmo.clone(), 0, stack_vmo.len(), flags) .unwrap(); #[cfg(target_arch = "x86_64")] let sp = stack_bottom + stack_vmo.len() - 8; #[cfg(target_arch = "aarch64")] let sp = stack_bottom + stack_vmo.len(); let (user_channel, kernel_channel) = Channel::create(); let handle = Handle::new(user_channel, Rights::DEFAULT_CHANNEL); let mut handles = vec![Handle::new(proc.clone(), Rights::empty()); K_HANDLECOUNT]; handles[K_PROC_SELF] = Handle::new(proc.clone(), Rights::DEFAULT_PROCESS); handles[K_VMARROOT_SELF] = Handle::new(proc.vmar(), Rights::DEFAULT_VMAR | Rights::IO); handles[K_ROOTJOB] = Handle::new(job, Rights::DEFAULT_JOB); handles[K_ROOTRESOURCE] = Handle::new(resource, Rights::DEFAULT_RESOURCE); handles[K_ZBI] = Handle::new(zbi_vmo, Rights::DEFAULT_VMO); const VDSO_DATA_CONSTANTS: usize = 0x4a50; const VDSO_DATA_CONSTANTS_SIZE: usize = 0x78; let constants: [u8; VDSO_DATA_CONSTANTS_SIZE] = unsafe { core::mem::transmute(kernel_hal::vdso_constants()) }; vdso_vmo.write(VDSO_DATA_CONSTANTS, &constants).unwrap(); vdso_vmo.set_name("vdso/full"); let vdso_test1 = vdso_vmo.create_child(false, 0, vdso_vmo.len()).unwrap(); vdso_test1.set_name("vdso/test1"); let vdso_test2 = vdso_vmo.create_child(false, 0, vdso_vmo.len()).unwrap(); vdso_test2.set_name("vdso/test2"); handles[K_FIRSTVDSO] = Handle::new(vdso_vmo, Rights::DEFAULT_VMO | Rights::EXECUTE); handles[K_FIRSTVDSO + 1] = Handle::new(vdso_test1, Rights::DEFAULT_VMO | Rights::EXECUTE); handles[K_FIRSTVDSO + 2] = Handle::new(vdso_test2, Rights::DEFAULT_VMO | Rights::EXECUTE); let crash_log_vmo = VmObject::new_paged(1); crash_log_vmo.set_name("crashlog"); handles[K_CRASHLOG] = Handle::new(crash_log_vmo, Rights::DEFAULT_VMO); let (counter_name_vmo, kcounters_vmo) = kcounter::create_kcounter_vmo(); handles[K_COUNTERNAMES] = Handle::new(counter_name_vmo, Rights::DEFAULT_VMO); handles[K_COUNTERS] = Handle::new(kcounters_vmo, Rights::DEFAULT_VMO); let instrumentation_data_vmo = VmObject::new_paged(0); instrumentation_data_vmo.set_name("UNIMPLEMENTED_VMO"); handles[K_FISTINSTRUMENTATIONDATA] = Handle::new(instrumentation_data_vmo.clone(), Rights::DEFAULT_VMO); handles[K_FISTINSTRUMENTATIONDATA + 1] = Handle::new(instrumentation_data_vmo.clone(), Rights::DEFAULT_VMO); handles[K_FISTINSTRUMENTATIONDATA + 2] = Handle::new(instrumentation_data_vmo.clone(), Rights::DEFAULT_VMO); handles[K_FISTINSTRUMENTATIONDATA + 3] = Handle::new(instrumentation_data_vmo, Rights::DEFAULT_VMO); let data = Vec::from(cmdline.replace(':', "\0") + "\0"); let msg = MessagePacket { data, handles }; kernel_channel.write(msg).unwrap(); proc.start(&thread, entry, sp, Some(handle), 0, spawn) .expect("failed to start main thread"); proc } kcounter!(EXCEPTIONS_USER, "exceptions.user"); kcounter!(EXCEPTIONS_TIMER, "exceptions.timer"); kcounter!(EXCEPTIONS_PGFAULT, "exceptions.pgfault"); fn spawn(thread: Arc<Thread>) { let vmtoken = thread.proc().vmar().table_phys(); let future = async move { kernel_hal::Thread::set_tid(thread.id(), thread.proc().id()); let mut exit = false; if thread.get_first_thread() { let proc_start_exception = Exception::create(thread.clone(), ExceptionType::ProcessStarting, None); if !proc_start_exception .handle_with_exceptionates( false, JobDebuggerIterator::new(thread.proc().job()), true, ) .await { exit = true; } }; let start_exception = Exception::create(thread.clone(), ExceptionType::ThreadStarting, None); if !start_exception .handle_with_exceptionates(false, Some(thread.proc().get_debug_exceptionate()), false) .await { exit = true; } while !exit { let mut cx = thread.wait_for_run().await; if thread.state() == ThreadState::Dying { info!( "proc={:?} thread={:?} was killed", thread.proc().name(), thread.name() ); break; } trace!("go to user: {:#x?}", cx); debug!("switch to {}|{}", thread.proc().name(), thread.name()); let tmp_time = kernel_hal::timer_now().as_nanos(); kernel_hal::context_run(&mut cx); let time = kernel_hal::timer_now().as_nanos() - tmp_time; thread.time_add(time); trace!("back from user: {:#x?}", cx); EXCEPTIONS_USER.add(1); #[cfg(target_arch = "aarch64")] match cx.trap_num { 0 => exit = handle_syscall(&thread, &mut cx.general).await, _ => unimplemented!(), } #[cfg(target_arch = "x86_64")] match cx.trap_num { 0x100 => exit = handle_syscall(&thread, &mut cx.general).await, 0x20..=0x3f => { kernel_hal::InterruptManager::handle(cx.trap_num as u8); if cx.trap_num == 0x20 { EXCEPTIONS_TIMER.add(1); kernel_hal::yield_now().await; } } 0xe => { EXCEPTIONS_PGFAULT.add(1); #[cfg(target_arch = "x86_64")] let flags = if cx.error_code & 0x2 == 0 { MMUFlags::READ } else { MMUFlags::WRITE }; #[cfg(target_arch = "aarch64")] let flags = MMUFlags::WRITE; error!( "page fualt from user mode {:#x} {:#x?}", kernel_hal::fetch_fault_vaddr(), flags ); match thread .proc() .vmar() .handle_page_fault(kernel_hal::fetch_fault_vaddr(), flags) { Ok(()) => {} Err(e) => { error!( "proc={:?} thread={:?} err={:?}", thread.proc().name(), thread.name(), e ); error!("Page Fault from user mode {:#x?}", cx); let exception = Exception::create( thread.clone(), ExceptionType::FatalPageFault, Some(&cx), ); if !exception.handle(true).await { exit = true; } } } } 0x8 => { panic!("Double fault from user mode! {:#x?}", cx); } num => { let type_ = match num { 0x1 => ExceptionType::HardwareBreakpoint, 0x3 => ExceptionType::SoftwareBreakpoint, 0x6 => ExceptionType::UndefinedInstruction, 0x17 => ExceptionType::UnalignedAccess, _ => ExceptionType::General, }; error!("User mode exception:{:?} {:#x?}", type_, cx); let exception = Exception::create(thread.clone(), type_, Some(&cx)); if !exception.handle(true).await { exit = true; } } } thread.end_running(cx); if exit { info!( "proc={:?} thread={:?} exited", thread.proc().name(), thread.name() ); break; } } let end_exception = Exception::create(thread.clone(), ExceptionType::ThreadExiting, None); let handled = thread .proc() .get_debug_exceptionate() .send_exception(&end_exception); if let Ok(future) = handled { thread.dying_run(future).await.ok(); } else { handled.ok(); } thread.terminate(); }; kernel_hal::Thread::spawn(Box::pin(future), vmtoken); } async fn handle_syscall(thread: &Arc<Thread>, regs: &mut GeneralRegs) -> bool { #[cfg(target_arch = "x86_64")] let num = regs.rax as u32; #[cfg(target_arch = "aarch64")] let num = regs.x16 as u32; #[cfg(feature = "std")] #[cfg(target_arch = "x86_64")] let args = unsafe { let a6 = (regs.rsp as *const usize).read(); let a7 = (regs.rsp as *const usize).add(1).read(); [ regs.rdi, regs.rsi, regs.rdx, regs.rcx, regs.r8, regs.r9, a6, a7, ] }; #[cfg(not(feature = "std"))] #[cfg(target_arch = "x86_64")] let args = [ regs.rdi, regs.rsi, regs.rdx, regs.r10, regs.r8, regs.r9, regs.r12, regs.r13, ]; #[cfg(target_arch = "aarch64")] let args = [ regs.x0, regs.x1, regs.x2, regs.x3, regs.x4, regs.x5, regs.x6, regs.x7, ]; let mut syscall = Syscall { regs, thread: thread.clone(), spawn_fn: spawn, exit: false, }; let ret = syscall.syscall(num, args).await as usize; #[cfg(target_arch = "x86_64")] { syscall.regs.rax = ret; } #[cfg(target_arch = "aarch64")] { syscall.regs.x0 = ret; } syscall.exit }
#![no_std] #![feature(asm)] #![feature(global_asm)] #![deny(warnings, unused_must_use)] #[macro_use] extern crate alloc; #[macro_use] extern crate log; use { alloc::{boxed::Box, sync::Arc, vec::Vec}, kernel_hal::GeneralRegs, xmas_elf::ElfFile, zircon_object::{dev::*, ipc::*, object::*, task::*, util::elf_loader::*, vm::*}, zircon_syscall::Syscall, }; mod kcounter; const K_PROC_SELF: usize = 0; const K_VMARROOT_SELF: usize = 1; const K_ROOTJOB: usize = 2; const K_ROOTRESOURCE: usize = 3; const K_ZBI: usize = 4; const K_FIRSTVDSO: usize = 5; const K_CRASHLOG: usize = 8; const K_COUNTERNAMES: usize = 9; const K_COUNTERS: usize = 10; const K_FISTINSTRUMENTATIONDATA: usize = 11; const K_HANDLECOUNT: usize = 15; pub struct Images<T: AsRef<[u8]>> { pub userboot: T, pub vdso: T, pub zbi: T, } pub fn run_userboot(images: &Images<impl AsRef<[u8]>>, cmdline: &str) -> Arc<Process> { let job = Job::root(); let proc = Process::create(&job, "userboot", 0).unwrap(); let thread = Thread::create(&proc, "userboot", 0).unwrap(); let resource = Resource::create( "root", ResourceKind::ROOT, 0, 0x1_0000_0000, ResourceFlags::empty(), ); let vmar = proc.vmar(); let (entry, userboot_size) = { let elf = ElfFile::new(images.userboot.as_ref()).unwrap(); let size = elf.load_segment_size(); let vmar = vmar .allocate(None, size, VmarFlags::CAN_MAP_RXW, PAGE_SIZE) .unwrap(); vmar.load_from_elf(&elf).unwrap(); (vmar.addr() + elf.header.pt2.entry_point() as usize, size) }; let vdso_vmo = { let elf = ElfFile::new(images.vdso.as_ref()).unwrap(); let vdso_vmo = VmObject::new_paged(images.vdso.as_ref().len() / PAGE_SIZE + 1); vdso_vmo.write(0, images.vdso.as_ref()).unwrap(); let size = elf.load_segment_size(); let vmar = vmar .allocate_at( userboot_size, size, VmarFlags::CAN_MAP_RXW | VmarFlags::SPECIFIC, PAGE_SIZE, ) .unwrap(); vmar.map_from_elf(&elf, vdso_vmo.clone()).unwrap(); #[cfg(feature = "std")] { let offset = elf .get_symbol_address("zcore_syscall_entry") .expect("failed to locate syscall entry") as usize; let syscall_entry = &(kernel_hal_unix::syscall_entry as usize).to_ne_bytes(); vdso_vmo.write(offset, syscall_entry).unwrap(); vdso_vmo.write(offset + 8, syscall_entry).unwrap(); vdso_vmo.write(offset + 16, syscall_entry).unwrap(); } vdso_vmo }; let zbi_vmo = { let vmo = VmObject::new_paged(images.zbi.as_ref().len() / PAGE_SIZE + 1); vmo.write(0, images.zbi.as_ref()).unwrap(); vmo.set_name("zbi"); vmo }; const STACK_PAGES: usize = 8; let stack_vmo = VmObject::new_paged(STACK_PAGES); let flags = MMUFlags::READ | MMUFlags::WRITE | MMUFlags::USER; let stack_bottom = vmar .map(None, stack_vmo.clone(), 0, stack_vmo.len(), flags) .unwrap(); #[cfg(target_arch = "x86_64")] let sp = stack_bottom + stack_vmo.len() - 8; #[cfg(target_arch = "aarch64")] let sp = stack_bottom + stack_vmo.len(); let (user_channel, kernel_channel) = Channel::create(); let handle = Handle::new(user_channel, Rights::DEFAULT_CHANNEL); let mut handles = vec![Handle::new(proc.clone(), Rights::empty()); K_HANDLECOUNT]; handles[K_PROC_SELF] = Handle::new(proc.clone(), Rights::DEFAULT_PROCESS); handles[K_VMARROOT_SELF] = Handle::new(proc.vmar(), Rights::DEFAULT_VMAR | Rights::IO); handles[K_ROOTJOB] = Handle::new(job, Rights::DEFAULT_JOB); handles[K_ROOTRESOURCE] = Handle::new(resource, Rights::DEFAULT_RESOURCE); handles[K_ZBI] = Handle::new(zbi_vmo, Rights::DEFAULT_VMO); const VDSO_DATA_CONSTANTS: usize = 0x4a50; const VDSO_DATA_CONSTANTS_SIZE: usize = 0x78; let constants: [u8; VDSO_DATA_CONSTANTS_SIZE] = unsafe { core::mem::transmute(kernel_hal::vdso_constants()) }; vdso_vmo.write(VDSO_DATA_CONSTANTS, &constants).unwrap(); vdso_vmo.set_name("vdso/full"); let vdso_test1 = vdso_vmo.create_child(false, 0, vdso_vmo.len()).unwrap(); vdso_test1.set_name("vdso/test1"); let vdso_test2 = vdso_vmo.create_child(false, 0, vdso_vmo.len()).unwrap(); vdso_test2.set_name("vdso/test2"); handles[K_FIRSTVDSO] = Handle::new(vdso_vmo, Rights::DEFAULT_VMO | Rights::EXECUTE); handles[K_FIRSTVDSO + 1] = Handle::new(vdso_test1, Rights::DEFAULT_VMO | Rights::EXECUTE); handles[K_FIRSTVDSO + 2] = Handle::new(vdso_test2, Rights::DEFAULT_VMO | Rights::EXECUTE); let crash_log_vmo = VmObject::new_paged(1); crash_log_vmo.set_name("crashlog"); handles[K_CRASHLOG] = Handle::new(crash_log_vmo, Rights::DEFAULT_VMO); let (counter_name_vmo, kcounters_vmo) = kcounter::create_kcounter_vmo(); handles[K_COUNTERNAMES] = Handle::new(counter_name_vmo, Rights::DEFAULT_VMO); handles[K_COUNTERS] = Handle::new(kcounters_vmo, Rights::DEFAULT_VMO); let instrumentation_data_vmo = VmObject::new_paged(0); instrumentation_data_vmo.set_name("UNIMPLEMENTED_VMO"); handles[K_FISTINSTRUMENTATIONDATA] = Handle::new(instrumentation_data_vmo.clone(), Rights::DEFAULT_VMO); handles[K_FISTINSTRUMENTATIONDATA + 1] = Handle::new(instrumentation_data_vmo.clone(), Rights::DEFAULT_VMO); handles[K_FISTINSTRUMENTATIONDATA + 2] = Handle::new(instrumentation_data_vmo.clone(), Rights::DEFAULT_VMO); handles[K_FISTINSTRUMENTATIONDATA + 3] = Handle::new(instrumentation_data_vmo, Rights::DEFAULT_VMO); let data = Vec::from(cmdline.replace(':', "\0") + "\0"); let msg = MessagePacket { data, handles }; kernel_channel.write(msg).unwrap(); proc.start(&thread, entry, sp, Some(handle), 0, spawn) .expect("failed to start main thread"); proc } kcounter!(EXCEPTIONS_USER, "exceptions.user"); kcounter!(EXCEPTIONS_TIMER, "exceptions.timer"); kcounter!(EXCEPTIONS_PGFAULT, "exceptions.pgfault"); fn spawn(thread: Arc<Thread>) { let vmtoken = thread.proc().vmar().table_phys(); let future = async move { kernel_hal::Thread::set_tid(thread.id(), thread.proc().id()); let mut exit = false; if thread.get_first_thread() { let proc_start_exception = Exception::create(thread.clone(), ExceptionType::ProcessStarting, None); if !proc_start_exception .handle_with_exceptionates( false, JobDebuggerIterator::new(thread.proc().job()), true, ) .await { exit = true; } }; let start_exception = Exception::create(thread.clone(), ExceptionType::ThreadStarting, None); if !start_exception .handle_with_exceptionates(false, Some(thread.proc().get_debug_exceptionate()), false) .await { exit = true; } while !exit { let mut cx = thread.wait_for_run().await; if thread.state() == ThreadState::Dying { info!( "proc={:?} thread={:?} was killed", thread.proc().name(), thread.name() ); break; } trace!("go to user: {:#x?}", cx); debug!("switch to {}|{}", thread.proc().name(), thread.name()); let tmp_time = kernel_hal::timer_now().as_nanos(); kernel_hal::context_run
flags ); match thread .proc() .vmar() .handle_page_fault(kernel_hal::fetch_fault_vaddr(), flags) { Ok(()) => {} Err(e) => { error!( "proc={:?} thread={:?} err={:?}", thread.proc().name(), thread.name(), e ); error!("Page Fault from user mode {:#x?}", cx); let exception = Exception::create( thread.clone(), ExceptionType::FatalPageFault, Some(&cx), ); if !exception.handle(true).await { exit = true; } } } } 0x8 => { panic!("Double fault from user mode! {:#x?}", cx); } num => { let type_ = match num { 0x1 => ExceptionType::HardwareBreakpoint, 0x3 => ExceptionType::SoftwareBreakpoint, 0x6 => ExceptionType::UndefinedInstruction, 0x17 => ExceptionType::UnalignedAccess, _ => ExceptionType::General, }; error!("User mode exception:{:?} {:#x?}", type_, cx); let exception = Exception::create(thread.clone(), type_, Some(&cx)); if !exception.handle(true).await { exit = true; } } } thread.end_running(cx); if exit { info!( "proc={:?} thread={:?} exited", thread.proc().name(), thread.name() ); break; } } let end_exception = Exception::create(thread.clone(), ExceptionType::ThreadExiting, None); let handled = thread .proc() .get_debug_exceptionate() .send_exception(&end_exception); if let Ok(future) = handled { thread.dying_run(future).await.ok(); } else { handled.ok(); } thread.terminate(); }; kernel_hal::Thread::spawn(Box::pin(future), vmtoken); } async fn handle_syscall(thread: &Arc<Thread>, regs: &mut GeneralRegs) -> bool { #[cfg(target_arch = "x86_64")] let num = regs.rax as u32; #[cfg(target_arch = "aarch64")] let num = regs.x16 as u32; #[cfg(feature = "std")] #[cfg(target_arch = "x86_64")] let args = unsafe { let a6 = (regs.rsp as *const usize).read(); let a7 = (regs.rsp as *const usize).add(1).read(); [ regs.rdi, regs.rsi, regs.rdx, regs.rcx, regs.r8, regs.r9, a6, a7, ] }; #[cfg(not(feature = "std"))] #[cfg(target_arch = "x86_64")] let args = [ regs.rdi, regs.rsi, regs.rdx, regs.r10, regs.r8, regs.r9, regs.r12, regs.r13, ]; #[cfg(target_arch = "aarch64")] let args = [ regs.x0, regs.x1, regs.x2, regs.x3, regs.x4, regs.x5, regs.x6, regs.x7, ]; let mut syscall = Syscall { regs, thread: thread.clone(), spawn_fn: spawn, exit: false, }; let ret = syscall.syscall(num, args).await as usize; #[cfg(target_arch = "x86_64")] { syscall.regs.rax = ret; } #[cfg(target_arch = "aarch64")] { syscall.regs.x0 = ret; } syscall.exit }
(&mut cx); let time = kernel_hal::timer_now().as_nanos() - tmp_time; thread.time_add(time); trace!("back from user: {:#x?}", cx); EXCEPTIONS_USER.add(1); #[cfg(target_arch = "aarch64")] match cx.trap_num { 0 => exit = handle_syscall(&thread, &mut cx.general).await, _ => unimplemented!(), } #[cfg(target_arch = "x86_64")] match cx.trap_num { 0x100 => exit = handle_syscall(&thread, &mut cx.general).await, 0x20..=0x3f => { kernel_hal::InterruptManager::handle(cx.trap_num as u8); if cx.trap_num == 0x20 { EXCEPTIONS_TIMER.add(1); kernel_hal::yield_now().await; } } 0xe => { EXCEPTIONS_PGFAULT.add(1); #[cfg(target_arch = "x86_64")] let flags = if cx.error_code & 0x2 == 0 { MMUFlags::READ } else { MMUFlags::WRITE }; #[cfg(target_arch = "aarch64")] let flags = MMUFlags::WRITE; error!( "page fualt from user mode {:#x} {:#x?}", kernel_hal::fetch_fault_vaddr(),
function_block-random_span
[]
Rust
src/cargo/sources/registry/local.rs
quark-zju/cargo
62180bf27d83e1d8785b32bbe4d6f6fb07fff4bc
use crate::core::{InternedString, PackageId}; use crate::sources::registry::{MaybeLock, RegistryConfig, RegistryData}; use crate::util::errors::CargoResult; use crate::util::paths; use crate::util::{Config, Filesystem, Sha256}; use std::fs::File; use std::io::prelude::*; use std::io::SeekFrom; use std::path::Path; pub struct LocalRegistry<'cfg> { index_path: Filesystem, root: Filesystem, src_path: Filesystem, config: &'cfg Config, } impl<'cfg> LocalRegistry<'cfg> { pub fn new(root: &Path, config: &'cfg Config, name: &str) -> LocalRegistry<'cfg> { LocalRegistry { src_path: config.registry_source_path().join(name), index_path: Filesystem::new(root.join("index")), root: Filesystem::new(root.to_path_buf()), config, } } } impl<'cfg> RegistryData for LocalRegistry<'cfg> { fn prepare(&self) -> CargoResult<()> { Ok(()) } fn index_path(&self) -> &Filesystem { &self.index_path } fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path { path.as_path_unlocked() } fn current_version(&self) -> Option<InternedString> { None } fn load( &self, root: &Path, path: &Path, data: &mut dyn FnMut(&[u8]) -> CargoResult<()>, ) -> CargoResult<()> { data(&paths::read_bytes(&root.join(path))?) } fn config(&mut self) -> CargoResult<Option<RegistryConfig>> { Ok(None) } fn update_index(&mut self) -> CargoResult<()> { let root = self.root.clone().into_path_unlocked(); if !root.is_dir() { anyhow::bail!("local registry path is not a directory: {}", root.display()) } let index_path = self.index_path.clone().into_path_unlocked(); if !index_path.is_dir() { anyhow::bail!( "local registry index path is not a directory: {}", index_path.display() ) } Ok(()) } fn download(&mut self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock> { let crate_file = format!("{}-{}.crate", pkg.name(), pkg.version()); let path = self.root.join(&crate_file).into_path_unlocked(); let mut crate_file = File::open(&path)?; let dst = format!("{}-{}", pkg.name(), pkg.version()); if self.src_path.join(dst).into_path_unlocked().exists() { return Ok(MaybeLock::Ready(crate_file)); } self.config.shell().status("Unpacking", pkg)?; let actual = Sha256::new().update_file(&crate_file)?.finish_hex(); if actual != checksum { anyhow::bail!("failed to verify the checksum of `{}`", pkg) } crate_file.seek(SeekFrom::Start(0))?; Ok(MaybeLock::Ready(crate_file)) } fn finish_download( &mut self, _pkg: PackageId, _checksum: &str, _data: &[u8], ) -> CargoResult<File> { panic!("this source doesn't download") } }
use crate::core::{InternedString, PackageId}; use crate::sources::registry::{MaybeLock, RegistryConfig, RegistryData}; use crate::util::errors::CargoResult; use crate::util::paths; use crate::util::{Config, Filesystem, Sha256}; use std::fs::File; use std::io::prelude::*; use std::io::SeekFrom; use std::path::Path; pub struct LocalRegistry<'cfg> { index_path: Filesystem, root: Filesystem, src_path: Filesystem, config: &'cfg Config, } impl<'cfg> LocalRegistry<'cfg> { pub fn new(root: &Path, config: &'cfg Config, name: &str) -> LocalRegistry<'cfg> { LocalRegistry { src_path: config.registry_source_path().join(name), index_path: Filesystem::new(root.join("index")), root: Filesystem::new(root.to_path_buf()), config, } } } impl<'cfg> RegistryData for LocalRegistry<'cfg> { fn prepare(&self) -> CargoResult<()> { Ok(()) } fn index_path(&self) -> &Filesystem { &self.index_path } fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path { path.as_path_unlocked() } fn current_version(&self) -> Option<InternedString> { None } fn load( &self, root: &Path, path: &Path, data: &mut dyn FnMut(&[u8]) -> CargoResult<()>, ) -> CargoResult<()> { data(&paths::read_bytes(&root.join(path))?) } fn config(&mut self) -> CargoResult<Option<RegistryConfig>> { Ok(None) }
fn download(&mut self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock> { let crate_file = format!("{}-{}.crate", pkg.name(), pkg.version()); let path = self.root.join(&crate_file).into_path_unlocked(); let mut crate_file = File::open(&path)?; let dst = format!("{}-{}", pkg.name(), pkg.version()); if self.src_path.join(dst).into_path_unlocked().exists() { return Ok(MaybeLock::Ready(crate_file)); } self.config.shell().status("Unpacking", pkg)?; let actual = Sha256::new().update_file(&crate_file)?.finish_hex(); if actual != checksum { anyhow::bail!("failed to verify the checksum of `{}`", pkg) } crate_file.seek(SeekFrom::Start(0))?; Ok(MaybeLock::Ready(crate_file)) } fn finish_download( &mut self, _pkg: PackageId, _checksum: &str, _data: &[u8], ) -> CargoResult<File> { panic!("this source doesn't download") } }
fn update_index(&mut self) -> CargoResult<()> { let root = self.root.clone().into_path_unlocked(); if !root.is_dir() { anyhow::bail!("local registry path is not a directory: {}", root.display()) } let index_path = self.index_path.clone().into_path_unlocked(); if !index_path.is_dir() { anyhow::bail!( "local registry index path is not a directory: {}", index_path.display() ) } Ok(()) }
function_block-full_function
[ { "content": "/// Determines the root directory where installation is done.\n\npub fn resolve_root(flag: Option<&str>, config: &Config) -> CargoResult<Filesystem> {\n\n let config_root = config.get_path(\"install.root\")?;\n\n Ok(flag\n\n .map(PathBuf::from)\n\n .or_else(|| env::var_os(\"CAR...
Rust
src/power/battery-manager/battery-cli/src/commands.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use { rustyline::{ completion::Completer, error::ReadlineError, highlight::Highlighter, hint::Hinter, Helper, }, std::{ borrow::Cow::{self, Borrowed, Owned}, fmt, str::FromStr, }, }; macro_rules! gen_commands { ($name:ident { $($variant:ident = ($val:expr, [$($arg:expr),*], $help:expr)),*, }) => { #[derive(PartialEq)] pub enum $name { $($variant),* } impl $name { pub fn variants() -> Vec<String> { let mut variants = Vec::new(); $(variants.push($val.to_string());)* variants } pub fn arguments(&self) -> &'static str { match self { $( $name::$variant => concat!($("<", $arg, "> ",)*) ),* } } #[allow(unused)] pub fn cmd_help(&self) -> &'static str { match self { $( $name::$variant => concat!($val, " ", $("<", $arg, "> ",)* "-- ", $help) ),* } } pub fn help_msg() -> &'static str { concat!("Commands:\n", $( "\t", $val, " ", $("<", $arg, "> ",)* "-- ", $help, "\n" ),*) } } impl fmt::Display for $name { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { $($name::$variant => write!(f, $val)),* , } } } impl FromStr for $name { type Err = (); fn from_str(s: &str) -> Result<$name, ()> { match s { $($val => Ok($name::$variant)),* , _ => Err(()), } } } } } gen_commands! { Command { Get = ("get", [], "Get all information of the battery state"), Set = ("set", ["<attribute1 value1> ... [attributeN valueN]", "--help"], "Set state of battery in one line | Print help message"), Reconnect = ("reconnect", [], "Connect the real battery and disconnect the simulator"), Disconnect = ("disconnect", [], "Disconnect the real battery and connect to the simulator"), Help = ("help", [], "Help message"), Exit = ("exit", [], "Exit/Close REPL"), Quit = ("quit", [], "Quit/Close REPL"), } } pub struct CmdHelper; impl CmdHelper { pub fn new() -> CmdHelper { CmdHelper {} } } impl Completer for CmdHelper { type Candidate = String; fn complete(&self, line: &str, _pos: usize) -> Result<(usize, Vec<String>), ReadlineError> { let mut variants = Vec::new(); for variant in Command::variants() { if variant.starts_with(line) { variants.push(variant) } } Ok((0, variants)) } } impl Hinter for CmdHelper { fn hint(&self, line: &str, _pos: usize) -> Option<String> { let needs_space = !line.ends_with(" "); line.trim() .parse::<Command>() .map(|cmd| { format!("{}{}", if needs_space { " " } else { "" }, cmd.arguments().to_string(),) }) .ok() } } impl Highlighter for CmdHelper { fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> { if hint.trim().is_empty() { Borrowed(hint) } else { Owned(format!("\x1b[90m{}\x1b[0m", hint)) } } } impl Helper for CmdHelper {} pub enum ReplControl { Break, Continue, }
use { rustyline::{ completion::Completer, error::ReadlineError, highlight::Highlighter, hint::Hinter, Helper, }, std::{ borrow::Cow::{self, Borrowed, Owned}, fmt, str::FromStr, }, }; macro_rules! gen_commands { ($name:ident { $($variant:ident = ($val:expr, [$($arg:expr),*], $help:expr)),*, }) => { #[derive(PartialEq)] pub enum $name { $($variant),* } impl $name { pub fn variants() -> Vec<String> { let mut variants = Vec::new(); $(variants.push($val.to_string());)* variants } pub fn arguments(&self) -> &'static str { match self { $( $name::$variant => concat!($("<", $arg, "> ",)*) ),* } } #[allow(unused)] pub fn cmd_help(&self) -> &'static str { match self { $( $name::$variant => concat!($val, " ", $("<", $arg, "> ",)* "-- ", $help) ),* } } pub fn help_msg() -> &'static str { concat!("Commands:\n", $( "\t", $val, " ", $("<", $arg, "> ",)* "-- ", $help, "\n" ),*) } } impl fmt::Display for $name { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { $($name::$variant => write!(f, $val)),* , } } } impl FromStr for $name { type Err = (); fn from_str(s: &str) -> Result<$name, ()> { match s { $($val => Ok($name::$variant)),* , _ => Err(()), } } } } } gen_commands! { Command { Get = ("get", [], "Get all information of the battery state"), Set = ("set", ["<attribute1 value1> ... [attributeN valueN]", "--help"], "Set state of battery in one line | Print help message"), Reconnect = ("reconnect", [], "Connect the real battery and disconnect the simulator"), Disconnect = ("disconnect", [], "Disconnect the real battery and connect to the simulator"), Help = ("help", [], "Help message"), Exit = ("exit", [], "Exit/Close REPL"), Quit = ("quit", [], "Quit/Close REPL"), } } pub struct CmdHelper; impl CmdHelper { pub fn new() -> CmdHelper { CmdHelper {} } } impl Completer for CmdHelper { type Candidate = String;
} impl Hinter for CmdHelper { fn hint(&self, line: &str, _pos: usize) -> Option<String> { let needs_space = !line.ends_with(" "); line.trim() .parse::<Command>() .map(|cmd| { format!("{}{}", if needs_space { " " } else { "" }, cmd.arguments().to_string(),) }) .ok() } } impl Highlighter for CmdHelper { fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> { if hint.trim().is_empty() { Borrowed(hint) } else { Owned(format!("\x1b[90m{}\x1b[0m", hint)) } } } impl Helper for CmdHelper {} pub enum ReplControl { Break, Continue, }
fn complete(&self, line: &str, _pos: usize) -> Result<(usize, Vec<String>), ReadlineError> { let mut variants = Vec::new(); for variant in Command::variants() { if variant.starts_with(line) { variants.push(variant) } } Ok((0, variants)) }
function_block-full_function
[]
Rust
bot/src/module/promotions.rs
Abendstolz/OxidizeBot
9c217e2c68bef0ff6e5ed9fb68aded6576d27186
use crate::auth; use crate::command; use crate::db; use crate::irc; use crate::module; use crate::prelude::*; use crate::utils; use chrono::Utc; pub struct Handler { enabled: settings::Var<bool>, promotions: injector::Ref<db::Promotions>, } #[async_trait] impl command::Handler for Handler { async fn handle(&self, ctx: &mut command::Context) -> Result<(), anyhow::Error> { if !self.enabled.load().await { return Ok(()); } let promotions = match self.promotions.load().await { Some(promotions) => promotions, None => return Ok(()), }; let next = command_base!(ctx, promotions, "promotion", PromoEdit); match next.as_deref() { Some("edit") => { ctx.check_scope(auth::Scope::PromoEdit).await?; let name = ctx.next_str("<name> <frequency> <template..>")?; let frequency = ctx.next_parse("<name> <frequency> <template..>")?; let template = ctx.rest_parse("<name> <frequency> <template..>")?; promotions .edit(ctx.channel(), &name, frequency, template) .await?; respond!(ctx, "Edited promo."); } None | Some(..) => { respond!( ctx, "Expected: show, list, edit, delete, enable, disable, or group." ); } } Ok(()) } } pub struct Module; #[async_trait] impl super::Module for Module { fn ty(&self) -> &'static str { "promotions" } async fn hook( &self, module::HookContext { injector, handlers, futures, sender, settings, idle, .. }: module::HookContext<'_>, ) -> Result<(), anyhow::Error> { let settings = settings.scoped("promotions"); let enabled = settings.var("enabled", false).await?; let (mut setting, frequency) = settings .stream("frequency") .or_with_else(|| utils::Duration::seconds(5 * 60)) .await?; handlers.insert( "promo", Handler { enabled: enabled.clone(), promotions: injector.var().await, }, ); let (mut promotions_stream, mut promotions) = injector.stream::<db::Promotions>().await; let sender = sender.clone(); let mut interval = tokio::time::interval(frequency.as_std()); let idle = idle.clone(); let future = async move { loop { tokio::select! { update = promotions_stream.recv() => { promotions = update; } duration = setting.recv() => { interval = tokio::time::interval(duration.as_std()); } _ = interval.tick() => { if !enabled.load().await { continue; } let promotions = match promotions.as_ref() { Some(promotions) => promotions, None => continue, }; if idle.is_idle().await { log::trace!("channel is too idle to send a promotion"); } else { let promotions = promotions.clone(); let sender = sender.clone(); if let Err(e) = promote(promotions, sender).await { log::error!("failed to send promotion: {}", e); } } } } } }; futures.push(Box::pin(future)); Ok(()) } } async fn promote(promotions: db::Promotions, sender: irc::Sender) -> Result<(), anyhow::Error> { let channel = sender.channel(); if let Some(p) = pick(promotions.list(channel).await) { let text = p.render(&PromoData { channel })?; promotions.bump_promoted_at(&*p).await?; sender.privmsg(text).await; } Ok(()) } #[derive(Debug, serde::Serialize)] struct PromoData<'a> { channel: &'a str, } fn pick(mut promotions: Vec<Arc<db::Promotion>>) -> Option<Arc<db::Promotion>> { promotions.sort_by(|a, b| a.promoted_at.cmp(&b.promoted_at)); let now = Utc::now(); for p in promotions { let promoted_at = match p.promoted_at.as_ref() { None => return Some(p), Some(promoted_at) => promoted_at, }; if now.clone().signed_duration_since(promoted_at.clone()) < p.frequency.as_chrono() { continue; } return Some(p); } None }
use crate::auth; use crate::command; use crate::db; use crate::irc; use crate::module; use crate::prelude::*; use crate::utils; use chrono::Utc; pub struct Handler { enabled: settings::Var<bool>, promotions: injector::Ref<db::Promotions>, } #[async_trait] impl command::Handler for Handler { async fn handle(&self, ctx: &mut command::Context) -> Result<(), anyhow::Error> { if !self.enabled.
>")?; let template = ctx.rest_parse("<name> <frequency> <template..>")?; promotions .edit(ctx.channel(), &name, frequency, template) .await?; respond!(ctx, "Edited promo."); } None | Some(..) => { respond!( ctx, "Expected: show, list, edit, delete, enable, disable, or group." ); } } Ok(()) } } pub struct Module; #[async_trait] impl super::Module for Module { fn ty(&self) -> &'static str { "promotions" } async fn hook( &self, module::HookContext { injector, handlers, futures, sender, settings, idle, .. }: module::HookContext<'_>, ) -> Result<(), anyhow::Error> { let settings = settings.scoped("promotions"); let enabled = settings.var("enabled", false).await?; let (mut setting, frequency) = settings .stream("frequency") .or_with_else(|| utils::Duration::seconds(5 * 60)) .await?; handlers.insert( "promo", Handler { enabled: enabled.clone(), promotions: injector.var().await, }, ); let (mut promotions_stream, mut promotions) = injector.stream::<db::Promotions>().await; let sender = sender.clone(); let mut interval = tokio::time::interval(frequency.as_std()); let idle = idle.clone(); let future = async move { loop { tokio::select! { update = promotions_stream.recv() => { promotions = update; } duration = setting.recv() => { interval = tokio::time::interval(duration.as_std()); } _ = interval.tick() => { if !enabled.load().await { continue; } let promotions = match promotions.as_ref() { Some(promotions) => promotions, None => continue, }; if idle.is_idle().await { log::trace!("channel is too idle to send a promotion"); } else { let promotions = promotions.clone(); let sender = sender.clone(); if let Err(e) = promote(promotions, sender).await { log::error!("failed to send promotion: {}", e); } } } } } }; futures.push(Box::pin(future)); Ok(()) } } async fn promote(promotions: db::Promotions, sender: irc::Sender) -> Result<(), anyhow::Error> { let channel = sender.channel(); if let Some(p) = pick(promotions.list(channel).await) { let text = p.render(&PromoData { channel })?; promotions.bump_promoted_at(&*p).await?; sender.privmsg(text).await; } Ok(()) } #[derive(Debug, serde::Serialize)] struct PromoData<'a> { channel: &'a str, } fn pick(mut promotions: Vec<Arc<db::Promotion>>) -> Option<Arc<db::Promotion>> { promotions.sort_by(|a, b| a.promoted_at.cmp(&b.promoted_at)); let now = Utc::now(); for p in promotions { let promoted_at = match p.promoted_at.as_ref() { None => return Some(p), Some(promoted_at) => promoted_at, }; if now.clone().signed_duration_since(promoted_at.clone()) < p.frequency.as_chrono() { continue; } return Some(p); } None }
load().await { return Ok(()); } let promotions = match self.promotions.load().await { Some(promotions) => promotions, None => return Ok(()), }; let next = command_base!(ctx, promotions, "promotion", PromoEdit); match next.as_deref() { Some("edit") => { ctx.check_scope(auth::Scope::PromoEdit).await?; let name = ctx.next_str("<name> <frequency> <template..>")?; let frequency = ctx.next_parse("<name> <frequency> <template..
function_block-random_span
[ { "content": "/// Extract a settings key from the context.\n\nfn key(ctx: &mut command::Context) -> Result<String> {\n\n let key = ctx.next().ok_or_else(|| respond_err!(\"Expected <key>\"))?;\n\n\n\n if key.starts_with(\"secrets/\") {\n\n respond_bail!(\"Cannot access secrets through chat!\");\n\n ...
Rust
system/kernel/src/mem/mm.rs
meg-os/maystorm
e1709de563f0d356898ad9681d29c630efea97e4
use super::slab::*; use crate::{ arch::cpu::Cpu, arch::page::*, sync::{fifo::EventQueue, semaphore::Semaphore}, system::System, task::scheduler::*, }; use alloc::{boxed::Box, sync::Arc}; use bitflags::*; use bootprot::*; use core::{ alloc::Layout, ffi::c_void, fmt::Write, mem::MaybeUninit, mem::{size_of, transmute}, num::*, slice, sync::atomic::*, }; use megstd::string::*; pub use crate::arch::page::{NonNullPhysicalAddress, PhysicalAddress}; static mut MM: MemoryManager = MemoryManager::new(); pub struct MemoryManager { reserved_memory_size: usize, page_size_min: usize, dummy_size: AtomicUsize, n_free: AtomicUsize, pairs: [MemFreePair; Self::MAX_FREE_PAIRS], slab: Option<Box<SlabAllocator>>, real_bitmap: [u32; 8], fifo: MaybeUninit<EventQueue<Arc<AsyncMmapRequest>>>, } impl MemoryManager { const MAX_FREE_PAIRS: usize = 1024; pub const PAGE_SIZE_MIN: usize = 0x1000; const fn new() -> Self { Self { reserved_memory_size: 0, page_size_min: 0x1000, dummy_size: AtomicUsize::new(0), n_free: AtomicUsize::new(0), pairs: [MemFreePair::empty(); Self::MAX_FREE_PAIRS], slab: None, real_bitmap: [0; 8], fifo: MaybeUninit::uninit(), } } pub unsafe fn init_first(info: &BootInfo) { let shared = Self::shared_mut(); let mm: &[BootMemoryMapDescriptor] = slice::from_raw_parts(info.mmap_base as usize as *const _, info.mmap_len as usize); let mut free_count = 0; let mut n_free = 0; for mem_desc in mm { if mem_desc.mem_type == BootMemoryType::Available { let size = mem_desc.page_count as usize * Self::PAGE_SIZE_MIN; shared.pairs[n_free] = MemFreePair::new(mem_desc.base as usize, size); free_count += size; } n_free += 1; } shared.n_free.store(n_free, Ordering::SeqCst); shared.reserved_memory_size = info.total_memory_size as usize - free_count; if cfg!(any(target_arch = "x86_64")) { shared.real_bitmap = info.real_bitmap; } PageManager::init(info); shared.slab = Some(Box::new(SlabAllocator::new())); shared.fifo.write(EventQueue::new(100)); } pub unsafe fn late_init() { PageManager::init_late(); SpawnOption::with_priority(Priority::Realtime).start(Self::page_thread, 0, "Page Manager"); } #[allow(dead_code)] fn page_thread(_args: usize) { let shared = Self::shared(); let fifo = unsafe { &*shared.fifo.as_ptr() }; while let Some(event) = fifo.wait_event() { let result = unsafe { PageManager::mmap(event.request) }; PageManager::broadcast_invalidate_tlb().unwrap(); event.result.store(result, Ordering::SeqCst); event.sem.signal(); } } #[inline] fn shared_mut() -> &'static mut Self { unsafe { &mut MM } } #[inline] pub fn shared() -> &'static Self { unsafe { &MM } } #[inline] pub unsafe fn mmap(request: MemoryMapRequest) -> Option<NonZeroUsize> { if Scheduler::is_enabled() { let fifo = &*Self::shared().fifo.as_ptr(); let event = Arc::new(AsyncMmapRequest { request, result: AtomicUsize::new(0), sem: Semaphore::new(0), }); let _ = fifo.post(event.clone()); event.sem.wait(); NonZeroUsize::new(event.result.load(Ordering::SeqCst)) } else { NonZeroUsize::new(PageManager::mmap(request)) } } #[inline] pub fn direct_map(pa: PhysicalAddress) -> usize { PageManager::direct_map(pa) } #[inline] pub unsafe fn invalidate_cache(p: usize) { PageManager::invalidate_cache(p); } #[inline] pub fn page_size_min(&self) -> usize { self.page_size_min } #[inline] pub fn reserved_memory_size() -> usize { let shared = Self::shared_mut(); shared.reserved_memory_size } #[inline] pub fn free_memory_size() -> usize { let shared = Self::shared_mut(); let mut total = shared.dummy_size.load(Ordering::Relaxed); total += shared .slab .as_ref() .map(|v| v.free_memory_size()) .unwrap_or(0); total += shared.pairs[..shared.n_free.load(Ordering::Relaxed)] .iter() .fold(0, |v, i| v + i.size()); total } pub unsafe fn pg_alloc(layout: Layout) -> Option<NonZeroUsize> { let shared = Self::shared_mut(); let align_m1 = Self::PAGE_SIZE_MIN - 1; let size = (layout.size() + align_m1) & !(align_m1); let n_free = shared.n_free.load(Ordering::SeqCst); for i in 0..n_free { let free_pair = &shared.pairs[i]; match free_pair.alloc(size) { Ok(v) => return Some(NonZeroUsize::new_unchecked(v)), Err(_) => (), } } None } #[inline] pub unsafe fn alloc_pages(size: usize) -> Option<NonZeroUsize> { let result = Self::pg_alloc(Layout::from_size_align_unchecked(size, Self::PAGE_SIZE_MIN)); if let Some(p) = result { let p = PageManager::direct_map(p.get() as PhysicalAddress) as *const c_void as *mut c_void; p.write_bytes(0, size); } result } pub unsafe fn zalloc(layout: Layout) -> Option<NonZeroUsize> { let shared = Self::shared_mut(); if let Some(slab) = &shared.slab { match slab.alloc(layout) { Ok(result) => return Some(result), Err(AllocationError::Unsupported) => (), Err(_err) => return None, } } Self::pg_alloc(layout) .and_then(|v| NonZeroUsize::new(PageManager::direct_map(v.get() as PhysicalAddress))) } pub unsafe fn zfree( base: Option<NonZeroUsize>, layout: Layout, ) -> Result<(), DeallocationError> { if let Some(base) = base { let ptr = base.get() as *mut u8; ptr.write_bytes(0xCC, layout.size()); let shared = Self::shared_mut(); if let Some(slab) = &shared.slab { match slab.free(base, layout) { Ok(_) => Ok(()), Err(_) => { shared.dummy_size.fetch_add(layout.size(), Ordering::SeqCst); Ok(()) } } } else { shared.dummy_size.fetch_add(layout.size(), Ordering::SeqCst); Ok(()) } } else { Ok(()) } } pub unsafe fn static_alloc_real() -> Option<NonZeroU8> { let max_real = 0xA0; let shared = Self::shared_mut(); for i in 1..max_real { let result = Cpu::interlocked_test_and_clear( &*(&shared.real_bitmap[0] as *const _ as *const AtomicUsize), i, ); if result { return NonZeroU8::new(i as u8); } } None } pub fn statistics(sb: &mut StringBuffer) { let shared = Self::shared_mut(); sb.clear(); let dummy = shared.dummy_size.load(Ordering::Relaxed); let free = shared.pairs[..shared.n_free.load(Ordering::Relaxed)] .iter() .fold(0, |v, i| v + i.size()); let total = free + dummy; writeln!( sb, "Memory {} MB Pages {} ({} + {})", System::current_device().total_memory_size() >> 20, total / Self::PAGE_SIZE_MIN, free / Self::PAGE_SIZE_MIN, dummy / Self::PAGE_SIZE_MIN, ) .unwrap(); for chunk in shared.slab.as_ref().unwrap().statistics().chunks(4) { write!(sb, "Slab").unwrap(); for item in chunk { write!(sb, " {:4}: {:4}/{:4}", item.0, item.1, item.2,).unwrap(); } writeln!(sb, "").unwrap(); } } } struct AsyncMmapRequest { request: MemoryMapRequest, result: AtomicUsize, sem: Semaphore, } #[derive(Debug, Clone, Copy)] struct MemFreePair { inner: u64, } impl MemFreePair { const PAGE_SIZE: usize = 0x1000; #[inline] pub const fn empty() -> Self { Self { inner: 0 } } #[inline] pub const fn new(base: usize, size: usize) -> Self { let base = (base / Self::PAGE_SIZE) as u64; let size = (size / Self::PAGE_SIZE) as u64; Self { inner: base | (size << 32), } } #[inline] pub fn alloc(&self, size: usize) -> Result<usize, ()> { let size = (size + Self::PAGE_SIZE - 1) / Self::PAGE_SIZE; let p: &AtomicU64 = unsafe { transmute(&self.inner) }; let mut data = p.load(Ordering::SeqCst); loop { let (base, limit) = ((data & 0xFFFF_FFFF) as usize, (data >> 32) as usize); if limit < size { return Err(()); } let new_size = limit - size; let new_data = (base as u64) | ((new_size as u64) << 32); data = match p.compare_exchange(data, new_data, Ordering::SeqCst, Ordering::Relaxed) { Ok(_) => return Ok((base + new_size) * Self::PAGE_SIZE), Err(v) => v, }; } } #[inline] fn split(&self) -> (usize, usize) { let p: &AtomicU64 = unsafe { transmute(&self.inner) }; let data = p.load(Ordering::SeqCst); ((data & 0xFFFF_FFFF) as usize, (data >> 32) as usize) } #[inline] #[allow(dead_code)] pub fn base(&self) -> usize { self.split().0 * Self::PAGE_SIZE } #[inline] pub fn size(&self) -> usize { self.split().1 * Self::PAGE_SIZE } } bitflags! { pub struct MProtect: usize { const READ = 0x4; const WRITE = 0x2; const EXEC = 0x1; const NONE = 0x0; const READ_WRITE = Self::READ.bits | Self::WRITE.bits; const READ_EXEC = Self::READ.bits | Self::WRITE.bits; } } #[derive(Debug, Copy, Clone)] pub enum AllocationError { Unexpected, OutOfMemory, InvalidArgument, Unsupported, } #[derive(Debug, Copy, Clone)] pub enum DeallocationError { Unexpected, InvalidArgument, Unsupported, } #[derive(Debug, Clone, Copy)] pub enum MemoryMapRequest { Mmio(PhysicalAddress, usize), Vram(PhysicalAddress, usize), Kernel(usize, usize, MProtect), User(usize, usize, MProtect), } impl MemoryMapRequest { #[allow(dead_code)] fn to_slice(&self) -> &[u8] { unsafe { slice::from_raw_parts(&self as *const _ as *const u8, size_of::<Self>()) } } }
use super::slab::*; use crate::{ arch::cpu::Cpu, arch::page::*, sync::{fifo::EventQueue, semaphore::Semaphore}, system::System, task::scheduler::*, }; use alloc::{boxed::Box, sync::Arc}; use bitflags::*; use bootprot::*; use core::{ alloc::Layout, ffi::c_void, fmt::Write, mem::MaybeUninit, mem::{size_of, transmute}, num::*, slice, sync::atomic::*, }; use megstd::string::*; pub use crate::arch::page::{NonNullPhysicalAddress, PhysicalAddress}; static mut MM: MemoryManager = MemoryManager::new(); pub struct MemoryManager { reserved_memory_size: usize, page_size_min: usize, dummy_size: AtomicUsize, n_free: AtomicUsize, pairs: [MemFreePair; Self::MAX_FREE_PAIRS], slab: Option<Box<SlabAllocator>>, real_bitmap: [u32; 8], fifo: MaybeUninit<EventQueue<Arc<AsyncMmapRequest>>>, } impl MemoryManager { const MAX_FREE_PAIRS: usize = 1024; pub const PAGE_SIZE_MIN: usize = 0x1000; const fn new() -> Self { Self { reserved_memory_size: 0, page_size_min: 0x1000, dummy_size: AtomicUsize::new(0), n_free: AtomicUsize::new(0), pairs: [MemFreePair::empty(); Self::MAX_FREE_PAIRS], slab: None, real_bitmap: [0; 8], fifo: MaybeUninit::uninit(), } } pub unsafe fn init_first(info: &BootInfo) { let shared = Self::shared_mut(); let mm: &[BootMemoryMapDescriptor] = slice::from_raw_parts(info.mmap_base as usize as *const _, info.mmap_len as usize); let mut free_count = 0; let mut n_free = 0; for mem_desc in mm { if mem_desc.mem_type == BootMemoryType::Available { let size = mem_desc.page_count as usize * Self::PAGE_SIZE_MIN; shared.pairs[n_free] = MemFreePair::new(mem_desc.base as usize, size); free_count += size; } n_free += 1; } shared.n_free.store(n_free, Ordering::SeqCst); shared.reserved_memory_size = info.total_memory_size as usize - free_count; if cfg!(any(target_arch = "x86_64")) { shared.real_bitmap = info.real_bitmap; } PageManager::init(info); shared.slab = Some(Box::new(SlabAllocator::new())); shared.fifo.write(EventQueue::new(100)); } pub unsafe fn late_init() { PageManager::init_late(); SpawnOption::with_priority(Priority::Realtime).start(Self::page_thread, 0, "Page Manager"); } #[allow(dead_code)] fn page_thread(_args: usize) { let shared = Self::shared(); let fifo = unsafe { &*shared.fifo.as_ptr() }; while let Some(event) = fifo.wait_event() { let result = unsafe { PageManager::mmap(event.request) }; PageManager::broadcast_invalidate_tlb().unwrap(); event.result.store(result, Ordering::SeqCst); event.sem.signal(); } } #[inline] fn shared_mut() -> &'static mut Self { unsafe { &mut MM } } #[inline] pub fn shared() -> &'static Self { unsafe { &MM } } #[inline] pub unsafe fn mmap(request: MemoryMapRequest) -> Option<NonZeroUsize> { if Scheduler::is_enabled() { let fifo = &*Self::shared().fifo.as_ptr(); let event = Arc::new(AsyncMmapRequest { request, result: AtomicUsize::new(0), sem: Semaphore::new(0), }); let _ = fifo.post(event.clone()); event.sem.wait(); NonZeroUsize::new(event.result.load(Ordering::SeqCst)) } else { NonZeroUsize::new(PageManager::mmap(request)) } } #[inline] pub fn direct_map(pa: PhysicalAddress) -> usize { PageManager::direct_map(pa) } #[inline] pub unsafe fn invalidate_cache(p: usize) { PageManager::invalidate_cache(p); } #[inline] pub fn page_size_min(&self) -> usize { self.page_size_min } #[inline] pub fn reserved_memory_size() -> usize { let shared = Self::shared_mut(); shared.reserved_memory_size } #[inline] pub fn free_memory_size() -> usize { let shared = Self::shared_mut(); let mut total = shared.dummy_size.load(Ordering::Relaxed); total += shared .slab .as_ref() .map(|v| v.free_memory_size()) .unwrap_or(0); total += shared.pairs[..shared.n_free.load(Ordering::Relaxed)] .iter() .fold(0, |v, i| v + i.size()); total } pub unsafe fn pg_alloc(layout: Layout) -> Option<NonZeroUsize> { let shared = Self::shared_mut(); let align_m1 = Self::PAGE_SIZE_MIN - 1; let size = (layout.size() + align_m1) & !(align_m1); let n_free = shared.n_free.load(Ordering::SeqCst); for i in 0..n_free { let free_pair = &shared.pairs[i]; match free_pair.alloc(size) { Ok(v) => return Some(NonZeroUsize::new_unchecked(v)), Err(_) => (), } } None } #[inline] pub unsafe fn alloc_pages(size: usize) -> Option<NonZeroUsize> { let result = Self::pg_alloc(Layout::from_size_align_unchecked(size, Self::PAGE_SIZE_MIN)); if let Some(p) = result { let p = PageManager::direct_map(p.get() as PhysicalAddress) as *const c_void as *mut c_void; p.write_bytes(0, size); } result } pub unsafe fn zalloc(layout: Layout) -> Option<NonZeroUsize> { let shared = Self::shared_mut(); if let Some(slab) = &shared.slab { match slab.alloc(layout) { Ok(result) => return Some(result), Err(AllocationError::Unsupported) => (), Err(_err) => return None, } } Self::pg_alloc(layout) .and_then(|v| NonZeroUsize::new(PageManager::direct_map(v.get() as PhysicalAddress))) } pub unsafe fn zfree( base: Option<NonZeroUsize>, layout: Layout, ) -> Result<(), DeallocationError> { if let Some(base) = base { let ptr = base.get() as *mut u8; ptr.write_bytes(0xCC, layout.size()); let shared = Self::shared_mut(); if let Some(slab) = &shared.slab { match slab.free(base, layout) { Ok(_) => Ok(()), Err(_) => { shared.dummy_size.fetch_add(layout.size(), Ordering::SeqCst); Ok(()) } } } else { shared.dummy_size.fetch_add(layout.size(), Ordering::SeqCst); Ok(()) } } else { Ok(()) } } pub unsafe fn static_alloc_real() -> Option<NonZeroU8> { let max_real = 0xA0; let shared = Self::shared_mut(); for i in 1..max_real { let result = Cpu::interlocked_test_and_clear( &*(&shared.real_bitmap[0] as *const _ as *const AtomicUsize), i, ); if result { return NonZeroU8::new(i as u8); } } None } pub fn statistics(sb: &mut StringBuffer) { let shared = Self::shared_mut(); sb.clear(); let dummy = shared.dummy_size.load(Ordering::Relaxed); let free = shared.pairs[..shared.n_free.load(Ordering::Relaxed)] .iter() .fold(0, |v, i| v + i.size()); let total = free + dummy; writeln!( sb, "Memory {} MB Pages {} ({} + {})", System::current_device().total_memory_size() >> 20, total / Self::PAGE_SIZE_MIN, free / Self::PAGE_SIZE_MIN, dummy / Self::PAGE_SIZE_MIN, ) .unwrap(); for chunk in shared.slab.as_ref().unwrap().statistics().chunks(4) { write!(sb, "Slab").unwrap(); for item in chunk { write!(sb, " {:4}: {:4}/{:4}", item.0, item.1, item.2,).unwrap(); } writeln!(sb, "").unwrap(); } } } struct AsyncMmapRequest { request: MemoryMapRequest, result: AtomicUsize, sem: Semaphore, } #[derive(Debug, Clone, Copy)] struct MemFreePair { inner: u64, } impl MemFreePair { const PAGE_SIZE: usize = 0x1000; #[inline] pub const fn empty() -> Self { Self { inner: 0 } } #[inline] pub const fn new(bas
r: base | (size << 32), } } #[inline] pub fn alloc(&self, size: usize) -> Result<usize, ()> { let size = (size + Self::PAGE_SIZE - 1) / Self::PAGE_SIZE; let p: &AtomicU64 = unsafe { transmute(&self.inner) }; let mut data = p.load(Ordering::SeqCst); loop { let (base, limit) = ((data & 0xFFFF_FFFF) as usize, (data >> 32) as usize); if limit < size { return Err(()); } let new_size = limit - size; let new_data = (base as u64) | ((new_size as u64) << 32); data = match p.compare_exchange(data, new_data, Ordering::SeqCst, Ordering::Relaxed) { Ok(_) => return Ok((base + new_size) * Self::PAGE_SIZE), Err(v) => v, }; } } #[inline] fn split(&self) -> (usize, usize) { let p: &AtomicU64 = unsafe { transmute(&self.inner) }; let data = p.load(Ordering::SeqCst); ((data & 0xFFFF_FFFF) as usize, (data >> 32) as usize) } #[inline] #[allow(dead_code)] pub fn base(&self) -> usize { self.split().0 * Self::PAGE_SIZE } #[inline] pub fn size(&self) -> usize { self.split().1 * Self::PAGE_SIZE } } bitflags! { pub struct MProtect: usize { const READ = 0x4; const WRITE = 0x2; const EXEC = 0x1; const NONE = 0x0; const READ_WRITE = Self::READ.bits | Self::WRITE.bits; const READ_EXEC = Self::READ.bits | Self::WRITE.bits; } } #[derive(Debug, Copy, Clone)] pub enum AllocationError { Unexpected, OutOfMemory, InvalidArgument, Unsupported, } #[derive(Debug, Copy, Clone)] pub enum DeallocationError { Unexpected, InvalidArgument, Unsupported, } #[derive(Debug, Clone, Copy)] pub enum MemoryMapRequest { Mmio(PhysicalAddress, usize), Vram(PhysicalAddress, usize), Kernel(usize, usize, MProtect), User(usize, usize, MProtect), } impl MemoryMapRequest { #[allow(dead_code)] fn to_slice(&self) -> &[u8] { unsafe { slice::from_raw_parts(&self as *const _ as *const u8, size_of::<Self>()) } } }
e: usize, size: usize) -> Self { let base = (base / Self::PAGE_SIZE) as u64; let size = (size / Self::PAGE_SIZE) as u64; Self { inne
function_block-random_span
[ { "content": "fn format_bytes(sb: &mut dyn Write, val: usize) -> core::fmt::Result {\n\n let kb = (val >> 10) & 0x3FF;\n\n let mb = (val >> 20) & 0x3FF;\n\n let gb = val >> 30;\n\n\n\n if gb >= 10 {\n\n // > 10G\n\n write!(sb, \"{:4}G\", gb)\n\n } else if gb >= 1 {\n\n // 1G~...
Rust
src/str/ascii.rs
LaudateCorpus1/ari
b01265230dec54b1608e6277d7be4b1a1957a11b
#[rustfmt::skip] pub trait AsciiExt { type Owned; fn is_ascii(&self) -> bool; fn to_ascii_uppercase(&self) -> Self::Owned; fn to_ascii_lowercase(&self) -> Self::Owned; fn eq_ignore_ascii_case(&self, other: &Self) -> bool; fn make_ascii_uppercase(&mut self); fn make_ascii_lowercase(&mut self); fn is_ascii_alphabetic(&self) -> bool { unimplemented!(); } fn is_ascii_uppercase(&self) -> bool { unimplemented!(); } fn is_ascii_lowercase(&self) -> bool { unimplemented!(); } fn is_ascii_alphanumeric(&self) -> bool { unimplemented!(); } fn is_ascii_digit(&self) -> bool { unimplemented!(); } fn is_ascii_hexdigit(&self) -> bool { unimplemented!(); } fn is_ascii_punctuation(&self) -> bool { unimplemented!(); } fn is_ascii_graphic(&self) -> bool { unimplemented!(); } fn is_ascii_whitespace(&self) -> bool { unimplemented!(); } fn is_ascii_control(&self) -> bool { unimplemented!(); } } macro_rules! delegate_ascii_methods { () => { #[inline] fn is_ascii (&self) -> bool { self.is_ascii() } #[inline] fn to_ascii_uppercase (&self) -> Self::Owned { self.to_ascii_uppercase() } #[inline] fn to_ascii_lowercase (&self) -> Self::Owned { self.to_ascii_lowercase() } #[inline] fn eq_ignore_ascii_case (&self, other: &Self) -> bool { self.eq_ignore_ascii_case(other) } #[inline] fn make_ascii_uppercase (&mut self) { self.make_ascii_uppercase(); } #[inline] fn make_ascii_lowercase (&mut self) { self.make_ascii_lowercase(); } } } macro_rules! delegate_ascii_ctype_methods { () => { #[inline] fn is_ascii_alphabetic (&self) -> bool { self.is_ascii_alphabetic() } #[inline] fn is_ascii_uppercase (&self) -> bool { self.is_ascii_uppercase() } #[inline] fn is_ascii_lowercase (&self) -> bool { self.is_ascii_lowercase() } #[inline] fn is_ascii_alphanumeric(&self) -> bool { self.is_ascii_alphanumeric() } #[inline] fn is_ascii_digit (&self) -> bool { self.is_ascii_digit() } #[inline] fn is_ascii_hexdigit (&self) -> bool { self.is_ascii_hexdigit() } #[inline] fn is_ascii_punctuation (&self) -> bool { self.is_ascii_punctuation() } #[inline] fn is_ascii_graphic (&self) -> bool { self.is_ascii_graphic() } #[inline] fn is_ascii_whitespace (&self) -> bool { self.is_ascii_whitespace() } #[inline] fn is_ascii_control (&self) -> bool { self.is_ascii_control() } } } impl AsciiExt for u8 { type Owned = u8; delegate_ascii_methods!(); delegate_ascii_ctype_methods!(); } impl AsciiExt for char { type Owned = char; delegate_ascii_methods!(); delegate_ascii_ctype_methods!(); } impl AsciiExt for [u8] { type Owned = Vec<u8>; delegate_ascii_methods!(); #[inline] fn is_ascii_alphabetic(&self) -> bool { self.iter().all(|b| b.is_ascii_alphabetic()) } #[inline] fn is_ascii_uppercase(&self) -> bool { self.iter().all(|b| b.is_ascii_uppercase()) } #[inline] fn is_ascii_lowercase(&self) -> bool { self.iter().all(|b| b.is_ascii_lowercase()) } #[inline] fn is_ascii_alphanumeric(&self) -> bool { self.iter().all(|b| b.is_ascii_alphanumeric()) } #[inline] fn is_ascii_digit(&self) -> bool { self.iter().all(|b| b.is_ascii_digit()) } #[inline] fn is_ascii_hexdigit(&self) -> bool { self.iter().all(|b| b.is_ascii_hexdigit()) } #[inline] fn is_ascii_punctuation(&self) -> bool { self.iter().all(|b| b.is_ascii_punctuation()) } #[inline] fn is_ascii_graphic(&self) -> bool { self.iter().all(|b| b.is_ascii_graphic()) } #[inline] fn is_ascii_whitespace(&self) -> bool { self.iter().all(|b| b.is_ascii_whitespace()) } #[inline] fn is_ascii_control(&self) -> bool { self.iter().all(|b| b.is_ascii_control()) } } impl AsciiExt for str { type Owned = String; delegate_ascii_methods!(); #[inline] fn is_ascii_alphabetic(&self) -> bool { self.bytes().all(|b| b.is_ascii_alphabetic()) } #[inline] fn is_ascii_uppercase(&self) -> bool { self.bytes().all(|b| b.is_ascii_uppercase()) } #[inline] fn is_ascii_lowercase(&self) -> bool { self.bytes().all(|b| b.is_ascii_lowercase()) } #[inline] fn is_ascii_alphanumeric(&self) -> bool { self.bytes().all(|b| b.is_ascii_alphanumeric()) } #[inline] fn is_ascii_digit(&self) -> bool { self.bytes().all(|b| b.is_ascii_digit()) } #[inline] fn is_ascii_hexdigit(&self) -> bool { self.bytes().all(|b| b.is_ascii_hexdigit()) } #[inline] fn is_ascii_punctuation(&self) -> bool { self.bytes().all(|b| b.is_ascii_punctuation()) } #[inline] fn is_ascii_graphic(&self) -> bool { self.bytes().all(|b| b.is_ascii_graphic()) } #[inline] fn is_ascii_whitespace(&self) -> bool { self.bytes().all(|b| b.is_ascii_whitespace()) } #[inline] fn is_ascii_control(&self) -> bool { self.bytes().all(|b| b.is_ascii_control()) } }
#[rustfmt::skip] pub trait AsciiExt { type Owned; fn is_ascii(&self) -> bool; fn to_ascii_uppercase(&self) -> Self::Owned; fn to_ascii_lowercase(&self) -> Self::Owned; fn eq_ignore_ascii_case(&self, other: &Self) -> bool; fn make_ascii_uppercase(&mut self); fn make_ascii_lowercase(&mut self); fn is_ascii_alphabetic(&self) -> bool { unimplemented!(); } fn is_ascii_uppercase(&self) -> bool { unimplemented!(); } fn is_ascii_lowercase(&self) -> bool { unimplemented!(); } fn is_ascii_alphanumeric(&self) -> bool { unimplemented!(); } fn is_ascii_digit(&self) -> bool { unimplemented!(); } fn is_ascii_hexdigit(&self) -> bool { unimplemented!(); } fn is_ascii_punctuation(&self) -> bool { unimplemented!(); } fn is_ascii_graphic(&self) -> bool { unimplemented!(); } fn is_ascii_whitespace(&self) -> bool { unimplemented!(); } fn is_ascii_control(&self) -> bool { unimplemented!(); } } macro_rules! delegate_ascii_methods { () => { #[inline] fn is_ascii (&self) -> bool { self.is_ascii() } #[inline] fn to_ascii_uppercase (&self) -> Self::Owned { self.to_ascii_uppercase() } #[inline] fn to_ascii_lowercase (&self) -> Self::Owned { self.to_ascii_lowercase() } #[inline] fn eq_ignore_ascii_case (&self, other: &Self) -> bool { self.eq_ignore_ascii_case(other) } #[inline] fn make_ascii_uppercase (&mut self) { self.make_ascii_uppercase(); } #[inline] fn make_ascii_lowercase (&mut self) { self.make_ascii_lowercase(); } } } macro_rules! delegate_ascii_ctype_methods { () => { #[inline] fn is_ascii_alphabetic (&self) -> bool { self.is_ascii_alphabetic() } #[inline] fn is_ascii_uppercase (&self) -> bool { self.is_ascii_uppercase() } #[inline] fn is_ascii_lowercase (&self) -> bool { self.is_ascii_lowercase() } #[inline] fn is_ascii_alphanumeric(&self) -> bool { self.is_ascii_alphanu
alphanumeric(&self) -> bool { self.iter().all(|b| b.is_ascii_alphanumeric()) } #[inline] fn is_ascii_digit(&self) -> bool { self.iter().all(|b| b.is_ascii_digit()) } #[inline] fn is_ascii_hexdigit(&self) -> bool { self.iter().all(|b| b.is_ascii_hexdigit()) } #[inline] fn is_ascii_punctuation(&self) -> bool { self.iter().all(|b| b.is_ascii_punctuation()) } #[inline] fn is_ascii_graphic(&self) -> bool { self.iter().all(|b| b.is_ascii_graphic()) } #[inline] fn is_ascii_whitespace(&self) -> bool { self.iter().all(|b| b.is_ascii_whitespace()) } #[inline] fn is_ascii_control(&self) -> bool { self.iter().all(|b| b.is_ascii_control()) } } impl AsciiExt for str { type Owned = String; delegate_ascii_methods!(); #[inline] fn is_ascii_alphabetic(&self) -> bool { self.bytes().all(|b| b.is_ascii_alphabetic()) } #[inline] fn is_ascii_uppercase(&self) -> bool { self.bytes().all(|b| b.is_ascii_uppercase()) } #[inline] fn is_ascii_lowercase(&self) -> bool { self.bytes().all(|b| b.is_ascii_lowercase()) } #[inline] fn is_ascii_alphanumeric(&self) -> bool { self.bytes().all(|b| b.is_ascii_alphanumeric()) } #[inline] fn is_ascii_digit(&self) -> bool { self.bytes().all(|b| b.is_ascii_digit()) } #[inline] fn is_ascii_hexdigit(&self) -> bool { self.bytes().all(|b| b.is_ascii_hexdigit()) } #[inline] fn is_ascii_punctuation(&self) -> bool { self.bytes().all(|b| b.is_ascii_punctuation()) } #[inline] fn is_ascii_graphic(&self) -> bool { self.bytes().all(|b| b.is_ascii_graphic()) } #[inline] fn is_ascii_whitespace(&self) -> bool { self.bytes().all(|b| b.is_ascii_whitespace()) } #[inline] fn is_ascii_control(&self) -> bool { self.bytes().all(|b| b.is_ascii_control()) } }
meric() } #[inline] fn is_ascii_digit (&self) -> bool { self.is_ascii_digit() } #[inline] fn is_ascii_hexdigit (&self) -> bool { self.is_ascii_hexdigit() } #[inline] fn is_ascii_punctuation (&self) -> bool { self.is_ascii_punctuation() } #[inline] fn is_ascii_graphic (&self) -> bool { self.is_ascii_graphic() } #[inline] fn is_ascii_whitespace (&self) -> bool { self.is_ascii_whitespace() } #[inline] fn is_ascii_control (&self) -> bool { self.is_ascii_control() } } } impl AsciiExt for u8 { type Owned = u8; delegate_ascii_methods!(); delegate_ascii_ctype_methods!(); } impl AsciiExt for char { type Owned = char; delegate_ascii_methods!(); delegate_ascii_ctype_methods!(); } impl AsciiExt for [u8] { type Owned = Vec<u8>; delegate_ascii_methods!(); #[inline] fn is_ascii_alphabetic(&self) -> bool { self.iter().all(|b| b.is_ascii_alphabetic()) } #[inline] fn is_ascii_uppercase(&self) -> bool { self.iter().all(|b| b.is_ascii_uppercase()) } #[inline] fn is_ascii_lowercase(&self) -> bool { self.iter().all(|b| b.is_ascii_lowercase()) } #[inline] fn is_ascii_
random
[ { "content": "/// returns true if `ari` has been initialized.\n\npub fn initialized() -> bool {\n\n INITIALIZED.state() != OnceState::Done\n\n}\n\n\n\n/// keep `x`, preventing llvm from optimizing it away.\n", "file_path": "src/core/mod.rs", "rank": 0, "score": 147101.8094612884 }, { "con...
Rust
arch/rv32i/src/syscall.rs
wjakobczyk/tock
af1efe87f3f52f9dc923f0ca936091f7681ce59a
use core::fmt::Write; use crate::csr::mcause; use kernel; use kernel::syscall::ContextSwitchReason; #[derive(Default)] #[repr(C)] pub struct Riscv32iStoredState { regs: [usize; 31], pc: usize, mcause: usize, mtval: usize, } const R_RA: usize = 0; const R_SP: usize = 1; const R_A0: usize = 9; const R_A1: usize = 10; const R_A2: usize = 11; const R_A3: usize = 12; const R_A4: usize = 13; pub struct SysCall(()); impl SysCall { pub const unsafe fn new() -> SysCall { SysCall(()) } } impl kernel::syscall::UserspaceKernelBoundary for SysCall { type StoredState = Riscv32iStoredState; unsafe fn initialize_process( &self, stack_pointer: *const usize, _stack_size: usize, state: &mut Self::StoredState, ) -> Result<*const usize, ()> { state.regs.iter_mut().for_each(|x| *x = 0); state.pc = 0; state.mcause = 0; state.regs[R_SP] = stack_pointer as usize; Ok(stack_pointer as *mut usize) } unsafe fn set_syscall_return_value( &self, _stack_pointer: *const usize, state: &mut Self::StoredState, return_value: isize, ) { state.regs[R_A0] = return_value as usize; } unsafe fn set_process_function( &self, stack_pointer: *const usize, _remaining_stack_memory: usize, state: &mut Riscv32iStoredState, callback: kernel::procs::FunctionCall, ) -> Result<*mut usize, *mut usize> { state.regs[R_A0] = callback.argument0; state.regs[R_A1] = callback.argument1; state.regs[R_A2] = callback.argument2; state.regs[R_A3] = callback.argument3; state.regs[R_RA] = state.pc; state.pc = callback.pc; Ok(stack_pointer as *mut usize) } #[cfg(not(any(target_arch = "riscv32", target_os = "none")))] unsafe fn switch_to_process( &self, _stack_pointer: *const usize, _state: &mut Riscv32iStoredState, ) -> (*mut usize, ContextSwitchReason) { let _cause = mcause::Trap::from(_state.mcause); let _arg4 = _state.regs[R_A4]; unimplemented!() } #[cfg(all(target_arch = "riscv32", target_os = "none"))] unsafe fn switch_to_process( &self, _stack_pointer: *const usize, state: &mut Riscv32iStoredState, ) -> (*mut usize, ContextSwitchReason) { llvm_asm! (" // Before switching to the app we need to save the kernel registers to // the kernel stack. We then save the stack pointer in the mscratch // CSR (0x340) so we can retrieve it after returning to the kernel // from the app. // // A few values get saved to the kernel stack, including an app // register temporarily after entering the trap handler. Here is a // memory map to make it easier to keep track: // // ``` // 34*4(sp): <- original stack pointer // 33*4(sp): // 32*4(sp): x31 // 31*4(sp): x30 // 30*4(sp): x29 // 29*4(sp): x28 // 28*4(sp): x27 // 27*4(sp): x26 // 26*4(sp): x25 // 25*4(sp): x24 // 24*4(sp): x23 // 23*4(sp): x22 // 22*4(sp): x21 // 21*4(sp): x20 // 20*4(sp): x19 // 19*4(sp): x18 // 18*4(sp): x17 // 17*4(sp): x16 // 16*4(sp): x15 // 15*4(sp): x14 // 14*4(sp): x13 // 13*4(sp): x12 // 12*4(sp): x11 // 11*4(sp): x10 // 10*4(sp): x9 // 9*4(sp): x8 // 8*4(sp): x7 // 7*4(sp): x6 // 6*4(sp): x5 // 5*4(sp): x4 // 4*4(sp): x3 // 3*4(sp): x1 // 2*4(sp): _return_to_kernel (address to resume after trap) // 1*4(sp): *state (Per-process StoredState struct) // 0*4(sp): app s0 <- new stack pointer // ``` addi sp, sp, -34*4 // Move the stack pointer down to make room. sw x1, 3*4(sp) // Save all of the registers on the kernel stack. sw x3, 4*4(sp) sw x4, 5*4(sp) sw x5, 6*4(sp) sw x6, 7*4(sp) sw x7, 8*4(sp) sw x8, 9*4(sp) sw x9, 10*4(sp) sw x10, 11*4(sp) sw x11, 12*4(sp) sw x12, 13*4(sp) sw x13, 14*4(sp) sw x14, 15*4(sp) sw x15, 16*4(sp) sw x16, 17*4(sp) sw x17, 18*4(sp) sw x18, 19*4(sp) sw x19, 20*4(sp) sw x20, 21*4(sp) sw x21, 22*4(sp) sw x22, 23*4(sp) sw x23, 24*4(sp) sw x24, 25*4(sp) sw x25, 26*4(sp) sw x26, 27*4(sp) sw x27, 28*4(sp) sw x28, 29*4(sp) sw x29, 30*4(sp) sw x30, 31*4(sp) sw x31, 32*4(sp) sw $0, 1*4(sp) // Store process state pointer on stack as well. // We need to have the available for after the app // returns to the kernel so we can store its // registers. // From here on we can't allow the CPU to take interrupts // anymore, as that might result in the trap handler // believing that a context switch to userspace already // occurred (as mscratch is non-zero). Restore the userspace // state fully prior to enabling interrupts again // (implicitly using mret). // // If this is executed _after_ setting mscratch, this result // in the race condition of [PR // 2308](https://github.com/tock/tock/pull/2308) // Therefore, clear the following bits in mstatus first: // 0x00000008 -> bit 3 -> MIE (disabling interrupts here) // + 0x00001800 -> bits 11,12 -> MPP (switch to usermode on mret) li t0, 0x00001808 csrrc x0, 0x300, t0 // clear bits in mstatus, don't care about read // Afterwards, set the following bits in mstatus: // 0x00000080 -> bit 7 -> MPIE (enable interrupts on mret) li t0, 0x00000080 csrrs x0, 0x300, t0 // set bits in mstatus, don't care about read // Store the address to jump back to on the stack so that the trap // handler knows where to return to after the app stops executing. lui t0, %hi(_return_to_kernel) addi t0, t0, %lo(_return_to_kernel) sw t0, 2*4(sp) csrw 0x340, sp // Save stack pointer in mscratch. This allows // us to find it when the app returns back to // the kernel. // We have to set the mepc CSR with the PC we want the app to start // executing at. This has been saved in Riscv32iStoredState for us // (either when the app returned back to the kernel or in the // `set_process_function()` function). lw t0, 31*4($0) // Retrieve the PC from Riscv32iStoredState csrw 0x341, t0 // Set mepc CSR. This is the PC we want to go to. // Restore all of the app registers from what we saved. If this is the // first time running the app then most of these values are // irrelevant, However we do need to set the four arguments to the // `_start_ function in the app. If the app has been executing then this // allows the app to correctly resume. mv t0, $0 // Save the state pointer to a specific register. lw x1, 0*4(t0) // ra lw x2, 1*4(t0) // sp lw x3, 2*4(t0) // gp lw x4, 3*4(t0) // tp lw x6, 5*4(t0) // t1 lw x7, 6*4(t0) // t2 lw x8, 7*4(t0) // s0,fp lw x9, 8*4(t0) // s1 lw x10, 9*4(t0) // a0 lw x11, 10*4(t0) // a1 lw x12, 11*4(t0) // a2 lw x13, 12*4(t0) // a3 lw x14, 13*4(t0) // a4 lw x15, 14*4(t0) // a5 lw x16, 15*4(t0) // a6 lw x17, 16*4(t0) // a7 lw x18, 17*4(t0) // s2 lw x19, 18*4(t0) // s3 lw x20, 19*4(t0) // s4 lw x21, 20*4(t0) // s5 lw x22, 21*4(t0) // s6 lw x23, 22*4(t0) // s7 lw x24, 23*4(t0) // s8 lw x25, 24*4(t0) // s9 lw x26, 25*4(t0) // s10 lw x27, 26*4(t0) // s11 lw x28, 27*4(t0) // t3 lw x29, 28*4(t0) // t4 lw x30, 29*4(t0) // t5 lw x31, 30*4(t0) // t6 lw x5, 4*4(t0) // t0. Do last since we overwrite our pointer. // Call mret to jump to where mepc points, switch to user mode, and // start running the app. mret // This is where the trap handler jumps back to after the app stops // executing. _return_to_kernel: // We have already stored the app registers in the trap handler. We // can restore the kernel registers before resuming kernel code. lw x1, 3*4(sp) lw x3, 4*4(sp) lw x4, 5*4(sp) lw x5, 6*4(sp) lw x6, 7*4(sp) lw x7, 8*4(sp) lw x8, 9*4(sp) lw x9, 10*4(sp) lw x10, 11*4(sp) lw x11, 12*4(sp) lw x12, 13*4(sp) lw x13, 14*4(sp) lw x14, 15*4(sp) lw x15, 16*4(sp) lw x16, 17*4(sp) lw x17, 18*4(sp) lw x18, 19*4(sp) lw x19, 20*4(sp) lw x20, 21*4(sp) lw x21, 22*4(sp) lw x22, 23*4(sp) lw x23, 24*4(sp) lw x24, 25*4(sp) lw x25, 26*4(sp) lw x26, 27*4(sp) lw x27, 28*4(sp) lw x28, 29*4(sp) lw x29, 30*4(sp) lw x30, 31*4(sp) lw x31, 32*4(sp) addi sp, sp, 34*4 // Reset kernel stack pointer " : : "r"(state as *mut Riscv32iStoredState) : "memory" : "volatile"); let ret = match mcause::Trap::from(state.mcause) { mcause::Trap::Interrupt(_intr) => { ContextSwitchReason::Interrupted } mcause::Trap::Exception(excp) => { match excp { mcause::Exception::UserEnvCall | mcause::Exception::MachineEnvCall => { state.pc += 4; let syscall = kernel::syscall::Syscall::from_register_arguments( state.regs[R_A0] as u8, state.regs[R_A1], state.regs[R_A2], state.regs[R_A3], state.regs[R_A4], ); match syscall { Some(s) => ContextSwitchReason::SyscallFired { syscall: s }, None => ContextSwitchReason::Fault, } } _ => { ContextSwitchReason::Fault } } } }; let new_stack_pointer = state.regs[R_SP]; (new_stack_pointer as *mut usize, ret) } unsafe fn print_context( &self, stack_pointer: *const usize, state: &Riscv32iStoredState, writer: &mut dyn Write, ) { let _ = writer.write_fmt(format_args!( "\ \r\n R0 : {:#010X} R16: {:#010X}\ \r\n R1 : {:#010X} R17: {:#010X}\ \r\n R2 : {:#010X} R18: {:#010X}\ \r\n R3 : {:#010X} R19: {:#010X}\ \r\n R4 : {:#010X} R20: {:#010X}\ \r\n R5 : {:#010X} R21: {:#010X}\ \r\n R6 : {:#010X} R22: {:#010X}\ \r\n R7 : {:#010X} R23: {:#010X}\ \r\n R8 : {:#010X} R24: {:#010X}\ \r\n R9 : {:#010X} R25: {:#010X}\ \r\n R10: {:#010X} R26: {:#010X}\ \r\n R11: {:#010X} R27: {:#010X}\ \r\n R12: {:#010X} R28: {:#010X}\ \r\n R13: {:#010X} R29: {:#010X}\ \r\n R14: {:#010X} R30: {:#010X}\ \r\n R15: {:#010X} R31: {:#010X}\ \r\n PC : {:#010X} SP : {:#010X}\ \r\n\ \r\n mcause: {:#010X} (", 0, state.regs[15], state.regs[0], state.regs[16], state.regs[1], state.regs[17], state.regs[2], state.regs[18], state.regs[3], state.regs[19], state.regs[4], state.regs[20], state.regs[5], state.regs[21], state.regs[6], state.regs[22], state.regs[7], state.regs[23], state.regs[8], state.regs[24], state.regs[9], state.regs[25], state.regs[10], state.regs[26], state.regs[11], state.regs[27], state.regs[12], state.regs[28], state.regs[13], state.regs[29], state.regs[14], state.regs[30], state.pc, stack_pointer as usize, state.mcause, )); crate::print_mcause(mcause::Trap::from(state.mcause), writer); let _ = writer.write_fmt(format_args!( ")\ \r\n mtval: {:#010X}\ \r\n\r\n", state.mtval, )); } }
use core::fmt::Write; use crate::csr::mcause; use kernel; use kernel::syscall::ContextSwitchReason; #[derive(Default)] #[repr(C)] pub struct Riscv32iStoredState { regs: [usize; 31], pc: usize, mcause: usize, mtval: usize, } const R_RA: usize = 0; const R_SP: usize = 1; const R_A0: usize = 9; const R_A1: usize = 10; const R_A2: usize = 11; const R_A3: usize = 12; const R_A4: usize = 13; pub struct SysCall(()); impl SysCall { pub const unsafe fn new() -> SysCall { SysCall(()) } } impl kernel::syscall::UserspaceKernelBoundary for SysCall { type StoredState = Riscv32iStoredState;
unsafe fn set_syscall_return_value( &self, _stack_pointer: *const usize, state: &mut Self::StoredState, return_value: isize, ) { state.regs[R_A0] = return_value as usize; } unsafe fn set_process_function( &self, stack_pointer: *const usize, _remaining_stack_memory: usize, state: &mut Riscv32iStoredState, callback: kernel::procs::FunctionCall, ) -> Result<*mut usize, *mut usize> { state.regs[R_A0] = callback.argument0; state.regs[R_A1] = callback.argument1; state.regs[R_A2] = callback.argument2; state.regs[R_A3] = callback.argument3; state.regs[R_RA] = state.pc; state.pc = callback.pc; Ok(stack_pointer as *mut usize) } #[cfg(not(any(target_arch = "riscv32", target_os = "none")))] unsafe fn switch_to_process( &self, _stack_pointer: *const usize, _state: &mut Riscv32iStoredState, ) -> (*mut usize, ContextSwitchReason) { let _cause = mcause::Trap::from(_state.mcause); let _arg4 = _state.regs[R_A4]; unimplemented!() } #[cfg(all(target_arch = "riscv32", target_os = "none"))] unsafe fn switch_to_process( &self, _stack_pointer: *const usize, state: &mut Riscv32iStoredState, ) -> (*mut usize, ContextSwitchReason) { llvm_asm! (" // Before switching to the app we need to save the kernel registers to // the kernel stack. We then save the stack pointer in the mscratch // CSR (0x340) so we can retrieve it after returning to the kernel // from the app. // // A few values get saved to the kernel stack, including an app // register temporarily after entering the trap handler. Here is a // memory map to make it easier to keep track: // // ``` // 34*4(sp): <- original stack pointer // 33*4(sp): // 32*4(sp): x31 // 31*4(sp): x30 // 30*4(sp): x29 // 29*4(sp): x28 // 28*4(sp): x27 // 27*4(sp): x26 // 26*4(sp): x25 // 25*4(sp): x24 // 24*4(sp): x23 // 23*4(sp): x22 // 22*4(sp): x21 // 21*4(sp): x20 // 20*4(sp): x19 // 19*4(sp): x18 // 18*4(sp): x17 // 17*4(sp): x16 // 16*4(sp): x15 // 15*4(sp): x14 // 14*4(sp): x13 // 13*4(sp): x12 // 12*4(sp): x11 // 11*4(sp): x10 // 10*4(sp): x9 // 9*4(sp): x8 // 8*4(sp): x7 // 7*4(sp): x6 // 6*4(sp): x5 // 5*4(sp): x4 // 4*4(sp): x3 // 3*4(sp): x1 // 2*4(sp): _return_to_kernel (address to resume after trap) // 1*4(sp): *state (Per-process StoredState struct) // 0*4(sp): app s0 <- new stack pointer // ``` addi sp, sp, -34*4 // Move the stack pointer down to make room. sw x1, 3*4(sp) // Save all of the registers on the kernel stack. sw x3, 4*4(sp) sw x4, 5*4(sp) sw x5, 6*4(sp) sw x6, 7*4(sp) sw x7, 8*4(sp) sw x8, 9*4(sp) sw x9, 10*4(sp) sw x10, 11*4(sp) sw x11, 12*4(sp) sw x12, 13*4(sp) sw x13, 14*4(sp) sw x14, 15*4(sp) sw x15, 16*4(sp) sw x16, 17*4(sp) sw x17, 18*4(sp) sw x18, 19*4(sp) sw x19, 20*4(sp) sw x20, 21*4(sp) sw x21, 22*4(sp) sw x22, 23*4(sp) sw x23, 24*4(sp) sw x24, 25*4(sp) sw x25, 26*4(sp) sw x26, 27*4(sp) sw x27, 28*4(sp) sw x28, 29*4(sp) sw x29, 30*4(sp) sw x30, 31*4(sp) sw x31, 32*4(sp) sw $0, 1*4(sp) // Store process state pointer on stack as well. // We need to have the available for after the app // returns to the kernel so we can store its // registers. // From here on we can't allow the CPU to take interrupts // anymore, as that might result in the trap handler // believing that a context switch to userspace already // occurred (as mscratch is non-zero). Restore the userspace // state fully prior to enabling interrupts again // (implicitly using mret). // // If this is executed _after_ setting mscratch, this result // in the race condition of [PR // 2308](https://github.com/tock/tock/pull/2308) // Therefore, clear the following bits in mstatus first: // 0x00000008 -> bit 3 -> MIE (disabling interrupts here) // + 0x00001800 -> bits 11,12 -> MPP (switch to usermode on mret) li t0, 0x00001808 csrrc x0, 0x300, t0 // clear bits in mstatus, don't care about read // Afterwards, set the following bits in mstatus: // 0x00000080 -> bit 7 -> MPIE (enable interrupts on mret) li t0, 0x00000080 csrrs x0, 0x300, t0 // set bits in mstatus, don't care about read // Store the address to jump back to on the stack so that the trap // handler knows where to return to after the app stops executing. lui t0, %hi(_return_to_kernel) addi t0, t0, %lo(_return_to_kernel) sw t0, 2*4(sp) csrw 0x340, sp // Save stack pointer in mscratch. This allows // us to find it when the app returns back to // the kernel. // We have to set the mepc CSR with the PC we want the app to start // executing at. This has been saved in Riscv32iStoredState for us // (either when the app returned back to the kernel or in the // `set_process_function()` function). lw t0, 31*4($0) // Retrieve the PC from Riscv32iStoredState csrw 0x341, t0 // Set mepc CSR. This is the PC we want to go to. // Restore all of the app registers from what we saved. If this is the // first time running the app then most of these values are // irrelevant, However we do need to set the four arguments to the // `_start_ function in the app. If the app has been executing then this // allows the app to correctly resume. mv t0, $0 // Save the state pointer to a specific register. lw x1, 0*4(t0) // ra lw x2, 1*4(t0) // sp lw x3, 2*4(t0) // gp lw x4, 3*4(t0) // tp lw x6, 5*4(t0) // t1 lw x7, 6*4(t0) // t2 lw x8, 7*4(t0) // s0,fp lw x9, 8*4(t0) // s1 lw x10, 9*4(t0) // a0 lw x11, 10*4(t0) // a1 lw x12, 11*4(t0) // a2 lw x13, 12*4(t0) // a3 lw x14, 13*4(t0) // a4 lw x15, 14*4(t0) // a5 lw x16, 15*4(t0) // a6 lw x17, 16*4(t0) // a7 lw x18, 17*4(t0) // s2 lw x19, 18*4(t0) // s3 lw x20, 19*4(t0) // s4 lw x21, 20*4(t0) // s5 lw x22, 21*4(t0) // s6 lw x23, 22*4(t0) // s7 lw x24, 23*4(t0) // s8 lw x25, 24*4(t0) // s9 lw x26, 25*4(t0) // s10 lw x27, 26*4(t0) // s11 lw x28, 27*4(t0) // t3 lw x29, 28*4(t0) // t4 lw x30, 29*4(t0) // t5 lw x31, 30*4(t0) // t6 lw x5, 4*4(t0) // t0. Do last since we overwrite our pointer. // Call mret to jump to where mepc points, switch to user mode, and // start running the app. mret // This is where the trap handler jumps back to after the app stops // executing. _return_to_kernel: // We have already stored the app registers in the trap handler. We // can restore the kernel registers before resuming kernel code. lw x1, 3*4(sp) lw x3, 4*4(sp) lw x4, 5*4(sp) lw x5, 6*4(sp) lw x6, 7*4(sp) lw x7, 8*4(sp) lw x8, 9*4(sp) lw x9, 10*4(sp) lw x10, 11*4(sp) lw x11, 12*4(sp) lw x12, 13*4(sp) lw x13, 14*4(sp) lw x14, 15*4(sp) lw x15, 16*4(sp) lw x16, 17*4(sp) lw x17, 18*4(sp) lw x18, 19*4(sp) lw x19, 20*4(sp) lw x20, 21*4(sp) lw x21, 22*4(sp) lw x22, 23*4(sp) lw x23, 24*4(sp) lw x24, 25*4(sp) lw x25, 26*4(sp) lw x26, 27*4(sp) lw x27, 28*4(sp) lw x28, 29*4(sp) lw x29, 30*4(sp) lw x30, 31*4(sp) lw x31, 32*4(sp) addi sp, sp, 34*4 // Reset kernel stack pointer " : : "r"(state as *mut Riscv32iStoredState) : "memory" : "volatile"); let ret = match mcause::Trap::from(state.mcause) { mcause::Trap::Interrupt(_intr) => { ContextSwitchReason::Interrupted } mcause::Trap::Exception(excp) => { match excp { mcause::Exception::UserEnvCall | mcause::Exception::MachineEnvCall => { state.pc += 4; let syscall = kernel::syscall::Syscall::from_register_arguments( state.regs[R_A0] as u8, state.regs[R_A1], state.regs[R_A2], state.regs[R_A3], state.regs[R_A4], ); match syscall { Some(s) => ContextSwitchReason::SyscallFired { syscall: s }, None => ContextSwitchReason::Fault, } } _ => { ContextSwitchReason::Fault } } } }; let new_stack_pointer = state.regs[R_SP]; (new_stack_pointer as *mut usize, ret) } unsafe fn print_context( &self, stack_pointer: *const usize, state: &Riscv32iStoredState, writer: &mut dyn Write, ) { let _ = writer.write_fmt(format_args!( "\ \r\n R0 : {:#010X} R16: {:#010X}\ \r\n R1 : {:#010X} R17: {:#010X}\ \r\n R2 : {:#010X} R18: {:#010X}\ \r\n R3 : {:#010X} R19: {:#010X}\ \r\n R4 : {:#010X} R20: {:#010X}\ \r\n R5 : {:#010X} R21: {:#010X}\ \r\n R6 : {:#010X} R22: {:#010X}\ \r\n R7 : {:#010X} R23: {:#010X}\ \r\n R8 : {:#010X} R24: {:#010X}\ \r\n R9 : {:#010X} R25: {:#010X}\ \r\n R10: {:#010X} R26: {:#010X}\ \r\n R11: {:#010X} R27: {:#010X}\ \r\n R12: {:#010X} R28: {:#010X}\ \r\n R13: {:#010X} R29: {:#010X}\ \r\n R14: {:#010X} R30: {:#010X}\ \r\n R15: {:#010X} R31: {:#010X}\ \r\n PC : {:#010X} SP : {:#010X}\ \r\n\ \r\n mcause: {:#010X} (", 0, state.regs[15], state.regs[0], state.regs[16], state.regs[1], state.regs[17], state.regs[2], state.regs[18], state.regs[3], state.regs[19], state.regs[4], state.regs[20], state.regs[5], state.regs[21], state.regs[6], state.regs[22], state.regs[7], state.regs[23], state.regs[8], state.regs[24], state.regs[9], state.regs[25], state.regs[10], state.regs[26], state.regs[11], state.regs[27], state.regs[12], state.regs[28], state.regs[13], state.regs[29], state.regs[14], state.regs[30], state.pc, stack_pointer as usize, state.mcause, )); crate::print_mcause(mcause::Trap::from(state.mcause), writer); let _ = writer.write_fmt(format_args!( ")\ \r\n mtval: {:#010X}\ \r\n\r\n", state.mtval, )); } }
unsafe fn initialize_process( &self, stack_pointer: *const usize, _stack_size: usize, state: &mut Self::StoredState, ) -> Result<*const usize, ()> { state.regs.iter_mut().for_each(|x| *x = 0); state.pc = 0; state.mcause = 0; state.regs[R_SP] = stack_pointer as usize; Ok(stack_pointer as *mut usize) }
function_block-full_function
[ { "content": "/// State that is stored in each process's grant region to support IPC.\n\nstruct IPCData<const NUM_PROCS: usize> {\n\n /// An array of app slices that this application has shared with other\n\n /// applications.\n\n shared_memory: [Option<AppSlice<Shared, u8>>; NUM_PROCS],\n\n /// An ...
Rust
src/rtc0.rs
cvetaevvitaliy/nrf52840-pac
bf07243a5a043883d915999f0f8ccd6cbf6229b8
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Start RTC COUNTER"] pub tasks_start: TASKS_START, #[doc = "0x04 - Stop RTC COUNTER"] pub tasks_stop: TASKS_STOP, #[doc = "0x08 - Clear RTC COUNTER"] pub tasks_clear: TASKS_CLEAR, #[doc = "0x0c - Set COUNTER to 0xFFFFF0"] pub tasks_trigovrflw: TASKS_TRIGOVRFLW, _reserved0: [u8; 240usize], #[doc = "0x100 - Event on COUNTER increment"] pub events_tick: EVENTS_TICK, #[doc = "0x104 - Event on COUNTER overflow"] pub events_ovrflw: EVENTS_OVRFLW, _reserved1: [u8; 56usize], #[doc = "0x140 - Description collection\\[n\\]: Compare event on CC\\[n\\] match"] pub events_compare: [EVENTS_COMPARE; 4], _reserved2: [u8; 436usize], #[doc = "0x304 - Enable interrupt"] pub intenset: INTENSET, #[doc = "0x308 - Disable interrupt"] pub intenclr: INTENCLR, _reserved3: [u8; 52usize], #[doc = "0x340 - Enable or disable event routing"] pub evten: EVTEN, #[doc = "0x344 - Enable event routing"] pub evtenset: EVTENSET, #[doc = "0x348 - Disable event routing"] pub evtenclr: EVTENCLR, _reserved4: [u8; 440usize], #[doc = "0x504 - Current COUNTER value"] pub counter: COUNTER, #[doc = "0x508 - 12 bit prescaler for COUNTER frequency (32768/(PRESCALER+1)).Must be written when RTC is stopped"] pub prescaler: PRESCALER, _reserved5: [u8; 52usize], #[doc = "0x540 - Description collection\\[n\\]: Compare register n"] pub cc: [CC; 4], } #[doc = "Start RTC COUNTER"] pub struct TASKS_START { register: ::vcell::VolatileCell<u32>, } #[doc = "Start RTC COUNTER"] pub mod tasks_start; #[doc = "Stop RTC COUNTER"] pub struct TASKS_STOP { register: ::vcell::VolatileCell<u32>, } #[doc = "Stop RTC COUNTER"] pub mod tasks_stop; #[doc = "Clear RTC COUNTER"] pub struct TASKS_CLEAR { register: ::vcell::VolatileCell<u32>, } #[doc = "Clear RTC COUNTER"] pub mod tasks_clear; #[doc = "Set COUNTER to 0xFFFFF0"] pub struct TASKS_TRIGOVRFLW { register: ::vcell::VolatileCell<u32>, } #[doc = "Set COUNTER to 0xFFFFF0"] pub mod tasks_trigovrflw; #[doc = "Event on COUNTER increment"] pub struct EVENTS_TICK { register: ::vcell::VolatileCell<u32>, } #[doc = "Event on COUNTER increment"] pub mod events_tick; #[doc = "Event on COUNTER overflow"] pub struct EVENTS_OVRFLW { register: ::vcell::VolatileCell<u32>, } #[doc = "Event on COUNTER overflow"] pub mod events_ovrflw; #[doc = "Description collection\\[n\\]: Compare event on CC\\[n\\] match"] pub struct EVENTS_COMPARE { register: ::vcell::VolatileCell<u32>, } #[doc = "Description collection\\[n\\]: Compare event on CC\\[n\\] match"] pub mod events_compare; #[doc = "Enable interrupt"] pub struct INTENSET { register: ::vcell::VolatileCell<u32>, } #[doc = "Enable interrupt"] pub mod intenset; #[doc = "Disable interrupt"] pub struct INTENCLR { register: ::vcell::VolatileCell<u32>, } #[doc = "Disable interrupt"] pub mod intenclr; #[doc = "Enable or disable event routing"] pub struct EVTEN { register: ::vcell::VolatileCell<u32>, } #[doc = "Enable or disable event routing"] pub mod evten; #[doc = "Enable event routing"] pub struct EVTENSET { register: ::vcell::VolatileCell<u32>, } #[doc = "Enable event routing"] pub mod evtenset; #[doc = "Disable event routing"] pub struct EVTENCLR { register: ::vcell::VolatileCell<u32>, } #[doc = "Disable event routing"] pub mod evtenclr; #[doc = "Current COUNTER value"] pub struct COUNTER { register: ::vcell::VolatileCell<u32>, } #[doc = "Current COUNTER value"] pub mod counter; #[doc = "12 bit prescaler for COUNTER frequency (32768/(PRESCALER+1)).Must be written when RTC is stopped"] pub struct PRESCALER { register: ::vcell::VolatileCell<u32>, } #[doc = "12 bit prescaler for COUNTER frequency (32768/(PRESCALER+1)).Must be written when RTC is stopped"] pub mod prescaler; #[doc = "Description collection\\[n\\]: Compare register n"] pub struct CC { register: ::vcell::VolatileCell<u32>, } #[doc = "Description collection\\[n\\]: Compare register n"] pub mod cc;
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Start RTC COUNTER"
top; #[doc = "Clear RTC COUNTER"] pub struct TASKS_CLEAR { register: ::vcell::VolatileCell<u32>, } #[doc = "Clear RTC COUNTER"] pub mod tasks_clear; #[doc = "Set COUNTER to 0xFFFFF0"] pub struct TASKS_TRIGOVRFLW { register: ::vcell::VolatileCell<u32>, } #[doc = "Set COUNTER to 0xFFFFF0"] pub mod tasks_trigovrflw; #[doc = "Event on COUNTER increment"] pub struct EVENTS_TICK { register: ::vcell::VolatileCell<u32>, } #[doc = "Event on COUNTER increment"] pub mod events_tick; #[doc = "Event on COUNTER overflow"] pub struct EVENTS_OVRFLW { register: ::vcell::VolatileCell<u32>, } #[doc = "Event on COUNTER overflow"] pub mod events_ovrflw; #[doc = "Description collection\\[n\\]: Compare event on CC\\[n\\] match"] pub struct EVENTS_COMPARE { register: ::vcell::VolatileCell<u32>, } #[doc = "Description collection\\[n\\]: Compare event on CC\\[n\\] match"] pub mod events_compare; #[doc = "Enable interrupt"] pub struct INTENSET { register: ::vcell::VolatileCell<u32>, } #[doc = "Enable interrupt"] pub mod intenset; #[doc = "Disable interrupt"] pub struct INTENCLR { register: ::vcell::VolatileCell<u32>, } #[doc = "Disable interrupt"] pub mod intenclr; #[doc = "Enable or disable event routing"] pub struct EVTEN { register: ::vcell::VolatileCell<u32>, } #[doc = "Enable or disable event routing"] pub mod evten; #[doc = "Enable event routing"] pub struct EVTENSET { register: ::vcell::VolatileCell<u32>, } #[doc = "Enable event routing"] pub mod evtenset; #[doc = "Disable event routing"] pub struct EVTENCLR { register: ::vcell::VolatileCell<u32>, } #[doc = "Disable event routing"] pub mod evtenclr; #[doc = "Current COUNTER value"] pub struct COUNTER { register: ::vcell::VolatileCell<u32>, } #[doc = "Current COUNTER value"] pub mod counter; #[doc = "12 bit prescaler for COUNTER frequency (32768/(PRESCALER+1)).Must be written when RTC is stopped"] pub struct PRESCALER { register: ::vcell::VolatileCell<u32>, } #[doc = "12 bit prescaler for COUNTER frequency (32768/(PRESCALER+1)).Must be written when RTC is stopped"] pub mod prescaler; #[doc = "Description collection\\[n\\]: Compare register n"] pub struct CC { register: ::vcell::VolatileCell<u32>, } #[doc = "Description collection\\[n\\]: Compare register n"] pub mod cc;
] pub tasks_start: TASKS_START, #[doc = "0x04 - Stop RTC COUNTER"] pub tasks_stop: TASKS_STOP, #[doc = "0x08 - Clear RTC COUNTER"] pub tasks_clear: TASKS_CLEAR, #[doc = "0x0c - Set COUNTER to 0xFFFFF0"] pub tasks_trigovrflw: TASKS_TRIGOVRFLW, _reserved0: [u8; 240usize], #[doc = "0x100 - Event on COUNTER increment"] pub events_tick: EVENTS_TICK, #[doc = "0x104 - Event on COUNTER overflow"] pub events_ovrflw: EVENTS_OVRFLW, _reserved1: [u8; 56usize], #[doc = "0x140 - Description collection\\[n\\]: Compare event on CC\\[n\\] match"] pub events_compare: [EVENTS_COMPARE; 4], _reserved2: [u8; 436usize], #[doc = "0x304 - Enable interrupt"] pub intenset: INTENSET, #[doc = "0x308 - Disable interrupt"] pub intenclr: INTENCLR, _reserved3: [u8; 52usize], #[doc = "0x340 - Enable or disable event routing"] pub evten: EVTEN, #[doc = "0x344 - Enable event routing"] pub evtenset: EVTENSET, #[doc = "0x348 - Disable event routing"] pub evtenclr: EVTENCLR, _reserved4: [u8; 440usize], #[doc = "0x504 - Current COUNTER value"] pub counter: COUNTER, #[doc = "0x508 - 12 bit prescaler for COUNTER frequency (32768/(PRESCALER+1)).Must be written when RTC is stopped"] pub prescaler: PRESCALER, _reserved5: [u8; 52usize], #[doc = "0x540 - Description collection\\[n\\]: Compare register n"] pub cc: [CC; 4], } #[doc = "Start RTC COUNTER"] pub struct TASKS_START { register: ::vcell::VolatileCell<u32>, } #[doc = "Start RTC COUNTER"] pub mod tasks_start; #[doc = "Stop RTC COUNTER"] pub struct TASKS_STOP { register: ::vcell::VolatileCell<u32>, } #[doc = "Stop RTC COUNTER"] pub mod tasks_s
random
[ { "content": "#[doc = r\" Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\nimpl super::COUNTER {\n\n #[doc = r\" Reads the contents of the register\"]\n\n #[inline]\n\n pub fn read(&self) -> R {\n\n R {\n\n bits: self.register.get(),\n\n }\n\n }\n\...
Rust
src/lexer.rs
mdlayher/monkey-rs
f7d7287a28c33c1cc833ffa0444405e5f5a3f04e
use crate::token::{Float, Integer, Radix, Token}; use std::error; use std::fmt; use std::num; use std::result; use std::str::FromStr; pub struct Lexer<'a> { input: &'a str, position: usize, read_position: usize, ch: char, } impl<'a> Lexer<'a> { pub fn new(input: &'a str) -> Self { let mut l = Lexer { input, position: 0, read_position: 0, ch: 0 as char, }; l.read_char(); l } pub fn lex(&mut self) -> Result<Vec<Token>> { let mut tokens = vec![]; loop { match self.next_token()? { t @ Token::Eof => { tokens.push(t); return Ok(tokens); } t => { tokens.push(t); } } } } pub fn next_token(&mut self) -> Result<Token> { self.skip_whitespace(); let t = match self.ch { '=' => { if self.peek_char() == '=' { self.read_char(); Token::Equal } else { Token::Assign } } '+' => Token::Plus, '-' => Token::Minus, '!' => { if self.peek_char() == '=' { self.read_char(); Token::NotEqual } else { Token::Bang } } '*' => Token::Asterisk, '/' => Token::Slash, '%' => Token::Percent, '<' => Token::LessThan, '>' => Token::GreaterThan, '&' => Token::Ampersand, ',' => Token::Comma, ':' => Token::Colon, ';' => Token::Semicolon, '(' => Token::LeftParen, ')' => Token::RightParen, '{' => Token::LeftBrace, '}' => Token::RightBrace, '[' => Token::LeftBracket, ']' => Token::RightBracket, '"' => self.read_string()?, '\u{0000}' => Token::Eof, _ => { if is_letter(self.ch) { let ident = self.read_identifier(); if let Some(key) = lookup_keyword(&ident) { return Ok(key); } else { return Ok(Token::Identifier(ident)); } } else if is_number(self.ch) { return self.read_number(); } else { Token::Illegal(self.ch) } } }; self.read_char(); Ok(t) } fn peek_char(&self) -> char { if self.read_position >= self.input.len() { 0 as char } else { if let Some(ch) = self.input.chars().nth(self.read_position) { ch } else { panic!("peeked out of range character") } } } fn read_char(&mut self) { if self.read_position >= self.input.len() { self.ch = 0 as char; } else { if let Some(ch) = self.input.chars().nth(self.read_position) { self.ch = ch; } else { panic!("read out of range character"); } } self.position = self.read_position; self.read_position += 1; } fn read_identifier(&mut self) -> String { let pos = self.position; while is_letter(self.ch) || self.ch.is_numeric() { self.read_char(); } self.input .chars() .skip(pos) .take(self.position - pos) .collect() } fn read_number(&mut self) -> Result<Token> { let pos = self.position; while (self.ch.is_ascii_alphanumeric() || self.ch == '.') && !self.ch.is_whitespace() { self.read_char(); } let chars: Vec<char> = self .input .chars() .skip(pos) .take(self.position - pos) .collect(); if chars.contains(&'.') { Ok(Token::Float(Float::from( f64::from_str(&chars.iter().collect::<String>()).map_err(Error::IllegalFloat)?, ))) } else { Ok(Token::Integer(parse_int(&chars)?)) } } fn read_string(&mut self) -> Result<Token> { let pos = self.position + 1; loop { self.read_char(); match self.ch { '"' => break, '\u{0000}' => { return Err(Error::UnexpectedEof); } _ => {} } } Ok(Token::String( self.input .chars() .skip(pos) .take(self.position - pos) .collect(), )) } fn skip_whitespace(&mut self) { while self.ch.is_ascii_whitespace() { self.read_char(); } } } fn lookup_keyword(s: &str) -> Option<Token> { match s { "fn" => Some(Token::Function), "let" => Some(Token::Let), "true" => Some(Token::True), "false" => Some(Token::False), "if" => Some(Token::If), "else" => Some(Token::Else), "return" => Some(Token::Return), "set" => Some(Token::Set), _ => None, } } fn is_letter(c: char) -> bool { c.is_ascii_alphabetic() || c == '_' } fn is_number(c: char) -> bool { ('0'..='9').contains(&c) } fn parse_int(chars: &[char]) -> Result<Integer> { if chars.len() < 2 { let raw: String = chars.iter().collect(); return Ok(Integer { radix: Radix::Decimal, value: raw.parse::<i64>().map_err(Error::IllegalInteger)?, }); } let (radix, skip) = match &chars[0..2] { ['0', 'b'] => (Radix::Binary, 2), ['0', 'x'] => (Radix::Hexadecimal, 2), ['0', 'o'] => (Radix::Octal, 2), ['0', '0'..='9'] => (Radix::Octal, 1), ['0', r] => { return Err(Error::IllegalIntegerRadix(*r)); } _ => (Radix::Decimal, 0), }; let raw: String = chars.iter().skip(skip).collect(); let base = match radix { Radix::Binary => 2, Radix::Decimal => 10, Radix::Hexadecimal => 16, Radix::Octal => 8, }; Ok(Integer { radix, value: i64::from_str_radix(&raw, base).map_err(Error::IllegalInteger)?, }) } pub type Result<T> = result::Result<T, Error>; #[derive(Debug, PartialEq)] pub enum Error { UnexpectedEof, IllegalFloat(num::ParseFloatError), IllegalIntegerRadix(char), IllegalInteger(num::ParseIntError), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::UnexpectedEof => write!(f, "unexpected EOF"), Error::IllegalFloat(err) => write!(f, "illegal floating point number: {}", err), Error::IllegalIntegerRadix(r) => write!(f, "illegal number radix: {}", r), Error::IllegalInteger(err) => write!(f, "illegal integer number: {}", err), } } } impl error::Error for Error { fn cause(&self) -> Option<&dyn error::Error> { match self { Error::IllegalFloat(err) => Some(err), Error::IllegalInteger(err) => Some(err), _ => None, } } }
use crate::token::{Float, Integer, Radix, Token}; use std::error; use std::fmt; use std::num; use std::result; use std::str::FromStr; pub struct Lexer<'a> { input: &'a str, position: usize, read_position: usize, ch: char, } impl<'a> Lexer<'a> { pub fn new(input: &'a str) -> Self { let mut l = Lexer { input, position: 0, read_position: 0, ch: 0 as char, }; l.read_char(); l }
]' => Token::RightBracket, '"' => self.read_string()?, '\u{0000}' => Token::Eof, _ => { if is_letter(self.ch) { let ident = self.read_identifier(); if let Some(key) = lookup_keyword(&ident) { return Ok(key); } else { return Ok(Token::Identifier(ident)); } } else if is_number(self.ch) { return self.read_number(); } else { Token::Illegal(self.ch) } } }; self.read_char(); Ok(t) } fn peek_char(&self) -> char { if self.read_position >= self.input.len() { 0 as char } else { if let Some(ch) = self.input.chars().nth(self.read_position) { ch } else { panic!("peeked out of range character") } } } fn read_char(&mut self) { if self.read_position >= self.input.len() { self.ch = 0 as char; } else { if let Some(ch) = self.input.chars().nth(self.read_position) { self.ch = ch; } else { panic!("read out of range character"); } } self.position = self.read_position; self.read_position += 1; } fn read_identifier(&mut self) -> String { let pos = self.position; while is_letter(self.ch) || self.ch.is_numeric() { self.read_char(); } self.input .chars() .skip(pos) .take(self.position - pos) .collect() } fn read_number(&mut self) -> Result<Token> { let pos = self.position; while (self.ch.is_ascii_alphanumeric() || self.ch == '.') && !self.ch.is_whitespace() { self.read_char(); } let chars: Vec<char> = self .input .chars() .skip(pos) .take(self.position - pos) .collect(); if chars.contains(&'.') { Ok(Token::Float(Float::from( f64::from_str(&chars.iter().collect::<String>()).map_err(Error::IllegalFloat)?, ))) } else { Ok(Token::Integer(parse_int(&chars)?)) } } fn read_string(&mut self) -> Result<Token> { let pos = self.position + 1; loop { self.read_char(); match self.ch { '"' => break, '\u{0000}' => { return Err(Error::UnexpectedEof); } _ => {} } } Ok(Token::String( self.input .chars() .skip(pos) .take(self.position - pos) .collect(), )) } fn skip_whitespace(&mut self) { while self.ch.is_ascii_whitespace() { self.read_char(); } } } fn lookup_keyword(s: &str) -> Option<Token> { match s { "fn" => Some(Token::Function), "let" => Some(Token::Let), "true" => Some(Token::True), "false" => Some(Token::False), "if" => Some(Token::If), "else" => Some(Token::Else), "return" => Some(Token::Return), "set" => Some(Token::Set), _ => None, } } fn is_letter(c: char) -> bool { c.is_ascii_alphabetic() || c == '_' } fn is_number(c: char) -> bool { ('0'..='9').contains(&c) } fn parse_int(chars: &[char]) -> Result<Integer> { if chars.len() < 2 { let raw: String = chars.iter().collect(); return Ok(Integer { radix: Radix::Decimal, value: raw.parse::<i64>().map_err(Error::IllegalInteger)?, }); } let (radix, skip) = match &chars[0..2] { ['0', 'b'] => (Radix::Binary, 2), ['0', 'x'] => (Radix::Hexadecimal, 2), ['0', 'o'] => (Radix::Octal, 2), ['0', '0'..='9'] => (Radix::Octal, 1), ['0', r] => { return Err(Error::IllegalIntegerRadix(*r)); } _ => (Radix::Decimal, 0), }; let raw: String = chars.iter().skip(skip).collect(); let base = match radix { Radix::Binary => 2, Radix::Decimal => 10, Radix::Hexadecimal => 16, Radix::Octal => 8, }; Ok(Integer { radix, value: i64::from_str_radix(&raw, base).map_err(Error::IllegalInteger)?, }) } pub type Result<T> = result::Result<T, Error>; #[derive(Debug, PartialEq)] pub enum Error { UnexpectedEof, IllegalFloat(num::ParseFloatError), IllegalIntegerRadix(char), IllegalInteger(num::ParseIntError), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::UnexpectedEof => write!(f, "unexpected EOF"), Error::IllegalFloat(err) => write!(f, "illegal floating point number: {}", err), Error::IllegalIntegerRadix(r) => write!(f, "illegal number radix: {}", r), Error::IllegalInteger(err) => write!(f, "illegal integer number: {}", err), } } } impl error::Error for Error { fn cause(&self) -> Option<&dyn error::Error> { match self { Error::IllegalFloat(err) => Some(err), Error::IllegalInteger(err) => Some(err), _ => None, } } }
pub fn lex(&mut self) -> Result<Vec<Token>> { let mut tokens = vec![]; loop { match self.next_token()? { t @ Token::Eof => { tokens.push(t); return Ok(tokens); } t => { tokens.push(t); } } } } pub fn next_token(&mut self) -> Result<Token> { self.skip_whitespace(); let t = match self.ch { '=' => { if self.peek_char() == '=' { self.read_char(); Token::Equal } else { Token::Assign } } '+' => Token::Plus, '-' => Token::Minus, '!' => { if self.peek_char() == '=' { self.read_char(); Token::NotEqual } else { Token::Bang } } '*' => Token::Asterisk, '/' => Token::Slash, '%' => Token::Percent, '<' => Token::LessThan, '>' => Token::GreaterThan, '&' => Token::Ampersand, ',' => Token::Comma, ':' => Token::Colon, ';' => Token::Semicolon, '(' => Token::LeftParen, ')' => Token::RightParen, '{' => Token::LeftBrace, '}' => Token::RightBrace, '[' => Token::LeftBracket, '
random
[ { "content": "fn compile(input: &str) -> Bytecode {\n\n let l = lexer::Lexer::new(input);\n\n\n\n let mut p = parser::Parser::new(l).expect(\"failed to create parser\");\n\n\n\n let prog = ast::Node::Program(p.parse().expect(\"failed to parse program\"));\n\n\n\n let mut c = Compiler::new();\n\n ...
Rust
runner/src/main.rs
Riey/gm-benchmark
afcabdebb82bdee9ab7fed69d46b3974ef44bff4
use ansi_term::Color; use anyhow::Context; use serde::{Deserialize, Serialize}; use std::fmt; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::time::{Duration, Instant}; use structopt::StructOpt; pub fn unknown_impl<T>(implementation: &str) -> anyhow::Result<T> { Err(anyhow::anyhow!( "Unknown implementation: {}", implementation )) } #[derive(Serialize, Deserialize, Clone, Copy)] pub enum LangType { Cpp, JavaScript, Python, Rust, } impl LangType { pub fn compile( self, opt: &Opt, program_path: &Path, implementation: &str, ) -> anyhow::Result<()> { let command = match self { LangType::Rust => match implementation { "rustc" => Some( Command::new("rustc") .current_dir(&opt.build_output) .stderr(Stdio::inherit()) .arg("-Ctarget-cpu=native") .arg("-Copt-level=2") .arg(program_path) .spawn()?, ), other => return unknown_impl(other), }, LangType::Cpp => match implementation { "g++" | "clang++" => Some( Command::new(implementation) .current_dir(&opt.build_output) .stderr(Stdio::inherit()) .arg("-o") .arg(program_path.file_stem().unwrap()) .arg("-march=native") .arg("-O3") .arg(program_path) .spawn()?, ), other => return unknown_impl(other), }, LangType::JavaScript | LangType::Python => None, }; if let Some(mut command) = command { let status = command .wait() .with_context(|| format!("Failed to compile with {}", implementation))?; assert!(status.success(), "Compile process failed!"); } Ok(()) } pub fn bench_command( self, opt: &Opt, program_path: &Path, implementation: &str, ) -> anyhow::Result<Command> { match self { LangType::JavaScript => { let mut com = Command::new(match implementation { "node" => "node", other => return unknown_impl(other), }); com.arg(program_path); Ok(com) } LangType::Python => { let mut com = Command::new(match implementation { "pypy" => "pypy", "python" => "python", other => return unknown_impl(other), }); com.arg(program_path); Ok(com) } LangType::Cpp | LangType::Rust => Ok(Command::new( opt.build_output.join(program_path.file_stem().unwrap()), )), } } } impl fmt::Display for LangType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { LangType::JavaScript => write!(f, "{}", Color::Yellow.paint("JavaScript")), LangType::Python => write!(f, "{}", Color::Blue.paint("Python")), LangType::Cpp => write!(f, "{}", Color::Cyan.paint("C++")), LangType::Rust => write!(f, "{}", Color::Red.paint("Rust")), } } } #[derive(Serialize, Deserialize)] pub struct Program { lang: LangType, #[serde(rename = "impl")] implementations: Vec<String>, idiomatic: bool, path: String, } impl Program { pub fn bench( &self, opt: &Opt, args: &[String], stdin_content: &[u8], expect_stdout: &[u8], ) -> anyhow::Result<()> { let program_path = opt.target.join(&self.path); for implementation in &self.implementations { let impl_color = Color::Purple.paint(implementation); println!("Start compile {} with {}", self.lang, impl_color); let compile_start = Instant::now(); self.lang .compile(opt, &program_path, implementation) .with_context(|| format!("Compile failed with {}", implementation))?; println!( "Compile with {} complete! elapsed: {}s", impl_color, Color::Yellow.paint(compile_start.elapsed().as_secs_f64().to_string()) ); let mut sum = Duration::new(0, 0); for i in 0..opt.bench_iter_count { let mut command = self .lang .bench_command(opt, &program_path, implementation)?; command .current_dir(&opt.build_output) .args(args) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::inherit()); let start = Instant::now(); let mut bench_process = command .spawn() .with_context(|| format!("Benchmark command failed with {}", implementation))?; bench_process .stdin .as_mut() .unwrap() .write_all(stdin_content)?; let output = bench_process.wait_with_output()?; let elapsed = start.elapsed(); assert!(output.status.success()); if i % 5 == 0 { println!( "Benchmark {}[{}] {}/{} elapsed: {}s", self.lang, impl_color, i, opt.bench_iter_count, Color::Yellow.paint(elapsed.as_secs_f64().to_string()) ); } sum += elapsed; assert_eq!(expect_stdout, output.stdout.as_slice()); } let average = sum / opt.bench_iter_count; println!( "Benchmark {}[{}] done! average: {}s", self.lang, impl_color, Color::Yellow.paint(average.as_secs_f64().to_string()), ); } Ok(()) } } #[derive(Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] enum ProgramStdinType { File, Text, } impl ProgramStdinType { pub fn get_bytes(&self, target_path: &Path, content: &str) -> anyhow::Result<Vec<u8>> { match self { ProgramStdinType::File => Ok(fs::read(Path::new(target_path).join(content))?), ProgramStdinType::Text => Ok(content.as_bytes().to_vec()), } } } #[derive(Serialize, Deserialize)] pub struct ProgramStdin { #[serde(rename = "type")] ty: ProgramStdinType, content: String, } impl ProgramStdin { pub fn get_bytes(&self, path: &Path) -> anyhow::Result<Vec<u8>> { self.ty.get_bytes(path, &self.content) } } #[derive(Serialize, Deserialize)] pub struct Bench { name: String, args: Vec<String>, stdin: Option<ProgramStdin>, stdout: String, programs: Vec<Program>, } impl Bench { pub fn bench(&self, opt: &Opt) -> anyhow::Result<()> { let bench_name = Color::Cyan.paint(&self.name); println!("Start {}...", bench_name); let stdin_content: Vec<u8> = self .stdin .as_ref() .map(|stdin| stdin.get_bytes(&opt.target)) .transpose()? .unwrap_or_default(); let args: Vec<String> = self .args .iter() .map(|arg| match arg.as_str() { "$CONTENT_LENGTH$" => stdin_content.len().to_string(), arg => arg.to_string(), }) .collect(); for program in self.programs.iter() { program.bench(opt, &args, &stdin_content, self.stdout.as_bytes())?; } Ok(()) } } #[derive(StructOpt)] #[structopt(name = "gm_benchmark_runner", about = "Benchmark Runner")] pub struct Opt { #[structopt(short = "b", about = "Path for store build output")] build_output: PathBuf, #[structopt(short = "t", about = "Path where bench.yml exists")] target: PathBuf, #[structopt(short = "c", about = "How many bench iterate", default_value = "10")] bench_iter_count: u32, } fn main() -> anyhow::Result<()> { let opt = Opt::from_args(); if !opt.build_output.exists() { std::fs::create_dir_all(&opt.build_output)?; } let bench: Bench = serde_yaml::from_reader(fs::File::open(opt.target.join("bench.yml"))?)?; bench .bench(&opt) .with_context(|| format!("Failed to benchmark {}", bench.name)) }
use ansi_term::Color; use anyhow::Context; use serde::{Deserialize, Serialize}; use std::fmt; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::time::{Duration, Instant}; use structopt::StructOpt; pub fn unknown_impl<T>(implementation: &str) -> anyhow::Result<T> { Err(anyhow::anyhow!( "Unknown implementation: {}", implementation )) } #[derive(Serialize, Deserialize, Clone, Copy)] pub enum LangType { Cpp, JavaScript, Python, Rust, } impl LangType { pub fn compile( self, opt: &Opt, program_path: &Path, implementation: &str, ) -> anyhow::Result<()> { let command = match self { LangType::Rust => match implementation { "rustc" =>
, other => return unknown_impl(other), }, LangType::Cpp => match implementation { "g++" | "clang++" => Some( Command::new(implementation) .current_dir(&opt.build_output) .stderr(Stdio::inherit()) .arg("-o") .arg(program_path.file_stem().unwrap()) .arg("-march=native") .arg("-O3") .arg(program_path) .spawn()?, ), other => return unknown_impl(other), }, LangType::JavaScript | LangType::Python => None, }; if let Some(mut command) = command { let status = command .wait() .with_context(|| format!("Failed to compile with {}", implementation))?; assert!(status.success(), "Compile process failed!"); } Ok(()) } pub fn bench_command( self, opt: &Opt, program_path: &Path, implementation: &str, ) -> anyhow::Result<Command> { match self { LangType::JavaScript => { let mut com = Command::new(match implementation { "node" => "node", other => return unknown_impl(other), }); com.arg(program_path); Ok(com) } LangType::Python => { let mut com = Command::new(match implementation { "pypy" => "pypy", "python" => "python", other => return unknown_impl(other), }); com.arg(program_path); Ok(com) } LangType::Cpp | LangType::Rust => Ok(Command::new( opt.build_output.join(program_path.file_stem().unwrap()), )), } } } impl fmt::Display for LangType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { LangType::JavaScript => write!(f, "{}", Color::Yellow.paint("JavaScript")), LangType::Python => write!(f, "{}", Color::Blue.paint("Python")), LangType::Cpp => write!(f, "{}", Color::Cyan.paint("C++")), LangType::Rust => write!(f, "{}", Color::Red.paint("Rust")), } } } #[derive(Serialize, Deserialize)] pub struct Program { lang: LangType, #[serde(rename = "impl")] implementations: Vec<String>, idiomatic: bool, path: String, } impl Program { pub fn bench( &self, opt: &Opt, args: &[String], stdin_content: &[u8], expect_stdout: &[u8], ) -> anyhow::Result<()> { let program_path = opt.target.join(&self.path); for implementation in &self.implementations { let impl_color = Color::Purple.paint(implementation); println!("Start compile {} with {}", self.lang, impl_color); let compile_start = Instant::now(); self.lang .compile(opt, &program_path, implementation) .with_context(|| format!("Compile failed with {}", implementation))?; println!( "Compile with {} complete! elapsed: {}s", impl_color, Color::Yellow.paint(compile_start.elapsed().as_secs_f64().to_string()) ); let mut sum = Duration::new(0, 0); for i in 0..opt.bench_iter_count { let mut command = self .lang .bench_command(opt, &program_path, implementation)?; command .current_dir(&opt.build_output) .args(args) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::inherit()); let start = Instant::now(); let mut bench_process = command .spawn() .with_context(|| format!("Benchmark command failed with {}", implementation))?; bench_process .stdin .as_mut() .unwrap() .write_all(stdin_content)?; let output = bench_process.wait_with_output()?; let elapsed = start.elapsed(); assert!(output.status.success()); if i % 5 == 0 { println!( "Benchmark {}[{}] {}/{} elapsed: {}s", self.lang, impl_color, i, opt.bench_iter_count, Color::Yellow.paint(elapsed.as_secs_f64().to_string()) ); } sum += elapsed; assert_eq!(expect_stdout, output.stdout.as_slice()); } let average = sum / opt.bench_iter_count; println!( "Benchmark {}[{}] done! average: {}s", self.lang, impl_color, Color::Yellow.paint(average.as_secs_f64().to_string()), ); } Ok(()) } } #[derive(Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] enum ProgramStdinType { File, Text, } impl ProgramStdinType { pub fn get_bytes(&self, target_path: &Path, content: &str) -> anyhow::Result<Vec<u8>> { match self { ProgramStdinType::File => Ok(fs::read(Path::new(target_path).join(content))?), ProgramStdinType::Text => Ok(content.as_bytes().to_vec()), } } } #[derive(Serialize, Deserialize)] pub struct ProgramStdin { #[serde(rename = "type")] ty: ProgramStdinType, content: String, } impl ProgramStdin { pub fn get_bytes(&self, path: &Path) -> anyhow::Result<Vec<u8>> { self.ty.get_bytes(path, &self.content) } } #[derive(Serialize, Deserialize)] pub struct Bench { name: String, args: Vec<String>, stdin: Option<ProgramStdin>, stdout: String, programs: Vec<Program>, } impl Bench { pub fn bench(&self, opt: &Opt) -> anyhow::Result<()> { let bench_name = Color::Cyan.paint(&self.name); println!("Start {}...", bench_name); let stdin_content: Vec<u8> = self .stdin .as_ref() .map(|stdin| stdin.get_bytes(&opt.target)) .transpose()? .unwrap_or_default(); let args: Vec<String> = self .args .iter() .map(|arg| match arg.as_str() { "$CONTENT_LENGTH$" => stdin_content.len().to_string(), arg => arg.to_string(), }) .collect(); for program in self.programs.iter() { program.bench(opt, &args, &stdin_content, self.stdout.as_bytes())?; } Ok(()) } } #[derive(StructOpt)] #[structopt(name = "gm_benchmark_runner", about = "Benchmark Runner")] pub struct Opt { #[structopt(short = "b", about = "Path for store build output")] build_output: PathBuf, #[structopt(short = "t", about = "Path where bench.yml exists")] target: PathBuf, #[structopt(short = "c", about = "How many bench iterate", default_value = "10")] bench_iter_count: u32, } fn main() -> anyhow::Result<()> { let opt = Opt::from_args(); if !opt.build_output.exists() { std::fs::create_dir_all(&opt.build_output)?; } let bench: Bench = serde_yaml::from_reader(fs::File::open(opt.target.join("bench.yml"))?)?; bench .bench(&opt) .with_context(|| format!("Failed to benchmark {}", bench.name)) }
Some( Command::new("rustc") .current_dir(&opt.build_output) .stderr(Stdio::inherit()) .arg("-Ctarget-cpu=native") .arg("-Copt-level=2") .arg(program_path) .spawn()?, )
call_expression
[ { "content": "fn main() {\n\n let stdin = io::stdin();\n\n let stdin = stdin.lock();\n\n let mut stdin = BufReader::with_capacity(8196, stdin);\n\n let stdout = io::stdout();\n\n let stdout = stdout.lock();\n\n let mut stdout = BufWriter::with_capacity(8196, stdout);\n\n\n\n let source_leng...
Rust
core/bin/zksync_api/src/fee_ticker/mod.rs
vikkkko/zksyncM
e7376b09429f4d261e1038876f1ee9b1b8d26fc9
use std::collections::{HashMap, HashSet}; use bigdecimal::BigDecimal; use futures::{ channel::{mpsc::Receiver, oneshot}, StreamExt, }; use num::{ rational::Ratio, traits::{Inv, Pow}, BigUint, }; use serde::{Deserialize, Serialize}; use tokio::task::JoinHandle; use zksync_config::{FeeTickerOptions, TokenPriceSource}; use zksync_storage::ConnectionPool; use zksync_types::{ Address, ChangePubKeyOp, Token, TokenId, TokenLike, TransferOp, TransferToNewOp, TxFeeTypes, WithdrawOp, }; use zksync_utils::ratio_to_big_decimal; use crate::fee_ticker::{ fee_token_validator::FeeTokenValidator, ticker_api::{ coingecko::CoinGeckoAPI, coinmarkercap::CoinMarketCapAPI, FeeTickerAPI, TickerApi, CONNECTION_TIMEOUT, }, ticker_info::{FeeTickerInfo, TickerInfo}, }; use crate::utils::token_db_cache::TokenDBCache; pub use self::fee::*; mod constants; mod fee; mod fee_token_validator; mod ticker_api; mod ticker_info; #[cfg(test)] mod tests; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct GasOperationsCost { standard_cost: HashMap<OutputFeeType, BigUint>, subsidize_cost: HashMap<OutputFeeType, BigUint>, } impl GasOperationsCost { pub fn from_constants(fast_processing_coeff: f64) -> Self { let standard_fast_withdrawal_cost = (constants::BASE_WITHDRAW_COST as f64 * fast_processing_coeff) as u32; let subsidy_fast_withdrawal_cost = (constants::SUBSIDY_WITHDRAW_COST as f64 * fast_processing_coeff) as u32; let standard_cost = vec![ ( OutputFeeType::Transfer, constants::BASE_TRANSFER_COST.into(), ), ( OutputFeeType::TransferToNew, constants::BASE_TRANSFER_TO_NEW_COST.into(), ), ( OutputFeeType::Withdraw, constants::BASE_WITHDRAW_COST.into(), ), ( OutputFeeType::FastWithdraw, standard_fast_withdrawal_cost.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: false, }, constants::BASE_CHANGE_PUBKEY_OFFCHAIN_COST.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: true, }, constants::BASE_CHANGE_PUBKEY_ONCHAIN_COST.into(), ), ] .into_iter() .collect::<HashMap<_, _>>(); let subsidize_cost = vec![ ( OutputFeeType::Transfer, constants::SUBSIDY_TRANSFER_COST.into(), ), ( OutputFeeType::TransferToNew, constants::SUBSIDY_TRANSFER_TO_NEW_COST.into(), ), ( OutputFeeType::Withdraw, constants::SUBSIDY_WITHDRAW_COST.into(), ), ( OutputFeeType::FastWithdraw, subsidy_fast_withdrawal_cost.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: false, }, constants::SUBSIDY_CHANGE_PUBKEY_OFFCHAIN_COST.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: true, }, constants::BASE_CHANGE_PUBKEY_ONCHAIN_COST.into(), ), ] .into_iter() .collect::<HashMap<_, _>>(); Self { standard_cost, subsidize_cost, } } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct TickerConfig { zkp_cost_chunk_usd: Ratio<BigUint>, gas_cost_tx: GasOperationsCost, tokens_risk_factors: HashMap<TokenId, Ratio<BigUint>>, not_subsidized_tokens: HashSet<Address>, } #[derive(Debug, PartialEq, Eq)] pub enum TokenPriceRequestType { USDForOneWei, USDForOneToken, } #[derive(Debug)] pub enum TickerRequest { GetTxFee { tx_type: TxFeeTypes, address: Address, token: TokenLike, response: oneshot::Sender<Result<Fee, anyhow::Error>>, }, GetTokenPrice { token: TokenLike, response: oneshot::Sender<Result<BigDecimal, anyhow::Error>>, req_type: TokenPriceRequestType, }, IsTokenAllowed { token: TokenLike, response: oneshot::Sender<Result<bool, anyhow::Error>>, }, } struct FeeTicker<API, INFO> { api: API, info: INFO, requests: Receiver<TickerRequest>, config: TickerConfig, validator: FeeTokenValidator, } #[must_use] pub fn run_ticker_task( db_pool: ConnectionPool, tricker_requests: Receiver<TickerRequest>, ) -> JoinHandle<()> { let config = FeeTickerOptions::from_env(); let ticker_config = TickerConfig { zkp_cost_chunk_usd: Ratio::from_integer(BigUint::from(10u32).pow(3u32)).inv(), gas_cost_tx: GasOperationsCost::from_constants(config.fast_processing_coeff), tokens_risk_factors: HashMap::new(), not_subsidized_tokens: config.not_subsidized_tokens, }; let cache = TokenDBCache::new(db_pool.clone()); let validator = FeeTokenValidator::new(cache, config.disabled_tokens); let client = reqwest::ClientBuilder::new() .timeout(CONNECTION_TIMEOUT) .connect_timeout(CONNECTION_TIMEOUT) .build() .expect("Failed to build reqwest::Client"); match config.token_price_source { TokenPriceSource::CoinMarketCap { base_url } => { let token_price_api = CoinMarketCapAPI::new(client, base_url); let ticker_api = TickerApi::new(db_pool.clone(), token_price_api); let ticker_info = TickerInfo::new(db_pool); let fee_ticker = FeeTicker::new( ticker_api, ticker_info, tricker_requests, ticker_config, validator, ); tokio::spawn(fee_ticker.run()) } TokenPriceSource::CoinGecko { base_url } => { let token_price_api = CoinGeckoAPI::new(client, base_url).expect("failed to init CoinGecko client"); let ticker_api = TickerApi::new(db_pool.clone(), token_price_api); let ticker_info = TickerInfo::new(db_pool); let fee_ticker = FeeTicker::new( ticker_api, ticker_info, tricker_requests, ticker_config, validator, ); tokio::spawn(fee_ticker.run()) } } } impl<API: FeeTickerAPI, INFO: FeeTickerInfo> FeeTicker<API, INFO> { fn new( api: API, info: INFO, requests: Receiver<TickerRequest>, config: TickerConfig, validator: FeeTokenValidator, ) -> Self { Self { api, info, requests, config, validator, } } async fn run(mut self) { while let Some(request) = self.requests.next().await { match request { TickerRequest::GetTxFee { tx_type, token, response, address, } => { let fee = self .get_fee_from_ticker_in_wei(tx_type, token, address) .await; response.send(fee).unwrap_or_default(); } TickerRequest::GetTokenPrice { token, response, req_type, } => { let price = self.get_token_price(token, req_type).await; response.send(price).unwrap_or_default(); } TickerRequest::IsTokenAllowed { token, response } => { let allowed = self.validator.token_allowed(token).await; response.send(allowed).unwrap_or_default(); } } } } async fn get_token_price( &self, token: TokenLike, request_type: TokenPriceRequestType, ) -> Result<BigDecimal, anyhow::Error> { let factor = match request_type { TokenPriceRequestType::USDForOneWei => { let token_decimals = self.api.get_token(token.clone()).await?.decimals; BigUint::from(10u32).pow(u32::from(token_decimals)) } TokenPriceRequestType::USDForOneToken => BigUint::from(1u32), }; self.api .get_last_quote(token) .await .map(|price| ratio_to_big_decimal(&(price.usd_price / factor), 100)) } async fn is_account_new(&mut self, address: Address) -> bool { self.info.is_account_new(address).await } async fn is_token_subsidized(&mut self, token: Token) -> bool { !self.config.not_subsidized_tokens.contains(&token.address) } async fn get_fee_from_ticker_in_wei( &mut self, tx_type: TxFeeTypes, token: TokenLike, recipient: Address, ) -> Result<Fee, anyhow::Error> { let zkp_cost_chunk = self.config.zkp_cost_chunk_usd.clone(); let token = self.api.get_token(token).await?; let token_risk_factor = self .config .tokens_risk_factors .get(&token.id) .cloned() .unwrap_or_else(|| Ratio::from_integer(1u32.into())); let (fee_type, op_chunks) = match tx_type { TxFeeTypes::Withdraw => (OutputFeeType::Withdraw, WithdrawOp::CHUNKS), TxFeeTypes::FastWithdraw => (OutputFeeType::FastWithdraw, WithdrawOp::CHUNKS), TxFeeTypes::Transfer => { if self.is_account_new(recipient).await { (OutputFeeType::TransferToNew, TransferToNewOp::CHUNKS) } else { (OutputFeeType::Transfer, TransferOp::CHUNKS) } } TxFeeTypes::ChangePubKey { onchain_pubkey_auth, } => ( OutputFeeType::ChangePubKey { onchain_pubkey_auth, }, ChangePubKeyOp::CHUNKS, ), }; let op_chunks = BigUint::from(op_chunks); let gas_tx_amount = { let is_token_subsidized = self.is_token_subsidized(token.clone()).await; if is_token_subsidized { self.config .gas_cost_tx .subsidize_cost .get(&fee_type) .cloned() .unwrap() } else { self.config .gas_cost_tx .standard_cost .get(&fee_type) .cloned() .unwrap() } }; let gas_price_wei = self.api.get_gas_price_wei().await?; let wei_price_usd = self.api.get_last_quote(TokenLike::Id(0)).await?.usd_price / BigUint::from(10u32).pow(18u32); let token_price_usd = self .api .get_last_quote(TokenLike::Id(token.id)) .await? .usd_price / BigUint::from(10u32).pow(u32::from(token.decimals)) * BigUint::from(10000u32); let zkp_fee = (zkp_cost_chunk * op_chunks) * token_risk_factor.clone() / token_price_usd.clone() * BigUint::from(0u32); let gas_fee = (wei_price_usd * gas_tx_amount.clone() * gas_price_wei.clone()) * token_risk_factor / token_price_usd * BigUint::from(0u32); Ok(Fee::new( fee_type, zkp_fee, gas_fee, gas_tx_amount, gas_price_wei, )) } }
use std::collections::{HashMap, HashSet}; use bigdecimal::BigDecimal; use futures::{ channel::{mpsc::Receiver, oneshot}, StreamExt, }; use num::{ rational::Ratio, traits::{Inv, Pow}, BigUint, }; use serde::{Deserialize, Serialize}; use tokio::task::JoinHandle; use zksync_config::{FeeTickerOptions, TokenPriceSource}; use zksync_storage::ConnectionPool; use zksync_types::{ Address, ChangePubKeyOp, Token, TokenId, TokenLike, TransferOp, TransferToNewOp, TxFeeTypes, WithdrawOp, }; use zksync_utils::ratio_to_big_decimal; use crate::fee_ticker::{ fee_token_validator::FeeTokenValidator, ticker_api::{ coingecko::CoinGeckoAPI, coinmarkercap::CoinMarketCapAPI, FeeTickerAPI, TickerApi, CONNECTION_TIMEOUT, }, ticker_info::{FeeTickerInfo, TickerInfo}, }; use crate::utils::token_db_cache::TokenDBCache; pub use self::fee::*; mod constants; mod fee; mod fee_token_validator; mod ticker_api; mod ticker_info; #[cfg(test)] mod tests; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct GasOperationsCost { standard_cost: HashMap<OutputFeeType, BigUint>, subsidize_cost: HashMap<OutputFeeType, BigUint>, } impl GasOperationsCost { pub fn from_constants(fast_processing_coeff: f64) -> Self { let standard_fast_withdrawal_cost = (constants::BASE_WITHDRAW_COST as f64 * fast_processing_coeff) as u32; let subsidy_fast_withdrawal_cost = (constants::SUBSIDY_WITHDRAW_COST as f64 * fast_processing_coeff) as u32; let standard_cost = vec![ ( OutputFeeType::Transfer, constants::BASE_TRANSFER_COST.into(), ), ( OutputFeeType::TransferToNew, constants::BASE_TRANSFER_TO_NEW_COST.into(), ), ( OutputFeeType::Withdraw, constants::BASE_WITHDRAW_COST.into(), ), ( OutputFeeType::FastWithdraw, standard_fast_withdrawal_cost.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: false, }, constants::BASE_CHANGE_PUBKEY_OFFCHAIN_COST.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: true, }, constants::BASE_CHANGE_PUBKEY_ONCHAIN_COST.into(), ), ] .into_iter() .collect::<HashMap<_, _>>(); let subsidize_cost = vec![ ( OutputFeeType::Transfer, constants::SUBSIDY_TRANSFER_COST.into(), ), ( OutputFeeType::TransferToNew, constants::SUBSIDY_TRANSFER_TO_NEW_COST.into(), ), ( OutputFeeType::Withdraw, constants::SUBSIDY_WITHDRAW_COST.into(), ), ( OutputFeeType::FastWithdraw, subsidy_fast_withdrawal_cost.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: false, }, constants::SUBSIDY_CHANGE_PUBKEY_OFFCHAIN_COST.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: true, }, constants::BASE_CHANGE_PUBKEY_ONCHAIN_COST.into(), ), ] .into_iter() .collect::<HashMap<_, _>>(); Self { standard_cost, subsidize_cost, } } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct TickerConfig { zkp_cost_chunk_usd: Ratio<BigUint>, gas_cost_tx: GasOperationsCost, tokens_risk_factors: HashMap<TokenId, Ratio<BigUint>>, not_subsidized_tokens: HashSet<Address>, } #[derive(Debug, PartialEq, Eq)] pub enum TokenPriceRequestType { USDForOneWei, USDForOneToken, } #[derive(Debug)] pub enum TickerRequest { GetTxFee { tx_type: TxFeeTypes, address: Address, token: TokenLike, response: oneshot::Sender<Result<Fee, anyhow::Error>>, }, GetTokenPrice { token: TokenLike, response: oneshot::Sender<Result<BigDecimal, anyhow::Error>>, req_type: TokenPriceRequestType, }, IsTokenAllowed { token: TokenLike, response: oneshot::Sender<Result<bool, anyhow::Error>>, }, } struct FeeTicker<API, INFO> { api: API, info: INFO, requests: Receiver<TickerRequest>, config: TickerConfig, validator: FeeTokenValidator, } #[must_use] pub fn run_ticker_task( db_pool: ConnectionPool, tricker_requests: Receiver<TickerRequest>, ) -> JoinHandle<()> { let config = FeeTickerOptions::from_env(); let ticker_config = TickerConfig { zkp_cost_chunk_usd: Ratio::from_integer(BigUint::from(10u32).pow(3u32)).inv(), gas_cost_tx: GasOperationsCost::from_constants(config.fast_processing_coeff), tokens_risk_factors: HashMap::new(), not_subsidized_tokens: config.not_subsidized_tokens, }; let cache = TokenDBCache::new(db_pool.clone()); let validator = FeeTokenValidator::new(cache, config.disabled_tokens); let client = reqwest::ClientBuilder::new() .timeout(CONNECTION_TIMEOUT) .connect_timeout(CONNECTION_TIMEOUT) .build() .expect("Failed to build reqwest::Client"); match config.token_price_source { TokenPriceSource::CoinMarketCap { base_url } => { let token_price_api = CoinMarketCapAPI::new(client, base_url); let ticker_api = TickerApi::new(db_pool.clone(), token_price_api); let ticker_info = TickerInfo::new(db_pool); let fee_ticker = FeeTicker::new( ticker_api, ticker_info, tricker_requests, ticker_config, validator, ); tokio::spawn(fee_ticker.run()) } TokenPriceSource::CoinGecko { base_url } => { let token_price_api = CoinGeckoAPI::new(client, base_url).expect("failed to init CoinGecko client"); let ticker_api = TickerApi::new(db_pool.clone(), token_price_api); let ticker_info = TickerInfo::new(db_pool); let fee_ticker = FeeTicker::new( ticker_api, ticker_info, tricker_requests, ticker_config, validator, ); tokio::spawn(fee_ticker.run()) } } } impl<API: FeeTickerAPI, INFO: FeeTickerInfo> FeeTicker<API, INFO> { fn new( api: API, info: INFO, requests: Receiver<TickerRequest>, config: TickerConfig, validator: FeeTokenValidator, ) -> Self { Self { api, info, requests, config, validator, } } async fn run(mut self) { while let Some(request) = self.requests.next().await { match request { TickerRequest::GetTxFee { tx_type, token, response, address, } => { let fee = self .get_fee_from_ticker_in_wei(tx_type, token, address) .await; response.send(fee).unwrap_or_default(); } TickerRequest::GetTokenPrice { token, response, req_type, } => { let price = self.get_token_price(token, req_type).await; response.send(price).unwrap_or_default(); } TickerRequest::IsTokenAllowed { token, response } => { let allowed = self.validator.token_allowed(token).await; response.send(allowed).unwrap_or_default(); } } } } async fn get_token_price( &self, token: TokenLike, request_type: TokenPriceRequestType, ) -> Result<BigDecimal, anyhow::Error> { let factor =
; self.api .get_last_quote(token) .await .map(|price| ratio_to_big_decimal(&(price.usd_price / factor), 100)) } async fn is_account_new(&mut self, address: Address) -> bool { self.info.is_account_new(address).await } async fn is_token_subsidized(&mut self, token: Token) -> bool { !self.config.not_subsidized_tokens.contains(&token.address) } async fn get_fee_from_ticker_in_wei( &mut self, tx_type: TxFeeTypes, token: TokenLike, recipient: Address, ) -> Result<Fee, anyhow::Error> { let zkp_cost_chunk = self.config.zkp_cost_chunk_usd.clone(); let token = self.api.get_token(token).await?; let token_risk_factor = self .config .tokens_risk_factors .get(&token.id) .cloned() .unwrap_or_else(|| Ratio::from_integer(1u32.into())); let (fee_type, op_chunks) = match tx_type { TxFeeTypes::Withdraw => (OutputFeeType::Withdraw, WithdrawOp::CHUNKS), TxFeeTypes::FastWithdraw => (OutputFeeType::FastWithdraw, WithdrawOp::CHUNKS), TxFeeTypes::Transfer => { if self.is_account_new(recipient).await { (OutputFeeType::TransferToNew, TransferToNewOp::CHUNKS) } else { (OutputFeeType::Transfer, TransferOp::CHUNKS) } } TxFeeTypes::ChangePubKey { onchain_pubkey_auth, } => ( OutputFeeType::ChangePubKey { onchain_pubkey_auth, }, ChangePubKeyOp::CHUNKS, ), }; let op_chunks = BigUint::from(op_chunks); let gas_tx_amount = { let is_token_subsidized = self.is_token_subsidized(token.clone()).await; if is_token_subsidized { self.config .gas_cost_tx .subsidize_cost .get(&fee_type) .cloned() .unwrap() } else { self.config .gas_cost_tx .standard_cost .get(&fee_type) .cloned() .unwrap() } }; let gas_price_wei = self.api.get_gas_price_wei().await?; let wei_price_usd = self.api.get_last_quote(TokenLike::Id(0)).await?.usd_price / BigUint::from(10u32).pow(18u32); let token_price_usd = self .api .get_last_quote(TokenLike::Id(token.id)) .await? .usd_price / BigUint::from(10u32).pow(u32::from(token.decimals)) * BigUint::from(10000u32); let zkp_fee = (zkp_cost_chunk * op_chunks) * token_risk_factor.clone() / token_price_usd.clone() * BigUint::from(0u32); let gas_fee = (wei_price_usd * gas_tx_amount.clone() * gas_price_wei.clone()) * token_risk_factor / token_price_usd * BigUint::from(0u32); Ok(Fee::new( fee_type, zkp_fee, gas_fee, gas_tx_amount, gas_price_wei, )) } }
match request_type { TokenPriceRequestType::USDForOneWei => { let token_decimals = self.api.get_token(token.clone()).await?.decimals; BigUint::from(10u32).pow(u32::from(token_decimals)) } TokenPriceRequestType::USDForOneToken => BigUint::from(1u32), }
if_condition
[ { "content": "/// Runs the massive API spam routine.\n\n///\n\n/// This process will continue until the cancel command is occurred or the limit is reached.\n\npub fn run(monitor: Monitor) -> (ApiTestsFuture, CancellationToken) {\n\n let cancellation = CancellationToken::default();\n\n\n\n let token = canc...
Rust
devolutions-gateway/src/rdp/sequence_future/post_mcs.rs
Devolutions/devolutions-gateway
80d83f7a07cd7a695f1f5ec30968efd59161b513
mod licensing; use std::io; use bytes::BytesMut; use ironrdp::mcs::SendDataContext; use ironrdp::rdp::server_license::LicenseEncryptionData; use ironrdp::{ClientInfoPdu, McsPdu, PduParsing, ShareControlHeader, ShareControlPdu}; use slog_scope::{debug, trace, warn}; use tokio::net::TcpStream; use tokio_rustls::TlsStream; use tokio_util::codec::Framed; use super::{FutureState, NextStream, SequenceFutureProperties}; use crate::rdp::filter::{Filter, FilterConfig}; use crate::transport::mcs::SendDataContextTransport; use licensing::{process_challenge, process_license_request, process_upgrade_license, LicenseCredentials, LicenseData}; pub type PostMcsFutureTransport = Framed<TlsStream<TcpStream>, SendDataContextTransport>; pub struct PostMcs { sequence_state: SequenceState, filter: Option<FilterConfig>, originator_id: Option<u16>, license_data: LicenseData, } impl PostMcs { pub fn new(filter: FilterConfig) -> Self { Self { sequence_state: SequenceState::ClientInfo, filter: Some(filter), originator_id: None, license_data: LicenseData { encryption_data: None, credentials: LicenseCredentials { username: String::from("hostname"), hostname: String::new(), }, }, } } } impl SequenceFutureProperties<TlsStream<TcpStream>, SendDataContextTransport, (ironrdp::McsPdu, Vec<u8>)> for PostMcs { type Item = (PostMcsFutureTransport, PostMcsFutureTransport, FilterConfig); fn process_pdu(&mut self, (mcs_pdu, pdu_data): (McsPdu, BytesMut)) -> io::Result<Option<(McsPdu, Vec<u8>)>> { let filter = self.filter.as_ref().expect( "The filter must exist in the client's RDP Connection Sequence, and must be taken only in the Finished state", ); let (next_sequence_state, result) = match mcs_pdu { McsPdu::SendDataRequest(SendDataContext { initiator_id, channel_id, .. }) => { let (next_sequence_state, pdu, credentials) = process_send_data_request_pdu(pdu_data, self.sequence_state, filter, self.originator_id)?; if let Some(credentials) = credentials { self.license_data.credentials = credentials; } ( next_sequence_state, ( McsPdu::SendDataRequest(SendDataContext { pdu_length: pdu.len(), initiator_id, channel_id, }), pdu, ), ) } McsPdu::SendDataIndication(SendDataContext { initiator_id, channel_id, .. }) => { let (next_sequence_state, pdu, indication_data) = process_send_data_indication_pdu( pdu_data, self.sequence_state, filter, self.license_data.encryption_data.clone(), &self.license_data.credentials, )?; if let Some(originator_id) = indication_data.originator_id { self.originator_id = Some(originator_id); } if let Some(encryption_data) = indication_data.encryption_data { self.license_data.encryption_data = Some(encryption_data); } ( next_sequence_state, ( McsPdu::SendDataIndication(SendDataContext { pdu_length: pdu.len(), initiator_id, channel_id, }), pdu, ), ) } _ => { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got MCS PDU during RDP Connection Sequence: {}", mcs_pdu.as_short_name() ), )) } }; self.sequence_state = next_sequence_state; Ok(Some(result)) } fn return_item( &mut self, mut client: Option<PostMcsFutureTransport>, mut server: Option<PostMcsFutureTransport>, ) -> Self::Item { debug!("Successfully processed RDP Connection Sequence"); ( client.take().expect( "In RDP Connection Sequence, the client's stream must exist in a return_item method, and the method cannot be fired multiple times"), server.take().expect( "In RDP Connection Sequence, the server's stream must exist in a return_item method, and the method cannot be fired multiple times"), self.filter.take().expect( "In RDP Connection Sequence, the filter must exist in a return_item method, and the method cannot be fired multiple times"), ) } fn next_sender(&self) -> NextStream { match self.sequence_state { SequenceState::ClientInfo | SequenceState::ClientConfirmActive => NextStream::Client, SequenceState::ServerLicenseRequest | SequenceState::ServerUpgradeLicense | SequenceState::ServerChallenge | SequenceState::ServerDemandActive => NextStream::Server, SequenceState::Finished => panic!( "In RDP Connection Sequence, the future must not require a next sender in the Finished sequence state" ), } } fn next_receiver(&self) -> NextStream { match self.sequence_state { SequenceState::ServerLicenseRequest | SequenceState::ServerChallenge | SequenceState::ServerUpgradeLicense | SequenceState::Finished => NextStream::Server, SequenceState::ServerDemandActive | SequenceState::ClientConfirmActive => NextStream::Client, SequenceState::ClientInfo => { unreachable!("The future must not require a next receiver in the first sequence state (ClientInfo)") } } } fn sequence_finished(&self, future_state: FutureState) -> bool { future_state == FutureState::SendMessage && self.sequence_state == SequenceState::Finished } } fn process_send_data_request_pdu( pdu_data: BytesMut, sequence_state: SequenceState, filter_config: &FilterConfig, originator_id: Option<u16>, ) -> io::Result<(SequenceState, Vec<u8>, Option<LicenseCredentials>)> { match sequence_state { SequenceState::ClientInfo => { let mut client_info_pdu = ClientInfoPdu::from_buffer(pdu_data.as_ref())?; trace!("Got Client Info PDU: {:?}", client_info_pdu); client_info_pdu.filter(filter_config); trace!("Filtered Client Info PDU: {:?}", client_info_pdu); let mut client_info_pdu_buffer = Vec::with_capacity(client_info_pdu.buffer_length()); client_info_pdu.to_buffer(&mut client_info_pdu_buffer)?; Ok(( SequenceState::ServerLicenseRequest, client_info_pdu_buffer, Some(LicenseCredentials { username: client_info_pdu.client_info.credentials.username, hostname: client_info_pdu.client_info.credentials.domain.unwrap_or_default(), }), )) } SequenceState::ClientConfirmActive => { let mut share_control_header = ShareControlHeader::from_buffer(pdu_data.as_ref())?; let next_sequence_state = match (sequence_state, &mut share_control_header.share_control_pdu) { (SequenceState::ClientConfirmActive, ShareControlPdu::ClientConfirmActive(client_confirm_active)) => { if client_confirm_active.originator_id != originator_id.expect("Originator ID must be set during Server Demand Active PDU processing") { warn!( "Got invalid originator ID: {} != {}", client_confirm_active.originator_id, originator_id.unwrap() ); } client_confirm_active.pdu.filter(filter_config); trace!("Got Client Confirm Active PDU: {:?}", client_confirm_active); SequenceState::Finished } (_, share_control_pdu) => { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid client's Share Control Header PDU: {:?}", share_control_pdu.as_short_name() ), )) } }; let mut share_control_header_buffer = Vec::with_capacity(share_control_header.buffer_length()); share_control_header.to_buffer(&mut share_control_header_buffer)?; Ok((next_sequence_state, share_control_header_buffer, None)) } state => Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid sequence state ({:?}) in the client's RDP Connection Sequence", state ), )), } } pub struct IndicationData { originator_id: Option<u16>, encryption_data: Option<LicenseEncryptionData>, } fn process_send_data_indication_pdu( pdu_data: BytesMut, sequence_state: SequenceState, filter_config: &FilterConfig, encryption_data: Option<LicenseEncryptionData>, credentials: &LicenseCredentials, ) -> io::Result<(SequenceState, Vec<u8>, IndicationData)> { match sequence_state { SequenceState::ServerLicenseRequest => process_license_request(pdu_data.as_ref(), credentials), SequenceState::ServerChallenge => process_challenge(pdu_data.as_ref(), encryption_data, credentials), SequenceState::ServerUpgradeLicense => process_upgrade_license(pdu_data.as_ref(), encryption_data), SequenceState::ServerDemandActive => { let mut share_control_header = ShareControlHeader::from_buffer(pdu_data.as_ref())?; let next_sequence_state = match (sequence_state, &mut share_control_header.share_control_pdu) { (SequenceState::ServerDemandActive, ShareControlPdu::ServerDemandActive(server_demand_active)) => { server_demand_active.pdu.filter(filter_config); trace!("Got Server Demand Active PDU: {:?}", server_demand_active); SequenceState::ClientConfirmActive } (_, share_control_pdu) => { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid server's Share Control Header PDU: {:?}", share_control_pdu.as_short_name() ), )) } }; let mut share_control_header_buffer = Vec::with_capacity(share_control_header.buffer_length()); share_control_header.to_buffer(&mut share_control_header_buffer)?; Ok(( next_sequence_state, share_control_header_buffer, IndicationData { originator_id: Some(share_control_header.pdu_source), encryption_data: None, }, )) } state => Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid sequence state ({:?}) in the server's RDP Connection Sequence", state ), )), } } #[derive(Copy, Clone, Debug, PartialEq)] pub enum SequenceState { ClientInfo, ServerLicenseRequest, ServerChallenge, ServerUpgradeLicense, ServerDemandActive, ClientConfirmActive, Finished, }
mod licensing; use std::io; use bytes::BytesMut; use ironrdp::mcs::SendDataContext; use ironrdp::rdp::server_license::LicenseEncryptionData; use ironrdp::{ClientInfoPdu, McsPdu, PduParsing, ShareControlHeader, ShareControlPdu}; use slog_scope::{debug, trace, warn}; use tokio::net::TcpStream; use tokio_rustls::TlsStream; use tokio_util::codec::Framed; use super::{FutureState, NextStream, SequenceFutureProperties}; use crate::rdp::filter::{Filter, FilterConfig}; use crate::transport::mcs::SendDataContextTransport; use licensing::{process_challenge, process_license_request, process_upgrade_license, LicenseCredentials, LicenseData}; pub type PostMcsFutureTransport = Framed<TlsStream<TcpStream>, SendDataContextTransport>; pub struct PostMcs { sequence_state: SequenceState, filter: Option<FilterConfig>, originator_id: Option<u16>, license_data: LicenseData, } impl PostMcs { pub fn new(filter: FilterConfig) -> Self { Self { sequence_state: SequenceState::ClientInfo, filter: Some(filter), originator_id: None, license_data: LicenseData { encryption_data: None, credentials: LicenseCredentials { username: String::from("hostname"), hostname: String::new(), }, }, } } } impl SequenceFutureProperties<TlsStream<TcpStream>, SendDataContextTransport, (ironrdp::McsPdu, Vec<u8>)> for PostMcs { type Item = (PostMcsFutureTransport, PostMcsFutureTransport, FilterConfig); fn process_pdu(&mut self, (mcs_pdu, pdu_data): (McsPdu, BytesMut)) -> io::Result<Option<(McsPdu, Vec<u8>)>> { let filter = self.filter.as_ref().expect( "The filter must exist in the client's RDP Connection Sequence, and must be taken only in the Finished state", ); let (next_sequence_state, result) = match mcs_pdu { McsPdu::SendDataRequest(SendDataContext { initiator_id, channel_id, .. }) => { let (next_sequence_state, pdu, credentials) = process_send_data_request_pdu(pdu_data, self.sequence_state, filter, self.originator_id)?; if let Some(credentials) = credentials { self.license_data.credentials = credentials; } ( next_sequence_state, ( McsPdu::SendDataRequest(SendDataContext { pdu_length: pdu.len(), initiator_id, channel_id, }), pdu, ), ) } McsPdu::SendDataIndication(SendDataContext { initiator_id, channel_id, .. }) => { let (next_sequence_state, pdu, indication_data) = process_send_data_indication_pdu( pdu_data, self.sequence_state, filter, self.license_data.encryption_data.clone(), &self.license_data.credentials, )?; if let Some(originator_id) = indication_data.originator_id { self.originator_id = Some(originator_id); } if let Some(encryption_data) = indication_data.encryption_data { self.license_data.encryption_data = Some(encryption_data); } ( next_sequence_state, ( McsPdu::SendDataIndication(SendDataContext { pdu_length: pdu.len(), initiator_id, channel_id, }), pdu, ), ) } _ => { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got MCS PDU during RDP Connection Sequence: {}", mcs_pdu.as_short_name() ), )) } }; self.sequence_state = next_sequence_state; Ok(Some(result)) } fn return_item( &mut self, mut client: Option<PostMcsFutureTransport>, mut server: Option<PostMcsFutureTransport>, ) -> Self::Item { debug!("Successfully processed RDP Connection Sequence"); ( client.take().expect( "In RDP Connection Sequence, the client's stream must exist in a return_item method, and the method cannot be fired multiple times"), server.take().expect( "In RDP Connection Sequence, the server's stream must exist in a return_item method, and the method cannot be fired multiple times"), self.filter.take().expect( "In RDP Connection Sequence, the filter must exist in a return_item method, and the method cannot be fired multiple times"), ) } fn next_sender(&self) -> NextStream { match self.sequence_state { SequenceState::ClientInfo | SequenceState::ClientConfirmActive => NextStream::Client, SequenceState::ServerLicenseRequest | SequenceState::ServerUpgradeLicense | SequenceState::ServerChallenge | SequenceState::ServerDemandActiv
fn next_receiver(&self) -> NextStream { match self.sequence_state { SequenceState::ServerLicenseRequest | SequenceState::ServerChallenge | SequenceState::ServerUpgradeLicense | SequenceState::Finished => NextStream::Server, SequenceState::ServerDemandActive | SequenceState::ClientConfirmActive => NextStream::Client, SequenceState::ClientInfo => { unreachable!("The future must not require a next receiver in the first sequence state (ClientInfo)") } } } fn sequence_finished(&self, future_state: FutureState) -> bool { future_state == FutureState::SendMessage && self.sequence_state == SequenceState::Finished } } fn process_send_data_request_pdu( pdu_data: BytesMut, sequence_state: SequenceState, filter_config: &FilterConfig, originator_id: Option<u16>, ) -> io::Result<(SequenceState, Vec<u8>, Option<LicenseCredentials>)> { match sequence_state { SequenceState::ClientInfo => { let mut client_info_pdu = ClientInfoPdu::from_buffer(pdu_data.as_ref())?; trace!("Got Client Info PDU: {:?}", client_info_pdu); client_info_pdu.filter(filter_config); trace!("Filtered Client Info PDU: {:?}", client_info_pdu); let mut client_info_pdu_buffer = Vec::with_capacity(client_info_pdu.buffer_length()); client_info_pdu.to_buffer(&mut client_info_pdu_buffer)?; Ok(( SequenceState::ServerLicenseRequest, client_info_pdu_buffer, Some(LicenseCredentials { username: client_info_pdu.client_info.credentials.username, hostname: client_info_pdu.client_info.credentials.domain.unwrap_or_default(), }), )) } SequenceState::ClientConfirmActive => { let mut share_control_header = ShareControlHeader::from_buffer(pdu_data.as_ref())?; let next_sequence_state = match (sequence_state, &mut share_control_header.share_control_pdu) { (SequenceState::ClientConfirmActive, ShareControlPdu::ClientConfirmActive(client_confirm_active)) => { if client_confirm_active.originator_id != originator_id.expect("Originator ID must be set during Server Demand Active PDU processing") { warn!( "Got invalid originator ID: {} != {}", client_confirm_active.originator_id, originator_id.unwrap() ); } client_confirm_active.pdu.filter(filter_config); trace!("Got Client Confirm Active PDU: {:?}", client_confirm_active); SequenceState::Finished } (_, share_control_pdu) => { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid client's Share Control Header PDU: {:?}", share_control_pdu.as_short_name() ), )) } }; let mut share_control_header_buffer = Vec::with_capacity(share_control_header.buffer_length()); share_control_header.to_buffer(&mut share_control_header_buffer)?; Ok((next_sequence_state, share_control_header_buffer, None)) } state => Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid sequence state ({:?}) in the client's RDP Connection Sequence", state ), )), } } pub struct IndicationData { originator_id: Option<u16>, encryption_data: Option<LicenseEncryptionData>, } fn process_send_data_indication_pdu( pdu_data: BytesMut, sequence_state: SequenceState, filter_config: &FilterConfig, encryption_data: Option<LicenseEncryptionData>, credentials: &LicenseCredentials, ) -> io::Result<(SequenceState, Vec<u8>, IndicationData)> { match sequence_state { SequenceState::ServerLicenseRequest => process_license_request(pdu_data.as_ref(), credentials), SequenceState::ServerChallenge => process_challenge(pdu_data.as_ref(), encryption_data, credentials), SequenceState::ServerUpgradeLicense => process_upgrade_license(pdu_data.as_ref(), encryption_data), SequenceState::ServerDemandActive => { let mut share_control_header = ShareControlHeader::from_buffer(pdu_data.as_ref())?; let next_sequence_state = match (sequence_state, &mut share_control_header.share_control_pdu) { (SequenceState::ServerDemandActive, ShareControlPdu::ServerDemandActive(server_demand_active)) => { server_demand_active.pdu.filter(filter_config); trace!("Got Server Demand Active PDU: {:?}", server_demand_active); SequenceState::ClientConfirmActive } (_, share_control_pdu) => { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid server's Share Control Header PDU: {:?}", share_control_pdu.as_short_name() ), )) } }; let mut share_control_header_buffer = Vec::with_capacity(share_control_header.buffer_length()); share_control_header.to_buffer(&mut share_control_header_buffer)?; Ok(( next_sequence_state, share_control_header_buffer, IndicationData { originator_id: Some(share_control_header.pdu_source), encryption_data: None, }, )) } state => Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid sequence state ({:?}) in the server's RDP Connection Sequence", state ), )), } } #[derive(Copy, Clone, Debug, PartialEq)] pub enum SequenceState { ClientInfo, ServerLicenseRequest, ServerChallenge, ServerUpgradeLicense, ServerDemandActive, ClientConfirmActive, Finished, }
e => NextStream::Server, SequenceState::Finished => panic!( "In RDP Connection Sequence, the future must not require a next sender in the Finished sequence state" ), } }
function_block-function_prefixed
[ { "content": "pub fn connect_as_server(mut stream: impl io::Write + io::Read, host: String) -> io::Result<Uuid> {\n\n let message = JetMessage::JetAcceptReq(JetAcceptReq {\n\n version: JET_VERSION_V1 as u32,\n\n host,\n\n association: Uuid::nil(),\n\n candidate: Uuid::nil(),\n\n ...
Rust
linkerd/app/outbound/src/target.rs
19h/linkerd2-proxy
20619fb1782216df515cd7927c764cfa58b6e46c
use linkerd_app_core::{ metrics, profiles, proxy::{ api_resolve::{ConcreteAddr, Metadata}, resolve::map_endpoint::MapEndpoint, }, svc::{self, stack::Param}, tls, transport, transport_header, Addr, Conditional, Error, }; use std::net::SocketAddr; #[derive(Copy, Clone)] pub struct EndpointFromMetadata; #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub struct Accept<P> { pub orig_dst: SocketAddr, pub protocol: P, } #[derive(Clone)] pub struct Logical<P> { pub orig_dst: SocketAddr, pub profile: Option<profiles::Receiver>, pub protocol: P, } #[derive(Clone, Debug)] pub struct Concrete<P> { pub resolve: ConcreteAddr, pub logical: Logical<P>, } #[derive(Clone, Debug)] pub struct Endpoint<P> { pub addr: SocketAddr, pub target_addr: SocketAddr, pub tls: tls::ConditionalClientTls, pub metadata: Metadata, pub logical: Logical<P>, } impl<P> Param<SocketAddr> for Accept<P> { fn param(&self) -> SocketAddr { self.orig_dst } } impl<P> Param<Addr> for Accept<P> { fn param(&self) -> Addr { self.orig_dst.into() } } impl<P> Param<transport::labels::Key> for Accept<P> { fn param(&self) -> transport::labels::Key { const NO_TLS: tls::ConditionalServerTls = Conditional::None(tls::NoServerTls::Loopback); transport::labels::Key::accept(transport::labels::Direction::Out, NO_TLS, self.orig_dst) } } impl<P> From<(Option<profiles::Receiver>, Accept<P>)> for Logical<P> { fn from( ( profile, Accept { orig_dst, protocol, .. }, ): (Option<profiles::Receiver>, Accept<P>), ) -> Self { Self { profile, orig_dst, protocol, } } } impl<P> Param<Option<profiles::Receiver>> for Logical<P> { fn param(&self) -> Option<profiles::Receiver> { self.profile.clone() } } impl<P> Param<SocketAddr> for Logical<P> { fn param(&self) -> SocketAddr { self.orig_dst } } impl<P> Param<profiles::LogicalAddr> for Logical<P> { fn param(&self) -> profiles::LogicalAddr { profiles::LogicalAddr(self.addr()) } } impl<P> Logical<P> { pub fn addr(&self) -> Addr { self.profile .as_ref() .and_then(|p| p.borrow().name.clone()) .map(|n| Addr::from((n, self.orig_dst.port()))) .unwrap_or_else(|| self.orig_dst.into()) } } impl<P: PartialEq> PartialEq<Logical<P>> for Logical<P> { fn eq(&self, other: &Logical<P>) -> bool { self.orig_dst == other.orig_dst && self.protocol == other.protocol } } impl<P: Eq> Eq for Logical<P> {} impl<P: std::hash::Hash> std::hash::Hash for Logical<P> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.orig_dst.hash(state); self.protocol.hash(state); } } impl<P: std::fmt::Debug> std::fmt::Debug for Logical<P> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Logical") .field("orig_dst", &self.orig_dst) .field("protocol", &self.protocol) .field( "profile", &format_args!( "{}", if self.profile.is_some() { "Some(..)" } else { "None" } ), ) .finish() } } impl<P> Logical<P> { pub fn or_endpoint( reason: tls::NoClientTls, ) -> impl Fn(Self) -> Result<svc::Either<Self, Endpoint<P>>, Error> + Copy { move |logical: Self| { let should_resolve = match logical.profile.as_ref() { Some(p) => { let p = p.borrow(); p.endpoint.is_none() && (p.name.is_some() || !p.targets.is_empty()) } None => false, }; if should_resolve { Ok(svc::Either::A(logical)) } else { Ok(svc::Either::B(Endpoint::from_logical(reason)(logical))) } } } } impl<P> From<(ConcreteAddr, Logical<P>)> for Concrete<P> { fn from((resolve, logical): (ConcreteAddr, Logical<P>)) -> Self { Self { resolve, logical } } } impl<P> Param<ConcreteAddr> for Concrete<P> { fn param(&self) -> ConcreteAddr { self.resolve.clone() } } impl<P> Endpoint<P> { pub fn from_logical(reason: tls::NoClientTls) -> impl (Fn(Logical<P>) -> Self) + Clone { move |logical| { let target_addr = logical.orig_dst; match logical .profile .as_ref() .and_then(|p| p.borrow().endpoint.clone()) { None => Self { addr: logical.param(), metadata: Metadata::default(), tls: Conditional::None(reason), logical, target_addr, }, Some((addr, metadata)) => Self { addr, tls: EndpointFromMetadata::client_tls(&metadata), metadata, logical, target_addr, }, } } } pub fn from_accept(reason: tls::NoClientTls) -> impl (Fn(Accept<P>) -> Self) + Clone { move |accept| Self::from_logical(reason)(Logical::from((None, accept))) } pub fn identity_disabled(mut self) -> Self { self.tls = Conditional::None(tls::NoClientTls::Disabled); self } } impl<P> Param<transport::ConnectAddr> for Endpoint<P> { fn param(&self) -> transport::ConnectAddr { transport::ConnectAddr(self.addr) } } impl<P> Param<tls::ConditionalClientTls> for Endpoint<P> { fn param(&self) -> tls::ConditionalClientTls { self.tls.clone() } } impl<P> Param<transport::labels::Key> for Endpoint<P> { fn param(&self) -> transport::labels::Key { transport::labels::Key::OutboundConnect(self.param()) } } impl<P> Param<metrics::OutboundEndpointLabels> for Endpoint<P> { fn param(&self) -> metrics::OutboundEndpointLabels { metrics::OutboundEndpointLabels { authority: Some(self.logical.addr().to_http_authority()), labels: metrics::prefix_labels("dst", self.metadata.labels().iter()), server_id: self.tls.clone(), target_addr: self.target_addr, } } } impl<P> Param<metrics::EndpointLabels> for Endpoint<P> { fn param(&self) -> metrics::EndpointLabels { Param::<metrics::OutboundEndpointLabels>::param(self).into() } } impl<P: std::hash::Hash> std::hash::Hash for Endpoint<P> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.addr.hash(state); self.tls.hash(state); self.logical.orig_dst.hash(state); self.logical.protocol.hash(state); } } impl EndpointFromMetadata { fn client_tls(metadata: &Metadata) -> tls::ConditionalClientTls { let use_transport_header = metadata.opaque_transport_port().is_some() || metadata.authority_override().is_some(); metadata .identity() .cloned() .map(move |server_id| { Conditional::Some(tls::ClientTls { server_id, alpn: if use_transport_header { Some(tls::client::AlpnProtocols(vec![ transport_header::PROTOCOL.into() ])) } else { None }, }) }) .unwrap_or(Conditional::None( tls::NoClientTls::NotProvidedByServiceDiscovery, )) } } impl<P: Clone + std::fmt::Debug> MapEndpoint<Concrete<P>, Metadata> for EndpointFromMetadata { type Out = Endpoint<P>; fn map_endpoint( &self, concrete: &Concrete<P>, addr: SocketAddr, metadata: Metadata, ) -> Self::Out { tracing::trace!(%addr, ?metadata, ?concrete, "Resolved endpoint"); Endpoint { addr, tls: Self::client_tls(&metadata), metadata, logical: concrete.logical.clone(), target_addr: concrete.logical.orig_dst, } } }
use linkerd_app_core::{ metrics, profiles, proxy::{ api_resolve::{ConcreteAddr, Metadata}, resolve::map_endpoint::MapEndpoint, }, svc::{self, stack::Param}, tls, transport, transport_header, Addr, Conditional, Error, }; use std::net::SocketAddr; #[derive(Copy, Clone)] pub struct EndpointFromMetadata; #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub struct Accept<P> { pub orig_dst: SocketAddr, pub protocol: P, } #[derive(Clone)] pub struct Logical<P> { pub orig_dst: SocketAddr, pub profile: Option<profiles::Receiver>, pub protocol: P, } #[derive(Clone, Debug)] pub struct Concrete<P> { pub resolve: ConcreteAddr, pub logical: Logical<P>, } #[derive(Clone, Debug)] pub struct Endpoint<P> { pub addr: SocketAddr, pub target_addr: SocketAddr, pub tls: tls::ConditionalClientTls, pub metadata: Metadata, pub logical: Logical<P>, } impl<P> Param<SocketAddr> for Accept<P> { fn param(&self) -> SocketAddr { self.orig_dst } } impl<P> Param<Addr> for Accept<P> { fn param(&self) -> Addr { self.orig_dst.into() } } impl<P> Param<transport::labels::Key> for Accept<P> { fn param(&self) -> transport::labels::Key { const NO_TLS: tls::ConditionalServerTls = Conditional::None(tls::NoServerTls::Loopback); transport::labels::Key::accept(transport::labels::Direction::Out, NO_TLS, self.orig_dst) } } impl<P> From<(Option<profiles::Receiver>, Accept<P>)> for Logical<P> { fn from( ( profile, Accept { orig_dst, protocol, .. }, ): (Option<profiles::Receiver>, Accept<P>), ) -> Self { Self { profile, orig_dst, protocol, } } } impl<P> Param<Option<profiles::Receiver>> for Logical<P> { fn param(&self) -> Option<profiles::Receiver> { self.profile.clone() } } impl<P> Param<SocketAddr> for Logical<P> { fn param(&self) -> SocketAddr { self.orig_dst } } impl<P> Param<profiles::LogicalAddr> for Logical<P> { fn param(&self) -> profiles::LogicalAddr { profiles::LogicalAddr(self.addr()) } } impl<P> Logical<P> { pub fn addr(&self) -> Addr { self.profile .as_ref() .and_then(|p| p.borrow().name.clone()) .map(|n| Addr::from((n, self.orig_dst.port()))) .unwrap_or_else(|| self.orig_dst.into()) } } impl<P: PartialEq> PartialEq<Logical<P>> for Logical<P> { fn eq(&self, other: &Logical<P>) -> bool { self.orig_dst == other.orig_dst && self.protocol == other.protocol } } impl<P: Eq> Eq for Logical<P> {} impl<P: std::hash::Hash> std::hash::Hash for Logical<P> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.orig_dst.hash(state); self.protocol.hash(state); } } impl<P: std::fmt::Debug> std::fmt::Debug for Logical<P> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Logical") .field("orig_dst", &self.orig_dst) .field("protocol", &self.protocol) .field( "profile", &format_args!( "{}", if self.profile.is_some() { "Some(..)" } else { "None" } ), ) .finish() } } impl<P> Logical<P> { pub fn or_endpoint( reason: tls::No
} impl<P> From<(ConcreteAddr, Logical<P>)> for Concrete<P> { fn from((resolve, logical): (ConcreteAddr, Logical<P>)) -> Self { Self { resolve, logical } } } impl<P> Param<ConcreteAddr> for Concrete<P> { fn param(&self) -> ConcreteAddr { self.resolve.clone() } } impl<P> Endpoint<P> { pub fn from_logical(reason: tls::NoClientTls) -> impl (Fn(Logical<P>) -> Self) + Clone { move |logical| { let target_addr = logical.orig_dst; match logical .profile .as_ref() .and_then(|p| p.borrow().endpoint.clone()) { None => Self { addr: logical.param(), metadata: Metadata::default(), tls: Conditional::None(reason), logical, target_addr, }, Some((addr, metadata)) => Self { addr, tls: EndpointFromMetadata::client_tls(&metadata), metadata, logical, target_addr, }, } } } pub fn from_accept(reason: tls::NoClientTls) -> impl (Fn(Accept<P>) -> Self) + Clone { move |accept| Self::from_logical(reason)(Logical::from((None, accept))) } pub fn identity_disabled(mut self) -> Self { self.tls = Conditional::None(tls::NoClientTls::Disabled); self } } impl<P> Param<transport::ConnectAddr> for Endpoint<P> { fn param(&self) -> transport::ConnectAddr { transport::ConnectAddr(self.addr) } } impl<P> Param<tls::ConditionalClientTls> for Endpoint<P> { fn param(&self) -> tls::ConditionalClientTls { self.tls.clone() } } impl<P> Param<transport::labels::Key> for Endpoint<P> { fn param(&self) -> transport::labels::Key { transport::labels::Key::OutboundConnect(self.param()) } } impl<P> Param<metrics::OutboundEndpointLabels> for Endpoint<P> { fn param(&self) -> metrics::OutboundEndpointLabels { metrics::OutboundEndpointLabels { authority: Some(self.logical.addr().to_http_authority()), labels: metrics::prefix_labels("dst", self.metadata.labels().iter()), server_id: self.tls.clone(), target_addr: self.target_addr, } } } impl<P> Param<metrics::EndpointLabels> for Endpoint<P> { fn param(&self) -> metrics::EndpointLabels { Param::<metrics::OutboundEndpointLabels>::param(self).into() } } impl<P: std::hash::Hash> std::hash::Hash for Endpoint<P> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.addr.hash(state); self.tls.hash(state); self.logical.orig_dst.hash(state); self.logical.protocol.hash(state); } } impl EndpointFromMetadata { fn client_tls(metadata: &Metadata) -> tls::ConditionalClientTls { let use_transport_header = metadata.opaque_transport_port().is_some() || metadata.authority_override().is_some(); metadata .identity() .cloned() .map(move |server_id| { Conditional::Some(tls::ClientTls { server_id, alpn: if use_transport_header { Some(tls::client::AlpnProtocols(vec![ transport_header::PROTOCOL.into() ])) } else { None }, }) }) .unwrap_or(Conditional::None( tls::NoClientTls::NotProvidedByServiceDiscovery, )) } } impl<P: Clone + std::fmt::Debug> MapEndpoint<Concrete<P>, Metadata> for EndpointFromMetadata { type Out = Endpoint<P>; fn map_endpoint( &self, concrete: &Concrete<P>, addr: SocketAddr, metadata: Metadata, ) -> Self::Out { tracing::trace!(%addr, ?metadata, ?concrete, "Resolved endpoint"); Endpoint { addr, tls: Self::client_tls(&metadata), metadata, logical: concrete.logical.clone(), target_addr: concrete.logical.orig_dst, } } }
ClientTls, ) -> impl Fn(Self) -> Result<svc::Either<Self, Endpoint<P>>, Error> + Copy { move |logical: Self| { let should_resolve = match logical.profile.as_ref() { Some(p) => { let p = p.borrow(); p.endpoint.is_none() && (p.name.is_some() || !p.targets.is_empty()) } None => false, }; if should_resolve { Ok(svc::Either::A(logical)) } else { Ok(svc::Either::B(Endpoint::from_logical(reason)(logical))) } } }
function_block-function_prefixed
[ { "content": "pub fn new<K: Eq + Hash + FmtLabels>(retain_idle: Duration) -> (Registry<K>, Report<K>) {\n\n let inner = Arc::new(Mutex::new(Inner::new()));\n\n let report = Report {\n\n metrics: inner.clone(),\n\n retain_idle,\n\n };\n\n (Registry(inner), report)\n\n}\n\n\n\n/// Implem...
Rust
src/lib.rs
zklapow/sbus
9ca73cb0d58d7a13db3d48103de5fdb51e6d9154
#![no_std] mod taranis; pub use taranis::TaranisX7SBusPacket; use arraydeque::{ArrayDeque, Wrapping}; const SBUS_FLAG_BYTE_MASK: u8 = 0b11110000; const SBUS_HEADER_BYTE: u8 = 0x0F; const SBUS_FOOTER_BYTE: u8 = 0b00000000; const SBUS_PACKET_SIZE: usize = 25; #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Copy, Clone)] pub struct SBusPacket { channels: [u16; 16], d1: bool, d2: bool, failsafe: bool, frame_lost: bool, } pub struct SBusPacketParser { buffer: ArrayDeque<[u8; (SBUS_PACKET_SIZE * 2) as usize], Wrapping>, } impl SBusPacketParser { pub fn new() -> SBusPacketParser { SBusPacketParser { buffer: ArrayDeque::new(), } } pub fn push_bytes(&mut self, bytes: &[u8]) { bytes.iter().for_each(|b| { self.buffer.push_back(*b); }) } pub fn try_parse(&mut self) -> Option<SBusPacket> { if self.buffer.len() < SBUS_PACKET_SIZE { return None; } if *self.buffer.get(0).unwrap() != SBUS_HEADER_BYTE { while self.buffer.len() > 0 && *self.buffer.get(0).unwrap() != SBUS_HEADER_BYTE { let _ = self.buffer.pop_front().unwrap(); } return None; } else if *self.buffer.get(SBUS_PACKET_SIZE - 1).unwrap() == SBUS_FOOTER_BYTE && self.buffer.get(SBUS_PACKET_SIZE - 2).unwrap() & SBUS_FLAG_BYTE_MASK == 0 { let mut data_bytes: [u16; 23] = [0; 23]; for i in 0..23 { data_bytes[i] = self.buffer.pop_front().unwrap_or(0) as u16; } let mut channels: [u16; 16] = [0; 16]; channels[0] = (((data_bytes[1]) | (data_bytes[2] << 8)) as u16 & 0x07FF).into(); channels[1] = ((((data_bytes[2] >> 3) | (data_bytes[3] << 5)) as u16) & 0x07FF).into(); channels[2] = ((((data_bytes[3] >> 6) | (data_bytes[4] << 2) | (data_bytes[5] << 10)) as u16) & 0x07FF) .into(); channels[3] = ((((data_bytes[5] >> 1) | (data_bytes[6] << 7)) as u16) & 0x07FF).into(); channels[4] = ((((data_bytes[6] >> 4) | (data_bytes[7] << 4)) as u16) & 0x07FF).into(); channels[5] = ((((data_bytes[7] >> 7) | (data_bytes[8] << 1) | (data_bytes[9] << 9)) as u16) & 0x07FF) .into(); channels[6] = ((((data_bytes[9] >> 2) | (data_bytes[10] << 6)) as u16) & 0x07FF).into(); channels[7] = ((((data_bytes[10] >> 5) | (data_bytes[11] << 3)) as u16) & 0x07FF).into(); channels[8] = ((((data_bytes[12]) | (data_bytes[13] << 8)) as u16) & 0x07FF).into(); channels[9] = ((((data_bytes[13] >> 3) | (data_bytes[14] << 5)) as u16) & 0x07FF).into(); channels[10] = ((((data_bytes[14] >> 6) | (data_bytes[15] << 2) | (data_bytes[16] << 10)) as u16) & 0x07FF) .into(); channels[11] = ((((data_bytes[16] >> 1) | (data_bytes[17] << 7)) as u16) & 0x07FF).into(); channels[12] = ((((data_bytes[17] >> 4) | (data_bytes[18] << 4)) as u16) & 0x07FF).into(); channels[13] = ((((data_bytes[18] >> 7) | (data_bytes[19] << 1) | (data_bytes[20] << 9)) as u16) & 0x07FF) .into(); channels[14] = ((((data_bytes[20] >> 2) | (data_bytes[21] << 6)) as u16) & 0x07FF).into(); channels[15] = ((((data_bytes[21] >> 5) | (data_bytes[22] << 3)) as u16) & 0x07FF).into(); let flag_byte = self.buffer.pop_front().unwrap_or(0); return Some(SBusPacket { channels, d1: is_flag_set(flag_byte, 0), d2: is_flag_set(flag_byte, 1), frame_lost: is_flag_set(flag_byte, 2), failsafe: is_flag_set(flag_byte, 3), }); } else { while self.buffer.len() > 0 && *self.buffer.get(0).unwrap() != SBUS_HEADER_BYTE { self.buffer.pop_front(); } } return None; } } fn is_flag_set(flag_byte: u8, idx: u8) -> bool { flag_byte & 1 << idx == 1 }
#![no_std] mod taranis; pub use taranis::TaranisX7SBusPacket; use arraydeque::{ArrayDeque, Wrapping}; const SBUS_FLAG_BYTE_MASK: u8 = 0b11110000; const SBUS_HEADER_BYTE: u8 = 0x0F; const SBUS_FOOTER_BYTE: u8 = 0b00000000; const SBUS_PACKET_SIZE: usize = 25; #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Copy, Clone)] pub struct SBusPacket { channels: [u16; 16], d1: bool, d2: bool, failsafe: bool, frame_lost: bool, } pub struct SBusPacketParser { buffer: ArrayDeque<[u8; (SBUS_PACKET_SIZE * 2) as usize], Wrapping>, } impl SBusPacketParser { pub fn new() -> SBusPacketParser { SBusPacketParser { buffer: ArrayDeque::new(), } } pub fn push_bytes(&mut self, bytes: &[u8]) { bytes.iter().for_each(|b| { self.buffer.push_back(*b); }) } pub fn try_parse(&mut self) -> Option<SBusPacket> { if self.buffer.len() < SBUS_PACKET_SIZE { return None; } if *self.buffer.get(0).unwrap() != SBUS_HEADER_BYTE { while self.buffer.len() > 0 && *self.buffer.get(0).unwrap() != SBUS_HEADER_BYTE { let _ = self.buffer.pop_front().unwrap(); } return None; } else if *self.buffer.get(SBUS_PACKET_SIZE - 1).unwrap() == SBUS_FOOTER_BYTE && self.buffer.get(SBUS_PACKET_SIZE - 2).unwrap() & SBUS_FLAG_BYTE_MASK == 0 { let mut data_bytes: [u16; 23] = [0; 23]; for i in 0..23 { data_bytes[i] = self.buffer.pop_front().unwrap_or(0) as u16; } let mut channels: [u16; 16] = [0; 16]; channels[0] = (((data_bytes[1]) | (data_bytes[2] << 8)) as u16 & 0x07FF).into(); channels[1] = ((((data_bytes[2] >> 3) | (data_bytes[3] << 5)) as u16) & 0x07FF).into(); channels[2] = ((((data_bytes[3] >> 6) | (data_bytes[4] << 2) | (data_bytes[5] << 10)) as u16) & 0x07FF) .into(); channels[3] = ((((data_bytes[5] >> 1) | (data_bytes[6] << 7)) as u16) & 0x07FF).into(); channels[4] = ((((data_bytes[6] >> 4) | (data_bytes[7] << 4)) as u16) & 0x07FF).into(); channels[5] = ((((data_bytes[7] >> 7) | (data_bytes[8] << 1) | (data_bytes[9] << 9)) as u16) & 0x07FF) .into(); channels[6] = ((((data_bytes[9] >> 2) | (data_bytes[10] << 6)) as u16) & 0x07FF).into(); channels[7] = ((((data_bytes[10] >> 5) | (data_bytes[11] << 3)) as u16) & 0x07FF).into(); channels[8] = ((((data_bytes[12]) | (data_bytes[13] << 8)) as u16) & 0x07FF).into(); channels[9] = ((((data_bytes[13] >> 3) | (data_bytes[14] << 5)) as u16) & 0x07FF).into(); channels[10] = ((((data_bytes[14] >> 6) | (data_bytes[15] << 2) | (data_bytes[16] << 10)) as u16) & 0x07FF) .into(); channels[11] = ((((data_bytes[16] >> 1) | (data_bytes[17] << 7)) as u16) & 0x07FF).into(); channels[12] = ((((data_bytes[17] >> 4) | (data_bytes[18] << 4)) as u16) & 0x07FF).into(); channels[13] = ((((data_bytes[18] >> 7) | (data_bytes[19] << 1) | (data_bytes[20] << 9)) as u16) & 0x07FF) .into();
} fn is_flag_set(flag_byte: u8, idx: u8) -> bool { flag_byte & 1 << idx == 1 }
channels[14] = ((((data_bytes[20] >> 2) | (data_bytes[21] << 6)) as u16) & 0x07FF).into(); channels[15] = ((((data_bytes[21] >> 5) | (data_bytes[22] << 3)) as u16) & 0x07FF).into(); let flag_byte = self.buffer.pop_front().unwrap_or(0); return Some(SBusPacket { channels, d1: is_flag_set(flag_byte, 0), d2: is_flag_set(flag_byte, 1), frame_lost: is_flag_set(flag_byte, 2), failsafe: is_flag_set(flag_byte, 3), }); } else { while self.buffer.len() > 0 && *self.buffer.get(0).unwrap() != SBUS_HEADER_BYTE { self.buffer.pop_front(); } } return None; }
function_block-function_prefix_line
[ { "content": "use crate::SBusPacket;\n\n\n\nconst X7_MIN: u16 = 172;\n\nconst X7_MAX: u16 = 1811;\n\nconst X7_RANGE: f32 = (X7_MAX - X7_MIN) as f32;\n\n\n\n#[derive(Debug, Copy, Clone)]\n\npub struct TaranisX7SBusPacket {\n\n pub channels: [f32; 16],\n\n failsafe: bool,\n\n frame_lost: bool,\n\n}\n\n\n...
Rust
sdk/storage/src/file/share/mod.rs
elemount/azure-sdk-for-rust
ba0cc92ba5245f93ade4270aa54a897cc8f78d92
pub mod access_tier; pub mod requests; pub mod responses; use crate::parsing_xml::{cast_must, cast_optional, traverse}; use access_tier::AccessTier; use azure_core::headers::{ META_PREFIX, SHARE_NEXT_ALLOWED_QUOTA_DOWNGRADE_TIME, SHARE_PROVISIONED_EGRESS_MBPS, SHARE_PROVISIONED_INGRESS_MBPS, SHARE_PROVISIONED_IOPS, SHARE_QUOTA, STORAGE_ACCESS_TIER, }; use azure_core::incompletevector::IncompleteVector; use chrono::{DateTime, Utc}; use http::{header, HeaderMap}; use std::collections::HashMap; use std::str::FromStr; use xml::{Element, Xml}; #[derive(Debug, Clone)] pub struct Share { pub name: String, pub snapshot: Option<String>, pub version: Option<String>, pub deleted: bool, pub last_modified: DateTime<Utc>, pub e_tag: String, pub quota: u64, pub provisioned_iops: Option<u64>, pub provisioned_ingress_mbps: Option<u64>, pub provisioned_egress_mbps: Option<u64>, pub next_allowed_quota_downgrade_time: Option<DateTime<Utc>>, pub deleted_time: Option<DateTime<Utc>>, pub remaining_retention_days: Option<u64>, pub access_tier: AccessTier, pub metadata: HashMap<String, String>, } impl AsRef<str> for Share { fn as_ref(&self) -> &str { &self.name } } impl Share { pub fn new(name: &str) -> Share { Share { name: name.to_owned(), snapshot: None, version: None, deleted: false, last_modified: Utc::now(), e_tag: "".to_owned(), quota: 0, provisioned_iops: None, provisioned_ingress_mbps: None, provisioned_egress_mbps: None, next_allowed_quota_downgrade_time: None, deleted_time: None, remaining_retention_days: None, access_tier: AccessTier::TransactionOptimized, metadata: HashMap::new(), } } pub(crate) fn from_response<NAME>( name: NAME, headers: &HeaderMap, ) -> Result<Share, crate::Error> where NAME: Into<String>, { let last_modified = match headers.get(header::LAST_MODIFIED) { Some(last_modified) => last_modified.to_str()?, None => { static LM: header::HeaderName = header::LAST_MODIFIED; return Err(crate::Error::MissingHeaderError(LM.as_str().to_owned())); } }; let last_modified = DateTime::parse_from_rfc2822(last_modified)?; let last_modified = DateTime::from_utc(last_modified.naive_utc(), Utc); let e_tag = match headers.get(header::ETAG) { Some(e_tag) => e_tag.to_str()?.to_owned(), None => { return Err(crate::Error::MissingHeaderError( header::ETAG.as_str().to_owned(), )); } }; let access_tier = match headers.get(STORAGE_ACCESS_TIER) { Some(access_tier) => access_tier.to_str()?, None => { return Err(crate::Error::MissingHeaderError( STORAGE_ACCESS_TIER.to_owned(), )) } }; let access_tier = AccessTier::from_str(access_tier)?; let quota = match headers.get(SHARE_QUOTA) { Some(quota_str) => quota_str.to_str()?.parse::<u64>()?, None => { return Err(crate::Error::MissingHeaderError(SHARE_QUOTA.to_owned())); } }; let provisioned_iops = match headers.get(SHARE_PROVISIONED_IOPS) { Some(value) => Some(value.to_str()?.parse::<u64>()?), None => None, }; let provisioned_ingress_mbps = match headers.get(SHARE_PROVISIONED_INGRESS_MBPS) { Some(value) => Some(value.to_str()?.parse::<u64>()?), None => None, }; let provisioned_egress_mbps = match headers.get(SHARE_PROVISIONED_EGRESS_MBPS) { Some(value) => Some(value.to_str()?.parse::<u64>()?), None => None, }; let next_allowed_quota_downgrade_time = match headers.get(SHARE_NEXT_ALLOWED_QUOTA_DOWNGRADE_TIME) { Some(value) => Some(DateTime::from_utc( DateTime::parse_from_rfc2822(value.to_str()?)?.naive_utc(), Utc, )), None => None, }; let mut metadata: HashMap<String, String> = HashMap::new(); for (key, value) in headers { if key.as_str().starts_with(META_PREFIX) { metadata.insert(key.as_str().to_owned(), value.to_str()?.to_owned()); } } Ok(Share { name: name.into(), last_modified, e_tag, access_tier, quota, provisioned_iops, provisioned_ingress_mbps, provisioned_egress_mbps, next_allowed_quota_downgrade_time, metadata, snapshot: None, version: None, deleted: false, deleted_time: None, remaining_retention_days: None, }) } fn parse(elem: &Element) -> Result<Share, crate::Error> { let name = cast_must::<String>(elem, &["Name"])?; let snapshot = cast_optional::<String>(elem, &["Snapshot"])?; let version = cast_optional::<String>(elem, &["Version"])?; let deleted = match cast_optional::<bool>(elem, &["Deleted"])? { Some(deleted_status) => deleted_status, None => false, }; let last_modified = cast_must::<DateTime<Utc>>(elem, &["Properties", "Last-Modified"])?; let e_tag = cast_must::<String>(elem, &["Properties", "Etag"])?; let quota = cast_must::<u64>(elem, &["Properties", "Quota"])?; let deleted_time = cast_optional::<DateTime<Utc>>(elem, &["Properties", "DeletedTime"])?; let remaining_retention_days = cast_optional::<u64>(elem, &["Properties", "RemainingRetentionDays"])?; let access_tier = cast_must::<AccessTier>(elem, &["Properties", "AccessTier"])?; let metadata = { let mut hm = HashMap::new(); let metadata = traverse(elem, &["Metadata"], true)?; for m in metadata { for key in &m.children { let elem = match key { Xml::ElementNode(elem) => elem, _ => { return Err(crate::Error::UnexpectedXMLError(String::from( "Metadata should contain an ElementNode", ))); } }; let key = elem.name.to_owned(); if elem.children.is_empty() { return Err(crate::Error::UnexpectedXMLError(String::from( "Metadata node should not be empty", ))); } let content = { match elem.children[0] { Xml::CharacterNode(ref content) => content.to_owned(), _ => { return Err(crate::Error::UnexpectedXMLError(String::from( "Metadata node should contain a CharacterNode with metadata value", ))); } } }; hm.insert(key, content); } } hm }; Ok(Share { name, snapshot, version, deleted, last_modified, e_tag, quota, deleted_time, remaining_retention_days, access_tier, metadata, provisioned_iops: None, provisioned_ingress_mbps: None, provisioned_egress_mbps: None, next_allowed_quota_downgrade_time: None, }) } } pub(crate) fn incomplete_vector_from_share_response( body: &str, ) -> Result<IncompleteVector<Share>, crate::Error> { let elem: Element = body.parse()?; let mut v = Vec::new(); for share in traverse(&elem, &["Shares", "Share"], true)? { v.push(Share::parse(share)?); } let next_marker = match cast_optional::<String>(&elem, &["NextMarker"])? { Some(ref nm) if nm.is_empty() => None, Some(nm) => Some(nm.into()), None => None, }; Ok(IncompleteVector::new(next_marker, v)) }
pub mod access_tier; pub mod requests; pub mod responses; use crate::parsing_xml::{cast_must, cast_optional, traverse}; use access_tier::AccessTier; use azure_core::headers::{ META_PREFIX, SHARE_NEXT_ALLOWED_QUOTA_DOWNGRADE_TIME, SHARE_PROVISIONED_EGRESS_MBPS, SHARE_PROVISIONED_INGRESS_MBPS, SHARE_PROVISIONED_IOPS, SHARE_QUOTA, STORAGE_ACCESS_TIER, }; use azure_core::incompletevector::IncompleteVector; use chrono::{DateTime, Utc}; use http::{header, HeaderMap}; use std::collections::HashMap; use std::str::FromStr; use xml::{Element, Xml}; #[derive(Debug, Clone)] pub struct Share { pub name: String, pub snapshot: Option<String>, pub version: Option<String>, pub deleted: bool, pub last_modified: DateTime<Utc>, pub e_tag: String, pub quota: u64, pub provisioned_iops: Option<u64>, pub provisioned_ingress_mbps: Option<u64>, pub provisioned_egress_mbps: Option<u64>, pub next_allowed_quota_downgrade_time: Option<DateTime<Utc>>, pub deleted_time: Option<DateTime<Utc>>, pub remaining_retention_days: Option<u64>, pub access_tier: AccessTier, pub metadata: HashMap<String, String>, } impl AsRef<str> for Share { fn as_ref(&self) -> &str { &self.name } } impl Share { pub fn new(name: &str) -> Share { Share { name: name.to_owned(), snapshot: None, version: None, deleted: false, last_modified: Utc::now(), e_tag: "".to_owned(), quota: 0, provisioned_iops: None, provisioned_ingress_mbps: None, provisioned_egress_mbps: None, next_allowed_quota_downgrade_time: None, deleted_time: None, remaining_retention_days: None, access_tier: AccessTier::TransactionOptimized, metadata: HashMap::new(), } } pub(crate) fn from_response<NAME>( name: NAME, headers: &HeaderMap, ) -> Result<Share, crate::Error> where NAME: Into<String>, { let last_modified = match headers.get(header::LAST_MODIFIED) { Some(last_modified) => last_modified.to_str()?, None => { static LM: header::HeaderName = header::LAST_MODIFIED; return Err(crate::Error::MissingHeaderError(LM.as_str().to_owned())); } }; let last_modified = DateTime::parse_from_rfc2822(last_modified)?; let last_modified = DateTime::from_utc(last_modified.naive_utc(), Utc); let e_tag = match headers.get(header::ETAG) { Some(e_tag) => e_tag.to_str()?.to_owned(), None => { return Err(crate::Error::MissingHeaderError( header::ETAG.as_str().to_owned(), )); } }; let access_tier = match headers.get(STORAGE_ACCESS_TIER) { Some(access_tier) => access_tier.to_str()?, None => { return Err(crate::Error::MissingHeaderError( STORAGE_ACCESS_TIER.to_owned(), )) } }; let access_tier = AccessTier::from_str(access_tier)?; let quota = match headers.get(SHARE_QUOTA) { Some(quota_str) => quota_str.to_str()?.parse::<u64>()?, None => { return Err(crate::Error::MissingHeaderError(SHARE_QUOTA.to_owned())); } };
let provisioned_ingress_mbps = match headers.get(SHARE_PROVISIONED_INGRESS_MBPS) { Some(value) => Some(value.to_str()?.parse::<u64>()?), None => None, }; let provisioned_egress_mbps = match headers.get(SHARE_PROVISIONED_EGRESS_MBPS) { Some(value) => Some(value.to_str()?.parse::<u64>()?), None => None, }; let next_allowed_quota_downgrade_time = match headers.get(SHARE_NEXT_ALLOWED_QUOTA_DOWNGRADE_TIME) { Some(value) => Some(DateTime::from_utc( DateTime::parse_from_rfc2822(value.to_str()?)?.naive_utc(), Utc, )), None => None, }; let mut metadata: HashMap<String, String> = HashMap::new(); for (key, value) in headers { if key.as_str().starts_with(META_PREFIX) { metadata.insert(key.as_str().to_owned(), value.to_str()?.to_owned()); } } Ok(Share { name: name.into(), last_modified, e_tag, access_tier, quota, provisioned_iops, provisioned_ingress_mbps, provisioned_egress_mbps, next_allowed_quota_downgrade_time, metadata, snapshot: None, version: None, deleted: false, deleted_time: None, remaining_retention_days: None, }) } fn parse(elem: &Element) -> Result<Share, crate::Error> { let name = cast_must::<String>(elem, &["Name"])?; let snapshot = cast_optional::<String>(elem, &["Snapshot"])?; let version = cast_optional::<String>(elem, &["Version"])?; let deleted = match cast_optional::<bool>(elem, &["Deleted"])? { Some(deleted_status) => deleted_status, None => false, }; let last_modified = cast_must::<DateTime<Utc>>(elem, &["Properties", "Last-Modified"])?; let e_tag = cast_must::<String>(elem, &["Properties", "Etag"])?; let quota = cast_must::<u64>(elem, &["Properties", "Quota"])?; let deleted_time = cast_optional::<DateTime<Utc>>(elem, &["Properties", "DeletedTime"])?; let remaining_retention_days = cast_optional::<u64>(elem, &["Properties", "RemainingRetentionDays"])?; let access_tier = cast_must::<AccessTier>(elem, &["Properties", "AccessTier"])?; let metadata = { let mut hm = HashMap::new(); let metadata = traverse(elem, &["Metadata"], true)?; for m in metadata { for key in &m.children { let elem = match key { Xml::ElementNode(elem) => elem, _ => { return Err(crate::Error::UnexpectedXMLError(String::from( "Metadata should contain an ElementNode", ))); } }; let key = elem.name.to_owned(); if elem.children.is_empty() { return Err(crate::Error::UnexpectedXMLError(String::from( "Metadata node should not be empty", ))); } let content = { match elem.children[0] { Xml::CharacterNode(ref content) => content.to_owned(), _ => { return Err(crate::Error::UnexpectedXMLError(String::from( "Metadata node should contain a CharacterNode with metadata value", ))); } } }; hm.insert(key, content); } } hm }; Ok(Share { name, snapshot, version, deleted, last_modified, e_tag, quota, deleted_time, remaining_retention_days, access_tier, metadata, provisioned_iops: None, provisioned_ingress_mbps: None, provisioned_egress_mbps: None, next_allowed_quota_downgrade_time: None, }) } } pub(crate) fn incomplete_vector_from_share_response( body: &str, ) -> Result<IncompleteVector<Share>, crate::Error> { let elem: Element = body.parse()?; let mut v = Vec::new(); for share in traverse(&elem, &["Shares", "Share"], true)? { v.push(Share::parse(share)?); } let next_marker = match cast_optional::<String>(&elem, &["NextMarker"])? { Some(ref nm) if nm.is_empty() => None, Some(nm) => Some(nm.into()), None => None, }; Ok(IncompleteVector::new(next_marker, v)) }
let provisioned_iops = match headers.get(SHARE_PROVISIONED_IOPS) { Some(value) => Some(value.to_str()?.parse::<u64>()?), None => None, };
assignment_statement
[]
Rust
dora/src/gc/swiper/sweep.rs
dinfuehr/dora
bcfdac576b729e2bbb2422d0239426b884059b2c
use parking_lot::Mutex; use scoped_threadpool::Pool; use std::sync::Arc; use crate::driver::cmd::Args; use crate::gc::root::{get_rootset, Slot}; use crate::gc::swiper::card::CardTable; use crate::gc::swiper::controller::{self, HeapConfig, SharedHeapConfig}; use crate::gc::swiper::crossing::CrossingMap; use crate::gc::swiper::large::LargeSpace; use crate::gc::swiper::sweep::old::OldGen; use crate::gc::swiper::verify::VerifierPhase; use crate::gc::swiper::young::YoungGen; use crate::gc::swiper::{CollectionKind, CARD_SIZE_BITS, LARGE_OBJECT_SIZE}; use crate::gc::tlab; use crate::gc::{align_gen, formatted_size, GEN_SIZE}; use crate::gc::{Address, Collector, GcReason, Region}; use crate::mem; use crate::os::{self, MemoryPermission}; use crate::safepoint; use crate::vm::VM; mod old; mod sweep; pub struct SweepSwiper { heap: Region, reserved_area: Region, young: YoungGen, old: OldGen, large: LargeSpace, card_table: CardTable, crossing_map: CrossingMap, card_table_offset: usize, emit_write_barrier: bool, min_heap_size: usize, max_heap_size: usize, threadpool: Mutex<Pool>, config: SharedHeapConfig, } impl SweepSwiper { pub fn new(args: &Args) -> SweepSwiper { let max_heap_size = align_gen(args.max_heap_size()); let min_heap_size = align_gen(args.min_heap_size()); let mut config = HeapConfig::new(min_heap_size, max_heap_size); controller::init(&mut config, args); let card_size = mem::page_align((4 * max_heap_size) >> CARD_SIZE_BITS); let crossing_size = mem::page_align(max_heap_size >> CARD_SIZE_BITS); let reserve_size = max_heap_size * 4 + card_size + crossing_size; let reservation = os::reserve_align(reserve_size, GEN_SIZE, false); let heap_start = reservation.start; assert!(heap_start.is_gen_aligned()); let heap_end = heap_start.offset(4 * max_heap_size); let reserved_area = heap_start.region_start(reserve_size); let card_table_offset = heap_end.to_usize() - (heap_start.to_usize() >> CARD_SIZE_BITS); let card_start = heap_end; let card_end = card_start.offset(card_size); os::commit_at(card_start, card_size, MemoryPermission::ReadWrite); let crossing_start = card_end; let crossing_end = crossing_start.offset(crossing_size); os::commit_at(crossing_start, crossing_size, MemoryPermission::ReadWrite); let young_start = heap_start; let young_end = young_start.offset(max_heap_size); let young = Region::new(young_start, young_end); let old_start = young_end; let old_end = old_start.offset(max_heap_size); let eden_size = config.eden_size; let semi_size = config.semi_size; let large_start = old_end; let large_end = large_start.offset(2 * max_heap_size); let card_table = CardTable::new( card_start, card_end, Region::new(old_start, large_end), old_end, max_heap_size, ); let crossing_map = CrossingMap::new(crossing_start, crossing_end, max_heap_size); let young = YoungGen::new(young, eden_size, semi_size, args.flag_gc_verify); let config = Arc::new(Mutex::new(config)); let old = OldGen::new( old_start, old_end, crossing_map.clone(), card_table.clone(), config.clone(), ); let large = LargeSpace::new(large_start, large_end, config.clone()); if args.flag_gc_verbose { println!( "GC: heap info: {}, eden {}, semi {}, card {}, crossing {}", formatted_size(max_heap_size), formatted_size(eden_size), formatted_size(semi_size), formatted_size(card_size), formatted_size(crossing_size) ); } let nworkers = args.gc_workers(); let emit_write_barrier = !args.flag_disable_barrier; SweepSwiper { heap: Region::new(heap_start, heap_end), reserved_area, young, old, large, card_table, crossing_map, config, card_table_offset, emit_write_barrier, min_heap_size, max_heap_size, threadpool: Mutex::new(Pool::new(nworkers as u32)), } } } impl Collector for SweepSwiper { fn supports_tlab(&self) -> bool { true } fn alloc_tlab_area(&self, _vm: &VM, _size: usize) -> Option<Region> { unimplemented!() } fn alloc(&self, vm: &VM, size: usize, array_ref: bool) -> Address { if size < LARGE_OBJECT_SIZE { self.alloc_normal(vm, size, array_ref) } else { self.alloc_large(vm, size, array_ref) } } fn collect(&self, _vm: &VM, _reason: GcReason) { unimplemented!() } fn minor_collect(&self, _vm: &VM, _reason: GcReason) { unimplemented!() } fn needs_write_barrier(&self) -> bool { self.emit_write_barrier } fn card_table_offset(&self) -> usize { self.card_table_offset } fn dump_summary(&self, _runtime: f32) { unimplemented!() } fn verify_ref(&self, _vm: &VM, _reference: Address) { unimplemented!() } } impl SweepSwiper { fn perform_collection_and_choose(&self, vm: &VM, reason: GcReason) -> CollectionKind { let kind = controller::choose_collection_kind(&self.config, &vm.args, &self.young); self.perform_collection(vm, kind, reason) } fn perform_collection( &self, vm: &VM, kind: CollectionKind, mut reason: GcReason, ) -> CollectionKind { safepoint::stop_the_world(vm, |threads| { controller::start(&self.config, &self.young, &self.old, &self.large); tlab::make_iterable_all(vm, threads); let rootset = get_rootset(vm, threads); let kind = match kind { CollectionKind::Minor => { let promotion_failed = self.minor_collect(vm, reason, &rootset); if promotion_failed { reason = GcReason::PromotionFailure; self.full_collect(vm, reason, &rootset); CollectionKind::Full } else { CollectionKind::Minor } } CollectionKind::Full => { self.full_collect(vm, reason, &rootset); CollectionKind::Full } }; controller::stop( &self.config, kind, &self.young, &self.old, &self.large, &vm.args, reason, ); kind }) } fn minor_collect(&self, _vm: &VM, _reason: GcReason, _rootset: &[Slot]) -> bool { unimplemented!() } fn full_collect(&self, _vm: &VM, _reason: GcReason, _rootset: &[Slot]) { unimplemented!(); } fn verify( &self, _vm: &VM, _phase: VerifierPhase, _kind: CollectionKind, _name: &str, _rootset: &[Slot], _promotion_failed: bool, ) { unimplemented!(); } fn alloc_normal(&self, vm: &VM, size: usize, _array_ref: bool) -> Address { let ptr = self.young.bump_alloc(size); if !ptr.is_null() { return ptr; } self.perform_collection_and_choose(vm, GcReason::AllocationFailure); self.young.bump_alloc(size) } fn alloc_large(&self, vm: &VM, size: usize, _: bool) -> Address { let ptr = self.large.alloc(size); if !ptr.is_null() { return ptr; } self.perform_collection(vm, CollectionKind::Full, GcReason::AllocationFailure); self.large.alloc(size) } }
use parking_lot::Mutex; use scoped_threadpool::Pool; use std::sync::Arc; use crate::driver::cmd::Args; use crate::gc::root::{get_rootset, Slot}; use crate::gc::swiper::card::CardTable; use crate::gc::swiper::controller::{self, HeapConfig, SharedHeapConfig}; use crate::gc::swiper::crossing::CrossingMap; use crate::gc::swiper::large::LargeSpace; use crate::gc::swiper::sweep::old::OldGen; use crate::gc::swiper::verify::VerifierPhase; use crate::gc::swiper::young::YoungGen; use crate::gc::swiper::{CollectionKind, CARD_SIZE_BITS, LARGE_OBJECT_SIZE}; use crate::gc::tlab; use crate::gc::{align_gen, formatted_size, GEN_SIZE}; use crate::gc::{Address, Collector, GcReason, Region}; use crate::mem; use crate::os::{self, MemoryPermission}; use crate::safepoint; use crate::vm::VM; mod old; mod sweep; pub struct SweepSwiper { heap: Region, reserved_area: Region, young: YoungGen, old: OldGen, large: LargeSpace, card_table: CardTable, crossing_map: CrossingMap, card_table_offset: usize, emit_write_barrier: bool, min_heap_size: usize, max_heap_size: usize, threadpool: Mutex<Pool>, config: SharedHeapConfig, } impl SweepSwiper { pub fn new(args: &Args) -> SweepSwiper { let max_heap_size = align_gen(args.max_heap_size()); let min_heap_size = align_ge
} impl Collector for SweepSwiper { fn supports_tlab(&self) -> bool { true } fn alloc_tlab_area(&self, _vm: &VM, _size: usize) -> Option<Region> { unimplemented!() } fn alloc(&self, vm: &VM, size: usize, array_ref: bool) -> Address { if size < LARGE_OBJECT_SIZE { self.alloc_normal(vm, size, array_ref) } else { self.alloc_large(vm, size, array_ref) } } fn collect(&self, _vm: &VM, _reason: GcReason) { unimplemented!() } fn minor_collect(&self, _vm: &VM, _reason: GcReason) { unimplemented!() } fn needs_write_barrier(&self) -> bool { self.emit_write_barrier } fn card_table_offset(&self) -> usize { self.card_table_offset } fn dump_summary(&self, _runtime: f32) { unimplemented!() } fn verify_ref(&self, _vm: &VM, _reference: Address) { unimplemented!() } } impl SweepSwiper { fn perform_collection_and_choose(&self, vm: &VM, reason: GcReason) -> CollectionKind { let kind = controller::choose_collection_kind(&self.config, &vm.args, &self.young); self.perform_collection(vm, kind, reason) } fn perform_collection( &self, vm: &VM, kind: CollectionKind, mut reason: GcReason, ) -> CollectionKind { safepoint::stop_the_world(vm, |threads| { controller::start(&self.config, &self.young, &self.old, &self.large); tlab::make_iterable_all(vm, threads); let rootset = get_rootset(vm, threads); let kind = match kind { CollectionKind::Minor => { let promotion_failed = self.minor_collect(vm, reason, &rootset); if promotion_failed { reason = GcReason::PromotionFailure; self.full_collect(vm, reason, &rootset); CollectionKind::Full } else { CollectionKind::Minor } } CollectionKind::Full => { self.full_collect(vm, reason, &rootset); CollectionKind::Full } }; controller::stop( &self.config, kind, &self.young, &self.old, &self.large, &vm.args, reason, ); kind }) } fn minor_collect(&self, _vm: &VM, _reason: GcReason, _rootset: &[Slot]) -> bool { unimplemented!() } fn full_collect(&self, _vm: &VM, _reason: GcReason, _rootset: &[Slot]) { unimplemented!(); } fn verify( &self, _vm: &VM, _phase: VerifierPhase, _kind: CollectionKind, _name: &str, _rootset: &[Slot], _promotion_failed: bool, ) { unimplemented!(); } fn alloc_normal(&self, vm: &VM, size: usize, _array_ref: bool) -> Address { let ptr = self.young.bump_alloc(size); if !ptr.is_null() { return ptr; } self.perform_collection_and_choose(vm, GcReason::AllocationFailure); self.young.bump_alloc(size) } fn alloc_large(&self, vm: &VM, size: usize, _: bool) -> Address { let ptr = self.large.alloc(size); if !ptr.is_null() { return ptr; } self.perform_collection(vm, CollectionKind::Full, GcReason::AllocationFailure); self.large.alloc(size) } }
n(args.min_heap_size()); let mut config = HeapConfig::new(min_heap_size, max_heap_size); controller::init(&mut config, args); let card_size = mem::page_align((4 * max_heap_size) >> CARD_SIZE_BITS); let crossing_size = mem::page_align(max_heap_size >> CARD_SIZE_BITS); let reserve_size = max_heap_size * 4 + card_size + crossing_size; let reservation = os::reserve_align(reserve_size, GEN_SIZE, false); let heap_start = reservation.start; assert!(heap_start.is_gen_aligned()); let heap_end = heap_start.offset(4 * max_heap_size); let reserved_area = heap_start.region_start(reserve_size); let card_table_offset = heap_end.to_usize() - (heap_start.to_usize() >> CARD_SIZE_BITS); let card_start = heap_end; let card_end = card_start.offset(card_size); os::commit_at(card_start, card_size, MemoryPermission::ReadWrite); let crossing_start = card_end; let crossing_end = crossing_start.offset(crossing_size); os::commit_at(crossing_start, crossing_size, MemoryPermission::ReadWrite); let young_start = heap_start; let young_end = young_start.offset(max_heap_size); let young = Region::new(young_start, young_end); let old_start = young_end; let old_end = old_start.offset(max_heap_size); let eden_size = config.eden_size; let semi_size = config.semi_size; let large_start = old_end; let large_end = large_start.offset(2 * max_heap_size); let card_table = CardTable::new( card_start, card_end, Region::new(old_start, large_end), old_end, max_heap_size, ); let crossing_map = CrossingMap::new(crossing_start, crossing_end, max_heap_size); let young = YoungGen::new(young, eden_size, semi_size, args.flag_gc_verify); let config = Arc::new(Mutex::new(config)); let old = OldGen::new( old_start, old_end, crossing_map.clone(), card_table.clone(), config.clone(), ); let large = LargeSpace::new(large_start, large_end, config.clone()); if args.flag_gc_verbose { println!( "GC: heap info: {}, eden {}, semi {}, card {}, crossing {}", formatted_size(max_heap_size), formatted_size(eden_size), formatted_size(semi_size), formatted_size(card_size), formatted_size(crossing_size) ); } let nworkers = args.gc_workers(); let emit_write_barrier = !args.flag_disable_barrier; SweepSwiper { heap: Region::new(heap_start, heap_end), reserved_area, young, old, large, card_table, crossing_map, config, card_table_offset, emit_write_barrier, min_heap_size, max_heap_size, threadpool: Mutex::new(Pool::new(nworkers as u32)), } }
function_block-function_prefixed
[ { "content": "pub fn start(rootset: &[Slot], heap: Region, perm: Region, threadpool: &mut Pool) {\n\n let number_workers = threadpool.thread_count() as usize;\n\n let mut workers = Vec::with_capacity(number_workers);\n\n let mut stealers = Vec::with_capacity(number_workers);\n\n let injector = Injec...
Rust
src/p6/p6iv.rs
lukasl93/msp430fr5994
41eb5ada14476ab7b986f6b6f5c327d46e01b558
#[doc = "Reader of register P6IV"] pub type R = crate::R<u16, super::P6IV>; #[doc = "Writer for register P6IV"] pub type W = crate::W<u16, super::P6IV>; #[doc = "Register P6IV `reset()`'s with value 0"] impl crate::ResetValue for super::P6IV { type Type = u16; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "4:0\\] Port 6 interrupt vector value\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum P6IV_A { #[doc = "0: No interrupt pending"] NONE = 0, #[doc = "2: Interrupt Source: Port 6.0 interrupt; Interrupt Flag: P6IFG0; Interrupt Priority: Highest"] P6IFG0 = 2, #[doc = "4: Interrupt Source: Port 6.1 interrupt; Interrupt Flag: P6IFG1"] P6IFG1 = 4, #[doc = "6: Interrupt Source: Port 6.2 interrupt; Interrupt Flag: P6IFG2"] P6IFG2 = 6, #[doc = "8: Interrupt Source: Port 6.3 interrupt; Interrupt Flag: P6IFG3"] P6IFG3 = 8, #[doc = "10: Interrupt Source: Port 6.4 interrupt; Interrupt Flag: P6IFG4"] P6IFG4 = 10, #[doc = "12: Interrupt Source: Port 6.5 interrupt; Interrupt Flag: P6IFG5"] P6IFG5 = 12, #[doc = "14: Interrupt Source: Port 6.6 interrupt; Interrupt Flag: P6IFG6"] P6IFG6 = 14, #[doc = "16: Interrupt Source: Port 6.7 interrupt; Interrupt Flag: P6IFG7; Interrupt Priority: Lowest"] P6IFG7 = 16, } impl From<P6IV_A> for u8 { #[inline(always)] fn from(variant: P6IV_A) -> Self { variant as _ } } #[doc = "Reader of field `P6IV`"] pub type P6IV_R = crate::R<u8, P6IV_A>; impl P6IV_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, P6IV_A> { use crate::Variant::*; match self.bits { 0 => Val(P6IV_A::NONE), 2 => Val(P6IV_A::P6IFG0), 4 => Val(P6IV_A::P6IFG1), 6 => Val(P6IV_A::P6IFG2), 8 => Val(P6IV_A::P6IFG3), 10 => Val(P6IV_A::P6IFG4), 12 => Val(P6IV_A::P6IFG5), 14 => Val(P6IV_A::P6IFG6), 16 => Val(P6IV_A::P6IFG7), i => Res(i), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == P6IV_A::NONE } #[doc = "Checks if the value of the field is `P6IFG0`"] #[inline(always)] pub fn is_p6ifg0(&self) -> bool { *self == P6IV_A::P6IFG0 } #[doc = "Checks if the value of the field is `P6IFG1`"] #[inline(always)] pub fn is_p6ifg1(&self) -> bool { *self == P6IV_A::P6IFG1 } #[doc = "Checks if the value of the field is `P6IFG2`"] #[inline(always)] pub fn is_p6ifg2(&self) -> bool { *self == P6IV_A::P6IFG2 } #[doc = "Checks if the value of the field is `P6IFG3`"] #[inline(always)] pub fn is_p6ifg3(&self) -> bool { *self == P6IV_A::P6IFG3 } #[doc = "Checks if the value of the field is `P6IFG4`"] #[inline(always)] pub fn is_p6ifg4(&self) -> bool { *self == P6IV_A::P6IFG4 } #[doc = "Checks if the value of the field is `P6IFG5`"] #[inline(always)] pub fn is_p6ifg5(&self) -> bool { *self == P6IV_A::P6IFG5 } #[doc = "Checks if the value of the field is `P6IFG6`"] #[inline(always)] pub fn is_p6ifg6(&self) -> bool { *self == P6IV_A::P6IFG6 } #[doc = "Checks if the value of the field is `P6IFG7`"] #[inline(always)] pub fn is_p6ifg7(&self) -> bool { *self == P6IV_A::P6IFG7 } } #[doc = "Write proxy for field `P6IV`"] pub struct P6IV_W<'a> { w: &'a mut W, } impl<'a> P6IV_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: P6IV_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "No interrupt pending"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(P6IV_A::NONE) } #[doc = "Interrupt Source: Port 6.0 interrupt; Interrupt Flag: P6IFG0; Interrupt Priority: Highest"] #[inline(always)] pub fn p6ifg0(self) -> &'a mut W { self.variant(P6IV_A::P6IFG0) } #[doc = "Interrupt Source: Port 6.1 interrupt; Interrupt Flag: P6IFG1"] #[inline(always)] pub fn p6ifg1(self) -> &'a mut W { self.variant(P6IV_A::P6IFG1) } #[doc = "Interrupt Source: Port 6.2 interrupt; Interrupt Flag: P6IFG2"] #[inline(always)] pub fn p6ifg2(self) -> &'a mut W { self.variant(P6IV_A::P6IFG2) } #[doc = "Interrupt Source: Port 6.3 interrupt; Interrupt Flag: P6IFG3"] #[inline(always)] pub fn p6ifg3(self) -> &'a mut W { self.variant(P6IV_A::P6IFG3) } #[doc = "Interrupt Source: Port 6.4 interrupt; Interrupt Flag: P6IFG4"] #[inline(always)] pub fn p6ifg4(self) -> &'a mut W { self.variant(P6IV_A::P6IFG4) } #[doc = "Interrupt Source: Port 6.5 interrupt; Interrupt Flag: P6IFG5"] #[inline(always)] pub fn p6ifg5(self) -> &'a mut W { self.variant(P6IV_A::P6IFG5) } #[doc = "Interrupt Source: Port 6.6 interrupt; Interrupt Flag: P6IFG6"] #[inline(always)] pub fn p6ifg6(self) -> &'a mut W { self.variant(P6IV_A::P6IFG6) } #[doc = "Interrupt Source: Port 6.7 interrupt; Interrupt Flag: P6IFG7; Interrupt Priority: Lowest"] #[inline(always)] pub fn p6ifg7(self) -> &'a mut W { self.variant(P6IV_A::P6IFG7) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x1f) | ((value as u16) & 0x1f); self.w } } impl R { #[doc = "Bits 0:4 - 4:0\\] Port 6 interrupt vector value"] #[inline(always)] pub fn p6iv(&self) -> P6IV_R { P6IV_R::new((self.bits & 0x1f) as u8) } } impl W { #[doc = "Bits 0:4 - 4:0\\] Port 6 interrupt vector value"] #[inline(always)] pub fn p6iv(&mut self) -> P6IV_W { P6IV_W { w: self } } }
#[doc = "Reader of register P6IV"] pub type R = crate::R<u16, super::P6IV>; #[doc = "Writer for register P6IV"] pub type W = crate::W<u16, super::P6IV>; #[doc = "Register P6IV `reset()`'s with value 0"] impl crate::ResetValue for super::P6IV { type Type = u16; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "4:0\\] Port 6 interrupt vector value\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum P6IV_A { #[doc = "0: No interrupt pending"] NONE = 0, #[doc = "2: Interrupt Source: Port 6.0 interrupt; Interrupt Flag: P6IFG0; Interrupt Priority: Highest"] P6IFG0 = 2, #[doc = "4: Interrupt Source: Port 6.1 interrupt; Interrupt Flag: P6IFG1"] P6IFG1 = 4, #[doc = "6: Interrupt Source: Port 6.2 interrupt; Interrupt Flag: P6IFG2"] P6IFG2 = 6, #[doc = "8: Interrupt Source: Port 6.3 interrupt; Interrupt Flag: P6IFG3"] P6IFG3 = 8, #[doc = "10: Interrupt Source: Port 6.4 interrupt; Interrupt Flag: P6IFG4"] P6IFG4 = 10, #[doc = "12: Interrupt Source: Port 6.5 interrupt; Interrupt Flag: P6IFG5"] P6IFG5 = 12, #[doc = "14: Interrupt Source: Port 6.6 interrupt; Interrupt Flag: P6IFG6"] P6IFG6 = 14, #[doc = "16: Interrupt Source: Port 6.7 interrupt; Interrupt Flag: P6IFG7; Interrupt Priority: Lowest"] P6IFG7 = 16, } impl From<P6IV_A> for u8 { #[inline(always)] fn from(variant: P6IV_A) -> Self { variant as _ } } #[doc = "Reader of field `P6IV`"] pub type P6IV_R = crate::R<u8, P6IV_A>; impl P6IV_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, P6IV_A> { use crate::Variant::*; match self.bits { 0 => Val(P6IV_A::NONE), 2 => Val(P6IV_A::P6IFG0), 4 => Val(P6IV_A::P6IFG1), 6 => Val(P6IV_A::P6IFG2), 8 => Val(P6IV_A::P6IFG3), 10 => Val(P6IV_A::P6IFG4), 12 => Val(P6IV_A::P6IFG5), 14 => Val(P6IV_A::P6IFG6), 16 => Val(P6IV_A::P6IFG7), i => Res(i), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == P6IV_A::NONE } #[doc = "Checks if the value of the field is `P6IFG0`"] #[inline(always)] pub fn is_p6ifg0(&self) -> bool { *self == P6IV_A::P6IFG0 } #[doc = "Checks if the value of the field is `P6IFG1`"] #[inline(always)] pub fn is_p6ifg1(&self) -> bool { *self == P6IV_A::P6IFG1 } #[doc = "Checks if the value of the field is `P6IFG2`"] #[inline(always)] pub fn is_p6ifg2(&self) -> bool { *self == P6IV_A::P6IFG2 } #[doc = "Checks if the value of the field is `P6IFG3`"] #[inline(always)] pub fn is_p6ifg3(&self) -> bool { *self == P6IV_A::P6IFG3 } #[doc = "Checks if the value of the field is `P6IFG4`"] #[inline(always)] pub fn is_p6ifg4(&self) -> bool { *self == P6IV_A::P6IFG4 } #[doc = "Checks if the value of the field is `P6IFG5`"] #[inline(always)] pub fn is_p6ifg5(&self) -> bool { *self == P6IV_A::P6IFG5 } #[doc = "Checks if the value of the field is `P6IFG6`"] #[inline(always)] pub fn is_p6ifg6(&self) -> bool { *self == P6IV_A::P6IFG6 } #[doc = "Checks if the value of the field is `P6IFG7`"] #[inline(always)] pub fn is_p6ifg7(&self) -> bool { *self == P6IV_A::P6IFG7 } } #[doc = "Write proxy for field `P6IV`"] pub struct P6IV_W<'a> { w: &'a mut W, } impl<'a> P6IV_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: P6IV_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "No interrupt pending"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(P6IV_A::NONE) } #[doc = "Interrupt Source: Port 6.0 interrupt; Interrupt Flag: P6IFG0; Interrupt Priority: Highest"] #[inline(always)] pub fn p6ifg0(self) -> &'a mut W { self.variant(P6IV_A::P6IFG0) } #[doc = "Interrupt Source: Port 6.1 interrupt; Interrupt Flag: P6IFG1"] #[inline(always)] pub fn p6ifg1(self) -> &'a mut W { self.variant(P6IV_A::P6IFG1) } #[doc = "Interrupt Source: Port 6.2 interrupt; Interrupt Flag: P6IFG2"] #[inline(always)] pub fn p6ifg2(self) -> &'a mut W { self.variant(P6IV_A::P6IFG2) } #[doc = "Interrupt Source: Port 6.3 interrupt; Interrupt Flag: P6IFG3"] #[inline(always)] pub fn p6ifg3(self) -> &'a mut W { self.variant(P6IV_A::P6IFG3) } #[doc = "Interrupt Source: Port 6.4 interrupt; Interrupt Flag: P6IFG4"] #[inline(always)] pub fn p6ifg4(self) -> &'a mut W { self.variant(P6IV_A::P6IFG4)
IV_A::P6IFG7) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x1f) | ((value as u16) & 0x1f); self.w } } impl R { #[doc = "Bits 0:4 - 4:0\\] Port 6 interrupt vector value"] #[inline(always)] pub fn p6iv(&self) -> P6IV_R { P6IV_R::new((self.bits & 0x1f) as u8) } } impl W { #[doc = "Bits 0:4 - 4:0\\] Port 6 interrupt vector value"] #[inline(always)] pub fn p6iv(&mut self) -> P6IV_W { P6IV_W { w: self } } }
} #[doc = "Interrupt Source: Port 6.5 interrupt; Interrupt Flag: P6IFG5"] #[inline(always)] pub fn p6ifg5(self) -> &'a mut W { self.variant(P6IV_A::P6IFG5) } #[doc = "Interrupt Source: Port 6.6 interrupt; Interrupt Flag: P6IFG6"] #[inline(always)] pub fn p6ifg6(self) -> &'a mut W { self.variant(P6IV_A::P6IFG6) } #[doc = "Interrupt Source: Port 6.7 interrupt; Interrupt Flag: P6IFG7; Interrupt Priority: Lowest"] #[inline(always)] pub fn p6ifg7(self) -> &'a mut W { self.variant(P6
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/osm_io/o5m/varint.rs
Vadeen/vadeen_osm
80aa4f862ed7a9ee135e7e818a332a7650511976
use crate::osm_io::error::{Error, ErrorKind, Result}; use std::io::{Read, Write}; #[derive(Debug)] pub struct VarInt { bytes: Vec<u8>, } impl VarInt { pub fn new(bytes: Vec<u8>) -> Self { VarInt { bytes } } pub fn create_bytes<T: Into<VarInt>>(value: T) -> Vec<u8> { let varint: VarInt = value.into(); varint.into_bytes() } pub fn into_bytes(self) -> Vec<u8> { self.bytes } } pub trait ReadVarInt: Read { fn read_varint(&mut self) -> Result<VarInt> { let mut bytes = Vec::new(); for i in 0..10 { if i == 9 { return Err(Error::new( ErrorKind::ParseError, Some("Varint overflow, read 9 bytes.".to_owned()), )); } let mut buf = [0u8; 1]; self.read_exact(&mut buf)?; let byte = buf[0]; bytes.push(byte); if byte & 0x80 == 0 { break; } } Ok(VarInt { bytes }) } } impl<R: Read + ?Sized> ReadVarInt for R {} pub trait WriteVarInt: Write { fn write_varint<T: Into<VarInt>>(&mut self, i: T) -> Result<()> { let varint: VarInt = i.into(); self.write_all(&varint.bytes)?; Ok(()) } } impl<W: Write + ?Sized> WriteVarInt for W {} impl From<VarInt> for i64 { fn from(mut vi: VarInt) -> Self { let (first, rest) = vi.bytes.split_first().unwrap(); let byte = *first as u64; let negative = (byte & 0x01) != 0x00; let mut value = (byte & 0x7E) >> 1; if (byte & 0x80) != 0x00 { vi.bytes = rest.to_vec(); value |= (Into::<u64>::into(vi)) << 6; } let value = value as i64; if negative { -value - 1 } else { value } } } impl From<VarInt> for u64 { fn from(vi: VarInt) -> Self { let mut value = 0; for (n, _) in vi.bytes.iter().enumerate() { let byte = vi.bytes[n] as u64; value |= (byte & 0x7F) << (7 * (n as u64)); if byte & 0x80 == 0 { break; } } value } } impl From<u32> for VarInt { fn from(value: u32) -> Self { VarInt::from(value as u64) } } impl From<u64> for VarInt { fn from(mut value: u64) -> Self { let mut bytes = Vec::new(); while value > 0x7F { bytes.push(((value & 0x7F) | 0x80) as u8); value >>= 7; } if value > 0 { bytes.push(value as u8); } VarInt::new(bytes) } } impl From<i32> for VarInt { fn from(value: i32) -> Self { VarInt::from(value as i64) } } impl From<i64> for VarInt { fn from(mut value: i64) -> Self { let mut sign_bit = 0x00; if value < 0 { sign_bit = 0x01; value = -value - 1; } let value = value as u64; let least_significant = (((value << 1) & 0x7F) | sign_bit) as u8; let mut bytes = Vec::new(); if value > 0x3F { bytes.push(least_significant | 0x80); let mut rest = Self::from((value >> 6) as u64); bytes.append(&mut rest.bytes); } else { bytes.push(least_significant); } VarInt::new(bytes) } } #[cfg(test)] mod test_from_bytes { use crate::osm_io::o5m::varint::ReadVarInt; use crate::osm_io::o5m::varint::VarInt; #[test] fn max_one_byte_uvarint() { let varint = VarInt::new(vec![0x7F]); assert_eq!(Into::<u64>::into(varint), 127); } #[test] fn read_two_bytes_uvarint() { let data = vec![0xC3, 0x02]; let varint = data.as_slice().read_varint().unwrap(); assert_eq!(Into::<u64>::into(varint), 323); } #[test] fn three_byte_uvarint() { let varint = VarInt::new(vec![0x80, 0x80, 0x01]); assert_eq!(Into::<u64>::into(varint), 16384); } #[test] fn read_one_byte_positive_varint() { let data = vec![0x08]; let varint = data.as_slice().read_varint().unwrap(); assert_eq!(Into::<i64>::into(varint), 4); } #[test] fn one_byte_negative_varint() { let varint = VarInt::new(vec![0x03]); assert_eq!(Into::<i64>::into(varint), -2); } #[test] fn read_four_byte_positive_varint() { let data = vec![0x94, 0xfe, 0xd2, 0x05]; let varint = data.as_slice().read_varint().unwrap(); assert_eq!(Into::<i64>::into(varint), 5922698); } #[test] fn two_byte_negative_varint() { let varint = VarInt::new(vec![0x81, 0x01]); assert_eq!(Into::<i64>::into(varint), -65); } #[test] fn too_many_bytes() { let data = vec![0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]; let error = data.as_slice().read_varint().unwrap_err(); assert_eq!(error.to_string(), "Varint overflow, read 9 bytes.") } } #[cfg(test)] mod test_to_bytes { use crate::osm_io::o5m::varint::VarInt; #[test] fn one_byte_uvarint() { let varint = VarInt::from(5 as u64); assert_eq!(varint.bytes, vec![0x05]); } #[test] fn max_one_byte_uvarint() { let varint = VarInt::from(127 as u64); assert_eq!(varint.bytes, vec![0x7F]); } #[test] fn two_byte_uvarint() { let varint = VarInt::from(323 as u64); assert_eq!(varint.bytes, vec![0xC3, 0x02]); } #[test] fn three_byte_uvarint() { let varint = VarInt::from(16384 as u64); assert_eq!(varint.bytes, vec![0x80, 0x80, 0x01]); } #[test] fn one_byte_positive_varint() { let varint = VarInt::from(4 as i64); assert_eq!(varint.bytes, vec![0x08]); } #[test] fn one_byte_negative_varint() { let varint = VarInt::from(-3 as i64); assert_eq!(varint.bytes, vec![0x05]); } #[test] fn two_byte_positive_varint() { let varint = VarInt::from(64 as i64); assert_eq!(varint.bytes, vec![0x80, 0x01]); } #[test] fn two_byte_negative_varint() { let varint = VarInt::from(-65 as i64); assert_eq!(varint.bytes, vec![0x81, 0x01]); } }
use crate::osm_io::error::{Error, ErrorKind, Result}; use std::io::{Read, Write}; #[derive(Debug)] pub struct VarInt { bytes: Vec<u8>, } impl VarInt { pub fn new(bytes: Vec<u8>) -> Self { VarInt { bytes } } pub fn create_bytes<T: Into<VarInt>>(value: T) -> Vec<u8> { let varint: VarInt = value.into(); varint.into_bytes() } pub fn into_bytes(self) -> Vec<u8> { self.bytes } } pub trait ReadVarInt: Read { fn read_varint(&mut self) -> Result<VarInt> { let mut bytes = Vec::new(); for i in 0..10 { if i == 9 { return
; } let mut buf = [0u8; 1]; self.read_exact(&mut buf)?; let byte = buf[0]; bytes.push(byte); if byte & 0x80 == 0 { break; } } Ok(VarInt { bytes }) } } impl<R: Read + ?Sized> ReadVarInt for R {} pub trait WriteVarInt: Write { fn write_varint<T: Into<VarInt>>(&mut self, i: T) -> Result<()> { let varint: VarInt = i.into(); self.write_all(&varint.bytes)?; Ok(()) } } impl<W: Write + ?Sized> WriteVarInt for W {} impl From<VarInt> for i64 { fn from(mut vi: VarInt) -> Self { let (first, rest) = vi.bytes.split_first().unwrap(); let byte = *first as u64; let negative = (byte & 0x01) != 0x00; let mut value = (byte & 0x7E) >> 1; if (byte & 0x80) != 0x00 { vi.bytes = rest.to_vec(); value |= (Into::<u64>::into(vi)) << 6; } let value = value as i64; if negative { -value - 1 } else { value } } } impl From<VarInt> for u64 { fn from(vi: VarInt) -> Self { let mut value = 0; for (n, _) in vi.bytes.iter().enumerate() { let byte = vi.bytes[n] as u64; value |= (byte & 0x7F) << (7 * (n as u64)); if byte & 0x80 == 0 { break; } } value } } impl From<u32> for VarInt { fn from(value: u32) -> Self { VarInt::from(value as u64) } } impl From<u64> for VarInt { fn from(mut value: u64) -> Self { let mut bytes = Vec::new(); while value > 0x7F { bytes.push(((value & 0x7F) | 0x80) as u8); value >>= 7; } if value > 0 { bytes.push(value as u8); } VarInt::new(bytes) } } impl From<i32> for VarInt { fn from(value: i32) -> Self { VarInt::from(value as i64) } } impl From<i64> for VarInt { fn from(mut value: i64) -> Self { let mut sign_bit = 0x00; if value < 0 { sign_bit = 0x01; value = -value - 1; } let value = value as u64; let least_significant = (((value << 1) & 0x7F) | sign_bit) as u8; let mut bytes = Vec::new(); if value > 0x3F { bytes.push(least_significant | 0x80); let mut rest = Self::from((value >> 6) as u64); bytes.append(&mut rest.bytes); } else { bytes.push(least_significant); } VarInt::new(bytes) } } #[cfg(test)] mod test_from_bytes { use crate::osm_io::o5m::varint::ReadVarInt; use crate::osm_io::o5m::varint::VarInt; #[test] fn max_one_byte_uvarint() { let varint = VarInt::new(vec![0x7F]); assert_eq!(Into::<u64>::into(varint), 127); } #[test] fn read_two_bytes_uvarint() { let data = vec![0xC3, 0x02]; let varint = data.as_slice().read_varint().unwrap(); assert_eq!(Into::<u64>::into(varint), 323); } #[test] fn three_byte_uvarint() { let varint = VarInt::new(vec![0x80, 0x80, 0x01]); assert_eq!(Into::<u64>::into(varint), 16384); } #[test] fn read_one_byte_positive_varint() { let data = vec![0x08]; let varint = data.as_slice().read_varint().unwrap(); assert_eq!(Into::<i64>::into(varint), 4); } #[test] fn one_byte_negative_varint() { let varint = VarInt::new(vec![0x03]); assert_eq!(Into::<i64>::into(varint), -2); } #[test] fn read_four_byte_positive_varint() { let data = vec![0x94, 0xfe, 0xd2, 0x05]; let varint = data.as_slice().read_varint().unwrap(); assert_eq!(Into::<i64>::into(varint), 5922698); } #[test] fn two_byte_negative_varint() { let varint = VarInt::new(vec![0x81, 0x01]); assert_eq!(Into::<i64>::into(varint), -65); } #[test] fn too_many_bytes() { let data = vec![0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]; let error = data.as_slice().read_varint().unwrap_err(); assert_eq!(error.to_string(), "Varint overflow, read 9 bytes.") } } #[cfg(test)] mod test_to_bytes { use crate::osm_io::o5m::varint::VarInt; #[test] fn one_byte_uvarint() { let varint = VarInt::from(5 as u64); assert_eq!(varint.bytes, vec![0x05]); } #[test] fn max_one_byte_uvarint() { let varint = VarInt::from(127 as u64); assert_eq!(varint.bytes, vec![0x7F]); } #[test] fn two_byte_uvarint() { let varint = VarInt::from(323 as u64); assert_eq!(varint.bytes, vec![0xC3, 0x02]); } #[test] fn three_byte_uvarint() { let varint = VarInt::from(16384 as u64); assert_eq!(varint.bytes, vec![0x80, 0x80, 0x01]); } #[test] fn one_byte_positive_varint() { let varint = VarInt::from(4 as i64); assert_eq!(varint.bytes, vec![0x08]); } #[test] fn one_byte_negative_varint() { let varint = VarInt::from(-3 as i64); assert_eq!(varint.bytes, vec![0x05]); } #[test] fn two_byte_positive_varint() { let varint = VarInt::from(64 as i64); assert_eq!(varint.bytes, vec![0x80, 0x01]); } #[test] fn two_byte_negative_varint() { let varint = VarInt::from(-65 as i64); assert_eq!(varint.bytes, vec![0x81, 0x01]); } }
Err(Error::new( ErrorKind::ParseError, Some("Varint overflow, read 9 bytes.".to_owned()), ))
call_expression
[ { "content": "/// Writer for the osm formats.\n\npub trait OsmWrite<W: Write> {\n\n fn write(&mut self, osm: &Osm) -> std::result::Result<(), Error>;\n\n\n\n fn into_inner(self: Box<Self>) -> W;\n\n}\n\n\n", "file_path": "src/osm_io.rs", "rank": 2, "score": 124140.17316385586 }, { "con...
Rust
src/nerve/github/response.rs
ustwo/github-issues
cc51621f3794d1172bb8bc333eb6be31f6736b61
use std::fmt; use hyper; use hyper::Client; use hyper::client::Response as HyperResponse; use hyper::header::{Headers, Accept, Authorization, Connection, UserAgent, qitem}; use regex::Regex; use rustc_serialize::json; use std::io::Read; use std::process; use say; use github; header! { (XRateLimitRemaining, "X-RateLimit-Remaining") => [u32] } header! { (Link, "Link") => [String] } #[derive(Debug)] pub struct Response { pub content: String, pub ratelimit: u32, } impl From<HyperResponse> for Response { fn from(mut res: HyperResponse) -> Self { let mut body = String::new(); res.read_to_string(&mut body).unwrap(); Response { content: body , ratelimit: ratelimit(&res.headers) } } } pub struct Page { pub content: String, pub next: Option<String>, pub ratelimit: u32, } impl Page { pub fn new(url: &str, token: &str) -> Page { let mut res = get_page(url.to_string(), token); let mut body = String::new(); res.read_to_string(&mut body).unwrap(); Page {content: body, next: next_url(link(&res.headers)), ratelimit: ratelimit(&res.headers)} } pub fn warn(&self) { if self.next.is_none() { println!("{} {} {}", say::warn(), self.ratelimit, "Remaining requests"); } } } impl fmt::Display for Page { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{{next: {:?}, ratelimit: {}}}", self.next, self.ratelimit) } } fn get_page(url: String, token: &str) -> HyperResponse { println!("{} {} {}", say::info(), "Fetching", url); let client = Client::new(); let res = client.get(&*url.clone()) .header(UserAgent(format!("nerve/{}", env!("CARGO_PKG_VERSION")))) .header(Authorization(format!("token {}", token))) .header(Accept(vec![qitem(github::mime())])) .header(Connection::close()) .send().unwrap_or_else(|_| process::exit(1)); match res.status { hyper::Ok => {} _ => { println!("{} {}", say::error(), "Unable to parse the response from Github"); process::exit(1) } } res } pub fn ratelimit(headers: &Headers) -> u32 { match headers.get() { Some(&XRateLimitRemaining(x)) => x, None => 0 } } pub fn warn_ratelimit(ratelimit: u32) { println!("{} {} {}", say::warn(), ratelimit, "Remaining requests"); } pub fn link(headers: &Headers) -> String { match headers.get() { Some(&Link(ref x)) => x.to_string(), None => "".to_string() } } fn next_url(link: String) -> Option<String> { let re = Regex::new(r"<([^;]+)>;\s*rel=.next.").unwrap(); match re.captures(&link) { None => None, Some(cs) => cs.at(1).as_ref().map(|x| x.to_string()) } } #[derive(Debug, RustcDecodable, RustcEncodable)] pub struct ResponseError { pub message: String, pub errors: Vec<ErrorResource>, } impl ResponseError { pub fn from_str(data: &str) -> Result<ResponseError, json::DecoderError> { json::decode(data) } } impl fmt::Display for ResponseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let error = self.errors.first().unwrap(); write!(f, "the field '{}' {}", error.field, "has an invalid value.") } } #[derive(Debug, RustcDecodable, RustcEncodable)] pub struct ErrorResource { pub code: String, pub resource: String, pub field: String, }
use std::fmt; use hyper; use hyper::Client; use hyper::client::Response as HyperResponse; use hyper::header::{Headers, Accept, Authorization, Connection, UserAgent, qitem}; use regex::Regex; use rustc_serialize::json; use std::io::Read; use std::process; use say; use github; header! { (XRateLimitRemaining, "X-RateLimit-Remaining") => [u32] } header! { (Link, "Link") => [String] } #[derive(Debug)] pub struct Response { pub content: String, pub ratelimit: u32, } impl From<HyperResponse> for Response { fn from(mut res: HyperResponse) -> Self { let mut body = String::new(); res.read_to_string(&mut body).unwrap(); Response { content: body , ratelimit: ratelimit(&res.headers) } } } pub struct Page { pub content: String, pub next: Option<String>, pub ratelimit: u32, } impl Page { pub fn new(url: &str, token: &str) -> Page { let mut res = get_page(url.to_string(), token); let mut body = String::new(); res.read_to_string(&mut body).unwrap(); Page {content: body, next: next_url(link(&res.headers)), ratelimit: ratelimit(&res.headers)} } pub fn warn(&self) { if self.next.is_none() { println!("{} {} {}", say::warn(), self.ratelimit, "Remaining requests"); } } } impl fmt::Display for Page { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{{next: {:?}, ratelimit: {}}}", self.next, self.ratelimit) } } fn get_page(url: String, token: &str) -> HyperResponse { println!("{} {} {}", say::info(), "Fetching", url); let client = Client::new(); let res = client.get(&*url.clone()) .header(UserAgent(format!("nerve/{}", env!("CARGO_PKG_VERSION")))) .header(Authorization(format!("token {}", token))) .header(Accept(vec![qitem(github::mime())])) .header(Connection::close()) .send().unwrap_or_else(|_| process::exit(1)); match res.status { hyper::Ok => {} _ => { println!("{} {}", say::error(), "Unable to parse the response from Github"); process::exit(1) } } res } pub fn ratelimit(headers: &Headers) ->
} impl ResponseError { pub fn from_str(data: &str) -> Result<ResponseError, json::DecoderError> { json::decode(data) } } impl fmt::Display for ResponseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let error = self.errors.first().unwrap(); write!(f, "the field '{}' {}", error.field, "has an invalid value.") } } #[derive(Debug, RustcDecodable, RustcEncodable)] pub struct ErrorResource { pub code: String, pub resource: String, pub field: String, }
u32 { match headers.get() { Some(&XRateLimitRemaining(x)) => x, None => 0 } } pub fn warn_ratelimit(ratelimit: u32) { println!("{} {} {}", say::warn(), ratelimit, "Remaining requests"); } pub fn link(headers: &Headers) -> String { match headers.get() { Some(&Link(ref x)) => x.to_string(), None => "".to_string() } } fn next_url(link: String) -> Option<String> { let re = Regex::new(r"<([^;]+)>;\s*rel=.next.").unwrap(); match re.captures(&link) { None => None, Some(cs) => cs.at(1).as_ref().map(|x| x.to_string()) } } #[derive(Debug, RustcDecodable, RustcEncodable)] pub struct ResponseError { pub message: String, pub errors: Vec<ErrorResource>,
random
[ { "content": "pub fn create(url: &str, token: &str, issue: &NewIssue) -> Result<Response, ResponseError> {\n\n let client = Client::new();\n\n let body = json::encode(issue).unwrap();\n\n\n\n let res = client.post(&*url.clone())\n\n .body(&body)\n\n .header(UserAge...
Rust
src/tools/clippy/clippy_lints/src/size_of_in_element_count.rs
ohno418/rust
395a09c3dafe0c7838c9ca41d2b47bb5e79a5b6d
use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_hir::BinOpKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, Ty, TypeAndMut}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::sym; declare_clippy_lint! { #[clippy::version = "1.50.0"] pub SIZE_OF_IN_ELEMENT_COUNT, correctness, "using `size_of::<T>` or `size_of_val::<T>` where a count of elements of `T` is expected" } declare_lint_pass!(SizeOfInElementCount => [SIZE_OF_IN_ELEMENT_COUNT]); fn get_size_of_ty<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, inverted: bool) -> Option<Ty<'tcx>> { match expr.kind { ExprKind::Call(count_func, _func_args) => { if_chain! { if !inverted; if let ExprKind::Path(ref count_func_qpath) = count_func.kind; if let Some(def_id) = cx.qpath_res(count_func_qpath, count_func.hir_id).opt_def_id(); if matches!(cx.tcx.get_diagnostic_name(def_id), Some(sym::mem_size_of | sym::mem_size_of_val)); then { cx.typeck_results().node_substs(count_func.hir_id).types().next() } else { None } } }, ExprKind::Binary(op, left, right) if BinOpKind::Mul == op.node => { get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right, inverted)) }, ExprKind::Binary(op, left, right) if BinOpKind::Div == op.node => { get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right, !inverted)) }, ExprKind::Cast(expr, _) => get_size_of_ty(cx, expr, inverted), _ => None, } } fn get_pointee_ty_and_count_expr<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ) -> Option<(Ty<'tcx>, &'tcx Expr<'tcx>)> { const FUNCTIONS: [&[&str]; 8] = [ &paths::PTR_COPY_NONOVERLAPPING, &paths::PTR_COPY, &paths::PTR_WRITE_BYTES, &paths::PTR_SWAP_NONOVERLAPPING, &paths::PTR_SLICE_FROM_RAW_PARTS, &paths::PTR_SLICE_FROM_RAW_PARTS_MUT, &paths::SLICE_FROM_RAW_PARTS, &paths::SLICE_FROM_RAW_PARTS_MUT, ]; const METHODS: [&str; 11] = [ "write_bytes", "copy_to", "copy_from", "copy_to_nonoverlapping", "copy_from_nonoverlapping", "add", "wrapping_add", "sub", "wrapping_sub", "offset", "wrapping_offset", ]; if_chain! { if let ExprKind::Call(func, [.., count]) = expr.kind; if let ExprKind::Path(ref func_qpath) = func.kind; if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id(); if FUNCTIONS.iter().any(|func_path| match_def_path(cx, def_id, func_path)); if let Some(pointee_ty) = cx.typeck_results().node_substs(func.hir_id).types().next(); then { return Some((pointee_ty, count)); } }; if_chain! { if let ExprKind::MethodCall(method_path, [ptr_self, .., count], _) = expr.kind; let method_ident = method_path.ident.as_str(); if METHODS.iter().any(|m| *m == &*method_ident); if let ty::RawPtr(TypeAndMut { ty: pointee_ty, .. }) = cx.typeck_results().expr_ty(ptr_self).kind(); then { return Some((*pointee_ty, count)); } }; None } impl<'tcx> LateLintPass<'tcx> for SizeOfInElementCount { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { const HELP_MSG: &str = "use a count of elements instead of a count of bytes\ , it already gets multiplied by the size of the type"; const LINT_MSG: &str = "found a count of bytes \ instead of a count of elements of `T`"; if_chain! { if let Some((pointee_ty, count_expr)) = get_pointee_ty_and_count_expr(cx, expr); if let Some(ty_used_for_size_of) = get_size_of_ty(cx, count_expr, false); if pointee_ty == ty_used_for_size_of; then { span_lint_and_help( cx, SIZE_OF_IN_ELEMENT_COUNT, count_expr.span, LINT_MSG, None, HELP_MSG ); } }; } }
use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_hir::BinOpKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, Ty, TypeAndMut}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::sym; declare_clippy_lint! { #[clippy::version = "1.50.0"] pub SIZE_OF_IN_ELEMENT_COUNT, correctness, "using `size_of::<T>` or `size_of_val::<T>` where a count of elements of `T` is expected" } declare_lint_pass!(SizeOfInElementCount => [SIZE_OF_IN_ELEMENT_COUNT]); fn get_size_of_ty<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, inverted: bool) -> Option<Ty<'tcx>> { match expr.kind { ExprKind::Call(count_func, _func_args) => { if_chain! { if !inverted; if let ExprKind::Path(ref count_func_qpath) = count_func.kind; if let Some(def_id) = cx.qpath_res(count_func_qpath, count_func.hir_id).opt_def_id(); if matches!(cx.tcx.get_diagnostic_name(def_id), Some(sym::mem_size_of | sym::mem_size_of_val)); then { cx.typeck_results().node_substs(count_func.hir_id).types().next() } else { None } } }, ExprKind::Binary(op, left, right) if BinOpKind::Mul == op.node => { get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right, inverted)) }, ExprKind::Binary(op, left, right) if BinOpKind::Div == op.node => { get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right, !inverted)) }, ExprKind::Cast(expr, _) => get_size_of_ty(cx, expr, inverted), _ => None, } }
impl<'tcx> LateLintPass<'tcx> for SizeOfInElementCount { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { const HELP_MSG: &str = "use a count of elements instead of a count of bytes\ , it already gets multiplied by the size of the type"; const LINT_MSG: &str = "found a count of bytes \ instead of a count of elements of `T`"; if_chain! { if let Some((pointee_ty, count_expr)) = get_pointee_ty_and_count_expr(cx, expr); if let Some(ty_used_for_size_of) = get_size_of_ty(cx, count_expr, false); if pointee_ty == ty_used_for_size_of; then { span_lint_and_help( cx, SIZE_OF_IN_ELEMENT_COUNT, count_expr.span, LINT_MSG, None, HELP_MSG ); } }; } }
fn get_pointee_ty_and_count_expr<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ) -> Option<(Ty<'tcx>, &'tcx Expr<'tcx>)> { const FUNCTIONS: [&[&str]; 8] = [ &paths::PTR_COPY_NONOVERLAPPING, &paths::PTR_COPY, &paths::PTR_WRITE_BYTES, &paths::PTR_SWAP_NONOVERLAPPING, &paths::PTR_SLICE_FROM_RAW_PARTS, &paths::PTR_SLICE_FROM_RAW_PARTS_MUT, &paths::SLICE_FROM_RAW_PARTS, &paths::SLICE_FROM_RAW_PARTS_MUT, ]; const METHODS: [&str; 11] = [ "write_bytes", "copy_to", "copy_from", "copy_to_nonoverlapping", "copy_from_nonoverlapping", "add", "wrapping_add", "sub", "wrapping_sub", "offset", "wrapping_offset", ]; if_chain! { if let ExprKind::Call(func, [.., count]) = expr.kind; if let ExprKind::Path(ref func_qpath) = func.kind; if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id(); if FUNCTIONS.iter().any(|func_path| match_def_path(cx, def_id, func_path)); if let Some(pointee_ty) = cx.typeck_results().node_substs(func.hir_id).types().next(); then { return Some((pointee_ty, count)); } }; if_chain! { if let ExprKind::MethodCall(method_path, [ptr_self, .., count], _) = expr.kind; let method_ident = method_path.ident.as_str(); if METHODS.iter().any(|m| *m == &*method_ident); if let ty::RawPtr(TypeAndMut { ty: pointee_ty, .. }) = cx.typeck_results().expr_ty(ptr_self).kind(); then { return Some((*pointee_ty, count)); } }; None }
function_block-full_function
[]
Rust
tarpc/examples/pubsub.rs
tikue/tarpc
90bc7f741d8fc837ac436a5ac39cca13245fe558
use anyhow::anyhow; use futures::{ channel::oneshot, future::{self, AbortHandle}, prelude::*, }; use log::info; use publisher::Publisher as _; use std::{ collections::HashMap, io, net::SocketAddr, sync::{Arc, Mutex, RwLock}, }; use subscriber::Subscriber as _; use tarpc::{ client, context, serde_transport::tcp, server::{self, Channel}, }; use tokio::net::ToSocketAddrs; use tokio_serde::formats::Json; pub mod subscriber { #[tarpc::service] pub trait Subscriber { async fn topics() -> Vec<String>; async fn receive(topic: String, message: String); } } pub mod publisher { #[tarpc::service] pub trait Publisher { async fn publish(topic: String, message: String); } } #[derive(Clone, Debug)] struct Subscriber { local_addr: SocketAddr, topics: Vec<String>, } #[tarpc::server] impl subscriber::Subscriber for Subscriber { async fn topics(self, _: context::Context) -> Vec<String> { self.topics.clone() } async fn receive(self, _: context::Context, topic: String, message: String) { info!( "[{}] received message on topic '{}': {}", self.local_addr, topic, message ); } } struct SubscriberHandle(AbortHandle); impl Drop for SubscriberHandle { fn drop(&mut self) { self.0.abort(); } } impl Subscriber { async fn connect( publisher_addr: impl ToSocketAddrs, topics: Vec<String>, ) -> anyhow::Result<SubscriberHandle> { let publisher = tcp::connect(publisher_addr, Json::default).await?; let local_addr = publisher.local_addr()?; let mut handler = server::BaseChannel::with_defaults(publisher).requests(); let subscriber = Subscriber { local_addr, topics }; match handler.next().await { Some(init_topics) => init_topics?.execute(subscriber.clone().serve()).await, None => { return Err(anyhow!( "[{}] Server never initialized the subscriber.", local_addr )) } }; let (handler, abort_handle) = future::abortable(handler.execute(subscriber.serve())); tokio::spawn(async move { match handler.await { Ok(()) | Err(future::Aborted) => info!("[{}] subscriber shutdown.", local_addr), } }); Ok(SubscriberHandle(abort_handle)) } } #[derive(Debug)] struct Subscription { subscriber: subscriber::SubscriberClient, topics: Vec<String>, } #[derive(Clone, Debug)] struct Publisher { clients: Arc<Mutex<HashMap<SocketAddr, Subscription>>>, subscriptions: Arc<RwLock<HashMap<String, HashMap<SocketAddr, subscriber::SubscriberClient>>>>, } struct PublisherAddrs { publisher: SocketAddr, subscriptions: SocketAddr, } impl Publisher { async fn start(self) -> io::Result<PublisherAddrs> { let mut connecting_publishers = tcp::listen("localhost:0", Json::default).await?; let publisher_addrs = PublisherAddrs { publisher: connecting_publishers.local_addr(), subscriptions: self.clone().start_subscription_manager().await?, }; info!("[{}] listening for publishers.", publisher_addrs.publisher); tokio::spawn(async move { let publisher = connecting_publishers.next().await.unwrap().unwrap(); info!("[{}] publisher connected.", publisher.peer_addr().unwrap()); server::BaseChannel::with_defaults(publisher) .execute(self.serve()) .await }); Ok(publisher_addrs) } async fn start_subscription_manager(mut self) -> io::Result<SocketAddr> { let mut connecting_subscribers = tcp::listen("localhost:0", Json::default) .await? .filter_map(|r| future::ready(r.ok())); let new_subscriber_addr = connecting_subscribers.get_ref().local_addr(); info!("[{}] listening for subscribers.", new_subscriber_addr); tokio::spawn(async move { while let Some(conn) = connecting_subscribers.next().await { let subscriber_addr = conn.peer_addr().unwrap(); let tarpc::client::NewClient { client: subscriber, dispatch, } = subscriber::SubscriberClient::new(client::Config::default(), conn); let (ready_tx, ready) = oneshot::channel(); self.clone() .start_subscriber_gc(subscriber_addr, dispatch, ready); self.initialize_subscription(subscriber_addr, subscriber) .await; ready_tx.send(()).unwrap(); } }); Ok(new_subscriber_addr) } async fn initialize_subscription( &mut self, subscriber_addr: SocketAddr, subscriber: subscriber::SubscriberClient, ) { if let Ok(topics) = subscriber.topics(context::current()).await { self.clients.lock().unwrap().insert( subscriber_addr, Subscription { subscriber: subscriber.clone(), topics: topics.clone(), }, ); info!("[{}] subscribed to topics: {:?}", subscriber_addr, topics); let mut subscriptions = self.subscriptions.write().unwrap(); for topic in topics { subscriptions .entry(topic) .or_insert_with(HashMap::new) .insert(subscriber_addr, subscriber.clone()); } } } fn start_subscriber_gc( self, subscriber_addr: SocketAddr, client_dispatch: impl Future<Output = anyhow::Result<()>> + Send + 'static, subscriber_ready: oneshot::Receiver<()>, ) { tokio::spawn(async move { if let Err(e) = client_dispatch.await { info!( "[{}] subscriber connection broken: {:?}", subscriber_addr, e ) } let _ = subscriber_ready.await; if let Some(subscription) = self.clients.lock().unwrap().remove(&subscriber_addr) { info!( "[{} unsubscribing from topics: {:?}", subscriber_addr, subscription.topics ); let mut subscriptions = self.subscriptions.write().unwrap(); for topic in subscription.topics { let subscribers = subscriptions.get_mut(&topic).unwrap(); subscribers.remove(&subscriber_addr); if subscribers.is_empty() { subscriptions.remove(&topic); } } } }); } } #[tarpc::server] impl publisher::Publisher for Publisher { async fn publish(self, _: context::Context, topic: String, message: String) { info!("received message to publish."); let mut subscribers = match self.subscriptions.read().unwrap().get(&topic) { None => return, Some(subscriptions) => subscriptions.clone(), }; let mut publications = Vec::new(); for client in subscribers.values_mut() { publications.push(client.receive(context::current(), topic.clone(), message.clone())); } for response in future::join_all(publications).await { if let Err(e) = response { info!("failed to broadcast to subscriber: {}", e); } } } } #[tokio::main] async fn main() -> anyhow::Result<()> { env_logger::init(); let clients = Arc::new(Mutex::new(HashMap::new())); let addrs = Publisher { clients, subscriptions: Arc::new(RwLock::new(HashMap::new())), } .start() .await?; let _subscriber0 = Subscriber::connect( addrs.subscriptions, vec!["calculus".into(), "cool shorts".into()], ) .await?; let _subscriber1 = Subscriber::connect( addrs.subscriptions, vec!["cool shorts".into(), "history".into()], ) .await?; let publisher = publisher::PublisherClient::new( client::Config::default(), tcp::connect(addrs.publisher, Json::default).await?, ) .spawn()?; publisher .publish(context::current(), "calculus".into(), "sqrt(2)".into()) .await?; publisher .publish( context::current(), "cool shorts".into(), "hello to all".into(), ) .await?; publisher .publish(context::current(), "history".into(), "napoleon".to_string()) .await?; drop(_subscriber0); publisher .publish( context::current(), "cool shorts".into(), "hello to who?".into(), ) .await?; info!("done."); Ok(()) }
use anyhow::anyhow; use futures::{ channel::oneshot, future::{self, AbortHandle}, prelude::*, }; use log::info; use publisher::Publisher as _; use std::{ collections::HashMap, io, net::SocketAddr, sync::{Arc, Mutex, RwLock}, }; use subscriber::Subscriber as _; use tarpc::{ client, context, serde_transport::tcp, server::{self, Channel}, }; use tokio::net::ToSocketAddrs; use tokio_serde::formats::Json; pub mod subscriber { #[tarpc::service] pub trait Subscriber { async fn topics() -> Vec<String>; async fn receive(topic: String, message: String); } } pub mod publisher { #[tarpc::service] pub trait Publisher { async fn publish(topic: String, message: String); } } #[derive(Clone, Debug)] struct Subscriber { local_addr: SocketAddr, topics: Vec<String>, } #[tarpc::server] impl subscriber::Subscriber for Subscriber { async fn topics(self, _: context::Context) -> Vec<String> { self.topics.clone() } async fn receive(self, _: context::Context, topic: String, message: String) { info!( "[{}] received message on topic '{}': {}", self.local_addr, topic, message ); } } struct SubscriberHandle(AbortHandle); impl Drop for SubscriberHandle { fn drop(&mut self) { self.0.abort(); } } impl Subscriber { async fn connect( publisher_addr: impl ToSocketAddrs, topics: Vec<String>, ) -> anyhow::Result<SubscriberHandle> { let publisher = tcp::connect(publisher_addr, Json::default).await?; let local_addr = publisher.local_addr()?; let mut handler = server::BaseChannel::with_defaults(publisher).requests(); let subscriber = Subscriber { local_addr, topics }; match handler.next().await { Some(init_topics) => init_topics?.execute(subscriber.clone().serve()).await, None => { return Err(anyhow!( "[{}] Server never initialized the subscriber.", local_addr )) } }; let (handler, abort_handle) = future::abortable(handler.execute(subscriber.serve())); tokio::spawn(async move { match handler.await { Ok(()) | Err(future::Aborted) => info!("[{}] subscriber shutdown.", local_addr), } }); Ok(SubscriberHandle(abort_handle)) } } #[derive(Debug)] struct Subscription { subscriber: subscriber::SubscriberClient, topics: Vec<String>, } #[derive(Clone, Debug)] struct Publisher { clients: Arc<Mutex<HashMap<SocketAddr, Subscription>>>, subscriptions: Arc<RwLock<HashMap<String, HashMap<SocketAddr, subscriber::SubscriberClient>>>>, } struct PublisherAddrs { publisher: SocketAddr, subscriptions: SocketAddr, } impl Publisher { async fn start(self) -> io::Result<PublisherAddrs> { let mut connecting_publishers = tcp::listen("localhost:0", Json::default).await?; let publisher_addrs = PublisherAddrs { publisher: connecting_publishers.local_addr(), subscriptions: self.clone().start_subscription_manager().await?, }; info!("[{}] listening for publishers.", publisher_addrs.publisher); tokio::spawn(async move { let publisher = connecting_publishers.next().await.unwrap().unwrap(); info!("[{}] publisher connected.", publisher.peer_addr().unwrap()); server::BaseChannel::with_defaults(publisher) .execute(self.serve()) .await }); Ok(publisher_addrs) } async fn start_subscription_manager(mut self) -> io::Result<SocketAddr> { let mut connecting_subscribers = tcp::listen("localhost:0", Json::default) .await? .filter_map(|r| future::ready(r.ok())); let new_subscriber_addr = connecting_subscribers.get_ref().local_addr(); info!("[{}] listening for subscribers.", new_subscriber_addr); tokio::spawn(async move { while let Some(conn) = connecting_subscribers.next().await { let subscriber_addr = conn.peer_addr().unwrap(); let tarpc::client::NewClient { client: subscriber, dispatch, } = subscriber::SubscriberClient::new(client::Config::default(), conn); let (ready_tx, ready) = oneshot::channel(); self.clone() .start_subscriber_gc(subscriber_addr, dispatch, ready); self.initialize_subscription(subscriber_addr, subscriber) .await; ready_tx.send(()).unwrap(); } }); Ok(new_subscriber_addr) } async fn initialize_subscription( &mut self, subscriber_addr: SocketAddr, subscriber: subscriber::SubscriberClient, ) {
} fn start_subscriber_gc( self, subscriber_addr: SocketAddr, client_dispatch: impl Future<Output = anyhow::Result<()>> + Send + 'static, subscriber_ready: oneshot::Receiver<()>, ) { tokio::spawn(async move { if let Err(e) = client_dispatch.await { info!( "[{}] subscriber connection broken: {:?}", subscriber_addr, e ) } let _ = subscriber_ready.await; if let Some(subscription) = self.clients.lock().unwrap().remove(&subscriber_addr) { info!( "[{} unsubscribing from topics: {:?}", subscriber_addr, subscription.topics ); let mut subscriptions = self.subscriptions.write().unwrap(); for topic in subscription.topics { let subscribers = subscriptions.get_mut(&topic).unwrap(); subscribers.remove(&subscriber_addr); if subscribers.is_empty() { subscriptions.remove(&topic); } } } }); } } #[tarpc::server] impl publisher::Publisher for Publisher { async fn publish(self, _: context::Context, topic: String, message: String) { info!("received message to publish."); let mut subscribers = match self.subscriptions.read().unwrap().get(&topic) { None => return, Some(subscriptions) => subscriptions.clone(), }; let mut publications = Vec::new(); for client in subscribers.values_mut() { publications.push(client.receive(context::current(), topic.clone(), message.clone())); } for response in future::join_all(publications).await { if let Err(e) = response { info!("failed to broadcast to subscriber: {}", e); } } } } #[tokio::main] async fn main() -> anyhow::Result<()> { env_logger::init(); let clients = Arc::new(Mutex::new(HashMap::new())); let addrs = Publisher { clients, subscriptions: Arc::new(RwLock::new(HashMap::new())), } .start() .await?; let _subscriber0 = Subscriber::connect( addrs.subscriptions, vec!["calculus".into(), "cool shorts".into()], ) .await?; let _subscriber1 = Subscriber::connect( addrs.subscriptions, vec!["cool shorts".into(), "history".into()], ) .await?; let publisher = publisher::PublisherClient::new( client::Config::default(), tcp::connect(addrs.publisher, Json::default).await?, ) .spawn()?; publisher .publish(context::current(), "calculus".into(), "sqrt(2)".into()) .await?; publisher .publish( context::current(), "cool shorts".into(), "hello to all".into(), ) .await?; publisher .publish(context::current(), "history".into(), "napoleon".to_string()) .await?; drop(_subscriber0); publisher .publish( context::current(), "cool shorts".into(), "hello to who?".into(), ) .await?; info!("done."); Ok(()) }
if let Ok(topics) = subscriber.topics(context::current()).await { self.clients.lock().unwrap().insert( subscriber_addr, Subscription { subscriber: subscriber.clone(), topics: topics.clone(), }, ); info!("[{}] subscribed to topics: {:?}", subscriber_addr, topics); let mut subscriptions = self.subscriptions.write().unwrap(); for topic in topics { subscriptions .entry(topic) .or_insert_with(HashMap::new) .insert(subscriber_addr, subscriber.clone()); } }
if_condition
[ { "content": "/// The server end of an open connection with a client, streaming in requests from, and sinking\n\n/// responses to, the client.\n\n///\n\n/// The ways to use a Channel, in order of simplest to most complex, is:\n\n/// 1. [`Channel::execute`] - Requires the `tokio1` feature. This method is best fo...
Rust
src/parsers.rs
hoodie/sdp-nom
c0ffeea95aeed252ba1af2b8a04c570a0e75c942
#![allow(dead_code)] use nom::{ branch::alt, bytes::complete::{tag, take_while, take_while1}, character::{ complete::{multispace0, space1}, is_digit, }, combinator::{complete, map, map_res, opt}, error::ParseError, multi::many0, sequence::{delimited, preceded, separated_pair, terminated}, IResult, Parser, }; use std::{borrow::Cow, net::IpAddr}; #[cfg(test)] pub fn create_test_vec(strs: &[&str]) -> Vec<Cow<'static, str>> { strs.iter().map(|&s| Cow::from(s.to_owned())).collect() } pub fn is_not_space(c: char) -> bool { c != ' ' } pub fn is_alphabetic(chr: u8) -> bool { (0x41..=0x5A).contains(&chr) || (0x61..=0x7A).contains(&chr) } pub fn is_alphanumeric(chr: char) -> bool { is_alphabetic(chr as u8) || is_digit(chr as u8) } pub fn is_numeric(chr: char) -> bool { is_digit(chr as u8) } pub fn ws<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( f: F, ) -> impl Parser<&'a str, O, E> { delimited(multispace0, f, multispace0) } pub fn wsf<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { delimited(multispace0, f, multispace0) } pub fn cowify<'a, E: ParseError<&'a str>, F: Parser<&'a str, &'a str, E>>( f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, Cow<'a, str>, E> { map(f, Cow::from) } pub fn a_line<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { line("a=", f) } pub fn attribute<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( attribute_kind: &'a str, f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { line( "a=", map(separated_pair(tag(attribute_kind), tag(":"), f), |(_, x)| x), ) } pub fn attribute_p<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( p: F, f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { line("a=", map(separated_pair(p, tag(":"), f), |(_, x)| x)) } pub fn line<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( prefix: &'a str, f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { complete(preceded(tag(prefix), f)) } pub fn read_number(input: &str) -> IResult<&str, u32> { map_res( take_while1(|c: char| -> bool { c != ' ' && c != ':' && c != '/' }), |i: &str| i.parse::<u32>(), )(input) } pub fn read_big_number(input: &str) -> IResult<&str, u64> { map_res( take_while1(|c: char| -> bool { c != ' ' && c != ':' && c != '/' }), |i: &str| (i).parse::<u64>(), )(input) } pub fn read_everything(input: &str) -> IResult<&str, &str> { take_while(|c| c != '\n')(input) } pub fn read_string0(input: &str) -> IResult<&str, &str> { take_while(is_not_space)(input) } pub fn read_string(input: &str) -> IResult<&str, &str> { take_while1(is_not_space)(input) } pub fn read_non_colon_string(input: &str) -> IResult<&str, &str> { take_while1(|c: char| -> bool { c != ' ' && c != ':' })(input) } pub fn read_non_slash_string(input: &str) -> IResult<&str, &str> { take_while1(|c: char| -> bool { c != ' ' && c != '/' })(input) } pub fn slash_separated_strings(input: &str) -> IResult<&str, Vec<&str>> { many0(terminated(read_non_slash_string, opt(tag("/"))))(input) } pub fn slash_separated_cow_strings(input: &str) -> IResult<&str, Vec<Cow<'_, str>>> { many0(terminated(cowify(read_non_slash_string), opt(tag("/"))))(input) } pub fn space_separated_cow_strings(input: &str) -> IResult<&str, Vec<Cow<'_, str>>> { many0(terminated(cowify(read_string), multispace0))(input) } pub fn space_separated_strings(input: &str) -> IResult<&str, Vec<&str>> { many0(terminated(read_string, multispace0))(input) } pub fn read_addr(input: &str) -> IResult<&str, IpAddr> { map_res(take_while1(|c| c != ' ' && c != '/'), str::parse)(input) } #[derive(Clone, PartialEq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr( feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase") )] #[non_exhaustive] pub enum IpVer { Ip4, Ip6, } pub fn read_ipver(input: &str) -> IResult<&str, IpVer> { alt(( map(tag("IP4"), |_| IpVer::Ip4), map(tag("IP6"), |_| IpVer::Ip6), ))(input) } pub fn read_as_strings(input: &str) -> IResult<&str, Vec<&str>> { many0(terminated(read_string, opt(space1)))(input) } pub fn read_as_cow_strings(input: &str) -> IResult<&str, Vec<Cow<'_, str>>> { many0(terminated(cowify(read_string), opt(space1)))(input) } pub fn read_as_numbers(input: &str) -> IResult<&str, Vec<u32>> { many0(terminated(read_number, opt(space1)))(input) }
#![allow(dead_code)] use nom::{ branch::alt, bytes::complete::{tag, take_while, take_while1}, character::{ complete::{multispace0, space1}, is_digit, }, combinator::{complete, map, map_res, opt}, error::ParseError, multi::many0, sequence::{delimited, preceded, separated_pair, terminated}, IResult, Parser, }; use std::{borrow::Cow, net::IpAddr}; #[cfg(test)] pub fn create_test_vec(strs: &[&str]) -> Vec<Cow<'static, str>> { strs.iter().map(|&s| Cow::from(s.to_owned())).collect() } pub fn is_not_space(c: char) -> bool { c != ' ' } pub fn is_alphabetic(chr: u8) -> bool { (0x41..=0x5A).contains(&chr) || (0x61..=0x7A).contains(&chr) } pub fn is_alphanumeric(chr: char) -> bool { is_alphabetic(chr as u8) || is_digit(chr as u8) } pub fn is_numeric(chr: char) -> bool { is_digit(chr as u8) } pub fn ws<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( f: F, ) -> impl Parser<&'a str, O, E> { delimited(multispace0, f, multispace0) } pub fn wsf<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { delimited(multispace0, f, multispace0) } pub fn cowify<'a, E: ParseError<&'a str>, F: Parser<&'a str, &'a str, E>>( f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, Cow<'a, str>, E> { map(f, Cow::from) } pub fn a_line<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { line("a=", f) } pub fn attribute<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( attribute_kind: &'a str, f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { line( "a=", map(separated_pair(tag(attribute_kind), tag(":"), f), |(_, x)| x), ) } pub fn attribute_p<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( p: F, f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { line("a=", map(separated_pair(p, tag(":"), f), |(_, x)| x)) } pub fn line<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( prefix: &'a str, f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { complete(preceded(tag(prefix), f)) } pub fn read_number(input: &str) -> IResult<&str, u32> { map_res( take_while1(|c: char| -> bool { c != ' ' && c != ':' && c != '/' }), |i: &str| i.parse::<u32>(), )(input) } pub fn read_big_number(input: &str) -> IResult<&str, u64> {
(input) } pub fn read_everything(input: &str) -> IResult<&str, &str> { take_while(|c| c != '\n')(input) } pub fn read_string0(input: &str) -> IResult<&str, &str> { take_while(is_not_space)(input) } pub fn read_string(input: &str) -> IResult<&str, &str> { take_while1(is_not_space)(input) } pub fn read_non_colon_string(input: &str) -> IResult<&str, &str> { take_while1(|c: char| -> bool { c != ' ' && c != ':' })(input) } pub fn read_non_slash_string(input: &str) -> IResult<&str, &str> { take_while1(|c: char| -> bool { c != ' ' && c != '/' })(input) } pub fn slash_separated_strings(input: &str) -> IResult<&str, Vec<&str>> { many0(terminated(read_non_slash_string, opt(tag("/"))))(input) } pub fn slash_separated_cow_strings(input: &str) -> IResult<&str, Vec<Cow<'_, str>>> { many0(terminated(cowify(read_non_slash_string), opt(tag("/"))))(input) } pub fn space_separated_cow_strings(input: &str) -> IResult<&str, Vec<Cow<'_, str>>> { many0(terminated(cowify(read_string), multispace0))(input) } pub fn space_separated_strings(input: &str) -> IResult<&str, Vec<&str>> { many0(terminated(read_string, multispace0))(input) } pub fn read_addr(input: &str) -> IResult<&str, IpAddr> { map_res(take_while1(|c| c != ' ' && c != '/'), str::parse)(input) } #[derive(Clone, PartialEq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr( feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase") )] #[non_exhaustive] pub enum IpVer { Ip4, Ip6, } pub fn read_ipver(input: &str) -> IResult<&str, IpVer> { alt(( map(tag("IP4"), |_| IpVer::Ip4), map(tag("IP6"), |_| IpVer::Ip6), ))(input) } pub fn read_as_strings(input: &str) -> IResult<&str, Vec<&str>> { many0(terminated(read_string, opt(space1)))(input) } pub fn read_as_cow_strings(input: &str) -> IResult<&str, Vec<Cow<'_, str>>> { many0(terminated(cowify(read_string), opt(space1)))(input) } pub fn read_as_numbers(input: &str) -> IResult<&str, Vec<u32>> { many0(terminated(read_number, opt(space1)))(input) }
map_res( take_while1(|c: char| -> bool { c != ' ' && c != ':' && c != '/' }), |i: &str| (i).parse::<u64>(), )
call_expression
[ { "content": "pub fn rtpmap_line(input: &str) -> IResult<&str, RtpMap> {\n\n attribute(\n\n \"rtpmap\",\n\n map(\n\n tuple((\n\n read_number, // payload_typ\n\n preceded(multispace1, cowify(read_non_slash_string))...
Rust
lib/codegen/src/ir/types.rs
gmorenz/cretonne
bcf6a058841bde1f773e5a30bdaff71224d0b99a
use std::default::Default; use std::fmt::{self, Debug, Display, Formatter}; #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct Type(u8); pub const VOID: Type = Type(0); const LANE_BASE: u8 = 0x70; const VECTOR_BASE: u8 = LANE_BASE + 16; include!(concat!(env!("OUT_DIR"), "/types.rs")); impl Type { pub fn lane_type(self) -> Type { if self.0 < VECTOR_BASE { self } else { Type(LANE_BASE | (self.0 & 0x0f)) } } pub fn log2_lane_bits(self) -> u8 { match self.lane_type() { B1 => 0, B8 | I8 => 3, B16 | I16 => 4, B32 | I32 | F32 => 5, B64 | I64 | F64 => 6, _ => 0, } } pub fn lane_bits(self) -> u8 { match self.lane_type() { B1 => 1, B8 | I8 => 8, B16 | I16 => 16, B32 | I32 | F32 => 32, B64 | I64 | F64 => 64, _ => 0, } } pub fn int(bits: u16) -> Option<Type> { match bits { 8 => Some(I8), 16 => Some(I16), 32 => Some(I32), 64 => Some(I64), _ => None, } } fn replace_lanes(self, lane: Type) -> Type { debug_assert!(lane.is_lane() && !self.is_special()); Type((lane.0 & 0x0f) | (self.0 & 0xf0)) } pub fn as_bool_pedantic(self) -> Type { self.replace_lanes(match self.lane_type() { B8 | I8 => B8, B16 | I16 => B16, B32 | I32 | F32 => B32, B64 | I64 | F64 => B64, _ => B1, }) } pub fn as_bool(self) -> Type { if !self.is_vector() { B1 } else { self.as_bool_pedantic() } } pub fn half_width(self) -> Option<Type> { Some(self.replace_lanes(match self.lane_type() { I16 => I8, I32 => I16, I64 => I32, F64 => F32, B16 => B8, B32 => B16, B64 => B32, _ => return None, })) } pub fn double_width(self) -> Option<Type> { Some(self.replace_lanes(match self.lane_type() { I8 => I16, I16 => I32, I32 => I64, F32 => F64, B8 => B16, B16 => B32, B32 => B64, _ => return None, })) } pub fn is_void(self) -> bool { self == VOID } pub fn is_special(self) -> bool { self.0 < LANE_BASE } pub fn is_lane(self) -> bool { LANE_BASE <= self.0 && self.0 < VECTOR_BASE } pub fn is_vector(self) -> bool { self.0 >= VECTOR_BASE } pub fn is_bool(self) -> bool { match self { B1 | B8 | B16 | B32 | B64 => true, _ => false, } } pub fn is_int(self) -> bool { match self { I8 | I16 | I32 | I64 => true, _ => false, } } pub fn is_float(self) -> bool { match self { F32 | F64 => true, _ => false, } } pub fn is_flags(self) -> bool { match self { IFLAGS | FFLAGS => true, _ => false, } } pub fn log2_lane_count(self) -> u8 { self.0.saturating_sub(LANE_BASE) >> 4 } pub fn lane_count(self) -> u16 { 1 << self.log2_lane_count() } pub fn bits(self) -> u16 { u16::from(self.lane_bits()) * self.lane_count() } pub fn bytes(self) -> u32 { (u32::from(self.bits()) + 7) / 8 } pub fn by(self, n: u16) -> Option<Type> { if self.lane_bits() == 0 || !n.is_power_of_two() { return None; } let log2_lanes: u32 = n.trailing_zeros(); let new_type = u32::from(self.0) + (log2_lanes << 4); if new_type < 0x100 { Some(Type(new_type as u8)) } else { None } } pub fn half_vector(self) -> Option<Type> { if self.is_vector() { Some(Type(self.0 - 0x10)) } else { None } } pub fn index(self) -> usize { usize::from(self.0) } pub fn wider_or_equal(self, other: Type) -> bool { self.lane_count() == other.lane_count() && self.lane_bits() >= other.lane_bits() } } impl Display for Type { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.is_bool() { write!(f, "b{}", self.lane_bits()) } else if self.is_int() { write!(f, "i{}", self.lane_bits()) } else if self.is_float() { write!(f, "f{}", self.lane_bits()) } else if self.is_vector() { write!(f, "{}x{}", self.lane_type(), self.lane_count()) } else { f.write_str(match *self { VOID => "void", IFLAGS => "iflags", FFLAGS => "fflags", _ => panic!("Invalid Type(0x{:x})", self.0), }) } } } impl Debug for Type { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.is_bool() { write!(f, "types::B{}", self.lane_bits()) } else if self.is_int() { write!(f, "types::I{}", self.lane_bits()) } else if self.is_float() { write!(f, "types::F{}", self.lane_bits()) } else if self.is_vector() { write!(f, "{:?}X{}", self.lane_type(), self.lane_count()) } else { match *self { VOID => write!(f, "types::VOID"), IFLAGS => write!(f, "types::IFLAGS"), FFLAGS => write!(f, "types::FFLAGS"), _ => write!(f, "Type(0x{:x})", self.0), } } } } impl Default for Type { fn default() -> Self { VOID } } #[cfg(test)] mod tests { use super::*; use std::string::ToString; #[test] fn basic_scalars() { assert_eq!(VOID, VOID.lane_type()); assert_eq!(0, VOID.bits()); assert_eq!(IFLAGS, IFLAGS.lane_type()); assert_eq!(0, IFLAGS.bits()); assert_eq!(FFLAGS, FFLAGS.lane_type()); assert_eq!(0, FFLAGS.bits()); assert_eq!(B1, B1.lane_type()); assert_eq!(B8, B8.lane_type()); assert_eq!(B16, B16.lane_type()); assert_eq!(B32, B32.lane_type()); assert_eq!(B64, B64.lane_type()); assert_eq!(I8, I8.lane_type()); assert_eq!(I16, I16.lane_type()); assert_eq!(I32, I32.lane_type()); assert_eq!(I64, I64.lane_type()); assert_eq!(F32, F32.lane_type()); assert_eq!(F64, F64.lane_type()); assert_eq!(VOID.lane_bits(), 0); assert_eq!(IFLAGS.lane_bits(), 0); assert_eq!(FFLAGS.lane_bits(), 0); assert_eq!(B1.lane_bits(), 1); assert_eq!(B8.lane_bits(), 8); assert_eq!(B16.lane_bits(), 16); assert_eq!(B32.lane_bits(), 32); assert_eq!(B64.lane_bits(), 64); assert_eq!(I8.lane_bits(), 8); assert_eq!(I16.lane_bits(), 16); assert_eq!(I32.lane_bits(), 32); assert_eq!(I64.lane_bits(), 64); assert_eq!(F32.lane_bits(), 32); assert_eq!(F64.lane_bits(), 64); } #[test] fn typevar_functions() { assert_eq!(VOID.half_width(), None); assert_eq!(IFLAGS.half_width(), None); assert_eq!(FFLAGS.half_width(), None); assert_eq!(B1.half_width(), None); assert_eq!(B8.half_width(), None); assert_eq!(B16.half_width(), Some(B8)); assert_eq!(B32.half_width(), Some(B16)); assert_eq!(B64.half_width(), Some(B32)); assert_eq!(I8.half_width(), None); assert_eq!(I16.half_width(), Some(I8)); assert_eq!(I32.half_width(), Some(I16)); assert_eq!(I32X4.half_width(), Some(I16X4)); assert_eq!(I64.half_width(), Some(I32)); assert_eq!(F32.half_width(), None); assert_eq!(F64.half_width(), Some(F32)); assert_eq!(VOID.double_width(), None); assert_eq!(IFLAGS.double_width(), None); assert_eq!(FFLAGS.double_width(), None); assert_eq!(B1.double_width(), None); assert_eq!(B8.double_width(), Some(B16)); assert_eq!(B16.double_width(), Some(B32)); assert_eq!(B32.double_width(), Some(B64)); assert_eq!(B64.double_width(), None); assert_eq!(I8.double_width(), Some(I16)); assert_eq!(I16.double_width(), Some(I32)); assert_eq!(I32.double_width(), Some(I64)); assert_eq!(I32X4.double_width(), Some(I64X4)); assert_eq!(I64.double_width(), None); assert_eq!(F32.double_width(), Some(F64)); assert_eq!(F64.double_width(), None); } #[test] fn vectors() { let big = F64.by(256).unwrap(); assert_eq!(big.lane_bits(), 64); assert_eq!(big.lane_count(), 256); assert_eq!(big.bits(), 64 * 256); assert_eq!(big.half_vector().unwrap().to_string(), "f64x128"); assert_eq!(B1.by(2).unwrap().half_vector().unwrap().to_string(), "b1"); assert_eq!(I32.half_vector(), None); assert_eq!(VOID.half_vector(), None); assert_eq!(I32.by(4), Some(I32X4)); assert_eq!(F64.by(8), Some(F64X8)); } #[test] fn format_scalars() { assert_eq!(VOID.to_string(), "void"); assert_eq!(IFLAGS.to_string(), "iflags"); assert_eq!(FFLAGS.to_string(), "fflags"); assert_eq!(B1.to_string(), "b1"); assert_eq!(B8.to_string(), "b8"); assert_eq!(B16.to_string(), "b16"); assert_eq!(B32.to_string(), "b32"); assert_eq!(B64.to_string(), "b64"); assert_eq!(I8.to_string(), "i8"); assert_eq!(I16.to_string(), "i16"); assert_eq!(I32.to_string(), "i32"); assert_eq!(I64.to_string(), "i64"); assert_eq!(F32.to_string(), "f32"); assert_eq!(F64.to_string(), "f64"); } #[test] fn format_vectors() { assert_eq!(B1.by(8).unwrap().to_string(), "b1x8"); assert_eq!(B8.by(1).unwrap().to_string(), "b8"); assert_eq!(B16.by(256).unwrap().to_string(), "b16x256"); assert_eq!(B32.by(4).unwrap().by(2).unwrap().to_string(), "b32x8"); assert_eq!(B64.by(8).unwrap().to_string(), "b64x8"); assert_eq!(I8.by(64).unwrap().to_string(), "i8x64"); assert_eq!(F64.by(2).unwrap().to_string(), "f64x2"); assert_eq!(I8.by(3), None); assert_eq!(I8.by(512), None); assert_eq!(VOID.by(4), None); } #[test] fn as_bool() { assert_eq!(I32X4.as_bool(), B32X4); assert_eq!(I32.as_bool(), B1); assert_eq!(I32X4.as_bool_pedantic(), B32X4); assert_eq!(I32.as_bool_pedantic(), B32); } }
use std::default::Default; use std::fmt::{self, Debug, Display, Formatter}; #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct Type(u8); pub const VOID: Type = Type(0); const LANE_BASE: u8 = 0x70; const VECTOR_BASE: u8 = LANE_BASE + 16; include!(concat!(env!("OUT_DIR"), "/types.rs")); impl Type { pub fn lane_type(self) -> Typ
pub fn log2_lane_bits(self) -> u8 { match self.lane_type() { B1 => 0, B8 | I8 => 3, B16 | I16 => 4, B32 | I32 | F32 => 5, B64 | I64 | F64 => 6, _ => 0, } } pub fn lane_bits(self) -> u8 { match self.lane_type() { B1 => 1, B8 | I8 => 8, B16 | I16 => 16, B32 | I32 | F32 => 32, B64 | I64 | F64 => 64, _ => 0, } } pub fn int(bits: u16) -> Option<Type> { match bits { 8 => Some(I8), 16 => Some(I16), 32 => Some(I32), 64 => Some(I64), _ => None, } } fn replace_lanes(self, lane: Type) -> Type { debug_assert!(lane.is_lane() && !self.is_special()); Type((lane.0 & 0x0f) | (self.0 & 0xf0)) } pub fn as_bool_pedantic(self) -> Type { self.replace_lanes(match self.lane_type() { B8 | I8 => B8, B16 | I16 => B16, B32 | I32 | F32 => B32, B64 | I64 | F64 => B64, _ => B1, }) } pub fn as_bool(self) -> Type { if !self.is_vector() { B1 } else { self.as_bool_pedantic() } } pub fn half_width(self) -> Option<Type> { Some(self.replace_lanes(match self.lane_type() { I16 => I8, I32 => I16, I64 => I32, F64 => F32, B16 => B8, B32 => B16, B64 => B32, _ => return None, })) } pub fn double_width(self) -> Option<Type> { Some(self.replace_lanes(match self.lane_type() { I8 => I16, I16 => I32, I32 => I64, F32 => F64, B8 => B16, B16 => B32, B32 => B64, _ => return None, })) } pub fn is_void(self) -> bool { self == VOID } pub fn is_special(self) -> bool { self.0 < LANE_BASE } pub fn is_lane(self) -> bool { LANE_BASE <= self.0 && self.0 < VECTOR_BASE } pub fn is_vector(self) -> bool { self.0 >= VECTOR_BASE } pub fn is_bool(self) -> bool { match self { B1 | B8 | B16 | B32 | B64 => true, _ => false, } } pub fn is_int(self) -> bool { match self { I8 | I16 | I32 | I64 => true, _ => false, } } pub fn is_float(self) -> bool { match self { F32 | F64 => true, _ => false, } } pub fn is_flags(self) -> bool { match self { IFLAGS | FFLAGS => true, _ => false, } } pub fn log2_lane_count(self) -> u8 { self.0.saturating_sub(LANE_BASE) >> 4 } pub fn lane_count(self) -> u16 { 1 << self.log2_lane_count() } pub fn bits(self) -> u16 { u16::from(self.lane_bits()) * self.lane_count() } pub fn bytes(self) -> u32 { (u32::from(self.bits()) + 7) / 8 } pub fn by(self, n: u16) -> Option<Type> { if self.lane_bits() == 0 || !n.is_power_of_two() { return None; } let log2_lanes: u32 = n.trailing_zeros(); let new_type = u32::from(self.0) + (log2_lanes << 4); if new_type < 0x100 { Some(Type(new_type as u8)) } else { None } } pub fn half_vector(self) -> Option<Type> { if self.is_vector() { Some(Type(self.0 - 0x10)) } else { None } } pub fn index(self) -> usize { usize::from(self.0) } pub fn wider_or_equal(self, other: Type) -> bool { self.lane_count() == other.lane_count() && self.lane_bits() >= other.lane_bits() } } impl Display for Type { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.is_bool() { write!(f, "b{}", self.lane_bits()) } else if self.is_int() { write!(f, "i{}", self.lane_bits()) } else if self.is_float() { write!(f, "f{}", self.lane_bits()) } else if self.is_vector() { write!(f, "{}x{}", self.lane_type(), self.lane_count()) } else { f.write_str(match *self { VOID => "void", IFLAGS => "iflags", FFLAGS => "fflags", _ => panic!("Invalid Type(0x{:x})", self.0), }) } } } impl Debug for Type { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.is_bool() { write!(f, "types::B{}", self.lane_bits()) } else if self.is_int() { write!(f, "types::I{}", self.lane_bits()) } else if self.is_float() { write!(f, "types::F{}", self.lane_bits()) } else if self.is_vector() { write!(f, "{:?}X{}", self.lane_type(), self.lane_count()) } else { match *self { VOID => write!(f, "types::VOID"), IFLAGS => write!(f, "types::IFLAGS"), FFLAGS => write!(f, "types::FFLAGS"), _ => write!(f, "Type(0x{:x})", self.0), } } } } impl Default for Type { fn default() -> Self { VOID } } #[cfg(test)] mod tests { use super::*; use std::string::ToString; #[test] fn basic_scalars() { assert_eq!(VOID, VOID.lane_type()); assert_eq!(0, VOID.bits()); assert_eq!(IFLAGS, IFLAGS.lane_type()); assert_eq!(0, IFLAGS.bits()); assert_eq!(FFLAGS, FFLAGS.lane_type()); assert_eq!(0, FFLAGS.bits()); assert_eq!(B1, B1.lane_type()); assert_eq!(B8, B8.lane_type()); assert_eq!(B16, B16.lane_type()); assert_eq!(B32, B32.lane_type()); assert_eq!(B64, B64.lane_type()); assert_eq!(I8, I8.lane_type()); assert_eq!(I16, I16.lane_type()); assert_eq!(I32, I32.lane_type()); assert_eq!(I64, I64.lane_type()); assert_eq!(F32, F32.lane_type()); assert_eq!(F64, F64.lane_type()); assert_eq!(VOID.lane_bits(), 0); assert_eq!(IFLAGS.lane_bits(), 0); assert_eq!(FFLAGS.lane_bits(), 0); assert_eq!(B1.lane_bits(), 1); assert_eq!(B8.lane_bits(), 8); assert_eq!(B16.lane_bits(), 16); assert_eq!(B32.lane_bits(), 32); assert_eq!(B64.lane_bits(), 64); assert_eq!(I8.lane_bits(), 8); assert_eq!(I16.lane_bits(), 16); assert_eq!(I32.lane_bits(), 32); assert_eq!(I64.lane_bits(), 64); assert_eq!(F32.lane_bits(), 32); assert_eq!(F64.lane_bits(), 64); } #[test] fn typevar_functions() { assert_eq!(VOID.half_width(), None); assert_eq!(IFLAGS.half_width(), None); assert_eq!(FFLAGS.half_width(), None); assert_eq!(B1.half_width(), None); assert_eq!(B8.half_width(), None); assert_eq!(B16.half_width(), Some(B8)); assert_eq!(B32.half_width(), Some(B16)); assert_eq!(B64.half_width(), Some(B32)); assert_eq!(I8.half_width(), None); assert_eq!(I16.half_width(), Some(I8)); assert_eq!(I32.half_width(), Some(I16)); assert_eq!(I32X4.half_width(), Some(I16X4)); assert_eq!(I64.half_width(), Some(I32)); assert_eq!(F32.half_width(), None); assert_eq!(F64.half_width(), Some(F32)); assert_eq!(VOID.double_width(), None); assert_eq!(IFLAGS.double_width(), None); assert_eq!(FFLAGS.double_width(), None); assert_eq!(B1.double_width(), None); assert_eq!(B8.double_width(), Some(B16)); assert_eq!(B16.double_width(), Some(B32)); assert_eq!(B32.double_width(), Some(B64)); assert_eq!(B64.double_width(), None); assert_eq!(I8.double_width(), Some(I16)); assert_eq!(I16.double_width(), Some(I32)); assert_eq!(I32.double_width(), Some(I64)); assert_eq!(I32X4.double_width(), Some(I64X4)); assert_eq!(I64.double_width(), None); assert_eq!(F32.double_width(), Some(F64)); assert_eq!(F64.double_width(), None); } #[test] fn vectors() { let big = F64.by(256).unwrap(); assert_eq!(big.lane_bits(), 64); assert_eq!(big.lane_count(), 256); assert_eq!(big.bits(), 64 * 256); assert_eq!(big.half_vector().unwrap().to_string(), "f64x128"); assert_eq!(B1.by(2).unwrap().half_vector().unwrap().to_string(), "b1"); assert_eq!(I32.half_vector(), None); assert_eq!(VOID.half_vector(), None); assert_eq!(I32.by(4), Some(I32X4)); assert_eq!(F64.by(8), Some(F64X8)); } #[test] fn format_scalars() { assert_eq!(VOID.to_string(), "void"); assert_eq!(IFLAGS.to_string(), "iflags"); assert_eq!(FFLAGS.to_string(), "fflags"); assert_eq!(B1.to_string(), "b1"); assert_eq!(B8.to_string(), "b8"); assert_eq!(B16.to_string(), "b16"); assert_eq!(B32.to_string(), "b32"); assert_eq!(B64.to_string(), "b64"); assert_eq!(I8.to_string(), "i8"); assert_eq!(I16.to_string(), "i16"); assert_eq!(I32.to_string(), "i32"); assert_eq!(I64.to_string(), "i64"); assert_eq!(F32.to_string(), "f32"); assert_eq!(F64.to_string(), "f64"); } #[test] fn format_vectors() { assert_eq!(B1.by(8).unwrap().to_string(), "b1x8"); assert_eq!(B8.by(1).unwrap().to_string(), "b8"); assert_eq!(B16.by(256).unwrap().to_string(), "b16x256"); assert_eq!(B32.by(4).unwrap().by(2).unwrap().to_string(), "b32x8"); assert_eq!(B64.by(8).unwrap().to_string(), "b64x8"); assert_eq!(I8.by(64).unwrap().to_string(), "i8x64"); assert_eq!(F64.by(2).unwrap().to_string(), "f64x2"); assert_eq!(I8.by(3), None); assert_eq!(I8.by(512), None); assert_eq!(VOID.by(4), None); } #[test] fn as_bool() { assert_eq!(I32X4.as_bool(), B32X4); assert_eq!(I32.as_bool(), B1); assert_eq!(I32X4.as_bool_pedantic(), B32X4); assert_eq!(I32.as_bool_pedantic(), B32); } }
e { if self.0 < VECTOR_BASE { self } else { Type(LANE_BASE | (self.0 & 0x0f)) } }
function_block-function_prefixed
[ { "content": "/// Look for `key` in `table`.\n\n///\n\n/// The provided `hash` value must have been computed from `key` using the same hash function that\n\n/// was used to construct the table.\n\n///\n\n/// Returns `Ok(idx)` with the table index containing the found entry, or `Err(idx)` with the empty\n\n/// s...
Rust
src/command/mod.rs
rwjblue/notion
05b6b795a732602b7301e6b08a4353caa712c191
mod config; mod current; mod deactivate; mod fetch; mod help; mod install; mod shim; mod use_; mod version; pub(crate) use self::config::Config; pub(crate) use self::current::Current; pub(crate) use self::deactivate::Deactivate; pub(crate) use self::fetch::Fetch; pub(crate) use self::help::Help; pub(crate) use self::install::Install; pub(crate) use self::shim::Shim; pub(crate) use self::use_::Use; pub(crate) use self::version::Version; use docopt::Docopt; use serde::de::DeserializeOwned; use notion_core::session::Session; use notion_fail::{FailExt, Fallible}; use {CliParseError, DocoptExt, Notion}; use std::fmt::{self, Display}; use std::str::FromStr; #[derive(Debug, Deserialize, Clone, Copy)] pub(crate) enum CommandName { Fetch, Install, Use, Config, Current, Deactivate, Shim, Help, Version, } impl Display for CommandName { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!( fmt, "{}", match *self { CommandName::Fetch => "fetch", CommandName::Install => "install", CommandName::Use => "use", CommandName::Config => "config", CommandName::Deactivate => "deactivate", CommandName::Current => "current", CommandName::Shim => "shim", CommandName::Help => "help", CommandName::Version => "version", } ) } } impl FromStr for CommandName { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "fetch" => CommandName::Fetch, "install" => CommandName::Install, "use" => CommandName::Use, "config" => CommandName::Config, "current" => CommandName::Current, "deactivate" => CommandName::Deactivate, "shim" => CommandName::Shim, "help" => CommandName::Help, "version" => CommandName::Version, _ => { throw!(()); } }) } } pub(crate) trait Command: Sized { type Args: DeserializeOwned; const USAGE: &'static str; fn help() -> Self; fn parse(notion: Notion, args: Self::Args) -> Fallible<Self>; fn run(self, session: &mut Session) -> Fallible<()>; fn go(notion: Notion, session: &mut Session) -> Fallible<()> { let argv = notion.full_argv(); let args = Docopt::new(Self::USAGE).and_then(|d| d.argv(argv).deserialize()); match args { Ok(args) => Self::parse(notion, args)?.run(session), Err(err) => { if err.is_help() { Self::help().run(session) } else { throw!(err.with_context(CliParseError::from_docopt)); } } } } }
mod config; mod current; mod deactivate; mod fetch; mod help; mod install; mod shim; mod use_; mod version; pub(crate) use self::config::Config; pub(crate) use self::current::Current; pub(crate) use self::deactivate::Deactivate; pub(crate) use self::fetch::Fetch; pub(crate) use self::help::Help; pub(crate) use self::install::Install; pub(crate) use self::shim::Shim; pub(crate) use self::use_::Use; pub(crate) use self::version::Version; use docopt::Docopt; use serde::de::DeserializeOwned; use notion_core::session::Session; use notion_fail::{FailExt, Fallible}; use {CliParseError, DocoptExt, Notion}; use std::fmt::{self, Display}; use std::str::FromStr; #[derive(Debug, Deserialize, Clone, Copy)] pub(crate) enum CommandName { Fetch, Install, Use, Config, Current, Deactivate, Shim, Help, Version, } impl Display for CommandName { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!( fmt, "{}", match *self { CommandName::Fetch => "fetch", CommandName::Install => "install", CommandName::Use => "use", CommandName::Config => "config", CommandName::Deactivate => "deactivate", CommandName::Current => "current", CommandName::Shim => "shim", CommandName::Help => "help", CommandName::Version => "version", } ) } } impl FromStr for CommandName { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "fetch" => CommandName::Fetch, "install" => CommandName::Install, "use" => CommandName::Use, "config" => CommandName::Config, "current" => CommandName::Current, "deactivate" => CommandName::Deactivate, "shim" => CommandName::Shim, "help" => CommandName::Help, "version" => CommandName::Version, _ => { throw!(()); } }) } } pub(crate) trait Command: Sized { type Args: DeserializeOwned; const USAGE: &'static str; fn help() -> Self; fn parse(notion: Notion, args: Self::Args) -> Fallible<Self>; fn run(self, session: &mut Session) -> Fallible<()>; fn go(notion: Notion, session: &mut Session) -> Fallible<()> { let argv = notion.full_argv(); let args = Docopt::new(Self::USAGE).and_then(|d| d.argv(argv).deserialize()); match args { Ok(args) => Self::parse(notion, args)?.run(session), Err(err) => { if err.is_help() { Self::help().run(session) }
}
else { throw!(err.with_context(CliParseError::from_docopt)); } } } }
function_block-function_prefix_line
[]
Rust
token-lending/program/tests/borrow_obligation_liquidity.rs
panoptesDev/panoptis-program-library
fe410cc1081742ebdf09f22ad21eb8cc511f9918
#![cfg(feature = "test-bpf")] mod helpers; use helpers::*; use solana_program_test::*; use solana_sdk::{ instruction::InstructionError, pubkey::Pubkey, signature::{Keypair, Signer}, transaction::{Transaction, TransactionError}, }; use spl_token_lending::{ error::LendingError, instruction::{borrow_obligation_liquidity, refresh_obligation}, math::Decimal, processor::process_instruction, state::{FeeCalculation, INITIAL_COLLATERAL_RATIO}, }; use std::u64; #[tokio::test] async fn test_borrow_usdc_fixed_amount() { let mut test = ProgramTest::new( "spl_token_lending", spl_token_lending::id(), processor!(process_instruction), ); test.set_bpf_compute_max_units(60_000); const USDC_TOTAL_BORROW_FRACTIONAL: u64 = 1_000 * FRACTIONAL_TO_USDC; const FEE_AMOUNT: u64 = 100; const HOST_FEE_AMOUNT: u64 = 20; const PANO_DEPOSIT_AMOUNT_LAMPORTS: u64 = 100 * LAMPORTS_TO_PANO * INITIAL_COLLATERAL_RATIO; const USDC_BORROW_AMOUNT_FRACTIONAL: u64 = USDC_TOTAL_BORROW_FRACTIONAL - FEE_AMOUNT; const PANO_RESERVE_COLLATERAL_LAMPORTS: u64 = 2 * PANO_DEPOSIT_AMOUNT_LAMPORTS; const USDC_RESERVE_LIQUIDITY_FRACTIONAL: u64 = 2 * USDC_TOTAL_BORROW_FRACTIONAL; let user_accounts_owner = Keypair::new(); let lending_market = add_lending_market(&mut test); let mut reserve_config = TEST_RESERVE_CONFIG; reserve_config.loan_to_value_ratio = 50; let sol_oracle = add_sol_oracle(&mut test); let sol_test_reserve = add_reserve( &mut test, &lending_market, &sol_oracle, &user_accounts_owner, AddReserveArgs { collateral_amount: PANO_RESERVE_COLLATERAL_LAMPORTS, liquidity_mint_pubkey: spl_token::native_mint::id(), liquidity_mint_decimals: 9, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let usdc_mint = add_usdc_mint(&mut test); let usdc_oracle = add_usdc_oracle(&mut test); let usdc_test_reserve = add_reserve( &mut test, &lending_market, &usdc_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: USDC_RESERVE_LIQUIDITY_FRACTIONAL, liquidity_mint_pubkey: usdc_mint.pubkey, liquidity_mint_decimals: usdc_mint.decimals, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let test_obligation = add_obligation( &mut test, &lending_market, &user_accounts_owner, AddObligationArgs { deposits: &[(&sol_test_reserve, PANO_DEPOSIT_AMOUNT_LAMPORTS)], ..AddObligationArgs::default() }, ); let (mut banks_client, payer, recent_blockhash) = test.start().await; let initial_liquidity_supply = get_token_balance(&mut banks_client, usdc_test_reserve.liquidity_supply_pubkey).await; let mut transaction = Transaction::new_with_payer( &[ refresh_obligation( spl_token_lending::id(), test_obligation.pubkey, vec![sol_test_reserve.pubkey], ), borrow_obligation_liquidity( spl_token_lending::id(), USDC_BORROW_AMOUNT_FRACTIONAL, usdc_test_reserve.liquidity_supply_pubkey, usdc_test_reserve.user_liquidity_pubkey, usdc_test_reserve.pubkey, usdc_test_reserve.liquidity_fee_receiver_pubkey, test_obligation.pubkey, lending_market.pubkey, test_obligation.owner, Some(usdc_test_reserve.liquidity_host_pubkey), ), ], Some(&payer.pubkey()), ); transaction.sign(&[&payer, &user_accounts_owner], recent_blockhash); assert!(banks_client.process_transaction(transaction).await.is_ok()); let usdc_reserve = usdc_test_reserve.get_state(&mut banks_client).await; let obligation = test_obligation.get_state(&mut banks_client).await; let (total_fee, host_fee) = usdc_reserve .config .fees .calculate_borrow_fees( USDC_BORROW_AMOUNT_FRACTIONAL.into(), FeeCalculation::Exclusive, ) .unwrap(); assert_eq!(total_fee, FEE_AMOUNT); assert_eq!(host_fee, HOST_FEE_AMOUNT); let borrow_amount = get_token_balance(&mut banks_client, usdc_test_reserve.user_liquidity_pubkey).await; assert_eq!(borrow_amount, USDC_BORROW_AMOUNT_FRACTIONAL); let liquidity = &obligation.borrows[0]; assert_eq!( liquidity.borrowed_amount_wads, Decimal::from(USDC_TOTAL_BORROW_FRACTIONAL) ); assert_eq!( usdc_reserve.liquidity.borrowed_amount_wads, liquidity.borrowed_amount_wads ); let liquidity_supply = get_token_balance(&mut banks_client, usdc_test_reserve.liquidity_supply_pubkey).await; assert_eq!( liquidity_supply, initial_liquidity_supply - USDC_TOTAL_BORROW_FRACTIONAL ); let fee_balance = get_token_balance( &mut banks_client, usdc_test_reserve.liquidity_fee_receiver_pubkey, ) .await; assert_eq!(fee_balance, FEE_AMOUNT - HOST_FEE_AMOUNT); let host_fee_balance = get_token_balance(&mut banks_client, usdc_test_reserve.liquidity_host_pubkey).await; assert_eq!(host_fee_balance, HOST_FEE_AMOUNT); } #[tokio::test] async fn test_borrow_sol_max_amount() { let mut test = ProgramTest::new( "spl_token_lending", spl_token_lending::id(), processor!(process_instruction), ); test.set_bpf_compute_max_units(60_000); const FEE_AMOUNT: u64 = 5000; const HOST_FEE_AMOUNT: u64 = 1000; const USDC_DEPOSIT_AMOUNT_FRACTIONAL: u64 = 2_000 * FRACTIONAL_TO_USDC * INITIAL_COLLATERAL_RATIO; const PANO_BORROW_AMOUNT_LAMPORTS: u64 = 50 * LAMPORTS_TO_PANO; const USDC_RESERVE_COLLATERAL_FRACTIONAL: u64 = 2 * USDC_DEPOSIT_AMOUNT_FRACTIONAL; const PANO_RESERVE_LIQUIDITY_LAMPORTS: u64 = 2 * PANO_BORROW_AMOUNT_LAMPORTS; let user_accounts_owner = Keypair::new(); let lending_market = add_lending_market(&mut test); let mut reserve_config = TEST_RESERVE_CONFIG; reserve_config.loan_to_value_ratio = 50; let usdc_mint = add_usdc_mint(&mut test); let usdc_oracle = add_usdc_oracle(&mut test); let usdc_test_reserve = add_reserve( &mut test, &lending_market, &usdc_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: USDC_RESERVE_COLLATERAL_FRACTIONAL, liquidity_mint_pubkey: usdc_mint.pubkey, liquidity_mint_decimals: usdc_mint.decimals, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let sol_oracle = add_sol_oracle(&mut test); let sol_test_reserve = add_reserve( &mut test, &lending_market, &sol_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: PANO_RESERVE_LIQUIDITY_LAMPORTS, liquidity_mint_pubkey: spl_token::native_mint::id(), liquidity_mint_decimals: 9, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let test_obligation = add_obligation( &mut test, &lending_market, &user_accounts_owner, AddObligationArgs { deposits: &[(&usdc_test_reserve, USDC_DEPOSIT_AMOUNT_FRACTIONAL)], ..AddObligationArgs::default() }, ); let (mut banks_client, payer, recent_blockhash) = test.start().await; let initial_liquidity_supply = get_token_balance(&mut banks_client, sol_test_reserve.liquidity_supply_pubkey).await; let mut transaction = Transaction::new_with_payer( &[ refresh_obligation( spl_token_lending::id(), test_obligation.pubkey, vec![usdc_test_reserve.pubkey], ), borrow_obligation_liquidity( spl_token_lending::id(), u64::MAX, sol_test_reserve.liquidity_supply_pubkey, sol_test_reserve.user_liquidity_pubkey, sol_test_reserve.pubkey, sol_test_reserve.liquidity_fee_receiver_pubkey, test_obligation.pubkey, lending_market.pubkey, test_obligation.owner, Some(sol_test_reserve.liquidity_host_pubkey), ), ], Some(&payer.pubkey()), ); transaction.sign(&[&payer, &user_accounts_owner], recent_blockhash); assert!(banks_client.process_transaction(transaction).await.is_ok()); let sol_reserve = sol_test_reserve.get_state(&mut banks_client).await; let obligation = test_obligation.get_state(&mut banks_client).await; let (total_fee, host_fee) = sol_reserve .config .fees .calculate_borrow_fees(PANO_BORROW_AMOUNT_LAMPORTS.into(), FeeCalculation::Inclusive) .unwrap(); assert_eq!(total_fee, FEE_AMOUNT); assert_eq!(host_fee, HOST_FEE_AMOUNT); let borrow_amount = get_token_balance(&mut banks_client, sol_test_reserve.user_liquidity_pubkey).await; assert_eq!(borrow_amount, PANO_BORROW_AMOUNT_LAMPORTS - FEE_AMOUNT); let liquidity = &obligation.borrows[0]; assert_eq!( liquidity.borrowed_amount_wads, Decimal::from(PANO_BORROW_AMOUNT_LAMPORTS) ); let liquidity_supply = get_token_balance(&mut banks_client, sol_test_reserve.liquidity_supply_pubkey).await; assert_eq!( liquidity_supply, initial_liquidity_supply - PANO_BORROW_AMOUNT_LAMPORTS ); let fee_balance = get_token_balance( &mut banks_client, sol_test_reserve.liquidity_fee_receiver_pubkey, ) .await; assert_eq!(fee_balance, FEE_AMOUNT - HOST_FEE_AMOUNT); let host_fee_balance = get_token_balance(&mut banks_client, sol_test_reserve.liquidity_host_pubkey).await; assert_eq!(host_fee_balance, HOST_FEE_AMOUNT); } #[tokio::test] async fn test_borrow_too_large() { let mut test = ProgramTest::new( "spl_token_lending", spl_token_lending::id(), processor!(process_instruction), ); const PANO_DEPOSIT_AMOUNT_LAMPORTS: u64 = 100 * LAMPORTS_TO_PANO * INITIAL_COLLATERAL_RATIO; const USDC_BORROW_AMOUNT_FRACTIONAL: u64 = 1_000 * FRACTIONAL_TO_USDC + 1; const PANO_RESERVE_COLLATERAL_LAMPORTS: u64 = 2 * PANO_DEPOSIT_AMOUNT_LAMPORTS; const USDC_RESERVE_LIQUIDITY_FRACTIONAL: u64 = 2 * USDC_BORROW_AMOUNT_FRACTIONAL; let user_accounts_owner = Keypair::new(); let lending_market = add_lending_market(&mut test); let mut reserve_config = TEST_RESERVE_CONFIG; reserve_config.loan_to_value_ratio = 50; let sol_oracle = add_sol_oracle(&mut test); let sol_test_reserve = add_reserve( &mut test, &lending_market, &sol_oracle, &user_accounts_owner, AddReserveArgs { collateral_amount: PANO_RESERVE_COLLATERAL_LAMPORTS, liquidity_mint_pubkey: spl_token::native_mint::id(), liquidity_mint_decimals: 9, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let usdc_mint = add_usdc_mint(&mut test); let usdc_oracle = add_usdc_oracle(&mut test); let usdc_test_reserve = add_reserve( &mut test, &lending_market, &usdc_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: USDC_RESERVE_LIQUIDITY_FRACTIONAL, liquidity_mint_pubkey: usdc_mint.pubkey, liquidity_mint_decimals: usdc_mint.decimals, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let test_obligation = add_obligation( &mut test, &lending_market, &user_accounts_owner, AddObligationArgs { deposits: &[(&sol_test_reserve, PANO_DEPOSIT_AMOUNT_LAMPORTS)], ..AddObligationArgs::default() }, ); let (mut banks_client, payer, recent_blockhash) = test.start().await; let mut transaction = Transaction::new_with_payer( &[ refresh_obligation( spl_token_lending::id(), test_obligation.pubkey, vec![sol_test_reserve.pubkey], ), borrow_obligation_liquidity( spl_token_lending::id(), USDC_BORROW_AMOUNT_FRACTIONAL, usdc_test_reserve.liquidity_supply_pubkey, usdc_test_reserve.user_liquidity_pubkey, usdc_test_reserve.pubkey, usdc_test_reserve.liquidity_fee_receiver_pubkey, test_obligation.pubkey, lending_market.pubkey, test_obligation.owner, Some(usdc_test_reserve.liquidity_host_pubkey), ), ], Some(&payer.pubkey()), ); transaction.sign(&[&payer, &user_accounts_owner], recent_blockhash); assert_eq!( banks_client .process_transaction(transaction) .await .unwrap_err() .unwrap(), TransactionError::InstructionError( 1, InstructionError::Custom(LendingError::BorrowTooLarge as u32) ) ); }
#![cfg(feature = "test-bpf")] mod helpers; use helpers::*; use solana_program_test::*; use solana_sdk::{ instruction::InstructionError, pubkey::Pubkey, signature::{Keypair, Signer}, transaction::{Transaction, TransactionError}, }; use spl_token_lending::{ error::LendingError, instruction::{borrow_obligation_liquidity, refresh_obligation}, math::Decimal, processor::process_instruction, state::{FeeCalculation, INITIAL_COLLATERAL_RATIO}, }; use std::u64; #[tokio::test] async fn test_borrow_usdc_fixed_amount() { let mut test = ProgramTest::new( "spl_token_lending", spl_token_lending::id(), processor!(process_instruction), ); test.set_bpf_compute_max_units(60_000); const USDC_TOTAL_BORROW_FRACTIONAL: u64 = 1_000 * FRACTIONAL_TO_USDC; const FEE_AMOUNT: u64 = 100; const HOST_FEE_AMOUNT: u64 = 20; const PANO_DEPOSIT_AMOUNT_LAMPORTS: u64 = 100 * LAMPORTS_TO_PANO * INITIAL_COLLATERAL_RATIO; const USDC_BORROW_AMOUNT_FRACTIONAL: u64 = USDC_TOTAL_BORROW_FRACTIONAL - FEE_AMOUNT; const PANO_RESERVE_COLLATERAL_LAMPORTS: u64 = 2 * PANO_DEPOSIT_AMOUNT_LAMPORTS; const USDC_RESERVE_LIQUIDITY_FRACTIONAL: u64 = 2 * USDC_TOTAL_BORROW_FRACTIONAL; let user_accounts_owner = Keypair::new(); let lending_market = add_lending_market(&mut test); let mut reserve_config = TEST_RESERVE_CONFIG; reserve_config.loan_to_value_ratio = 50; let sol_oracle = add_sol_oracle(&mut test); let sol_test_reserve = add_reserve( &mut test, &lending_market, &sol_oracle, &user_accounts_owner, AddReserveArgs { collateral_amount: PANO_RESERVE_COLLATERAL_LAMPORTS, liquidity_mint_pubkey: spl_token::native_mint::id(), liquidity_mint_decimals: 9, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let usdc_mint = add_usdc_mint(&mut test); let usdc_oracle = add_usdc_oracle(&mut test); let usdc_test_reserve = add_reserve( &mut test, &lending_market, &usdc_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: USDC_RESERVE_LIQUIDITY_FRACTIONAL, liquidity_mint_pubkey: usdc_mint.pubkey, liquidity_mint_decimals: usdc_mint.decimals, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let test_obligation = add_obligation( &mut test, &lending_market, &user_accounts_owner, AddObligationArgs { deposits: &[(&sol_test_reserve, PANO_DEPOSIT_AMOUNT_LAMPORTS)], ..AddObligationArgs::default() }, ); let (mut banks_client, payer, recent_blockhash) = test.start().await; let initial_liquidity_supply = get_token_balance(&mut banks_client, usdc_test_reserve.liquidity_supply_pubkey).await; let mut transaction = Transaction::new_with_payer( &[ refresh_obligation( spl_token_lending::id(), test_obligation.pubkey, vec![sol_test_reserve.pubkey], ), borrow_obligation_liquidity( spl_token_lending::id(), USDC_BORROW_AMOUNT_FRACTIONAL, usdc_test_reserve.liquidity_supply_pubkey, usdc_test_reserve.user_liquidity_pubkey, usdc_test_reserve.pubkey, usdc_test_reserve.liquidity_fee_receiver_pubkey, test_obligation.pubkey, lending_market.pubkey, test_obligation.owner, Some(usdc_test_reserve.liquidity_host_pubkey), ), ], Some(&payer.pubkey()), ); transaction.sign(&[&payer, &user_accounts_owner], recent_blockhash); assert!(banks_client.process_transaction(transaction).await.is_ok()); let usdc_reserve = usdc_test_reserve.get_state(&mut banks_client).await; let obligation = test_obligation.get_state(&mut banks_client).await; let (total_fee, host_fee) = usdc_reserve .config .fees .calculate_borrow_fees( USDC_BORROW_AMOUNT_FRACTIONAL.into(), FeeCalculation::Exclusive, ) .unwrap(); assert_eq!(total_fee, FEE_AMOUNT); assert_eq!(host_fee, HOST_FEE_AMOUNT); let borrow_amount = get_token_balance(&mut banks_client, usdc_test_reserve.user_liquidity_pubkey).await; assert_eq!(borrow_amount, USDC_BORROW_AMOUNT_FRACTIONAL); let liquidity = &obligation.borrows[0]; assert_eq!( liquidity.borrowed_amount_wads, Decimal::from(USDC_TOTAL_BORROW_FRACTIONAL) ); assert_eq!( usdc_reserve.liquidity.borrowed_amount_wads, liquidity.borrowed_amount_wads ); let liquidity_supply = get_token_balance(&mut banks_client, usdc_test_reserve.liquidity_supply_pubkey).await; assert_eq!( liquidity_supply, initial_liquidity_supply - USDC_TOTAL_BORROW_FRACTIONAL ); let fee_balance = get_token_balance( &mut banks_client, usdc_test_reserve.liquidity_fee_receiver_pubkey, ) .await; assert_eq!(fee_balance, FEE_AMOUNT - HOST_FEE_AMOUNT); let host_fee_balance = get_token_balance(&mut banks_client, usdc_test_reserve.liquidity_host_pubkey).await; assert_eq!(host_fee_balance, HOST_FEE_AMOUNT); } #[tokio::test] async fn test_borrow_sol_max_amount() {
test.set_bpf_compute_max_units(60_000); const FEE_AMOUNT: u64 = 5000; const HOST_FEE_AMOUNT: u64 = 1000; const USDC_DEPOSIT_AMOUNT_FRACTIONAL: u64 = 2_000 * FRACTIONAL_TO_USDC * INITIAL_COLLATERAL_RATIO; const PANO_BORROW_AMOUNT_LAMPORTS: u64 = 50 * LAMPORTS_TO_PANO; const USDC_RESERVE_COLLATERAL_FRACTIONAL: u64 = 2 * USDC_DEPOSIT_AMOUNT_FRACTIONAL; const PANO_RESERVE_LIQUIDITY_LAMPORTS: u64 = 2 * PANO_BORROW_AMOUNT_LAMPORTS; let user_accounts_owner = Keypair::new(); let lending_market = add_lending_market(&mut test); let mut reserve_config = TEST_RESERVE_CONFIG; reserve_config.loan_to_value_ratio = 50; let usdc_mint = add_usdc_mint(&mut test); let usdc_oracle = add_usdc_oracle(&mut test); let usdc_test_reserve = add_reserve( &mut test, &lending_market, &usdc_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: USDC_RESERVE_COLLATERAL_FRACTIONAL, liquidity_mint_pubkey: usdc_mint.pubkey, liquidity_mint_decimals: usdc_mint.decimals, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let sol_oracle = add_sol_oracle(&mut test); let sol_test_reserve = add_reserve( &mut test, &lending_market, &sol_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: PANO_RESERVE_LIQUIDITY_LAMPORTS, liquidity_mint_pubkey: spl_token::native_mint::id(), liquidity_mint_decimals: 9, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let test_obligation = add_obligation( &mut test, &lending_market, &user_accounts_owner, AddObligationArgs { deposits: &[(&usdc_test_reserve, USDC_DEPOSIT_AMOUNT_FRACTIONAL)], ..AddObligationArgs::default() }, ); let (mut banks_client, payer, recent_blockhash) = test.start().await; let initial_liquidity_supply = get_token_balance(&mut banks_client, sol_test_reserve.liquidity_supply_pubkey).await; let mut transaction = Transaction::new_with_payer( &[ refresh_obligation( spl_token_lending::id(), test_obligation.pubkey, vec![usdc_test_reserve.pubkey], ), borrow_obligation_liquidity( spl_token_lending::id(), u64::MAX, sol_test_reserve.liquidity_supply_pubkey, sol_test_reserve.user_liquidity_pubkey, sol_test_reserve.pubkey, sol_test_reserve.liquidity_fee_receiver_pubkey, test_obligation.pubkey, lending_market.pubkey, test_obligation.owner, Some(sol_test_reserve.liquidity_host_pubkey), ), ], Some(&payer.pubkey()), ); transaction.sign(&[&payer, &user_accounts_owner], recent_blockhash); assert!(banks_client.process_transaction(transaction).await.is_ok()); let sol_reserve = sol_test_reserve.get_state(&mut banks_client).await; let obligation = test_obligation.get_state(&mut banks_client).await; let (total_fee, host_fee) = sol_reserve .config .fees .calculate_borrow_fees(PANO_BORROW_AMOUNT_LAMPORTS.into(), FeeCalculation::Inclusive) .unwrap(); assert_eq!(total_fee, FEE_AMOUNT); assert_eq!(host_fee, HOST_FEE_AMOUNT); let borrow_amount = get_token_balance(&mut banks_client, sol_test_reserve.user_liquidity_pubkey).await; assert_eq!(borrow_amount, PANO_BORROW_AMOUNT_LAMPORTS - FEE_AMOUNT); let liquidity = &obligation.borrows[0]; assert_eq!( liquidity.borrowed_amount_wads, Decimal::from(PANO_BORROW_AMOUNT_LAMPORTS) ); let liquidity_supply = get_token_balance(&mut banks_client, sol_test_reserve.liquidity_supply_pubkey).await; assert_eq!( liquidity_supply, initial_liquidity_supply - PANO_BORROW_AMOUNT_LAMPORTS ); let fee_balance = get_token_balance( &mut banks_client, sol_test_reserve.liquidity_fee_receiver_pubkey, ) .await; assert_eq!(fee_balance, FEE_AMOUNT - HOST_FEE_AMOUNT); let host_fee_balance = get_token_balance(&mut banks_client, sol_test_reserve.liquidity_host_pubkey).await; assert_eq!(host_fee_balance, HOST_FEE_AMOUNT); } #[tokio::test] async fn test_borrow_too_large() { let mut test = ProgramTest::new( "spl_token_lending", spl_token_lending::id(), processor!(process_instruction), ); const PANO_DEPOSIT_AMOUNT_LAMPORTS: u64 = 100 * LAMPORTS_TO_PANO * INITIAL_COLLATERAL_RATIO; const USDC_BORROW_AMOUNT_FRACTIONAL: u64 = 1_000 * FRACTIONAL_TO_USDC + 1; const PANO_RESERVE_COLLATERAL_LAMPORTS: u64 = 2 * PANO_DEPOSIT_AMOUNT_LAMPORTS; const USDC_RESERVE_LIQUIDITY_FRACTIONAL: u64 = 2 * USDC_BORROW_AMOUNT_FRACTIONAL; let user_accounts_owner = Keypair::new(); let lending_market = add_lending_market(&mut test); let mut reserve_config = TEST_RESERVE_CONFIG; reserve_config.loan_to_value_ratio = 50; let sol_oracle = add_sol_oracle(&mut test); let sol_test_reserve = add_reserve( &mut test, &lending_market, &sol_oracle, &user_accounts_owner, AddReserveArgs { collateral_amount: PANO_RESERVE_COLLATERAL_LAMPORTS, liquidity_mint_pubkey: spl_token::native_mint::id(), liquidity_mint_decimals: 9, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let usdc_mint = add_usdc_mint(&mut test); let usdc_oracle = add_usdc_oracle(&mut test); let usdc_test_reserve = add_reserve( &mut test, &lending_market, &usdc_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: USDC_RESERVE_LIQUIDITY_FRACTIONAL, liquidity_mint_pubkey: usdc_mint.pubkey, liquidity_mint_decimals: usdc_mint.decimals, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let test_obligation = add_obligation( &mut test, &lending_market, &user_accounts_owner, AddObligationArgs { deposits: &[(&sol_test_reserve, PANO_DEPOSIT_AMOUNT_LAMPORTS)], ..AddObligationArgs::default() }, ); let (mut banks_client, payer, recent_blockhash) = test.start().await; let mut transaction = Transaction::new_with_payer( &[ refresh_obligation( spl_token_lending::id(), test_obligation.pubkey, vec![sol_test_reserve.pubkey], ), borrow_obligation_liquidity( spl_token_lending::id(), USDC_BORROW_AMOUNT_FRACTIONAL, usdc_test_reserve.liquidity_supply_pubkey, usdc_test_reserve.user_liquidity_pubkey, usdc_test_reserve.pubkey, usdc_test_reserve.liquidity_fee_receiver_pubkey, test_obligation.pubkey, lending_market.pubkey, test_obligation.owner, Some(usdc_test_reserve.liquidity_host_pubkey), ), ], Some(&payer.pubkey()), ); transaction.sign(&[&payer, &user_accounts_owner], recent_blockhash); assert_eq!( banks_client .process_transaction(transaction) .await .unwrap_err() .unwrap(), TransactionError::InstructionError( 1, InstructionError::Custom(LendingError::BorrowTooLarge as u32) ) ); }
let mut test = ProgramTest::new( "spl_token_lending", spl_token_lending::id(), processor!(process_instruction), );
assignment_statement
[ { "content": "fn check_fee_payer_balance(config: &Config, required_balance: u64) -> Result<(), Error> {\n\n let balance = config.rpc_client.get_balance(&config.fee_payer)?;\n\n if balance < required_balance {\n\n Err(format!(\n\n \"Fee payer, {}, has insufficient balance: {} required, {}...
Rust
libs/port_io/src/lib.rs
jacob-earle/Theseus
d53038328d1a39c69ffff6e32226394e8c957e33
#![feature(llvm_asm, const_fn_trait_bound)] #![no_std] use core::marker::PhantomData; #[cfg(any(target_arch="x86", target_arch="x86_64"))] mod x86; #[cfg(any(target_arch="x86", target_arch="x86_64"))] pub use x86::{inb, outb, inw, outw, inl, outl}; pub trait PortIn { unsafe fn port_in(port: u16) -> Self; } pub trait PortOut { unsafe fn port_out(port: u16, value: Self); } impl PortOut for u8 { unsafe fn port_out(port: u16, value: Self) { outb(value, port); } } impl PortOut for u16 { unsafe fn port_out(port: u16, value: Self) { outw(value, port); } } impl PortOut for u32 { unsafe fn port_out(port: u16, value: Self) { outl(value, port); } } impl PortIn for u8 { unsafe fn port_in(port: u16) -> Self { inb(port) } } impl PortIn for u16 { unsafe fn port_in(port: u16) -> Self { inw(port) } } impl PortIn for u32 { unsafe fn port_in(port: u16) -> Self { inl(port) } } #[derive(Debug)] pub struct Port<T: PortIn + PortOut> { port: u16, _phantom: PhantomData<T>, } impl<T: PortIn + PortOut> Port<T> { pub const fn new(port: u16) -> Port<T> { Port { port: port, _phantom: PhantomData } } pub const fn port_address(&self) -> u16 { self.port } pub fn read(&self) -> T { unsafe { T::port_in(self.port) } } pub unsafe fn write(&self, value: T) { T::port_out(self.port, value); } } #[derive(Debug)] pub struct PortReadOnly<T: PortIn> { port: u16, _phantom: PhantomData<T>, } impl<T: PortIn> PortReadOnly<T> { pub const fn new(port: u16) -> PortReadOnly<T> { PortReadOnly { port: port, _phantom: PhantomData } } pub const fn port_address(&self) -> u16 { self.port } pub fn read(&self) -> T { unsafe { T::port_in(self.port) } } } #[derive(Debug)] pub struct PortWriteOnly<T: PortOut> { port: u16, _phantom: PhantomData<T>, } impl<T: PortOut> PortWriteOnly<T> { pub const fn new(port: u16) -> PortWriteOnly<T> { PortWriteOnly { port: port, _phantom: PhantomData } } pub const fn port_address(&self) -> u16 { self.port } pub unsafe fn write(&self, value: T) { T::port_out(self.port, value); } }
#![feature(llvm_asm, const_fn_trait_bound)] #![no_std] use core::marker::PhantomData; #[cfg(any(target_arch="x86", target_arch="x86_64"))] mod x86; #[cfg(any(target_arch="x86", target_arch="x86_64"))] pub use x86::{inb, outb, inw, outw, inl, outl}; pub trait PortIn { unsafe fn port_in(port: u16) -> Self; } pub trait PortOut { unsafe fn port_out(port: u16, value: Self); } impl PortOut for u8 { unsafe fn port_out(port: u16, value: Self) { outb(value, port); } } impl PortOut for u16 { unsafe fn port_out(port: u16, value: Self) { outw(value, port); } } impl PortOut for u32 { unsafe fn port_out(port: u16, value: Self) { outl(value, port); } } impl PortIn for u8 { unsafe fn port_in(port: u16) -> Self { inb(port) } } impl PortIn for u16 { unsafe fn port_in(port: u16) -> Self { inw(port) } } impl PortIn for u32 { unsafe fn port_in(port: u16) -> Self { inl(port) } } #[derive(Debug)] pub struct Port<T: PortIn + PortOut> { port: u16, _phantom: PhantomData<T>, } impl<T: PortIn + PortOut> Port<T> { pub const fn new(port: u16) -> Port<T> { Port { port: port, _phantom: PhantomData } } pub const fn port_address(&self) -> u16 { self.port } pub fn read(&self) -> T { unsafe { T::port_in(self.port) } } pub unsafe fn write(&self, value: T) { T::port_out(self.port, value); } } #[derive(Debug)] pub struct PortReadOnly<T: PortIn> { port: u16, _phantom: PhantomData<T>, } impl<T: PortIn> PortReadOnly<T> { pub const fn new(port: u16) -> PortReadOnly<T> { PortReadOnly { port: port, _phantom: PhantomData } } pub const fn port_address(&self) -> u16 { self.port } pub fn read(&self) -> T { unsafe { T::
pub unsafe fn write(&self, value: T) { T::port_out(self.port, value); } }
port_in(self.port) } } } #[derive(Debug)] pub struct PortWriteOnly<T: PortOut> { port: u16, _phantom: PhantomData<T>, } impl<T: PortOut> PortWriteOnly<T> { pub const fn new(port: u16) -> PortWriteOnly<T> { PortWriteOnly { port: port, _phantom: PhantomData } } pub const fn port_address(&self) -> u16 { self.port }
random
[ { "content": "/// write data to the second ps2 data port and return the response\n\npub fn data_to_port2(value: u8) -> u8 {\n\n ps2_write_command(0xD4);\n\n data_to_port1(value)\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 0, "score": 298433.0900723853 }, { "content": "//...
Rust
src/app.rs
iamcodemaker/euca
00387b2e368231a3e0e25ebe0e63b951231cf61f
pub mod detach; pub mod model; pub mod dispatch; pub mod side_effect; pub mod application; pub use crate::app::detach::Detach; pub use crate::app::model::{Update, Render}; pub use crate::app::dispatch::Dispatcher; pub use crate::app::side_effect::{SideEffect, Processor, Commands}; pub use crate::app::application::{Application, ScheduledRender}; use web_sys; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use std::rc::Rc; use std::cell::RefCell; use std::fmt; use std::hash::Hash; use crate::diff; use crate::vdom::DomIter; use crate::vdom::Storage; use crate::vdom::WebItem; use crate::route::Route; pub struct AppBuilder<Message, Command, Processor, Router> where Command: SideEffect<Message>, Processor: side_effect::Processor<Message, Command>, Router: Route<Message>, { router: Option<Rc<Router>>, processor: Processor, clear_parent: bool, message: std::marker::PhantomData<Message>, command: std::marker::PhantomData<Command>, } impl<Message, Command> Default for AppBuilder< Message, Command, side_effect::DefaultProcessor<Message, Command>, (), > where Command: SideEffect<Message>, { fn default() -> Self { AppBuilder { router: None, processor: side_effect::DefaultProcessor::default(), clear_parent: false, message: std::marker::PhantomData, command: std::marker::PhantomData, } } } impl<Message, Command, Processor, Router> AppBuilder<Message, Command, Processor, Router> where Command: SideEffect<Message> + 'static, Processor: side_effect::Processor<Message, Command> + 'static, Router: Route<Message> + 'static, { #[must_use] pub fn router<R: Route<Message>>(self, router: R) -> AppBuilder<Message, Command, Processor, R> { let AppBuilder { message, command, processor, clear_parent, router: _router, } = self; AppBuilder { message: message, command: command, processor, clear_parent: clear_parent, router: Some(Rc::new(router)), } } #[must_use] pub(crate) fn processor<P: side_effect::Processor<Message, Command>>(self, processor: P) -> AppBuilder<Message, Command, P, Router> { let AppBuilder { message, command, router, clear_parent, processor: _processor, } = self; AppBuilder { message: message, command: command, processor: processor, router: router, clear_parent: clear_parent, } } #[must_use] pub fn clear(mut self) -> Self { self.clear_parent = true; self } #[must_use] pub(crate) fn create<Model, DomTree, Key>(self, mut model: Model) -> (Rc<RefCell<Box<dyn Application<Message, Command>>>>, Vec<web_sys::Node>) where Model: Update<Message, Command> + Render<DomTree> + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Key: Eq + Hash + 'static, { let AppBuilder { router, processor, .. } = self; let mut commands = Commands::default(); if let Some(ref router) = router { let url = web_sys::window() .expect("window") .document() .expect("document") .url() .expect("url"); if let Some(msg) = router.route(&url) { model.update(msg, &mut commands); } } let (app_rc, nodes) = App::create(model, processor); let dispatcher = Dispatcher::from(&app_rc); if let Some(ref router) = router { let window = web_sys::window() .expect("couldn't get window handle"); let document = window.document() .expect("couldn't get document handle"); for event in ["popstate", "hashchange"].iter() { let dispatcher = dispatcher.clone(); let document = document.clone(); let router = router.clone(); let closure = Closure::wrap( Box::new(move |_event| { let url = document.url() .expect_throw("couldn't get document url"); if let Some(msg) = router.route(&url) { dispatcher.dispatch(msg); } }) as Box<dyn FnMut(web_sys::Event)> ); window .add_event_listener_with_callback(event, closure.as_ref().unchecked_ref()) .expect("failed to add event listener"); app_rc.borrow_mut().push_listener((event.to_string(), closure)); } for cmd in commands.immediate { app_rc.borrow().process(cmd, &dispatcher); } for cmd in commands.post_render { app_rc.borrow().process(cmd, &dispatcher); } } (app_rc, nodes) } pub fn attach<Model, DomTree, Key>(self, parent: web_sys::Element, model: Model) -> Rc<RefCell<Box<dyn Application<Message, Command>>>> where Model: Update<Message, Command> + Render<DomTree> + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Key: Eq + Hash + 'static, { if self.clear_parent { while let Some(child) = parent.first_child() { parent.remove_child(&child) .expect("failed to remove child of parent element"); } } let (app_rc, nodes) = self.create(model); for node in nodes.iter() { parent.append_child(node) .expect("failed to append child to parent element"); } app_rc } } impl<Model, DomTree, Processor, Message, Command, Key> Application<Message, Command> for App<Model, DomTree, Processor, Message, Command, Key> where Model: Update<Message, Command> + Render<DomTree> + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Processor: side_effect::Processor<Message, Command> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Key: Eq + Hash + 'static, { fn update(&mut self, msg: Message) -> Commands<Command> { let mut commands = Commands::default(); self.model.update(msg, &mut commands); commands } fn get_scheduled_render(&mut self) -> &mut Option<ScheduledRender<Command>> { &mut self.animation_frame_handle } fn set_scheduled_render(&mut self, handle: ScheduledRender<Command>) { self.animation_frame_handle = Some(handle) } fn render(&mut self, app_rc: &Dispatcher<Message, Command>) -> Vec<Command> { let parent = self.node() .expect("empty app?") .parent_element() .expect("app not attached to the dom"); let App { ref mut model, ref mut storage, ref dom, .. } = *self; let new_dom = model.render(); let old = dom.dom_iter(); let new = new_dom.dom_iter(); let patch_set = diff::diff(old, new, storage); self.storage = patch_set.apply(&parent, app_rc); self.dom = new_dom; let commands; if let Some((cmds, _, _)) = self.animation_frame_handle.take() { commands = cmds; } else { commands = vec![]; } commands } fn process(&self, cmd: Command, app: &Dispatcher<Message, Command>) { Processor::process(&self.processor, cmd, app); } fn push_listener(&mut self, listener: (String, Closure<dyn FnMut(web_sys::Event)>)) { self.listeners.push(listener); } fn detach(&mut self, app: &Dispatcher<Message, Command>) { use std::iter; let parent = self.node() .expect("empty app?") .parent_element() .expect("app not attached to the dom"); let App { ref mut storage, ref dom, ref mut listeners, .. } = *self; let window = web_sys::window() .expect("couldn't get window handle"); for (event, listener) in listeners.drain(..) { window .remove_event_listener_with_callback(&event, listener.as_ref().unchecked_ref()) .expect("failed to remove event listener"); } let o = dom.dom_iter(); let patch_set = diff::diff(o, iter::empty(), storage); self.storage = patch_set.apply(&parent, app); } fn node(&self) -> Option<web_sys::Node> { self.storage.first() .and_then(|item| -> Option<web_sys::Node> { match item { WebItem::Element(ref node) => Some(node.clone().into()), WebItem::Text(ref node) => Some(node.clone().into()), WebItem::Component(component) => component.node(), i => panic!("unknown item, expected something with a node in it: {:?}", i) } }) } fn nodes(&self) -> Vec<web_sys::Node> { let mut nodes = vec![]; let mut depth = 0; for item in &self.storage { match item { WebItem::Element(_) | WebItem::Text(_) | WebItem::Component(_) if depth > 0 => { depth += 1; } WebItem::Up => depth -= 1, WebItem::Closure(_) => {} WebItem::Element(ref node) => { nodes.push(node.clone().into()); depth += 1; } WebItem::Text(ref node) => { nodes.push(node.clone().into()); depth += 1; } WebItem::Component(component) => { nodes.extend(component.nodes()); depth += 1; } i => panic!("unexpected item, expected something with a node in it, got : {:?}", i) } } nodes } fn create(&mut self, app: &Dispatcher<Message, Command>) -> Vec<web_sys::Node> { use std::iter; let App { ref mut storage, ref dom, .. } = *self; let n = dom.dom_iter(); let patch_set = diff::diff(iter::empty(), n, storage); let (storage, pending) = patch_set.prepare(app); self.storage = storage; pending } } struct App<Model, DomTree, Processor, Message, Command, Key> where Command: SideEffect<Message>, Processor: side_effect::Processor<Message, Command>, { dom: DomTree, model: Model, storage: Storage<Message>, listeners: Vec<(String, Closure<dyn FnMut(web_sys::Event)>)>, animation_frame_handle: Option<ScheduledRender<Command>>, processor: Processor, command: std::marker::PhantomData<Command>, key: std::marker::PhantomData<Key>, } impl<Model, DomTree, Processor, Message, Command, Key> App<Model, DomTree, Processor, Message, Command, Key> where Command: SideEffect<Message>, Processor: side_effect::Processor<Message, Command> + 'static, { fn create(model: Model, processor: Processor) -> (Rc<RefCell<Box<dyn Application<Message, Command>>>>, Vec<web_sys::Node>) where Model: Update<Message, Command> + Render<DomTree> + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Key: Eq + Hash + 'static, { let dom = model.render(); let app = App { dom: dom, model: model, storage: vec![], listeners: vec![], animation_frame_handle: None, processor: processor, command: std::marker::PhantomData, key: std::marker::PhantomData, }; let app_rc = Rc::new(RefCell::new(Box::new(app) as Box<dyn Application<Message, Command>>)); let nodes = Application::create(&mut **app_rc.borrow_mut(), &Dispatcher::from(&app_rc)); (app_rc, nodes) } }
pub mod detach; pub mod model; pub mod dispatch; pub mod side_effect; pub mod application; pub use crate::app::detach::Detach; pub use crate::app::model::{Update, Render}; pub use crate::app::dispatch::Dispatcher; pub use crate::app::side_effect::{SideEffect, Processor, Commands}; pub use crate::app::application::{Application, ScheduledRender}; use web_sys; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use std::rc::Rc; use std::cell::RefCell; use std::fmt; use std::hash::Hash; use crate::diff; use crate::vdom::DomIter; use crate::vdom::Storage; use crate::vdom::WebItem; use crate::route::Route; pub struct AppBuilder<Message, Command, Processor, Router> where Command: SideEffect<Message>, Processor: side_effect::Processor<Message, Command>, Router: Route<Message>, { router: Option<Rc<Router>>, processor: Processor, clear_parent: bool, message: std::marker::PhantomData<Message>, command: std::marker::PhantomData<Command>, } impl<Message, Command> Default for AppBuilder< Message, Command, side_effect::DefaultProcessor<Message, Command>, (), > where Command: SideEffect<Message>, { fn default() -> Self { AppBuilder { router: None, processor: side_effect::DefaultProcessor::default(), clear_parent: false, message: std::marker::PhantomData, command: std::marker::PhantomData, } } } impl<Message, Command, Processor, Router> AppBuilder<Message, Command, Processor, Router> where Command: SideEffect<Message> + 'static, Processor: side_effect::Processor<Message, Command> + 'static, Router: Route<Message> + 'static, { #[must_use] pub fn router<R: Route<Message>>(self, router: R) -> AppBuilder<Message, Command, Processor, R> { let AppBuilder { message, command, processor, clear_parent, router: _router, } = self; AppBuilder { message: message, command: command, processor, clear_parent: clear_parent, router: Some(Rc::new(router)), } } #[must_use] pub(crate) fn processor<P: side_effect::Processor<Message, Command>>(self, processor: P) -> AppBuilder<Message, Command, P, Router> { let AppBuilder { message, command, router, clear_parent, processor: _processor, } = self; AppBuilder { message: message, command: command, processor: processor, router: router, clear_parent: clear_parent, } } #[must_use] pub fn clear(mut self) -> Self { self.clear_parent = true; self } #[must_use] pub(crate) fn create<Model, DomTree, Key>(self, mut model: Model) -> (Rc<RefCell<Box<dyn Application<Message, Command>>>>, Vec<web_sys::Node>) where Model: Update<Message, Command> + Render<DomTree> + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Key: Eq + Hash + 'static, { let AppBuilder { router, processor, .. } = self; let mut commands = Commands::default(); if let Some(ref router) = router { let url = web_sys::window() .expect("window") .document() .expect("document") .url() .expect("url"); if let Some(msg) = router.route(&url) { model.update(msg, &mut commands); } } let (app_rc, nodes) = App::create(model, processor); let dispatcher = Dispatcher::from(&app_rc); if let Some(ref router) = router { let window = web_sys::window() .expect("couldn't get window handle"); let document = window.document() .expect("couldn't get document handle"); for event in ["popstate", "hashchange"].iter() { let dispatcher = dispatcher.clone(); let document = document.clone(); let router = router.clone();
window .add_event_listener_with_callback(event, closure.as_ref().unchecked_ref()) .expect("failed to add event listener"); app_rc.borrow_mut().push_listener((event.to_string(), closure)); } for cmd in commands.immediate { app_rc.borrow().process(cmd, &dispatcher); } for cmd in commands.post_render { app_rc.borrow().process(cmd, &dispatcher); } } (app_rc, nodes) } pub fn attach<Model, DomTree, Key>(self, parent: web_sys::Element, model: Model) -> Rc<RefCell<Box<dyn Application<Message, Command>>>> where Model: Update<Message, Command> + Render<DomTree> + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Key: Eq + Hash + 'static, { if self.clear_parent { while let Some(child) = parent.first_child() { parent.remove_child(&child) .expect("failed to remove child of parent element"); } } let (app_rc, nodes) = self.create(model); for node in nodes.iter() { parent.append_child(node) .expect("failed to append child to parent element"); } app_rc } } impl<Model, DomTree, Processor, Message, Command, Key> Application<Message, Command> for App<Model, DomTree, Processor, Message, Command, Key> where Model: Update<Message, Command> + Render<DomTree> + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Processor: side_effect::Processor<Message, Command> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Key: Eq + Hash + 'static, { fn update(&mut self, msg: Message) -> Commands<Command> { let mut commands = Commands::default(); self.model.update(msg, &mut commands); commands } fn get_scheduled_render(&mut self) -> &mut Option<ScheduledRender<Command>> { &mut self.animation_frame_handle } fn set_scheduled_render(&mut self, handle: ScheduledRender<Command>) { self.animation_frame_handle = Some(handle) } fn render(&mut self, app_rc: &Dispatcher<Message, Command>) -> Vec<Command> { let parent = self.node() .expect("empty app?") .parent_element() .expect("app not attached to the dom"); let App { ref mut model, ref mut storage, ref dom, .. } = *self; let new_dom = model.render(); let old = dom.dom_iter(); let new = new_dom.dom_iter(); let patch_set = diff::diff(old, new, storage); self.storage = patch_set.apply(&parent, app_rc); self.dom = new_dom; let commands; if let Some((cmds, _, _)) = self.animation_frame_handle.take() { commands = cmds; } else { commands = vec![]; } commands } fn process(&self, cmd: Command, app: &Dispatcher<Message, Command>) { Processor::process(&self.processor, cmd, app); } fn push_listener(&mut self, listener: (String, Closure<dyn FnMut(web_sys::Event)>)) { self.listeners.push(listener); } fn detach(&mut self, app: &Dispatcher<Message, Command>) { use std::iter; let parent = self.node() .expect("empty app?") .parent_element() .expect("app not attached to the dom"); let App { ref mut storage, ref dom, ref mut listeners, .. } = *self; let window = web_sys::window() .expect("couldn't get window handle"); for (event, listener) in listeners.drain(..) { window .remove_event_listener_with_callback(&event, listener.as_ref().unchecked_ref()) .expect("failed to remove event listener"); } let o = dom.dom_iter(); let patch_set = diff::diff(o, iter::empty(), storage); self.storage = patch_set.apply(&parent, app); } fn node(&self) -> Option<web_sys::Node> { self.storage.first() .and_then(|item| -> Option<web_sys::Node> { match item { WebItem::Element(ref node) => Some(node.clone().into()), WebItem::Text(ref node) => Some(node.clone().into()), WebItem::Component(component) => component.node(), i => panic!("unknown item, expected something with a node in it: {:?}", i) } }) } fn nodes(&self) -> Vec<web_sys::Node> { let mut nodes = vec![]; let mut depth = 0; for item in &self.storage { match item { WebItem::Element(_) | WebItem::Text(_) | WebItem::Component(_) if depth > 0 => { depth += 1; } WebItem::Up => depth -= 1, WebItem::Closure(_) => {} WebItem::Element(ref node) => { nodes.push(node.clone().into()); depth += 1; } WebItem::Text(ref node) => { nodes.push(node.clone().into()); depth += 1; } WebItem::Component(component) => { nodes.extend(component.nodes()); depth += 1; } i => panic!("unexpected item, expected something with a node in it, got : {:?}", i) } } nodes } fn create(&mut self, app: &Dispatcher<Message, Command>) -> Vec<web_sys::Node> { use std::iter; let App { ref mut storage, ref dom, .. } = *self; let n = dom.dom_iter(); let patch_set = diff::diff(iter::empty(), n, storage); let (storage, pending) = patch_set.prepare(app); self.storage = storage; pending } } struct App<Model, DomTree, Processor, Message, Command, Key> where Command: SideEffect<Message>, Processor: side_effect::Processor<Message, Command>, { dom: DomTree, model: Model, storage: Storage<Message>, listeners: Vec<(String, Closure<dyn FnMut(web_sys::Event)>)>, animation_frame_handle: Option<ScheduledRender<Command>>, processor: Processor, command: std::marker::PhantomData<Command>, key: std::marker::PhantomData<Key>, } impl<Model, DomTree, Processor, Message, Command, Key> App<Model, DomTree, Processor, Message, Command, Key> where Command: SideEffect<Message>, Processor: side_effect::Processor<Message, Command> + 'static, { fn create(model: Model, processor: Processor) -> (Rc<RefCell<Box<dyn Application<Message, Command>>>>, Vec<web_sys::Node>) where Model: Update<Message, Command> + Render<DomTree> + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Key: Eq + Hash + 'static, { let dom = model.render(); let app = App { dom: dom, model: model, storage: vec![], listeners: vec![], animation_frame_handle: None, processor: processor, command: std::marker::PhantomData, key: std::marker::PhantomData, }; let app_rc = Rc::new(RefCell::new(Box::new(app) as Box<dyn Application<Message, Command>>)); let nodes = Application::create(&mut **app_rc.borrow_mut(), &Dispatcher::from(&app_rc)); (app_rc, nodes) } }
let closure = Closure::wrap( Box::new(move |_event| { let url = document.url() .expect_throw("couldn't get document url"); if let Some(msg) = router.route(&url) { dispatcher.dispatch(msg); } }) as Box<dyn FnMut(web_sys::Event)> );
assignment_statement
[ { "content": "/// Some helpers to make testing a model easier.\n\npub trait Model<Message, Command> {\n\n /// Update a model with the given message.\n\n ///\n\n /// This function is a helper function designed to make testing models simpler. Normally during\n\n /// an update to a model, the `Commands...
Rust
world/src/consensus/ethash.rs
Fantom-foundation/fantom-rust-vm
a68fbe71f63365a8f3d05d2d84990e20a0bce45d
#![allow(dead_code)] #![allow(clippy::many_single_char_names)] use bigint_miner::{H256, H512, H64, U256}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use sha3::{Digest, Keccak256, Keccak512}; use std::ops::BitXor; use super::miller_rabin::is_prime; const DATASET_BYTES_INIT: usize = 1_073_741_824; const DATASET_BYTES_GROWTH: usize = 8_388_608; const CACHE_BYTES_INIT: usize = 16_777_216; const CACHE_BYTES_GROWTH: usize = 131_072; const CACHE_MULTIPLIER: usize = 1024; const MIX_BYTES: usize = 128; const WORD_BYTES: usize = 4; const HASH_BYTES: usize = 64; const DATASET_PARENTS: usize = 256; const CACHE_ROUNDS: usize = 3; const ACCESSES: usize = 64; pub fn get_cache_size(epoch: usize) -> usize { let mut sz = CACHE_BYTES_INIT + CACHE_BYTES_GROWTH * epoch; sz -= HASH_BYTES; while !is_prime(sz / HASH_BYTES) { sz -= 2 * HASH_BYTES; } sz } pub fn get_full_size(epoch: usize) -> usize { let mut sz = DATASET_BYTES_INIT + DATASET_BYTES_GROWTH * epoch; sz -= MIX_BYTES; while !is_prime(sz / MIX_BYTES) { sz -= 2 * MIX_BYTES } sz } fn fill_sha512(input: &[u8], a: &mut [u8], from_index: usize) { let mut hasher = Keccak512::default(); hasher.input(input); let out = hasher.result(); for i in 0..out.len() { a[from_index + i] = out[i]; } } fn fill_sha256(input: &[u8], a: &mut [u8], from_index: usize) { let mut hasher = Keccak256::default(); hasher.input(input); let out = hasher.result(); for i in 0..out.len() { a[from_index + i] = out[i]; } } pub fn make_cache(cache: &mut [u8], seed: H256) { assert!(cache.len() % HASH_BYTES == 0); let n = cache.len() / HASH_BYTES; fill_sha512(&seed, cache, 0); for i in 1..n { let (last, next) = cache.split_at_mut(i * 64); fill_sha512(&last[(last.len() - 64)..], next, 0); } for _ in 0..CACHE_ROUNDS { for i in 0..n { let v = ((&cache[(i * 64)..]).read_u32::<LittleEndian>().unwrap() as usize) % n; let mut r = [0u8; 64]; for j in 0..64 { let a = cache[((n + i - 1) % n) * 64 + j]; let b = cache[v * 64 + j]; r[j] = a.bitxor(b); } fill_sha512(&r, cache, i * 64); } } } const FNV_PRIME: u32 = 0x0100_0193; fn fnv(v1: u32, v2: u32) -> u32 { let v1 = u64::from(v1); let v2 = u64::from(v2); ((v1 * 0x0100_0000) | (v1 * 0x193) | v2) as u32 } fn fnv64(a: [u8; 64], b: [u8; 64]) -> [u8; 64] { let mut r = [0u8; 64]; for i in 0..(64 / 4) { let j = i * 4; let _a32 = (&a[j..]).read_u32::<LittleEndian>().unwrap(); let _b32 = (&b[j..]).read_u32::<LittleEndian>().unwrap(); let _ = (&mut r[j..]).write_u32::<LittleEndian>(fnv( (&a[j..]).read_u32::<LittleEndian>().unwrap(), (&b[j..]).read_u32::<LittleEndian>().unwrap(), )); } r } fn fnv128(a: [u8; 128], b: [u8; 128]) -> [u8; 128] { let mut r = [0u8; 128]; for i in 0..(128 / 4) { let j = i * 4; let _a32 = (&a[j..]).read_u32::<LittleEndian>().unwrap(); let _b32 = (&b[j..]).read_u32::<LittleEndian>().unwrap(); let _ = (&mut r[j..]).write_u32::<LittleEndian>(fnv( (&a[j..]).read_u32::<LittleEndian>().unwrap(), (&b[j..]).read_u32::<LittleEndian>().unwrap(), )); } r } fn u8s_to_u32(a: &[u8]) -> u32 { let _n = a.len(); (u32::from(a[0]) + u32::from(a[1])) << (8 + u32::from(a[2])) } pub fn calc_dataset_item(cache: &[u8], i: usize) -> H512 { debug_assert!(cache.len() % 64 == 0); let n = cache.len() / 64; let r = HASH_BYTES / WORD_BYTES; let mut mix = [0u8; 64]; for j in 0..64 { mix[j] = cache[(i % n) * 64 + j]; } let mix_first32 = mix.as_ref().read_u32::<LittleEndian>().unwrap().bitxor(i as u32); let _ = mix.as_mut().write_u32::<LittleEndian>(mix_first32); { let mut remix = [0u8; 64]; remix[..64].clone_from_slice(&mix[..64]); fill_sha512(&remix, &mut mix, 0); } for j in 0..DATASET_PARENTS { let cache_index = fnv( (i.bitxor(j) & (u32::max_value() as usize)) as u32, (&mix[(j % r * 4)..]).read_u32::<LittleEndian>().unwrap(), ) as usize; let mut item = [0u8; 64]; let cache_index = cache_index % n; for i in 0..64 { item[i] = cache[cache_index * 64 + i]; } mix = fnv64(mix, item); } let mut z = [0u8; 64]; fill_sha512(&mix, &mut z, 0); H512::from(z) } pub fn make_dataset(dataset: &mut [u8], cache: &[u8]) { let n = dataset.len() / HASH_BYTES; for i in 0..n { let z = calc_dataset_item(cache, i); for j in 0..64 { dataset[i * 64 + j] = z[j]; } } } pub fn hashimoto<F: Fn(usize) -> H512>(header_hash: H256, nonce: H64, full_size: usize, lookup: F) -> (H256, H256) { let n = full_size / HASH_BYTES; let w = MIX_BYTES / WORD_BYTES; const MIXHASHES: usize = MIX_BYTES / HASH_BYTES; let s = { let mut hasher = Keccak512::default(); let mut reversed_nonce: Vec<u8> = nonce.as_ref().into(); reversed_nonce.reverse(); hasher.input(&header_hash); hasher.input(&reversed_nonce); hasher.result() }; let mut mix = [0u8; MIX_BYTES]; for i in 0..MIXHASHES { for j in 0..64 { mix[i * HASH_BYTES + j] = s[j]; } } for i in 0..ACCESSES { let p = (fnv( (i as u32).bitxor(s.as_ref().read_u32::<LittleEndian>().unwrap()), (&mix[(i % w * 4)..]).read_u32::<LittleEndian>().unwrap(), ) as usize) % (n / MIXHASHES) * MIXHASHES; let mut newdata = [0u8; MIX_BYTES]; for j in 0..MIXHASHES { let v = lookup(p + j); for k in 0..64 { newdata[j * 64 + k] = v[k]; } } mix = fnv128(mix, newdata); } let mut cmix = [0u8; MIX_BYTES / 4]; for i in 0..(MIX_BYTES / 4 / 4) { let j = i * 4; let a = fnv( (&mix[(j * 4)..]).read_u32::<LittleEndian>().unwrap(), (&mix[((j + 1) * 4)..]).read_u32::<LittleEndian>().unwrap(), ); let b = fnv(a, (&mix[((j + 2) * 4)..]).read_u32::<LittleEndian>().unwrap()); let c = fnv(b, (&mix[((j + 3) * 4)..]).read_u32::<LittleEndian>().unwrap()); let _ = (&mut cmix[j..]).write_u32::<LittleEndian>(c); } let result = { let mut hasher = Keccak256::default(); hasher.input(&s); hasher.input(&cmix); let r = hasher.result(); let mut z = [0u8; 32]; for i in 0..32 { z[i] = r[i]; } z }; (H256::from(cmix), H256::from(result)) } pub fn hashimoto_light(header_hash: H256, nonce: H64, full_size: usize, cache: &[u8]) -> (H256, H256) { hashimoto(header_hash, nonce, full_size, |i| calc_dataset_item(cache, i)) } pub fn hashimoto_full(header_hash: H256, nonce: H64, full_size: usize, dataset: &[u8]) -> (H256, H256) { hashimoto(header_hash, nonce, full_size, |i| { let mut r = [0u8; 64]; for j in 0..64 { r[j] = dataset[i * 64 + j]; } H512::from(r) }) } pub fn cross_boundary(val: U256) -> U256 { if val <= U256::one() { U256::max_value() } else { ((U256::one() << 255) / val) << 1 } } pub fn mine( header: &block::Header, full_size: usize, dataset: &[u8], nonce_start: H64, difficulty: U256, ) -> (H64, H256) { let target = cross_boundary(difficulty); let header = rlp::encode(header).to_vec(); let mut nonce_current = nonce_start; loop { let (_, result) = hashimoto( H256::from(Keccak256::digest(&header).as_slice()), nonce_current, full_size, |i| { let mut r = [0u8; 64]; for j in 0..64 { r[j] = dataset[i * 64 + j]; } H512::from(r) }, ); let result_cmp: U256 = result.into(); if result_cmp <= target { return (nonce_current, result); } let nonce_u64: u64 = nonce_current.into(); nonce_current = H64::from(nonce_u64 + 1); } } #[allow(clippy::clone_on_copy)] pub fn get_seedhash(epoch: usize) -> H256 { let mut s = [0u8; 32]; for _i in 0..epoch { fill_sha256(&s.clone(), &mut s, 0); } H256::from(s.as_ref()) } #[cfg(test)] mod tests {}
#![allow(dead_code)] #![allow(clippy::many_single_char_names)] use bigint_miner::{H256, H512, H64, U256}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use sha3::{Digest, Keccak256, Keccak512}; use std::ops::BitXor; use super::miller_rabin::is_prime; const DATASET_BYTES_INIT: usize = 1_073_741_824; const DATASET_BYTES_GROWTH: usize = 8_388_608; const CACHE_BYTES_INIT: usize = 16_777_216; const CACHE_BYTES_GROWTH: usize = 131_072; const CACHE_MULTIPLIER: usize = 1024; const MIX_BYTES: usize = 128; const WORD_BYTES: usize = 4; const HASH_BYTES: usize = 64; const DATASET_PARENTS: usize = 256; const CACHE_ROUNDS: usize = 3; const ACCESSES: usize = 64; pub fn get_cache_size(epoch: usize) -> usize { let mut sz = CACHE_BYTES_INIT + CACHE_BYTES_GROWTH * epoch; sz -= HASH_BYTES; while !is_prime(sz / HASH_BYTES) { sz -= 2 * HASH_BYTES; } sz } pub fn get_full_size(epoch: usize) -> usize { let mut sz = DATASET_BYTES_INIT + DATASET_BYTES_GROWTH * epoch; sz -= MIX_BYTES; while !is_prime(sz / MIX_BYTES) { sz -= 2 * MIX_BYTES } sz } fn fill_sha512(input: &[u8], a: &mut [u8], from_index: usize) { let mut hasher = Keccak512::default(); hasher.input(input); let out = hasher.result(); for i in 0..out.len() { a[from_index + i] = out[i]; } } fn fill_sha256(input: &[u8], a: &mut [u8], from_index: usize) { let mut hasher = Keccak256::default(); hasher.input(input); let out = hasher.result(); for i in 0..out.len() { a[from_index + i] = out[i]; } } pub fn make_cache(cache: &mut [u8], seed: H256) { assert!(cache.len() % HASH_BYTES == 0); let n = cache.len() / HASH_BYTES; fill_sha512(&seed, cache, 0); for i in 1..n { let (last, next) = cache.split_at_mut(i * 64); fill_sha512(&last[(last.len() - 64)..], next, 0); } for _ in 0..CACHE_ROUNDS { for i in 0..n { let v = ((&cache[(i * 64)..]).read_u32::<LittleEndian>().unwrap() as usize) % n; let mut r = [0u8; 64]; for j in 0..64 { let a = cache[((n + i - 1) % n) * 64 + j]; let b = cache[v * 64 + j]; r[j] = a.bitxor(b); } fill_sha512(&r, cache, i * 64); } } } const FNV_PRIME: u32 = 0x0100_0193; fn fnv(v1: u32, v2: u32) -> u32 { let v1 = u64::from(v1); let v2 = u64::from(v2); ((v1 * 0x0100_0000) | (v1 * 0x193) | v2) as u32 } fn fnv64(a: [u8; 64], b: [u8; 64]) -> [u8; 64] { let mut r = [0u8; 64]; for i in 0..(64 / 4) { let j = i * 4; let _a32 = (&a[j..]).read_u32::<LittleEndian>().unwrap(); let _b32 = (&b[j..]).read_u32::<LittleEndian>().unwrap(); let _ = (&mut r[j..]).write_u32::<LittleEndian>(fnv( (&a[j..]).read_u32::<LittleEndian>().unwrap(), (&b[j..]).read_u32::<LittleEndian>().unwrap(), )); } r } fn fnv128(a: [u8; 128], b: [u8; 128]) -> [u8; 128] { let mut r = [0u8; 128]; for i in 0..(128 / 4) { let j = i * 4; let _a32 = (&a[j..]).read_u32::<LittleEndian>().unwrap(); let _b32 = (&b[j..]).read_u32::<LittleEndian>().unwrap(); let _ = (&mut r[j..]).write_u32::<LittleEndian>(fnv( (&a[j..]).read_u32::<LittleEndian>().unwrap(), (&b[j..]).read_u32::<LittleEndian>().unwrap(), )); } r } fn u8s_to_u32(a: &[u8]) -> u32 { let _n = a.len(); (u32::from(a[0]) + u32::from(a[1])) << (8 + u32::from(a[2])) } pub fn calc_dataset_item(cache: &[u8], i: usize) -> H512 { debug_assert!(cache.len() % 64 == 0); let n = cache.len() / 64; let r = HASH_BYTES / WORD_BYTES; let mut mix = [0u8; 64]; for j in 0..64 { mix[j] = cache[(i % n) * 64 + j]; } let mix_first32 = mix.as_ref().read_u32::<LittleEndian>().unwrap().bitxor(i as u32); let _ = mix.as_mut().write_u32::<LittleEndian>(mix_first32); { let mut remix = [0u8; 64]; remix[..64].clone_from_slice(&mix[..64]); fill_sha512(&remix, &mut mix, 0); } for j in 0..DATASET_PARENTS { let cache_index = fnv( (i.bitxor(j) & (u32::max_value() as usize)) as u32, (&mix[(j % r * 4)..]).read_u32::<LittleEndian>().unwrap(), ) as usize; let mut item = [0u8; 64]; let cache_index = cache_index % n; for i in 0..64 { item[i] = cache[cache_index * 64 + i]; } mix = fnv64(mix, item); } let mut z = [0u8; 64]; fill_sha512(&mix, &mut z, 0); H512::from(z) } pub fn make_dataset(dataset: &mut [u8], cache: &[u8]) { let n = dataset.len() / HASH_BYTES; for i in 0..n { let z = calc_dataset_item(cache, i); for j in 0..64 { dataset[i * 64 + j] = z[j]; } } } pub fn hashimoto<F: Fn(usize) -> H512>(header_hash: H256, nonce: H64, full_size: usize, lookup: F) -> (H256, H256) { let n = full_size / HASH_BYTES; let w = MIX_BYTES / WORD_BYTES; const MIXHASHES: usize = MIX_BYTES / HASH_BYTES; let s = { let mut hasher = Keccak512::default(); let mut reversed_nonce: Vec<u8> = nonce.as_ref().into(); reversed_nonce.reverse(); hasher.input(&header_hash); hasher.input(&reversed_nonce); hasher.result() }; let mut mix = [0u8; MIX_BYTES]; for i in 0..MIXHASHES { for j in 0..64 { mix[i * HASH_BYTES + j] = s[j]; } } for i in 0..ACCESSES { let p = (fnv( (i as u32).bitxor(s.as_ref().read_u32::<LittleEndian>().unwrap()), (&mix[(i % w * 4)..]).read_u32::<LittleEndian>().unwrap(), ) as usize) % (n / MIXHASHES) * MIXHASHES; let mut newdata = [0u8; MIX_BYTES]; for j in 0..MIXHASHES { let v = lookup(p + j); for k in 0..64 { newdata[j * 64 + k] = v[k]; } } mix = fnv128(mix, newdata); } let mut cmix = [0u8; MIX_BYTES / 4]; for i in 0..(MIX_BYTES / 4 / 4) { let j = i * 4; let a = fnv( (&mix[(j * 4)..]).read_u32::<LittleEndian>().unwrap(), (&mix[((j + 1) * 4)..]).read_u32::<LittleEndian>().unwrap(), ); let b = fnv(a, (&mix[((j + 2) * 4)..]).read_u32::<LittleEndian>().unwrap()); let c = fnv(b, (&mix[((j + 3) * 4)..]).read_u32::<LittleEndian>().unwrap()); let _ = (&mut cmix[j..]).write_u32::<LittleEndian>(c); } let result = { let mut hasher = Keccak256::default(); hasher.input(&s); hasher.input(&cmix); let r = hasher.result(); let mut z = [0u8; 32]; for i in 0..32 { z[i] = r[i]; } z }; (H256::from(cmix), H256::from(result)) } pub fn hashimoto_light(header_hash: H256, nonce: H64, full_size: usize, cache: &[u8]) -> (H256, H256) { hashimoto(header_hash, nonce, full_size, |i| calc_dataset_item(cache, i)) } pub fn hashimoto_full(header_hash: H256, nonce: H64, full_size: usize, dataset: &[u8]) -> (H256, H256) { hashimoto(header_hash, nonce, full_size, |i| { let mut r = [0u8; 64]; for j in 0..64 { r[j] = dataset[i * 64 + j]; } H512::from(r) }) }
pub fn mine( header: &block::Header, full_size: usize, dataset: &[u8], nonce_start: H64, difficulty: U256, ) -> (H64, H256) { let target = cross_boundary(difficulty); let header = rlp::encode(header).to_vec(); let mut nonce_current = nonce_start; loop { let (_, result) = hashimoto( H256::from(Keccak256::digest(&header).as_slice()), nonce_current, full_size, |i| { let mut r = [0u8; 64]; for j in 0..64 { r[j] = dataset[i * 64 + j]; } H512::from(r) }, ); let result_cmp: U256 = result.into(); if result_cmp <= target { return (nonce_current, result); } let nonce_u64: u64 = nonce_current.into(); nonce_current = H64::from(nonce_u64 + 1); } } #[allow(clippy::clone_on_copy)] pub fn get_seedhash(epoch: usize) -> H256 { let mut s = [0u8; 32]; for _i in 0..epoch { fill_sha256(&s.clone(), &mut s, 0); } H256::from(s.as_ref()) } #[cfg(test)] mod tests {}
pub fn cross_boundary(val: U256) -> U256 { if val <= U256::one() { U256::max_value() } else { ((U256::one() << 255) / val) << 1 } }
function_block-full_function
[ { "content": "fn mod_exp(mut x: usize, mut d: usize, n: usize) -> usize {\n\n let mut ret: usize = 1;\n\n while d != 0 {\n\n if d % 2 == 1 {\n\n ret = mod_mul(ret, x, n)\n\n }\n\n d /= 2;\n\n x = mod_sqr(x, n);\n\n }\n\n ret\n\n}\n\n\n", "file_path": "world...
Rust
src/request.rs
auula/poem
b3d15f83e994389b97ccd614d9361d48e3730002
use std::{ any::Any, convert::{TryFrom, TryInto}, sync::Arc, }; use crate::{ body::Body, error::{Error, ErrorBodyHasBeenTaken, Result}, http::{ header::{self, HeaderMap, HeaderName, HeaderValue}, Extensions, Method, Uri, Version, }, route_recognizer::Params, web::CookieJar, }; pub struct RequestParts { method: Method, uri: Uri, version: Version, headers: HeaderMap, extensions: Extensions, } #[derive(Default)] pub(crate) struct RequestState { pub(crate) original_uri: Uri, pub(crate) match_params: Params, pub(crate) cookie_jar: CookieJar, } pub struct Request { method: Method, uri: Uri, version: Version, headers: HeaderMap, extensions: Extensions, body: Option<Body>, state: RequestState, } impl Request { pub(crate) fn from_hyper_request(req: hyper::Request<hyper::Body>) -> Result<Self> { let (parts, body) = req.into_parts(); let mut cookie_jar = ::cookie::CookieJar::new(); for header in parts.headers.get_all(header::COOKIE) { if let Ok(value) = std::str::from_utf8(header.as_bytes()) { for cookie_str in value.split(';').map(str::trim) { if let Ok(cookie) = ::cookie::Cookie::parse_encoded(cookie_str) { cookie_jar.add_original(cookie.into_owned()); } } } } Ok(Self { method: parts.method, uri: parts.uri.clone(), version: parts.version, headers: parts.headers, extensions: parts.extensions, body: Some(Body(body)), state: RequestState { original_uri: parts.uri, match_params: Default::default(), cookie_jar: CookieJar(Arc::new(parking_lot::Mutex::new(cookie_jar))), }, }) } pub fn builder() -> RequestBuilder { RequestBuilder(Ok(RequestParts { method: Method::GET, uri: Default::default(), version: Default::default(), headers: Default::default(), extensions: Default::default(), })) } #[inline] pub fn method(&self) -> &Method { &self.method } #[inline] pub fn set_method(&mut self, method: Method) { self.method = method; } #[inline] pub fn uri(&self) -> &Uri { &self.uri } #[inline] pub fn original_uri(&self) -> &Uri { &self.state.original_uri } #[inline] pub fn set_uri(&mut self, uri: Uri) { self.uri = uri; } #[inline] pub fn version(&self) -> Version { self.version } #[inline] pub fn set_version(&mut self, version: Version) { self.version = version; } #[inline] pub fn headers(&self) -> &HeaderMap { &self.headers } #[inline] pub fn headers_mut(&mut self) -> &mut HeaderMap { &mut self.headers } pub fn content_type(&self) -> Option<&str> { self.headers() .get(header::CONTENT_TYPE) .and_then(|value| value.to_str().ok()) } #[inline] pub fn extensions(&self) -> &Extensions { &self.extensions } #[inline] pub fn extensions_mut(&mut self) -> &mut Extensions { &mut self.extensions } #[inline] pub fn cookie(&self) -> &CookieJar { &self.state.cookie_jar } pub fn set_body(&mut self, body: Body) { self.body = Some(body); } #[inline] pub fn take_body(&mut self) -> Result<Body> { self.body.take().ok_or_else(|| ErrorBodyHasBeenTaken.into()) } #[inline] pub(crate) fn state(&self) -> &RequestState { &self.state } #[inline] pub(crate) fn state_mut(&mut self) -> &mut RequestState { &mut self.state } } pub struct RequestBuilder(Result<RequestParts>); impl RequestBuilder { #[must_use] pub fn method(self, method: Method) -> RequestBuilder { Self(self.0.map(move |parts| RequestParts { method, ..parts })) } #[must_use] pub fn uri<T>(self, uri: T) -> RequestBuilder where T: TryInto<Uri, Error = Error>, { Self(self.0.and_then(move |parts| { Ok(RequestParts { uri: uri.try_into()?, ..parts }) })) } #[must_use] pub fn version(self, version: Version) -> RequestBuilder { Self(self.0.map(move |parts| RequestParts { version, ..parts })) } #[must_use] pub fn header<K, V>(self, key: K, value: V) -> Self where HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: Into<Error>, HeaderValue: TryFrom<V>, <HeaderValue as TryFrom<V>>::Error: Into<Error>, { Self(self.0.and_then(move |mut parts| { let key = <HeaderName as TryFrom<K>>::try_from(key).map_err(Into::into)?; let value = <HeaderValue as TryFrom<V>>::try_from(value).map_err(Into::into)?; parts.headers.append(key, value); Ok(parts) })) } #[must_use] pub fn content_type(self, content_type: &str) -> Self { Self(self.0.and_then(move |mut parts| { let value = content_type.parse()?; parts.headers.append(header::CONTENT_TYPE, value); Ok(parts) })) } #[must_use] pub fn extension<T>(self, extension: T) -> Self where T: Any + Send + Sync + 'static, { Self(self.0.map(move |mut parts| { parts.extensions.insert(extension); parts })) } pub fn body(self, body: Body) -> Result<Request> { self.0.map(move |parts| Request { method: parts.method, uri: parts.uri, version: parts.version, headers: parts.headers, extensions: parts.extensions, body: Some(body), state: Default::default(), }) } }
use std::{ any::Any, convert::{TryFrom, TryInto}, sync::Arc, }; use crate::{ body::Body, error::{Error, ErrorBodyHasBeenTaken, Result}, http::{ header::{self, HeaderMap, HeaderName, HeaderValue}, Extensions, Method, Uri, Version, }, route_recognizer::Params, web::CookieJar, }; pub struct RequestParts { method: Method, uri: Uri, version: Version, headers: HeaderMap, extensions: Extensions, } #[derive(Default)] pub(crate) struct RequestState { pub(crate) original_uri: Uri, pub(crate) match_params: Params, pub(crate) cookie_jar: CookieJar, } pub struct Request { method: Method, uri: Uri, version: Version, headers: HeaderMap, extensions: Extensions,
HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: Into<Error>, HeaderValue: TryFrom<V>, <HeaderValue as TryFrom<V>>::Error: Into<Error>, { Self(self.0.and_then(move |mut parts| { let key = <HeaderName as TryFrom<K>>::try_from(key).map_err(Into::into)?; let value = <HeaderValue as TryFrom<V>>::try_from(value).map_err(Into::into)?; parts.headers.append(key, value); Ok(parts) })) } #[must_use] pub fn content_type(self, content_type: &str) -> Self { Self(self.0.and_then(move |mut parts| { let value = content_type.parse()?; parts.headers.append(header::CONTENT_TYPE, value); Ok(parts) })) } #[must_use] pub fn extension<T>(self, extension: T) -> Self where T: Any + Send + Sync + 'static, { Self(self.0.map(move |mut parts| { parts.extensions.insert(extension); parts })) } pub fn body(self, body: Body) -> Result<Request> { self.0.map(move |parts| Request { method: parts.method, uri: parts.uri, version: parts.version, headers: parts.headers, extensions: parts.extensions, body: Some(body), state: Default::default(), }) } }
body: Option<Body>, state: RequestState, } impl Request { pub(crate) fn from_hyper_request(req: hyper::Request<hyper::Body>) -> Result<Self> { let (parts, body) = req.into_parts(); let mut cookie_jar = ::cookie::CookieJar::new(); for header in parts.headers.get_all(header::COOKIE) { if let Ok(value) = std::str::from_utf8(header.as_bytes()) { for cookie_str in value.split(';').map(str::trim) { if let Ok(cookie) = ::cookie::Cookie::parse_encoded(cookie_str) { cookie_jar.add_original(cookie.into_owned()); } } } } Ok(Self { method: parts.method, uri: parts.uri.clone(), version: parts.version, headers: parts.headers, extensions: parts.extensions, body: Some(Body(body)), state: RequestState { original_uri: parts.uri, match_params: Default::default(), cookie_jar: CookieJar(Arc::new(parking_lot::Mutex::new(cookie_jar))), }, }) } pub fn builder() -> RequestBuilder { RequestBuilder(Ok(RequestParts { method: Method::GET, uri: Default::default(), version: Default::default(), headers: Default::default(), extensions: Default::default(), })) } #[inline] pub fn method(&self) -> &Method { &self.method } #[inline] pub fn set_method(&mut self, method: Method) { self.method = method; } #[inline] pub fn uri(&self) -> &Uri { &self.uri } #[inline] pub fn original_uri(&self) -> &Uri { &self.state.original_uri } #[inline] pub fn set_uri(&mut self, uri: Uri) { self.uri = uri; } #[inline] pub fn version(&self) -> Version { self.version } #[inline] pub fn set_version(&mut self, version: Version) { self.version = version; } #[inline] pub fn headers(&self) -> &HeaderMap { &self.headers } #[inline] pub fn headers_mut(&mut self) -> &mut HeaderMap { &mut self.headers } pub fn content_type(&self) -> Option<&str> { self.headers() .get(header::CONTENT_TYPE) .and_then(|value| value.to_str().ok()) } #[inline] pub fn extensions(&self) -> &Extensions { &self.extensions } #[inline] pub fn extensions_mut(&mut self) -> &mut Extensions { &mut self.extensions } #[inline] pub fn cookie(&self) -> &CookieJar { &self.state.cookie_jar } pub fn set_body(&mut self, body: Body) { self.body = Some(body); } #[inline] pub fn take_body(&mut self) -> Result<Body> { self.body.take().ok_or_else(|| ErrorBodyHasBeenTaken.into()) } #[inline] pub(crate) fn state(&self) -> &RequestState { &self.state } #[inline] pub(crate) fn state_mut(&mut self) -> &mut RequestState { &mut self.state } } pub struct RequestBuilder(Result<RequestParts>); impl RequestBuilder { #[must_use] pub fn method(self, method: Method) -> RequestBuilder { Self(self.0.map(move |parts| RequestParts { method, ..parts })) } #[must_use] pub fn uri<T>(self, uri: T) -> RequestBuilder where T: TryInto<Uri, Error = Error>, { Self(self.0.and_then(move |parts| { Ok(RequestParts { uri: uri.try_into()?, ..parts }) })) } #[must_use] pub fn version(self, version: Version) -> RequestBuilder { Self(self.0.map(move |parts| RequestParts { version, ..parts })) } #[must_use] pub fn header<K, V>(self, key: K, value: V) -> Self where
random
[]
Rust
datafusion/src/datasource/memory.rs
andts/arrow-datafusion
1c39f5ce865e3e1225b4895196073be560a93e82
use futures::StreamExt; use std::any::Any; use std::sync::Arc; use arrow::datatypes::SchemaRef; use arrow::record_batch::RecordBatch; use async_trait::async_trait; use crate::datasource::TableProvider; use crate::error::{DataFusionError, Result}; use crate::execution::runtime_env::RuntimeEnv; use crate::logical_plan::Expr; use crate::physical_plan::common; use crate::physical_plan::memory::MemoryExec; use crate::physical_plan::ExecutionPlan; use crate::physical_plan::{repartition::RepartitionExec, Partitioning}; pub struct MemTable { schema: SchemaRef, batches: Vec<Vec<RecordBatch>>, } impl MemTable { pub fn try_new(schema: SchemaRef, partitions: Vec<Vec<RecordBatch>>) -> Result<Self> { if partitions .iter() .flatten() .all(|batches| schema.contains(&batches.schema())) { Ok(Self { schema, batches: partitions, }) } else { Err(DataFusionError::Plan( "Mismatch between schema and batches".to_string(), )) } } pub async fn load( t: Arc<dyn TableProvider>, batch_size: usize, output_partitions: Option<usize>, runtime: Arc<RuntimeEnv>, ) -> Result<Self> { let schema = t.schema(); let exec = t.scan(&None, batch_size, &[], None).await?; let partition_count = exec.output_partitioning().partition_count(); let tasks = (0..partition_count) .map(|part_i| { let runtime1 = runtime.clone(); let exec = exec.clone(); tokio::spawn(async move { let stream = exec.execute(part_i, runtime1.clone()).await?; common::collect(stream).await }) }) .collect::<Vec<_>>(); let mut data: Vec<Vec<RecordBatch>> = Vec::with_capacity(exec.output_partitioning().partition_count()); for task in tasks { let result = task.await.expect("MemTable::load could not join task")?; data.push(result); } let exec = MemoryExec::try_new(&data, schema.clone(), None)?; if let Some(num_partitions) = output_partitions { let exec = RepartitionExec::try_new( Arc::new(exec), Partitioning::RoundRobinBatch(num_partitions), )?; let mut output_partitions = vec![]; for i in 0..exec.output_partitioning().partition_count() { let mut stream = exec.execute(i, runtime.clone()).await?; let mut batches = vec![]; while let Some(result) = stream.next().await { batches.push(result?); } output_partitions.push(batches); } return MemTable::try_new(schema.clone(), output_partitions); } MemTable::try_new(schema.clone(), data) } } #[async_trait] impl TableProvider for MemTable { fn as_any(&self) -> &dyn Any { self } fn schema(&self) -> SchemaRef { self.schema.clone() } async fn scan( &self, projection: &Option<Vec<usize>>, _batch_size: usize, _filters: &[Expr], _limit: Option<usize>, ) -> Result<Arc<dyn ExecutionPlan>> { Ok(Arc::new(MemoryExec::try_new( &self.batches.clone(), self.schema(), projection.clone(), )?)) } } #[cfg(test)] mod tests { use super::*; use arrow::array::Int32Array; use arrow::datatypes::{DataType, Field, Schema}; use futures::StreamExt; use std::collections::HashMap; #[tokio::test] async fn test_with_projection() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); let schema = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), Field::new("d", DataType::Int32, true), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), Arc::new(Int32Array::from(vec![None, None, Some(9)])), ], )?; let provider = MemTable::try_new(schema, vec![vec![batch]])?; let exec = provider.scan(&Some(vec![2, 1]), 1024, &[], None).await?; let mut it = exec.execute(0, runtime).await?; let batch2 = it.next().await.unwrap()?; assert_eq!(2, batch2.schema().fields().len()); assert_eq!("c", batch2.schema().field(0).name()); assert_eq!("b", batch2.schema().field(1).name()); assert_eq!(2, batch2.num_columns()); Ok(()) } #[tokio::test] async fn test_without_projection() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); let schema = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let provider = MemTable::try_new(schema, vec![vec![batch]])?; let exec = provider.scan(&None, 1024, &[], None).await?; let mut it = exec.execute(0, runtime).await?; let batch1 = it.next().await.unwrap()?; assert_eq!(3, batch1.schema().fields().len()); assert_eq!(3, batch1.num_columns()); Ok(()) } #[tokio::test] async fn test_invalid_projection() -> Result<()> { let schema = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let provider = MemTable::try_new(schema, vec![vec![batch]])?; let projection: Vec<usize> = vec![0, 4]; match provider.scan(&Some(projection), 1024, &[], None).await { Err(DataFusionError::Internal(e)) => { assert_eq!("\"Projection index out of range\"", format!("{:?}", e)) } _ => panic!("Scan should failed on invalid projection"), }; Ok(()) } #[test] fn test_schema_validation_incompatible_column() -> Result<()> { let schema1 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let schema2 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Float64, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema1, vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; match MemTable::try_new(schema2, vec![vec![batch]]) { Err(DataFusionError::Plan(e)) => assert_eq!( "\"Mismatch between schema and batches\"", format!("{:?}", e) ), _ => panic!("MemTable::new should have failed due to schema mismatch"), } Ok(()) } #[test] fn test_schema_validation_different_column_count() -> Result<()> { let schema1 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let schema2 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema1, vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![7, 5, 9])), ], )?; match MemTable::try_new(schema2, vec![vec![batch]]) { Err(DataFusionError::Plan(e)) => assert_eq!( "\"Mismatch between schema and batches\"", format!("{:?}", e) ), _ => panic!("MemTable::new should have failed due to schema mismatch"), } Ok(()) } #[tokio::test] async fn test_merged_schema() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); let mut metadata = HashMap::new(); metadata.insert("foo".to_string(), "bar".to_string()); let schema1 = Schema::new_with_metadata( vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ], metadata, ); let schema2 = Schema::new(vec![ Field::new("a", DataType::Int32, true), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ]); let merged_schema = Schema::try_merge(vec![schema1.clone(), schema2.clone()])?; let batch1 = RecordBatch::try_new( Arc::new(schema1), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let batch2 = RecordBatch::try_new( Arc::new(schema2), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let provider = MemTable::try_new(Arc::new(merged_schema), vec![vec![batch1, batch2]])?; let exec = provider.scan(&None, 1024, &[], None).await?; let mut it = exec.execute(0, runtime).await?; let batch1 = it.next().await.unwrap()?; assert_eq!(3, batch1.schema().fields().len()); assert_eq!(3, batch1.num_columns()); Ok(()) } }
use futures::StreamExt; use std::any::Any; use std::sync::Arc; use arrow::datatypes::SchemaRef; use arrow::record_batch::RecordBatch; use async_trait::async_trait; use crate::datasource::TableProvider; use crate::error::{DataFusionError, Result}; use crate::execution::runtime_env::RuntimeEnv; use crate::logical_plan::Expr; use crate::physical_plan::common; use crate::physical_plan::memory::MemoryExec; use crate::physical_plan::ExecutionPlan; use crate::physical_plan::{repartition::RepartitionExec, Partitioning}; pub struct MemTable { schema: SchemaRef, batches: Vec<Vec<RecordBatch>>, } impl MemTable {
pub async fn load( t: Arc<dyn TableProvider>, batch_size: usize, output_partitions: Option<usize>, runtime: Arc<RuntimeEnv>, ) -> Result<Self> { let schema = t.schema(); let exec = t.scan(&None, batch_size, &[], None).await?; let partition_count = exec.output_partitioning().partition_count(); let tasks = (0..partition_count) .map(|part_i| { let runtime1 = runtime.clone(); let exec = exec.clone(); tokio::spawn(async move { let stream = exec.execute(part_i, runtime1.clone()).await?; common::collect(stream).await }) }) .collect::<Vec<_>>(); let mut data: Vec<Vec<RecordBatch>> = Vec::with_capacity(exec.output_partitioning().partition_count()); for task in tasks { let result = task.await.expect("MemTable::load could not join task")?; data.push(result); } let exec = MemoryExec::try_new(&data, schema.clone(), None)?; if let Some(num_partitions) = output_partitions { let exec = RepartitionExec::try_new( Arc::new(exec), Partitioning::RoundRobinBatch(num_partitions), )?; let mut output_partitions = vec![]; for i in 0..exec.output_partitioning().partition_count() { let mut stream = exec.execute(i, runtime.clone()).await?; let mut batches = vec![]; while let Some(result) = stream.next().await { batches.push(result?); } output_partitions.push(batches); } return MemTable::try_new(schema.clone(), output_partitions); } MemTable::try_new(schema.clone(), data) } } #[async_trait] impl TableProvider for MemTable { fn as_any(&self) -> &dyn Any { self } fn schema(&self) -> SchemaRef { self.schema.clone() } async fn scan( &self, projection: &Option<Vec<usize>>, _batch_size: usize, _filters: &[Expr], _limit: Option<usize>, ) -> Result<Arc<dyn ExecutionPlan>> { Ok(Arc::new(MemoryExec::try_new( &self.batches.clone(), self.schema(), projection.clone(), )?)) } } #[cfg(test)] mod tests { use super::*; use arrow::array::Int32Array; use arrow::datatypes::{DataType, Field, Schema}; use futures::StreamExt; use std::collections::HashMap; #[tokio::test] async fn test_with_projection() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); let schema = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), Field::new("d", DataType::Int32, true), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), Arc::new(Int32Array::from(vec![None, None, Some(9)])), ], )?; let provider = MemTable::try_new(schema, vec![vec![batch]])?; let exec = provider.scan(&Some(vec![2, 1]), 1024, &[], None).await?; let mut it = exec.execute(0, runtime).await?; let batch2 = it.next().await.unwrap()?; assert_eq!(2, batch2.schema().fields().len()); assert_eq!("c", batch2.schema().field(0).name()); assert_eq!("b", batch2.schema().field(1).name()); assert_eq!(2, batch2.num_columns()); Ok(()) } #[tokio::test] async fn test_without_projection() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); let schema = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let provider = MemTable::try_new(schema, vec![vec![batch]])?; let exec = provider.scan(&None, 1024, &[], None).await?; let mut it = exec.execute(0, runtime).await?; let batch1 = it.next().await.unwrap()?; assert_eq!(3, batch1.schema().fields().len()); assert_eq!(3, batch1.num_columns()); Ok(()) } #[tokio::test] async fn test_invalid_projection() -> Result<()> { let schema = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let provider = MemTable::try_new(schema, vec![vec![batch]])?; let projection: Vec<usize> = vec![0, 4]; match provider.scan(&Some(projection), 1024, &[], None).await { Err(DataFusionError::Internal(e)) => { assert_eq!("\"Projection index out of range\"", format!("{:?}", e)) } _ => panic!("Scan should failed on invalid projection"), }; Ok(()) } #[test] fn test_schema_validation_incompatible_column() -> Result<()> { let schema1 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let schema2 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Float64, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema1, vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; match MemTable::try_new(schema2, vec![vec![batch]]) { Err(DataFusionError::Plan(e)) => assert_eq!( "\"Mismatch between schema and batches\"", format!("{:?}", e) ), _ => panic!("MemTable::new should have failed due to schema mismatch"), } Ok(()) } #[test] fn test_schema_validation_different_column_count() -> Result<()> { let schema1 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let schema2 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema1, vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![7, 5, 9])), ], )?; match MemTable::try_new(schema2, vec![vec![batch]]) { Err(DataFusionError::Plan(e)) => assert_eq!( "\"Mismatch between schema and batches\"", format!("{:?}", e) ), _ => panic!("MemTable::new should have failed due to schema mismatch"), } Ok(()) } #[tokio::test] async fn test_merged_schema() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); let mut metadata = HashMap::new(); metadata.insert("foo".to_string(), "bar".to_string()); let schema1 = Schema::new_with_metadata( vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ], metadata, ); let schema2 = Schema::new(vec![ Field::new("a", DataType::Int32, true), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ]); let merged_schema = Schema::try_merge(vec![schema1.clone(), schema2.clone()])?; let batch1 = RecordBatch::try_new( Arc::new(schema1), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let batch2 = RecordBatch::try_new( Arc::new(schema2), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let provider = MemTable::try_new(Arc::new(merged_schema), vec![vec![batch1, batch2]])?; let exec = provider.scan(&None, 1024, &[], None).await?; let mut it = exec.execute(0, runtime).await?; let batch1 = it.next().await.unwrap()?; assert_eq!(3, batch1.schema().fields().len()); assert_eq!(3, batch1.num_columns()); Ok(()) } }
pub fn try_new(schema: SchemaRef, partitions: Vec<Vec<RecordBatch>>) -> Result<Self> { if partitions .iter() .flatten() .all(|batches| schema.contains(&batches.schema())) { Ok(Self { schema, batches: partitions, }) } else { Err(DataFusionError::Plan( "Mismatch between schema and batches".to_string(), )) } }
function_block-full_function
[]
Rust
src/utils/random.rs
xiangminghu/native_spark
f6199cce8ec546b9f16e14b7d098801f28b08018
use std::any::Any; use std::rc::Rc; use downcast_rs::Downcast; use rand::{Rng, SeedableRng}; use rand_distr::{Bernoulli, Distribution, Poisson}; use rand_pcg::Pcg64; use crate::{Data, Deserialize, Serialize}; const DEFAULT_MAX_GAP_SAMPLING_FRACTION: f64 = 0.4; const RNG_EPSILON: f64 = 5e-11; const ROUNDING_EPSILON: f64 = 1e-6; type RSamplerFunc<'a, T> = Box<dyn Fn(Box<dyn Iterator<Item = T>>) -> Vec<T> + 'a>; pub(crate) trait RandomSampler<T: Data>: Send + Sync + Serialize + Deserialize { fn get_sampler(&self) -> RSamplerFunc<T>; } pub(crate) fn get_default_rng() -> Pcg64 { Pcg64::new( 0xcafe_f00d_d15e_a5e5, 0x0a02_bdbf_7bb3_c0a7_ac28_fa16_a64a_bf96, ) } fn get_rng_with_random_seed() -> Pcg64 { Pcg64::seed_from_u64(rand::random::<u64>()) } #[derive(Clone, Serialize, Deserialize)] pub(crate) struct PoissonSampler { fraction: f64, use_gap_sampling_if_possible: bool, prob: f64, } impl PoissonSampler { pub fn new(fraction: f64, use_gap_sampling_if_possible: bool) -> PoissonSampler { let prob = if fraction > 0.0 { fraction } else { 1.0 }; PoissonSampler { fraction, use_gap_sampling_if_possible, prob, } } } impl<T: Data> RandomSampler<T> for PoissonSampler { fn get_sampler(&self) -> RSamplerFunc<T> { Box::new(move |items: Box<dyn Iterator<Item = T>>| -> Vec<T> { if self.fraction <= 0.0 { vec![] } else { let use_gap_sampling = self.use_gap_sampling_if_possible && self.fraction <= DEFAULT_MAX_GAP_SAMPLING_FRACTION; let mut gap_sampling = if use_gap_sampling { Some(GapSamplingReplacement::new(self.fraction, RNG_EPSILON)) } else { None }; let dist = Poisson::new(self.prob).unwrap(); let mut rng = get_rng_with_random_seed(); items .flat_map(move |item| { let count = if use_gap_sampling { gap_sampling.as_mut().unwrap().sample() } else { dist.sample(&mut rng) }; if count != 0 { vec![item; count as usize] } else { vec![] } }) .collect() } }) } } #[derive(Clone, Serialize, Deserialize)] pub(crate) struct BernoulliSampler { fraction: f64, } impl BernoulliSampler { pub fn new(fraction: f64) -> BernoulliSampler { assert!(fraction >= (0.0 - ROUNDING_EPSILON) && fraction <= (1.0 + ROUNDING_EPSILON)); BernoulliSampler { fraction } } fn sample(&self, gap_sampling: Option<&mut GapSamplingReplacement>, rng: &mut Pcg64) -> u64 { match self.fraction { v if v <= 0.0 => 0, v if v >= 1.0 => 1, v if v <= DEFAULT_MAX_GAP_SAMPLING_FRACTION => gap_sampling.unwrap().sample(), v if rng.gen::<f64>() <= v => 1, _ => 0, } } } impl<T: Data> RandomSampler<T> for BernoulliSampler { fn get_sampler(&self) -> RSamplerFunc<T> { Box::new(move |items: Box<dyn Iterator<Item = T>>| -> Vec<T> { let mut gap_sampling = if self.fraction > 0.0 && self.fraction < 1.0 { Some(GapSamplingReplacement::new(self.fraction, RNG_EPSILON)) } else { None }; let mut rng = get_rng_with_random_seed(); items .filter(move |item| self.sample(gap_sampling.as_mut(), &mut rng) > 0) .collect() }) } } struct GapSamplingReplacement { fraction: f64, epsilon: f64, q: f64, rng: rand_pcg::Pcg64, count_for_dropping: u64, } impl GapSamplingReplacement { fn new(fraction: f64, epsilon: f64) -> GapSamplingReplacement { assert!(fraction > 0.0 && fraction < 1.0); assert!(epsilon > 0.0); let mut sampler = GapSamplingReplacement { q: (-fraction).exp(), fraction, epsilon, rng: get_rng_with_random_seed(), count_for_dropping: 0, }; sampler.advance(); sampler } fn sample(&mut self) -> u64 { if self.count_for_dropping > 0 { self.count_for_dropping -= 1; 0 } else { let r = self.poisson_ge1(); self.advance(); r } } fn poisson_ge1(&mut self) -> u64 { let mut pp: f64 = self.q + ((1.0 - self.q) * self.rng.gen::<f64>()); let mut r = 1; pp *= self.rng.gen::<f64>(); while pp > self.q { r += 1; pp *= self.rng.gen::<f64>() } r } fn advance(&mut self) { let u = self.epsilon.max(self.rng.gen::<f64>()); self.count_for_dropping = (u.log(std::f64::consts::E) / (-self.fraction)) as u64; } } pub(crate) fn compute_fraction_for_sample_size( sample_size_lower_bound: u64, total: u64, with_replacement: bool, ) -> f64 { if (with_replacement) { poisson_bounds::get_upper_bound(sample_size_lower_bound as f64) / total as f64 } else { let fraction = sample_size_lower_bound as f64 / total as f64; binomial_bounds::get_upper_bound(1e-4, total, fraction) } } mod poisson_bounds { pub(super) fn get_upper_bound(s: f64) -> f64 { (s + num_std(s) * s.sqrt()).max(1e-10) } #[inline(always)] fn num_std(s: f64) -> f64 { match s { v if v < 6.0 => 12.0, v if v < 16.0 => 9.0, _ => 6.0, } } } mod binomial_bounds { const MIN_SAMPLING_RATE: f64 = 1e-10; pub(super) fn get_upper_bound(delta: f64, n: u64, fraction: f64) -> f64 { let gamma = -delta.log(std::f64::consts::E) / n as f64; let max = MIN_SAMPLING_RATE .max(fraction + gamma + (gamma * gamma + 2.0 * gamma * fraction).sqrt()); max.min(1.0) } }
use std::any::Any; use std::rc::Rc; use downcast_rs::Downcast; use rand::{Rng, SeedableRng}; use rand_distr::{Bernoulli, Distribution, Poisson}; use rand_pcg::Pcg64; use crate::{Data, Deserialize, Serialize}; const DEFAULT_MAX_GAP_SAMPLING_FRACTION: f64 = 0.4; const RNG_EPSILON: f64 = 5e-11; const ROUNDING_EPSILON: f64 = 1e-6; type RSamplerFunc<'a, T> = Box<dyn Fn(Box<dyn Iterator<Item = T>>) -> Vec<T> + 'a>; pub(crate) trait RandomSampler<T: Data>: Send + Sync + Serialize + Deserialize { fn get_sampler(&self) -> RSamplerFunc<T>; } pub(crate) fn get_default_rng() -> Pcg64 { Pcg64::new( 0xcafe_f00d_d15e_a5e5, 0x0a02_bdbf_7bb3_c0a7_ac28_fa16_a64a_bf96, ) } fn get_rng_with_random_seed() -> Pcg64 { Pcg64::seed_from_u64(rand::random::<u64>()) } #[derive(Clone, Serialize, Deserialize)] pub(crate) struct PoissonSampler { fraction: f64, use_gap_sampling_if_possible: bool, prob: f64, } impl PoissonSampler { pub fn new(fraction: f64, use_gap_sampling_if_possible: bool) -> PoissonSampler { let prob = if fraction > 0.0 { fraction } else { 1.0 }; PoissonSampler { fraction, use_gap_sampling_if_possible, prob, } } } impl<T: Data> RandomSampler<T> for PoissonSampler { fn get_sampler(&self) -> RSamplerFunc<T> { Box::new(move |items: Box<dyn Iterator<Item = T>>| -> Vec<T> { if self.fraction <= 0.0 { vec![] } else { let use_gap_sampling = self.use_gap_sampling_if_possible && self.fraction <= DEFAULT_MAX_GAP_SAMPLING_FRACTION; let mut gap_sampling = if use_gap_sampling { Some(GapSamplingReplacement::new(self.fraction, RNG_EPSILON)) } else { None }; let dist = Poisson::new(self.prob).unwrap(); let mut rng = get_rng_with_random_seed(); items .flat_map(move |item| { let count = if use_gap_sampling { gap_sampling.as_mut().unwrap().sample() } else { dist.sample(&mut rng) }; if count != 0 { vec![item; count as usize] } else {
= 1e-10; pub(super) fn get_upper_bound(delta: f64, n: u64, fraction: f64) -> f64 { let gamma = -delta.log(std::f64::consts::E) / n as f64; let max = MIN_SAMPLING_RATE .max(fraction + gamma + (gamma * gamma + 2.0 * gamma * fraction).sqrt()); max.min(1.0) } }
vec![] } }) .collect() } }) } } #[derive(Clone, Serialize, Deserialize)] pub(crate) struct BernoulliSampler { fraction: f64, } impl BernoulliSampler { pub fn new(fraction: f64) -> BernoulliSampler { assert!(fraction >= (0.0 - ROUNDING_EPSILON) && fraction <= (1.0 + ROUNDING_EPSILON)); BernoulliSampler { fraction } } fn sample(&self, gap_sampling: Option<&mut GapSamplingReplacement>, rng: &mut Pcg64) -> u64 { match self.fraction { v if v <= 0.0 => 0, v if v >= 1.0 => 1, v if v <= DEFAULT_MAX_GAP_SAMPLING_FRACTION => gap_sampling.unwrap().sample(), v if rng.gen::<f64>() <= v => 1, _ => 0, } } } impl<T: Data> RandomSampler<T> for BernoulliSampler { fn get_sampler(&self) -> RSamplerFunc<T> { Box::new(move |items: Box<dyn Iterator<Item = T>>| -> Vec<T> { let mut gap_sampling = if self.fraction > 0.0 && self.fraction < 1.0 { Some(GapSamplingReplacement::new(self.fraction, RNG_EPSILON)) } else { None }; let mut rng = get_rng_with_random_seed(); items .filter(move |item| self.sample(gap_sampling.as_mut(), &mut rng) > 0) .collect() }) } } struct GapSamplingReplacement { fraction: f64, epsilon: f64, q: f64, rng: rand_pcg::Pcg64, count_for_dropping: u64, } impl GapSamplingReplacement { fn new(fraction: f64, epsilon: f64) -> GapSamplingReplacement { assert!(fraction > 0.0 && fraction < 1.0); assert!(epsilon > 0.0); let mut sampler = GapSamplingReplacement { q: (-fraction).exp(), fraction, epsilon, rng: get_rng_with_random_seed(), count_for_dropping: 0, }; sampler.advance(); sampler } fn sample(&mut self) -> u64 { if self.count_for_dropping > 0 { self.count_for_dropping -= 1; 0 } else { let r = self.poisson_ge1(); self.advance(); r } } fn poisson_ge1(&mut self) -> u64 { let mut pp: f64 = self.q + ((1.0 - self.q) * self.rng.gen::<f64>()); let mut r = 1; pp *= self.rng.gen::<f64>(); while pp > self.q { r += 1; pp *= self.rng.gen::<f64>() } r } fn advance(&mut self) { let u = self.epsilon.max(self.rng.gen::<f64>()); self.count_for_dropping = (u.log(std::f64::consts::E) / (-self.fraction)) as u64; } } pub(crate) fn compute_fraction_for_sample_size( sample_size_lower_bound: u64, total: u64, with_replacement: bool, ) -> f64 { if (with_replacement) { poisson_bounds::get_upper_bound(sample_size_lower_bound as f64) / total as f64 } else { let fraction = sample_size_lower_bound as f64 / total as f64; binomial_bounds::get_upper_bound(1e-4, total, fraction) } } mod poisson_bounds { pub(super) fn get_upper_bound(s: f64) -> f64 { (s + num_std(s) * s.sqrt()).max(1e-10) } #[inline(always)] fn num_std(s: f64) -> f64 { match s { v if v < 6.0 => 12.0, v if v < 16.0 => 9.0, _ => 6.0, } } } mod binomial_bounds { const MIN_SAMPLING_RATE: f64
random
[ { "content": "pub trait ShuffleDependencyTrait: Serialize + Deserialize + Send + Sync {\n\n fn get_shuffle_id(&self) -> usize;\n\n // fn get_partitioner(&self) -> &dyn PartitionerBox;\n\n fn is_shuffle(&self) -> bool;\n\n fn get_rdd_base(&self) -> Arc<dyn RddBase>;\n\n fn do_shuffle_task(&self...
Rust
crates/wast/src/ast/memory.rs
peterhuene/wasm-tools
bb96b2431f01e5a0e7c83fb1f6bcb08ccb8cb073
use crate::ast::{self, kw}; use crate::parser::{Lookahead1, Parse, Parser, Peek, Result}; #[derive(Debug)] pub struct Memory<'a> { pub span: ast::Span, pub id: Option<ast::Id<'a>>, pub name: Option<ast::NameAnnotation<'a>>, pub exports: ast::InlineExport<'a>, pub kind: MemoryKind<'a>, } #[derive(Debug)] pub enum MemoryKind<'a> { #[allow(missing_docs)] Import { import: ast::InlineImport<'a>, ty: ast::MemoryType, }, Normal(ast::MemoryType), Inline { is_32: bool, data: Vec<DataVal<'a>>, }, } impl<'a> Parse<'a> for Memory<'a> { fn parse(parser: Parser<'a>) -> Result<Self> { let span = parser.parse::<kw::memory>()?.0; let id = parser.parse()?; let name = parser.parse()?; let exports = parser.parse()?; let mut l = parser.lookahead1(); let kind = if let Some(import) = parser.parse()? { MemoryKind::Import { import, ty: parser.parse()?, } } else if l.peek::<ast::LParen>() || parser.peek2::<ast::LParen>() { let is_32 = if parser.parse::<Option<kw::i32>>()?.is_some() { true } else if parser.parse::<Option<kw::i64>>()?.is_some() { false } else { true }; let data = parser.parens(|parser| { parser.parse::<kw::data>()?; let mut data = Vec::new(); while !parser.is_empty() { data.push(parser.parse()?); } Ok(data) })?; MemoryKind::Inline { data, is_32 } } else if l.peek::<u32>() || l.peek::<kw::i32>() || l.peek::<kw::i64>() { MemoryKind::Normal(parser.parse()?) } else { return Err(l.error()); }; Ok(Memory { span, id, name, exports, kind, }) } } #[derive(Debug)] pub struct Data<'a> { pub span: ast::Span, pub id: Option<ast::Id<'a>>, pub name: Option<ast::NameAnnotation<'a>>, pub kind: DataKind<'a>, pub data: Vec<DataVal<'a>>, } #[derive(Debug)] pub enum DataKind<'a> { Passive, Active { memory: ast::ItemRef<'a, kw::memory>, offset: ast::Expression<'a>, }, } impl<'a> Parse<'a> for Data<'a> { fn parse(parser: Parser<'a>) -> Result<Self> { let span = parser.parse::<kw::data>()?.0; let id = parser.parse()?; let name = parser.parse()?; let kind = if parser.peek::<kw::passive>() { parser.parse::<kw::passive>()?; DataKind::Passive } else if parser.peek::<&[u8]>() { DataKind::Passive } else { let memory = if let Some(index) = parser.parse::<Option<ast::IndexOrRef<_>>>()? { index.0 } else { ast::ItemRef::Item { kind: kw::memory(parser.prev_span()), idx: ast::Index::Num(0, span), exports: Vec::new(), #[cfg(wast_check_exhaustive)] visited: false, } }; let offset = parser.parens(|parser| { if parser.peek::<kw::offset>() { parser.parse::<kw::offset>()?; parser.parse() } else { let insn = parser.parse()?; if parser.is_empty() { return Ok(ast::Expression { instrs: [insn].into(), }); } let expr: ast::Expression = parser.parse()?; let mut instrs = Vec::from(expr.instrs); instrs.push(insn); Ok(ast::Expression { instrs: instrs.into(), }) } })?; DataKind::Active { memory, offset } }; let mut data = Vec::new(); while !parser.is_empty() { data.push(parser.parse()?); } Ok(Data { span, id, name, kind, data, }) } } #[derive(Debug)] #[allow(missing_docs)] pub enum DataVal<'a> { String(&'a [u8]), Integral(Vec<u8>), } impl DataVal<'_> { pub fn len(&self) -> usize { match self { DataVal::String(s) => s.len(), DataVal::Integral(s) => s.len(), } } pub fn push_onto(&self, dst: &mut Vec<u8>) { match self { DataVal::String(s) => dst.extend_from_slice(s), DataVal::Integral(s) => dst.extend_from_slice(s), } } } impl<'a> Parse<'a> for DataVal<'a> { fn parse(parser: Parser<'a>) -> Result<Self> { if !parser.peek::<ast::LParen>() { return Ok(DataVal::String(parser.parse()?)); } return parser.parens(|p| { let mut result = Vec::new(); let mut lookahead = p.lookahead1(); let l = &mut lookahead; let r = &mut result; if consume::<kw::i8, i8, _>(p, l, r, |u, v| v.push(u as u8))? || consume::<kw::i16, i16, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))? || consume::<kw::i32, i32, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))? || consume::<kw::i64, i64, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))? || consume::<kw::f32, ast::Float32, _>(p, l, r, |u, v| { v.extend(&u.bits.to_le_bytes()) })? || consume::<kw::f64, ast::Float64, _>(p, l, r, |u, v| { v.extend(&u.bits.to_le_bytes()) })? || consume::<kw::v128, ast::V128Const, _>(p, l, r, |u, v| { v.extend(&u.to_le_bytes()) })? { Ok(DataVal::Integral(result)) } else { Err(lookahead.error()) } }); fn consume<'a, T: Peek + Parse<'a>, U: Parse<'a>, F>( parser: Parser<'a>, lookahead: &mut Lookahead1<'a>, dst: &mut Vec<u8>, push: F, ) -> Result<bool> where F: Fn(U, &mut Vec<u8>), { if !lookahead.peek::<T>() { return Ok(false); } parser.parse::<T>()?; while !parser.is_empty() { let val = parser.parse::<U>()?; push(val, dst); } Ok(true) } } }
use crate::ast::{self, kw}; use crate::parser::{Lookahead1, Parse, Parser, Peek, Result}; #[derive(Debug)] pub struct Memory<'a> { pub span: ast::Span, pub id: Option<ast::Id<'a>>, pub name: Option<ast::NameAnnotation<'a>>, pub exports: ast::InlineExport<'a>, pub kind: MemoryKind<'a>, } #[derive(Debug)] pub enum MemoryKind<'a> { #[allow(missing_docs)] Import { import: ast::InlineImport<'a>, ty: ast::MemoryType, }, Normal(ast::MemoryType), Inline { is_32: bool, data: Vec<DataVal<'a>>, }, } impl<'a> Parse<'a> for Memory<'a> { fn parse(parser: Parser<'a>) -> Result<Self> { let span = parser.parse::<kw::memory>()?.0; let id = parser.parse()?; let name = parser.parse()?; let exports = parser.parse()?; let mut l = parser.lookahead1(); let kind = if let Some(import) = parser.parse()? { MemoryKind::Import { import, ty: parser.parse()?, } } else if l.peek::<ast::LParen>() || parser.peek2::<ast::LParen>() { let is_32 = if parser.parse::<Option<kw::i32>>()?.is_some() { true } else if parser.parse::<Option<kw::i64>>()?.is_some() { false } else { true }; let data = parser.parens(|parser| { parser.parse::<kw::data>()?; let mut data = Vec::new(); while !parser.is_empty() { data.push(parser.parse()?); } Ok(data) })?; MemoryKind::Inline { data, is_32 } } else if l.peek::<u32>() || l.peek::<kw::i32>() || l.peek::<kw::i64>() { MemoryKind::Normal(parser.parse()?) } else { return Err(l.error()); }; Ok(Memory { span, id, name, exports, kind, }) } } #[derive(Debug)] pub struct Data<'a> { pub span: ast::Span, pub id: Option<ast::Id<'a>>, pub name: Option<ast::NameAnnotation<'a>>, pub kind: DataKind<'a>, pub data: Vec<DataVal<'a>>, } #[derive(Debug)] pub enum DataKind<'a> { Passive, Active { memory: ast::ItemRef<'a, kw::memory>, offset: ast::Expression<'a>, }, } impl<'a> Parse<'a> for Data<'a> {
} #[derive(Debug)] #[allow(missing_docs)] pub enum DataVal<'a> { String(&'a [u8]), Integral(Vec<u8>), } impl DataVal<'_> { pub fn len(&self) -> usize { match self { DataVal::String(s) => s.len(), DataVal::Integral(s) => s.len(), } } pub fn push_onto(&self, dst: &mut Vec<u8>) { match self { DataVal::String(s) => dst.extend_from_slice(s), DataVal::Integral(s) => dst.extend_from_slice(s), } } } impl<'a> Parse<'a> for DataVal<'a> { fn parse(parser: Parser<'a>) -> Result<Self> { if !parser.peek::<ast::LParen>() { return Ok(DataVal::String(parser.parse()?)); } return parser.parens(|p| { let mut result = Vec::new(); let mut lookahead = p.lookahead1(); let l = &mut lookahead; let r = &mut result; if consume::<kw::i8, i8, _>(p, l, r, |u, v| v.push(u as u8))? || consume::<kw::i16, i16, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))? || consume::<kw::i32, i32, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))? || consume::<kw::i64, i64, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))? || consume::<kw::f32, ast::Float32, _>(p, l, r, |u, v| { v.extend(&u.bits.to_le_bytes()) })? || consume::<kw::f64, ast::Float64, _>(p, l, r, |u, v| { v.extend(&u.bits.to_le_bytes()) })? || consume::<kw::v128, ast::V128Const, _>(p, l, r, |u, v| { v.extend(&u.to_le_bytes()) })? { Ok(DataVal::Integral(result)) } else { Err(lookahead.error()) } }); fn consume<'a, T: Peek + Parse<'a>, U: Parse<'a>, F>( parser: Parser<'a>, lookahead: &mut Lookahead1<'a>, dst: &mut Vec<u8>, push: F, ) -> Result<bool> where F: Fn(U, &mut Vec<u8>), { if !lookahead.peek::<T>() { return Ok(false); } parser.parse::<T>()?; while !parser.is_empty() { let val = parser.parse::<U>()?; push(val, dst); } Ok(true) } } }
fn parse(parser: Parser<'a>) -> Result<Self> { let span = parser.parse::<kw::data>()?.0; let id = parser.parse()?; let name = parser.parse()?; let kind = if parser.peek::<kw::passive>() { parser.parse::<kw::passive>()?; DataKind::Passive } else if parser.peek::<&[u8]>() { DataKind::Passive } else { let memory = if let Some(index) = parser.parse::<Option<ast::IndexOrRef<_>>>()? { index.0 } else { ast::ItemRef::Item { kind: kw::memory(parser.prev_span()), idx: ast::Index::Num(0, span), exports: Vec::new(), #[cfg(wast_check_exhaustive)] visited: false, } }; let offset = parser.parens(|parser| { if parser.peek::<kw::offset>() { parser.parse::<kw::offset>()?; parser.parse() } else { let insn = parser.parse()?; if parser.is_empty() { return Ok(ast::Expression { instrs: [insn].into(), }); } let expr: ast::Expression = parser.parse()?; let mut instrs = Vec::from(expr.instrs); instrs.push(insn); Ok(ast::Expression { instrs: instrs.into(), }) } })?; DataKind::Active { memory, offset } }; let mut data = Vec::new(); while !parser.is_empty() { data.push(parser.parse()?); } Ok(Data { span, id, name, kind, data, }) }
function_block-full_function
[ { "content": "/// Construct a dummy memory for the given memory type.\n\npub fn dummy_memory<T>(store: &mut Store<T>, ty: MemoryType) -> Result<Memory> {\n\n Memory::new(store, ty)\n\n}\n", "file_path": "crates/fuzz-stats/src/dummy.rs", "rank": 0, "score": 415256.02069778426 }, { "content...
Rust
http/src/request/channel/invite/create_invite.rs
dawn-rs/dawn
294f80cc0ab556925c53bb6cf8d1297e150f49bc
use crate::{ client::Client, error::Error as HttpError, request::{self, AuditLogReason, Request, TryIntoRequest}, response::ResponseFuture, routing::Route, }; use serde::Serialize; use twilight_model::{ id::{ marker::{ApplicationMarker, ChannelMarker, UserMarker}, Id, }, invite::{Invite, TargetType}, }; use twilight_validate::request::{ audit_reason as validate_audit_reason, invite_max_age as validate_invite_max_age, invite_max_uses as validate_invite_max_uses, ValidationError, }; #[derive(Serialize)] struct CreateInviteFields { #[serde(skip_serializing_if = "Option::is_none")] max_age: Option<u32>, #[serde(skip_serializing_if = "Option::is_none")] max_uses: Option<u16>, #[serde(skip_serializing_if = "Option::is_none")] temporary: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] target_application_id: Option<Id<ApplicationMarker>>, #[serde(skip_serializing_if = "Option::is_none")] target_user_id: Option<Id<UserMarker>>, #[serde(skip_serializing_if = "Option::is_none")] target_type: Option<TargetType>, #[serde(skip_serializing_if = "Option::is_none")] unique: Option<bool>, } #[must_use = "requests must be configured and executed"] pub struct CreateInvite<'a> { channel_id: Id<ChannelMarker>, fields: CreateInviteFields, http: &'a Client, reason: Option<&'a str>, } impl<'a> CreateInvite<'a> { pub(crate) const fn new(http: &'a Client, channel_id: Id<ChannelMarker>) -> Self { Self { channel_id, fields: CreateInviteFields { max_age: None, max_uses: None, temporary: None, target_application_id: None, target_user_id: None, target_type: None, unique: None, }, http, reason: None, } } pub const fn max_age(mut self, max_age: u32) -> Result<Self, ValidationError> { if let Err(source) = validate_invite_max_age(max_age) { return Err(source); } self.fields.max_age = Some(max_age); Ok(self) } pub const fn max_uses(mut self, max_uses: u16) -> Result<Self, ValidationError> { if let Err(source) = validate_invite_max_uses(max_uses) { return Err(source); } self.fields.max_uses = Some(max_uses); Ok(self) } pub const fn target_application_id( mut self, target_application_id: Id<ApplicationMarker>, ) -> Self { self.fields.target_application_id = Some(target_application_id); self } pub const fn target_user_id(mut self, target_user_id: Id<UserMarker>) -> Self { self.fields.target_user_id = Some(target_user_id); self } pub const fn target_type(mut self, target_type: TargetType) -> Self { self.fields.target_type = Some(target_type); self } pub const fn temporary(mut self, temporary: bool) -> Self { self.fields.temporary = Some(temporary); self } pub const fn unique(mut self, unique: bool) -> Self { self.fields.unique = Some(unique); self } pub fn exec(self) -> ResponseFuture<Invite> { let http = self.http; match self.try_into_request() { Ok(request) => http.request(request), Err(source) => ResponseFuture::error(source), } } } impl<'a> AuditLogReason<'a> for CreateInvite<'a> { fn reason(mut self, reason: &'a str) -> Result<Self, ValidationError> { validate_audit_reason(reason)?; self.reason.replace(reason); Ok(self) } } impl TryIntoRequest for CreateInvite<'_> { fn try_into_request(self) -> Result<Request, HttpError> { let mut request = Request::builder(&Route::CreateInvite { channel_id: self.channel_id.get(), }); request = request.json(&self.fields)?; if let Some(reason) = self.reason { let header = request::audit_header(reason)?; request = request.headers(header); } Ok(request.build()) } } #[cfg(test)] mod tests { use super::CreateInvite; use crate::Client; use std::error::Error; use twilight_model::id::Id; #[test] fn max_age() -> Result<(), Box<dyn Error>> { let client = Client::new("foo".to_owned()); let mut builder = CreateInvite::new(&client, Id::new(1)).max_age(0)?; assert_eq!(Some(0), builder.fields.max_age); builder = builder.max_age(604_800)?; assert_eq!(Some(604_800), builder.fields.max_age); assert!(builder.max_age(604_801).is_err()); Ok(()) } #[test] fn max_uses() -> Result<(), Box<dyn Error>> { let client = Client::new("foo".to_owned()); let mut builder = CreateInvite::new(&client, Id::new(1)).max_uses(0)?; assert_eq!(Some(0), builder.fields.max_uses); builder = builder.max_uses(100)?; assert_eq!(Some(100), builder.fields.max_uses); assert!(builder.max_uses(101).is_err()); Ok(()) } }
use crate::{ client::Client, error::Error as HttpError, request::{self, AuditLogReason, Request, TryIntoRequest}, response::ResponseFuture, routing::Route, }; use serde::Serialize; use twilight_model::{ id::{ marker::{ApplicationMarker, ChannelMarker, UserMarker}, Id, }, invite::{Invite, TargetType}, }; use twilight_validate::request::{ audit_reason as validate_audit_reason, invite_max_age as validate_invite_max_age, invite_max_uses as validate_invite_max_uses, ValidationError, }; #[derive(Serialize)] struct CreateInviteFields { #[serde(skip_serializing_if = "Option::is_none")] max_age: Option<u32>, #[serde(skip_serializing_if = "Option::is_none")] max_uses: Option<u16>, #[serde(skip_serializing_if = "Option::is_none")] temporary: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] target_application_id: Option<Id<ApplicationMarker>>, #[serde(skip_serializing_if = "Option::is_none")] target_user_id: Option<Id<UserMarker>>, #[serde(skip_serializing_if = "Option::is_
lidationError> { if let Err(source) = validate_invite_max_age(max_age) { return Err(source); } self.fields.max_age = Some(max_age); Ok(self) } pub const fn max_uses(mut self, max_uses: u16) -> Result<Self, ValidationError> { if let Err(source) = validate_invite_max_uses(max_uses) { return Err(source); } self.fields.max_uses = Some(max_uses); Ok(self) } pub const fn target_application_id( mut self, target_application_id: Id<ApplicationMarker>, ) -> Self { self.fields.target_application_id = Some(target_application_id); self } pub const fn target_user_id(mut self, target_user_id: Id<UserMarker>) -> Self { self.fields.target_user_id = Some(target_user_id); self } pub const fn target_type(mut self, target_type: TargetType) -> Self { self.fields.target_type = Some(target_type); self } pub const fn temporary(mut self, temporary: bool) -> Self { self.fields.temporary = Some(temporary); self } pub const fn unique(mut self, unique: bool) -> Self { self.fields.unique = Some(unique); self } pub fn exec(self) -> ResponseFuture<Invite> { let http = self.http; match self.try_into_request() { Ok(request) => http.request(request), Err(source) => ResponseFuture::error(source), } } } impl<'a> AuditLogReason<'a> for CreateInvite<'a> { fn reason(mut self, reason: &'a str) -> Result<Self, ValidationError> { validate_audit_reason(reason)?; self.reason.replace(reason); Ok(self) } } impl TryIntoRequest for CreateInvite<'_> { fn try_into_request(self) -> Result<Request, HttpError> { let mut request = Request::builder(&Route::CreateInvite { channel_id: self.channel_id.get(), }); request = request.json(&self.fields)?; if let Some(reason) = self.reason { let header = request::audit_header(reason)?; request = request.headers(header); } Ok(request.build()) } } #[cfg(test)] mod tests { use super::CreateInvite; use crate::Client; use std::error::Error; use twilight_model::id::Id; #[test] fn max_age() -> Result<(), Box<dyn Error>> { let client = Client::new("foo".to_owned()); let mut builder = CreateInvite::new(&client, Id::new(1)).max_age(0)?; assert_eq!(Some(0), builder.fields.max_age); builder = builder.max_age(604_800)?; assert_eq!(Some(604_800), builder.fields.max_age); assert!(builder.max_age(604_801).is_err()); Ok(()) } #[test] fn max_uses() -> Result<(), Box<dyn Error>> { let client = Client::new("foo".to_owned()); let mut builder = CreateInvite::new(&client, Id::new(1)).max_uses(0)?; assert_eq!(Some(0), builder.fields.max_uses); builder = builder.max_uses(100)?; assert_eq!(Some(100), builder.fields.max_uses); assert!(builder.max_uses(101).is_err()); Ok(()) } }
none")] target_type: Option<TargetType>, #[serde(skip_serializing_if = "Option::is_none")] unique: Option<bool>, } #[must_use = "requests must be configured and executed"] pub struct CreateInvite<'a> { channel_id: Id<ChannelMarker>, fields: CreateInviteFields, http: &'a Client, reason: Option<&'a str>, } impl<'a> CreateInvite<'a> { pub(crate) const fn new(http: &'a Client, channel_id: Id<ChannelMarker>) -> Self { Self { channel_id, fields: CreateInviteFields { max_age: None, max_uses: None, temporary: None, target_application_id: None, target_user_id: None, target_type: None, unique: None, }, http, reason: None, } } pub const fn max_age(mut self, max_age: u32) -> Result<Self, Va
random
[ { "content": "struct PresenceVisitor(Id<GuildMarker>);\n\n\n\nimpl<'de> Visitor<'de> for PresenceVisitor {\n\n type Value = Presence;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"Presence struct\")\n\n }\n\n\n\n fn visit_map<M: MapAccess<'de>>(self, map:...
Rust
src/cli/src/cluster/install/tls.rs
simlay/fluvio
a42283200e667223d3a52b217d266db8927db4eb
use std::path::PathBuf; use tracing::debug; use structopt::StructOpt; use fluvio::config::{TlsPolicy, TlsPaths}; use std::convert::TryFrom; use crate::CliError; #[derive(Debug, StructOpt)] pub struct TlsOpt { #[structopt(long)] pub tls: bool, #[structopt(long)] pub domain: Option<String>, #[structopt(long, parse(from_os_str))] pub ca_cert: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub client_cert: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub client_key: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub server_cert: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub server_key: Option<PathBuf>, } impl TryFrom<TlsOpt> for (TlsPolicy, TlsPolicy) { type Error = CliError; fn try_from(opt: TlsOpt) -> Result<Self, Self::Error> { if !opt.tls { debug!("no optional tls"); return Ok((TlsPolicy::Disabled, TlsPolicy::Disabled)); } let policies = (|| -> Option<(TlsPolicy, TlsPolicy)> { let domain = opt.domain?; let ca_cert = opt.ca_cert?; let client_cert = opt.client_cert?; let client_key = opt.client_key?; let server_cert = opt.server_cert?; let server_key = opt.server_key?; let server_policy = TlsPolicy::from(TlsPaths { domain: domain.clone(), ca_cert: ca_cert.clone(), cert: server_cert, key: server_key, }); let client_policy = TlsPolicy::from(TlsPaths { domain, ca_cert, cert: client_cert, key: client_key, }); Some((client_policy, server_policy)) })(); policies.ok_or_else(|| { CliError::Other( "Missing required args after --tls:\ --domain, --ca-cert, --client-cert, --client-key, --server-cert, --server-key" .to_string(), ) }) } } #[cfg(test)] mod tests { use super::*; use std::convert::TryInto; #[test] fn test_from_opt() { let tls_opt = TlsOpt::from_iter(vec![ "test", "--tls", "--domain", "fluvio.io", "--ca-cert", "/tmp/certs/ca.crt", "--client-cert", "/tmp/certs/client.crt", "--client-key", "/tmp/certs/client.key", "--server-cert", "/tmp/certs/server.crt", "--server-key", "/tmp/certs/server.key", ]); let (client, server): (TlsPolicy, TlsPolicy) = tls_opt.try_into().unwrap(); use fluvio::config::{TlsPolicy::*, TlsConfig::*}; match (client, server) { (Verified(Files(client_paths)), Verified(Files(server_paths))) => { assert_eq!(client_paths.domain, "fluvio.io"); assert_eq!(client_paths.ca_cert, PathBuf::from("/tmp/certs/ca.crt")); assert_eq!(client_paths.cert, PathBuf::from("/tmp/certs/client.crt")); assert_eq!(client_paths.key, PathBuf::from("/tmp/certs/client.key")); assert_eq!(server_paths.domain, "fluvio.io"); assert_eq!(server_paths.ca_cert, PathBuf::from("/tmp/certs/ca.crt")); assert_eq!(server_paths.cert, PathBuf::from("/tmp/certs/server.crt")); assert_eq!(server_paths.key, PathBuf::from("/tmp/certs/server.key")); } _ => panic!("Failed to parse TlsProfiles from TlsOpt"), } } #[test] fn test_missing_opts() { let tls_opt: TlsOpt = TlsOpt::from_iter(vec![ "test", "--tls", ]); let result: Result<(TlsPolicy, TlsPolicy), _> = tls_opt.try_into(); assert!(result.is_err()); } }
use std::path::PathBuf; use tracing::debug; use structopt::StructOpt; use fluvio::config::{TlsPolicy, TlsPaths}; use std::convert::TryFrom; use crate::CliError; #[derive(Debug, StructOpt)] pub struct TlsOpt { #[structopt(long)] pub tls: bool, #[structopt(long)] pub domain: Option<String>, #[structopt(long, parse(from_os_str))] pub ca_cert: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub client_cert: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub client_key: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub server_cert: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub server_key
d, TlsPolicy::Disabled)); } let policies = (|| -> Option<(TlsPolicy, TlsPolicy)> { let domain = opt.domain?; let ca_cert = opt.ca_cert?; let client_cert = opt.client_cert?; let client_key = opt.client_key?; let server_cert = opt.server_cert?; let server_key = opt.server_key?; let server_policy = TlsPolicy::from(TlsPaths { domain: domain.clone(), ca_cert: ca_cert.clone(), cert: server_cert, key: server_key, }); let client_policy = TlsPolicy::from(TlsPaths { domain, ca_cert, cert: client_cert, key: client_key, }); Some((client_policy, server_policy)) })(); policies.ok_or_else(|| { CliError::Other( "Missing required args after --tls:\ --domain, --ca-cert, --client-cert, --client-key, --server-cert, --server-key" .to_string(), ) }) } } #[cfg(test)] mod tests { use super::*; use std::convert::TryInto; #[test] fn test_from_opt() { let tls_opt = TlsOpt::from_iter(vec![ "test", "--tls", "--domain", "fluvio.io", "--ca-cert", "/tmp/certs/ca.crt", "--client-cert", "/tmp/certs/client.crt", "--client-key", "/tmp/certs/client.key", "--server-cert", "/tmp/certs/server.crt", "--server-key", "/tmp/certs/server.key", ]); let (client, server): (TlsPolicy, TlsPolicy) = tls_opt.try_into().unwrap(); use fluvio::config::{TlsPolicy::*, TlsConfig::*}; match (client, server) { (Verified(Files(client_paths)), Verified(Files(server_paths))) => { assert_eq!(client_paths.domain, "fluvio.io"); assert_eq!(client_paths.ca_cert, PathBuf::from("/tmp/certs/ca.crt")); assert_eq!(client_paths.cert, PathBuf::from("/tmp/certs/client.crt")); assert_eq!(client_paths.key, PathBuf::from("/tmp/certs/client.key")); assert_eq!(server_paths.domain, "fluvio.io"); assert_eq!(server_paths.ca_cert, PathBuf::from("/tmp/certs/ca.crt")); assert_eq!(server_paths.cert, PathBuf::from("/tmp/certs/server.crt")); assert_eq!(server_paths.key, PathBuf::from("/tmp/certs/server.key")); } _ => panic!("Failed to parse TlsProfiles from TlsOpt"), } } #[test] fn test_missing_opts() { let tls_opt: TlsOpt = TlsOpt::from_iter(vec![ "test", "--tls", ]); let result: Result<(TlsPolicy, TlsPolicy), _> = tls_opt.try_into(); assert!(result.is_err()); } }
: Option<PathBuf>, } impl TryFrom<TlsOpt> for (TlsPolicy, TlsPolicy) { type Error = CliError; fn try_from(opt: TlsOpt) -> Result<Self, Self::Error> { if !opt.tls { debug!("no optional tls"); return Ok((TlsPolicy::Disable
random
[ { "content": "#[derive(Debug, StructOpt)]\n\nstruct VersionCmd {}\n\n\n", "file_path": "src/cli/src/root_cli.rs", "rank": 0, "score": 78096.27395499004 }, { "content": "#[derive(Debug, StructOpt)]\n\nstruct CompletionOpt {\n\n #[structopt(long, default_value = \"fluvio\")]\n\n name: St...
Rust
eventually-redis/tests/store.rs
J3A/eventually-rs
866a471479a8c2781966339287a4e57ca9838b38
use std::sync::Arc; use eventually::inmemory::Projector; use eventually::store::{Expected, Persisted, Select}; use eventually::sync::RwLock; use eventually::{EventStore, EventSubscriber, Projection}; use eventually_redis::{Builder, EventStore as RedisEventStore}; use async_trait::async_trait; use futures::stream::TryStreamExt; use serde::{Deserialize, Serialize}; use testcontainers::core::Docker; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] enum Event { A, B, C, } #[tokio::test] async fn it_works() { let docker = testcontainers::clients::Cli::default(); let redis_image = testcontainers::images::redis::Redis::default(); let node = docker.run(redis_image); let dsn = format!("redis://127.0.0.1:{}/", node.get_host_port(6379).unwrap()); let client = redis::Client::open(dsn).expect("failed to connect to Redis"); let builder = Builder::new(client) .stream_page_size(128) .source_name("test-stream"); let builder_clone = builder.clone(); tokio::spawn(async move { builder_clone .build_subscriber::<String, Event>() .subscribe_all() .try_for_each(|_event| async { Ok(()) }) .await .unwrap(); }); let mut store: RedisEventStore<String, Event> = builder .build_store() .await .expect("failed to create redis connection"); for chunk in 0..1000 { store .append( "test-source-1".to_owned(), Expected::Any, vec![Event::A, Event::B, Event::C], ) .await .unwrap(); store .append( "test-source-2".to_owned(), Expected::Exact(chunk * 2), vec![Event::B, Event::A], ) .await .unwrap(); } let now = std::time::SystemTime::now(); assert_eq!( 5000usize, store .stream_all(Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap() ); println!("Stream $all took {:?}", now.elapsed().unwrap()); assert_eq!( 3000usize, store .stream("test-source-1".to_owned(), Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap() ); assert_eq!( 2000usize, store .stream("test-source-2".to_owned(), Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap() ); } #[tokio::test] async fn it_creates_persistent_subscription_successfully() { let docker = testcontainers::clients::Cli::default(); let redis_image = testcontainers::images::redis::Redis::default(); let node = docker.run(redis_image); let dsn = format!("redis://127.0.0.1:{}/", node.get_host_port(6379).unwrap()); let client = redis::Client::open(dsn).expect("failed to connect to Redis"); let events_count: usize = 3; let builder = Builder::new(client) .stream_page_size(128) .source_name("test-stream"); let builder_clone = builder.clone(); let subscription = builder .build_persistent_subscription::<String, Event>("subscription") .await .unwrap(); builder .build_persistent_subscription::<String, Event>("subscription") .await .unwrap(); #[derive(Debug, Default)] struct Counter(usize); #[async_trait] impl Projection for Counter { type SourceId = String; type Event = Event; type Error = std::convert::Infallible; async fn project( &mut self, _event: Persisted<Self::SourceId, Self::Event>, ) -> Result<(), Self::Error> { self.0 += 1; Ok(()) } } let counter = Arc::new(RwLock::new(Counter::default())); let mut projector = Projector::new(counter.clone(), subscription); tokio::spawn(async move { projector.run().await.unwrap(); }); let mut store = builder_clone .build_store::<String, Event>() .await .expect("create event store"); for i in 0..events_count { store .append( format!("test-subscription-{}", i), Expected::Any, vec![Event::A, Event::B, Event::C], ) .await .unwrap(); } let size = store .stream_all(Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap(); tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; assert_eq!(size, counter.read().await.0); }
use std::sync::Arc; use eventually::inmemory::Projector; use eventually::store::{Expected, Persisted, Select}; use eventually::sync::RwLock; use eventually::{EventStore, EventSubscriber, Projection}; use eventually_redis::{Builder, EventStore as RedisEventStore}; use async_trait::async_trait; use futures::stream::TryStreamExt; use serde::{Deserialize, Serialize}; use testcontainers::core::Docker; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] enum Event { A, B, C, } #[tokio::test] async fn it_works() { let docker = testcontainers::clients::Cli::default(); let redis_image = testcontainers::images::redis::Redis::default(); let node = docker.run(redis_image); let dsn = format!("redis://127.0.0.1:{}/", node.get_host_port(6379).unwrap()); let client = redis::Client::open(dsn).expect("failed to connect to Redis"); let builder = Builder::new(client) .stream_page_size(128) .source_name("test-stream"); let builder_clone = builder.clone(); tokio::spawn(async move { builder_clone .build_subscriber::<String, Event>() .subscribe_all() .try_for_each(|_event| async { Ok(()) }) .await .unwrap(); }); let mut store: RedisEventStore<String, Event> = builder .build_store() .await .expect("failed to create redis connection"); for chunk in 0..1000 { store .append( "test-source-1".to_owned(), Expected::Any, vec![Event::A, Event::B, Event::C], ) .await .unwrap(); store .append( "test-source-2".to_owned(), Expected::Exact(chunk * 2), vec![Event::B, Event::A], ) .await .unwrap(); } let now = std::time::SystemTime::now(); assert_eq!( 5000usize, store .stream_all(Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap() ); println!("Stream $all took {:?}", now.elapsed().unwrap()); assert_eq!( 3000usize, store .stream("test-source-1".to_owned(), Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap() ); assert_eq!( 2000usize, store .stream("test-source-2".to_owned(), Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap() ); } #[tokio::test] async fn it_creates_persistent_subscription_successfully() { let docker = testcontainers::clients::Cli::default(); let redis_image = testcontainers::images::redis::Redis::default(); let node = docker.run(redis_image); let dsn = for
mat!("redis://127.0.0.1:{}/", node.get_host_port(6379).unwrap()); let client = redis::Client::open(dsn).expect("failed to connect to Redis"); let events_count: usize = 3; let builder = Builder::new(client) .stream_page_size(128) .source_name("test-stream"); let builder_clone = builder.clone(); let subscription = builder .build_persistent_subscription::<String, Event>("subscription") .await .unwrap(); builder .build_persistent_subscription::<String, Event>("subscription") .await .unwrap(); #[derive(Debug, Default)] struct Counter(usize); #[async_trait] impl Projection for Counter { type SourceId = String; type Event = Event; type Error = std::convert::Infallible; async fn project( &mut self, _event: Persisted<Self::SourceId, Self::Event>, ) -> Result<(), Self::Error> { self.0 += 1; Ok(()) } } let counter = Arc::new(RwLock::new(Counter::default())); let mut projector = Projector::new(counter.clone(), subscription); tokio::spawn(async move { projector.run().await.unwrap(); }); let mut store = builder_clone .build_store::<String, Event>() .await .expect("create event store"); for i in 0..events_count { store .append( format!("test-subscription-{}", i), Expected::Any, vec![Event::A, Event::B, Event::C], ) .await .unwrap(); } let size = store .stream_all(Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap(); tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; assert_eq!(size, counter.read().await.0); }
function_block-function_prefixed
[ { "content": "#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\n\nenum Event {\n\n A,\n\n B,\n\n C,\n\n}\n\n\n\n#[tokio::test]\n\nasync fn different_types_can_share_id() {\n\n let docker = testcontainers::clients::Cli::default();\n\n let postgres_image = testcontainers::images::post...