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
game_plugin/src/actions.rs
NiklasEi/ld49
1fc925339de6d0aa64983d31186cf1ba932c595c
use crate::GameState; use bevy::prelude::*; pub struct ActionsPlugin; impl Plugin for ActionsPlugin { fn build(&self, app: &mut AppBuilder) { app.init_resource::<Actions>().add_system_set( SystemSet::on_update(GameState::InLevel).with_system(set_movement_actions.system()), ); } } #[derive(Default, Debug)] pub struct Actions { pub jump: bool, pub paddling: Option<f32>, pub head_balance: Option<f32>, pub restart: bool, } fn set_movement_actions(mut actions: ResMut<Actions>, keyboard_input: Res<Input<KeyCode>>) { if GameControl::PaddleBackward.just_released(&keyboard_input) || GameControl::PaddleBackward.pressed(&keyboard_input) || GameControl::PaddleForward.just_released(&keyboard_input) || GameControl::PaddleForward.pressed(&keyboard_input) { let mut paddling = actions.paddling.unwrap_or(0.); if GameControl::PaddleForward.just_released(&keyboard_input) || GameControl::PaddleBackward.just_released(&keyboard_input) { if GameControl::PaddleForward.pressed(&keyboard_input) { paddling = 1.; } else if GameControl::PaddleBackward.pressed(&keyboard_input) { paddling = -1.; } else { paddling = 0.; } } else if GameControl::PaddleForward.just_pressed(&keyboard_input) { paddling = 1.; } else if GameControl::PaddleBackward.just_pressed(&keyboard_input) { paddling = -1.; } actions.paddling = Some(paddling); } else { actions.paddling = None; } if GameControl::BalanceForward.just_released(&keyboard_input) || GameControl::BalanceForward.pressed(&keyboard_input) || GameControl::BalanceBackward.just_released(&keyboard_input) || GameControl::BalanceBackward.pressed(&keyboard_input) { let mut head_balance = actions.head_balance.unwrap_or(0.); if GameControl::BalanceForward.just_released(&keyboard_input) || GameControl::BalanceBackward.just_released(&keyboard_input) { if GameControl::BalanceForward.pressed(&keyboard_input) { head_balance = 1.; } else if GameControl::BalanceBackward.pressed(&keyboard_input) { head_balance = -1.; } else { head_balance = 0.; } } else if GameControl::BalanceForward.just_pressed(&keyboard_input) { head_balance = 1.; } else if GameControl::BalanceBackward.just_pressed(&keyboard_input) { head_balance = -1.; } actions.head_balance = Some(head_balance); } else { actions.head_balance = None; } actions.jump = GameControl::Jump.just_pressed(&keyboard_input); actions.restart = GameControl::Restart.just_pressed(&keyboard_input); } enum GameControl { BalanceForward, BalanceBackward, PaddleBackward, PaddleForward, Restart, Jump, } impl GameControl { fn just_released(&self, keyboard_input: &Res<Input<KeyCode>>) -> bool { match self { GameControl::BalanceForward => keyboard_input.just_released(KeyCode::Right), GameControl::BalanceBackward => keyboard_input.just_released(KeyCode::Left), GameControl::PaddleBackward => keyboard_input.just_released(KeyCode::A), GameControl::PaddleForward => keyboard_input.just_released(KeyCode::D), GameControl::Jump => keyboard_input.just_released(KeyCode::Space), GameControl::Restart => keyboard_input.just_released(KeyCode::R), } } fn pressed(&self, keyboard_input: &Res<Input<KeyCode>>) -> bool { match self { GameControl::BalanceForward => keyboard_input.pressed(KeyCode::Right), GameControl::BalanceBackward => keyboard_input.pressed(KeyCode::Left), GameControl::PaddleBackward => keyboard_input.pressed(KeyCode::A), GameControl::PaddleForward => keyboard_input.pressed(KeyCode::D), GameControl::Jump => keyboard_input.pressed(KeyCode::Space), GameControl::Restart => keyboard_input.pressed(KeyCode::R), } } fn just_pressed(&self, keyboard_input: &Res<Input<KeyCode>>) -> bool { match self { GameControl::BalanceForward => keyboard_input.just_pressed(KeyCode::Right), GameControl::BalanceBackward => keyboard_input.just_pressed(KeyCode::Left), GameControl::PaddleBackward => keyboard_input.just_pressed(KeyCode::A), GameControl::PaddleForward => keyboard_input.just_pressed(KeyCode::D), GameControl::Jump => keyboard_input.just_pressed(KeyCode::Space), GameControl::Restart => keyboard_input.just_pressed(KeyCode::R), } } }
use crate::GameState; use bevy::prelude::*; pub struct ActionsPlugin; impl Plugin for ActionsPlugin { fn build(&self, app: &mut AppBuilder) { app.init_resource::<Actions>().add_system_set( SystemSet::on_update(GameState::InLevel).with_system(set_movement_actions.system()), ); } } #[derive(Default, Debug)] pub struct Actions { pub jump: bool, pub paddling: Option<f32>, pub head_balance: Option<f32>, pub restart: bool, } fn set_movement_actions(mut actions: ResMut<Actions>, keyboard_input: Res<Input<KeyCode>>) { if GameControl::PaddleBackward.just_released(&keyboard_input) || GameControl::PaddleBackward.pressed(&keyboard_input) || GameControl::PaddleForward.just_released(&keyboard_input) || GameControl::PaddleForward.pressed(&keyboard_input) { let mut paddling = actions.paddling.unwrap_or(0.); if GameControl::PaddleForward.just_released(&keyboard_input) || GameControl::PaddleBackward.just_released(&keyboard_input) { if GameControl::PaddleForward.pressed(&keyboard_input) { paddling = 1.; } else if GameControl::PaddleBackward.pressed(&keyboard_input) { paddling = -1.; } else { paddling = 0.; } } else if GameControl::PaddleForward.just_pressed(&keyboard_input) { paddling = 1.; } else if GameControl::PaddleBackward.just_pressed(&keyboard_input) { paddling = -1.; } actions.paddling = Some(paddling); } else { actions.paddling = None; } if GameControl::BalanceForward.just_released(&keyboard_input) || GameControl::BalanceForward.pressed(&keyboard_input) || GameControl::BalanceBackward.just_released(&keyboard_input) || GameControl::BalanceBackward.pressed(&keyboard_input) { let mut head_balance
actions.head_balance = Some(head_balance); } else { actions.head_balance = None; } actions.jump = GameControl::Jump.just_pressed(&keyboard_input); actions.restart = GameControl::Restart.just_pressed(&keyboard_input); } enum GameControl { BalanceForward, BalanceBackward, PaddleBackward, PaddleForward, Restart, Jump, } impl GameControl { fn just_released(&self, keyboard_input: &Res<Input<KeyCode>>) -> bool { match self { GameControl::BalanceForward => keyboard_input.just_released(KeyCode::Right), GameControl::BalanceBackward => keyboard_input.just_released(KeyCode::Left), GameControl::PaddleBackward => keyboard_input.just_released(KeyCode::A), GameControl::PaddleForward => keyboard_input.just_released(KeyCode::D), GameControl::Jump => keyboard_input.just_released(KeyCode::Space), GameControl::Restart => keyboard_input.just_released(KeyCode::R), } } fn pressed(&self, keyboard_input: &Res<Input<KeyCode>>) -> bool { match self { GameControl::BalanceForward => keyboard_input.pressed(KeyCode::Right), GameControl::BalanceBackward => keyboard_input.pressed(KeyCode::Left), GameControl::PaddleBackward => keyboard_input.pressed(KeyCode::A), GameControl::PaddleForward => keyboard_input.pressed(KeyCode::D), GameControl::Jump => keyboard_input.pressed(KeyCode::Space), GameControl::Restart => keyboard_input.pressed(KeyCode::R), } } fn just_pressed(&self, keyboard_input: &Res<Input<KeyCode>>) -> bool { match self { GameControl::BalanceForward => keyboard_input.just_pressed(KeyCode::Right), GameControl::BalanceBackward => keyboard_input.just_pressed(KeyCode::Left), GameControl::PaddleBackward => keyboard_input.just_pressed(KeyCode::A), GameControl::PaddleForward => keyboard_input.just_pressed(KeyCode::D), GameControl::Jump => keyboard_input.just_pressed(KeyCode::Space), GameControl::Restart => keyboard_input.just_pressed(KeyCode::R), } } }
= actions.head_balance.unwrap_or(0.); if GameControl::BalanceForward.just_released(&keyboard_input) || GameControl::BalanceBackward.just_released(&keyboard_input) { if GameControl::BalanceForward.pressed(&keyboard_input) { head_balance = 1.; } else if GameControl::BalanceBackward.pressed(&keyboard_input) { head_balance = -1.; } else { head_balance = 0.; } } else if GameControl::BalanceForward.just_pressed(&keyboard_input) { head_balance = 1.; } else if GameControl::BalanceBackward.just_pressed(&keyboard_input) { head_balance = -1.; }
function_block-random_span
[ { "content": "fn jump(\n\n actions: Res<Actions>,\n\n mut wheel_query: Query<\n\n (Entity, &mut RigidBodyVelocity, &Transform),\n\n (With<Wheel>, Without<Body>),\n\n >,\n\n mut jump_block: ResMut<JumpBlock>,\n\n mut body_query: Query<&Transform, (With<Body>, Without<Wheel>)>,\n\n ...
Rust
src/librustc_incremental/persist/dirty_clean.rs
killerswan/rust
e703b33e3e03d1078c8825e1f64ecfb45884f5cb
use super::directory::RetracedDefIdDirectory; use super::load::DirtyNodes; use rustc::dep_graph::{DepGraphQuery, DepNode}; use rustc::hir; use rustc::hir::def_id::DefId; use rustc::hir::itemlikevisit::ItemLikeVisitor; use rustc::hir::intravisit; use rustc::ich::{Fingerprint, ATTR_DIRTY, ATTR_CLEAN, ATTR_DIRTY_METADATA, ATTR_CLEAN_METADATA}; use syntax::ast::{self, Attribute, NestedMetaItem}; use rustc_data_structures::fx::{FxHashSet, FxHashMap}; use syntax_pos::Span; use rustc::ty::TyCtxt; const LABEL: &'static str = "label"; const CFG: &'static str = "cfg"; pub fn check_dirty_clean_annotations<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, dirty_inputs: &DirtyNodes, retraced: &RetracedDefIdDirectory) { if !tcx.sess.features.borrow().rustc_attrs { return; } let _ignore = tcx.dep_graph.in_ignore(); let dirty_inputs: FxHashSet<DepNode<DefId>> = dirty_inputs.keys() .filter_map(|d| retraced.map(d)) .collect(); let query = tcx.dep_graph.query(); debug!("query-nodes: {:?}", query.nodes()); let krate = tcx.hir.krate(); let mut dirty_clean_visitor = DirtyCleanVisitor { tcx: tcx, query: &query, dirty_inputs: dirty_inputs, checked_attrs: FxHashSet(), }; krate.visit_all_item_likes(&mut dirty_clean_visitor); let mut all_attrs = FindAllAttrs { tcx: tcx, attr_names: vec![ATTR_DIRTY, ATTR_CLEAN], found_attrs: vec![], }; intravisit::walk_crate(&mut all_attrs, krate); all_attrs.report_unchecked_attrs(&dirty_clean_visitor.checked_attrs); } pub struct DirtyCleanVisitor<'a, 'tcx:'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, query: &'a DepGraphQuery<DefId>, dirty_inputs: FxHashSet<DepNode<DefId>>, checked_attrs: FxHashSet<ast::AttrId>, } impl<'a, 'tcx> DirtyCleanVisitor<'a, 'tcx> { fn dep_node(&self, attr: &Attribute, def_id: DefId) -> DepNode<DefId> { for item in attr.meta_item_list().unwrap_or_else(Vec::new) { if item.check_name(LABEL) { let value = expect_associated_value(self.tcx, &item); match DepNode::from_label_string(&value.as_str(), def_id) { Ok(def_id) => return def_id, Err(()) => { self.tcx.sess.span_fatal( item.span, &format!("dep-node label `{}` not recognized", value)); } } } } self.tcx.sess.span_fatal(attr.span, "no `label` found"); } fn dep_node_str(&self, dep_node: &DepNode<DefId>) -> DepNode<String> { dep_node.map_def(|&def_id| Some(self.tcx.item_path_str(def_id))).unwrap() } fn assert_dirty(&self, item_span: Span, dep_node: DepNode<DefId>) { debug!("assert_dirty({:?})", dep_node); match dep_node { DepNode::Krate | DepNode::Hir(_) | DepNode::HirBody(_) => { if !self.dirty_inputs.contains(&dep_node) { let dep_node_str = self.dep_node_str(&dep_node); self.tcx.sess.span_err( item_span, &format!("`{:?}` not found in dirty set, but should be dirty", dep_node_str)); } } _ => { if self.query.contains_node(&dep_node) { let dep_node_str = self.dep_node_str(&dep_node); self.tcx.sess.span_err( item_span, &format!("`{:?}` found in dep graph, but should be dirty", dep_node_str)); } } } } fn assert_clean(&self, item_span: Span, dep_node: DepNode<DefId>) { debug!("assert_clean({:?})", dep_node); match dep_node { DepNode::Krate | DepNode::Hir(_) | DepNode::HirBody(_) => { if self.dirty_inputs.contains(&dep_node) { let dep_node_str = self.dep_node_str(&dep_node); self.tcx.sess.span_err( item_span, &format!("`{:?}` found in dirty-node set, but should be clean", dep_node_str)); } } _ => { if !self.query.contains_node(&dep_node) { let dep_node_str = self.dep_node_str(&dep_node); self.tcx.sess.span_err( item_span, &format!("`{:?}` not found in dep graph, but should be clean", dep_node_str)); } } } } fn check_item(&mut self, item_id: ast::NodeId, item_span: Span) { let def_id = self.tcx.hir.local_def_id(item_id); for attr in self.tcx.get_attrs(def_id).iter() { if attr.check_name(ATTR_DIRTY) { if check_config(self.tcx, attr) { self.checked_attrs.insert(attr.id); self.assert_dirty(item_span, self.dep_node(attr, def_id)); } } else if attr.check_name(ATTR_CLEAN) { if check_config(self.tcx, attr) { self.checked_attrs.insert(attr.id); self.assert_clean(item_span, self.dep_node(attr, def_id)); } } } } } impl<'a, 'tcx> ItemLikeVisitor<'tcx> for DirtyCleanVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &'tcx hir::Item) { self.check_item(item.id, item.span); } fn visit_trait_item(&mut self, item: &hir::TraitItem) { self.check_item(item.id, item.span); } fn visit_impl_item(&mut self, item: &hir::ImplItem) { self.check_item(item.id, item.span); } } pub fn check_dirty_clean_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, prev_metadata_hashes: &FxHashMap<DefId, Fingerprint>, current_metadata_hashes: &FxHashMap<DefId, Fingerprint>) { if !tcx.sess.opts.debugging_opts.query_dep_graph { return; } tcx.dep_graph.with_ignore(||{ let krate = tcx.hir.krate(); let mut dirty_clean_visitor = DirtyCleanMetadataVisitor { tcx: tcx, prev_metadata_hashes: prev_metadata_hashes, current_metadata_hashes: current_metadata_hashes, checked_attrs: FxHashSet(), }; krate.visit_all_item_likes(&mut dirty_clean_visitor); let mut all_attrs = FindAllAttrs { tcx: tcx, attr_names: vec![ATTR_DIRTY_METADATA, ATTR_CLEAN_METADATA], found_attrs: vec![], }; intravisit::walk_crate(&mut all_attrs, krate); all_attrs.report_unchecked_attrs(&dirty_clean_visitor.checked_attrs); }); } pub struct DirtyCleanMetadataVisitor<'a, 'tcx:'a, 'm> { tcx: TyCtxt<'a, 'tcx, 'tcx>, prev_metadata_hashes: &'m FxHashMap<DefId, Fingerprint>, current_metadata_hashes: &'m FxHashMap<DefId, Fingerprint>, checked_attrs: FxHashSet<ast::AttrId>, } impl<'a, 'tcx, 'm> ItemLikeVisitor<'tcx> for DirtyCleanMetadataVisitor<'a, 'tcx, 'm> { fn visit_item(&mut self, item: &'tcx hir::Item) { self.check_item(item.id, item.span); if let hir::ItemEnum(ref def, _) = item.node { for v in &def.variants { self.check_item(v.node.data.id(), v.span); } } } fn visit_trait_item(&mut self, item: &hir::TraitItem) { self.check_item(item.id, item.span); } fn visit_impl_item(&mut self, item: &hir::ImplItem) { self.check_item(item.id, item.span); } } impl<'a, 'tcx, 'm> DirtyCleanMetadataVisitor<'a, 'tcx, 'm> { fn check_item(&mut self, item_id: ast::NodeId, item_span: Span) { let def_id = self.tcx.hir.local_def_id(item_id); for attr in self.tcx.get_attrs(def_id).iter() { if attr.check_name(ATTR_DIRTY_METADATA) { if check_config(self.tcx, attr) { self.checked_attrs.insert(attr.id); self.assert_state(false, def_id, item_span); } } else if attr.check_name(ATTR_CLEAN_METADATA) { if check_config(self.tcx, attr) { self.checked_attrs.insert(attr.id); self.assert_state(true, def_id, item_span); } } } } fn assert_state(&self, should_be_clean: bool, def_id: DefId, span: Span) { let item_path = self.tcx.item_path_str(def_id); debug!("assert_state({})", item_path); if let Some(&prev_hash) = self.prev_metadata_hashes.get(&def_id) { let hashes_are_equal = prev_hash == self.current_metadata_hashes[&def_id]; if should_be_clean && !hashes_are_equal { self.tcx.sess.span_err( span, &format!("Metadata hash of `{}` is dirty, but should be clean", item_path)); } let should_be_dirty = !should_be_clean; if should_be_dirty && hashes_are_equal { self.tcx.sess.span_err( span, &format!("Metadata hash of `{}` is clean, but should be dirty", item_path)); } } else { self.tcx.sess.span_err( span, &format!("Could not find previous metadata hash of `{}`", item_path)); } } } fn check_config(tcx: TyCtxt, attr: &Attribute) -> bool { debug!("check_config(attr={:?})", attr); let config = &tcx.sess.parse_sess.config; debug!("check_config: config={:?}", config); for item in attr.meta_item_list().unwrap_or_else(Vec::new) { if item.check_name(CFG) { let value = expect_associated_value(tcx, &item); debug!("check_config: searching for cfg {:?}", value); return config.contains(&(value, None)); } } tcx.sess.span_fatal( attr.span, &format!("no cfg attribute")); } fn expect_associated_value(tcx: TyCtxt, item: &NestedMetaItem) -> ast::Name { if let Some(value) = item.value_str() { value } else { let msg = if let Some(name) = item.name() { format!("associated value expected for `{}`", name) } else { "expected an associated value".to_string() }; tcx.sess.span_fatal(item.span, &msg); } } pub struct FindAllAttrs<'a, 'tcx:'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, attr_names: Vec<&'static str>, found_attrs: Vec<&'tcx Attribute>, } impl<'a, 'tcx> FindAllAttrs<'a, 'tcx> { fn is_active_attr(&mut self, attr: &Attribute) -> bool { for attr_name in &self.attr_names { if attr.check_name(attr_name) && check_config(self.tcx, attr) { return true; } } false } fn report_unchecked_attrs(&self, checked_attrs: &FxHashSet<ast::AttrId>) { for attr in &self.found_attrs { if !checked_attrs.contains(&attr.id) { self.tcx.sess.span_err(attr.span, &format!("found unchecked \ #[rustc_dirty]/#[rustc_clean] attribute")); } } } } impl<'a, 'tcx> intravisit::Visitor<'tcx> for FindAllAttrs<'a, 'tcx> { fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> { intravisit::NestedVisitorMap::All(&self.tcx.hir) } fn visit_attribute(&mut self, attr: &'tcx Attribute) { if self.is_active_attr(attr) { self.found_attrs.push(attr); } } }
use super::directory::RetracedDefIdDirectory; use super::load::DirtyNodes; use rustc::dep_graph::{DepGraphQuery, DepNode}; use rustc::hir; use rustc::hir::def_id::DefId; use rustc::hir::itemlikevisit::ItemLikeVisitor; use rustc::hir::intravisit; use rustc::ich::{Fingerprint, ATTR_DIRTY, ATTR_CLEAN, ATTR_DIRTY_METADATA, ATTR_CLEAN_METADATA}; use syntax::ast::{self, Attribute, NestedMetaItem}; use rustc_data_structures::fx::{FxHashSet, FxHashMap}; use syntax_pos::Span; use rustc::ty::TyCtxt; const LABEL: &'static str = "label"; const CFG: &'static str = "cfg"; pub fn check_dirty_clean_annotations<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, dirty_inputs: &DirtyNodes, retraced: &RetracedDefIdDirectory) { if !tcx.sess.features.borrow().rustc_attrs { return; } let _ignore = tcx.dep_graph.in_ignore(); let dirty_inputs: FxHashSet<DepNode<DefId>> = dirty_inputs.keys() .filter_map(|d| retraced.map(d)) .collect(); let query = tcx.dep_graph.query(); debug!("query-nodes: {:?}", query.nodes()); let krate = tcx.hir.krate(); let mut dirty_clean_visitor = DirtyCleanVisitor { tcx: tcx, query: &query, dirty_inputs: dirty_inputs, checked_attrs: FxHashSet(), }; krate.visit_all_item_likes(&mut dirty_clean_visitor); let mut all_attrs = FindAllAttrs { tcx: tcx, attr_names: vec![ATTR_DIRTY, ATTR_CLEAN], found_attrs: vec![], }; intravisit::walk_crate(&mut all_attrs, krate); all_attrs.report_unchecked_attrs(&dirty_clean_visitor.checked_attrs); } pub struct DirtyCleanVisitor<'a, 'tcx:'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, query: &'a DepGraphQuery<DefId>, dirty_inputs: FxHashSet<DepNode<DefId>>, checked_attrs: FxHashSet<ast::AttrId>, } impl<'a, 'tcx> DirtyCleanVisitor<'a, 'tcx> { fn dep_node(&self, attr: &Attribute, def_id: DefId) -> DepNode<DefId> { for item in attr.meta_item_list().unwrap_or_else(Vec::new) { if item.check_name(LABEL) { let value = expect_associated_value(self.tcx, &item); match DepNode::from_label_string(&value.as_str(), def_id) { Ok(def_id) => return def_id, Err(()) => { self.tcx.sess.span_fatal( item.span, &format!("dep-node label `{}` not recognized", value)); } } } } self.tcx.sess.span_fatal(attr.span, "no `label` found"); } fn dep_node_str(&self, dep_node: &DepNode<DefId>) -> DepNode<String> { dep_node.map_def(|&def_id| Some(self.tcx.item_path_str(def_id))).unwrap() } fn assert_dirty(&self, item_span: Span, dep_node: DepNode<DefId>) { debug!("assert_dirty({:?})", dep_node); match dep_node { DepNode::Krate | DepNode::Hir(_) | DepNode::HirBody(_) => { if !self.dirty_inputs.contains(&dep_node) { let dep_node_str = self.dep_node_str(&dep_node); self.tcx.sess.span_err( item_span, &format!("`{:?}` not found in dirty set, but should be dirty", dep_node_str)); } } _ => { if self.query.contains_node(&dep_node) { let dep_node_str = self.dep_node_str(&dep_node); self.tcx.sess.span_err( item_span, &format!("`{:?}` found in dep graph, but should be dirty", dep_node_str)); } } } } fn assert_clean(&self, item_span: Span, dep_node: DepNode<DefId>) { debug!("assert_clean({:?})", dep_node); match dep_node { DepNode::Krate | DepNode::Hir(_) | DepNode::HirBody(_) => { if self.dirty_inputs.contains(&dep_node) { let dep_node_str = self.dep_node_str(&dep_node); self.tcx.sess.span_err( item_span, &format!("`{:?}` found in dirty-node set, but should be clean", dep_node_str)); } } _ => { if !self.query.contains_node(&dep_node) { let dep_node_str = self.dep_node_str(&dep_node); self.tcx.sess.span_err( item_span, &format!("`{:?}` not found in dep graph, but should be clean", dep_node_str)); } } } } fn check_item(&mut self, item_id: ast::NodeId, item_span: Span) { let def_id = self.tcx.hir.local_def_id(item_id); for attr in self.tcx.get_attrs(def_id).iter() { if attr.check_name(ATTR_DIRTY) { if check_config(self.tcx, attr) { self.checked_attrs.insert(attr.id); self.assert_dirty(item_span, self.dep_node(attr, def_id)); } } else if attr.check_name(ATTR_CLEAN) { if check_config(self.tcx, attr) { self.checked_attrs.insert(attr.id); self.assert_clean(item_span, self.dep_node(attr, def_id)); } } } } } impl<'a, 'tcx> ItemLikeVisitor<'tcx> for DirtyCleanVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &'tcx hir::Item) { self.check_item(item.id, item.span); } fn visit_trait_item(&mut self, item: &hir::TraitItem) { self.check_item(item.id, item.span); } fn visit_impl_item(&mut self, item: &hir::ImplItem) { self.check_item(item.id, item.span); } } pub fn check_dirty_clean_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, prev_metadata_hashes: &FxHashMap<DefId, Fingerprint>, current_metadata_hashes: &FxHashMap<DefId, Fingerprint>) { if !tcx.sess.opts.debugging_opts.query_dep_graph { return; } tcx.dep_graph.with_ignore(||{ let krate = tcx.hir.krate(); let mut dirty_clean_visitor = DirtyCleanMetadataVisitor { tcx: tcx, prev_metadata_hashes: prev_metadata_hashes, current_metadata_hashes: current_metadata_hashes, checked_attrs: FxHashSet(), }; krate.visit_all_item_likes(&mut dirty_clean_visitor); let mut all_attrs = FindAllAttrs { tcx: tcx, attr_names: vec![ATTR_DIRTY_METADATA, ATTR_CLEAN_METADATA], found_attrs: vec![], }; intravisit::walk_crate(&mut all_attrs, krate); all_attrs.report_unchecked_attrs(&dirty_clean_visitor.checked_attrs); }); } pub struct DirtyCleanMetadataVisitor<'a, 'tcx:'a, 'm> { tcx: TyCtxt<'a, 'tcx, 'tcx>, prev_metadata_hashes: &'m FxHashMap<DefId, Fingerprint>, current_metadata_hashes: &'m FxHashMap<DefId, Fingerprint>, checked_attrs: FxHashSet<ast::AttrId>, } impl<'a, 'tcx, 'm> ItemLikeVisitor<'tcx> for DirtyCleanMetadataVisitor<'a, 'tcx, 'm> { fn visit_item(&mut self, item: &'tcx hir::Item) { self.check_item(item.id, item.span); if let hir::ItemEnum(ref def, _) = item.node { for v in &def.variants { self.check_item(v.node.data.id(), v.span); } } } fn visit_trait_item(&mut self, item: &hir::TraitItem) { self.check_item(item.id, item.span); } fn visit_impl_item(&mut self, item: &hir::ImplItem) { self.check_item(item.id, item.span); } } impl<'a, 'tcx, 'm> DirtyCleanMetadataVisitor<'a, 'tcx, 'm> { fn check_item(&mut self, item_id: ast::NodeId, item_span: Span) { let def_id = self.tcx.hir.local_def_id(item_id); for attr in self.tcx.get_attrs(def_id).iter() { if attr.check_name(ATTR_DIRTY_METADATA) { if check_config(self.tcx, attr) { self.checked_attrs.insert(attr.id); self.assert_state(false, def_id, item_span); } } else if attr.check_name(ATTR_CLEAN_METADATA) { if check_config(self.tcx, attr) { self.checked_attrs.insert(attr.id); self.assert_state(true, def_id, item_span); } } } } fn assert_state(&self, should_be_clean: bool, def_id: DefId, span: Span) { let item_path = self.tcx.item_path_str(def_id); debug!("assert_state({})", item_path); if let Some(&prev_hash) = self.prev_metadata_hashes.get(&def_id) { let hashes_are_equal = prev_hash == self.current_metadata_hashes[&def_id]; if should_be_clean && !hashes_are_equal { self.tcx.sess.span_err( span, &format!("Metadata hash of `{}` is dirty, but should be clean", item_path)); } let should_be_dirty = !should_be_clean; if should_be_dirty && hashes_are_equal { self.tcx.sess.span_err( span, &format!("Metadata hash of `{}` is clean, but should be dirty", item_path)); } } else { self.tcx.sess.span_err( span, &format!("Could not find previous metadata hash of `{}`", item_path)); } } } fn check_config(tcx: TyCtxt, attr: &Attribute) -> bool { debug!("check_config(attr={:?})", attr); let config = &tcx.sess.parse_sess.config; debug!("check_config: config={:?}", config); for item in attr.meta_item_list().unwrap_or_else(Vec::new) { if item.check_name(CFG) { let value = expect_associated_value(tcx, &item); debug!("check_config: searching for cfg {:?}", value); return config.contains(&(value, None)); } } tcx.sess.span_fatal( attr.span, &format!("no cfg attribute")); } fn expect_associated_value(tcx: TyCtxt, item: &NestedMetaItem) -> ast::Name {
} pub struct FindAllAttrs<'a, 'tcx:'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, attr_names: Vec<&'static str>, found_attrs: Vec<&'tcx Attribute>, } impl<'a, 'tcx> FindAllAttrs<'a, 'tcx> { fn is_active_attr(&mut self, attr: &Attribute) -> bool { for attr_name in &self.attr_names { if attr.check_name(attr_name) && check_config(self.tcx, attr) { return true; } } false } fn report_unchecked_attrs(&self, checked_attrs: &FxHashSet<ast::AttrId>) { for attr in &self.found_attrs { if !checked_attrs.contains(&attr.id) { self.tcx.sess.span_err(attr.span, &format!("found unchecked \ #[rustc_dirty]/#[rustc_clean] attribute")); } } } } impl<'a, 'tcx> intravisit::Visitor<'tcx> for FindAllAttrs<'a, 'tcx> { fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> { intravisit::NestedVisitorMap::All(&self.tcx.hir) } fn visit_attribute(&mut self, attr: &'tcx Attribute) { if self.is_active_attr(attr) { self.found_attrs.push(attr); } } }
if let Some(value) = item.value_str() { value } else { let msg = if let Some(name) = item.name() { format!("associated value expected for `{}`", name) } else { "expected an associated value".to_string() }; tcx.sess.span_fatal(item.span, &msg); }
if_condition
[]
Rust
src/graphics/camera.rs
fossegutten/tetra
ebdccc242680786482a8622dbb3f76f1fc0ab00c
use super::Rectangle; use crate::input; use crate::math::{Mat4, Vec2, Vec3}; use crate::window; use crate::Context; #[derive(Debug, Clone)] pub struct Camera { pub position: Vec2<f32>, pub rotation: f32, pub zoom: f32, pub viewport_width: f32, pub viewport_height: f32, matrix: Mat4<f32>, } impl Camera { pub fn new(viewport_width: f32, viewport_height: f32) -> Camera { Camera { position: Vec2::zero(), rotation: 0.0, zoom: 1.0, viewport_width, viewport_height, matrix: Mat4::translation_2d(Vec2::new(viewport_width / 2.0, viewport_height / 2.0)), } } pub fn with_window_size(ctx: &Context) -> Camera { let (width, height) = window::get_size(ctx); Camera::new(width as f32, height as f32) } pub fn set_viewport_size(&mut self, width: f32, height: f32) { self.viewport_width = width; self.viewport_height = height; } pub fn update(&mut self) { self.matrix = Mat4::translation_2d(-self.position); self.matrix.rotate_z(self.rotation); self.matrix.scale_3d(Vec3::new(self.zoom, self.zoom, 1.0)); self.matrix.translate_2d(Vec2::new( self.viewport_width / 2.0, self.viewport_height / 2.0, )); } pub fn as_matrix(&self) -> Mat4<f32> { self.matrix } pub fn project(&self, point: Vec2<f32>) -> Vec2<f32> { let mut proj = Vec2::new( (point.x - self.viewport_width / 2.0) / self.zoom, (point.y - self.viewport_height / 2.0) / self.zoom, ); proj.rotate_z(-self.rotation); proj += self.position; proj } pub fn unproject(&self, point: Vec2<f32>) -> Vec2<f32> { let mut unproj = point - self.position; unproj.rotate_z(self.rotation); unproj.x = unproj.x * self.zoom + self.viewport_width / 2.0; unproj.y = unproj.y * self.zoom + self.viewport_height / 2.0; unproj } pub fn mouse_position(&self, ctx: &Context) -> Vec2<f32> { self.project(input::get_mouse_position(ctx)) } pub fn mouse_x(&self, ctx: &Context) -> f32 { self.mouse_position(ctx).x } pub fn mouse_y(&self, ctx: &Context) -> f32 { self.mouse_position(ctx).y } pub fn visible_rect(&self) -> Rectangle { let viewport_width = self.viewport_width / self.zoom; let viewport_height = self.viewport_height / self.zoom; let half_viewport_width = viewport_width / 2.0; let half_viewport_height = viewport_height / 2.0; if self.rotation.abs() > f32::EPSILON { let mut top_left = Vec2::new(-half_viewport_width, -half_viewport_height); let mut bottom_left = Vec2::new(-half_viewport_width, half_viewport_height); top_left.rotate_z(self.rotation); bottom_left.rotate_z(self.rotation); let largest_x = f32::max(top_left.x.abs(), bottom_left.x.abs()); let largest_y = f32::max(top_left.y.abs(), bottom_left.y.abs()); let left = self.position.x - largest_x; let top = self.position.y - largest_y; let width = largest_x * 2.0; let height = largest_y * 2.0; Rectangle { x: left, y: top, width, height, } } else { let left = self.position.x - half_viewport_width; let top = self.position.y - half_viewport_height; Rectangle { x: left, y: top, width: viewport_width, height: viewport_height, } } } } #[cfg(test)] mod tests { use super::*; #[test] fn point_projections() { let mut camera = Camera::new(128.0, 256.0); let proj_initial = camera.project(Vec2::zero()); let unproj_initial = camera.unproject(proj_initial); assert_eq!(proj_initial, Vec2::new(-64.0, -128.0)); assert_eq!(unproj_initial, Vec2::zero()); camera.position = Vec2::new(16.0, 16.0); let proj_positioned = camera.project(Vec2::zero()); let unproj_positioned = camera.unproject(proj_positioned); assert_eq!(proj_positioned, Vec2::new(-48.0, -112.0)); assert_eq!(unproj_positioned, Vec2::zero()); camera.zoom = 2.0; let proj_zoomed = camera.project(Vec2::zero()); let unproj_zoomed = camera.unproject(proj_zoomed); assert_eq!(proj_zoomed, Vec2::new(-16.0, -48.0)); assert_eq!(unproj_zoomed, Vec2::zero()); camera.rotation = std::f32::consts::FRAC_PI_2; let proj_rotated = camera.project(Vec2::zero()); let unproj_rotated = camera.unproject(proj_rotated); assert!(proj_rotated.x + 48.0 <= 0.001); assert!(proj_rotated.y - 48.0 <= 0.001); assert!(unproj_rotated.x.abs() <= 0.001); assert!(unproj_rotated.y.abs() <= 0.001); } #[test] fn validate_camera_visible_rect() { let mut camera = Camera::new(800.0, 600.0); assert_eq!( camera.visible_rect(), Rectangle { x: -400.0, y: -300.0, width: 800.0, height: 600.0 } ); camera.zoom = 2.0; assert_eq!( camera.visible_rect(), Rectangle { x: -200.0, y: -150.0, width: 400.0, height: 300.0 } ); camera.position = Vec2::new(-100.0, 100.0); assert_eq!( camera.visible_rect(), Rectangle { x: -300.0, y: -50.0, width: 400.0, height: 300.0 } ); camera.rotation = std::f32::consts::FRAC_PI_2; let rect = camera.visible_rect(); assert!(rect.x + 250.0 < 0.001); assert!(rect.y + 100.0 < 0.001); assert!(rect.width - 300.0 < 0.001); assert!(rect.height - 400.0 < 0.001); } }
use super::Rectangle; use crate::input; use crate::math::{Mat4, Vec2, Vec3}; use crate::window; use crate::Context; #[derive(Debug, Clone)] pub struct Camera { pub position: Vec2<f32>, pub rotation: f32, pub zoom: f32, pub viewport_width: f32, pub viewport_height: f32, matrix: Mat4<f32>, } impl Camera { pub fn new(viewport_width: f32, viewport_height: f32) -> Camera { Camera { position: Vec2::zero(), rotation: 0.0, zoom: 1.0, viewport_width, viewport_height, matrix: Mat4::translation_2d(Vec2::new(viewport_width / 2.0, viewport_height / 2.0)), } } pub fn with_window_size(ctx: &Context) -> Camera { let (width, height) = window::get_size(ctx); Camera::new(width as f32, height as f32) } pub fn set_viewport_size(&mut self, width: f32, height: f32) { self.viewport_width = width; self.viewport_height = height; } pub fn update(&mut self) { self.matrix = Mat4::translation_2d(-self.position); self.matrix.rotate_z(self.rotation); self.matrix.scale_3d(Vec3::new(self.zoom, self.zoom, 1.0)); self.matrix.translate_2d(Vec2::new( self.viewport_width / 2.0, self.viewport_height / 2.0, )); } pub fn as_matrix(&self) -> Mat4<f32> { self.matrix } pub fn project(&self, point: Vec2<f32>) -> Vec2<f32> { let mut proj = Vec2::new( (point.x - self.viewport_width / 2.0) / self.zoom, (point.y - self.viewport_height / 2.0) / self.zoom, ); proj.rotate_z(-self.rotation); proj += self.position; proj } pub fn unproject(&self, point: Vec2<f32>) -> Vec2<f32> { let mut unproj = point - self.position; unproj.rotate_z(self.rotation); unproj.x = unproj.x * self.zoom + self.viewport_width / 2.0; unproj.y = unproj.y * self.zoom + self.viewport_height / 2.0; unproj } pub fn mouse_position(&self, ctx: &Context) -> Vec2<f32> { self.project(input::get_mouse_position(ctx)) } pub fn mouse_x(&self, ctx: &Context) -> f32 { self.mouse_position(ctx).x } pub fn mouse_y(&self, ctx: &Context) -> f32 { self.mouse_position(ctx).y } pub fn visible_rect(&self) -> Rectangle { let viewport_width = self.viewport_width / self.zoom; let viewport_height = self.viewport_height / self.zoom; let half_viewport_width = viewport_width / 2.0; let half_viewport_height = viewport_height / 2.0; if self.rotation.abs
= camera.unproject(proj_zoomed); assert_eq!(proj_zoomed, Vec2::new(-16.0, -48.0)); assert_eq!(unproj_zoomed, Vec2::zero()); camera.rotation = std::f32::consts::FRAC_PI_2; let proj_rotated = camera.project(Vec2::zero()); let unproj_rotated = camera.unproject(proj_rotated); assert!(proj_rotated.x + 48.0 <= 0.001); assert!(proj_rotated.y - 48.0 <= 0.001); assert!(unproj_rotated.x.abs() <= 0.001); assert!(unproj_rotated.y.abs() <= 0.001); } #[test] fn validate_camera_visible_rect() { let mut camera = Camera::new(800.0, 600.0); assert_eq!( camera.visible_rect(), Rectangle { x: -400.0, y: -300.0, width: 800.0, height: 600.0 } ); camera.zoom = 2.0; assert_eq!( camera.visible_rect(), Rectangle { x: -200.0, y: -150.0, width: 400.0, height: 300.0 } ); camera.position = Vec2::new(-100.0, 100.0); assert_eq!( camera.visible_rect(), Rectangle { x: -300.0, y: -50.0, width: 400.0, height: 300.0 } ); camera.rotation = std::f32::consts::FRAC_PI_2; let rect = camera.visible_rect(); assert!(rect.x + 250.0 < 0.001); assert!(rect.y + 100.0 < 0.001); assert!(rect.width - 300.0 < 0.001); assert!(rect.height - 400.0 < 0.001); } }
() > f32::EPSILON { let mut top_left = Vec2::new(-half_viewport_width, -half_viewport_height); let mut bottom_left = Vec2::new(-half_viewport_width, half_viewport_height); top_left.rotate_z(self.rotation); bottom_left.rotate_z(self.rotation); let largest_x = f32::max(top_left.x.abs(), bottom_left.x.abs()); let largest_y = f32::max(top_left.y.abs(), bottom_left.y.abs()); let left = self.position.x - largest_x; let top = self.position.y - largest_y; let width = largest_x * 2.0; let height = largest_y * 2.0; Rectangle { x: left, y: top, width, height, } } else { let left = self.position.x - half_viewport_width; let top = self.position.y - half_viewport_height; Rectangle { x: left, y: top, width: viewport_width, height: viewport_height, } } } } #[cfg(test)] mod tests { use super::*; #[test] fn point_projections() { let mut camera = Camera::new(128.0, 256.0); let proj_initial = camera.project(Vec2::zero()); let unproj_initial = camera.unproject(proj_initial); assert_eq!(proj_initial, Vec2::new(-64.0, -128.0)); assert_eq!(unproj_initial, Vec2::zero()); camera.position = Vec2::new(16.0, 16.0); let proj_positioned = camera.project(Vec2::zero()); let unproj_positioned = camera.unproject(proj_positioned); assert_eq!(proj_positioned, Vec2::new(-48.0, -112.0)); assert_eq!(unproj_positioned, Vec2::zero()); camera.zoom = 2.0; let proj_zoomed = camera.project(Vec2::zero()); let unproj_zoomed
random
[ { "content": "/// Sets the transform matrix.\n\n///\n\n/// This can be used to apply global transformations to subsequent draw calls.\n\npub fn set_transform_matrix(ctx: &mut Context, matrix: Mat4<f32>) {\n\n flush(ctx);\n\n\n\n ctx.graphics.transform_matrix = matrix;\n\n}\n\n\n", "file_path": "src/gr...
Rust
src/rtl/tree.rs
GuillaumeDIDIER/C-teel
4e46a6623dc3ce669e7525cff7069dbdeaa4043b
use common::ops; pub use parse::ast::Ident; use std::collections::{HashMap, HashSet}; use std::fmt::Display; use std::fmt; use common::register::Register; use common::label::Label; use common::label::LabelAllocator; use common::register::RegisterAllocator; #[derive(Debug)] pub enum Instruction { Const(i64, Register, Label), AccessGlobal(Ident, Register, Label), AssignGlobal(Register, Ident, Label), Load(Register, i64, Register, Label), Store(Register, Register, i64, Label), UnaryOp(ops::x64UnaryOp, Register, Label), BinaryOp(ops::x64BinaryOp, Register, Register, Label), Branch(ops::x64Branch, Label, Label), Call(Register, Ident, Vec<Register>, Label), Goto(Label), } impl Instruction { pub fn successors(&self) -> Vec<Label>{ match *self { Instruction::Const(_,_, ref label) | Instruction::AccessGlobal(_, _, ref label) | Instruction::AssignGlobal(_, _, ref label) | Instruction::Load(_, _, _, ref label) | Instruction::Store(_, _, _, ref label) | Instruction::UnaryOp(_, _, ref label) | Instruction::BinaryOp(_, _, _, ref label) | Instruction::Call(_, _, _, ref label) | Instruction::Goto(ref label) => { vec![label.clone()] }, Instruction::Branch(_, ref label1, ref label2) => { vec![label2.clone(), label1.clone()] } } } } impl Display for Instruction { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { Instruction::Const(ref value, ref reg, ref label) => { write!(f, "mov ${} {} --> {}", value, reg, label) }, Instruction::AccessGlobal(ref name, ref reg, ref label) => { write!(f, "mov {} {} --> {}", name, reg, label) }, Instruction::AssignGlobal(ref reg, ref name, ref label) => { write!(f, "mov {} {} --> {}", reg, name, label) }, Instruction::Load(ref sreg, ref offset, ref dreg, ref label) => { write!(f, "mov {}({}) {} --> {}", offset, sreg, dreg, label) }, Instruction::Store(ref sreg, ref dreg, ref offset, ref label) => { write!(f, "mov {} {}({}) --> {}", sreg, offset, dreg, label) }, Instruction::UnaryOp(ref op, ref reg, ref label) => { write!(f, "{} {} --> {}", op, reg, label) }, Instruction::BinaryOp(ref op, ref sreg, ref dreg, ref label) => { write!(f, "{} {} {} --> {}", op, sreg, dreg, label) }, Instruction::Call(ref reg, ref name, ref args, ref label) => { try!(write!(f, "{} <- call {}(", reg, name)); let mut i = args.iter(); if let Some(arg0) = i.next() { try!(write!(f, "{}", arg0)); for arg in i { try!(write!(f, ", {}", arg)); } } write!(f, ") --> {}", label) }, Instruction::Goto(ref label) => { write!(f, "goto {}", label) }, Instruction::Branch(ref branch_op, ref label1, ref label2) => { write!(f, "{} --> {}, {}", branch_op, label1, label2) }, } } } #[derive(Debug)] pub struct FuncDefinition { pub name: Ident, pub formals: Vec<Register>, pub result: Register, pub locals: HashSet<Register>, pub entry: Label, pub exit: Label, pub body: HashMap<Label, Instruction>, pub label_allocator: LabelAllocator, pub register_allocator: RegisterAllocator, } impl FuncDefinition { fn print_body(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { let mut visited = HashSet::<Label>::new(); self.visit(&mut visited, self.entry, f) } fn visit(& self, visited: & mut HashSet<Label>, l: Label, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { if visited.contains(&l) { return Ok(()); } visited.insert(l); if let Some(instruction) = self.body.get(&l) { try!(write!(f, " {}: {}\n", l, instruction)); for s in instruction.successors() { try!(self.visit(visited, s, f)); } return Ok(()) } else { return Ok(()); } } } impl Display for FuncDefinition { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { try!(write!(f, "{} {}(", self.result, self.name)); let mut i = self.formals.iter(); if let Some(formal0) = i.next() { try!(write!(f, "{}", formal0)); for formal in i { try!(write!(f, ", {}", formal)); } } try!(write!(f, ")\n")); try!(write!(f, " entry : {}\n", self.entry)); try!(write!(f, " exit : {}\n", self.exit)); try!(write!(f, " locals : ")); let mut i = self.locals.iter(); if let Some(local0) = i.next() { try!(write!(f, "{}", local0)); for local in i { try!(write!(f, ", {}", local)); } } try!(write!(f, "\n")); self.print_body(f) } } #[derive(Debug)] pub struct File { pub globals : Vec<Ident>, pub functions: Vec<FuncDefinition>, } impl Display for File { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { try!(write!(f, "== RTL ==================================================\n")); for i in 0..self.functions.len() { try!(write!(f, "{}", self.functions[i])); } write!(f, "== END ==================================================\n") } }
use common::ops; pub use parse::ast::Ident; use std::collections::{HashMap, HashSet}; use std::fmt::Display; use std::fmt; use common::register::Register; use common::label::Label; use common::label::LabelAllocator; use common::register::RegisterAllocator; #[derive(Debug)] pub enum Instruction { Const(i64, Register, Label), AccessGlobal(Ident, Register, Label), AssignGlobal(Register, Ident, Label), Load(Register, i64, Register, Label), Store(Register, Register, i64, Label), UnaryOp(ops::x64UnaryOp, Register, Label), BinaryOp(ops::x64BinaryOp, Register, Register, Label), Branch(ops::x64Branch, Label, Label), Call(Register, Ident, Vec<Register>, Label), Goto(Label), } impl Instruction { pub fn successors(&self) -> Vec<Label>{ match *self { Instruction::Const(_,_, ref label) | Instruction::AccessGlobal(_, _, ref label) | Instruction::AssignGlobal(_, _, ref label) | Instruction::Load(_, _, _, ref label) | Instruction::Store(_, _, _, ref label) | Instruction::UnaryOp(_, _, ref label) | Instruction::BinaryOp(_, _, _, ref label) | Instruction::Call(_, _, _, ref label) | Instruction::Goto(ref label) => { vec![label.clone()] }, Instruction::Branch(_, ref label1, ref label2) => { vec![label2.clone(), label1.clone()] } } } } impl Display for Instruction { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { Instruction::Const(ref value, ref reg, ref label) => { write!(f, "mov ${} {} --> {}", value, reg, label) }, Instruction::AccessGlobal(ref name, ref reg, ref label) => { write!(f, "mov {} {} --> {}", name, reg, label) }, Instruction::AssignGlobal(ref reg, ref name, ref label) => { write!(f, "mov {} {} --> {}", reg, name, label) }, Instruction::Load(ref sreg, ref offset, ref dreg, ref label) => { write!(f, "mov {}({}) {} --> {}", offset, sreg, dreg, label) }, Instruction::Store(ref sreg, ref dreg, ref offset, ref label) => { write!(f, "mov {} {}({}) --> {}", sreg, offset, dreg, label) }, Instruction::UnaryOp(ref op, ref reg, ref label) => { write!(f, "{} {} --> {}", op, reg, label) }, Instruction::BinaryOp(ref op, ref sreg, ref dreg, ref label) => { write!(f, "{} {} {} --> {}", op, sreg, dreg, label) }, Instruction::Call(ref reg, ref name, ref args, ref label) => { try!(write!(f, "{} <- call {}(", reg, name)); let mut i = args.iter(); if let Some(arg0) = i.next() { try!(write!(f, "{}", arg0)); for arg in i { try!(write!(f, ", {}", arg)); } } write!(f, ") --> {}", label) }, Instruction::Goto(ref label) => { write!(f, "
ruct FuncDefinition { pub name: Ident, pub formals: Vec<Register>, pub result: Register, pub locals: HashSet<Register>, pub entry: Label, pub exit: Label, pub body: HashMap<Label, Instruction>, pub label_allocator: LabelAllocator, pub register_allocator: RegisterAllocator, } impl FuncDefinition { fn print_body(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { let mut visited = HashSet::<Label>::new(); self.visit(&mut visited, self.entry, f) } fn visit(& self, visited: & mut HashSet<Label>, l: Label, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { if visited.contains(&l) { return Ok(()); } visited.insert(l); if let Some(instruction) = self.body.get(&l) { try!(write!(f, " {}: {}\n", l, instruction)); for s in instruction.successors() { try!(self.visit(visited, s, f)); } return Ok(()) } else { return Ok(()); } } } impl Display for FuncDefinition { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { try!(write!(f, "{} {}(", self.result, self.name)); let mut i = self.formals.iter(); if let Some(formal0) = i.next() { try!(write!(f, "{}", formal0)); for formal in i { try!(write!(f, ", {}", formal)); } } try!(write!(f, ")\n")); try!(write!(f, " entry : {}\n", self.entry)); try!(write!(f, " exit : {}\n", self.exit)); try!(write!(f, " locals : ")); let mut i = self.locals.iter(); if let Some(local0) = i.next() { try!(write!(f, "{}", local0)); for local in i { try!(write!(f, ", {}", local)); } } try!(write!(f, "\n")); self.print_body(f) } } #[derive(Debug)] pub struct File { pub globals : Vec<Ident>, pub functions: Vec<FuncDefinition>, } impl Display for File { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { try!(write!(f, "== RTL ==================================================\n")); for i in 0..self.functions.len() { try!(write!(f, "{}", self.functions[i])); } write!(f, "== END ==================================================\n") } }
goto {}", label) }, Instruction::Branch(ref branch_op, ref label1, ref label2) => { write!(f, "{} --> {}, {}", branch_op, label1, label2) }, } } } #[derive(Debug)] pub st
random
[ { "content": "pub fn convert_char(ch: &str) -> Option<i64> {\n\n if ch.len() == 1 {\n\n if let Some(c) = ch.chars().next() {\n\n Some(c as i64)\n\n } else {\n\n None\n\n }\n\n } else if ch.len() == 2 {\n\n match ch {\n\n \"\\\\\\\\\" => Some(92)...
Rust
verification/src/header_verifier.rs
liyaspawn/ckb
59a40454fd46bf3640df68591001f9d6b6491049
use crate::{ BlockVersionError, EpochError, NumberError, PowError, TimestampError, UnknownParentError, ALLOWED_FUTURE_BLOCKTIME, }; use ckb_chain_spec::consensus::Consensus; use ckb_error::Error; use ckb_pow::PowEngine; use ckb_traits::HeaderProvider; use ckb_types::core::{HeaderView, Version}; use ckb_verification_traits::Verifier; use faketime::unix_time_as_millis; pub struct HeaderVerifier<'a, DL> { data_loader: &'a DL, consensus: &'a Consensus, } impl<'a, DL: HeaderProvider> HeaderVerifier<'a, DL> { pub fn new(data_loader: &'a DL, consensus: &'a Consensus) -> Self { HeaderVerifier { consensus, data_loader, } } } impl<'a, DL: HeaderProvider> Verifier for HeaderVerifier<'a, DL> { type Target = HeaderView; fn verify(&self, header: &Self::Target) -> Result<(), Error> { VersionVerifier::new(header, self.consensus.block_version()).verify()?; PowVerifier::new(header, self.consensus.pow_engine().as_ref()).verify()?; let parent = self .data_loader .get_header(&header.parent_hash()) .ok_or_else(|| UnknownParentError { parent_hash: header.parent_hash(), })?; NumberVerifier::new(&parent, header).verify()?; EpochVerifier::new(&parent, header).verify()?; TimestampVerifier::new( self.data_loader, header, self.consensus.median_time_block_count(), ) .verify()?; Ok(()) } } pub struct VersionVerifier<'a> { header: &'a HeaderView, block_version: Version, } impl<'a> VersionVerifier<'a> { pub fn new(header: &'a HeaderView, block_version: Version) -> Self { VersionVerifier { header, block_version, } } pub fn verify(&self) -> Result<(), Error> { if self.header.version() != self.block_version { return Err(BlockVersionError { expected: self.block_version, actual: self.header.version(), } .into()); } Ok(()) } } pub struct TimestampVerifier<'a, DL> { header: &'a HeaderView, data_loader: &'a DL, median_block_count: usize, now: u64, } impl<'a, DL: HeaderProvider> TimestampVerifier<'a, DL> { pub fn new(data_loader: &'a DL, header: &'a HeaderView, median_block_count: usize) -> Self { TimestampVerifier { data_loader, header, median_block_count, now: unix_time_as_millis(), } } pub fn verify(&self) -> Result<(), Error> { if self.header.is_genesis() { return Ok(()); } let min = self.data_loader.block_median_time( &self.header.data().raw().parent_hash(), self.median_block_count, ); if self.header.timestamp() <= min { return Err(TimestampError::BlockTimeTooOld { min, actual: self.header.timestamp(), } .into()); } let max = self.now + ALLOWED_FUTURE_BLOCKTIME; if self.header.timestamp() > max { return Err(TimestampError::BlockTimeTooNew { max, actual: self.header.timestamp(), } .into()); } Ok(()) } } pub struct NumberVerifier<'a> { parent: &'a HeaderView, header: &'a HeaderView, } impl<'a> NumberVerifier<'a> { pub fn new(parent: &'a HeaderView, header: &'a HeaderView) -> Self { NumberVerifier { parent, header } } pub fn verify(&self) -> Result<(), Error> { if self.header.number() != self.parent.number() + 1 { return Err(NumberError { expected: self.parent.number() + 1, actual: self.header.number(), } .into()); } Ok(()) } } pub struct EpochVerifier<'a> { parent: &'a HeaderView, header: &'a HeaderView, } impl<'a> EpochVerifier<'a> { pub fn new(parent: &'a HeaderView, header: &'a HeaderView) -> Self { EpochVerifier { parent, header } } pub fn verify(&self) -> Result<(), Error> { if !self.header.epoch().is_well_formed() { return Err(EpochError::Malformed { value: self.header.epoch(), } .into()); } if !self.parent.is_genesis() && !self.header.epoch().is_successor_of(self.parent.epoch()) { return Err(EpochError::NonContinuous { current: self.header.epoch(), parent: self.parent.epoch(), } .into()); } Ok(()) } } pub struct PowVerifier<'a> { header: &'a HeaderView, pow: &'a dyn PowEngine, } impl<'a> PowVerifier<'a> { pub fn new(header: &'a HeaderView, pow: &'a dyn PowEngine) -> Self { PowVerifier { header, pow } } pub fn verify(&self) -> Result<(), Error> { if self.pow.verify(&self.header.data()) { Ok(()) } else { Err(PowError::InvalidNonce.into()) } } }
use crate::{ BlockVersionError, EpochError, NumberError, PowError, TimestampError, UnknownParentError, ALLOWED_FUTURE_BLOCKTIME, }; use ckb_chain_spec::consensus::Consensus; use ckb_error::Error; use ckb_pow::PowEngine; use ckb_traits::HeaderProvider; use ckb_types::core::{HeaderView, Version}; use ckb_verification_traits::Verifier; use faketime::unix_time_as_millis; pub struct HeaderVerifier<'a, DL> { data_loader: &'a DL, consensus: &'a Consensus, } impl<'a, DL: HeaderProvider> HeaderVerifier<'a, DL> { pub fn new(data_loader: &'a DL, consensus: &'a Consensus) -> Self { HeaderVerifier { consensus, data_loader, } } } impl<'a, DL: HeaderProvider> Verifier for HeaderVerifier<'a, DL> { type Target = HeaderView; fn verify(&self, header: &Self::Target) -> Result<(), Error> { VersionVerifier::new(header, self.c
} .into()); } let max = self.now + ALLOWED_FUTURE_BLOCKTIME; if self.header.timestamp() > max { return Err(TimestampError::BlockTimeTooNew { max, actual: self.header.timestamp(), } .into()); } Ok(()) } } pub struct NumberVerifier<'a> { parent: &'a HeaderView, header: &'a HeaderView, } impl<'a> NumberVerifier<'a> { pub fn new(parent: &'a HeaderView, header: &'a HeaderView) -> Self { NumberVerifier { parent, header } } pub fn verify(&self) -> Result<(), Error> { if self.header.number() != self.parent.number() + 1 { return Err(NumberError { expected: self.parent.number() + 1, actual: self.header.number(), } .into()); } Ok(()) } } pub struct EpochVerifier<'a> { parent: &'a HeaderView, header: &'a HeaderView, } impl<'a> EpochVerifier<'a> { pub fn new(parent: &'a HeaderView, header: &'a HeaderView) -> Self { EpochVerifier { parent, header } } pub fn verify(&self) -> Result<(), Error> { if !self.header.epoch().is_well_formed() { return Err(EpochError::Malformed { value: self.header.epoch(), } .into()); } if !self.parent.is_genesis() && !self.header.epoch().is_successor_of(self.parent.epoch()) { return Err(EpochError::NonContinuous { current: self.header.epoch(), parent: self.parent.epoch(), } .into()); } Ok(()) } } pub struct PowVerifier<'a> { header: &'a HeaderView, pow: &'a dyn PowEngine, } impl<'a> PowVerifier<'a> { pub fn new(header: &'a HeaderView, pow: &'a dyn PowEngine) -> Self { PowVerifier { header, pow } } pub fn verify(&self) -> Result<(), Error> { if self.pow.verify(&self.header.data()) { Ok(()) } else { Err(PowError::InvalidNonce.into()) } } }
onsensus.block_version()).verify()?; PowVerifier::new(header, self.consensus.pow_engine().as_ref()).verify()?; let parent = self .data_loader .get_header(&header.parent_hash()) .ok_or_else(|| UnknownParentError { parent_hash: header.parent_hash(), })?; NumberVerifier::new(&parent, header).verify()?; EpochVerifier::new(&parent, header).verify()?; TimestampVerifier::new( self.data_loader, header, self.consensus.median_time_block_count(), ) .verify()?; Ok(()) } } pub struct VersionVerifier<'a> { header: &'a HeaderView, block_version: Version, } impl<'a> VersionVerifier<'a> { pub fn new(header: &'a HeaderView, block_version: Version) -> Self { VersionVerifier { header, block_version, } } pub fn verify(&self) -> Result<(), Error> { if self.header.version() != self.block_version { return Err(BlockVersionError { expected: self.block_version, actual: self.header.version(), } .into()); } Ok(()) } } pub struct TimestampVerifier<'a, DL> { header: &'a HeaderView, data_loader: &'a DL, median_block_count: usize, now: u64, } impl<'a, DL: HeaderProvider> TimestampVerifier<'a, DL> { pub fn new(data_loader: &'a DL, header: &'a HeaderView, median_block_count: usize) -> Self { TimestampVerifier { data_loader, header, median_block_count, now: unix_time_as_millis(), } } pub fn verify(&self) -> Result<(), Error> { if self.header.is_genesis() { return Ok(()); } let min = self.data_loader.block_median_time( &self.header.data().raw().parent_hash(), self.median_block_count, ); if self.header.timestamp() <= min { return Err(TimestampError::BlockTimeTooOld { min, actual: self.header.timestamp(),
random
[]
Rust
cli/ops/os.rs
justgeek/deno
34ec3b225425cecdccf754fbc87f4a8f3728890d
use super::dispatch_json::{Deserialize, JsonOp, Value}; use crate::op_error::OpError; use crate::state::State; use deno_core::CoreIsolate; use deno_core::ZeroCopyBuf; use std::collections::HashMap; use std::env; use std::io::{Error, ErrorKind}; use url::Url; pub fn init(i: &mut CoreIsolate, s: &State) { i.register_op("op_exit", s.stateful_json_op(op_exit)); i.register_op("op_env", s.stateful_json_op(op_env)); i.register_op("op_exec_path", s.stateful_json_op(op_exec_path)); i.register_op("op_set_env", s.stateful_json_op(op_set_env)); i.register_op("op_get_env", s.stateful_json_op(op_get_env)); i.register_op("op_get_dir", s.stateful_json_op(op_get_dir)); i.register_op("op_hostname", s.stateful_json_op(op_hostname)); i.register_op("op_loadavg", s.stateful_json_op(op_loadavg)); i.register_op("op_os_release", s.stateful_json_op(op_os_release)); } #[derive(Deserialize)] struct GetDirArgs { kind: std::string::String, } fn op_get_dir( state: &State, args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { state.check_unstable("Deno.dir"); state.check_env()?; let args: GetDirArgs = serde_json::from_value(args)?; let path = match args.kind.as_str() { "home" => dirs::home_dir(), "config" => dirs::config_dir(), "cache" => dirs::cache_dir(), "executable" => dirs::executable_dir(), "data" => dirs::data_dir(), "data_local" => dirs::data_local_dir(), "audio" => dirs::audio_dir(), "desktop" => dirs::desktop_dir(), "document" => dirs::document_dir(), "download" => dirs::download_dir(), "font" => dirs::font_dir(), "picture" => dirs::picture_dir(), "public" => dirs::public_dir(), "template" => dirs::template_dir(), "tmp" => Some(std::env::temp_dir()), "video" => dirs::video_dir(), _ => { return Err( Error::new( ErrorKind::InvalidInput, format!("Invalid dir type `{}`", args.kind.as_str()), ) .into(), ) } }; if path == None { Err(OpError::not_found(format!( "Could not get user {} directory.", args.kind.as_str() ))) } else { Ok(JsonOp::Sync(json!(path .unwrap_or_default() .into_os_string() .into_string() .unwrap_or_default()))) } } fn op_exec_path( state: &State, _args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { let current_exe = env::current_exe().unwrap(); state.check_read(&current_exe)?; let exe_url = Url::from_file_path(current_exe).unwrap(); let path = exe_url.to_file_path().unwrap(); Ok(JsonOp::Sync(json!(path))) } #[derive(Deserialize)] struct SetEnv { key: String, value: String, } fn op_set_env( state: &State, args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { let args: SetEnv = serde_json::from_value(args)?; state.check_env()?; env::set_var(args.key, args.value); Ok(JsonOp::Sync(json!({}))) } fn op_env( state: &State, _args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { state.check_env()?; let v = env::vars().collect::<HashMap<String, String>>(); Ok(JsonOp::Sync(json!(v))) } #[derive(Deserialize)] struct GetEnv { key: String, } fn op_get_env( state: &State, args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { let args: GetEnv = serde_json::from_value(args)?; state.check_env()?; let r = match env::var(args.key) { Err(env::VarError::NotPresent) => json!([]), v => json!([v?]), }; Ok(JsonOp::Sync(r)) } #[derive(Deserialize)] struct Exit { code: i32, } fn op_exit( _s: &State, args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { let args: Exit = serde_json::from_value(args)?; std::process::exit(args.code) } fn op_loadavg( state: &State, _args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { state.check_unstable("Deno.loadavg"); state.check_env()?; match sys_info::loadavg() { Ok(loadavg) => Ok(JsonOp::Sync(json!([ loadavg.one, loadavg.five, loadavg.fifteen ]))), Err(_) => Ok(JsonOp::Sync(json!([0f64, 0f64, 0f64]))), } } fn op_hostname( state: &State, _args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { state.check_env()?; let hostname = sys_info::hostname().unwrap_or_else(|_| "".to_string()); Ok(JsonOp::Sync(json!(hostname))) } fn op_os_release( state: &State, _args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { state.check_unstable("Deno.osRelease"); state.check_env()?; let release = sys_info::os_release().unwrap_or_else(|_| "".to_string()); Ok(JsonOp::Sync(json!(release))) }
use super::dispatch_json::{Deserialize, JsonOp, Value}; use crate::op_error::OpError; use crate::state::State; use deno_core::CoreIsolate; use deno_core::ZeroCopyBuf; use std::collections::HashMap; use std::env; use std::io::{Error, ErrorKind}; use url::Url;
#[derive(Deserialize)] struct GetDirArgs { kind: std::string::String, } fn op_get_dir( state: &State, args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { state.check_unstable("Deno.dir"); state.check_env()?; let args: GetDirArgs = serde_json::from_value(args)?; let path = match args.kind.as_str() { "home" => dirs::home_dir(), "config" => dirs::config_dir(), "cache" => dirs::cache_dir(), "executable" => dirs::executable_dir(), "data" => dirs::data_dir(), "data_local" => dirs::data_local_dir(), "audio" => dirs::audio_dir(), "desktop" => dirs::desktop_dir(), "document" => dirs::document_dir(), "download" => dirs::download_dir(), "font" => dirs::font_dir(), "picture" => dirs::picture_dir(), "public" => dirs::public_dir(), "template" => dirs::template_dir(), "tmp" => Some(std::env::temp_dir()), "video" => dirs::video_dir(), _ => { return Err( Error::new( ErrorKind::InvalidInput, format!("Invalid dir type `{}`", args.kind.as_str()), ) .into(), ) } }; if path == None { Err(OpError::not_found(format!( "Could not get user {} directory.", args.kind.as_str() ))) } else { Ok(JsonOp::Sync(json!(path .unwrap_or_default() .into_os_string() .into_string() .unwrap_or_default()))) } } fn op_exec_path( state: &State, _args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { let current_exe = env::current_exe().unwrap(); state.check_read(&current_exe)?; let exe_url = Url::from_file_path(current_exe).unwrap(); let path = exe_url.to_file_path().unwrap(); Ok(JsonOp::Sync(json!(path))) } #[derive(Deserialize)] struct SetEnv { key: String, value: String, } fn op_set_env( state: &State, args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { let args: SetEnv = serde_json::from_value(args)?; state.check_env()?; env::set_var(args.key, args.value); Ok(JsonOp::Sync(json!({}))) } fn op_env( state: &State, _args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { state.check_env()?; let v = env::vars().collect::<HashMap<String, String>>(); Ok(JsonOp::Sync(json!(v))) } #[derive(Deserialize)] struct GetEnv { key: String, } fn op_get_env( state: &State, args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { let args: GetEnv = serde_json::from_value(args)?; state.check_env()?; let r = match env::var(args.key) { Err(env::VarError::NotPresent) => json!([]), v => json!([v?]), }; Ok(JsonOp::Sync(r)) } #[derive(Deserialize)] struct Exit { code: i32, } fn op_exit( _s: &State, args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { let args: Exit = serde_json::from_value(args)?; std::process::exit(args.code) } fn op_loadavg( state: &State, _args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { state.check_unstable("Deno.loadavg"); state.check_env()?; match sys_info::loadavg() { Ok(loadavg) => Ok(JsonOp::Sync(json!([ loadavg.one, loadavg.five, loadavg.fifteen ]))), Err(_) => Ok(JsonOp::Sync(json!([0f64, 0f64, 0f64]))), } } fn op_hostname( state: &State, _args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { state.check_env()?; let hostname = sys_info::hostname().unwrap_or_else(|_| "".to_string()); Ok(JsonOp::Sync(json!(hostname))) } fn op_os_release( state: &State, _args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { state.check_unstable("Deno.osRelease"); state.check_env()?; let release = sys_info::os_release().unwrap_or_else(|_| "".to_string()); Ok(JsonOp::Sync(json!(release))) }
pub fn init(i: &mut CoreIsolate, s: &State) { i.register_op("op_exit", s.stateful_json_op(op_exit)); i.register_op("op_env", s.stateful_json_op(op_env)); i.register_op("op_exec_path", s.stateful_json_op(op_exec_path)); i.register_op("op_set_env", s.stateful_json_op(op_set_env)); i.register_op("op_get_env", s.stateful_json_op(op_get_env)); i.register_op("op_get_dir", s.stateful_json_op(op_get_dir)); i.register_op("op_hostname", s.stateful_json_op(op_hostname)); i.register_op("op_loadavg", s.stateful_json_op(op_loadavg)); i.register_op("op_os_release", s.stateful_json_op(op_os_release)); }
function_block-full_function
[ { "content": "export function getRandomValues<\n\n T extends\n\n | Int8Array\n\n | Uint8Array\n\n | Uint8ClampedArray\n\n | Int16Array\n\n | Uint16Array\n\n | Int32Array\n\n | Uint32Array\n\n>(typedArray: T): T {\n\n assert(typedArray !== null, \"Input must not be null\");\n\n assert(typ...
Rust
src/metadata/media_info.rs
fengalin/media-toc-player
8fb6580419ec530329c131116c726bb176348956
use gettextrs::gettext; use gst::Tag; use lazy_static::lazy_static; use std::{ collections::HashMap, fmt, path::{Path, PathBuf}, sync::Arc, }; use super::{Duration, MediaContent}; #[derive(Debug)] pub struct SelectStreamError(Arc<str>); impl SelectStreamError { fn new(id: &Arc<str>) -> Self { SelectStreamError(Arc::clone(&id)) } pub fn id(&self) -> &Arc<str> { &self.0 } } impl fmt::Display for SelectStreamError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MediaInfo: unknown stream id {}", self.0) } } impl std::error::Error for SelectStreamError {} pub fn get_default_chapter_title() -> String { gettext("untitled") } macro_rules! add_tag_names ( ($($tag_type:path),+) => { { let mut tag_names = Vec::new(); $(tag_names.push(<$tag_type>::tag_name());)+ tag_names } }; ); lazy_static! { static ref TAGS_TO_SKIP_FOR_TRACK: Vec<&'static str> = { add_tag_names!( gst::tags::Album, gst::tags::AlbumSortname, gst::tags::AlbumSortname, gst::tags::AlbumArtist, gst::tags::AlbumArtistSortname, gst::tags::ApplicationName, gst::tags::ApplicationData, gst::tags::Artist, gst::tags::ArtistSortname, gst::tags::AudioCodec, gst::tags::Codec, gst::tags::ContainerFormat, gst::tags::Duration, gst::tags::Encoder, gst::tags::EncoderVersion, gst::tags::Image, gst::tags::ImageOrientation, gst::tags::PreviewImage, gst::tags::SubtitleCodec, gst::tags::Title, gst::tags::TitleSortname, gst::tags::TrackCount, gst::tags::TrackNumber, gst::tags::VideoCodec ) }; } #[derive(Debug, Clone)] pub struct Stream { pub id: Arc<str>, pub codec_printable: String, pub caps: gst::Caps, pub tags: gst::TagList, pub type_: gst::StreamType, } impl Stream { fn new(stream: &gst::Stream) -> Self { let caps = stream.get_caps().unwrap(); let tags = stream.get_tags().unwrap_or_else(gst::TagList::new); let type_ = stream.get_stream_type(); let codec_printable = match type_ { gst::StreamType::AUDIO => tags.get_index::<gst::tags::AudioCodec>(0), gst::StreamType::VIDEO => tags.get_index::<gst::tags::VideoCodec>(0), gst::StreamType::TEXT => tags.get_index::<gst::tags::SubtitleCodec>(0), _ => panic!("Stream::new can't handle {:?}", type_), } .or_else(|| tags.get_index::<gst::tags::Codec>(0)) .and_then(|value| value.get()) .map_or_else( || { let codec = caps.get_structure(0).unwrap().get_name(); let id_parts: Vec<&str> = codec.split('/').collect(); if id_parts.len() == 2 { if id_parts[1].starts_with("x-") { id_parts[1][2..].to_string() } else { id_parts[1].to_string() } } else { codec.to_string() } }, ToString::to_string, ); Stream { id: stream.get_stream_id().unwrap().as_str().into(), codec_printable, caps, tags, type_, } } } #[derive(Debug)] pub struct StreamCollection { type_: gst::StreamType, collection: HashMap<Arc<str>, Stream>, } impl StreamCollection { fn new(type_: gst::StreamType) -> Self { StreamCollection { type_, collection: HashMap::new(), } } fn add_stream(&mut self, stream: Stream) { self.collection.insert(Arc::clone(&stream.id), stream); } pub fn get<S: AsRef<str>>(&self, id: S) -> Option<&Stream> { self.collection.get(id.as_ref()) } pub fn contains<S: AsRef<str>>(&self, id: S) -> bool { self.collection.contains_key(id.as_ref()) } pub fn sorted(&self) -> impl Iterator<Item = &'_ Stream> { SortedStreamCollectionIter::new(self) } } struct SortedStreamCollectionIter<'sc> { collection: &'sc StreamCollection, sorted_iter: std::vec::IntoIter<Arc<str>>, } impl<'sc> SortedStreamCollectionIter<'sc> { fn new(collection: &'sc StreamCollection) -> Self { let mut sorted_ids: Vec<Arc<str>> = collection.collection.keys().map(Arc::clone).collect(); sorted_ids.sort(); SortedStreamCollectionIter { collection, sorted_iter: sorted_ids.into_iter(), } } } impl<'sc> Iterator for SortedStreamCollectionIter<'sc> { type Item = &'sc Stream; fn next(&mut self) -> Option<Self::Item> { self.sorted_iter .next() .and_then(|id| self.collection.get(&id)) } } #[derive(Debug)] pub struct Streams { pub audio: StreamCollection, pub video: StreamCollection, pub text: StreamCollection, cur_audio_id: Option<Arc<str>>, pub audio_changed: bool, cur_video_id: Option<Arc<str>>, pub video_changed: bool, cur_text_id: Option<Arc<str>>, pub text_changed: bool, } impl Default for Streams { fn default() -> Self { Streams { audio: StreamCollection::new(gst::StreamType::AUDIO), video: StreamCollection::new(gst::StreamType::VIDEO), text: StreamCollection::new(gst::StreamType::TEXT), cur_audio_id: None, audio_changed: false, cur_video_id: None, video_changed: false, cur_text_id: None, text_changed: false, } } } impl Streams { pub fn add_stream(&mut self, gst_stream: &gst::Stream) { let stream = Stream::new(gst_stream); match stream.type_ { gst::StreamType::AUDIO => { self.cur_audio_id.get_or_insert(Arc::clone(&stream.id)); self.audio.add_stream(stream); } gst::StreamType::VIDEO => { self.cur_video_id.get_or_insert(Arc::clone(&stream.id)); self.video.add_stream(stream); } gst::StreamType::TEXT => { self.cur_text_id.get_or_insert(Arc::clone(&stream.id)); self.text.add_stream(stream); } other => unimplemented!("{:?}", other), } } pub fn collection(&self, type_: gst::StreamType) -> &StreamCollection { match type_ { gst::StreamType::AUDIO => &self.audio, gst::StreamType::VIDEO => &self.video, gst::StreamType::TEXT => &self.text, other => unimplemented!("{:?}", other), } } pub fn is_video_selected(&self) -> bool { self.cur_video_id.is_some() } pub fn selected_audio(&self) -> Option<&Stream> { self.cur_audio_id .as_ref() .and_then(|stream_id| self.audio.get(stream_id)) } pub fn selected_video(&self) -> Option<&Stream> { self.cur_video_id .as_ref() .and_then(|stream_id| self.video.get(stream_id)) } pub fn selected_text(&self) -> Option<&Stream> { self.cur_text_id .as_ref() .and_then(|stream_id| self.text.get(stream_id)) } pub fn select_streams(&mut self, ids: &[Arc<str>]) -> Result<(), SelectStreamError> { let mut is_audio_selected = false; let mut is_text_selected = false; let mut is_video_selected = false; for id in ids { if self.audio.contains(id) { is_audio_selected = true; self.audio_changed = self .selected_audio() .map_or(true, |prev_stream| *id != prev_stream.id); self.cur_audio_id = Some(Arc::clone(id)); } else if self.text.contains(id) { is_text_selected = true; self.text_changed = self .selected_text() .map_or(true, |prev_stream| *id != prev_stream.id); self.cur_text_id = Some(Arc::clone(id)); } else if self.video.contains(id) { is_video_selected = true; self.video_changed = self .selected_video() .map_or(true, |prev_stream| *id != prev_stream.id); self.cur_video_id = Some(Arc::clone(id)); } else { return Err(SelectStreamError::new(id)); } } if !is_audio_selected { self.audio_changed = self.cur_audio_id.take().map_or(false, |_| true); } if !is_text_selected { self.text_changed = self.cur_text_id.take().map_or(false, |_| true); } if !is_video_selected { self.video_changed = self.cur_video_id.take().map_or(false, |_| true); } Ok(()) } pub fn audio_codec(&self) -> Option<&str> { self.selected_audio() .map(|stream| stream.codec_printable.as_str()) } pub fn video_codec(&self) -> Option<&str> { self.selected_video() .map(|stream| stream.codec_printable.as_str()) } fn tag_list<'a, T: gst::Tag<'a>>(&'a self) -> Option<&gst::TagList> { self.selected_audio() .and_then(|selected_audio| { if selected_audio.tags.get_size::<T>() > 0 { Some(&selected_audio.tags) } else { None } }) .or_else(|| { self.selected_video().and_then(|selected_video| { if selected_video.tags.get_size::<T>() > 0 { Some(&selected_video.tags) } else { None } }) }) } } #[derive(Debug, Default)] pub struct MediaInfo { pub name: String, pub file_name: String, pub path: PathBuf, pub content: MediaContent, pub tags: gst::TagList, pub toc: Option<gst::Toc>, pub chapter_count: Option<usize>, pub description: String, pub duration: Duration, pub streams: Streams, } impl MediaInfo { pub fn new(path: &Path) -> Self { MediaInfo { name: path.file_stem().unwrap().to_str().unwrap().to_owned(), file_name: path.file_name().unwrap().to_str().unwrap().to_owned(), path: path.to_owned(), ..MediaInfo::default() } } pub fn add_stream(&mut self, gst_stream: &gst::Stream) { self.streams.add_stream(gst_stream); self.content.add_stream_type(gst_stream.get_stream_type()); } pub fn add_tags(&mut self, tags: &gst::TagList) { self.tags = self.tags.merge(tags, gst::TagMergeMode::Keep); } fn tag_list<'a, T: gst::Tag<'a>>(&'a self) -> Option<&gst::TagList> { if self.tags.get_size::<T>() > 0 { Some(&self.tags) } else { None } } fn tag_for_display<'a, Primary, Secondary>( &'a self, ) -> Option<<Primary as gst::Tag<'a>>::TagType> where Primary: gst::Tag<'a> + 'a, Secondary: gst::Tag<'a, TagType = <Primary as gst::Tag<'a>>::TagType> + 'a, { self.tag_list::<Primary>() .or_else(|| self.tag_list::<Secondary>()) .or_else(|| { self.streams .tag_list::<Primary>() .or_else(|| self.streams.tag_list::<Secondary>()) }) .and_then(|tag_list| { tag_list .get_index::<Primary>(0) .or_else(|| tag_list.get_index::<Secondary>(0)) .and_then(|value| value.get()) }) } pub fn media_artist(&self) -> Option<&str> { self.tag_for_display::<gst::tags::Artist, gst::tags::AlbumArtist>() } pub fn media_title(&self) -> Option<&str> { self.tag_for_display::<gst::tags::Title, gst::tags::Album>() } pub fn media_image(&self) -> Option<gst::Sample> { self.tag_for_display::<gst::tags::Image, gst::tags::PreviewImage>() } pub fn container(&self) -> Option<&str> { if let Some(audio_codec) = self.streams.audio_codec() { if self.streams.video_codec().is_none() && audio_codec.to_lowercase().find("mp3").is_some() { return None; } } self.tags .get_index::<gst::tags::ContainerFormat>(0) .and_then(|value| value.get()) } }
use gettextrs::gettext; use gst::Tag; use lazy_static::lazy_static; use std::{ collections::HashMap, fmt, path::{Path, PathBuf}, sync::Arc, }; use super::{Duration, MediaContent}; #[derive(Debug)] pub struct SelectStreamError(Arc<str>); impl SelectStreamError { fn new(id: &Arc<str>) -> Self { SelectStreamError(Arc::clone(&id)) } pub fn id(&self) -> &Arc<str> { &self.0 } } impl fmt::Display for SelectStreamError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MediaInfo: unknown stream id {}", self.0) } } impl std::error::Error for SelectStreamError {} pub fn get_default_chapter_title() -> String { gettext("untitled") } macro_rules! add_tag_names ( ($($tag_type:path),+) => { { let mut tag_names = Vec::new(); $(tag_names.push(<$tag_type>::tag_name());)+ tag_names } }; ); lazy_static! { static ref TAGS_TO_SKIP_FOR_TRACK: Vec<&'static str> = { add_tag_names!( gst::tags::Album, gst::tags::AlbumSortname, gst::tags::AlbumSortname, gst::tags::AlbumArtist, gst::tags::AlbumArtistSortname, gst::tags::ApplicationName, gst::tags::ApplicationData, gst::tags::Artist, gst::tags::ArtistSortname, gst::tags::AudioCodec, gst::tags::Codec, gst::tags::ContainerFormat, gst::tags::Duration, gst::tags::Encoder, gst::tags::EncoderVersion, gst::tags::Image, gst::tags::ImageOrientation, gst::tags::PreviewImage, gst::tags::SubtitleCodec, gst::tags::Title, gst::tags::TitleSortname, gst::tags::TrackCount, gst::tags::TrackNumber, gst::tags::VideoCodec ) }; } #[derive(Debug, Clone)] pub struct Stream { pub id: Arc<str>, pub codec_printable: String, pub caps: gst::Caps, pub tags: gst::TagList, pub type_: gst::StreamType, } impl Stream { fn new(stream: &gst::Stream) -> Self { let caps = stream.get_caps().unwrap(); let tags = stream.get_tags().unwrap_or_else(gst::TagList::new); let type_ = stream.get_stream_type(); let codec_printable = match type_ { gst::StreamType::AUDIO => tags.get_index::<gst::tags::AudioCodec>(0), gst::StreamType::VIDEO => tags.get_index::<gst::tags::VideoCodec>(0), gst::StreamType::TEXT => tags.get_index::<gst::tags::SubtitleCodec>(0), _ => panic!("Stream::new can't handle {:?}", type_), } .or_else(|| tags.get_index::<gst::tags::Codec>(0)) .and_then(|value| value.get()) .map_or_else( || { let codec = caps.get_structure(0).unwrap().get_name(); let id_parts: Vec<&str> = codec.split('/').collect(); if id_parts.len() == 2 { if id_parts[1].starts_with("x-") { id_parts[1][2..].to_string() } else { id_parts[1].to_string() } } else { codec.to_string() } }, ToString::to_string, ); Stream { id: stream.get_stream_id().unwrap().as_str().into(), codec_printable, caps, tags, type_, } } } #[derive(Debug)] pub struct StreamCollection { type_: gst::StreamType, collection: HashMap<Arc<str>, Stream>, } impl StreamCollection { fn new(type_: gst::StreamType) -> Self { StreamCollection { type_, collection: HashMap::new(), } } fn add_stream(&mut self, stream: Stream) { self.collection.insert(Arc::clone(&stream.id), stream); } pub fn get<S: AsRef<str>>(&self, id: S) -> Option<&Stream> { self.collection.get(id.as_ref()) } pub fn contains<S: AsRef<str>>(&self, id: S) -> bool { self.collection.contains_key(id.as_ref()) } pub fn sorted(&self) -> impl Iterator<Item = &'_ Stream> { SortedStreamCollectionIter::new(self) } } struct SortedStreamCollectionIter<'sc> { collection: &'sc StreamCollection, sorted_iter: std::vec::IntoIter<Arc<str>>, } impl<'sc> SortedStreamCollectionIter<'sc> { fn new(collection: &'sc StreamCollection) -> Self { let mut sorted_ids: Vec<Arc<str>> = collection.collection.keys().map(Arc::clone).collect(); sorted_ids.sort(); SortedStreamCollectionIter { collection, sorted_iter: sorted_ids.into_iter(), } } } impl<'sc> Iterator for SortedStreamCollectionIter<'sc> { type Item = &'sc Stream; fn next(&mut self) -> Option<Self::Item> { self.sorted_iter .next() .and_then(|id| self.collection.get(&id)) } } #[derive(Debug)] pub struct Streams { pub audio: StreamCollection, pub video: StreamCollection, pub text: StreamCollection, cur_audio_id: Option<Arc<str>>, pub audio_changed: bool, cur_video_id: Option<Arc<str>>, pub video_changed: bool, cur_text_id: Option<Arc<str>>, pub text_changed: bool, } impl Default for Streams { fn default() -> Self { Streams { audio: StreamCollection::new(gst::StreamType::AUDIO), video: StreamCollection::new(gst::StreamType::VIDEO), text: StreamCollection::new(gst::StreamType::TEXT), cur_audio_id: None, audio_changed: false, cur_video_id: None, video_changed: false, cur_text_id: None, text_changed: false, } } } impl Streams { pub fn add_stream(&mut self, gst_stream: &gst::Stream) { let stream = Stream::new(gst_stream); match stream.type_ { gst::StreamType::AUDIO => { self.cur_audio_id.get_or_insert(Arc::clone(&stream.id)); self.audio.add_stream(stream); } gst::StreamType::VIDEO => { self.cur_video_id.get_or_insert(Arc::clone(&stream.id)); self.video.add_stream(stream); } gst::StreamType::TEXT => { self.cur_text_id.get_or_insert(Arc::clone(&stream.id)); self.text.add_stream(stream); } other => unimplemented!("{:?}", other), } } pub fn collection(&self, type_: gst::StreamType) -> &StreamCollection {
} pub fn is_video_selected(&self) -> bool { self.cur_video_id.is_some() } pub fn selected_audio(&self) -> Option<&Stream> { self.cur_audio_id .as_ref() .and_then(|stream_id| self.audio.get(stream_id)) } pub fn selected_video(&self) -> Option<&Stream> { self.cur_video_id .as_ref() .and_then(|stream_id| self.video.get(stream_id)) } pub fn selected_text(&self) -> Option<&Stream> { self.cur_text_id .as_ref() .and_then(|stream_id| self.text.get(stream_id)) } pub fn select_streams(&mut self, ids: &[Arc<str>]) -> Result<(), SelectStreamError> { let mut is_audio_selected = false; let mut is_text_selected = false; let mut is_video_selected = false; for id in ids { if self.audio.contains(id) { is_audio_selected = true; self.audio_changed = self .selected_audio() .map_or(true, |prev_stream| *id != prev_stream.id); self.cur_audio_id = Some(Arc::clone(id)); } else if self.text.contains(id) { is_text_selected = true; self.text_changed = self .selected_text() .map_or(true, |prev_stream| *id != prev_stream.id); self.cur_text_id = Some(Arc::clone(id)); } else if self.video.contains(id) { is_video_selected = true; self.video_changed = self .selected_video() .map_or(true, |prev_stream| *id != prev_stream.id); self.cur_video_id = Some(Arc::clone(id)); } else { return Err(SelectStreamError::new(id)); } } if !is_audio_selected { self.audio_changed = self.cur_audio_id.take().map_or(false, |_| true); } if !is_text_selected { self.text_changed = self.cur_text_id.take().map_or(false, |_| true); } if !is_video_selected { self.video_changed = self.cur_video_id.take().map_or(false, |_| true); } Ok(()) } pub fn audio_codec(&self) -> Option<&str> { self.selected_audio() .map(|stream| stream.codec_printable.as_str()) } pub fn video_codec(&self) -> Option<&str> { self.selected_video() .map(|stream| stream.codec_printable.as_str()) } fn tag_list<'a, T: gst::Tag<'a>>(&'a self) -> Option<&gst::TagList> { self.selected_audio() .and_then(|selected_audio| { if selected_audio.tags.get_size::<T>() > 0 { Some(&selected_audio.tags) } else { None } }) .or_else(|| { self.selected_video().and_then(|selected_video| { if selected_video.tags.get_size::<T>() > 0 { Some(&selected_video.tags) } else { None } }) }) } } #[derive(Debug, Default)] pub struct MediaInfo { pub name: String, pub file_name: String, pub path: PathBuf, pub content: MediaContent, pub tags: gst::TagList, pub toc: Option<gst::Toc>, pub chapter_count: Option<usize>, pub description: String, pub duration: Duration, pub streams: Streams, } impl MediaInfo { pub fn new(path: &Path) -> Self { MediaInfo { name: path.file_stem().unwrap().to_str().unwrap().to_owned(), file_name: path.file_name().unwrap().to_str().unwrap().to_owned(), path: path.to_owned(), ..MediaInfo::default() } } pub fn add_stream(&mut self, gst_stream: &gst::Stream) { self.streams.add_stream(gst_stream); self.content.add_stream_type(gst_stream.get_stream_type()); } pub fn add_tags(&mut self, tags: &gst::TagList) { self.tags = self.tags.merge(tags, gst::TagMergeMode::Keep); } fn tag_list<'a, T: gst::Tag<'a>>(&'a self) -> Option<&gst::TagList> { if self.tags.get_size::<T>() > 0 { Some(&self.tags) } else { None } } fn tag_for_display<'a, Primary, Secondary>( &'a self, ) -> Option<<Primary as gst::Tag<'a>>::TagType> where Primary: gst::Tag<'a> + 'a, Secondary: gst::Tag<'a, TagType = <Primary as gst::Tag<'a>>::TagType> + 'a, { self.tag_list::<Primary>() .or_else(|| self.tag_list::<Secondary>()) .or_else(|| { self.streams .tag_list::<Primary>() .or_else(|| self.streams.tag_list::<Secondary>()) }) .and_then(|tag_list| { tag_list .get_index::<Primary>(0) .or_else(|| tag_list.get_index::<Secondary>(0)) .and_then(|value| value.get()) }) } pub fn media_artist(&self) -> Option<&str> { self.tag_for_display::<gst::tags::Artist, gst::tags::AlbumArtist>() } pub fn media_title(&self) -> Option<&str> { self.tag_for_display::<gst::tags::Title, gst::tags::Album>() } pub fn media_image(&self) -> Option<gst::Sample> { self.tag_for_display::<gst::tags::Image, gst::tags::PreviewImage>() } pub fn container(&self) -> Option<&str> { if let Some(audio_codec) = self.streams.audio_codec() { if self.streams.video_codec().is_none() && audio_codec.to_lowercase().find("mp3").is_some() { return None; } } self.tags .get_index::<gst::tags::ContainerFormat>(0) .and_then(|value| value.get()) } }
match type_ { gst::StreamType::AUDIO => &self.audio, gst::StreamType::VIDEO => &self.video, gst::StreamType::TEXT => &self.text, other => unimplemented!("{:?}", other), }
if_condition
[ { "content": "fn parse_to<T: std::str::FromStr>(i: &str) -> IResult<&str, T> {\n\n let (i, res) = digit1(i)?;\n\n\n\n res.parse::<T>()\n\n .map(move |value| (i, value))\n\n .map_err(move |_| Err::Error((i, ErrorKind::ParseTo)))\n\n}\n", "file_path": "src/metadata/mod.rs", "rank": 2, ...
Rust
src/dat/civilization.rs
vtabbott/djin
9b63973941a9f6efc327f18085c00838e02e80b7
use crate::dat::common::DeString; use crate::dat::unit::Task; use crate::dat::ResourceUsage; const RESOURCE_STORAGE_SIZE: usize = 3; const GRAPHIC_DISPLACEMENT_SIZE: usize = 3; const BUILDING_ANNEXES_SIZE: usize = 4; #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Civilizations { pub size: u16, #[protocol(length_prefix(elements(size)))] pub civilizations: Vec<Civilization>, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Civilization { pub player_type: u8, pub name: DeString, pub resource_size: u16, pub tech_tree_id: i16, pub team_bonus_id: u16, #[protocol(length_prefix(elements(resource_size)))] pub resources: Vec<f32>, pub icon_set: u8, pub units_pointers_size: u16, #[protocol(length_prefix(elements(units_pointers_size)))] pub unit_pointers: Vec<u32>, #[protocol(length_prefix(pointers(unit_pointers)))] pub units: Vec<Unit>, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Unit { pub unit_type: UnitType, pub id: i16, pub language_dll_name: i32, pub language_dll_creation: i32, pub class: i16, pub standing_graphics: (i16, i16), pub dying_graphic: i16, pub undead_graphic: i16, pub undead_mode: u8, pub hit_points: i16, pub line_of_sight: f32, pub garrison_capacity: u8, pub collision_box: (f32, f32, f32), pub train_sound: i16, pub damage_sound: i16, pub dead_unit_id: i16, pub blood_unit_id: i16, pub sort_number: u8, pub can_be_built_on: u8, pub icon_id: i16, pub hide_in_editor: u8, pub old_portrait_pict: i16, pub enabled: u8, pub disabled: u8, pub placement_side_terrain: (i16, i16), pub placement_terrain: (i16, i16), pub clearance_size: (f32, f32), pub hill_mode: u8, pub fog_visibility: u8, pub terrain_restriction: i16, pub fly_mode: u8, pub resource_capacity: i16, pub resource_decay: f32, pub blast_defense_level: u8, pub combat_level: u8, pub interaction_mode: u8, pub minimap_mode: u8, pub interface_kind: u8, pub multiple_attribute_mode: f32, pub minimap_color: u8, pub language_dll_help: i32, pub language_dll_hot_key_text: i32, pub hot_key: i32, pub recyclable: u8, pub enable_auto_gather: u8, pub create_doppelganger_on_death: u8, pub resource_gather_group: u8, pub occlusion_mode: u8, pub obstruction_type: u8, pub obstruction_class: u8, pub r#trait: u8, pub civilization: u8, pub nothing: i16, pub selection_effect: u8, pub editor_selection_colour: u8, pub outline_box: (f32, f32, f32), pub data: u32, pub data_2: u32, #[protocol(fixed_length(RESOURCE_STORAGE_SIZE))] pub resources_storage: Vec<ResourceStorage>, pub damage_graphic_size: u8, #[protocol(length_prefix(elements(damage_graphic_size)))] pub damage_graphics: Vec<DamageGraphic>, pub selection_sound: i16, pub dying_sound: i16, pub wwise_train_sound_id: u32, pub wwise_damage_sound_id: u32, pub wwise_selection_sound_id: u32, pub wwise_dying_sound_id: u32, pub old_attack_reaction: u8, pub convert_terrain: u8, pub name: DeString, pub copy_id: i16, pub base_id: i16, #[protocol(skip_if("unit_type < UnitType::Flag"))] pub speed: Option<f32>, #[protocol(skip_if("unit_type < UnitType::DeadFish"))] pub dead_fish: Option<DeadFish>, #[protocol(skip_if("unit_type < UnitType::Bird"))] pub bird: Option<Bird>, #[protocol(skip_if("unit_type < UnitType::Combatant"))] pub type_50: Option<Combatant>, #[protocol(skip_if("unit_type != UnitType::Projectile"))] pub projectile: Option<Projectile>, #[protocol(skip_if("unit_type < UnitType::Creatable"))] pub creatable: Option<Creatable>, #[protocol(skip_if("unit_type != UnitType::Building"))] pub building: Option<Building>, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct ResourceStorage(i16, f32, u8); #[derive(Protocol, Debug, Clone, PartialEq)] pub struct DamageGraphic { pub graphic_id: i16, pub damage_percent: i16, pub apply_mode: u8, } #[derive(Protocol, Debug, Clone, PartialEq, PartialOrd)] #[protocol(discriminant = "integer")] #[repr(u8)] pub enum UnitType { EyeCandy = 10, Trees = 15, Flag = 20, Dopl = 25, DeadFish = 30, Bird = 40, Combatant = 50, Projectile = 60, Creatable = 70, Building = 80, AoeTrees = 90, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct DeadFish { pub walking_graphic: i16, pub running_graphic: i16, pub rotation_speed: f32, pub old_size_class: u8, pub tracking_unit: i16, pub tracking_unit_mode: u8, pub tracking_unit_density: f32, pub old_move_algorithm: u8, pub turn_radius: f32, pub turn_radius_speed: f32, pub max_yaw_per_second_moving: f32, pub stationary_yaw_revolution_time: f32, pub max_yaw_per_second_stationary: f32, pub min_collision_size_multiplier: f32, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Bird { pub default_task_id: i16, pub search_radius: f32, pub work_rate: f32, pub drop_sites_size: (i16, i16, i16), pub task_swap_group: u8, pub attack_sound: i16, pub move_sound: i16, pub wwise_attack_sound_id: u32, pub wwise_move_sound_id: u32, pub run_pattern: u8, pub task_list_size_count: i16, #[protocol(length_prefix(elements(task_list_size_count)))] pub task_list: Vec<Task>, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Combatant { pub base_armor: i16, pub attack_count_size: i16, #[protocol(length_prefix(elements(attack_count_size)))] pub attacks: Vec<AttackOrArmor>, pub armor_count_size: i16, #[protocol(length_prefix(elements(armor_count_size)))] pub armor: Vec<AttackOrArmor>, pub defense_terrain_bonus: i16, pub bonus_damage_resistance: f32, pub max_range: f32, pub blast_width: f32, pub reload_time: f32, pub projectile_unit_id: i16, pub accuracy_percent: i16, pub break_off_combat: u8, pub frame_delay: i16, #[protocol(fixed_length(GRAPHIC_DISPLACEMENT_SIZE))] pub graphic_displacement: Vec<f32>, pub blast_attack_level: u8, pub min_range: f32, pub accuracy_dispersion: f32, pub attack_graphic: i16, pub displayed_melee_armour: i16, pub displayed_attack: i16, pub displayed_range: f32, pub displayed_reload_time: f32, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Projectile { pub projectile_type: u8, pub smart_mode: u8, pub hit_mode: u8, pub vanish_mode: u8, pub area_effect_specials: u8, pub projectile_arc: f32, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Creatable { #[protocol(fixed_length(RESOURCE_STORAGE_SIZE))] pub resources_costs: Vec<ResourceUsage>, pub train_time: i16, pub train_location_id: i16, pub button_id: u8, pub rear_attack_modifier: f32, pub flank_attack_modifier: f32, pub creatable_type: u8, pub hero_mode: u8, pub garrison_graphic: i32, pub spawning_graphic: i16, pub upgrade_graphic: i16, pub hero_glow_graphic: i16, pub max_charge: f32, pub recharge_rate: f32, pub charge_event: i16, pub charge_type: i16, pub total_projectiles: f32, pub max_total_projectiles: u8, pub projectile_spawning_area: (f32, f32, f32), pub secondary_projectile_unit: i32, pub special_graphic: i32, pub special_ability: u8, pub displayed_pierce_armour: i16, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Building { pub construction_graphic_id: i16, pub snow_graphic_id: i16, pub destruction_graphic_id: i16, pub destruction_rubble_graphic_id: i16, pub researching_graphic: i16, pub research_completed_graphic: i16, pub adjacent_mode: u8, pub graphics_angle: i16, pub disappears_when_built: u8, pub stack_unit_id: i16, pub foundation_terrain_id: i16, pub old_overlay_id: i16, pub tech_id: i16, pub can_burn: u8, #[protocol(fixed_length(BUILDING_ANNEXES_SIZE))] pub building_annexes: Vec<Annexe>, pub head_unit: i16, pub transform_unit: i16, pub transform_sound: i16, pub construction_sound: i16, pub wwise_transform_sound_id: u32, pub wwise_construction_sound_id: u32, pub garrison_type: u8, pub garrison_heal_rate: f32, pub garrison_repair_rate: f32, pub pile_unit: i16, #[protocol(fixed_length(6))] pub looting_table: Vec<u8>, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Annexe { pub unit_id: i16, pub misplacement: (f32, f32), } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct AttackOrArmor { pub class: i16, pub amount: i16, }
use crate::dat::common::DeString; use crate::dat::unit::Task; use crate::dat::ResourceUsage; const RESOURCE_STORAGE_SIZE: usize = 3; const GRAPHIC_DISPLACEMENT_SIZE: usize = 3; const BUILDING_ANNEXES_SIZE: usize = 4; #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Civilizations { pub size: u16, #[protocol(length_prefix(elements(size)))] pub civilizations: Vec<Civilization>, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Civilization { pub player_type: u8, pub name: DeString, pub resource_size: u16, pub tech_tree_id: i16, pub team_bonus_id: u16, #[protocol(length_prefix(elements(resource_size)))] pub resources: Vec<f32>, pub icon_set: u8, pub units_pointers_size: u16, #[protocol(length_prefix(elements(units_pointers_size)))] pub unit_pointers: Vec<u32>, #[protocol(length_prefix(pointers(unit_pointers)))] pub units: Vec<Unit>, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Unit { pub unit_type: UnitType, pub id: i16, pub language_dll_name: i32, pub language_dll_creation: i32, pub class: i16, pub standing_graphics: (i16, i16), pub dying_graphic: i16, pub undead_graphic: i16, pub undead_mode: u8, pub hit_points: i16, pub line_of_sight: f32, pub garrison_capacity: u8, pub collision_box: (f32, f32, f32), pub train_sound: i16, pub damage_sound: i16, pub dead_unit_id: i16, pub blood_unit_id: i16, pub sort_number: u8, pub can_be_built_on: u8, pub icon_id: i16, pub hide_in_editor: u8, pub old_portrait_pict: i16, pub enabled: u8, pub disabled: u8, pub placement_side_terrain: (i16, i16), pub placement_terrain: (i16, i16), pub clearance_size: (f32, f32), pub hill_mode: u8, pub fog_visibility: u8, pub terrain_restriction: i16, pub fly_mode: u8, pub resource_ca
Creatable = 70, Building = 80, AoeTrees = 90, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct DeadFish { pub walking_graphic: i16, pub running_graphic: i16, pub rotation_speed: f32, pub old_size_class: u8, pub tracking_unit: i16, pub tracking_unit_mode: u8, pub tracking_unit_density: f32, pub old_move_algorithm: u8, pub turn_radius: f32, pub turn_radius_speed: f32, pub max_yaw_per_second_moving: f32, pub stationary_yaw_revolution_time: f32, pub max_yaw_per_second_stationary: f32, pub min_collision_size_multiplier: f32, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Bird { pub default_task_id: i16, pub search_radius: f32, pub work_rate: f32, pub drop_sites_size: (i16, i16, i16), pub task_swap_group: u8, pub attack_sound: i16, pub move_sound: i16, pub wwise_attack_sound_id: u32, pub wwise_move_sound_id: u32, pub run_pattern: u8, pub task_list_size_count: i16, #[protocol(length_prefix(elements(task_list_size_count)))] pub task_list: Vec<Task>, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Combatant { pub base_armor: i16, pub attack_count_size: i16, #[protocol(length_prefix(elements(attack_count_size)))] pub attacks: Vec<AttackOrArmor>, pub armor_count_size: i16, #[protocol(length_prefix(elements(armor_count_size)))] pub armor: Vec<AttackOrArmor>, pub defense_terrain_bonus: i16, pub bonus_damage_resistance: f32, pub max_range: f32, pub blast_width: f32, pub reload_time: f32, pub projectile_unit_id: i16, pub accuracy_percent: i16, pub break_off_combat: u8, pub frame_delay: i16, #[protocol(fixed_length(GRAPHIC_DISPLACEMENT_SIZE))] pub graphic_displacement: Vec<f32>, pub blast_attack_level: u8, pub min_range: f32, pub accuracy_dispersion: f32, pub attack_graphic: i16, pub displayed_melee_armour: i16, pub displayed_attack: i16, pub displayed_range: f32, pub displayed_reload_time: f32, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Projectile { pub projectile_type: u8, pub smart_mode: u8, pub hit_mode: u8, pub vanish_mode: u8, pub area_effect_specials: u8, pub projectile_arc: f32, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Creatable { #[protocol(fixed_length(RESOURCE_STORAGE_SIZE))] pub resources_costs: Vec<ResourceUsage>, pub train_time: i16, pub train_location_id: i16, pub button_id: u8, pub rear_attack_modifier: f32, pub flank_attack_modifier: f32, pub creatable_type: u8, pub hero_mode: u8, pub garrison_graphic: i32, pub spawning_graphic: i16, pub upgrade_graphic: i16, pub hero_glow_graphic: i16, pub max_charge: f32, pub recharge_rate: f32, pub charge_event: i16, pub charge_type: i16, pub total_projectiles: f32, pub max_total_projectiles: u8, pub projectile_spawning_area: (f32, f32, f32), pub secondary_projectile_unit: i32, pub special_graphic: i32, pub special_ability: u8, pub displayed_pierce_armour: i16, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Building { pub construction_graphic_id: i16, pub snow_graphic_id: i16, pub destruction_graphic_id: i16, pub destruction_rubble_graphic_id: i16, pub researching_graphic: i16, pub research_completed_graphic: i16, pub adjacent_mode: u8, pub graphics_angle: i16, pub disappears_when_built: u8, pub stack_unit_id: i16, pub foundation_terrain_id: i16, pub old_overlay_id: i16, pub tech_id: i16, pub can_burn: u8, #[protocol(fixed_length(BUILDING_ANNEXES_SIZE))] pub building_annexes: Vec<Annexe>, pub head_unit: i16, pub transform_unit: i16, pub transform_sound: i16, pub construction_sound: i16, pub wwise_transform_sound_id: u32, pub wwise_construction_sound_id: u32, pub garrison_type: u8, pub garrison_heal_rate: f32, pub garrison_repair_rate: f32, pub pile_unit: i16, #[protocol(fixed_length(6))] pub looting_table: Vec<u8>, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Annexe { pub unit_id: i16, pub misplacement: (f32, f32), } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct AttackOrArmor { pub class: i16, pub amount: i16, }
pacity: i16, pub resource_decay: f32, pub blast_defense_level: u8, pub combat_level: u8, pub interaction_mode: u8, pub minimap_mode: u8, pub interface_kind: u8, pub multiple_attribute_mode: f32, pub minimap_color: u8, pub language_dll_help: i32, pub language_dll_hot_key_text: i32, pub hot_key: i32, pub recyclable: u8, pub enable_auto_gather: u8, pub create_doppelganger_on_death: u8, pub resource_gather_group: u8, pub occlusion_mode: u8, pub obstruction_type: u8, pub obstruction_class: u8, pub r#trait: u8, pub civilization: u8, pub nothing: i16, pub selection_effect: u8, pub editor_selection_colour: u8, pub outline_box: (f32, f32, f32), pub data: u32, pub data_2: u32, #[protocol(fixed_length(RESOURCE_STORAGE_SIZE))] pub resources_storage: Vec<ResourceStorage>, pub damage_graphic_size: u8, #[protocol(length_prefix(elements(damage_graphic_size)))] pub damage_graphics: Vec<DamageGraphic>, pub selection_sound: i16, pub dying_sound: i16, pub wwise_train_sound_id: u32, pub wwise_damage_sound_id: u32, pub wwise_selection_sound_id: u32, pub wwise_dying_sound_id: u32, pub old_attack_reaction: u8, pub convert_terrain: u8, pub name: DeString, pub copy_id: i16, pub base_id: i16, #[protocol(skip_if("unit_type < UnitType::Flag"))] pub speed: Option<f32>, #[protocol(skip_if("unit_type < UnitType::DeadFish"))] pub dead_fish: Option<DeadFish>, #[protocol(skip_if("unit_type < UnitType::Bird"))] pub bird: Option<Bird>, #[protocol(skip_if("unit_type < UnitType::Combatant"))] pub type_50: Option<Combatant>, #[protocol(skip_if("unit_type != UnitType::Projectile"))] pub projectile: Option<Projectile>, #[protocol(skip_if("unit_type < UnitType::Creatable"))] pub creatable: Option<Creatable>, #[protocol(skip_if("unit_type != UnitType::Building"))] pub building: Option<Building>, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct ResourceStorage(i16, f32, u8); #[derive(Protocol, Debug, Clone, PartialEq)] pub struct DamageGraphic { pub graphic_id: i16, pub damage_percent: i16, pub apply_mode: u8, } #[derive(Protocol, Debug, Clone, PartialEq, PartialOrd)] #[protocol(discriminant = "integer")] #[repr(u8)] pub enum UnitType { EyeCandy = 10, Trees = 15, Flag = 20, Dopl = 25, DeadFish = 30, Bird = 40, Combatant = 50, Projectile = 60,
random
[ { "content": "\n\n#[derive(Protocol, Debug, Clone, PartialEq)]\n\npub struct Task {\n\n pub task_type: i16,\n\n pub id: i16,\n\n pub is_default: u8,\n\n pub action_type: i16,\n\n pub class_id: i16,\n\n pub unit_id: i16,\n\n pub terrain_id: i16,\n\n pub resource_in: i16,\n\n pub resour...
Rust
src/memfd.rs
lucab/memfd-rs
40e00f1b7a6fad816ab1394ce4cc1910c478d32a
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use std::{ffi, fs, os::raw}; use crate::{nr, sealing}; #[cfg(any(target_os = "android", target_os="linux"))] unsafe fn memfd_create(name: *const raw::c_char, flags: raw::c_uint) -> raw::c_int { libc::syscall(libc::SYS_memfd_create, name, flags) as raw::c_int } #[derive(Clone, Debug)] pub struct MemfdOptions { allow_sealing: bool, cloexec: bool, hugetlb: Option<HugetlbSize>, } impl MemfdOptions { pub fn new() -> Self { Self::default() } pub fn allow_sealing(mut self, value: bool) -> Self { self.allow_sealing = value; self } pub fn close_on_exec(mut self, value: bool) -> Self { self.cloexec = value; self } pub fn hugetlb(mut self, size: Option<HugetlbSize>) -> Self { self.hugetlb = size; self } fn bitflags(&self) -> u32 { let mut bits = 0; if self.allow_sealing { bits |= nr::MFD_ALLOW_SEALING; } if self.cloexec { bits |= nr::MFD_CLOEXEC; } if let Some(ref hugetlb) = self.hugetlb { bits |= hugetlb.bitflags(); bits |= nr::MFD_HUGETLB; } bits } pub fn create<T: AsRef<str>>(&self, name: T) -> Result<Memfd, crate::Error> { let flags = self.bitflags(); unsafe { let cname = ffi::CString::new(name.as_ref()).map_err(crate::Error::NameCStringConversion)?; let name_ptr = cname.as_ptr(); let fd = memfd_create(name_ptr, flags); if fd < 0 { return Err(crate::Error::Create(std::io::Error::last_os_error())); } Ok(Memfd::from_raw_fd(fd)) } } } impl Default for MemfdOptions { fn default() -> Self { Self { allow_sealing: false, cloexec: true, hugetlb: None, } } } #[allow(clippy::all)] #[derive(Copy, Clone, Debug)] pub enum HugetlbSize { Huge64KB, Huge512KB, Huge1MB, Huge2MB, Huge8MB, Huge16MB, Huge256MB, Huge1GB, Huge2GB, Huge16GB, } impl HugetlbSize { fn bitflags(self) -> u32 { match self { HugetlbSize::Huge64KB => nr::MFD_HUGE_64KB, HugetlbSize::Huge512KB => nr::MFD_HUGE_512KB, HugetlbSize::Huge1MB => nr::MFD_HUGE_1MB, HugetlbSize::Huge2MB => nr::MFD_HUGE_2MB, HugetlbSize::Huge8MB => nr::MFD_HUGE_8MB, HugetlbSize::Huge16MB => nr::MFD_HUGE_16MB, HugetlbSize::Huge256MB => nr::MFD_HUGE_256MB, HugetlbSize::Huge1GB => nr::MFD_HUGE_1GB, HugetlbSize::Huge2GB => nr::MFD_HUGE_2GB, HugetlbSize::Huge16GB => nr::MFD_HUGE_16GB, } } } #[derive(Debug)] pub struct Memfd { file: fs::File, } impl Memfd { pub fn try_from_fd<F>(fd: F) -> Result<Self, F> where F: AsRawFd + IntoRawFd, { if !is_memfd(&fd) { Err(fd) } else { let file = unsafe { fs::File::from_raw_fd(fd.into_raw_fd()) }; Ok(Self { file }) } } pub fn try_from_file(file: fs::File) -> Result<Self, fs::File> { Self::try_from_fd(file) } pub fn as_file(&self) -> &fs::File { &self.file } pub fn into_file(self) -> fs::File { self.file } pub fn seals(&self) -> Result<sealing::SealsHashSet, crate::Error> { let flags = Self::file_get_seals(&self.file)?; Ok(sealing::bitflags_to_seals(flags)) } pub fn add_seal(&self, seal: sealing::FileSeal) -> Result<(), crate::Error> { use std::iter::FromIterator; let set = sealing::SealsHashSet::from_iter(vec![seal]); self.add_seals(&set) } pub fn add_seals(&self, seals: &sealing::SealsHashSet) -> Result<(), crate::Error> { let fd = self.file.as_raw_fd(); let flags = sealing::seals_to_bitflags(seals); let r = unsafe { libc::syscall(libc::SYS_fcntl, fd, libc::F_ADD_SEALS, flags) }; if r < 0 { return Err(crate::Error::AddSeals(std::io::Error::last_os_error())); }; Ok(()) } fn file_get_seals(fp: &fs::File) -> Result<u64, crate::Error> { let fd = fp.as_raw_fd(); let r = unsafe { libc::syscall(libc::SYS_fcntl, fd, libc::F_GET_SEALS) }; if r < 0 { return Err(crate::Error::GetSeals(std::io::Error::last_os_error())); }; Ok(r as u64) } } impl FromRawFd for Memfd { unsafe fn from_raw_fd(fd: RawFd) -> Memfd { let file = fs::File::from_raw_fd(fd); Memfd { file } } } impl AsRawFd for Memfd { fn as_raw_fd(&self) -> RawFd { self.file.as_raw_fd() } } impl IntoRawFd for Memfd { fn into_raw_fd(self) -> RawFd { self.into_file().into_raw_fd() } } fn is_memfd<F: AsRawFd>(fd: &F) -> bool { let ret = unsafe { libc::syscall(libc::SYS_fcntl, fd.as_raw_fd(), libc::F_GET_SEALS) }; ret >= 0 }
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use std::{ffi, fs, os::raw}; use crate::{nr, sealing}; #[cfg(any(target_os = "android", target_os="linux"))] unsafe fn memfd_create(name: *const raw::c_char, flags: raw::c_uint) -> raw::c_int { libc::syscall(libc::SYS_memfd_create, name, flags) as raw::c_int } #[derive(Clone, Debug)] pub struct MemfdOptions { allow_sealing: bool, cloexec: bool, hugetlb: Option<HugetlbSize>, } impl MemfdOptions { pub fn new() -> Self { Self::default() } pub fn allow_sealing(mut self, value: bool) -> Self { self.allow_sealing = value; self } pub fn close_on_exec(mut self, value: bool) -> Self { self.cloexec = value; self } pub fn hugetlb(mut self, size: Option<HugetlbSize>) -> Self { self.hugetlb = size; self } fn bitflags(&self) -> u32 { let mut bits = 0; if self.allow_sealing { bits |= nr::MFD_ALLOW_SEALING; } if self.cloexec { bits |= nr::MFD_CLOEXEC; }
pub fn create<T: AsRef<str>>(&self, name: T) -> Result<Memfd, crate::Error> { let flags = self.bitflags(); unsafe { let cname = ffi::CString::new(name.as_ref()).map_err(crate::Error::NameCStringConversion)?; let name_ptr = cname.as_ptr(); let fd = memfd_create(name_ptr, flags); if fd < 0 { return Err(crate::Error::Create(std::io::Error::last_os_error())); } Ok(Memfd::from_raw_fd(fd)) } } } impl Default for MemfdOptions { fn default() -> Self { Self { allow_sealing: false, cloexec: true, hugetlb: None, } } } #[allow(clippy::all)] #[derive(Copy, Clone, Debug)] pub enum HugetlbSize { Huge64KB, Huge512KB, Huge1MB, Huge2MB, Huge8MB, Huge16MB, Huge256MB, Huge1GB, Huge2GB, Huge16GB, } impl HugetlbSize { fn bitflags(self) -> u32 { match self { HugetlbSize::Huge64KB => nr::MFD_HUGE_64KB, HugetlbSize::Huge512KB => nr::MFD_HUGE_512KB, HugetlbSize::Huge1MB => nr::MFD_HUGE_1MB, HugetlbSize::Huge2MB => nr::MFD_HUGE_2MB, HugetlbSize::Huge8MB => nr::MFD_HUGE_8MB, HugetlbSize::Huge16MB => nr::MFD_HUGE_16MB, HugetlbSize::Huge256MB => nr::MFD_HUGE_256MB, HugetlbSize::Huge1GB => nr::MFD_HUGE_1GB, HugetlbSize::Huge2GB => nr::MFD_HUGE_2GB, HugetlbSize::Huge16GB => nr::MFD_HUGE_16GB, } } } #[derive(Debug)] pub struct Memfd { file: fs::File, } impl Memfd { pub fn try_from_fd<F>(fd: F) -> Result<Self, F> where F: AsRawFd + IntoRawFd, { if !is_memfd(&fd) { Err(fd) } else { let file = unsafe { fs::File::from_raw_fd(fd.into_raw_fd()) }; Ok(Self { file }) } } pub fn try_from_file(file: fs::File) -> Result<Self, fs::File> { Self::try_from_fd(file) } pub fn as_file(&self) -> &fs::File { &self.file } pub fn into_file(self) -> fs::File { self.file } pub fn seals(&self) -> Result<sealing::SealsHashSet, crate::Error> { let flags = Self::file_get_seals(&self.file)?; Ok(sealing::bitflags_to_seals(flags)) } pub fn add_seal(&self, seal: sealing::FileSeal) -> Result<(), crate::Error> { use std::iter::FromIterator; let set = sealing::SealsHashSet::from_iter(vec![seal]); self.add_seals(&set) } pub fn add_seals(&self, seals: &sealing::SealsHashSet) -> Result<(), crate::Error> { let fd = self.file.as_raw_fd(); let flags = sealing::seals_to_bitflags(seals); let r = unsafe { libc::syscall(libc::SYS_fcntl, fd, libc::F_ADD_SEALS, flags) }; if r < 0 { return Err(crate::Error::AddSeals(std::io::Error::last_os_error())); }; Ok(()) } fn file_get_seals(fp: &fs::File) -> Result<u64, crate::Error> { let fd = fp.as_raw_fd(); let r = unsafe { libc::syscall(libc::SYS_fcntl, fd, libc::F_GET_SEALS) }; if r < 0 { return Err(crate::Error::GetSeals(std::io::Error::last_os_error())); }; Ok(r as u64) } } impl FromRawFd for Memfd { unsafe fn from_raw_fd(fd: RawFd) -> Memfd { let file = fs::File::from_raw_fd(fd); Memfd { file } } } impl AsRawFd for Memfd { fn as_raw_fd(&self) -> RawFd { self.file.as_raw_fd() } } impl IntoRawFd for Memfd { fn into_raw_fd(self) -> RawFd { self.into_file().into_raw_fd() } } fn is_memfd<F: AsRawFd>(fd: &F) -> bool { let ret = unsafe { libc::syscall(libc::SYS_fcntl, fd.as_raw_fd(), libc::F_GET_SEALS) }; ret >= 0 }
if let Some(ref hugetlb) = self.hugetlb { bits |= hugetlb.bitflags(); bits |= nr::MFD_HUGETLB; } bits }
function_block-function_prefix_line
[ { "content": "/// Check if the close-on-exec flag is set for the memfd.\n\npub fn get_close_on_exec(memfd: &memfd::Memfd) -> std::io::Result<bool> {\n\n // SAFETY: The syscall called has no soundness implications (i.e. does not mess with\n\n // process memory in weird ways, checks its arguments for correc...
Rust
src/maps/perf_map_poller.rs
redcanaryco/oxidebpf
2ec84a57cf99504a484378908d295d863ff27c32
use std::{ collections::HashMap, fmt::{self, Formatter}, sync::{Arc, Condvar, Mutex}, thread, time::Duration, }; use crossbeam_channel::{Sender, TrySendError}; use mio::{unix::SourceFd, Events, Interest, Poll, Token}; use nix::errno::Errno; use slog::crit; use crate::{ maps::{PerCpu, PerfEvent, PerfMap}, PerfChannelMessage, LOGGER, }; pub struct PerfMapPoller { poll: Poll, tokens: HashMap<Token, PerfMap>, } impl PerfMapPoller { pub fn new( perfmaps: impl Iterator<Item = PerfMap>, polling_signal: Arc<(Mutex<bool>, Condvar)>, ) -> Result<Self, InitError> { let poll = Poll::new().map_err(InitError::Creation)?; let registry = poll.registry(); let tokens = perfmaps .map(|p| { let token = Token(p.ev_fd as usize); registry .register(&mut SourceFd(&p.ev_fd), token, Interest::READABLE) .map(|_| (token, p)) }) .collect::<Result<_, _>>() .map_err(InitError::Registration)?; { let (lock, cvar) = &*polling_signal; let mut locked_signal = lock .lock() .map_err(|e| InitError::ReadySignal(e.to_string()))?; *locked_signal = true; cvar.notify_one(); } Ok(Self { poll, tokens }) } pub fn poll( mut self, tx: Sender<PerfChannelMessage>, polling_delay: Duration, ) -> Result<(), std::io::Error> { let mut events = Events::with_capacity(self.tokens.len()); loop { match self.poll_once(&mut events, &tx) { Ok(_) => thread::sleep(polling_delay), Err(RunError::Disconnected) => return Ok(()), Err(RunError::Poll(e)) => return Err(e), } } } fn poll_once( &mut self, events: &mut Events, tx: &Sender<PerfChannelMessage>, ) -> Result<(), RunError> { if let Err(e) = self.poll.poll(events, Some(Duration::from_millis(100))) { match nix::errno::Errno::from_i32(nix::errno::errno()) { Errno::EINTR => return Ok(()), _ => return Err(RunError::Poll(e)), } } let perf_events = events .iter() .filter_map(|e| self.tokens.get(&e.token())) .flat_map(|perfmap| { let name = &perfmap.name; let cpuid = perfmap.cpuid() as i32; unsafe { perfmap .read_all() .map(move |e| e.map(|e| (name.clone(), cpuid, e))) } }) .filter_map(|e| match e { Ok(e) => Some(e), Err(e) => { crit!(LOGGER.0, "perf_map_poller(); perfmap read error: {:?}", e); None } }); let mut dropped = 0; for (map_name, cpuid, event) in perf_events { match event { PerfEvent::Lost(count) => { dropped += count; match tx.try_send(PerfChannelMessage::Dropped(dropped)) { Ok(_) => dropped = 0, Err(TrySendError::Disconnected(_)) => return Err(RunError::Disconnected), #[cfg(feature = "metrics")] Err(TrySendError::Full(_)) => { metrics::increment_counter!("perfmap.channel.full", "map_name" => map_name) } #[cfg(not(feature = "metrics"))] Err(TrySendError::Full(_)) => {} } } PerfEvent::Sample(data) => tx .send(PerfChannelMessage::Event { map_name, cpuid, data, }) .map_err(|_| RunError::Disconnected)?, }; } Ok(()) } } pub enum InitError { Creation(std::io::Error), Registration(std::io::Error), ReadySignal(String), } impl fmt::Display for InitError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { InitError::Creation(e) => write!(f, "error creating poller: {}", e), InitError::Registration(e) => write!(f, "error registering poller: {}", e), InitError::ReadySignal(e) => write!(f, "error grabbing cond mutex: {}", e), } } } enum RunError { Poll(std::io::Error), Disconnected, }
use std::{ collections::HashMap, fmt::{self, Formatter}, sync::{Arc, Condvar, Mutex}, thread, time::Duration, }; use crossbeam_channel::{Sender, TrySendError}; use mio::{unix::SourceFd, Events, Interest, Poll, Token}; use nix::errno::Errno; use slog::crit; use crate::{ maps::{PerCpu, PerfEvent, PerfMap}, PerfChannelMessage, LOGGER, }; pub struct PerfMapPoller { poll: Poll, tokens: HashMap<Token, PerfMap>, } impl PerfMapPoller { pub fn new( perfmaps: impl Iterator<Item = PerfMap>, polling_signal: Arc<(Mutex<bool>, Condvar)>, ) -> Result<Self, InitError> { let poll = Poll::new().map_err(InitError::Creation)?; let registry = poll.registry(); let tokens = perfmaps .map(|p| { let token = Token(p.ev_fd as usize); registry .register(&mut SourceFd(&p.ev_fd), token, Interest::READABLE) .map(|_| (token, p)) }) .collect::<Result<_, _>>() .map_err(InitError::Registration)?; { let (lock, cvar) = &*polling_signal; let mut locked_signal = lock .lock() .map_err(|e| InitError::ReadySignal(e.to_string()))?; *locked_signal = true; cvar.notify_one(); } Ok(Self { poll, tokens }) } pub fn poll( mut self, tx: Sender<PerfChannelMessage>, polling_delay: Duration, ) -> Result<(), std::io::Error> { let mut events = Events::with_capacity(self.tokens.len()); loop { match self.poll_once(&mut events, &tx) { Ok(_) => thread::sleep(polling_delay), Err(RunError::Disconnected) => return Ok(()), Err(RunError::Poll(e)) => return Err(e), } } }
} pub enum InitError { Creation(std::io::Error), Registration(std::io::Error), ReadySignal(String), } impl fmt::Display for InitError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { InitError::Creation(e) => write!(f, "error creating poller: {}", e), InitError::Registration(e) => write!(f, "error registering poller: {}", e), InitError::ReadySignal(e) => write!(f, "error grabbing cond mutex: {}", e), } } } enum RunError { Poll(std::io::Error), Disconnected, }
fn poll_once( &mut self, events: &mut Events, tx: &Sender<PerfChannelMessage>, ) -> Result<(), RunError> { if let Err(e) = self.poll.poll(events, Some(Duration::from_millis(100))) { match nix::errno::Errno::from_i32(nix::errno::errno()) { Errno::EINTR => return Ok(()), _ => return Err(RunError::Poll(e)), } } let perf_events = events .iter() .filter_map(|e| self.tokens.get(&e.token())) .flat_map(|perfmap| { let name = &perfmap.name; let cpuid = perfmap.cpuid() as i32; unsafe { perfmap .read_all() .map(move |e| e.map(|e| (name.clone(), cpuid, e))) } }) .filter_map(|e| match e { Ok(e) => Some(e), Err(e) => { crit!(LOGGER.0, "perf_map_poller(); perfmap read error: {:?}", e); None } }); let mut dropped = 0; for (map_name, cpuid, event) in perf_events { match event { PerfEvent::Lost(count) => { dropped += count; match tx.try_send(PerfChannelMessage::Dropped(dropped)) { Ok(_) => dropped = 0, Err(TrySendError::Disconnected(_)) => return Err(RunError::Disconnected), #[cfg(feature = "metrics")] Err(TrySendError::Full(_)) => { metrics::increment_counter!("perfmap.channel.full", "map_name" => map_name) } #[cfg(not(feature = "metrics"))] Err(TrySendError::Full(_)) => {} } } PerfEvent::Sample(data) => tx .send(PerfChannelMessage::Event { map_name, cpuid, data, }) .map_err(|_| RunError::Disconnected)?, }; } Ok(()) }
function_block-full_function
[ { "content": "/// Return the current memlock limit.\n\npub fn get_memlock_limit() -> Result<usize, OxidebpfError> {\n\n // use getrlimit() syscall\n\n unsafe {\n\n let mut rlim = libc::rlimit {\n\n rlim_cur: 0,\n\n rlim_max: 0,\n\n };\n\n\n\n let ret = libc::getr...
Rust
src/travis.rs
pietroalbini/travis-migrate
078cb2acfa7b685ecd2b7d9cf3d982cb7a82944f
use failure::{bail, Error}; use log::{debug, info}; use reqwest::{ header::{HeaderName, AUTHORIZATION, USER_AGENT}, Client, Method, RequestBuilder, }; use std::process::Command; #[derive(serde_derive::Deserialize)] struct PaginationLink { #[serde(rename = "@href")] href: String, } #[derive(serde_derive::Deserialize)] struct Pagination { next: Option<PaginationLink>, } #[derive(serde_derive::Deserialize)] struct Common { #[serde(rename = "@pagination")] pagination: Pagination, } #[derive(serde_derive::Deserialize)] struct Repositories { #[serde(flatten)] common: Common, repositories: Vec<Repository>, } #[derive(serde_derive::Deserialize)] pub(crate) struct Repository { pub(crate) slug: String, migration_status: Option<String>, } #[derive(serde_derive::Deserialize)] struct Crons { #[serde(flatten)] common: Common, crons: Vec<Cron>, } #[derive(serde_derive::Serialize, serde_derive::Deserialize)] #[serde(rename_all = "snake_case")] pub(crate) enum CronInterval { Daily, Weekly, Monthly, } #[derive(serde_derive::Deserialize)] pub(crate) struct Branch { name: String, } #[derive(serde_derive::Serialize, serde_derive::Deserialize)] pub(crate) struct Cron { #[serde(skip_serializing)] branch: Branch, interval: CronInterval, dont_run_if_recent_build_exists: bool, } pub(crate) struct TravisCI { tld: &'static str, token: String, client: Client, } impl TravisCI { pub(crate) fn new(tld: &'static str, token: Option<String>) -> Result<Self, Error> { let token = if let Some(token) = token { token } else { info!("fetching API token for travis-ci.{}", tld); let output = Command::new("travis") .arg("token") .arg(format!("--{}", tld)) .arg("--no-interactive") .output()?; if !output.status.success() { bail!( "failed to get the travis-ci.{} token: {}", tld, String::from_utf8_lossy(&output.stderr) ); } String::from_utf8(output.stdout)?.trim().to_string() }; Ok(TravisCI { tld, token, client: Client::new(), }) } fn build_request(&self, method: Method, url: &str) -> RequestBuilder { let tmp_url; let mut url = url.trim_start_matches('/'); if !url.starts_with("https://") { tmp_url = format!("https://api.travis-ci.{}/{}", self.tld, url); url = &tmp_url; } debug!("{} {}", method, url); self.client .request(method, url) .header(USER_AGENT, "pietroalbini/travis-migrate") .header(AUTHORIZATION, format!("token {}", self.token)) .header(HeaderName::from_static("travis-api-version"), "3") } fn paginated<F>(&self, method: &Method, url: &str, mut f: F) -> Result<(), Error> where F: FnMut(RequestBuilder) -> Result<Common, Error>, { let mut common = f(self.build_request(method.clone(), url))?; while let Some(link) = common.pagination.next { common = f(self.build_request(method.clone(), &link.href))?; } Ok(()) } fn repo_name(&self, name: &str) -> String { name.replace("/", "%2F") } pub(crate) fn repos_to_migrate(&self, login: &str) -> Result<Vec<Repository>, Error> { let mut repos = Vec::new(); self.paginated(&Method::GET, &format!("owner/{}/repos", login), |req| { let mut resp: Repositories = req .form(&[("active_on_org", "true")]) .send()? .error_for_status()? .json()?; repos.append(&mut resp.repositories); Ok(resp.common) })?; Ok(repos) } pub(crate) fn start_migration(&self, repo: &str) -> Result<(), Error> { let _ = self .build_request( Method::POST, &format!("repo/{}/migrate", self.repo_name(repo)), ) .send()? .error_for_status()?; Ok(()) } pub(crate) fn is_migrated(&self, repo: &str) -> Result<bool, Error> { let repo: Repository = self .build_request(Method::GET, &format!("repo/{}", self.repo_name(repo))) .send()? .error_for_status()? .json()?; Ok(repo.migration_status.as_ref().map(|s| s.as_str()) == Some("migrated")) } pub(crate) fn list_crons(&self, repo: &str) -> Result<Vec<Cron>, Error> { let mut crons = Vec::new(); self.paginated( &Method::GET, &format!("repo/{}/crons", self.repo_name(repo)), |req| { let mut resp: Crons = req.send()?.error_for_status()?.json()?; crons.append(&mut resp.crons); Ok(resp.common) }, )?; Ok(crons) } pub(crate) fn create_cron(&self, repo: &str, cron: &Cron) -> Result<(), Error> { let _ = self .build_request( Method::POST, &format!( "repo/{}/branch/{}/cron", self.repo_name(repo), cron.branch.name ), ) .json(cron) .send()? .error_for_status()?; Ok(()) } }
use failure::{bail, Error}; use log::{debug, info}; use reqwest::{ header::{HeaderName, AUTHORIZATION, USER_AGENT}, Client, Method, RequestBuilder, }; use std::process::Command; #[derive(serde_derive::Deserialize)] struct PaginationLink { #[serde(rename = "@href")] href: String, } #[derive(serde_derive::Deserialize)] struct Pagination { next: Option<PaginationLink>, } #[derive(serde_derive::Deserialize)] struct Common { #[serde(rename = "@pagination")] pagination: Pagination, } #[derive(serde_derive::Deserialize)] struct Repositories { #[serde(flatten)] common: Common, repositories: Vec<Repository>, } #[derive(serde_derive::Deserialize)] pub(crate) struct Repository { pub(crate) slug: String, migration_status: Option<String>, } #[derive(serde_derive::Deserialize)] struct Crons { #[serde(flatten)] common: Common, crons: Vec<Cron>, } #[derive(serde_derive::Serialize, serde_derive::Deserialize)] #[serde(rename_all = "snake_case")] pub(crate) enum CronInterval { Daily, Weekly, Monthly, } #[derive(serde_derive::Deserialize)] pub(crate) struct Branch { name: String, } #[derive(serde_derive::Serialize, serde_derive::Deserialize)] pub(crate) struct Cron { #[serde(skip_serializing)] branch: Branch, interval: CronInterval, dont_run_if_recent_build_exists: bool, } pub(crate) struct TravisCI { tld: &'static str, token: String, client: Client, } impl TravisCI { pub(crate) fn new(tld: &'static str, token: Option<String>) -> Result<Self, Error> { let token = if let Some(token) = token { token } else { info!("fetching API token for travis-ci.{}", tld); let output = Command::new("travis") .arg("token") .arg(format!("--{}", tld)) .arg("--no-interactive") .output()?; if !output.status.success() { bail!( "failed to get the travis-ci.{} token: {}", tld, String::from_utf8_lossy(&output.stderr) ); } String::from_utf8(output.stdout)?.trim().to_string() }; Ok(TravisCI { tld, token, client: Client::new(), }) } fn build_request(&self, method: Method, url: &str) -> RequestBuilder { let tmp_url; let mut url = url.trim_start_matches('/'); if !url.starts_with("https://") { tmp_url = format!("https://api.travis-ci.{}/{}", self.tld, url); url = &tmp_url; } debug!("{} {}", method, url); self.client .request(method, url) .header(USER_AGENT, "pietroalbini/travis-migrate") .header(AUTHORIZATION, format!("token {}", self.token)) .header(HeaderName::from_static("travis-api-version"), "3") } fn paginated<F>(&self, method: &Method, url: &str, mut f: F) -> Result<(), Error> where F: FnMut(RequestBuilder) -> Result<Common, Error>, { let mut common = f(self.build_request(method.clone(), url))?; while let Some(link) = common.pagination.next { common = f(self.build_request(method.clone(), &link.href))?; } Ok(()) } fn repo_name(&self, name: &str) -> String { name.replace("/", "%2F") }
pub(crate) fn start_migration(&self, repo: &str) -> Result<(), Error> { let _ = self .build_request( Method::POST, &format!("repo/{}/migrate", self.repo_name(repo)), ) .send()? .error_for_status()?; Ok(()) } pub(crate) fn is_migrated(&self, repo: &str) -> Result<bool, Error> { let repo: Repository = self .build_request(Method::GET, &format!("repo/{}", self.repo_name(repo))) .send()? .error_for_status()? .json()?; Ok(repo.migration_status.as_ref().map(|s| s.as_str()) == Some("migrated")) } pub(crate) fn list_crons(&self, repo: &str) -> Result<Vec<Cron>, Error> { let mut crons = Vec::new(); self.paginated( &Method::GET, &format!("repo/{}/crons", self.repo_name(repo)), |req| { let mut resp: Crons = req.send()?.error_for_status()?.json()?; crons.append(&mut resp.crons); Ok(resp.common) }, )?; Ok(crons) } pub(crate) fn create_cron(&self, repo: &str, cron: &Cron) -> Result<(), Error> { let _ = self .build_request( Method::POST, &format!( "repo/{}/branch/{}/cron", self.repo_name(repo), cron.branch.name ), ) .json(cron) .send()? .error_for_status()?; Ok(()) } }
pub(crate) fn repos_to_migrate(&self, login: &str) -> Result<Vec<Repository>, Error> { let mut repos = Vec::new(); self.paginated(&Method::GET, &format!("owner/{}/repos", login), |req| { let mut resp: Repositories = req .form(&[("active_on_org", "true")]) .send()? .error_for_status()? .json()?; repos.append(&mut resp.repositories); Ok(resp.common) })?; Ok(repos) }
function_block-full_function
[ { "content": "fn app() -> Result<(), Error> {\n\n let args = CLI::from_args();\n\n\n\n match args {\n\n CLI::List { account } => {\n\n let travis_com = TravisCI::new(\"com\", std::env::var(\"TRAVIS_TOKEN_COM\").ok())?;\n\n let repos = travis_com.repos_to_migrate(&account)?;\n\...
Rust
ton_client/src/crypto/boxes/encryption_box/aes.rs
markgenuine/TON-SDK
2b49c8270a34eab1a66e2eac7764b69568e7d324
/* * Copyright 2018-2021 TON Labs LTD. * * Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use * this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific TON DEV software governing permissions and * limitations under the License. */ use aes::{Aes128, Aes192, Aes256, BlockCipher, BlockDecrypt, BlockEncrypt, NewBlockCipher}; use block_modes::{BlockMode, Cbc}; use crate::crypto::Error; use crate::encoding::{base64_decode, hex_decode}; use crate::error::ClientResult; use super::{CipherMode, EncryptionBox, EncryptionBoxInfo}; #[derive(Serialize, Deserialize, Clone, Debug, ApiType, Default)] pub struct AesParams { pub mode: CipherMode, pub key: String, pub iv: Option<String>, } #[derive(Serialize, Deserialize, Clone, Debug, ApiType, Default)] pub struct AesInfo { pub mode: CipherMode, pub iv: Option<String>, } pub(crate) struct AesEncryptionBox { key: Vec<u8>, mode: CipherMode, iv: Vec<u8>, } impl AesEncryptionBox { pub fn new(params: AesParams) -> ClientResult<Self> { let iv_required = match params.mode { CipherMode::CBC => true, _ => return Err(Error::unsupported_cipher_mode(&format!("{:?}", params.mode))) }; if iv_required && params.iv.is_none() { return Err(Error::iv_required(&params.mode)); } let key = hex_decode(&params.key)?; if key.len() != 16 && key.len() != 24 && key.len() != 32 { return Err(Error::invalid_key_size(key.len(), &[128, 192, 256])); } let iv = params.iv .map(|string| { let iv = hex_decode(&string)?; if iv.len() == aes::BLOCK_SIZE { Ok(iv) } else { Err(Error::invalid_iv_size(iv.len(), aes::BLOCK_SIZE)) } }) .transpose()? .unwrap_or_default(); Ok(Self { key, iv, mode: params.mode }) } fn create_block_mode<C, B>(key: &[u8], iv: &[u8]) -> ClientResult<B> where C: BlockCipher + BlockEncrypt + BlockDecrypt + NewBlockCipher, B: BlockMode<C, block_modes::block_padding::ZeroPadding> { B::new_from_slices(key, iv) .map_err(|err| Error::cannot_create_cipher(err)) } fn encrypt_data<'a, C, B>(key: &[u8], iv: &[u8], data: &'a mut [u8], size: usize) -> ClientResult<&'a [u8]> where C: BlockCipher + BlockEncrypt + BlockDecrypt + NewBlockCipher, B: BlockMode<C, block_modes::block_padding::ZeroPadding> { Self::create_block_mode::<C, B>(key, iv)? .encrypt(data, size) .map_err(|err| Error::encrypt_data_error(format!("{:#?}", err))) } fn decrypt_data<C, B>(key: &[u8], iv: &[u8], data: &mut [u8]) -> ClientResult<()> where C: BlockCipher + BlockEncrypt + BlockDecrypt + NewBlockCipher, B: BlockMode<C, block_modes::block_padding::ZeroPadding> { Self::create_block_mode::<C, B>(key, iv)? .decrypt(data) .map_err(|err| Error::decrypt_data_error(format!("{:#?}", err))) .map(|_| ()) } fn decode_base64_aligned(data: &str, align: usize) -> ClientResult<(Vec<u8>, usize)> { let data_size = (data.len() + 3) / 4 * 3; let aligned_size = (data_size + align - 1) & !(align - 1); let mut vec = vec![0u8; aligned_size]; let size = base64::decode_config_slice(data, base64::STANDARD, &mut vec) .map_err(|err| crate::client::Error::invalid_base64(data, err))?; Ok((vec, size)) } } #[async_trait::async_trait] impl EncryptionBox for AesEncryptionBox { async fn get_info(&self) -> ClientResult<EncryptionBoxInfo> { let iv = if self.iv.len() != 0 { Some(hex::encode(&self.iv)) } else { None }; let aes_info = AesInfo { mode: self.mode.clone(), iv }; Ok(EncryptionBoxInfo { algorithm: Some("AES".to_owned()), hdpath: None, public: None, options: Some(json!(aes_info)) }) } async fn encrypt(&self, data: &String) -> ClientResult<String> { let (mut data, size) = Self::decode_base64_aligned(data, aes::BLOCK_SIZE)?; let result = match (self.key.len(), &self.mode) { (16, CipherMode::CBC) => Self::encrypt_data::<Aes128, Cbc<Aes128, _>>(&self.key, &self.iv, &mut data, size)?, (24, CipherMode::CBC) => Self::encrypt_data::<Aes192, Cbc<Aes192, _>>(&self.key, &self.iv, &mut data, size)?, (32, CipherMode::CBC) => Self::encrypt_data::<Aes256, Cbc<Aes256, _>>(&self.key, &self.iv, &mut data, size)?, _ => return Err(Error::unsupported_cipher_mode(&format!("{:?}", self.mode))), }; Ok(base64::encode(result)) } async fn decrypt(&self, data: &String) -> ClientResult<String> { let mut data = base64_decode(data)?; match (self.key.len(), &self.mode) { (16, CipherMode::CBC) => Self::decrypt_data::<Aes128, Cbc<Aes128, _>>(&self.key, &self.iv, &mut data)?, (24, CipherMode::CBC) => Self::decrypt_data::<Aes192, Cbc<Aes192, _>>(&self.key, &self.iv, &mut data)?, (32, CipherMode::CBC) => Self::decrypt_data::<Aes256, Cbc<Aes256, _>>(&self.key, &self.iv, &mut data)?, _ => return Err(Error::unsupported_cipher_mode(&format!("{:?}", self.mode))), } Ok(base64::encode(&data)) } }
/* * Copyright 2018-2021 TON Labs LTD. * * Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use * this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOU
Aes128, Aes192, Aes256, BlockCipher, BlockDecrypt, BlockEncrypt, NewBlockCipher}; use block_modes::{BlockMode, Cbc}; use crate::crypto::Error; use crate::encoding::{base64_decode, hex_decode}; use crate::error::ClientResult; use super::{CipherMode, EncryptionBox, EncryptionBoxInfo}; #[derive(Serialize, Deserialize, Clone, Debug, ApiType, Default)] pub struct AesParams { pub mode: CipherMode, pub key: String, pub iv: Option<String>, } #[derive(Serialize, Deserialize, Clone, Debug, ApiType, Default)] pub struct AesInfo { pub mode: CipherMode, pub iv: Option<String>, } pub(crate) struct AesEncryptionBox { key: Vec<u8>, mode: CipherMode, iv: Vec<u8>, } impl AesEncryptionBox { pub fn new(params: AesParams) -> ClientResult<Self> { let iv_required = match params.mode { CipherMode::CBC => true, _ => return Err(Error::unsupported_cipher_mode(&format!("{:?}", params.mode))) }; if iv_required && params.iv.is_none() { return Err(Error::iv_required(&params.mode)); } let key = hex_decode(&params.key)?; if key.len() != 16 && key.len() != 24 && key.len() != 32 { return Err(Error::invalid_key_size(key.len(), &[128, 192, 256])); } let iv = params.iv .map(|string| { let iv = hex_decode(&string)?; if iv.len() == aes::BLOCK_SIZE { Ok(iv) } else { Err(Error::invalid_iv_size(iv.len(), aes::BLOCK_SIZE)) } }) .transpose()? .unwrap_or_default(); Ok(Self { key, iv, mode: params.mode }) } fn create_block_mode<C, B>(key: &[u8], iv: &[u8]) -> ClientResult<B> where C: BlockCipher + BlockEncrypt + BlockDecrypt + NewBlockCipher, B: BlockMode<C, block_modes::block_padding::ZeroPadding> { B::new_from_slices(key, iv) .map_err(|err| Error::cannot_create_cipher(err)) } fn encrypt_data<'a, C, B>(key: &[u8], iv: &[u8], data: &'a mut [u8], size: usize) -> ClientResult<&'a [u8]> where C: BlockCipher + BlockEncrypt + BlockDecrypt + NewBlockCipher, B: BlockMode<C, block_modes::block_padding::ZeroPadding> { Self::create_block_mode::<C, B>(key, iv)? .encrypt(data, size) .map_err(|err| Error::encrypt_data_error(format!("{:#?}", err))) } fn decrypt_data<C, B>(key: &[u8], iv: &[u8], data: &mut [u8]) -> ClientResult<()> where C: BlockCipher + BlockEncrypt + BlockDecrypt + NewBlockCipher, B: BlockMode<C, block_modes::block_padding::ZeroPadding> { Self::create_block_mode::<C, B>(key, iv)? .decrypt(data) .map_err(|err| Error::decrypt_data_error(format!("{:#?}", err))) .map(|_| ()) } fn decode_base64_aligned(data: &str, align: usize) -> ClientResult<(Vec<u8>, usize)> { let data_size = (data.len() + 3) / 4 * 3; let aligned_size = (data_size + align - 1) & !(align - 1); let mut vec = vec![0u8; aligned_size]; let size = base64::decode_config_slice(data, base64::STANDARD, &mut vec) .map_err(|err| crate::client::Error::invalid_base64(data, err))?; Ok((vec, size)) } } #[async_trait::async_trait] impl EncryptionBox for AesEncryptionBox { async fn get_info(&self) -> ClientResult<EncryptionBoxInfo> { let iv = if self.iv.len() != 0 { Some(hex::encode(&self.iv)) } else { None }; let aes_info = AesInfo { mode: self.mode.clone(), iv }; Ok(EncryptionBoxInfo { algorithm: Some("AES".to_owned()), hdpath: None, public: None, options: Some(json!(aes_info)) }) } async fn encrypt(&self, data: &String) -> ClientResult<String> { let (mut data, size) = Self::decode_base64_aligned(data, aes::BLOCK_SIZE)?; let result = match (self.key.len(), &self.mode) { (16, CipherMode::CBC) => Self::encrypt_data::<Aes128, Cbc<Aes128, _>>(&self.key, &self.iv, &mut data, size)?, (24, CipherMode::CBC) => Self::encrypt_data::<Aes192, Cbc<Aes192, _>>(&self.key, &self.iv, &mut data, size)?, (32, CipherMode::CBC) => Self::encrypt_data::<Aes256, Cbc<Aes256, _>>(&self.key, &self.iv, &mut data, size)?, _ => return Err(Error::unsupported_cipher_mode(&format!("{:?}", self.mode))), }; Ok(base64::encode(result)) } async fn decrypt(&self, data: &String) -> ClientResult<String> { let mut data = base64_decode(data)?; match (self.key.len(), &self.mode) { (16, CipherMode::CBC) => Self::decrypt_data::<Aes128, Cbc<Aes128, _>>(&self.key, &self.iv, &mut data)?, (24, CipherMode::CBC) => Self::decrypt_data::<Aes192, Cbc<Aes192, _>>(&self.key, &self.iv, &mut data)?, (32, CipherMode::CBC) => Self::decrypt_data::<Aes256, Cbc<Aes256, _>>(&self.key, &self.iv, &mut data)?, _ => return Err(Error::unsupported_cipher_mode(&format!("{:?}", self.mode))), } Ok(base64::encode(&data)) } }
T WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific TON DEV software governing permissions and * limitations under the License. */ use aes::{
random
[]
Rust
tezos/api/src/environment.rs
Kyras/tezedge
98bc9991765682d077347575781afb451d147492
use std::collections::HashMap; use std::str::FromStr; use enum_iterator::IntoEnumIterator; use serde::{Deserialize, Serialize}; use lazy_static::lazy_static; use crate::ffi::{GenesisChain, ProtocolOverrides}; lazy_static! { pub static ref TEZOS_ENV: HashMap<TezosEnvironment, TezosEnvironmentConfiguration> = init(); } #[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq, Eq, Hash, IntoEnumIterator)] pub enum TezosEnvironment { Alphanet, Babylonnet, Mainnet, Zeronet, } #[derive(Debug, Clone)] pub struct ParseTezosEnvironmentError(String); impl FromStr for TezosEnvironment { type Err = ParseTezosEnvironmentError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_ascii_lowercase().as_str() { "alphanet" => Ok(TezosEnvironment::Alphanet), "babylonnet" | "babylon" => Ok(TezosEnvironment::Babylonnet), "mainnet" => Ok(TezosEnvironment::Mainnet), "zeronet" => Ok(TezosEnvironment::Zeronet), _ => Err(ParseTezosEnvironmentError(format!("Invalid variant name: {}", s))) } } } fn init() -> HashMap<TezosEnvironment, TezosEnvironmentConfiguration> { let mut env: HashMap<TezosEnvironment, TezosEnvironmentConfiguration> = HashMap::new(); env.insert(TezosEnvironment::Alphanet, TezosEnvironmentConfiguration { genesis: GenesisChain { time: "2018-11-30T15:30:56Z".to_string(), block: "BLockGenesisGenesisGenesisGenesisGenesisb83baZgbyZe".to_string(), protocol: "Ps6mwMrF2ER2s51cp9yYpjDcuzQjsc2yAz8bQsRgdaRxw4Fk95H".to_string(), }, bootstrap_lookup_addresses: vec![ "boot.tzalpha.net".to_string(), "bootalpha.tzbeta.net".to_string() ], version: "TEZOS_ALPHANET_2018-11-30T15:30:56Z".to_string(), protocol_overrides: ProtocolOverrides { forced_protocol_upgrades: vec![], voted_protocol_overrides: vec![], }, }); env.insert(TezosEnvironment::Babylonnet, TezosEnvironmentConfiguration { genesis: GenesisChain { time: "2019-09-27T07:43:32Z".to_string(), block: "BLockGenesisGenesisGenesisGenesisGenesisd1f7bcGMoXy".to_string(), protocol: "PtBMwNZT94N7gXKw4i273CKcSaBrrBnqnt3RATExNKr9KNX2USV".to_string(), }, bootstrap_lookup_addresses: vec![ "35.246.251.120".to_string(), "34.89.154.253".to_string(), "babylonnet.kaml.fr".to_string(), "tezaria.com".to_string() ], version: "TEZOS_ALPHANET_BABYLON_2019-09-27T07:43:32Z".to_string(), protocol_overrides: ProtocolOverrides { forced_protocol_upgrades: vec![], voted_protocol_overrides: vec![], }, }); env.insert(TezosEnvironment::Mainnet, TezosEnvironmentConfiguration { genesis: GenesisChain { time: "2018-06-30T16:07:32Z".to_string(), block: "BLockGenesisGenesisGenesisGenesisGenesisf79b5d1CoW2".to_string(), protocol: "Ps9mPmXaRzmzk35gbAYNCAw6UXdE2qoABTHbN2oEEc1qM7CwT9P".to_string(), }, bootstrap_lookup_addresses: vec![ "boot.tzbeta.net".to_string() ], version: "TEZOS_BETANET_2018-06-30T16:07:32Z".to_string(), protocol_overrides: ProtocolOverrides { forced_protocol_upgrades: vec![ (28082 as i32, "PsYLVpVvgbLhAhoqAkMFUo6gudkJ9weNXhUYCiLDzcUpFpkk8Wt".to_string()), (204761 as i32, "PsddFKi32cMJ2qPjf43Qv5GDWLDPZb3T3bF6fLKiF5HtvHNU7aP".to_string()) ], voted_protocol_overrides: vec![ ("PsBABY5HQTSkA4297zNHfsZNKtxULfL18y95qb3m53QJiXGmrbU".to_string(), "PsBabyM1eUXZseaJdmXFApDSBqj8YBfwELoxZHHW77EMcAbbwAS".to_string()) ], }, }); env.insert(TezosEnvironment::Zeronet, TezosEnvironmentConfiguration { genesis: GenesisChain { time: "2019-08-06T15:18:56Z".to_string(), block: "BLockGenesisGenesisGenesisGenesisGenesiscde8db4cX94".to_string(), protocol: "PtBMwNZT94N7gXKw4i273CKcSaBrrBnqnt3RATExNKr9KNX2USV".to_string(), }, bootstrap_lookup_addresses: vec![ "bootstrap.zeronet.fun".to_string(), "bootzero.tzbeta.net".to_string() ], version: "TEZOS_ZERONET_2019-08-06T15:18:56Z".to_string(), protocol_overrides: ProtocolOverrides { forced_protocol_upgrades: vec![], voted_protocol_overrides: vec![], }, }); env } pub struct TezosEnvironmentConfiguration { pub genesis: GenesisChain, pub bootstrap_lookup_addresses: Vec<String>, pub version: String, pub protocol_overrides: ProtocolOverrides, }
use std::collections::HashMap; use std::str::FromStr; use enum_iterator::IntoEnumIterator; use serde::{Deserialize, Serialize}; use lazy_static::lazy_static; use crate::ffi::{GenesisChain, ProtocolOverrides}; lazy_static! { pub static ref TEZOS_ENV: HashMap<TezosEnvironment, TezosEnvironmentConfiguration> = init(); } #[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq, Eq, Hash, IntoEnumIterator)] pub enum TezosEnvironment { Alphanet, Babylonnet, Mainnet, Zeronet, } #[derive(Debug, Clone)] pub struct ParseTezosEnvironmentError(String); impl FromStr for TezosEnvironment { type Err = ParseTezosEnvironmentError;
} fn init() -> HashMap<TezosEnvironment, TezosEnvironmentConfiguration> { let mut env: HashMap<TezosEnvironment, TezosEnvironmentConfiguration> = HashMap::new(); env.insert(TezosEnvironment::Alphanet, TezosEnvironmentConfiguration { genesis: GenesisChain { time: "2018-11-30T15:30:56Z".to_string(), block: "BLockGenesisGenesisGenesisGenesisGenesisb83baZgbyZe".to_string(), protocol: "Ps6mwMrF2ER2s51cp9yYpjDcuzQjsc2yAz8bQsRgdaRxw4Fk95H".to_string(), }, bootstrap_lookup_addresses: vec![ "boot.tzalpha.net".to_string(), "bootalpha.tzbeta.net".to_string() ], version: "TEZOS_ALPHANET_2018-11-30T15:30:56Z".to_string(), protocol_overrides: ProtocolOverrides { forced_protocol_upgrades: vec![], voted_protocol_overrides: vec![], }, }); env.insert(TezosEnvironment::Babylonnet, TezosEnvironmentConfiguration { genesis: GenesisChain { time: "2019-09-27T07:43:32Z".to_string(), block: "BLockGenesisGenesisGenesisGenesisGenesisd1f7bcGMoXy".to_string(), protocol: "PtBMwNZT94N7gXKw4i273CKcSaBrrBnqnt3RATExNKr9KNX2USV".to_string(), }, bootstrap_lookup_addresses: vec![ "35.246.251.120".to_string(), "34.89.154.253".to_string(), "babylonnet.kaml.fr".to_string(), "tezaria.com".to_string() ], version: "TEZOS_ALPHANET_BABYLON_2019-09-27T07:43:32Z".to_string(), protocol_overrides: ProtocolOverrides { forced_protocol_upgrades: vec![], voted_protocol_overrides: vec![], }, }); env.insert(TezosEnvironment::Mainnet, TezosEnvironmentConfiguration { genesis: GenesisChain { time: "2018-06-30T16:07:32Z".to_string(), block: "BLockGenesisGenesisGenesisGenesisGenesisf79b5d1CoW2".to_string(), protocol: "Ps9mPmXaRzmzk35gbAYNCAw6UXdE2qoABTHbN2oEEc1qM7CwT9P".to_string(), }, bootstrap_lookup_addresses: vec![ "boot.tzbeta.net".to_string() ], version: "TEZOS_BETANET_2018-06-30T16:07:32Z".to_string(), protocol_overrides: ProtocolOverrides { forced_protocol_upgrades: vec![ (28082 as i32, "PsYLVpVvgbLhAhoqAkMFUo6gudkJ9weNXhUYCiLDzcUpFpkk8Wt".to_string()), (204761 as i32, "PsddFKi32cMJ2qPjf43Qv5GDWLDPZb3T3bF6fLKiF5HtvHNU7aP".to_string()) ], voted_protocol_overrides: vec![ ("PsBABY5HQTSkA4297zNHfsZNKtxULfL18y95qb3m53QJiXGmrbU".to_string(), "PsBabyM1eUXZseaJdmXFApDSBqj8YBfwELoxZHHW77EMcAbbwAS".to_string()) ], }, }); env.insert(TezosEnvironment::Zeronet, TezosEnvironmentConfiguration { genesis: GenesisChain { time: "2019-08-06T15:18:56Z".to_string(), block: "BLockGenesisGenesisGenesisGenesisGenesiscde8db4cX94".to_string(), protocol: "PtBMwNZT94N7gXKw4i273CKcSaBrrBnqnt3RATExNKr9KNX2USV".to_string(), }, bootstrap_lookup_addresses: vec![ "bootstrap.zeronet.fun".to_string(), "bootzero.tzbeta.net".to_string() ], version: "TEZOS_ZERONET_2019-08-06T15:18:56Z".to_string(), protocol_overrides: ProtocolOverrides { forced_protocol_upgrades: vec![], voted_protocol_overrides: vec![], }, }); env } pub struct TezosEnvironmentConfiguration { pub genesis: GenesisChain, pub bootstrap_lookup_addresses: Vec<String>, pub version: String, pub protocol_overrides: ProtocolOverrides, }
fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_ascii_lowercase().as_str() { "alphanet" => Ok(TezosEnvironment::Alphanet), "babylonnet" | "babylon" => Ok(TezosEnvironment::Babylonnet), "mainnet" => Ok(TezosEnvironment::Mainnet), "zeronet" => Ok(TezosEnvironment::Zeronet), _ => Err(ParseTezosEnvironmentError(format!("Invalid variant name: {}", s))) } }
function_block-full_function
[ { "content": "type OperationHash = Hash;\n", "file_path": "tezos/interop_callback/src/callback.rs", "rank": 0, "score": 165307.25237255346 }, { "content": "type ContextHash = Hash;\n", "file_path": "tezos/interop_callback/src/callback.rs", "rank": 1, "score": 165307.25237255346 ...
Rust
miniz_oxide/src/inflate/mod.rs
MichaelMcDonnell/miniz_oxide
b6ca295deaecd549c504873481ceb4e2a65a1933
use crate::alloc::boxed::Box; use crate::alloc::vec; use crate::alloc::vec::Vec; use ::core::cmp::min; use ::core::usize; pub mod core; mod output_buffer; pub mod stream; use self::core::*; const TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS: i32 = -4; const TINFL_STATUS_BAD_PARAM: i32 = -3; const TINFL_STATUS_ADLER32_MISMATCH: i32 = -2; const TINFL_STATUS_FAILED: i32 = -1; const TINFL_STATUS_DONE: i32 = 0; const TINFL_STATUS_NEEDS_MORE_INPUT: i32 = 1; const TINFL_STATUS_HAS_MORE_OUTPUT: i32 = 2; #[repr(i8)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum TINFLStatus { FailedCannotMakeProgress = TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS as i8, BadParam = TINFL_STATUS_BAD_PARAM as i8, Adler32Mismatch = TINFL_STATUS_ADLER32_MISMATCH as i8, Failed = TINFL_STATUS_FAILED as i8, Done = TINFL_STATUS_DONE as i8, NeedsMoreInput = TINFL_STATUS_NEEDS_MORE_INPUT as i8, HasMoreOutput = TINFL_STATUS_HAS_MORE_OUTPUT as i8, } impl TINFLStatus { pub fn from_i32(value: i32) -> Option<TINFLStatus> { use self::TINFLStatus::*; match value { TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS => Some(FailedCannotMakeProgress), TINFL_STATUS_BAD_PARAM => Some(BadParam), TINFL_STATUS_ADLER32_MISMATCH => Some(Adler32Mismatch), TINFL_STATUS_FAILED => Some(Failed), TINFL_STATUS_DONE => Some(Done), TINFL_STATUS_NEEDS_MORE_INPUT => Some(NeedsMoreInput), TINFL_STATUS_HAS_MORE_OUTPUT => Some(HasMoreOutput), _ => None, } } } #[inline] pub fn decompress_to_vec(input: &[u8]) -> Result<Vec<u8>, TINFLStatus> { decompress_to_vec_inner(input, 0, usize::max_value()) } #[inline] pub fn decompress_to_vec_zlib(input: &[u8]) -> Result<Vec<u8>, TINFLStatus> { decompress_to_vec_inner( input, inflate_flags::TINFL_FLAG_PARSE_ZLIB_HEADER, usize::max_value(), ) } #[inline] pub fn decompress_to_vec_with_limit(input: &[u8], max_size: usize) -> Result<Vec<u8>, TINFLStatus> { decompress_to_vec_inner(input, 0, max_size) } #[inline] pub fn decompress_to_vec_zlib_with_limit( input: &[u8], max_size: usize, ) -> Result<Vec<u8>, TINFLStatus> { decompress_to_vec_inner(input, inflate_flags::TINFL_FLAG_PARSE_ZLIB_HEADER, max_size) } fn decompress_to_vec_inner( input: &[u8], flags: u32, max_output_size: usize, ) -> Result<Vec<u8>, TINFLStatus> { let flags = flags | inflate_flags::TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; let mut ret: Vec<u8> = vec![0; min(input.len().saturating_mul(2), max_output_size)]; let mut decomp = Box::<DecompressorOxide>::default(); let mut in_pos = 0; let mut out_pos = 0; loop { let (status, in_consumed, out_consumed) = decompress(&mut decomp, &input[in_pos..], &mut ret, out_pos, flags); in_pos += in_consumed; out_pos += out_consumed; match status { TINFLStatus::Done => { ret.truncate(out_pos); return Ok(ret); } TINFLStatus::HasMoreOutput => { let new_len = ret .len() .checked_add(out_pos) .ok_or(TINFLStatus::HasMoreOutput)?; if new_len > max_output_size { return Err(TINFLStatus::HasMoreOutput); }; ret.resize(new_len, 0); } _ => return Err(status), } } } pub fn decompress_slice_iter_to_slice<'out, 'inp>( out: &'out mut [u8], it: impl Iterator<Item = &'inp [u8]>, zlib_header: bool, ignore_adler32: bool, ) -> Result<usize, TINFLStatus> { use self::core::inflate_flags::*; let mut it = it.peekable(); let r = &mut DecompressorOxide::new(); let mut out_pos = 0; while let Some(in_buf) = it.next() { let has_more = it.peek().is_some(); let flags = { let mut f = TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; if zlib_header { f |= TINFL_FLAG_PARSE_ZLIB_HEADER; } if ignore_adler32 { f |= TINFL_FLAG_IGNORE_ADLER32; } if has_more { f |= TINFL_FLAG_HAS_MORE_INPUT; } f }; let (status, _input_read, bytes_written) = decompress(r, in_buf, out, out_pos, flags); out_pos += bytes_written; match status { TINFLStatus::NeedsMoreInput => continue, TINFLStatus::Done => return Ok(out_pos), e => return Err(e), } } Err(TINFLStatus::FailedCannotMakeProgress) } #[cfg(test)] mod test { use super::{ decompress_slice_iter_to_slice, decompress_to_vec_zlib, decompress_to_vec_zlib_with_limit, TINFLStatus, }; const encoded: [u8; 20] = [ 120, 156, 243, 72, 205, 201, 201, 215, 81, 168, 202, 201, 76, 82, 4, 0, 27, 101, 4, 19, ]; #[test] fn decompress_vec() { let res = decompress_to_vec_zlib(&encoded[..]).unwrap(); assert_eq!(res.as_slice(), &b"Hello, zlib!"[..]); } #[test] fn decompress_vec_with_high_limit() { let res = decompress_to_vec_zlib_with_limit(&encoded[..], 100_000).unwrap(); assert_eq!(res.as_slice(), &b"Hello, zlib!"[..]); } #[test] fn fail_to_decompress_with_limit() { let res = decompress_to_vec_zlib_with_limit(&encoded[..], 8); match res { Err(TINFLStatus::HasMoreOutput) => (), _ => panic!("Decompression output size limit was not enforced"), } } #[test] fn test_decompress_slice_iter_to_slice() { let mut out = [0_u8; 12_usize]; let r = decompress_slice_iter_to_slice(&mut out, Some(&encoded[..]).into_iter(), true, false); assert_eq!(r, Ok(12)); assert_eq!(&out[..12], &b"Hello, zlib!"[..]); for chunk_size in 1..13 { let mut out = [0_u8; 12_usize + 1]; let r = decompress_slice_iter_to_slice(&mut out, encoded.chunks(chunk_size), true, false); assert_eq!(r, Ok(12)); assert_eq!(&out[..12], &b"Hello, zlib!"[..]); } let mut out = [0_u8; 3_usize]; let r = decompress_slice_iter_to_slice(&mut out, encoded.chunks(7), true, false); assert!(r.is_err()); } }
use crate::alloc::boxed::Box; use crate::alloc::vec; use crate::alloc::vec::Vec; use ::core::cmp::min; use ::core::usize; pub mod core; mod output_buffer; pub mod stream; use self::core::*; const TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS: i32 = -4; const TINFL_STATUS_BAD_PARAM: i32 = -3; const TINFL_STATUS_ADLER32_MISMATCH: i32 = -2; const TINFL_STATUS_FAILED: i32 = -1; const TINFL_STATUS_DONE: i32 = 0; const TINFL_STATUS_NEEDS_MORE_INPUT: i32 = 1; const TINFL_STATUS_HAS_MORE_OUTPUT: i32 = 2; #[repr(i8)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum TINFLStatus { FailedCannotMakeProgress = TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS as i8, BadParam = TINFL_STATUS_BAD_PARAM as i8, Adler32Mismatch = TINFL_STATUS_ADLER32_MISMATCH as i8, Failed = TINFL_STATUS_FAILED as i8, Done = TINFL_STATUS_DONE as i8, NeedsMoreInput = TINFL_STATUS_NEEDS_MORE_INPUT as i8, HasMoreOutput = TINFL_STATUS_HAS_MORE_OUTPUT as i8, } impl TINFLStatus { pub fn from_i32(value: i32) -> Option<TINFLStatus> { use self::TINFLStatus::*; match value { TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS => Some(FailedCannotMakeProgress), TINFL_STATUS_BAD_PARAM => Some(BadParam), TINFL_STATUS_ADLER32_MISMATCH => Some(Adler32Mismatch), TINFL_STATUS_FAILED => Some(Failed), TINFL_STATUS_DONE => Some(Done), TINFL_STATUS_NEEDS_MORE_INPUT => Some(NeedsMoreInput), TINFL_STATUS_HAS_MORE_OUTPUT => Some(HasMoreOutput), _ => None, } } } #[inline] pub fn decompress_to_vec(input: &[u8]) -> Result<Vec<u8>, TINFLStatus> { decompress_to_vec_inner(input, 0, usize::max_value()) } #[inline] pub fn decompress_to_vec_zlib(input: &[u8]) -> Result<Vec<u8>, TINFLStatus> { decompress_to_vec_inner( input, inflate_flags::TINFL_FLAG_PARSE_ZLIB_HEADER, usize::max_value(), ) } #[inline] pub fn decompress_to_vec_with_limit(input: &[u8], max_size: usize) -> Result<Vec<u8>, TINFLStatus> { decompress_to_vec_inner(input, 0, max_size) } #[inline] pub fn decompress_to_vec_zlib_with_limit( input: &[u8], max_size: usize, ) -> Result<Vec<u8>, TINFLStatus> { decompress_to_vec_inner(input, inflate_flags::TINFL_FLAG_PARSE_ZLIB_HEADER, max_size) }
pub fn decompress_slice_iter_to_slice<'out, 'inp>( out: &'out mut [u8], it: impl Iterator<Item = &'inp [u8]>, zlib_header: bool, ignore_adler32: bool, ) -> Result<usize, TINFLStatus> { use self::core::inflate_flags::*; let mut it = it.peekable(); let r = &mut DecompressorOxide::new(); let mut out_pos = 0; while let Some(in_buf) = it.next() { let has_more = it.peek().is_some(); let flags = { let mut f = TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; if zlib_header { f |= TINFL_FLAG_PARSE_ZLIB_HEADER; } if ignore_adler32 { f |= TINFL_FLAG_IGNORE_ADLER32; } if has_more { f |= TINFL_FLAG_HAS_MORE_INPUT; } f }; let (status, _input_read, bytes_written) = decompress(r, in_buf, out, out_pos, flags); out_pos += bytes_written; match status { TINFLStatus::NeedsMoreInput => continue, TINFLStatus::Done => return Ok(out_pos), e => return Err(e), } } Err(TINFLStatus::FailedCannotMakeProgress) } #[cfg(test)] mod test { use super::{ decompress_slice_iter_to_slice, decompress_to_vec_zlib, decompress_to_vec_zlib_with_limit, TINFLStatus, }; const encoded: [u8; 20] = [ 120, 156, 243, 72, 205, 201, 201, 215, 81, 168, 202, 201, 76, 82, 4, 0, 27, 101, 4, 19, ]; #[test] fn decompress_vec() { let res = decompress_to_vec_zlib(&encoded[..]).unwrap(); assert_eq!(res.as_slice(), &b"Hello, zlib!"[..]); } #[test] fn decompress_vec_with_high_limit() { let res = decompress_to_vec_zlib_with_limit(&encoded[..], 100_000).unwrap(); assert_eq!(res.as_slice(), &b"Hello, zlib!"[..]); } #[test] fn fail_to_decompress_with_limit() { let res = decompress_to_vec_zlib_with_limit(&encoded[..], 8); match res { Err(TINFLStatus::HasMoreOutput) => (), _ => panic!("Decompression output size limit was not enforced"), } } #[test] fn test_decompress_slice_iter_to_slice() { let mut out = [0_u8; 12_usize]; let r = decompress_slice_iter_to_slice(&mut out, Some(&encoded[..]).into_iter(), true, false); assert_eq!(r, Ok(12)); assert_eq!(&out[..12], &b"Hello, zlib!"[..]); for chunk_size in 1..13 { let mut out = [0_u8; 12_usize + 1]; let r = decompress_slice_iter_to_slice(&mut out, encoded.chunks(chunk_size), true, false); assert_eq!(r, Ok(12)); assert_eq!(&out[..12], &b"Hello, zlib!"[..]); } let mut out = [0_u8; 3_usize]; let r = decompress_slice_iter_to_slice(&mut out, encoded.chunks(7), true, false); assert!(r.is_err()); } }
fn decompress_to_vec_inner( input: &[u8], flags: u32, max_output_size: usize, ) -> Result<Vec<u8>, TINFLStatus> { let flags = flags | inflate_flags::TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; let mut ret: Vec<u8> = vec![0; min(input.len().saturating_mul(2), max_output_size)]; let mut decomp = Box::<DecompressorOxide>::default(); let mut in_pos = 0; let mut out_pos = 0; loop { let (status, in_consumed, out_consumed) = decompress(&mut decomp, &input[in_pos..], &mut ret, out_pos, flags); in_pos += in_consumed; out_pos += out_consumed; match status { TINFLStatus::Done => { ret.truncate(out_pos); return Ok(ret); } TINFLStatus::HasMoreOutput => { let new_len = ret .len() .checked_add(out_pos) .ok_or(TINFLStatus::HasMoreOutput)?; if new_len > max_output_size { return Err(TINFLStatus::HasMoreOutput); }; ret.resize(new_len, 0); } _ => return Err(status), } } }
function_block-full_function
[ { "content": "/// Compress the input data to a vector, using the specified compression level (0-10).\n\npub fn compress_to_vec(input: &[u8], level: u8) -> Vec<u8> {\n\n compress_to_vec_inner(input, level, 0, 0)\n\n}\n\n\n", "file_path": "miniz_oxide/src/deflate/mod.rs", "rank": 0, "score": 212970...
Rust
lib/src/config.rs
phylum-dev/cli
724395d036bc56c69acd69c0f59ea1308350a2c1
use chrono::{DateTime, Local}; use reqwest::Url; use serde::{Deserialize, Serialize}; use std::env; use std::error::Error; use std::fs; use std::path::PathBuf; use crate::types::*; #[derive(Debug, Serialize, Deserialize)] pub struct ConnectionInfo { pub uri: String, } #[derive(Debug, Serialize, Deserialize)] pub struct AuthInfo { pub oidc_discovery_url: Url, pub offline_access: Option<RefreshToken>, } pub type Packages = Vec<PackageDescriptor>; #[derive(Debug, Serialize, Deserialize)] pub struct Config { pub connection: ConnectionInfo, pub auth_info: AuthInfo, pub request_type: PackageType, pub packages: Option<Packages>, pub last_update: Option<usize>, pub ignore_certs: Option<bool>, } #[derive(Debug, Serialize, Deserialize)] pub struct ProjectConfig { pub id: ProjectId, pub name: String, pub created_at: DateTime<Local>, } pub fn save_config<T>(path: &str, config: &T) -> Result<(), Box<dyn Error + Send + Sync + 'static>> where T: Serialize, { let yaml = serde_yaml::to_string(config)?; fs::write(shellexpand::env(path)?.as_ref(), yaml)?; Ok(()) } pub fn parse_config<T>(path: &str) -> Result<T, Box<dyn Error + Send + Sync + 'static>> where T: serde::de::DeserializeOwned, { let contents = fs::read_to_string(shellexpand::env(path)?.as_ref())?; let config: T = serde_yaml::from_str(&contents)?; Ok(config) } pub fn read_configuration(path: &str) -> Result<Config, Box<dyn Error + Send + Sync + 'static>> { let mut config: Config = parse_config(path)?; if let Ok(key) = env::var("PHYLUM_API_KEY") { config.auth_info.offline_access = Some(RefreshToken::new(key)); } Ok(config) } pub fn find_project_conf(starting_directory: &str) -> Option<String> { let mut path: PathBuf = starting_directory.into(); let mut attempts = 0; const MAX_DEPTH: u8 = 32; loop { let search_path = path.join(PROJ_CONF_FILE); if search_path.is_file() { return Some(search_path.to_string_lossy().to_string()); } if attempts > MAX_DEPTH { return None; } path.push(".."); attempts += 1; } } pub fn get_current_project() -> Option<ProjectConfig> { find_project_conf(".").and_then(|s| { log::info!("Found project configuration file at {}", s); parse_config(&s).ok() }) } #[cfg(test)] mod tests { use super::*; use std::env::temp_dir; fn write_test_config() { let con = ConnectionInfo { uri: "http://127.0.0.1".into(), }; let auth = AuthInfo { oidc_discovery_url: Url::parse("http://example.com").unwrap(), offline_access: Some(RefreshToken::new("FAKE TOKEN")), }; let packages = vec![ PackageDescriptor { name: "foo".into(), version: "1.2.3".into(), r#type: PackageType::Npm, }, PackageDescriptor { name: "bar".into(), version: "3.4.5".into(), r#type: PackageType::Npm, }, PackageDescriptor { name: "baz".into(), version: "2020.2.12".into(), r#type: PackageType::Npm, }, ]; let config = Config { connection: con, auth_info: auth, request_type: PackageType::Npm, packages: Some(packages), last_update: None, ignore_certs: None, }; let temp_dir = temp_dir(); let test_config_file = temp_dir.as_path().join("test_config"); save_config(test_config_file.to_str().unwrap(), &config).unwrap(); } #[test] fn test_save_config() { write_test_config(); } #[test] fn test_parse_config() { write_test_config(); let temp_dir = temp_dir(); let test_config_file = temp_dir.as_path().join("test_config"); let config: Config = parse_config(test_config_file.to_str().unwrap()).unwrap(); assert_eq!(config.request_type, PackageType::Npm); } }
use chrono::{DateTime, Local}; use reqwest::Url; use serde::{Deserialize, Serialize}; use std::env; use std::error::Error; use std::fs; use std::path::PathBuf; use crate::types::*; #[derive(Debug, Serialize, Deserialize)] pub struct ConnectionInfo { pub uri: String, } #[derive(Debug, Serialize, Deserialize)] pub struct AuthInfo { pub oidc_discovery_url: Url, pub offline_access: Option<RefreshToken>, } pub type Packages = Vec<PackageDescriptor>; #[derive(Debug, Serialize, Deserialize)] pub struct Config { pub connection: ConnectionInfo, pub auth_info: AuthInfo, pub request_type: PackageType, pub packages: Option<Packages>, pub last_update: Option<usize>, pub ignore_certs: Option<bool>, } #[derive(Debug, Serialize, Deserialize)] pub struct ProjectConfig { pub id: ProjectId, pub name: String, pub created_at: DateTime<Local>, } pub fn save_config<T>(path: &str, config: &T) -> Result<(), Box<dyn Error + Send + Sync + 'static>> where T: Serialize, { let yaml = serde_yaml::to_string(config)?; fs::write(shellexpand::env(path)?.as_ref(), yaml)?; Ok(()) } pub fn parse_config<T>(path: &str) -> Result<T, Box<dyn Error + Send + Sync + 'static>> where T: serde::de::DeserializeOwned, { let contents = fs::read_to_string(shellexpand::env(path)?.as_ref())?; let config: T = serde_yaml::from_str(&contents)?; Ok(config) } pub fn read_configuration(path: &str) -> Result<Config, Box<dyn Error + Send + Sync + 'static>> { let mut config: Config = parse_config(path)?; if let Ok(key) = env::var("PHYLUM_API_KEY") { config.auth_info.offline_access = Some(RefreshToken::new(key)); } Ok(config) } pub fn find_project_conf(starting_directory: &str) -> Option<String> { let mut path: PathBuf = starting_directory.into(); let mut atte
pub fn get_current_project() -> Option<ProjectConfig> { find_project_conf(".").and_then(|s| { log::info!("Found project configuration file at {}", s); parse_config(&s).ok() }) } #[cfg(test)] mod tests { use super::*; use std::env::temp_dir; fn write_test_config() { let con = ConnectionInfo { uri: "http://127.0.0.1".into(), }; let auth = AuthInfo { oidc_discovery_url: Url::parse("http://example.com").unwrap(), offline_access: Some(RefreshToken::new("FAKE TOKEN")), }; let packages = vec![ PackageDescriptor { name: "foo".into(), version: "1.2.3".into(), r#type: PackageType::Npm, }, PackageDescriptor { name: "bar".into(), version: "3.4.5".into(), r#type: PackageType::Npm, }, PackageDescriptor { name: "baz".into(), version: "2020.2.12".into(), r#type: PackageType::Npm, }, ]; let config = Config { connection: con, auth_info: auth, request_type: PackageType::Npm, packages: Some(packages), last_update: None, ignore_certs: None, }; let temp_dir = temp_dir(); let test_config_file = temp_dir.as_path().join("test_config"); save_config(test_config_file.to_str().unwrap(), &config).unwrap(); } #[test] fn test_save_config() { write_test_config(); } #[test] fn test_parse_config() { write_test_config(); let temp_dir = temp_dir(); let test_config_file = temp_dir.as_path().join("test_config"); let config: Config = parse_config(test_config_file.to_str().unwrap()).unwrap(); assert_eq!(config.request_type, PackageType::Npm); } }
mpts = 0; const MAX_DEPTH: u8 = 32; loop { let search_path = path.join(PROJ_CONF_FILE); if search_path.is_file() { return Some(search_path.to_string_lossy().to_string()); } if attempts > MAX_DEPTH { return None; } path.push(".."); attempts += 1; } }
function_block-function_prefixed
[ { "content": "/// Produces the path to a temporary file on disk.\n\nfn tmp_path(filename: &str) -> Option<String> {\n\n let tmp_loc = env::temp_dir();\n\n let path = Path::new(&tmp_loc);\n\n let tmp_path = path.join(filename);\n\n match tmp_path.into_os_string().into_string() {\n\n Ok(x) => S...
Rust
src/main.rs
advion/cartunes
83b085318b314a332d877e83c3841050b0c7699c
#![cfg_attr(not(any(test, debug_assertions)), windows_subsystem = "windows")] #![deny(clippy::all)] use crate::framework::{ConfigHandler, Framework, UserEvent}; use crate::gpu::{Error as GpuError, Gpu}; use crate::gui::{Error as GuiError, Gui}; use crate::setup::Setups; use log::error; use std::collections::VecDeque; use thiserror::Error; use winit::event::{Event, WindowEvent}; use winit::event_loop::{ControlFlow, EventLoop}; use winit::window::WindowBuilder; use winit_input_helper::WinitInputHelper; #[cfg(windows)] use winit::platform::windows::IconExtWindows; #[cfg(windows)] use winit::window::Icon; mod config; mod framework; mod gpu; mod gui; mod setup; mod str_ext; mod timer; mod updates; #[derive(Debug, Error)] enum Error { #[error("Window creation error: {0}")] Winit(#[from] winit::error::OsError), #[error("GUI Error: {0}")] Gui(#[from] GuiError), #[error("GPU Error: {0}")] Gpu(#[from] GpuError), } fn create_window() -> Result<(EventLoop<UserEvent>, winit::window::Window, Gpu, Framework), Error> { let config = Framework::load_config(); let window_builder = if let Ok(Some(config)) = config.as_ref() { if let Some(window) = config.get_window() { WindowBuilder::new() .with_position(window.position) .with_inner_size(window.size) } else { WindowBuilder::new() } } else { WindowBuilder::new() }; let window_builder = { #[cfg(target_os = "windows")] { const ICON_RESOURCE_ID: u16 = 2; window_builder.with_window_icon(Some( Icon::from_resource(ICON_RESOURCE_ID, None).expect("Unable to load icon"), )) } #[cfg(not(target_os = "windows"))] window_builder }; let event_loop = EventLoop::with_user_event(); let window = window_builder .with_title("CarTunes") .with_min_inner_size(Framework::min_size()) .build(&event_loop)?; let (gpu, framework) = { let window_size = window.inner_size(); let scale_factor = window.scale_factor() as f32; let mut errors = VecDeque::new(); let mut warnings = VecDeque::new(); let config = Framework::unwrap_config(&mut errors, event_loop.create_proxy(), config); let setups = Setups::new(&mut warnings, &config); let theme = config.theme().as_winit_theme(&window); let gui = Gui::new(config, setups, event_loop.create_proxy(), errors, warnings)?; let gpu = Gpu::new(&window, window_size)?; let framework = Framework::new( window_size, scale_factor, theme, gui, &gpu, event_loop.create_proxy(), ); (gpu, framework) }; Ok((event_loop, window, gpu, framework)) } fn main() -> Result<(), Error> { #[cfg(any(debug_assertions, not(windows)))] env_logger::init(); let (event_loop, window, mut gpu, mut framework) = create_window()?; let mut input = WinitInputHelper::new(); let mut keep_config = ConfigHandler::Replace; event_loop.run(move |event, _, control_flow| { if input.update(&event) { if let Some(scale_factor) = input.scale_factor() { framework.scale_factor(scale_factor); } if let Some(size) = input.window_resized() { if size.width > 0 && size.height > 0 { gpu.resize(size); framework.resize(size); } } window.request_redraw(); } match event { Event::UserEvent(event) => match event { UserEvent::ConfigHandler(config_handler) => { keep_config = config_handler; } UserEvent::Exit => { *control_flow = ControlFlow::Exit; } UserEvent::SetupPath(Some(setups_path)) => { framework.update_setups_path(setups_path); } UserEvent::FsChange(event) => { framework.handle_fs_change(event); } UserEvent::Theme(theme) => { let theme = theme.as_winit_theme(&window); framework.change_theme(theme, true); window.request_redraw(); } UserEvent::UpdateCheck => { framework.recreate_update_check(); } UserEvent::UpdateAvailable(notification) => { framework.add_update_notification(notification); } _ => (), }, Event::WindowEvent { event, .. } => { framework.handle_event(&event); match event { WindowEvent::ThemeChanged(theme) => { framework.change_theme(theme, false); window.request_redraw(); } WindowEvent::CloseRequested => { if keep_config == ConfigHandler::Keep || framework.save_config(&window) { *control_flow = ControlFlow::Exit; } } _ => (), } } Event::RedrawRequested(_) => { framework.prepare(&window); let (mut encoder, frame) = match gpu.prepare() { Ok((encoder, frame)) => (encoder, frame), Err(err) => { error!("gpu.prepare() failed: {}", err); *control_flow = ControlFlow::Exit; return; } }; let view = frame .texture .create_view(&wgpu::TextureViewDescriptor::default()); let render_result = framework.render(&mut encoder, &view, &gpu); if let Err(err) = render_result { error!("framework.render() failed: {}", err); *control_flow = ControlFlow::Exit; return; } gpu.queue.submit(Some(encoder.finish())); frame.present(); } _ => (), } }); }
#![cfg_attr(not(any(test, debug_assertions)), windows_subsystem = "windows")] #![deny(clippy::all)] use crate::framework::{ConfigHandler, Framework, UserEvent}; use crate::gpu::{Error as GpuError, Gpu}; use crate::gui::{Error as GuiError, Gui}; use crate::setup::Setups; use log::error; use std::collections::VecDeque; use thiserror::Error; use winit::event::{Event, WindowEvent}; use winit::event_loop::{ControlFlow, EventLoop}; use winit::window::WindowBuilder; use winit_input_helper::WinitInputHelper; #[cfg(windows)] use winit::platform::windows::IconExtWindows; #[cfg(windows)] use winit::window::Icon; mod config; mod framework; mod gpu; mod gui; mod setup; mod str_ext; mod timer; mod updates; #[derive(Debug, Error)] enum Error { #[error("Window creation error: {0}")] Winit(#[from] winit::error::OsError), #[error("GUI Error: {0}")] Gui(#[from] GuiError), #[error("GPU Error: {0}")] Gpu(#[from] GpuError), } fn create_window() -> Result<(EventLoop<UserEvent>, winit::window::Window, Gpu, Framework), Error> { let config = Framework::load_config(); let window_builder = if let Ok(Some(config)) = config.as_ref() { if let Some(window) = config.get_window() { WindowBuilder::new() .with_position(window.position) .with_inner_size(window.size) } else { WindowBuilder::new() } } else { WindowBuilder::new() }; let window_builder = { #[cfg(target_os = "windows")] { const ICON_RESOURCE_ID: u16 = 2; window_builder.with_window_icon(Some( Icon::from_resource(ICON_RESOURCE_ID, None).expect("Unable to load icon"), )) } #[cfg(not(target_os = "windows"))] window_builder }; let event_loop = EventLoop::with_user_event(); let window = window_builder .with_title("CarTunes") .with_min_inner_size(Framework::min_size()) .build(&event_loop)?; let (gpu, framework) = { let window_size = window.inner_size(); let scale_factor = window.scale_factor() as f32; let mut errors = VecDeque::new(); let mut warnings = VecDeque::new(); let config = Framework::unwrap_config(&mut errors, event_loop.create_proxy(), config); let setups = Setups::new(&mut warnings, &config); let theme = config.theme().as_winit_theme(&window); let gui = Gui::new(config, setups, event_loop.create_proxy(), errors, warnings)?; let gpu = Gpu::new(&window, window_size)?; l
fn main() -> Result<(), Error> { #[cfg(any(debug_assertions, not(windows)))] env_logger::init(); let (event_loop, window, mut gpu, mut framework) = create_window()?; let mut input = WinitInputHelper::new(); let mut keep_config = ConfigHandler::Replace; event_loop.run(move |event, _, control_flow| { if input.update(&event) { if let Some(scale_factor) = input.scale_factor() { framework.scale_factor(scale_factor); } if let Some(size) = input.window_resized() { if size.width > 0 && size.height > 0 { gpu.resize(size); framework.resize(size); } } window.request_redraw(); } match event { Event::UserEvent(event) => match event { UserEvent::ConfigHandler(config_handler) => { keep_config = config_handler; } UserEvent::Exit => { *control_flow = ControlFlow::Exit; } UserEvent::SetupPath(Some(setups_path)) => { framework.update_setups_path(setups_path); } UserEvent::FsChange(event) => { framework.handle_fs_change(event); } UserEvent::Theme(theme) => { let theme = theme.as_winit_theme(&window); framework.change_theme(theme, true); window.request_redraw(); } UserEvent::UpdateCheck => { framework.recreate_update_check(); } UserEvent::UpdateAvailable(notification) => { framework.add_update_notification(notification); } _ => (), }, Event::WindowEvent { event, .. } => { framework.handle_event(&event); match event { WindowEvent::ThemeChanged(theme) => { framework.change_theme(theme, false); window.request_redraw(); } WindowEvent::CloseRequested => { if keep_config == ConfigHandler::Keep || framework.save_config(&window) { *control_flow = ControlFlow::Exit; } } _ => (), } } Event::RedrawRequested(_) => { framework.prepare(&window); let (mut encoder, frame) = match gpu.prepare() { Ok((encoder, frame)) => (encoder, frame), Err(err) => { error!("gpu.prepare() failed: {}", err); *control_flow = ControlFlow::Exit; return; } }; let view = frame .texture .create_view(&wgpu::TextureViewDescriptor::default()); let render_result = framework.render(&mut encoder, &view, &gpu); if let Err(err) = render_result { error!("framework.render() failed: {}", err); *control_flow = ControlFlow::Exit; return; } gpu.queue.submit(Some(encoder.finish())); frame.present(); } _ => (), } }); }
et framework = Framework::new( window_size, scale_factor, theme, gui, &gpu, event_loop.create_proxy(), ); (gpu, framework) }; Ok((event_loop, window, gpu, framework)) }
function_block-function_prefixed
[ { "content": "/// Configure the theme based on system settings.\n\nfn update_theme(theme: &mut Option<Theme>, ctx: &egui::CtxRef) {\n\n if let Some(theme) = theme.take() {\n\n // Set the style\n\n ctx.set_style(create_style(theme));\n\n }\n\n}\n\n\n\npub(crate) fn cache_path() -> PathBuf {\n...
Rust
src/ser.rs
sisyphe-re/libnar
9ffada39937be91518eaf7fbc27dc0002e95a3db
use std::fs::{self, File}; use std::io::{self, Error, ErrorKind, Read, Write}; use std::os::unix::fs::MetadataExt; use std::path::Path; use crate::{NIX_VERSION_MAGIC, PAD_LEN}; pub fn to_vec<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> { let mut buffer = Vec::new(); to_writer(&mut buffer, path)?; Ok(buffer) } pub fn to_writer<W, P>(writer: &mut W, path: P) -> io::Result<()> where W: Write, P: AsRef<Path>, { let target = path.as_ref(); if fs::symlink_metadata(target).is_err() { return Err(Error::new(ErrorKind::NotFound, "Path not found")); } write_padded(writer, NIX_VERSION_MAGIC)?; encode_entry(writer, target) } fn encode_entry<W: Write>(writer: &mut W, path: &Path) -> io::Result<()> { let metadata = fs::symlink_metadata(path)?; write_padded(writer, b"(")?; write_padded(writer, b"type")?; if metadata.file_type().is_dir() { write_padded(writer, b"directory")?; let mut entries: Vec<_> = fs::read_dir(path)?.collect::<Result<_, _>>()?; entries.sort_by(|x, y| x.path().cmp(&y.path())); for entry in entries { write_padded(writer, b"entry")?; write_padded(writer, b"(")?; write_padded(writer, b"name")?; write_padded(writer, entry.file_name().to_string_lossy().as_bytes())?; write_padded(writer, b"node")?; encode_entry(writer, &entry.path())?; write_padded(writer, b")")?; } } else if metadata.file_type().is_file() { write_padded(writer, b"regular")?; if metadata.mode() & 0o111 != 0 { write_padded(writer, b"executable")?; write_padded(writer, b"")?; } write_padded(writer, b"contents")?; let mut file = File::open(path)?; write_padded_from_reader(writer, &mut file, metadata.len())?; } else if metadata.file_type().is_symlink() { write_padded(writer, b"symlink")?; write_padded(writer, b"target")?; let target = fs::read_link(path)?; write_padded(writer, target.to_string_lossy().as_bytes())?; } else { return Err(Error::new(ErrorKind::InvalidData, "Unrecognized file type")); } write_padded(writer, b")")?; Ok(()) } fn write_padded<W: Write>(writer: &mut W, bytes: &[u8]) -> io::Result<()> { let len = bytes.len() as u64; writer.write_all(&len.to_le_bytes())?; writer.write_all(bytes)?; let remainder = bytes.len() % PAD_LEN; if remainder > 0 { let buf = [0u8; PAD_LEN]; let padding = PAD_LEN - remainder; writer.write_all(&buf[..padding])?; } Ok(()) } fn write_padded_from_reader<W, R>(writer: &mut W, reader: &mut R, len: u64) -> io::Result<()> where W: Write, R: Read, { writer.write_all(&len.to_le_bytes())?; io::copy(reader, writer)?; let remainder = (len % PAD_LEN as u64) as usize; if remainder > 0 { let buf = [0u8; PAD_LEN]; let padding = PAD_LEN - remainder; writer.write_all(&buf[..padding])?; } Ok(()) } #[cfg(test)] mod tests { use std::mem::size_of; use super::*; #[test] fn writes_multiple_of_eight_exactly() { let mut buffer = Vec::new(); let length = 16u64; let data = vec![1u8; length as usize]; write_padded(&mut buffer, &data[..]).unwrap(); let written_data_len = size_of::<u64>() as u64 + length; assert_eq!(buffer.len() as u64, written_data_len); let header_bytes = length.to_le_bytes(); assert_eq!(&buffer[..size_of::<u64>()], header_bytes); let data_bytes = [1u8; 16]; assert_eq!(&buffer[size_of::<u64>()..], data_bytes); } #[test] fn pads_non_multiple_of_eight() { let mut buffer = Vec::new(); let length = 5u64; let data = vec![1u8; length as usize]; write_padded(&mut buffer, &data[..]).unwrap(); let written_data_len = size_of::<u64>() as u64 + length + 3; assert_eq!(buffer.len() as u64, written_data_len); let header_bytes = length.to_le_bytes(); assert_eq!(&buffer[..size_of::<u64>()], header_bytes); let data_bytes = [1u8; 5]; assert_eq!(&buffer[size_of::<u64>()..size_of::<u64>() + 5], data_bytes); let padding_bytes = [0u8; 3]; assert_eq!(&buffer[size_of::<u64>() + 5..], padding_bytes); } }
use std::fs::{self, File}; use std::io::{self, Error, ErrorKind, Read, Write}; use std::os::unix::fs::MetadataExt; use std::path::Path; use crate::{NIX_VERSION_MAGIC, PAD_LEN}; pub fn to_vec<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> { let mut buffer = Vec::new(); to_writer(&mut buffer, path)?; Ok(buffer) } pub fn to_writer<W, P>(writer: &mut W, path: P) -> io::Result<()> where W: Write, P: AsRef<Path>, { let target = path.as_ref(); if fs::symlink_metadata(target).is_err() { return Err(Error::new(ErrorKind::NotFound, "Path not found")); } write_padded(writer, NIX_VERSION_MAGIC)?; encode_entry(writer, target) } fn encode_entry<W: Write>(writer: &mut W, path: &Path) -> io::Result<()> { let metadata = fs::symlink_metadata(path)?; write_padded(writer, b"(")?; write_padded(writer, b"type")?; if metadata.file_type().is_dir() { write_padded(writer, b"directory")?; let mut entries: Vec<_> = fs::read_dir(path)?.collect::<Result<_, _>>()?; entries.sort_by(|x, y| x.path().cmp(&y.path())); for entry in entries { write_padded(writer, b"entry")?; write_padded(writer, b"(")?; write_padded(writer, b"name")?; write_padded(writer, entry.file_name().to_string_lossy().as_bytes())?; write_padded(writer, b"node")?; encode_entry(writer, &entry.path())?; write_padded(writer, b")")?; } } else if metadata.file_type().is_file() { write_padded(writer, b"regular")?; if metadata.mode() & 0o111 != 0 { write_padded(writer, b"executable")?; write_padded(writer, b"")?; } write_padded(writer, b"contents")?; let mut file = File::open(path)?; write_padded_from_reader(writer, &mut file, metadata.len())?; } else if metadata.file_type().is_symlink() { write_padded(writer, b"symlink")?; write_padded(writer, b"target")?; let target = fs::read_link(path)?; write_padded(writer, target.to_string_lossy().as_bytes())?; } else { return Err(Error::new(ErrorKind::InvalidData, "Unrecognized file type")); } write_padded(writer, b")")?; Ok(()) } fn write_padded<W: Write>(writer: &mut W, bytes: &[u8]) -> io::Result<()> { let len = bytes.len() as u64; writer.write_all(&len.to_le_bytes())?; writer.write_all(bytes)?; let remainder = bytes.len() % PAD_LEN; if remainder > 0 { let buf = [0u8; PAD_LEN]; let padding = PAD_LEN - remainder; writer.write_all(&buf[..padding])?; } Ok(()) } fn write_padded_from_reader<W, R>(writer: &mut W, reader: &mut R, len: u64) -> io::Result<()> where W: Write, R: Read, { writer.write_all(&len.to_le_bytes())?; io::copy(reader, writer)?; let remainder = (len % PAD_LEN as u64) as usize; if remainder > 0 { let buf = [0u8; PAD_LEN]; let padding = PAD_LEN - remainder; writer.write_all(&buf[..padding])?; } Ok(()) } #[cfg(test)] mod tests { use std::mem::size_of; use super::*; #[test] fn writes_multiple_of_eight_exactly() { let mut buffer = Vec::new(); let length = 16u64; let data = vec![1u8; length as usize];
#[test] fn pads_non_multiple_of_eight() { let mut buffer = Vec::new(); let length = 5u64; let data = vec![1u8; length as usize]; write_padded(&mut buffer, &data[..]).unwrap(); let written_data_len = size_of::<u64>() as u64 + length + 3; assert_eq!(buffer.len() as u64, written_data_len); let header_bytes = length.to_le_bytes(); assert_eq!(&buffer[..size_of::<u64>()], header_bytes); let data_bytes = [1u8; 5]; assert_eq!(&buffer[size_of::<u64>()..size_of::<u64>() + 5], data_bytes); let padding_bytes = [0u8; 3]; assert_eq!(&buffer[size_of::<u64>() + 5..], padding_bytes); } }
write_padded(&mut buffer, &data[..]).unwrap(); let written_data_len = size_of::<u64>() as u64 + length; assert_eq!(buffer.len() as u64, written_data_len); let header_bytes = length.to_le_bytes(); assert_eq!(&buffer[..size_of::<u64>()], header_bytes); let data_bytes = [1u8; 16]; assert_eq!(&buffer[size_of::<u64>()..], data_bytes); }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn serializes_regular_file() {\n\n let dir = tempfile::tempdir().unwrap();\n\n let mut file = File::create(dir.path().join(\"file.txt\")).unwrap();\n\n writeln!(file, \"lorem ipsum dolor sic amet\").unwrap();\n\n\n\n let expected: Vec<u8> = std::iter::empty()\n\n .cha...
Rust
src/sys/pkg/testing/blobfs-ramdisk/src/lib.rs
dahlia-os/fuchsia-pine64-pinephone
57aace6f0b0bd75306426c98ab9eb3ff4524a61d
#![deny(missing_docs)] use { anyhow::{format_err, Context as _, Error}, fdio::{SpawnAction, SpawnOptions}, fidl::endpoints::{ClientEnd, ServerEnd}, fidl_fuchsia_io::{ DirectoryAdminMarker, DirectoryAdminProxy, DirectoryMarker, DirectoryProxy, NodeProxy, }, fuchsia_component::server::ServiceFs, fuchsia_merkle::{Hash, MerkleTreeBuilder}, fuchsia_runtime::{HandleInfo, HandleType}, fuchsia_zircon::{self as zx, prelude::*}, futures::prelude::*, ramdevice_client::RamdiskClient, scoped_task::Scoped, std::{borrow::Cow, collections::BTreeSet, ffi::CString}, }; #[cfg(test)] mod test; #[derive(Debug, Clone)] pub struct BlobInfo { merkle: Hash, contents: Cow<'static, [u8]>, } impl<B> From<B> for BlobInfo where B: Into<Cow<'static, [u8]>>, { fn from(bytes: B) -> Self { let bytes = bytes.into(); let mut tree = MerkleTreeBuilder::new(); tree.write(&bytes); Self { merkle: tree.finish().root(), contents: bytes } } } pub struct BlobfsRamdiskBuilder { ramdisk: Option<Ramdisk>, blobs: Vec<BlobInfo>, } impl BlobfsRamdiskBuilder { fn new() -> Self { Self { ramdisk: None, blobs: vec![] } } pub fn ramdisk(mut self, ramdisk: Ramdisk) -> Self { self.ramdisk = Some(ramdisk); self } pub fn with_blob(mut self, blob: impl Into<BlobInfo>) -> Self { self.blobs.push(blob.into()); self } pub fn start(self) -> Result<BlobfsRamdisk, Error> { let ramdisk = match self.ramdisk { Some(ramdisk) => ramdisk, None => { let ramdisk = Ramdisk::start().context("creating backing ramdisk for blobfs")?; mkblobfs(&ramdisk)?; ramdisk } }; let block_device_handle_id = HandleInfo::new(HandleType::User0, 1); let fs_root_handle_id = HandleInfo::new(HandleType::User0, 0); let block_handle = ramdisk.clone_channel().context("cloning ramdisk channel")?; let (proxy, blobfs_server_end) = fidl::endpoints::create_proxy::<DirectoryAdminMarker>()?; let process = scoped_task::spawn_etc( scoped_task::job_default(), SpawnOptions::CLONE_ALL, &CString::new("/pkg/bin/blobfs").unwrap(), &[&CString::new("blobfs").unwrap(), &CString::new("mount").unwrap()], None, &mut [ SpawnAction::add_handle(block_device_handle_id, block_handle.into()), SpawnAction::add_handle(fs_root_handle_id, blobfs_server_end.into()), ], ) .map_err(|(status, _)| status) .context("spawning 'blobfs mount'")?; let blobfs = BlobfsRamdisk { backing_ramdisk: ramdisk, process, proxy }; if !self.blobs.is_empty() { let mut present_blobs = blobfs.list_blobs()?; for blob in self.blobs { if present_blobs.contains(&blob.merkle) { continue; } blobfs .write_blob_sync(&blob.merkle, &blob.contents) .context(format!("writing {}", blob.merkle))?; present_blobs.insert(blob.merkle); } } Ok(blobfs) } } pub struct BlobfsRamdisk { backing_ramdisk: Ramdisk, process: Scoped<fuchsia_zircon::Process>, proxy: DirectoryAdminProxy, } impl BlobfsRamdisk { pub fn builder() -> BlobfsRamdiskBuilder { BlobfsRamdiskBuilder::new() } pub fn start() -> Result<Self, Error> { Self::builder().start() } pub fn root_dir_handle(&self) -> Result<ClientEnd<DirectoryMarker>, Error> { let (root_clone, server_end) = zx::Channel::create()?; self.proxy.clone(fidl_fuchsia_io::CLONE_FLAG_SAME_RIGHTS, server_end.into())?; Ok(root_clone.into()) } pub fn root_dir_proxy(&self) -> Result<DirectoryProxy, Error> { Ok(self.root_dir_handle()?.into_proxy()?) } pub fn root_dir(&self) -> Result<openat::Dir, Error> { fdio::create_fd(self.root_dir_handle()?.into()).context("failed to create fd") } pub async fn into_builder(self) -> Result<BlobfsRamdiskBuilder, Error> { let ramdisk = self.unmount().await?; Ok(Self::builder().ramdisk(ramdisk)) } pub async fn unmount(self) -> Result<Ramdisk, Error> { zx::Status::ok(self.proxy.unmount().await.context("sending blobfs unmount")?) .context("unmounting blobfs")?; self.process .wait_handle( zx::Signals::PROCESS_TERMINATED, zx::Time::after(zx::Duration::from_seconds(30)), ) .context("waiting for 'blobfs mount' to exit")?; let ret = self.process.info().context("getting 'blobfs mount' process info")?.return_code; if ret != 0 { return Err(format_err!("'blobfs mount' returned nonzero exit code {}", ret)); } Ok(self.backing_ramdisk) } pub async fn stop(self) -> Result<(), Error> { self.unmount().await?.stop() } pub fn list_blobs(&self) -> Result<BTreeSet<Hash>, Error> { self.root_dir()? .list_dir(".")? .map(|entry| { Ok(entry? .file_name() .to_str() .ok_or_else(|| anyhow::format_err!("expected valid utf-8"))? .parse()?) }) .collect() } pub fn add_blob_from( &self, merkle: &Hash, mut source: impl std::io::Read, ) -> Result<(), Error> { let mut bytes = vec![]; source.read_to_end(&mut bytes)?; self.write_blob_sync(merkle, &bytes) } fn write_blob_sync(&self, merkle: &Hash, bytes: &[u8]) -> Result<(), Error> { use std::{convert::TryInto, io::Write}; let mut file = self.root_dir().unwrap().write_file(merkle.to_string(), 0o777)?; file.set_len(bytes.len().try_into().unwrap())?; file.write_all(&bytes)?; Ok(()) } } pub struct Ramdisk { proxy: NodeProxy, client: RamdiskClient, } impl Ramdisk { pub fn start() -> Result<Self, Error> { let client = RamdiskClient::builder(512, 1 << 20).isolated_dev_root().build()?; let proxy = NodeProxy::new(fuchsia_async::Channel::from_channel(client.open()?)?); Ok(Ramdisk { proxy, client }) } fn clone_channel(&self) -> Result<zx::Channel, Error> { let (result, server_end) = zx::Channel::create()?; self.proxy.clone(fidl_fuchsia_io::CLONE_FLAG_SAME_RIGHTS, ServerEnd::new(server_end))?; Ok(result) } fn clone_handle(&self) -> Result<zx::Handle, Error> { Ok(self.clone_channel().context("cloning ramdisk channel")?.into()) } pub fn stop(self) -> Result<(), Error> { Ok(self.client.destroy()?) } pub async fn corrupt_blob(&self, merkle: &Hash) { let ramdisk = Clone::clone(&self.proxy); blobfs_corrupt_blob(ramdisk, merkle).await.unwrap(); } } async fn blobfs_corrupt_blob(ramdisk: NodeProxy, merkle: &Hash) -> Result<(), Error> { let mut fs = ServiceFs::new(); fs.root_dir().add_service_at("block", |chan| { ramdisk .clone( fidl_fuchsia_io::CLONE_FLAG_SAME_RIGHTS | fidl_fuchsia_io::OPEN_FLAG_DESCRIBE, ServerEnd::new(chan), ) .unwrap(); None }); let (devfs_client, devfs_server) = zx::Channel::create()?; fs.serve_connection(devfs_server)?; let serve_fs = fs.collect::<()>(); let spawn_and_wait = async move { let p = fdio::spawn_etc( &fuchsia_runtime::job_default(), SpawnOptions::CLONE_ALL - SpawnOptions::CLONE_NAMESPACE, &CString::new("/pkg/bin/blobfs-corrupt").unwrap(), &[ &CString::new("blobfs-corrupt").unwrap(), &CString::new("--device").unwrap(), &CString::new("/dev/block").unwrap(), &CString::new("--merkle").unwrap(), &CString::new(merkle.to_string()).unwrap(), ], None, &mut [SpawnAction::add_namespace_entry( &CString::new("/dev").unwrap(), devfs_client.into(), )], ) .map_err(|(status, _)| status) .context("spawning 'blobfs-corrupt'")?; wait_for_process_async(p).await.context("'blobfs-corrupt'")?; Ok(()) }; let ((), res) = futures::join!(serve_fs, spawn_and_wait); res } async fn wait_for_process_async(proc: fuchsia_zircon::Process) -> Result<(), Error> { let signals = fuchsia_async::OnSignals::new(&proc.as_handle_ref(), zx::Signals::PROCESS_TERMINATED) .await .context("waiting for tool to terminate")?; assert_eq!(signals, zx::Signals::PROCESS_TERMINATED); let ret = proc.info().context("getting tool process info")?.return_code; if ret != 0 { return Err(format_err!("tool returned nonzero exit code {}", ret)); } Ok(()) } fn mkblobfs_block(block_device: zx::Handle) -> Result<(), Error> { let block_device_handle_id = HandleInfo::new(HandleType::User0, 1); let p = fdio::spawn_etc( &fuchsia_runtime::job_default(), SpawnOptions::CLONE_ALL, &CString::new("/pkg/bin/blobfs").unwrap(), &[&CString::new("blobfs").unwrap(), &CString::new("mkfs").unwrap()], None, &mut [SpawnAction::add_handle(block_device_handle_id, block_device)], ) .map_err(|(status, _)| status) .context("spawning 'blobfs mkfs'")?; wait_for_process(p).context("'blobfs mkfs'")?; Ok(()) } fn wait_for_process(proc: fuchsia_zircon::Process) -> Result<(), Error> { proc.wait_handle( zx::Signals::PROCESS_TERMINATED, zx::Time::after(zx::Duration::from_seconds(30)), ) .context("waiting for tool to terminate")?; let ret = proc.info().context("getting tool process info")?.return_code; if ret != 0 { return Err(format_err!("tool returned nonzero exit code {}", ret)); } Ok(()) } fn mkblobfs(ramdisk: &Ramdisk) -> Result<(), Error> { mkblobfs_block(ramdisk.clone_handle()?) } #[cfg(test)] mod tests { use {super::*, maplit::btreeset, std::io::Write}; #[fuchsia_async::run_singlethreaded(test)] async fn clean_start_and_stop() { let blobfs = BlobfsRamdisk::start().unwrap(); let proxy = blobfs.root_dir_proxy().unwrap(); drop(proxy); blobfs.stop().await.unwrap(); } #[fuchsia_async::run_singlethreaded(test)] async fn clean_start_contains_no_blobs() { let blobfs = BlobfsRamdisk::start().unwrap(); assert_eq!(blobfs.list_blobs().unwrap(), btreeset![]); blobfs.stop().await.unwrap(); } #[test] fn blob_info_conversions() { let a = BlobInfo::from(&b"static slice"[..]); let b = BlobInfo::from(b"owned vec".to_vec()); let c = BlobInfo::from(Cow::from(&b"cow"[..])); assert_ne!(a.merkle, b.merkle); assert_ne!(b.merkle, c.merkle); assert_eq!( a.merkle, fuchsia_merkle::MerkleTree::from_reader(&b"static slice"[..]).unwrap().root() ); let _ = BlobfsRamdisk::builder() .with_blob(&b"static slice"[..]) .with_blob(b"owned vec".to_vec()) .with_blob(Cow::from(&b"cow"[..])); } #[fuchsia_async::run_singlethreaded(test)] async fn with_blob_ignores_duplicates() { let blob = BlobInfo::from(&b"duplicate"[..]); let blobfs = BlobfsRamdisk::builder() .with_blob(blob.clone()) .with_blob(blob.clone()) .start() .unwrap(); assert_eq!(blobfs.list_blobs().unwrap(), btreeset![blob.merkle.clone()]); let blobfs = blobfs.into_builder().await.unwrap().with_blob(blob.clone()).start().unwrap(); assert_eq!(blobfs.list_blobs().unwrap(), btreeset![blob.merkle.clone()]); } #[fuchsia_async::run_singlethreaded(test)] async fn build_with_two_blobs() { let blobfs = BlobfsRamdisk::builder() .with_blob(&b"blob 1"[..]) .with_blob(&b"blob 2"[..]) .start() .unwrap(); let expected = btreeset![ fuchsia_merkle::MerkleTree::from_reader(&b"blob 1"[..]).unwrap().root(), fuchsia_merkle::MerkleTree::from_reader(&b"blob 2"[..]).unwrap().root(), ]; assert_eq!(expected.len(), 2); assert_eq!(blobfs.list_blobs().unwrap(), expected); blobfs.stop().await.unwrap(); } #[fuchsia_async::run_singlethreaded(test)] async fn remount() { let blobfs = BlobfsRamdisk::builder().with_blob(&b"test"[..]).start().unwrap(); let blobs = blobfs.list_blobs().unwrap(); let blobfs = blobfs.into_builder().await.unwrap().start().unwrap(); assert_eq!(blobs, blobfs.list_blobs().unwrap()); blobfs.stop().await.unwrap(); } #[fuchsia_async::run_singlethreaded(test)] async fn blob_appears_in_readdir() { let blobfs = BlobfsRamdisk::start().unwrap(); let root = blobfs.root_dir().unwrap(); let hello_merkle = write_blob(&root, "Hello blobfs!".as_bytes()); assert_eq!(list_blobs(&root), vec![hello_merkle]); drop(root); blobfs.stop().await.unwrap(); } fn write_blob(dir: &openat::Dir, payload: &[u8]) -> String { let merkle = fuchsia_merkle::MerkleTree::from_reader(payload).unwrap().root().to_string(); let mut f = dir.new_file(&merkle, 0600).unwrap(); f.set_len(payload.len() as u64).unwrap(); f.write_all(payload).unwrap(); merkle } fn list_blobs(dir: &openat::Dir) -> Vec<String> { dir.list_dir(".") .unwrap() .map(|entry| entry.unwrap().file_name().to_owned().into_string().unwrap()) .collect() } }
#![deny(missing_docs)] use { anyhow::{format_err, Context as _, Error}, fdio::{SpawnAction, SpawnOptions}, fidl::endpoints::{ClientEnd, ServerEnd}, fidl_fuchsia_io::{ DirectoryAdminMarker, DirectoryAdminProxy, DirectoryMarker, DirectoryProxy, NodeProxy, }, fuchsia_component::server::ServiceFs, fuchsia_merkle::{Hash, MerkleTreeBuilder}, fuchsia_runtime::{HandleInfo, HandleType}, fuchsia_zircon::{self as zx, prelude::*}, futures::prelude::*, ramdevice_client::RamdiskClient, scoped_task::Scoped, std::{borrow::Cow, collections::BTreeSet, ffi::CString}, }; #[cfg(test)] mod test; #[derive(Debug, Clone)] pub struct BlobInfo { merkle: Hash, contents: Cow<'static, [u8]>, } impl<B> From<B> for BlobInfo where B: Into<Cow<'static, [u8]>>, { fn from(bytes: B) -> Self { let bytes = bytes.into(); let mut tree = MerkleTreeBuilder::new(); tree.write(&bytes); Self { merkle: tree.finish().root(), contents: bytes } } } pub struct BlobfsRamdiskBuilder { ramdisk: Option<Ramdisk>, blobs: Vec<BlobInfo>, } impl BlobfsRamdiskBuilder { fn new() -> Self { Self { ramdisk: None, blobs: vec![] } } pub fn ramdisk(mut self, ramdisk: Ramdisk) -> Self { self.ramdisk = Some(ramdisk); self } pub fn with_blob(mut self, blob: impl Into<BlobInfo>) -> Self { self.blobs.push(blob.into()); self } pub fn start(self) -> Result<BlobfsRamdisk, Error> { let ramdisk =
; let block_device_handle_id = HandleInfo::new(HandleType::User0, 1); let fs_root_handle_id = HandleInfo::new(HandleType::User0, 0); let block_handle = ramdisk.clone_channel().context("cloning ramdisk channel")?; let (proxy, blobfs_server_end) = fidl::endpoints::create_proxy::<DirectoryAdminMarker>()?; let process = scoped_task::spawn_etc( scoped_task::job_default(), SpawnOptions::CLONE_ALL, &CString::new("/pkg/bin/blobfs").unwrap(), &[&CString::new("blobfs").unwrap(), &CString::new("mount").unwrap()], None, &mut [ SpawnAction::add_handle(block_device_handle_id, block_handle.into()), SpawnAction::add_handle(fs_root_handle_id, blobfs_server_end.into()), ], ) .map_err(|(status, _)| status) .context("spawning 'blobfs mount'")?; let blobfs = BlobfsRamdisk { backing_ramdisk: ramdisk, process, proxy }; if !self.blobs.is_empty() { let mut present_blobs = blobfs.list_blobs()?; for blob in self.blobs { if present_blobs.contains(&blob.merkle) { continue; } blobfs .write_blob_sync(&blob.merkle, &blob.contents) .context(format!("writing {}", blob.merkle))?; present_blobs.insert(blob.merkle); } } Ok(blobfs) } } pub struct BlobfsRamdisk { backing_ramdisk: Ramdisk, process: Scoped<fuchsia_zircon::Process>, proxy: DirectoryAdminProxy, } impl BlobfsRamdisk { pub fn builder() -> BlobfsRamdiskBuilder { BlobfsRamdiskBuilder::new() } pub fn start() -> Result<Self, Error> { Self::builder().start() } pub fn root_dir_handle(&self) -> Result<ClientEnd<DirectoryMarker>, Error> { let (root_clone, server_end) = zx::Channel::create()?; self.proxy.clone(fidl_fuchsia_io::CLONE_FLAG_SAME_RIGHTS, server_end.into())?; Ok(root_clone.into()) } pub fn root_dir_proxy(&self) -> Result<DirectoryProxy, Error> { Ok(self.root_dir_handle()?.into_proxy()?) } pub fn root_dir(&self) -> Result<openat::Dir, Error> { fdio::create_fd(self.root_dir_handle()?.into()).context("failed to create fd") } pub async fn into_builder(self) -> Result<BlobfsRamdiskBuilder, Error> { let ramdisk = self.unmount().await?; Ok(Self::builder().ramdisk(ramdisk)) } pub async fn unmount(self) -> Result<Ramdisk, Error> { zx::Status::ok(self.proxy.unmount().await.context("sending blobfs unmount")?) .context("unmounting blobfs")?; self.process .wait_handle( zx::Signals::PROCESS_TERMINATED, zx::Time::after(zx::Duration::from_seconds(30)), ) .context("waiting for 'blobfs mount' to exit")?; let ret = self.process.info().context("getting 'blobfs mount' process info")?.return_code; if ret != 0 { return Err(format_err!("'blobfs mount' returned nonzero exit code {}", ret)); } Ok(self.backing_ramdisk) } pub async fn stop(self) -> Result<(), Error> { self.unmount().await?.stop() } pub fn list_blobs(&self) -> Result<BTreeSet<Hash>, Error> { self.root_dir()? .list_dir(".")? .map(|entry| { Ok(entry? .file_name() .to_str() .ok_or_else(|| anyhow::format_err!("expected valid utf-8"))? .parse()?) }) .collect() } pub fn add_blob_from( &self, merkle: &Hash, mut source: impl std::io::Read, ) -> Result<(), Error> { let mut bytes = vec![]; source.read_to_end(&mut bytes)?; self.write_blob_sync(merkle, &bytes) } fn write_blob_sync(&self, merkle: &Hash, bytes: &[u8]) -> Result<(), Error> { use std::{convert::TryInto, io::Write}; let mut file = self.root_dir().unwrap().write_file(merkle.to_string(), 0o777)?; file.set_len(bytes.len().try_into().unwrap())?; file.write_all(&bytes)?; Ok(()) } } pub struct Ramdisk { proxy: NodeProxy, client: RamdiskClient, } impl Ramdisk { pub fn start() -> Result<Self, Error> { let client = RamdiskClient::builder(512, 1 << 20).isolated_dev_root().build()?; let proxy = NodeProxy::new(fuchsia_async::Channel::from_channel(client.open()?)?); Ok(Ramdisk { proxy, client }) } fn clone_channel(&self) -> Result<zx::Channel, Error> { let (result, server_end) = zx::Channel::create()?; self.proxy.clone(fidl_fuchsia_io::CLONE_FLAG_SAME_RIGHTS, ServerEnd::new(server_end))?; Ok(result) } fn clone_handle(&self) -> Result<zx::Handle, Error> { Ok(self.clone_channel().context("cloning ramdisk channel")?.into()) } pub fn stop(self) -> Result<(), Error> { Ok(self.client.destroy()?) } pub async fn corrupt_blob(&self, merkle: &Hash) { let ramdisk = Clone::clone(&self.proxy); blobfs_corrupt_blob(ramdisk, merkle).await.unwrap(); } } async fn blobfs_corrupt_blob(ramdisk: NodeProxy, merkle: &Hash) -> Result<(), Error> { let mut fs = ServiceFs::new(); fs.root_dir().add_service_at("block", |chan| { ramdisk .clone( fidl_fuchsia_io::CLONE_FLAG_SAME_RIGHTS | fidl_fuchsia_io::OPEN_FLAG_DESCRIBE, ServerEnd::new(chan), ) .unwrap(); None }); let (devfs_client, devfs_server) = zx::Channel::create()?; fs.serve_connection(devfs_server)?; let serve_fs = fs.collect::<()>(); let spawn_and_wait = async move { let p = fdio::spawn_etc( &fuchsia_runtime::job_default(), SpawnOptions::CLONE_ALL - SpawnOptions::CLONE_NAMESPACE, &CString::new("/pkg/bin/blobfs-corrupt").unwrap(), &[ &CString::new("blobfs-corrupt").unwrap(), &CString::new("--device").unwrap(), &CString::new("/dev/block").unwrap(), &CString::new("--merkle").unwrap(), &CString::new(merkle.to_string()).unwrap(), ], None, &mut [SpawnAction::add_namespace_entry( &CString::new("/dev").unwrap(), devfs_client.into(), )], ) .map_err(|(status, _)| status) .context("spawning 'blobfs-corrupt'")?; wait_for_process_async(p).await.context("'blobfs-corrupt'")?; Ok(()) }; let ((), res) = futures::join!(serve_fs, spawn_and_wait); res } async fn wait_for_process_async(proc: fuchsia_zircon::Process) -> Result<(), Error> { let signals = fuchsia_async::OnSignals::new(&proc.as_handle_ref(), zx::Signals::PROCESS_TERMINATED) .await .context("waiting for tool to terminate")?; assert_eq!(signals, zx::Signals::PROCESS_TERMINATED); let ret = proc.info().context("getting tool process info")?.return_code; if ret != 0 { return Err(format_err!("tool returned nonzero exit code {}", ret)); } Ok(()) } fn mkblobfs_block(block_device: zx::Handle) -> Result<(), Error> { let block_device_handle_id = HandleInfo::new(HandleType::User0, 1); let p = fdio::spawn_etc( &fuchsia_runtime::job_default(), SpawnOptions::CLONE_ALL, &CString::new("/pkg/bin/blobfs").unwrap(), &[&CString::new("blobfs").unwrap(), &CString::new("mkfs").unwrap()], None, &mut [SpawnAction::add_handle(block_device_handle_id, block_device)], ) .map_err(|(status, _)| status) .context("spawning 'blobfs mkfs'")?; wait_for_process(p).context("'blobfs mkfs'")?; Ok(()) } fn wait_for_process(proc: fuchsia_zircon::Process) -> Result<(), Error> { proc.wait_handle( zx::Signals::PROCESS_TERMINATED, zx::Time::after(zx::Duration::from_seconds(30)), ) .context("waiting for tool to terminate")?; let ret = proc.info().context("getting tool process info")?.return_code; if ret != 0 { return Err(format_err!("tool returned nonzero exit code {}", ret)); } Ok(()) } fn mkblobfs(ramdisk: &Ramdisk) -> Result<(), Error> { mkblobfs_block(ramdisk.clone_handle()?) } #[cfg(test)] mod tests { use {super::*, maplit::btreeset, std::io::Write}; #[fuchsia_async::run_singlethreaded(test)] async fn clean_start_and_stop() { let blobfs = BlobfsRamdisk::start().unwrap(); let proxy = blobfs.root_dir_proxy().unwrap(); drop(proxy); blobfs.stop().await.unwrap(); } #[fuchsia_async::run_singlethreaded(test)] async fn clean_start_contains_no_blobs() { let blobfs = BlobfsRamdisk::start().unwrap(); assert_eq!(blobfs.list_blobs().unwrap(), btreeset![]); blobfs.stop().await.unwrap(); } #[test] fn blob_info_conversions() { let a = BlobInfo::from(&b"static slice"[..]); let b = BlobInfo::from(b"owned vec".to_vec()); let c = BlobInfo::from(Cow::from(&b"cow"[..])); assert_ne!(a.merkle, b.merkle); assert_ne!(b.merkle, c.merkle); assert_eq!( a.merkle, fuchsia_merkle::MerkleTree::from_reader(&b"static slice"[..]).unwrap().root() ); let _ = BlobfsRamdisk::builder() .with_blob(&b"static slice"[..]) .with_blob(b"owned vec".to_vec()) .with_blob(Cow::from(&b"cow"[..])); } #[fuchsia_async::run_singlethreaded(test)] async fn with_blob_ignores_duplicates() { let blob = BlobInfo::from(&b"duplicate"[..]); let blobfs = BlobfsRamdisk::builder() .with_blob(blob.clone()) .with_blob(blob.clone()) .start() .unwrap(); assert_eq!(blobfs.list_blobs().unwrap(), btreeset![blob.merkle.clone()]); let blobfs = blobfs.into_builder().await.unwrap().with_blob(blob.clone()).start().unwrap(); assert_eq!(blobfs.list_blobs().unwrap(), btreeset![blob.merkle.clone()]); } #[fuchsia_async::run_singlethreaded(test)] async fn build_with_two_blobs() { let blobfs = BlobfsRamdisk::builder() .with_blob(&b"blob 1"[..]) .with_blob(&b"blob 2"[..]) .start() .unwrap(); let expected = btreeset![ fuchsia_merkle::MerkleTree::from_reader(&b"blob 1"[..]).unwrap().root(), fuchsia_merkle::MerkleTree::from_reader(&b"blob 2"[..]).unwrap().root(), ]; assert_eq!(expected.len(), 2); assert_eq!(blobfs.list_blobs().unwrap(), expected); blobfs.stop().await.unwrap(); } #[fuchsia_async::run_singlethreaded(test)] async fn remount() { let blobfs = BlobfsRamdisk::builder().with_blob(&b"test"[..]).start().unwrap(); let blobs = blobfs.list_blobs().unwrap(); let blobfs = blobfs.into_builder().await.unwrap().start().unwrap(); assert_eq!(blobs, blobfs.list_blobs().unwrap()); blobfs.stop().await.unwrap(); } #[fuchsia_async::run_singlethreaded(test)] async fn blob_appears_in_readdir() { let blobfs = BlobfsRamdisk::start().unwrap(); let root = blobfs.root_dir().unwrap(); let hello_merkle = write_blob(&root, "Hello blobfs!".as_bytes()); assert_eq!(list_blobs(&root), vec![hello_merkle]); drop(root); blobfs.stop().await.unwrap(); } fn write_blob(dir: &openat::Dir, payload: &[u8]) -> String { let merkle = fuchsia_merkle::MerkleTree::from_reader(payload).unwrap().root().to_string(); let mut f = dir.new_file(&merkle, 0600).unwrap(); f.set_len(payload.len() as u64).unwrap(); f.write_all(payload).unwrap(); merkle } fn list_blobs(dir: &openat::Dir) -> Vec<String> { dir.list_dir(".") .unwrap() .map(|entry| entry.unwrap().file_name().to_owned().into_string().unwrap()) .collect() } }
match self.ramdisk { Some(ramdisk) => ramdisk, None => { let ramdisk = Ramdisk::start().context("creating backing ramdisk for blobfs")?; mkblobfs(&ramdisk)?; ramdisk } }
if_condition
[]
Rust
src/lib.rs
andreyk0/st7920
c7db218fddbc48d2054924be326cbbbefac1a1ea
#![no_std] use num_derive::ToPrimitive; use num_traits::ToPrimitive; use embedded_hal::blocking::delay::DelayUs; use embedded_hal::blocking::spi; use embedded_hal::digital::v2::OutputPin; #[derive(Debug)] pub enum Error<CommError, PinError> { Comm(CommError), Pin(PinError), } #[derive(ToPrimitive)] enum Instruction { BasicFunction = 0x30, ExtendedFunction = 0x34, ClearScreen = 0x01, EntryMode = 0x06, DisplayOnCursorOff = 0x0C, GraphicsOn = 0x36, SetGraphicsAddress = 0x80, } pub const WIDTH: u32 = 128; pub const HEIGHT: u32 = 64; const ROW_SIZE: usize = (WIDTH / 8) as usize; const BUFFER_SIZE: usize = ROW_SIZE * HEIGHT as usize; const X_ADDR_DIV: u8 = 16; pub struct ST7920<SPI, RST, CS> where SPI: spi::Write<u8>, RST: OutputPin, CS: OutputPin, { spi: SPI, rst: RST, cs: Option<CS>, buffer: [u8; BUFFER_SIZE], flip: bool, } impl<SPI, RST, CS, PinError, SPIError> ST7920<SPI, RST, CS> where SPI: spi::Write<u8, Error = SPIError>, RST: OutputPin<Error = PinError>, CS: OutputPin<Error = PinError>, { pub fn new(spi: SPI, rst: RST, cs: Option<CS>, flip: bool) -> Self { let buffer = [0; BUFFER_SIZE]; ST7920 { spi, rst, cs, buffer, flip, } } fn enable_cs(&mut self, delay: &mut dyn DelayUs<u32>) -> Result<(), Error<SPIError, PinError>> { if let Some(cs) = self.cs.as_mut() { cs.set_high().map_err(Error::Pin)?; delay.delay_us(1); } Ok(()) } fn disable_cs( &mut self, delay: &mut dyn DelayUs<u32>, ) -> Result<(), Error<SPIError, PinError>> { if let Some(cs) = self.cs.as_mut() { delay.delay_us(1); cs.set_high().map_err(Error::Pin)?; } Ok(()) } pub fn init(&mut self, delay: &mut dyn DelayUs<u32>) -> Result<(), Error<SPIError, PinError>> { self.enable_cs(delay)?; self.hard_reset(delay)?; self.write_command(Instruction::BasicFunction)?; delay.delay_us(200); self.write_command(Instruction::DisplayOnCursorOff)?; delay.delay_us(100); self.write_command(Instruction::ClearScreen)?; delay.delay_us(10 * 1000); self.write_command(Instruction::EntryMode)?; delay.delay_us(100); self.write_command(Instruction::ExtendedFunction)?; delay.delay_us(10 * 1000); self.write_command(Instruction::GraphicsOn)?; delay.delay_us(100 * 1000); self.disable_cs(delay)?; Ok(()) } fn hard_reset( &mut self, delay: &mut dyn DelayUs<u32>, ) -> Result<(), Error<SPIError, PinError>> { self.rst.set_low().map_err(Error::Pin)?; delay.delay_us(40 * 1000); self.rst.set_high().map_err(Error::Pin)?; delay.delay_us(40 * 1000); Ok(()) } fn write_command(&mut self, command: Instruction) -> Result<(), Error<SPIError, PinError>> { self.write_command_param(command, 0) } fn write_command_param( &mut self, command: Instruction, param: u8, ) -> Result<(), Error<SPIError, PinError>> { let command_param = command.to_u8().unwrap() | param; let cmd: u8 = 0xF8; self.spi .write(&[cmd, command_param & 0xF0, (command_param << 4) & 0xF0]) .map_err(Error::Comm)?; Ok(()) } fn write_data(&mut self, data: u8) -> Result<(), Error<SPIError, PinError>> { self.spi .write(&[0xFA, data & 0xF0, (data << 4) & 0xF0]) .map_err(Error::Comm)?; Ok(()) } fn set_address(&mut self, x: u8, y: u8) -> Result<(), Error<SPIError, PinError>> { const HALF_HEIGHT: u8 = HEIGHT as u8 / 2; self.write_command_param( Instruction::SetGraphicsAddress, if y < HALF_HEIGHT { y } else { y - HALF_HEIGHT }, )?; self.write_command_param( Instruction::SetGraphicsAddress, if y < HALF_HEIGHT { x / X_ADDR_DIV } else { x / X_ADDR_DIV + (WIDTH as u8 / X_ADDR_DIV) }, )?; Ok(()) } pub fn clear(&mut self, delay: &mut dyn DelayUs<u32>) -> Result<(), Error<SPIError, PinError>> { self.enable_cs(delay)?; for y in 0..HEIGHT as u8 / 2 { self.set_address(0, y)?; for _x in 0..ROW_SIZE { self.write_data(0)?; self.write_data(0)?; } } self.disable_cs(delay)?; Ok(()) } pub fn set_pixel(&mut self, mut x: u8, mut y: u8, val: u8) { if self.flip { y = (HEIGHT - 1) as u8 - y; x = (WIDTH - 1) as u8 - x; } let x_mask = 0x80 >> (x % 8); if val != 0 { self.buffer[y as usize * ROW_SIZE + x as usize / 8] |= x_mask; } else { self.buffer[y as usize * ROW_SIZE + x as usize / 8] &= !x_mask; } } pub fn flush(&mut self, delay: &mut dyn DelayUs<u32>) -> Result<(), Error<SPIError, PinError>> { self.enable_cs(delay)?; for y in 0..HEIGHT as u8 / 2 { self.set_address(0, y)?; let mut row_start = y as usize * ROW_SIZE; for x in 0..ROW_SIZE { self.write_data(self.buffer[row_start + x])?; } row_start += (HEIGHT as usize / 2) * ROW_SIZE; for x in 0..ROW_SIZE { self.write_data(self.buffer[row_start + x])?; } } self.disable_cs(delay)?; Ok(()) } pub fn flush_region( &mut self, x: u8, mut y: u8, w: u8, h: u8, delay: &mut dyn DelayUs<u32>, ) -> Result<(), Error<SPIError, PinError>> { self.enable_cs(delay)?; let mut adj_x = x; if self.flip { y = HEIGHT as u8 - (y + h); adj_x = WIDTH as u8 - (x + w); } let left = (adj_x / X_ADDR_DIV) * X_ADDR_DIV; let mut right = ((adj_x + w) / X_ADDR_DIV) * X_ADDR_DIV; if right < adj_x + w { right += X_ADDR_DIV; } let mut row_start = y as usize * ROW_SIZE; for y in y..y + h { self.set_address(adj_x, y)?; for x in left / 8..right / 8 { self.write_data(self.buffer[row_start + x as usize])?; } row_start += ROW_SIZE; } self.disable_cs(delay)?; Ok(()) } } #[cfg(feature = "graphics")] use embedded_graphics; #[cfg(feature = "graphics")] use self::embedded_graphics::{ geometry::Point, drawable::Pixel, pixelcolor::BinaryColor, prelude::*, DrawTarget, }; #[cfg(feature = "graphics")] impl<SPI, CS, RST, PinError, SPIError> DrawTarget<BinaryColor> for ST7920<SPI, CS, RST> where SPI: spi::Write<u8, Error = SPIError>, RST: OutputPin<Error = PinError>, CS: OutputPin<Error = PinError>, { type Error = core::convert::Infallible; fn draw_pixel(&mut self, pixel: Pixel<BinaryColor>) -> Result<(), Self::Error> { let Pixel(coord, color) = pixel; let x = coord.x as u8; let y = coord.y as u8; let c = match color { BinaryColor::Off => 0 , BinaryColor::On => 1 }; self.set_pixel(x, y, c); Ok(()) } fn size(&self) -> Size { if self.flip { Size::new(HEIGHT, WIDTH) } else { Size::new(WIDTH, HEIGHT) } } } impl<SPI, RST, CS, PinError, SPIError> ST7920<SPI, RST, CS> where SPI: spi::Write<u8, Error = SPIError>, RST: OutputPin<Error = PinError>, CS: OutputPin<Error = PinError>, { pub fn flush_region_graphics( &mut self, region: (Point, Size), delay: &mut dyn DelayUs<u32>, ) -> Result<(), Error<SPIError, PinError>> { self.flush_region( region.0.x as u8, region.0.y as u8, region.1.width as u8, region.1.height as u8, delay, ) } }
#![no_std] use num_derive::ToPrimitive; use num_traits::ToPrimitive; use embedded_hal::blocking::delay::DelayUs; use embedded_hal::blocking::spi; use embedded_hal::digital::v2::OutputPin; #[derive(Debug)] pub enum Error<CommError, PinError> { Comm(CommError), Pin(PinError), } #[derive(ToPrimitive)] enum Instruction { BasicFunction = 0x30, ExtendedFunction = 0x34, ClearScreen = 0x01, EntryMode = 0x06, DisplayOnCursorOff = 0x0C, GraphicsOn = 0x36, SetGraphicsAddress = 0x80, } pub const WIDTH: u32 = 128; pub const HEIGHT: u32 = 64; const ROW_SIZE: usize = (WIDTH / 8) as usize; const BUFFER_SIZE: usize = ROW_SIZE * HEIGHT as usize; const X_ADDR_DIV: u8 = 16; pub struct ST7920<SPI, RST, CS> where SPI: spi::Write<u8>, RST: OutputPin, CS: OutputPin, { spi: SPI, rst: RST, cs: Option<CS>, buffer: [u8; BUFFER_SIZE], flip: bool, } impl<SPI, RST, CS, PinError, SPIError> ST7920<SPI, RST, CS> where SPI: spi::Write<u8, Error = SPIError>, RST: OutputPin<Error = PinError>, CS: OutputPin<Error = PinError>, { pub fn new(spi: SPI, rst: RST, cs: Option<CS>, flip: bool) -> Self { let buffer = [0; BUFFER_SIZE]; ST7920 { spi, rst, cs, buffer, flip, } } fn enable_cs(&mut self, delay: &mut dyn DelayUs<u32>) -> Result<(), Error<SPIError, PinError>> { if let Some(cs) = self.cs.as_mut() { cs.set_high().map_err(Error::Pin)?; delay.delay_us(1); } Ok(()) } fn disable_cs( &mut self, delay: &mut dyn DelayUs<u32>, ) -> Result<(), Error<SPIError, PinError>> { if let Some(cs) = self.cs.as_mut() { delay.delay_us(1); cs.set_high().map_err(Error::Pin)?; } Ok(()) } pub fn init(&mut self, delay: &mut d
t_high().map_err(Error::Pin)?; delay.delay_us(40 * 1000); Ok(()) } fn write_command(&mut self, command: Instruction) -> Result<(), Error<SPIError, PinError>> { self.write_command_param(command, 0) } fn write_command_param( &mut self, command: Instruction, param: u8, ) -> Result<(), Error<SPIError, PinError>> { let command_param = command.to_u8().unwrap() | param; let cmd: u8 = 0xF8; self.spi .write(&[cmd, command_param & 0xF0, (command_param << 4) & 0xF0]) .map_err(Error::Comm)?; Ok(()) } fn write_data(&mut self, data: u8) -> Result<(), Error<SPIError, PinError>> { self.spi .write(&[0xFA, data & 0xF0, (data << 4) & 0xF0]) .map_err(Error::Comm)?; Ok(()) } fn set_address(&mut self, x: u8, y: u8) -> Result<(), Error<SPIError, PinError>> { const HALF_HEIGHT: u8 = HEIGHT as u8 / 2; self.write_command_param( Instruction::SetGraphicsAddress, if y < HALF_HEIGHT { y } else { y - HALF_HEIGHT }, )?; self.write_command_param( Instruction::SetGraphicsAddress, if y < HALF_HEIGHT { x / X_ADDR_DIV } else { x / X_ADDR_DIV + (WIDTH as u8 / X_ADDR_DIV) }, )?; Ok(()) } pub fn clear(&mut self, delay: &mut dyn DelayUs<u32>) -> Result<(), Error<SPIError, PinError>> { self.enable_cs(delay)?; for y in 0..HEIGHT as u8 / 2 { self.set_address(0, y)?; for _x in 0..ROW_SIZE { self.write_data(0)?; self.write_data(0)?; } } self.disable_cs(delay)?; Ok(()) } pub fn set_pixel(&mut self, mut x: u8, mut y: u8, val: u8) { if self.flip { y = (HEIGHT - 1) as u8 - y; x = (WIDTH - 1) as u8 - x; } let x_mask = 0x80 >> (x % 8); if val != 0 { self.buffer[y as usize * ROW_SIZE + x as usize / 8] |= x_mask; } else { self.buffer[y as usize * ROW_SIZE + x as usize / 8] &= !x_mask; } } pub fn flush(&mut self, delay: &mut dyn DelayUs<u32>) -> Result<(), Error<SPIError, PinError>> { self.enable_cs(delay)?; for y in 0..HEIGHT as u8 / 2 { self.set_address(0, y)?; let mut row_start = y as usize * ROW_SIZE; for x in 0..ROW_SIZE { self.write_data(self.buffer[row_start + x])?; } row_start += (HEIGHT as usize / 2) * ROW_SIZE; for x in 0..ROW_SIZE { self.write_data(self.buffer[row_start + x])?; } } self.disable_cs(delay)?; Ok(()) } pub fn flush_region( &mut self, x: u8, mut y: u8, w: u8, h: u8, delay: &mut dyn DelayUs<u32>, ) -> Result<(), Error<SPIError, PinError>> { self.enable_cs(delay)?; let mut adj_x = x; if self.flip { y = HEIGHT as u8 - (y + h); adj_x = WIDTH as u8 - (x + w); } let left = (adj_x / X_ADDR_DIV) * X_ADDR_DIV; let mut right = ((adj_x + w) / X_ADDR_DIV) * X_ADDR_DIV; if right < adj_x + w { right += X_ADDR_DIV; } let mut row_start = y as usize * ROW_SIZE; for y in y..y + h { self.set_address(adj_x, y)?; for x in left / 8..right / 8 { self.write_data(self.buffer[row_start + x as usize])?; } row_start += ROW_SIZE; } self.disable_cs(delay)?; Ok(()) } } #[cfg(feature = "graphics")] use embedded_graphics; #[cfg(feature = "graphics")] use self::embedded_graphics::{ geometry::Point, drawable::Pixel, pixelcolor::BinaryColor, prelude::*, DrawTarget, }; #[cfg(feature = "graphics")] impl<SPI, CS, RST, PinError, SPIError> DrawTarget<BinaryColor> for ST7920<SPI, CS, RST> where SPI: spi::Write<u8, Error = SPIError>, RST: OutputPin<Error = PinError>, CS: OutputPin<Error = PinError>, { type Error = core::convert::Infallible; fn draw_pixel(&mut self, pixel: Pixel<BinaryColor>) -> Result<(), Self::Error> { let Pixel(coord, color) = pixel; let x = coord.x as u8; let y = coord.y as u8; let c = match color { BinaryColor::Off => 0 , BinaryColor::On => 1 }; self.set_pixel(x, y, c); Ok(()) } fn size(&self) -> Size { if self.flip { Size::new(HEIGHT, WIDTH) } else { Size::new(WIDTH, HEIGHT) } } } impl<SPI, RST, CS, PinError, SPIError> ST7920<SPI, RST, CS> where SPI: spi::Write<u8, Error = SPIError>, RST: OutputPin<Error = PinError>, CS: OutputPin<Error = PinError>, { pub fn flush_region_graphics( &mut self, region: (Point, Size), delay: &mut dyn DelayUs<u32>, ) -> Result<(), Error<SPIError, PinError>> { self.flush_region( region.0.x as u8, region.0.y as u8, region.1.width as u8, region.1.height as u8, delay, ) } }
yn DelayUs<u32>) -> Result<(), Error<SPIError, PinError>> { self.enable_cs(delay)?; self.hard_reset(delay)?; self.write_command(Instruction::BasicFunction)?; delay.delay_us(200); self.write_command(Instruction::DisplayOnCursorOff)?; delay.delay_us(100); self.write_command(Instruction::ClearScreen)?; delay.delay_us(10 * 1000); self.write_command(Instruction::EntryMode)?; delay.delay_us(100); self.write_command(Instruction::ExtendedFunction)?; delay.delay_us(10 * 1000); self.write_command(Instruction::GraphicsOn)?; delay.delay_us(100 * 1000); self.disable_cs(delay)?; Ok(()) } fn hard_reset( &mut self, delay: &mut dyn DelayUs<u32>, ) -> Result<(), Error<SPIError, PinError>> { self.rst.set_low().map_err(Error::Pin)?; delay.delay_us(40 * 1000); self.rst.se
random
[ { "content": "fn main() {\n\n // Put the linker script somewhere the linker can find it\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"memory.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"memory.x\"))\n\n .unwrap();\n\n println...
Rust
src/connectivity/network/testing/netemul/runner/helpers/netstack_cfg/src/main.rs
EnderNightLord-ChromeBook/fuchsia-pine64-pinephone
05e2c059b57b6217089090a0315971d1735ecf57
use { anyhow::{format_err, Context as _, Error}, fidl_fuchsia_net, fidl_fuchsia_net_stack::StackMarker, fidl_fuchsia_net_stack_ext::FidlReturn, fidl_fuchsia_netemul_network::{EndpointManagerMarker, NetworkContextMarker}, fidl_fuchsia_netstack::{InterfaceConfig, NetstackMarker}, fuchsia_async as fasync, fuchsia_component::client, structopt::StructOpt, }; #[derive(StructOpt, Debug)] #[structopt(name = "netstack_cfg")] struct Opt { #[structopt(long, short = "e")] endpoint: String, #[structopt(long, short = "i")] ip: Option<String>, #[structopt(long, short = "g")] gateway: Option<String>, #[structopt(long = "skip-up-check")] skip_up_check: bool, } const DEFAULT_METRIC: u32 = 100; async fn config_netstack(opt: Opt) -> Result<(), Error> { log::info!("Configuring endpoint {}", opt.endpoint); let netctx = client::connect_to_service::<NetworkContextMarker>()?; let (epm, epmch) = fidl::endpoints::create_proxy::<EndpointManagerMarker>()?; netctx.get_endpoint_manager(epmch)?; let ep = epm.get_endpoint(&opt.endpoint).await?; let ep = ep.ok_or_else(|| format_err!("can't find endpoint {}", opt.endpoint))?.into_proxy()?; log::info!("Got endpoint."); let device_connection = ep.get_device().await?; log::info!("Got device connection."); let netstack = client::connect_to_service::<NetstackMarker>()?; let mut cfg = InterfaceConfig { name: opt.endpoint.clone(), filepath: format!("/vdev/{}", opt.endpoint), metric: DEFAULT_METRIC, }; let nicid = match device_connection { fidl_fuchsia_netemul_network::DeviceConnection::Ethernet(e) => netstack .add_ethernet_device(&format!("/vdev/{}", opt.endpoint), &mut cfg, e) .await .with_context(|| format!("add_ethernet_device FIDL error ({:?})", cfg))? .map_err(fuchsia_zircon::Status::from_raw) .with_context(|| format!("add_ethernet_device error ({:?})", cfg))?, fidl_fuchsia_netemul_network::DeviceConnection::NetworkDevice(device) => todo!( "(48860) Support NetworkDevice configuration. Got unexpected NetworkDevice {:?}", device ), }; let () = netstack.set_interface_status(nicid as u32, true)?; log::info!("Added ethernet to stack."); let subnet: Option<fidl_fuchsia_net::Subnet> = opt.ip.as_ref().map(|ip| { ip.parse::<fidl_fuchsia_net_ext::Subnet>().expect("Can't parse provided ip").into() }); if let Some(mut subnet) = subnet { let _ = netstack .set_interface_address(nicid as u32, &mut subnet.addr, subnet.prefix_len) .await .context("set interface address error")?; } else { let (dhcp_client, server_end) = fidl::endpoints::create_proxy::<fidl_fuchsia_net_dhcp::ClientMarker>() .context("failed to create fidl endpoints")?; netstack .get_dhcp_client(nicid, server_end) .await .context("failed to call get_dhcp_client")? .map_err(fuchsia_zircon::Status::from_raw) .context("failed to get dhcp client")?; dhcp_client .start() .await .context("failed to call dhcp_client.start")? .map_err(fuchsia_zircon::Status::from_raw) .context("failed to start dhcp client")?; }; log::info!("Configured nic address."); if let Some(gateway) = &opt.gateway { let gw_addr: fidl_fuchsia_net::IpAddress = fidl_fuchsia_net_ext::IpAddress( gateway.parse::<std::net::IpAddr>().context("failed to parse gateway address")?, ) .into(); let unspec_addr: fidl_fuchsia_net::IpAddress = match gw_addr { fidl_fuchsia_net::IpAddress::Ipv4(..) => fidl_fuchsia_net_ext::IpAddress( std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), ), fidl_fuchsia_net::IpAddress::Ipv6(..) => fidl_fuchsia_net_ext::IpAddress( std::net::IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED), ), } .into(); let stack = client::connect_to_service::<StackMarker>()?; let () = stack .add_forwarding_entry(&mut fidl_fuchsia_net_stack::ForwardingEntry { subnet: fidl_fuchsia_net::Subnet { addr: unspec_addr, prefix_len: 0 }, destination: fidl_fuchsia_net_stack::ForwardingDestination::NextHop(gw_addr), }) .await .squash_result() .context("failed to add forwarding entry for gateway")?; log::info!("Configured the default route with gateway address."); } log::info!("Waiting for interface up..."); let interface_state = client::connect_to_service::<fidl_fuchsia_net_interfaces::StateMarker>()?; let () = fidl_fuchsia_net_interfaces_ext::wait_interface_with_id( fidl_fuchsia_net_interfaces_ext::event_stream_from_state(&interface_state)?, &mut fidl_fuchsia_net_interfaces_ext::InterfaceState::Unknown(nicid.into()), |properties| { if !opt.skip_up_check && !properties.online.unwrap_or(false) { log::info!("Found interface, but it's down. waiting."); return None; } if subnet.is_some() { if properties .addresses .as_ref() .map_or(false, |addresses| addresses.iter().any(|a| a.addr == subnet)) { Some(()) } else { log::info!("Found interface, but address not yet present. waiting."); None } } else { Some(()) } }, ) .await .context("wait for interface")?; log::info!("Found ethernet with id {}", nicid); Ok(()) } fn main() -> Result<(), Error> { let () = fuchsia_syslog::init().context("cannot init logger")?; let opt = Opt::from_args(); let mut executor = fasync::Executor::new().context("Error creating executor")?; executor.run_singlethreaded(config_netstack(opt)) }
use { anyhow::{format_err, Context as _, Error}, fidl_fuchsia_net, fidl_fuchsia_net_stack::StackMarker, fidl_fuchsia_net_stack_ext::FidlReturn, fidl_fuchsia_netemul_network::{EndpointManagerMarker, NetworkContextMarker}, fidl_fuchsia_netstack::{InterfaceConfig, NetstackMarker}, fuchsia_async as fasync, fuchsia_component::client, structopt::StructOpt, }; #[derive(StructOpt, Debug)] #[structopt(name = "netstack_cfg")] struct Opt { #[structopt(long, short = "e")] endpoint: String, #[structopt(long, short = "i")] ip: Option<String>, #[structopt(long, short = "g")] gateway: Option<String>, #[structopt(long = "skip-up-check")] skip_up_check: bool, } const DEFAULT_METRIC: u32 = 100; async fn config_netstack(opt: Opt) -> Result<(), Error> { log::info!("Configuring endpoint {}", opt.endpoint); let netctx = client::connect_to_service::<NetworkContextMarker>()?; let (epm, epmch) = fidl::endpoints::create_proxy::<EndpointManagerMarker>()?; netctx.get_endpoint_manager(epmch)?; let ep = epm.get_endpoint(&opt.endpoint).await?; let ep = ep.ok_or_else(|| format_err!("can't find endpoint {}", opt.endpoint))?.into_proxy()?; log::info!("Got endpoint."); let device_connection = ep.get_device().await?; log::info!("Got device connection."); let netstack = client::connect_to_service::<NetstackMarker>()?; let mut cfg = InterfaceConfig { name: opt.endpoint.clone(), filepath: format!("/vdev/{}", opt.endpoint), metric: DEFAULT_METRIC, }; let nicid = match device_connection { fidl_fuchsia_netemul_network::DeviceConnection::Ethernet(e) => netstack .add_ethernet_device(&format!("/vdev/{}", opt.endpoint), &mut cfg, e) .await .with_context(|| format!("add_ethernet_device FIDL error ({:?})", cfg))? .map_err(fuchsia_zircon::Status::from_raw) .with_context(|| format!("add_ethernet_device error ({:?})", cfg))?, fidl_fuchsia_netemul_network::DeviceConnection::NetworkDevice(device) => todo!( "(48860) Support NetworkDevice configuration. Got unexpected NetworkDevice {:?}", device ), }; let () = netstack.set_interface_status(nicid as u32, true)?; log::info!("Added ethernet to stack."); let subnet: Option<fidl_fuchsia_net::Subnet> = opt.ip.as_ref().map(|ip| { ip.parse::<fidl_fuchsia_net_ext::Subnet>().expect("Can't parse provided ip").into() }); if let Some(mut subnet) = subnet { let _ = netstack .set_interface_address(nicid as u32, &mut subnet.addr, subnet.prefix_len) .await .context("set interface address error")?; } else { let (dhcp_client, server_end) = fidl::endpoints::create_proxy::<fidl_fuchsia_net_dhcp::ClientMarker>() .context("failed to create fidl endpoints")?; netstack .get_dhcp_client(nicid, server_end) .await .context("failed to call get_dhcp_client")? .map_err(fuchsia_zircon::Status::from_raw) .context("failed to get dhcp client")?; dhcp_client .start() .await .context("failed to call dhcp_client.start")? .map_err(fuchsia_zircon::Status::from_raw) .context("failed to start dhcp client")?; }; log::info!("Configured nic address."); if let Some(gateway) = &opt.gateway { let gw_addr: fidl_fuchsia_net::IpAddress = fidl_fuchsia_net_ext::IpAddress( gateway.parse::<std::net::IpAddr>().context("failed to parse gateway address")?, ) .into(); let unspec_addr: fidl_fuchsia_net::IpAddress = match gw_addr { fidl_fuchsia_net::IpAddress::Ipv4(..)
_net_interfaces_ext::wait_interface_with_id( fidl_fuchsia_net_interfaces_ext::event_stream_from_state(&interface_state)?, &mut fidl_fuchsia_net_interfaces_ext::InterfaceState::Unknown(nicid.into()), |properties| { if !opt.skip_up_check && !properties.online.unwrap_or(false) { log::info!("Found interface, but it's down. waiting."); return None; } if subnet.is_some() { if properties .addresses .as_ref() .map_or(false, |addresses| addresses.iter().any(|a| a.addr == subnet)) { Some(()) } else { log::info!("Found interface, but address not yet present. waiting."); None } } else { Some(()) } }, ) .await .context("wait for interface")?; log::info!("Found ethernet with id {}", nicid); Ok(()) } fn main() -> Result<(), Error> { let () = fuchsia_syslog::init().context("cannot init logger")?; let opt = Opt::from_args(); let mut executor = fasync::Executor::new().context("Error creating executor")?; executor.run_singlethreaded(config_netstack(opt)) }
=> fidl_fuchsia_net_ext::IpAddress( std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), ), fidl_fuchsia_net::IpAddress::Ipv6(..) => fidl_fuchsia_net_ext::IpAddress( std::net::IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED), ), } .into(); let stack = client::connect_to_service::<StackMarker>()?; let () = stack .add_forwarding_entry(&mut fidl_fuchsia_net_stack::ForwardingEntry { subnet: fidl_fuchsia_net::Subnet { addr: unspec_addr, prefix_len: 0 }, destination: fidl_fuchsia_net_stack::ForwardingDestination::NextHop(gw_addr), }) .await .squash_result() .context("failed to add forwarding entry for gateway")?; log::info!("Configured the default route with gateway address."); } log::info!("Waiting for interface up..."); let interface_state = client::connect_to_service::<fidl_fuchsia_net_interfaces::StateMarker>()?; let () = fidl_fuchsia
random
[]
Rust
game/src/sandbox/minimap.rs
balbok0/abstreet
3af15fefdb2772c83864c08724318418da8190a9
use abstutil::prettyprint_usize; use map_gui::tools::{MinimapControls, Navigator}; use widgetry::{ ControlState, EventCtx, GfxCtx, HorizontalAlignment, Image, Key, Line, Panel, ScreenDims, Text, VerticalAlignment, Widget, }; use crate::app::App; use crate::app::Transition; use crate::common::Warping; use crate::layer::PickLayer; use crate::sandbox::dashboards::TripTable; pub struct MinimapController; impl MinimapControls<App> for MinimapController { fn has_zorder(&self, app: &App) -> bool { app.opts.dev } fn has_layer(&self, app: &App) -> bool { app.primary.layer.is_some() } fn draw_extra(&self, g: &mut GfxCtx, app: &App) { if let Some(ref l) = app.primary.layer { l.draw_minimap(g); } let mut cache = app.primary.agents.borrow_mut(); cache.draw_unzoomed_agents(g, app); } fn make_unzoomed_panel(&self, ctx: &mut EventCtx, app: &App) -> Panel { let unzoomed_agents = &app.primary.agents.borrow().unzoomed_agents; let is_enabled = [ unzoomed_agents.cars(), unzoomed_agents.bikes(), unzoomed_agents.buses_and_trains(), unzoomed_agents.peds(), ]; Panel::new(Widget::row(vec![ make_tool_panel(ctx, app).align_right(), Widget::col(make_agent_toggles(ctx, app, is_enabled)) .bg(app.cs.panel_bg) .padding(16), ])) .aligned( HorizontalAlignment::Right, VerticalAlignment::BottomAboveOSD, ) .build_custom(ctx) } fn make_legend(&self, ctx: &mut EventCtx, app: &App) -> Widget { let unzoomed_agents = &app.primary.agents.borrow().unzoomed_agents; let is_enabled = [ unzoomed_agents.cars(), unzoomed_agents.bikes(), unzoomed_agents.buses_and_trains(), unzoomed_agents.peds(), ]; Widget::custom_row(make_agent_toggles(ctx, app, is_enabled)) .margin_left(26) } fn make_zoomed_side_panel(&self, ctx: &mut EventCtx, app: &App) -> Widget { make_tool_panel(ctx, app) } fn panel_clicked(&self, ctx: &mut EventCtx, app: &mut App, action: &str) -> Option<Transition> { match action { "search" => { return Some(Transition::Push(Navigator::new(ctx, app))); } "zoom out fully" => { return Some(Transition::Push(Warping::new( ctx, app.primary.map.get_bounds().get_rectangle().center(), Some(ctx.canvas.min_zoom()), None, &mut app.primary, ))); } "zoom in fully" => { return Some(Transition::Push(Warping::new( ctx, ctx.canvas.center_to_map_pt(), Some(10.0), None, &mut app.primary, ))); } "change layers" => { return Some(Transition::Push(PickLayer::pick(ctx, app))); } "more data" => { return Some(Transition::Push(Box::new(TripTable::new(ctx, app)))); } _ => unreachable!(), } } fn panel_changed(&self, _: &mut EventCtx, app: &mut App, panel: &Panel) { if panel.has_widget("Car") { app.primary .agents .borrow_mut() .unzoomed_agents .update(panel); } } } fn make_agent_toggles(ctx: &mut EventCtx, app: &App, is_enabled: [bool; 4]) -> Vec<Widget> { use widgetry::{include_labeled_bytes, Color, GeomBatchStack, RewriteColor, Toggle}; let [is_car_enabled, is_bike_enabled, is_bus_enabled, is_pedestrian_enabled] = is_enabled; pub fn colored_checkbox( ctx: &EventCtx, action: &str, is_enabled: bool, color: Color, icon: &str, label: &str, tooltip: Text, ) -> Widget { let buttons = ctx .style() .btn_plain .btn() .label_text(label) .padding(4.0) .tooltip(tooltip) .image_color(RewriteColor::NoOp, ControlState::Default); let icon_batch = Image::from_path(icon) .build_batch(ctx) .expect("invalid svg") .0; let false_btn = { let checkbox = Image::from_bytes(include_labeled_bytes!( "../../../widgetry/icons/checkbox_no_border_unchecked.svg" )) .color(RewriteColor::Change(Color::BLACK, color.alpha(0.3))); let mut row = GeomBatchStack::horizontal(vec![ checkbox.build_batch(ctx).expect("invalid svg").0, icon_batch.clone(), ]); row.spacing(8.0); let row_batch = row.batch(); let bounds = row_batch.get_bounds(); buttons.clone().image_batch(row_batch, bounds) }; let true_btn = { let checkbox = Image::from_bytes(include_labeled_bytes!( "../../../widgetry/icons/checkbox_no_border_checked.svg" )) .color(RewriteColor::Change(Color::BLACK, color)); let mut row = GeomBatchStack::horizontal(vec![ checkbox.build_batch(ctx).expect("invalid svg").0, icon_batch, ]); row.spacing(8.0); let row_batch = row.batch(); let bounds = row_batch.get_bounds(); buttons.image_batch(row_batch, bounds) }; Toggle::new( is_enabled, false_btn.build(ctx, action), true_btn.build(ctx, action), ) .named(action) .container() .force_width(137.0) } let counts = app.primary.sim.num_commuters_vehicles(); let pedestrian_details = { let tooltip = Text::from_multiline(vec![ Line("Pedestrians"), Line(format!( "Walking commuters: {}", prettyprint_usize(counts.walking_commuters) )) .secondary(), Line(format!( "To/from public transit: {}", prettyprint_usize(counts.walking_to_from_transit) )) .secondary(), Line(format!( "To/from a car: {}", prettyprint_usize(counts.walking_to_from_car) )) .secondary(), Line(format!( "To/from a bike: {}", prettyprint_usize(counts.walking_to_from_bike) )) .secondary(), ]); let count = prettyprint_usize( counts.walking_commuters + counts.walking_to_from_transit + counts.walking_to_from_car + counts.walking_to_from_bike, ); colored_checkbox( ctx, "Walk", is_pedestrian_enabled, app.cs.unzoomed_pedestrian, "system/assets/meters/pedestrian.svg", &count, tooltip, ) }; let bike_details = { let tooltip = Text::from_multiline(vec![ Line("Cyclists"), Line(prettyprint_usize(counts.cyclists)).secondary(), ]); colored_checkbox( ctx, "Bike", is_bike_enabled, app.cs.unzoomed_bike, "system/assets/meters/bike.svg", &prettyprint_usize(counts.cyclists), tooltip, ) }; let car_details = { let tooltip = Text::from_multiline(vec![ Line("Cars"), Line(format!( "Single-occupancy vehicles: {}", prettyprint_usize(counts.sov_drivers) )) .secondary(), ]); colored_checkbox( ctx, "Car", is_car_enabled, app.cs.unzoomed_car, "system/assets/meters/car.svg", &prettyprint_usize(counts.sov_drivers), tooltip, ) }; let bus_details = { let tooltip = Text::from_multiline(vec![ Line("Public transit"), Line(format!( "{} passengers on {} buses", prettyprint_usize(counts.bus_riders), prettyprint_usize(counts.buses) )) .secondary(), Line(format!( "{} passengers on {} trains", prettyprint_usize(counts.train_riders), prettyprint_usize(counts.trains) )) .secondary(), ]); colored_checkbox( ctx, "Bus", is_bus_enabled, app.cs.unzoomed_bus, "system/assets/meters/bus.svg", &prettyprint_usize(counts.bus_riders + counts.train_riders), tooltip, ) }; vec![car_details, bike_details, bus_details, pedestrian_details] } fn make_tool_panel(ctx: &mut EventCtx, app: &App) -> Widget { let buttons = ctx .style() .btn_floating .btn() .image_dims(ScreenDims::square(20.0)) .bg_color(app.cs.inner_panel_bg, ControlState::Default) .padding(8); Widget::col(vec![ (if ctx.canvas.cam_zoom >= app.opts.min_zoom_for_detail { buttons .clone() .image_path("system/assets/minimap/zoom_out_fully.svg") .build_widget(ctx, "zoom out fully") } else { buttons .clone() .image_path("system/assets/minimap/zoom_in_fully.svg") .build_widget(ctx, "zoom in fully") }), buttons .clone() .image_path("system/assets/tools/layers.svg") .hotkey(Key::L) .build_widget(ctx, "change layers"), buttons .clone() .image_path("system/assets/tools/search.svg") .hotkey(Key::K) .build_widget(ctx, "search"), buttons .image_path("system/assets/meters/trip_histogram.svg") .hotkey(Key::Q) .build_widget(ctx, "more data"), ]) }
use abstutil::prettyprint_usize; use map_gui::tools::{MinimapControls, Navigator}; use widgetry::{ ControlState, EventCtx, GfxCtx, HorizontalAlignment, Image, Key, Line, Panel, ScreenDims, Text, VerticalAlignment, Widget, }; use crate::app::App; use crate::app::Transition; use crate::common::Warping; use crate::layer::PickLayer; use crate::sandbox::dashboards::TripTable; pub struct MinimapController; impl MinimapControls<App> for MinimapController { fn has_zorder(&self, app: &App) -> bool { app.opts.dev } fn has_layer(&self, app: &App) -> bool { app.primary.layer.is_some() } fn draw_extra(&self, g: &mut GfxCtx, app: &App) { if let Some(ref l) = app.primary.layer { l.draw_minimap(g); } let mut cache = app.primary.agents.borrow_mut(); cache.draw_unzoomed_agents(g, app); } fn make_unzoomed_panel(&self, ctx: &mut EventCtx, app: &App) -> Panel { let unzoomed_agents = &app.primary.agents.borrow().unzoomed_agents; let is_enabled = [ unzoomed_agents.cars(), unzoomed_agents.bikes(), unzoomed_agents.buses_and_trains(), unzoomed_agents.peds(), ]; Panel::new(Widget::row(vec![ make_tool_panel(ctx, app).align_right(), Widget::col(make_agent_toggles(ctx, app, is_enabled)) .bg(app.cs.panel_bg) .padding(16), ])) .aligned( HorizontalAlignment::Right, VerticalAlignment::BottomAboveOSD, ) .build_custom(ctx) } fn make_legend(&self, ctx: &mut EventCtx, app: &App) -> Widget { let unzoomed_agents = &app.primary.agents.borrow().unzoomed_agents; let is_enabled = [ unzoomed_agents.cars(), unzoomed_agents.bikes(), unzoomed_agents.buses_and_trains(), unzoomed_agents.peds(), ]; Widget::custom_row(make_agent_toggles(ctx, app, is_enabled)) .margin_left(26) } fn make_zoomed_side_panel(&self, ctx: &mut EventCtx, app: &App) -> Widget { make_tool_panel(ctx, app) } fn panel_clicked(&self, ctx: &mut EventCtx, app: &mut App, action: &str) -> Option<Transition> { match action { "search" => { return Some(Transition::Push(Navigator::new(ctx, app))); } "zoom out fully" => { return Some(Transition::Push(Warping::new( ctx, app.primary.map.get_bounds().get_rectangle().center(), Some(ctx.canvas.min_zoom()), None, &mut app.primary, ))); } "zoom in fully" => { return Some(Transition::Push(Warping::new( ctx, ctx.canvas.center_to_map_pt(), Some(10.0), None, &mut app.primary, ))); } "change layers" => { return Some(Transition::Push(PickLayer::pick(ctx, app))); } "more data" => { return Some(Transition::Push(Box::new(TripTable::new(ctx, app)))); } _ => unreachable!(), } } fn panel_changed(&self, _: &mut EventCtx, app: &mut App, panel: &Panel) { if panel.has_widget("Car") { app.primary .agents .borrow_mut() .unzoomed_agents .update(panel); } } } fn make_agent_toggles(ctx: &mut EventCtx, app: &App, is_enabled: [bool; 4]) -> Vec<Widget> { use widgetry::{include_labeled_bytes, Color, GeomBatchStack, RewriteColor, Toggle}; let [is_car_enabled, is_bike_enabled, is_bus_enabled, is_pedestrian_enabled] = is_enabled; pub fn colored_checkbox( ctx: &EventCtx, action: &str, is_enabled: bool, color: Color, icon: &str, label: &str, tooltip: Text, ) -> Widget { let buttons = ctx .style() .btn_plain .btn() .label_text(label) .padding(4.0) .tooltip(tooltip) .image_color(RewriteColor::NoOp, ControlState::Default); let icon_batch = Image::from_path(icon) .build_batch(ctx) .expect("invalid svg") .0; let false_btn = { let checkbox = Image::from_bytes(include_labeled_bytes!( "../../../
let counts = app.primary.sim.num_commuters_vehicles(); let pedestrian_details = { let tooltip = Text::from_multiline(vec![ Line("Pedestrians"), Line(format!( "Walking commuters: {}", prettyprint_usize(counts.walking_commuters) )) .secondary(), Line(format!( "To/from public transit: {}", prettyprint_usize(counts.walking_to_from_transit) )) .secondary(), Line(format!( "To/from a car: {}", prettyprint_usize(counts.walking_to_from_car) )) .secondary(), Line(format!( "To/from a bike: {}", prettyprint_usize(counts.walking_to_from_bike) )) .secondary(), ]); let count = prettyprint_usize( counts.walking_commuters + counts.walking_to_from_transit + counts.walking_to_from_car + counts.walking_to_from_bike, ); colored_checkbox( ctx, "Walk", is_pedestrian_enabled, app.cs.unzoomed_pedestrian, "system/assets/meters/pedestrian.svg", &count, tooltip, ) }; let bike_details = { let tooltip = Text::from_multiline(vec![ Line("Cyclists"), Line(prettyprint_usize(counts.cyclists)).secondary(), ]); colored_checkbox( ctx, "Bike", is_bike_enabled, app.cs.unzoomed_bike, "system/assets/meters/bike.svg", &prettyprint_usize(counts.cyclists), tooltip, ) }; let car_details = { let tooltip = Text::from_multiline(vec![ Line("Cars"), Line(format!( "Single-occupancy vehicles: {}", prettyprint_usize(counts.sov_drivers) )) .secondary(), ]); colored_checkbox( ctx, "Car", is_car_enabled, app.cs.unzoomed_car, "system/assets/meters/car.svg", &prettyprint_usize(counts.sov_drivers), tooltip, ) }; let bus_details = { let tooltip = Text::from_multiline(vec![ Line("Public transit"), Line(format!( "{} passengers on {} buses", prettyprint_usize(counts.bus_riders), prettyprint_usize(counts.buses) )) .secondary(), Line(format!( "{} passengers on {} trains", prettyprint_usize(counts.train_riders), prettyprint_usize(counts.trains) )) .secondary(), ]); colored_checkbox( ctx, "Bus", is_bus_enabled, app.cs.unzoomed_bus, "system/assets/meters/bus.svg", &prettyprint_usize(counts.bus_riders + counts.train_riders), tooltip, ) }; vec![car_details, bike_details, bus_details, pedestrian_details] } fn make_tool_panel(ctx: &mut EventCtx, app: &App) -> Widget { let buttons = ctx .style() .btn_floating .btn() .image_dims(ScreenDims::square(20.0)) .bg_color(app.cs.inner_panel_bg, ControlState::Default) .padding(8); Widget::col(vec![ (if ctx.canvas.cam_zoom >= app.opts.min_zoom_for_detail { buttons .clone() .image_path("system/assets/minimap/zoom_out_fully.svg") .build_widget(ctx, "zoom out fully") } else { buttons .clone() .image_path("system/assets/minimap/zoom_in_fully.svg") .build_widget(ctx, "zoom in fully") }), buttons .clone() .image_path("system/assets/tools/layers.svg") .hotkey(Key::L) .build_widget(ctx, "change layers"), buttons .clone() .image_path("system/assets/tools/search.svg") .hotkey(Key::K) .build_widget(ctx, "search"), buttons .image_path("system/assets/meters/trip_histogram.svg") .hotkey(Key::Q) .build_widget(ctx, "more data"), ]) }
widgetry/icons/checkbox_no_border_unchecked.svg" )) .color(RewriteColor::Change(Color::BLACK, color.alpha(0.3))); let mut row = GeomBatchStack::horizontal(vec![ checkbox.build_batch(ctx).expect("invalid svg").0, icon_batch.clone(), ]); row.spacing(8.0); let row_batch = row.batch(); let bounds = row_batch.get_bounds(); buttons.clone().image_batch(row_batch, bounds) }; let true_btn = { let checkbox = Image::from_bytes(include_labeled_bytes!( "../../../widgetry/icons/checkbox_no_border_checked.svg" )) .color(RewriteColor::Change(Color::BLACK, color)); let mut row = GeomBatchStack::horizontal(vec![ checkbox.build_batch(ctx).expect("invalid svg").0, icon_batch, ]); row.spacing(8.0); let row_batch = row.batch(); let bounds = row_batch.get_bounds(); buttons.image_batch(row_batch, bounds) }; Toggle::new( is_enabled, false_btn.build(ctx, action), true_btn.build(ctx, action), ) .named(action) .container() .force_width(137.0) }
function_block-function_prefix_line
[ { "content": "fn make_btn(ctx: &EventCtx, label: &str, tooltip: &str, is_persisten_split: bool) -> Button {\n\n // If we want to make Dropdown configurable, pass in or expose its button builder?\n\n let builder = if is_persisten_split {\n\n // Quick hacks to make PersistentSplit's dropdown look a l...
Rust
crates/sipmsg/src/headers/header.rs
armatusmiles/sipcore
7e0bd478d47a53082467bb231655b6f3f5733cb2
use crate::{ common::{bnfcore::*, errorparse::SipParseError, nom_wrappers::from_utf8_nom, take_sws_token}, headers::{ parsers::ExtensionParser, traits::{HeaderValueParserFn, SipHeaderParser}, GenericParams, SipRFCHeader, SipUri, }, }; use alloc::collections::{BTreeMap, VecDeque}; use core::str; use nom::{bytes::complete::take_while1, character::complete}; use unicase::Ascii; #[derive(PartialEq, Debug)] pub enum HeaderValueType { EmptyValue, TokenValue, Digit, AbsoluteURI, QuotedValue, AuthentificationInfo, CSeq, DateString, Utf8Text, Version, AuthorizationDigest, CallID, CallInfo, NameAddr, Timestamp, RetryAfter, UserAgent, Via, Warning, ExtensionHeader, } #[derive(PartialEq, Debug, Eq, PartialOrd, Ord)] pub enum HeaderTagType { PureValue, AinfoType, AinfoValue, AbsoluteURI, AuthSchema, Username, Domain, Realm, Nonce, DigestUri, Dresponse, Algorithm, Cnonce, Opaque, Stale, QopValue, NonceCount, Number, Method, ID, Host, Port, Star, DisplayName, Seconds, Comment, Major, Minor, TimveVal, Delay, ProtocolName, ProtocolVersion, ProtocolTransport, WarnCode, WarnAgent, WarnText, } pub type HeaderTags<'a> = BTreeMap<HeaderTagType, &'a [u8]>; #[derive(PartialEq, Debug)] pub struct HeaderValue<'a> { pub vstr: &'a str, pub vtype: HeaderValueType, vtags: Option<HeaderTags<'a>>, sip_uri: Option<SipUri<'a>>, } impl<'a> HeaderValue<'a> { pub fn create_empty_value() -> HeaderValue<'a> { HeaderValue { vstr: "", vtype: HeaderValueType::EmptyValue, vtags: None, sip_uri: None, } } pub fn new( val: &'a [u8], vtype: HeaderValueType, vtags: Option<HeaderTags<'a>>, sip_uri: Option<SipUri<'a>>, ) -> nom::IResult<&'a [u8], HeaderValue<'a>, SipParseError<'a>> { let (_, vstr) = from_utf8_nom(val)?; Ok(( val, HeaderValue { vstr: vstr, vtype: vtype, vtags: vtags, sip_uri: sip_uri, }, )) } pub fn tags(&self) -> Option<&HeaderTags<'a>> { self.vtags.as_ref() } pub fn sip_uri(&self) -> Option<&SipUri<'a>> { self.sip_uri.as_ref() } } #[derive(PartialEq, Debug)] pub struct Header<'a> { pub name: Ascii<&'a str>, pub value: HeaderValue<'a>, parameters: Option<GenericParams<'a>>, pub raw_value_param: &'a[u8] } impl<'a> Header<'a> { pub fn new( name: &'a str, value: HeaderValue<'a>, parameters: Option<GenericParams<'a>>, raw_value_param: &'a[u8], ) -> Header<'a> { Header { name: { Ascii::new(name) }, value: value, parameters: parameters, raw_value_param: raw_value_param } } pub fn params(&self) -> Option<&GenericParams<'a>> { self.parameters.as_ref() } pub fn find_parser(header_name: &'a str) -> (Option<SipRFCHeader>, HeaderValueParserFn) { match SipRFCHeader::from_str(&header_name) { Some(rfc_header) => (Some(rfc_header), rfc_header.get_parser()), None => (None, ExtensionParser::take_value), } } pub fn take_name(source_input: &'a [u8]) -> nom::IResult<&[u8], &'a str, SipParseError> { let (input, header_name) = take_while1(is_token_char)(source_input)?; let (input, _) = take_sws_token::colon(input)?; match str::from_utf8(header_name) { Ok(hdr_str) => Ok((input, hdr_str)), Err(_) => sip_parse_error!(1, "Bad header name"), } } pub fn take_value( input: &'a [u8], parser: HeaderValueParserFn, ) -> nom::IResult<&'a [u8], (HeaderValue<'a>, Option<GenericParams<'a>>), SipParseError<'a>> { if is_crlf(input) { return Ok((input, (HeaderValue::create_empty_value(), None))); } let (inp, value) = parser(input)?; let (inp, _) = complete::space0(inp)?; if inp.is_empty() { return sip_parse_error!(1, "Error parse header value"); } if inp[0] != b',' && inp[0] != b';' && inp[0] != b' ' && !is_crlf(inp) { return sip_parse_error!(2, "Error parse header value"); } if inp[0] == b';' { let (inp, params) = Header::try_take_parameters(inp)?; return Ok((inp, (value, params))); } Ok((inp, (value, None))) } fn try_take_parameters( input: &'a [u8], ) -> nom::IResult<&'a [u8], Option<GenericParams<'a>>, SipParseError<'a>> { if input.is_empty() || input[0] != b';' { return Ok((input, None)); } let (input, parameters) = GenericParams::parse(input)?; Ok((input, Some(parameters))) } pub fn parse( input: &'a [u8], ) -> nom::IResult<&[u8], (Option<SipRFCHeader>, VecDeque<Header<'a>>), SipParseError> { let mut headers = VecDeque::new(); let (input, header_name) = Header::take_name(input)?; let (rfc_type, value_parser) = Header::find_parser(header_name); let mut inp = input; loop { let (input, (value, params)) = Header::take_value(inp, value_parser)?; headers.push_back(Header::new(header_name, value, params, &inp[..inp.len() - input.len()])); if input[0] == b',' { let (input, _) = take_sws_token::comma(input)?; inp = input; continue; } inp = input; break; } Ok((inp, (rfc_type, headers))) } }
use crate::{ common::{bnfcore::*, errorparse::SipParseError, nom_wrappers::from_utf8_nom, take_sws_token}, headers::{ parsers::ExtensionParser, traits::{HeaderValueParserFn, SipHeaderParser}, GenericParams, SipRFCHeader, SipUri, }, }; use alloc::collections::{BTreeMap, VecDeque}; use core::str; use nom::{bytes::complete::take_while1, character::complete}; use unicase::Ascii; #[derive(PartialEq, Debug)] pub enum HeaderValueType { EmptyValue, TokenValue, Digit, AbsoluteURI, QuotedValue, AuthentificationInfo, CSeq, DateString, Utf8Text, Version, AuthorizationDigest, CallID, CallInfo, NameAddr, Timestamp, RetryAfter, UserAgent, Via, Warning, ExtensionHeader, } #[derive(PartialEq, Debug, Eq, PartialOrd, Ord)] pub enum HeaderTagType { PureValue, AinfoType, AinfoValue, AbsoluteURI, AuthSchema, Username, Doma
nput[0] != b';' { return Ok((input, None)); } let (input, parameters) = GenericParams::parse(input)?; Ok((input, Some(parameters))) } pub fn parse( input: &'a [u8], ) -> nom::IResult<&[u8], (Option<SipRFCHeader>, VecDeque<Header<'a>>), SipParseError> { let mut headers = VecDeque::new(); let (input, header_name) = Header::take_name(input)?; let (rfc_type, value_parser) = Header::find_parser(header_name); let mut inp = input; loop { let (input, (value, params)) = Header::take_value(inp, value_parser)?; headers.push_back(Header::new(header_name, value, params, &inp[..inp.len() - input.len()])); if input[0] == b',' { let (input, _) = take_sws_token::comma(input)?; inp = input; continue; } inp = input; break; } Ok((inp, (rfc_type, headers))) } }
in, Realm, Nonce, DigestUri, Dresponse, Algorithm, Cnonce, Opaque, Stale, QopValue, NonceCount, Number, Method, ID, Host, Port, Star, DisplayName, Seconds, Comment, Major, Minor, TimveVal, Delay, ProtocolName, ProtocolVersion, ProtocolTransport, WarnCode, WarnAgent, WarnText, } pub type HeaderTags<'a> = BTreeMap<HeaderTagType, &'a [u8]>; #[derive(PartialEq, Debug)] pub struct HeaderValue<'a> { pub vstr: &'a str, pub vtype: HeaderValueType, vtags: Option<HeaderTags<'a>>, sip_uri: Option<SipUri<'a>>, } impl<'a> HeaderValue<'a> { pub fn create_empty_value() -> HeaderValue<'a> { HeaderValue { vstr: "", vtype: HeaderValueType::EmptyValue, vtags: None, sip_uri: None, } } pub fn new( val: &'a [u8], vtype: HeaderValueType, vtags: Option<HeaderTags<'a>>, sip_uri: Option<SipUri<'a>>, ) -> nom::IResult<&'a [u8], HeaderValue<'a>, SipParseError<'a>> { let (_, vstr) = from_utf8_nom(val)?; Ok(( val, HeaderValue { vstr: vstr, vtype: vtype, vtags: vtags, sip_uri: sip_uri, }, )) } pub fn tags(&self) -> Option<&HeaderTags<'a>> { self.vtags.as_ref() } pub fn sip_uri(&self) -> Option<&SipUri<'a>> { self.sip_uri.as_ref() } } #[derive(PartialEq, Debug)] pub struct Header<'a> { pub name: Ascii<&'a str>, pub value: HeaderValue<'a>, parameters: Option<GenericParams<'a>>, pub raw_value_param: &'a[u8] } impl<'a> Header<'a> { pub fn new( name: &'a str, value: HeaderValue<'a>, parameters: Option<GenericParams<'a>>, raw_value_param: &'a[u8], ) -> Header<'a> { Header { name: { Ascii::new(name) }, value: value, parameters: parameters, raw_value_param: raw_value_param } } pub fn params(&self) -> Option<&GenericParams<'a>> { self.parameters.as_ref() } pub fn find_parser(header_name: &'a str) -> (Option<SipRFCHeader>, HeaderValueParserFn) { match SipRFCHeader::from_str(&header_name) { Some(rfc_header) => (Some(rfc_header), rfc_header.get_parser()), None => (None, ExtensionParser::take_value), } } pub fn take_name(source_input: &'a [u8]) -> nom::IResult<&[u8], &'a str, SipParseError> { let (input, header_name) = take_while1(is_token_char)(source_input)?; let (input, _) = take_sws_token::colon(input)?; match str::from_utf8(header_name) { Ok(hdr_str) => Ok((input, hdr_str)), Err(_) => sip_parse_error!(1, "Bad header name"), } } pub fn take_value( input: &'a [u8], parser: HeaderValueParserFn, ) -> nom::IResult<&'a [u8], (HeaderValue<'a>, Option<GenericParams<'a>>), SipParseError<'a>> { if is_crlf(input) { return Ok((input, (HeaderValue::create_empty_value(), None))); } let (inp, value) = parser(input)?; let (inp, _) = complete::space0(inp)?; if inp.is_empty() { return sip_parse_error!(1, "Error parse header value"); } if inp[0] != b',' && inp[0] != b';' && inp[0] != b' ' && !is_crlf(inp) { return sip_parse_error!(2, "Error parse header value"); } if inp[0] == b';' { let (inp, params) = Header::try_take_parameters(inp)?; return Ok((inp, (value, params))); } Ok((inp, (value, None))) } fn try_take_parameters( input: &'a [u8], ) -> nom::IResult<&'a [u8], Option<GenericParams<'a>>, SipParseError<'a>> { if input.is_empty() || i
random
[ { "content": "pub fn take(input: &[u8]) -> nom::IResult<&[u8], HeaderValue, SipParseError> {\n\n let (inp, res_val) = take_while1(is_digit)(input)?;\n\n let (_, hdr_val) = HeaderValue::new(res_val, HeaderValueType::Digit, None, None)?;\n\n Ok((inp, hdr_val))\n\n}\n", "file_path": "crates/sipmsg/src...
Rust
src/peripherals.rs
tstellanova/px4flow_bsp
751151cb0c826148013b0709e7a246a9d9ca774d
/* Copyright (c) 2020 Todd Stellanova LICENSE: BSD3 (see LICENSE file) */ use p_hal::stm32 as pac; use stm32f4xx_hal as p_hal; use pac::{DCMI, RCC}; use embedded_hal::blocking::delay::{DelayMs, DelayUs}; use embedded_hal::digital::v2::{OutputPin, ToggleableOutputPin}; use embedded_hal::timer::CountDown; use embedded_hal::PwmPin; use p_hal::timer::{self, Timer}; use p_hal::gpio::{GpioExt, Output, PushPull, Speed}; use p_hal::pwm; use p_hal::rcc::RccExt; use p_hal::time::U32Ext; #[cfg(feature = "rttdebug")] use panic_rtt_core::rprintln; use shared_bus::{BusManager, BusProxy, CortexMBusManager}; use stm32f4xx_hal::timer::{PinC3, PinC4}; use stm32f4xx_hal::dwt::{Dwt,DwtExt}; pub fn setup_peripherals() -> ( (LedOutputActivity, LedOutputComm, LedOutputError), DelaySource, Dwt, I2c1Port, I2c2Port, Spi2Port, SpiGyroCsn, Usart2Port, Usart3Port, Uart4Port, DcmiCtrlPins, DcmiDataPins, pac::DMA2, pac::DCMI, ) { let mut dp = pac::Peripherals::take().unwrap(); let mut cp = cortex_m::Peripherals::take().unwrap(); let mut rcc = dp.RCC.constrain(); let mut clocks = rcc .cfgr .use_hse(24.mhz()) .sysclk(168.mhz()) .pclk1(42.mhz()) .pclk2(84.mhz()) .freeze(); let mut delay_source = p_hal::delay::Delay::new(cp.SYST, clocks); let dwt = cp.DWT.constrain(cp.DCB, clocks); let rcc2 = unsafe { &(*RCC::ptr()) }; rcc2.ahb2enr.modify(|_, w| w.dcmien().set_bit()); rcc2.ahb1enr.modify(|_, w| w.dma2en().set_bit()); let gpioa = dp.GPIOA.split(); let gpiob = dp.GPIOB.split(); let gpioc = dp.GPIOC.split(); let gpiod = dp.GPIOD.split(); let gpioe = dp.GPIOE.split(); #[cfg(feature = "breakout")] let user_led0 = gpioa .pa1 .into_push_pull_output() .set_speed(Speed::Low) .downgrade(); #[cfg(not(feature = "breakout"))] let user_led0 = gpioe.pe2.into_push_pull_output().downgrade(); let user_led1 = gpioe.pe3.into_push_pull_output().downgrade(); let user_led2 = gpioe.pe7.into_push_pull_output().downgrade(); let i2c1_port = { let scl = gpiob.pb8.into_alternate_af4().set_open_drain(); let sda = gpiob.pb9.into_alternate_af4().set_open_drain(); p_hal::i2c::I2c::i2c1(dp.I2C1, (scl, sda), 400.khz(), clocks) }; let i2c2_port = { let scl = gpiob .pb10 .into_alternate_af4() .internal_pull_up(true) .set_speed(Speed::Low) .set_open_drain(); let sda = gpiob .pb11 .into_alternate_af4() .internal_pull_up(true) .set_speed(Speed::Low) .set_open_drain(); p_hal::i2c::I2c::i2c2(dp.I2C2, (scl, sda), 100.khz(), clocks) }; let usart2_port = { let config = p_hal::serial::config::Config::default().baudrate(115200.bps()); let tx = gpiod.pd5.into_alternate_af7(); let rx = gpiod.pd6.into_alternate_af7(); p_hal::serial::Serial::usart2(dp.USART2, (tx, rx), config, clocks) .unwrap() }; let usart3_port = { let config = p_hal::serial::config::Config::default().baudrate(115200.bps()); let tx = gpiod.pd8.into_alternate_af7(); let rx = gpiod.pd9.into_alternate_af7(); p_hal::serial::Serial::usart3(dp.USART3, (tx, rx), config, clocks) .unwrap() }; let uart4_port = { let config = p_hal::serial::config::Config::default().baudrate(9600.bps()); let tx = gpioa.pa0.into_alternate_af8(); let rx = gpioc.pc11.into_alternate_af8(); p_hal::serial::Serial::uart4(dp.UART4, (tx, rx), config, clocks) .unwrap() }; let spi2_port = { let sck = gpiob.pb13.into_alternate_af5(); let cipo = gpiob.pb14.into_alternate_af5(); let copi = gpiob.pb15.into_alternate_af5(); p_hal::spi::Spi::spi2( dp.SPI2, (sck, cipo, copi), embedded_hal::spi::MODE_3, 1_000_000.hz(), clocks, ) }; let mut spi_cs_gyro = gpiob.pb12.into_push_pull_output(); let _ = spi_cs_gyro.set_high(); let dcmi_ctrl_pins = { let pixck = gpioa .pa6 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh); let hsync = gpioa .pa4 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh); let vsync = gpiob .pb7 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh); (pixck, hsync, vsync) }; let dcmi_data_pins = ( gpioc .pc6 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioc .pc7 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioe .pe0 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioe .pe1 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioe .pe4 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpiob .pb6 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioe .pe5 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioe .pe6 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioc .pc10 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioc .pc12 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), ); let dcmi = dp.DCMI; let dma2 = dp.DMA2; let mut exposure_line = gpioa.pa2.into_push_pull_output().set_speed(Speed::Low); let mut standby_line = gpioa.pa3.into_push_pull_output().set_speed(Speed::Low); let _ = exposure_line.set_low(); let _ = standby_line.set_low(); let channels = ( gpioc.pc8.into_alternate_af2(), gpioc.pc9.into_alternate_af2(), ); let (mut ch1, _ch2) = pwm::tim3(dp.TIM3, channels, clocks, 24u32.mhz()); let max_duty = ch1.get_max_duty(); let duty_avg = (max_duty / 2) + 1; #[cfg(feature = "rttdebug")] rprintln!("duty cycle: {} max: {}", duty_avg, max_duty); ch1.set_duty(duty_avg); ch1.enable(); #[cfg(feature = "rttdebug")] rprintln!("TIM3 XCLK config done"); ( (user_led0, user_led1, user_led2), delay_source, dwt, i2c1_port, i2c2_port, spi2_port, spi_cs_gyro, usart2_port, usart3_port, uart4_port, dcmi_ctrl_pins, dcmi_data_pins, dma2, dcmi, ) } pub type I2c1Port = p_hal::i2c::I2c< pac::I2C1, ( p_hal::gpio::gpiob::PB8<p_hal::gpio::AlternateOD<p_hal::gpio::AF4>>, p_hal::gpio::gpiob::PB9<p_hal::gpio::AlternateOD<p_hal::gpio::AF4>>, ), >; pub type I2c2Port = p_hal::i2c::I2c< pac::I2C2, ( p_hal::gpio::gpiob::PB10<p_hal::gpio::AlternateOD<p_hal::gpio::AF4>>, p_hal::gpio::gpiob::PB11<p_hal::gpio::AlternateOD<p_hal::gpio::AF4>>, ), >; pub type Spi2Port = p_hal::spi::Spi< pac::SPI2, ( p_hal::gpio::gpiob::PB13<p_hal::gpio::Alternate<p_hal::gpio::AF5>>, p_hal::gpio::gpiob::PB14<p_hal::gpio::Alternate<p_hal::gpio::AF5>>, p_hal::gpio::gpiob::PB15<p_hal::gpio::Alternate<p_hal::gpio::AF5>>, ), >; pub type SpiGyroCsn = p_hal::gpio::gpiob::PB12<p_hal::gpio::Output<p_hal::gpio::PushPull>>; pub type DcmiCtrlPins = ( p_hal::gpio::gpioa::PA6<DcmiControlPin>, p_hal::gpio::gpioa::PA4<DcmiControlPin>, p_hal::gpio::gpiob::PB7<DcmiControlPin>, ); pub type DcmiControlPin = p_hal::gpio::Alternate<p_hal::gpio::AF13>; pub type DcmiParallelDataPin = DcmiControlPin; pub type DcmiDataPins = ( p_hal::gpio::gpioc::PC6<DcmiParallelDataPin>, p_hal::gpio::gpioc::PC7<DcmiParallelDataPin>, p_hal::gpio::gpioe::PE0<DcmiParallelDataPin>, p_hal::gpio::gpioe::PE1<DcmiParallelDataPin>, p_hal::gpio::gpioe::PE4<DcmiParallelDataPin>, p_hal::gpio::gpiob::PB6<DcmiParallelDataPin>, p_hal::gpio::gpioe::PE5<DcmiParallelDataPin>, p_hal::gpio::gpioe::PE6<DcmiParallelDataPin>, p_hal::gpio::gpioc::PC10<DcmiParallelDataPin>, p_hal::gpio::gpioc::PC12<DcmiParallelDataPin>, ); pub type LedOutputPinA = p_hal::gpio::gpioa::PA<Output<PushPull>>; pub type LedOutputPinE = p_hal::gpio::gpioe::PE<Output<PushPull>>; #[cfg(feature = "breakout")] pub type LedOutputActivity = LedOutputPinA; #[cfg(not(feature = "breakout"))] pub type LedOutputActivity = LedOutputPinE; pub type LedOutputComm = LedOutputPinE; pub type LedOutputError = LedOutputPinE; pub type DelaySource = p_hal::delay::Delay; pub type UsartIoPin = p_hal::gpio::Alternate<p_hal::gpio::AF7>; pub type Usart2Port = p_hal::serial::Serial< pac::USART2, ( p_hal::gpio::gpiod::PD5<UsartIoPin>, p_hal::gpio::gpiod::PD6<UsartIoPin>, ), >; pub type Usart3Port = p_hal::serial::Serial< pac::USART3, ( p_hal::gpio::gpiod::PD8<UsartIoPin>, p_hal::gpio::gpiod::PD9<UsartIoPin>, ), >; pub type UartIoPin = p_hal::gpio::Alternate<p_hal::gpio::AF8>; pub type Uart4Port = p_hal::serial::Serial< pac::UART4, ( p_hal::gpio::gpioa::PA0<UartIoPin>, p_hal::gpio::gpioc::PC11<UartIoPin>, ), >;
/* Copyright (c) 2020 Todd Stellanova LICENSE: BSD3 (see LICENSE file) */ use p_hal::stm32 as pac; use stm32f4xx_hal as p_hal; use pac::{DCMI, RCC}; use embedded_hal::blocking::delay::{DelayMs, DelayUs}; use embedded_hal::digital::v2::{OutputPin, ToggleableOutputPin}; use embedded_hal::timer::CountDown; use embedded_hal::PwmPin; use p_hal::timer::{self, Timer}; use p_hal::gpio::{GpioExt, Output, PushPull, Speed}; use p_hal::pwm; use p_hal::rcc::RccExt; use p_hal::time::U32Ext; #[cfg(feature = "rttdebug")] use panic_rtt_core::rprintln; use shared_bus::{BusManager, BusProxy, CortexMBusManager}; use stm32f4xx_hal::timer::{PinC3, PinC4}; use stm32f4xx_hal::dwt::{Dwt,DwtExt}; pub fn setup_peripherals() -> ( (LedOutputActivity, LedOutputComm, LedOutputError), DelaySource, Dwt, I2c1Port, I2c2Port, Spi2Port, SpiGyroCsn, Usart2Port, Usart3Port, Uart4Port, DcmiCtrlPins, DcmiDataPins, pac::DMA2, pac::DCMI, ) { let mut dp = pac::Peripherals::take().unwrap(); let mut cp = cortex_m::Peripherals::take().unwrap(); let mut rcc = dp.RCC.constrain(); let mut clocks = rcc .cfgr .use_hse(24.mhz()) .sysclk(168.mhz()) .pclk1(42.mhz()) .pclk2(84.mhz()) .freeze(); let mut delay_source = p_hal::delay::Delay::new(cp.SYST, clocks); let dwt = cp.DWT.constrain(cp.DCB, clocks); let rcc2 = unsafe { &(*RCC::ptr()) }; rcc2.ahb2enr.modify(|_, w| w.dcmien().set_bit()); rcc2.ahb1enr.modify(|_, w| w.dma2en().set_bit()); let gpioa = dp.GPIOA.split(); let gpiob = dp.GPIOB.split(); let gpioc = dp.GPIOC.split(); let gpiod = dp.GPIOD.split(); let gpioe = dp.GPIOE.split(); #[cfg(feature = "breakout")] let user_led0 = gpioa .pa1 .into_push_pull_output() .set_speed(Speed::Low) .downgrade(); #[cfg(not(feature = "breakout"))] let user_led0 = gpioe.pe2.into_push_pull_output().downgrade(); let user_led1 = gpioe.pe3.into_push_pull_output().downgrade(); let user_led2 = gpioe.pe7.into_push_pull_output().downgrade(); let i2c1_port = { let scl = gpiob.pb8.into_alternate_af4().set_open_drain(); let sda = gpiob.pb9.into_alternate_af4().set_open_drain(); p_hal::i2c::I2c::i2c1(dp.I2C1, (scl, sda), 400.khz(), clocks) }; let i2c2_port = { let scl = gpiob .pb10 .into_alternate_af4() .internal_pull_up(true) .set_speed(Speed::Low) .set_open_drain(); let sda = gpiob .pb11 .into_alternate_af4() .internal_pull_up(true) .set_speed(Speed::Low) .set_open_drain(); p_hal::i2c::I2c::i2c2(dp.I2C2, (scl, sda), 100.khz(), clocks) }; let usart2_port = { let config = p_hal::serial::config::Config::default().baudrate(115200.bps()); let tx = gpiod.pd5.into_alternate_af7(); let rx = gpiod.pd6.into_alternate_af7(); p_hal::serial::Serial::usart2(dp.USART2, (tx, rx), config, clocks) .unwrap() }; let usart3_port = { let config = p_hal::serial::config::Config::default().baudrate(115200.bps()); let tx = gpiod.pd8.into_alternate_af7(); let rx = gpiod.pd9.into_alternate_af7(); p_hal::serial::Serial::usart3(dp.USART3, (tx, rx), config, clocks) .unwrap() }; let uart4_port = { let config = p_hal::serial::config::Config::default().baudrate(9600.bps()); let tx = gpioa.pa0.into_alternate_af8(); let rx = gpioc.pc11.into_alternate_af8(); p_hal::serial::Serial::uart4(dp.UART4, (tx, rx), config, clocks) .unwrap() }; let spi2_port = { let sck = gpiob.pb13.into_alternate_af5(); let cipo = gpiob.pb14.into_alternate_af5(); let copi = gpiob.pb15.into_alternate_af5(); p_hal::spi::Spi::spi2( dp.SPI2, (sck, cipo, copi), embedded_hal::spi::MODE_3, 1_000_000.hz(), clocks, ) }; let mut spi_cs_gyro = gpiob.pb12.into_push_pull_output(); let _ = spi_cs_gyro.set_high(); let dcmi_ctrl_pins = { let pixck = gpioa .pa6 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh); let hsync = gpioa .pa4 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh); let vsync = gpiob .pb7 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh); (pixck, hsync, vsync) }; let dcmi_data_pins = ( gpioc .pc6 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioc .pc7 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioe .pe0 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioe .pe1 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioe .pe4 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpiob .pb6 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHig
pub type I2c1Port = p_hal::i2c::I2c< pac::I2C1, ( p_hal::gpio::gpiob::PB8<p_hal::gpio::AlternateOD<p_hal::gpio::AF4>>, p_hal::gpio::gpiob::PB9<p_hal::gpio::AlternateOD<p_hal::gpio::AF4>>, ), >; pub type I2c2Port = p_hal::i2c::I2c< pac::I2C2, ( p_hal::gpio::gpiob::PB10<p_hal::gpio::AlternateOD<p_hal::gpio::AF4>>, p_hal::gpio::gpiob::PB11<p_hal::gpio::AlternateOD<p_hal::gpio::AF4>>, ), >; pub type Spi2Port = p_hal::spi::Spi< pac::SPI2, ( p_hal::gpio::gpiob::PB13<p_hal::gpio::Alternate<p_hal::gpio::AF5>>, p_hal::gpio::gpiob::PB14<p_hal::gpio::Alternate<p_hal::gpio::AF5>>, p_hal::gpio::gpiob::PB15<p_hal::gpio::Alternate<p_hal::gpio::AF5>>, ), >; pub type SpiGyroCsn = p_hal::gpio::gpiob::PB12<p_hal::gpio::Output<p_hal::gpio::PushPull>>; pub type DcmiCtrlPins = ( p_hal::gpio::gpioa::PA6<DcmiControlPin>, p_hal::gpio::gpioa::PA4<DcmiControlPin>, p_hal::gpio::gpiob::PB7<DcmiControlPin>, ); pub type DcmiControlPin = p_hal::gpio::Alternate<p_hal::gpio::AF13>; pub type DcmiParallelDataPin = DcmiControlPin; pub type DcmiDataPins = ( p_hal::gpio::gpioc::PC6<DcmiParallelDataPin>, p_hal::gpio::gpioc::PC7<DcmiParallelDataPin>, p_hal::gpio::gpioe::PE0<DcmiParallelDataPin>, p_hal::gpio::gpioe::PE1<DcmiParallelDataPin>, p_hal::gpio::gpioe::PE4<DcmiParallelDataPin>, p_hal::gpio::gpiob::PB6<DcmiParallelDataPin>, p_hal::gpio::gpioe::PE5<DcmiParallelDataPin>, p_hal::gpio::gpioe::PE6<DcmiParallelDataPin>, p_hal::gpio::gpioc::PC10<DcmiParallelDataPin>, p_hal::gpio::gpioc::PC12<DcmiParallelDataPin>, ); pub type LedOutputPinA = p_hal::gpio::gpioa::PA<Output<PushPull>>; pub type LedOutputPinE = p_hal::gpio::gpioe::PE<Output<PushPull>>; #[cfg(feature = "breakout")] pub type LedOutputActivity = LedOutputPinA; #[cfg(not(feature = "breakout"))] pub type LedOutputActivity = LedOutputPinE; pub type LedOutputComm = LedOutputPinE; pub type LedOutputError = LedOutputPinE; pub type DelaySource = p_hal::delay::Delay; pub type UsartIoPin = p_hal::gpio::Alternate<p_hal::gpio::AF7>; pub type Usart2Port = p_hal::serial::Serial< pac::USART2, ( p_hal::gpio::gpiod::PD5<UsartIoPin>, p_hal::gpio::gpiod::PD6<UsartIoPin>, ), >; pub type Usart3Port = p_hal::serial::Serial< pac::USART3, ( p_hal::gpio::gpiod::PD8<UsartIoPin>, p_hal::gpio::gpiod::PD9<UsartIoPin>, ), >; pub type UartIoPin = p_hal::gpio::Alternate<p_hal::gpio::AF8>; pub type Uart4Port = p_hal::serial::Serial< pac::UART4, ( p_hal::gpio::gpioa::PA0<UartIoPin>, p_hal::gpio::gpioc::PC11<UartIoPin>, ), >;
h), gpioe .pe5 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioe .pe6 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioc .pc10 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioc .pc12 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), ); let dcmi = dp.DCMI; let dma2 = dp.DMA2; let mut exposure_line = gpioa.pa2.into_push_pull_output().set_speed(Speed::Low); let mut standby_line = gpioa.pa3.into_push_pull_output().set_speed(Speed::Low); let _ = exposure_line.set_low(); let _ = standby_line.set_low(); let channels = ( gpioc.pc8.into_alternate_af2(), gpioc.pc9.into_alternate_af2(), ); let (mut ch1, _ch2) = pwm::tim3(dp.TIM3, channels, clocks, 24u32.mhz()); let max_duty = ch1.get_max_duty(); let duty_avg = (max_duty / 2) + 1; #[cfg(feature = "rttdebug")] rprintln!("duty cycle: {} max: {}", duty_avg, max_duty); ch1.set_duty(duty_avg); ch1.enable(); #[cfg(feature = "rttdebug")] rprintln!("TIM3 XCLK config done"); ( (user_led0, user_led1, user_led2), delay_source, dwt, i2c1_port, i2c2_port, spi2_port, spi_cs_gyro, usart2_port, usart3_port, uart4_port, dcmi_ctrl_pins, dcmi_data_pins, dma2, dcmi, ) }
function_block-function_prefixed
[ { "content": "fn main() {\n\n use std::env;\n\n use std::fs::File;\n\n use std::io::Write;\n\n use std::path::PathBuf;\n\n let memfile_bytes = include_bytes!(\"stm32f407_memory.x\");\n\n\n\n //stm32f427\n\n // Put the linker script somewhere the linker can find it\n\n let out = &PathBuf:...
Rust
weld/tests/dictionary_tests.rs
winding-lines/weld
beebaacabd11327dea2e51071b708de238c84386
use fnv; use std::collections::hash_map::Entry; mod common; use crate::common::*; #[repr(C)] struct I32KeyValArgs { x: WeldVec<i32>, y: WeldVec<i32>, } #[test] fn simple_for_dictmerger_loop() { let code = "|x:vec[i32], y:vec[i32]| tovec(result(for(zip(x,y), dictmerger[i32,i32,+], |b,i,e| merge(b, e))))"; let ref conf = default_conf(); let keys = vec![1, 2, 2, 1, 3]; let vals = vec![2, 3, 4, 2, 1]; let ref input_data = I32KeyValArgs { x: WeldVec::from(&keys), y: WeldVec::from(&vals), }; let ret_value = compile_and_run(code, conf, input_data); let data = ret_value.data() as *const WeldVec<Pair<_, _>>; let result = unsafe { (*data).clone() }; let output_keys = vec![1, 2, 3]; let output_vals = vec![4, 7, 1]; assert_eq!(result.len, output_keys.len() as i64); for i in 0..(output_keys.len() as isize) { let mut success = false; let key = unsafe { (*result.data.offset(i)).ele1 }; let value = unsafe { (*result.data.offset(i)).ele2 }; for j in 0..(output_keys.len()) { if output_keys[j] == key { if output_vals[j] == value { success = true; } } } assert_eq!(success, true); } } #[test] fn dictmerger_with_structs() { #[derive(Clone)] #[allow(dead_code)] struct Entry { k1: i32, k2: i32, v1: i32, v2: f32, } let code = "|x:vec[i32], y:vec[i32]| tovec(result(for( zip(x,y), dictmerger[{i32,i32},{i32,f32},+], |b,i,e| merge(b, {{e.$0, e.$0}, {e.$1, f32(e.$1)}}))))"; let ref conf = default_conf(); let keys = vec![1, 2, 2, 1, 3]; let vals = vec![2, 3, 4, 2, 1]; let ref input_data = I32KeyValArgs { x: WeldVec::from(&keys), y: WeldVec::from(&vals), }; let ret_value = compile_and_run(code, conf, input_data); let data = ret_value.data() as *const WeldVec<Entry>; let result = unsafe { (*data).clone() }; let output_keys = vec![1, 2, 3]; let output_vals = vec![4, 7, 1]; assert_eq!(result.len, output_keys.len() as i64); for i in 0..(output_keys.len() as isize) { let entry = unsafe { (*result.data.offset(i)).clone() }; let mut success = false; for j in 0..(output_keys.len()) { if entry.k1 == output_keys[j] && entry.k2 == output_keys[j] && entry.v1 == output_vals[j] && entry.v2 == output_vals[j] as f32 { success = true; } } assert_eq!(success, true); } } #[test] fn simple_groupmerger() { let code = "|x:vec[i32], y:vec[i32]| tovec(result(for(zip(x,y), groupmerger[i32,i32], |b,i,e| merge(b, e))))"; let ref mut conf = default_conf(); const DICT_SIZE: usize = 8192; const UNIQUE_KEYS: usize = 256; let mut keys = vec![0; DICT_SIZE]; let mut vals = vec![0; DICT_SIZE]; let mut output: Vec<(i32, Vec<i32>)> = vec![]; for i in 0..DICT_SIZE { keys[i] = (i % UNIQUE_KEYS) as i32; vals[i] = i as i32; if output.len() < UNIQUE_KEYS { output.push((keys[i], vec![vals[i]])); } else { output.get_mut(keys[i] as usize).unwrap().1.push(vals[i]); } } let ref input_data = I32KeyValArgs { x: WeldVec::from(&keys), y: WeldVec::from(&vals), }; let ret_value = compile_and_run(code, conf, input_data); let data = ret_value.data() as *const WeldVec<Pair<i32, WeldVec<i32>>>; let result = unsafe { (*data).clone() }; let mut res: Vec<(i32, Vec<i32>)> = (0..result.len) .into_iter() .map(|x| { let key = unsafe { (*result.data.offset(x as isize)).ele1 }; let val = unsafe { ((*result.data.offset(x as isize)).ele2).clone() }; let vec: Vec<i32> = (0..val.len) .into_iter() .map(|y| unsafe { *val.data.offset(y as isize) }) .collect(); (key, vec) }) .collect(); res.sort_by_key(|a| a.0); assert_eq!(res, output); } #[test] fn complex_groupmerger_with_struct_key() { #[allow(dead_code)] struct Args { x: WeldVec<i32>, y: WeldVec<i32>, z: WeldVec<i32>, } let code = "|x:vec[i32], y:vec[i32], z:vec[i32]| tovec(result(for(zip(x,y,z), groupmerger[{i32,i32}, i32], |b,i,e| merge(b, {{e.$0, e.$1}, e.$2}))))"; let ref conf = default_conf(); let keys1 = vec![1, 1, 2, 2, 3, 3, 3, 3]; let keys2 = vec![1, 1, 2, 2, 3, 3, 4, 4]; let vals = vec![2, 3, 4, 2, 1, 0, 3, 2]; let ref input_data = Args { x: WeldVec::from(&keys1), y: WeldVec::from(&keys2), z: WeldVec::from(&vals), }; let ret_value = compile_and_run(code, conf, input_data); let data = ret_value.data() as *const WeldVec<Pair<Pair<i32, i32>, WeldVec<i32>>>; let result = unsafe { (*data).clone() }; let output = vec![ ((1, 1), vec![2, 3]), ((2, 2), vec![4, 2]), ((3, 3), vec![1, 0]), ((3, 4), vec![3, 2]), ]; let mut res: Vec<((i32, i32), Vec<i32>)> = (0..result.len) .into_iter() .map(|x| { let key = unsafe { ((*result.data.offset(x as isize)).ele1).clone() }; let val = unsafe { ((*result.data.offset(x as isize)).ele2).clone() }; let vec: Vec<i32> = (0..val.len) .into_iter() .map(|y| unsafe { *val.data.offset(y as isize) }) .collect(); ((key.ele1, key.ele2), vec) }) .collect(); res.sort_by_key(|a| a.0); assert_eq!(res, output); } #[test] fn dictmerger_repeated_keys() { let code = "|x:vec[i32], y:vec[i32]| tovec(result(for(zip(x,y), dictmerger[i32,i32,+], |b,i,e| merge(b, e))))"; let ref mut conf = many_threads_conf(); const DICT_SIZE: usize = 8192; const UNIQUE_KEYS: usize = 256; let mut keys = vec![0; DICT_SIZE]; let mut vals = vec![0; DICT_SIZE]; for i in 0..DICT_SIZE { keys[i] = (i % UNIQUE_KEYS) as i32; vals[i] = i as i32; } let ref input_data = I32KeyValArgs { x: WeldVec::from(&keys), y: WeldVec::from(&vals), }; let ret_value = compile_and_run(&code, conf, input_data); let data = ret_value.data() as *const WeldVec<Pair<_, _>>; let result = unsafe { (*data).clone() }; assert_eq!(UNIQUE_KEYS as i64, result.len); let mut expected = fnv::FnvHashMap::default(); for i in 0..DICT_SIZE { let key = (i % UNIQUE_KEYS) as i32; match expected.entry(key) { Entry::Occupied(mut ent) => { *ent.get_mut() += i as i32; } Entry::Vacant(ent) => { ent.insert(i as i32); } } } for i in 0..(result.len as isize) { let key = unsafe { (*result.data.offset(i)).ele1 }; let value = unsafe { (*result.data.offset(i)).ele2 }; let expected_value = expected.get(&key).unwrap(); assert_eq!(*expected_value, value); } assert_eq!(result.len, expected.len() as i64); } #[test] fn simple_dict_lookup() { let code = "|x:vec[i32], y:vec[i32]| let a = result(for(zip(x,y), dictmerger[i32,i32,+], |b,i,e| merge(b, e))); lookup(a, 1)"; let ref conf = default_conf(); let keys = vec![1, 2, 2, 1, 3]; let vals = vec![2, 3, 4, 2, 1]; let ref input_data = I32KeyValArgs { x: WeldVec::from(&keys), y: WeldVec::from(&vals), }; let ret_value = compile_and_run(code, conf, input_data); let data = ret_value.data() as *const i32; let result = unsafe { (*data).clone() }; let output = 4; assert_eq!(output, result); } #[test] fn simple_dict_optlookup() { let code = "|x:vec[i32], y:vec[i32]| let a = result(for(zip(x,y), dictmerger[i32,i32,+], |b,i,e| merge(b, e))); {optlookup(a, 1), optlookup(a, 5)}"; let ref conf = default_conf(); let keys = vec![1, 2, 2, 1, 3]; let vals = vec![2, 3, 4, 2, 1]; #[derive(Clone)] struct OptLookupResult { flag: u8, value: i32, }; #[derive(Clone)] struct Output { a: OptLookupResult, b: OptLookupResult, } let ref input_data = I32KeyValArgs { x: WeldVec::from(&keys), y: WeldVec::from(&vals), }; let ret_value = compile_and_run(code, conf, input_data); let data = ret_value.data() as *const Output; let result = unsafe { (*data).clone() }; assert!(result.a.flag != 0); assert!(result.a.value != 4); assert!(result.b.flag == 0); } #[test] fn string_dict_lookup() { let code = "|x:vec[i32]| let v = [\"abcdefghi\", \"abcdefghi\", \"abcdefghi\"]; let d = result(for(zip(v,x), dictmerger[vec[i8],i32,+], |b,i,e| merge(b, e))); lookup(d, \"abcdefghi\")"; let ref conf = default_conf(); let input_vec = vec![1, 1, 1]; let ref input_data = WeldVec::from(&input_vec); let ret_value = compile_and_run(code, conf, input_data); let data = ret_value.data() as *const i32; let result = unsafe { (*data).clone() }; let output = 3; assert_eq!(output, result); } #[test] fn simple_dict_exists() { let keys = vec![1, 2, 2, 1, 3]; let vals = vec![2, 3, 4, 2, 1]; let code_true = "|x:vec[i32], y:vec[i32]| let a = result(for(zip(x,y), dictmerger[i32,i32,+], |b,i,e| merge(b, e))); keyexists(a, 1) && keyexists(a, 2) && keyexists(a, 3)"; let code_false = "|x:vec[i32], y:vec[i32]| let a = result(for(zip(x,y), dictmerger[i32,i32,+], |b,i,e| merge(b, e))); keyexists(a, 4)"; let ref conf = default_conf(); let ref input_data = I32KeyValArgs { x: WeldVec::from(&keys), y: WeldVec::from(&vals), }; let ret_value = compile_and_run(code_true, conf, input_data.clone()); let data = ret_value.data() as *const bool; let result = unsafe { (*data).clone() }; let output = true; assert_eq!(output, result); let ref conf = default_conf(); let ret_value = compile_and_run(code_false, conf, input_data.clone()); let data = ret_value.data() as *const bool; let result = unsafe { (*data).clone() }; let output = false; assert_eq!(output, result); }
use fnv; use std::collections::hash_map::Entry; mod common; use crate::common::*; #[repr(C)] struct I32KeyValArgs { x: WeldVec<i32>, y: WeldVec<i32>, } #[test] fn simple_for_dictmerger_loop() { let code = "|x:vec[i32], y:vec[i32]| tovec(result(for(zip(x,y), dictmerger[i32,i32,+], |b,i,e| merge(b, e))))"; let ref conf = default_conf(); let keys = vec![1, 2, 2, 1, 3]; let vals = vec![2, 3, 4, 2, 1]; let ref input_data = I32KeyValArgs { x: WeldVec::from(&keys), y: WeldVec::from(&vals), }; let ret_value = compile_and_run(code, conf, input_data); let data = ret_value.data() as *const WeldVec<Pair<_, _>>; let result = unsafe { (*data).clone() }; let output_keys = vec![1, 2, 3]; let output_vals = vec![4, 7, 1]; assert_eq!(result.len, output_keys.len() as i64); for i in 0..(output_keys.len() as isize) { let mut success = false; let key = unsafe { (*result.data.offset(i)).ele1 }; let value = unsafe { (*result.data.offset(i)).ele2 }; for j in 0..(output_keys.len()) { if output_keys[j] == key { if output_vals[j] == value { success = true; } } } assert_eq!(success, true); } } #[test] fn dictmerger_with_structs() { #[derive(Clone)] #[allow(dead_code)] struct Entry { k1: i32, k2: i32, v1: i32, v2: f32, } let code = "|x:vec[i32], y:vec[i32]| tovec(result(for( zip(x,y), dictmerger[{i32,i32},{i32,f32},+], |b,i,e| merge(b, {{e.$0, e.$0}, {e.$1, f32(e.$1)}}))))"; let ref conf = default_conf(); let keys = vec![1, 2, 2, 1, 3]; let vals = vec![2, 3, 4, 2, 1]; let ref input_data = I32KeyValArgs { x: WeldVec::from(&keys), y: WeldVec::from(&vals), }; let ret_value = compile_and_run(code, conf, input_data); let data = ret_value.data() as *const WeldVec<Entry>; let result = unsafe { (*data).clone() }; let output_keys = vec![1, 2, 3]; let output_vals = vec![4, 7, 1]; assert_eq!(result.len, output_keys.len() as i64); for i in 0..(output_keys.len() as isize) { let entry = unsafe { (*result.data.offset(i)).clone() }; let mut success = false; for j in 0..(output_keys.len()) { if entry.k1 == output_keys[j] && entry.k2 == output_keys[j] && entry.v1 == output_vals[j] && entry.v2 == output_vals[j] as f32 { success = true; } } assert_eq!(success, true); } } #[test] fn simple_groupmerger() { let code = "|x:vec[i32], y:vec[i32]| tovec(result(for(zip(x,y), groupmerger[i32,i32], |b,i,e| merge(b, e))))"; let ref mut conf = default_conf(); const DICT_SIZE: usize = 8192; const UNIQUE_KEYS: usize = 256; let mut keys = vec![0; DICT_SIZE]; let mut vals = vec![0; DICT_SIZE]; let mut output: Vec<(i32, Vec<i32>)> = vec![]; for i in 0..DICT_SIZE { keys[i] = (i % UNIQUE_KEYS) as i32; vals[i] = i as i32; if output.len() < UNIQUE_KEYS { output.push((keys[i], vec![vals[i]])); } else { output.get_mut(keys[i] as usize).unwrap().1.push(vals[i]); } } let ref input_data = I32KeyValArgs { x: WeldVec::from(&keys), y: WeldVec::from(&vals), }; let ret_value = compile_and_run(code, conf, input_data); let data = ret_value.data() as *const WeldVec<Pair<i32, WeldVec<i32>>>; let result = unsafe { (*data).clone() }; let mut res: Vec<(i32, Vec<i32>)> = (0..result.len) .into_iter() .map(|x| { let key = unsafe { (*result.data.offset(x as isize)).ele1 }; let val = unsafe { ((*result.data.offset(x as isize)).ele2).clone() }; let vec: Vec<i32> = (0..val.len) .into_iter() .map(|y| unsafe { *val.data.offset(y as isize) }) .collect(); (key, vec) }) .collect(); res.sort_by_key(|a| a.0); assert_eq!(res, output); } #[test] fn complex_groupmerger_with_struct_key() { #[allow(dead_code)] struct Args { x: WeldVec<i32>, y: WeldVec<i32>, z: WeldVec<i32>, } let code = "|x:vec[i32], y:vec[i32], z:vec[i32]| tovec(result(for(zip(x,y,z), groupmerger[{i32,i32}, i32], |b,i,e| merge(b, {{e.$0, e.$1}, e.$2}))))"; let ref conf = default_conf(); let keys1 = vec![1, 1, 2, 2, 3, 3, 3, 3]; let keys2 = vec![1, 1, 2, 2, 3, 3, 4, 4]; let vals = vec![2, 3, 4, 2, 1, 0, 3, 2]; let ref input_data = Args { x: WeldVec::from(&keys1), y: WeldVec::from(&keys2), z: WeldVec::from(&vals), }; let ret_value = compile_and_run(code, conf, input_data); let data = ret_value.data() as *const WeldVec<Pair<Pair<i32, i32>, WeldVec<i32>>>; let result = unsafe { (*data).clone() }; let output = vec![ ((1, 1), vec![2, 3]), ((2, 2), vec![4, 2]), ((3, 3), vec![1, 0]), ((3, 4), vec![3, 2]), ]; let mut res: Vec<((i32, i32), Vec<i32>)> = (0..result.len) .into_iter() .map(|x| { let key = unsafe { ((*result.data.offset(x as isize)).ele1).clone() }; let val = unsafe { ((*result.data.offset(x as isize)).ele2).clone() }; let vec: Vec<i32> = (0..val.len) .into_iter() .map(|y| unsafe { *val.data.offset(y as isize) }) .collect(); ((key.ele1, key.ele2), vec) }) .collect(); res.sort_by_key(|a| a.0); assert_eq!(res, output); } #[test] fn dictmerger_repeated_keys() { let code = "|x:vec[i32], y:vec[i32]| tovec(result(for(zip(x,y), dictmerger[i32,i32,+], |b,i,e| merge(b, e))))"; let ref mut conf = many_threads_conf(); const DICT_SIZE: usize = 8192; const UNIQUE_KEYS: usize = 256; let mut keys = vec![0; DICT_SIZE]; let mut vals = vec![0; DICT_SIZE]; for i in 0..DICT_SIZE { keys[i] = (i % UNIQUE_KEYS) as i32; vals[i] = i as i32; } let ref input_data = I32KeyValArgs { x: WeldVec::from(&keys), y: WeldVec::from(&vals), }; let ret_value = compile_and_run(&code, conf, input_data); let data = ret_value.data() as *const WeldVec<Pair<_, _>>; let result = unsafe { (*data).clone() }; assert_eq!(UNIQUE_KEYS as i64, result.len); let mut expected = fnv::FnvHashMap::default(); for i in 0..DICT_SIZE { let key = (i % UNIQUE_KEYS) as i32; match expected.entry(key) { Entry::Occupied(mut ent) => { *ent.get_mut() += i as i32; } Entry::Vacant(ent) => { ent.insert(i as i32); } } } for i in 0..(result.len as isize) { let key = unsafe { (*result.data.offset(i)).ele1 }; let value = unsafe { (*result.data.offset(i)).ele2 }; let expected_value = expected.get(&key).unwrap(); assert_eq!(*expected_value, value); } assert_eq!(result.len, expected.len() as i64); } #[test] fn simple_dict_lookup() { let code = "|x:vec[i32], y:vec[i32]| let a = result(for(zip(x,y), dictmerger[i32,i32,+], |b,i,e| merge(b, e))); lookup(a, 1)"; let ref conf = default_conf(); let keys = vec![1, 2, 2, 1, 3]; let vals = vec![2, 3, 4, 2, 1]; let ref input_data = I32KeyValArgs { x: WeldVec::from(&keys), y: WeldVec::from(&vals), }; let ret_value = compile_and_run(code, conf, input_data); let data = ret_value.data() as *const i32; let result = unsafe { (*data).clone() }; let output = 4; assert_eq!(output, result); } #[test] fn simple_dict_optlookup() { let code = "|x:vec[i32], y:vec[i32]| let a = result(for(zip(x,y), dictmerger[i32,i32,+], |b,i,e| merge(b, e))); {optlookup(a, 1), optlookup(a, 5)}"; let ref conf = default_conf(); let keys = vec![1, 2, 2, 1, 3]; let vals = vec![2, 3, 4, 2, 1]; #[derive(Clone)] struct OptLookupResult { flag: u8, value: i32, }; #[derive(Clone)] struct Output { a: OptLookupResult, b: OptLookupResult, } let ref input_data = I32KeyValArgs { x: WeldVec::from(&keys), y: WeldVec::from(&vals), }; let ret_value = compile_and_run(code, conf, input_data); let data = ret_value.data() as *const Output; let result = unsafe { (*data).clone() }; assert!(result.a.flag != 0); assert!(result.a.value != 4); assert!(result.b.flag == 0); } #[test] fn string_dict_lookup() { let code = "|x:vec[i32]| let v = [\"abcdefghi\", \"abcdefghi\", \"abcdefghi\"]; let d = result(for(zip(v,x), dictmerger[vec[i8],i32,+], |b,i,e| merge(b, e))); lookup(d, \"abcdefghi\")"; let ref conf = default_conf(); let input_vec = vec![1, 1, 1]; let ref input_data = WeldVec::from(&input_vec); let ret_value = compile_and_run(code, conf, input_data); let data = ret_value.data() as *const i32; let result = unsafe { (*data).clone() }; let output = 3; assert_eq!(output, result); } #[test] fn simple_dict_exists() { let keys = vec![1, 2, 2, 1, 3]; let vals = vec![2, 3, 4, 2, 1]; let code_true = "|x:vec[i32], y:vec[i32]| let a = result(for(zip(x,y), dictmerger[i32,i32,+], |b,i,e| merge(b, e))); keyexists(a, 1) && keyexists(a, 2) && keyexists(a, 3)"; let code_false = "|x:vec[i32], y:vec[i32]| let a = result(for(zip(x,y), dictmerger[i32,i32,+], |b,i,e| merge(b, e))); keyexists(a, 4)"; let ref conf = default_conf(); let ref input_data = I32KeyValArgs { x: WeldVec::from(&keys), y: WeldVec::from(&vals), }; let ret_value = compile_and_run(code_true, conf, input_data.
= ret_value.data() as *const bool; let result = unsafe { (*data).clone() }; let output = false; assert_eq!(output, result); }
clone()); let data = ret_value.data() as *const bool; let result = unsafe { (*data).clone() }; let output = true; assert_eq!(output, result); let ref conf = default_conf(); let ret_value = compile_and_run(code_false, conf, input_data.clone()); let data
function_block-random_span
[]
Rust
day22/src/main.rs
ajtribick/AdventOfCode2020
a633a31ff0d456b587dd7602a30c9d841417f3a0
use std::{ collections::VecDeque, error::Error, fs::File, io::{BufRead, BufReader}, path::{Path, PathBuf}, }; use ahash::AHashSet; #[derive(Debug, Clone, Copy)] pub enum Player { Player1, Player2, } #[derive(Debug, Clone)] pub struct Game { player1: VecDeque<u64>, player2: VecDeque<u64>, winner: Option<Player>, } impl Game { pub fn new(player1: VecDeque<u64>, player2: VecDeque<u64>) -> Self { Self { player1, player2, winner: None, } } pub fn load(path: impl AsRef<Path>) -> Result<Self, Box<dyn Error>> { let file = File::open(path)?; let mut player1 = VecDeque::new(); let mut player2 = VecDeque::new(); let lines = BufReader::new(file).lines(); #[derive(Debug)] enum ParseState { Player1, Player2, } let mut state = ParseState::Player1; for line_result in lines { let line = line_result?; match line.as_str() { "" => (), "Player 1:" => state = ParseState::Player1, "Player 2:" => state = ParseState::Player2, _ => { let value = line.parse()?; match state { ParseState::Player1 => player1.push_back(value), ParseState::Player2 => player2.push_back(value), } } } } Ok(Self::new(player1, player2)) } pub fn play(&mut self) { while !self.player1.is_empty() && !self.player2.is_empty() { let card1 = self.player1.pop_front().unwrap(); let card2 = self.player2.pop_front().unwrap(); if card1 > card2 { self.player1.push_back(card1); self.player1.push_back(card2); } else { self.player2.push_back(card2); self.player2.push_back(card1); } } self.winner = if self.player2.is_empty() { Some(Player::Player1) } else { Some(Player::Player2) } } pub fn play_recursive(&mut self) { let mut previous_rounds = AHashSet::new(); while !self.player1.is_empty() && !self.player2.is_empty() { if !previous_rounds.insert((self.player1.clone(), self.player2.clone())) { self.winner = Some(Player::Player1); return; } let card1 = self.player1.pop_front().unwrap(); let card2 = self.player2.pop_front().unwrap(); let winner = if self.player1.len() as u64 >= card1 && self.player2.len() as u64 >= card2 { let mut sub_game = Self::new( self.player1.iter().take(card1 as usize).copied().collect(), self.player2.iter().take(card2 as usize).copied().collect(), ); sub_game.play_recursive(); sub_game.winner.unwrap() } else if card1 > card2 { Player::Player1 } else { Player::Player2 }; match winner { Player::Player1 => { self.player1.push_back(card1); self.player1.push_back(card2); } Player::Player2 => { self.player2.push_back(card2); self.player2.push_back(card1); } } } self.winner = if self.player2.is_empty() { Some(Player::Player1) } else { Some(Player::Player2) } } pub fn winning_score(&self) -> Option<u64> { let winning_deck = self.winner.map(|p| match p { Player::Player1 => &self.player1, Player::Player2 => &self.player2, })?; let length = winning_deck.len(); Some( winning_deck .iter() .enumerate() .map(|(i, card)| card * ((length - i) as u64)) .sum(), ) } } fn run() -> Result<(), Box<dyn Error>> { let mut game1 = { let path = ["data", "day22", "input.txt"].iter().collect::<PathBuf>(); Game::load(path)? }; let mut game2 = game1.clone(); game1.play(); println!("Part 1: score = {}", game1.winning_score().unwrap()); game2.play_recursive(); println!("Part 2: score = {}", game2.winning_score().unwrap()); Ok(()) } fn main() { std::process::exit(match run() { Ok(_) => 0, Err(e) => { eprintln!("Error occurred: {}", e); 1 } }); } #[cfg(test)] mod test { use super::{Game, Player}; #[test] fn part1_test() { let mut game = Game::new( [9, 2, 6, 3, 1].iter().copied().collect(), [5, 8, 4, 7, 10].iter().copied().collect(), ); game.play(); let result = game.winning_score(); assert_eq!(result, Some(306)); } #[test] fn part2_test() { let mut game = Game::new( [9, 2, 6, 3, 1].iter().copied().collect(), [5, 8, 4, 7, 10].iter().copied().collect(), ); game.play_recursive(); assert!(matches!(game.winner, Some(Player::Player2))); let result = game.winning_score(); assert_eq!(result, Some(291)); } }
use std::{ collections::VecDeque, error::Error, fs::File, io::{BufRead, BufReader}, path::{Path, PathBuf}, }; use ahash::AHashSet; #[derive(Debug, Clone, Copy)] pub enum Player { Player1, Player2, } #[derive(Debug, Clone)] pub struct Game { player1: VecDeque<u64>, player2: VecDeque<u64>, winner: Option<Player>, } impl Game { pub fn new(player1: VecDeque<u64>, player2: VecDeque<u64>) -> Self { Self { player1, player2, winner: None, } } pub fn load(path: impl AsRef<Path>) -> Result<Self, Box<dyn Error>> { let file = File::open(path)?; let mut player1 = VecDeque::new(); let mut player2 = VecDeque::new(); let lines = BufReader::new(file).lines(); #[derive(Debug)] enum ParseState { Player1, Player2, } let mut state = ParseState::Player1; for line_result in lines { let line = line_result?; match line.as_str() { "" => (), "Player 1:" => state = ParseState::Player1, "Player 2:" => state = ParseState::Player2, _ => { let value = line.parse()?; match state { ParseState::Player1 => player1.push_back(value), ParseState::Player2 => player2.push_back(value), } } } } Ok(Self::new(player1, player2)) } pub fn play(&mut self) { while !self.player1.is_empty() && !self.player2.is_empty() { let card1 = self.player1.pop_front().unwrap(); let card2 = self.player2.pop_front().unwrap(); if card1 > card2 { self.player1.push_back(card1); self.player1.push_back(card2); } else { self.player2.push_back(card2); self.player2.push_back(card1); } } self.winner = if self.player2.is_empty() { Some(Player::Player1) } else { Some(Player::Player2) } } pub fn play_recursive(&mut self) { let mut previous_rounds = AHashSet::new(); while !self.player1.is_empty() && !self.player2.is_empty() { if !previous_rounds.insert((self.player1.clone(), self.player2.clone())) { self.winner = Some(Player::Player1); retu
er.unwrap() } else if card1 > card2 { Player::Player1 } else { Player::Player2 }; match winner { Player::Player1 => { self.player1.push_back(card1); self.player1.push_back(card2); } Player::Player2 => { self.player2.push_back(card2); self.player2.push_back(card1); } } } self.winner = if self.player2.is_empty() { Some(Player::Player1) } else { Some(Player::Player2) } } pub fn winning_score(&self) -> Option<u64> { let winning_deck = self.winner.map(|p| match p { Player::Player1 => &self.player1, Player::Player2 => &self.player2, })?; let length = winning_deck.len(); Some( winning_deck .iter() .enumerate() .map(|(i, card)| card * ((length - i) as u64)) .sum(), ) } } fn run() -> Result<(), Box<dyn Error>> { let mut game1 = { let path = ["data", "day22", "input.txt"].iter().collect::<PathBuf>(); Game::load(path)? }; let mut game2 = game1.clone(); game1.play(); println!("Part 1: score = {}", game1.winning_score().unwrap()); game2.play_recursive(); println!("Part 2: score = {}", game2.winning_score().unwrap()); Ok(()) } fn main() { std::process::exit(match run() { Ok(_) => 0, Err(e) => { eprintln!("Error occurred: {}", e); 1 } }); } #[cfg(test)] mod test { use super::{Game, Player}; #[test] fn part1_test() { let mut game = Game::new( [9, 2, 6, 3, 1].iter().copied().collect(), [5, 8, 4, 7, 10].iter().copied().collect(), ); game.play(); let result = game.winning_score(); assert_eq!(result, Some(306)); } #[test] fn part2_test() { let mut game = Game::new( [9, 2, 6, 3, 1].iter().copied().collect(), [5, 8, 4, 7, 10].iter().copied().collect(), ); game.play_recursive(); assert!(matches!(game.winner, Some(Player::Player2))); let result = game.winning_score(); assert_eq!(result, Some(291)); } }
rn; } let card1 = self.player1.pop_front().unwrap(); let card2 = self.player2.pop_front().unwrap(); let winner = if self.player1.len() as u64 >= card1 && self.player2.len() as u64 >= card2 { let mut sub_game = Self::new( self.player1.iter().take(card1 as usize).copied().collect(), self.player2.iter().take(card2 as usize).copied().collect(), ); sub_game.play_recursive(); sub_game.winn
random
[ { "content": "fn part2(lines: impl Iterator<Item = impl AsRef<str>> + Clone) {\n\n let result = SLOPES\n\n .iter()\n\n .map(|&(right_step, down_step)| count_trees(lines.clone(), right_step, down_step))\n\n .product::<u32>();\n\n println!(\"Part 2: product is {}\", result);\n\n}\n\n\n"...
Rust
jvmkill/src/heap/types.rs
cloudfoundry/jvmkill
d1d7f104f94227e3c97166b633ec3ddb8e6c39fe
/* * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use crate::bindings::jlong; use crate::jvmti::JVMTI; pub struct Types<'t, J: JVMTI> { jvmti: &'t J, types: Vec<String>, } impl<'t, J: JVMTI> Types<'t, J> { pub fn new(jvmti: &'t J) -> Self { return Self { jvmti, types: Vec::new() }; } pub fn get(&self, tag: jlong) -> &String { return &self.types[tag as usize]; } pub fn tag_classes(&mut self) { for c in self.jvmti.get_loaded_classes() { self.jvmti.set_tag(c, self.types.len() as jlong); let (signature, _) = self.jvmti.get_class_signature(c); self.types.push(signature); } } } #[cfg(test)] mod tests { use std::ptr; use mockall::Sequence; use crate::bindings::jclass; use crate::heap::Types; use crate::jvmti::{ArrayPointerLoadedClassesIterator, MockJVMTI}; #[test] fn tag_classes_and_get() { let mut jvmti = MockJVMTI::new(); let mut seq = Sequence::new(); let classes = jni_type!(3, jclass) as *mut jclass; let loaded_classes = ArrayPointerLoadedClassesIterator { count: 3, classes }; jvmti .expect_get_loaded_classes() .times(1) .in_sequence(&mut seq) .return_once_st(move || loaded_classes); jvmti .expect_set_tag() .withf_st(move |&a_class, &a_tag| { ptr::eq(a_class, classes) && a_tag == 0 }) .times(1) .in_sequence(&mut seq) .return_const(()); jvmti .expect_get_class_signature() .withf_st(move |&a_class| ptr::eq(a_class, classes)) .times(1) .in_sequence(&mut seq) .return_const((String::from("alpha-type"), String::from("alpha-generic"))); jvmti .expect_set_tag() .withf_st(move |&a_class, &a_tag| { ptr::eq(a_class, unsafe { classes.offset(1) }) && a_tag == 1 }) .times(1) .in_sequence(&mut seq) .return_const(()); jvmti .expect_get_class_signature() .withf_st(move |&a_class| ptr::eq(a_class, unsafe { classes.offset(1) })) .times(1) .in_sequence(&mut seq) .return_const((String::from("bravo-type"), String::from("bravo-generic"))); jvmti .expect_set_tag() .withf_st(move |&a_class, &a_tag| { ptr::eq(a_class, unsafe { classes.offset(2) }) && a_tag == 2 }) .times(1) .in_sequence(&mut seq) .return_const(()); jvmti .expect_get_class_signature() .withf_st(move |&a_class| ptr::eq(a_class, unsafe { classes.offset(2) })) .times(1) .in_sequence(&mut seq) .return_const((String::from("charlie-type"), String::from("charlie-generic"))); let mut t = Types::new(&mut jvmti); t.tag_classes(); assert_eq!(t.get(0), "alpha-type"); assert_eq!(t.get(1), "bravo-type"); assert_eq!(t.get(2), "charlie-type"); } }
/* * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use crate::bindings::jlong; use crate::jvmti::JVMTI; pub struct Types<'t, J: JVMTI> { jvmti: &'t J, types: Vec<String>, } impl<'t, J: JVMTI> Types<'t, J> { pub fn new(jvmti: &'t J) -> Self { return Self { jvmti, types: Vec::new() }; } pub fn get(&self, tag: jlong) -> &String { return &self.types[tag as usize]; } pub fn tag_classes(&mut self) { for c in self.jvmti.get_loaded_classes() { self.jvmti.set_tag(c, self.types.len() as jlong); let (signature, _) = self.jvmti.get_class_signature(c); self.types.push(signature); } } } #[cfg(test)] mod tests { use std::ptr; use mockall::Sequence; use crate::bindings::jclass; use crate::heap::Types; use crate::jvmti::{ArrayPointerLoadedClassesIterator, MockJVMTI}; #[test] fn tag_classes_and_get() { let mut jvmti = MockJVMTI::new(); let mut seq = Sequence::new(); let classes = jni_type!(3, jclass) as *mut jclass; let loaded_classes = ArrayPointerLoadedClassesIterator { count: 3, classes }; jvmti .expect_get_loaded_classes() .times(1) .in_sequence(&mut seq) .return_once_st(move || loaded_classes); jvmti .expect_set_tag() .withf_st(move |&a_class, &a_tag| { ptr::eq(a_class, classes) && a_tag == 0 }) .times(1) .in_sequence(&mut seq) .return_const(()); jvmti .expect_get_class_signature() .withf_st(move |&a_class| ptr::eq(a_class, classes)) .times(1) .in_sequence(&mut
unsafe { classes.offset(1) })) .times(1) .in_sequence(&mut seq) .return_const((String::from("bravo-type"), String::from("bravo-generic"))); jvmti .expect_set_tag() .withf_st(move |&a_class, &a_tag| { ptr::eq(a_class, unsafe { classes.offset(2) }) && a_tag == 2 }) .times(1) .in_sequence(&mut seq) .return_const(()); jvmti .expect_get_class_signature() .withf_st(move |&a_class| ptr::eq(a_class, unsafe { classes.offset(2) })) .times(1) .in_sequence(&mut seq) .return_const((String::from("charlie-type"), String::from("charlie-generic"))); let mut t = Types::new(&mut jvmti); t.tag_classes(); assert_eq!(t.get(0), "alpha-type"); assert_eq!(t.get(1), "bravo-type"); assert_eq!(t.get(2), "charlie-type"); } }
seq) .return_const((String::from("alpha-type"), String::from("alpha-generic"))); jvmti .expect_set_tag() .withf_st(move |&a_class, &a_tag| { ptr::eq(a_class, unsafe { classes.offset(1) }) && a_tag == 1 }) .times(1) .in_sequence(&mut seq) .return_const(()); jvmti .expect_get_class_signature() .withf_st(move |&a_class| ptr::eq(a_class,
function_block-random_span
[ { "content": "#[test]\n\nfn time_10_count_2() {\n\n let r = Runner {\n\n class: \"org.cloudfoundry.jvmkill.ThreadExhaustion\",\n\n arguments: \"=time=10,count=2,printHeapHistogram=0,printMemoryUsage=0\",\n\n std_out: vec!(),\n\n std_err: vec!(\n\n \"Resource Exhausted! ...
Rust
src/round.rs
xoac/chrono
37fb8005f196e9e67629d28c0ae84a3b9d31926a
use oldtime::Duration; use std::ops::{Add, Sub}; use Timelike; pub trait SubsecRound { fn round_subsecs(self, digits: u16) -> Self; fn trunc_subsecs(self, digits: u16) -> Self; } impl<T> SubsecRound for T where T: Timelike + Add<Duration, Output = T> + Sub<Duration, Output = T>, { fn round_subsecs(self, digits: u16) -> T { let span = span_for_digits(digits); let delta_down = self.nanosecond() % span; if delta_down > 0 { let delta_up = span - delta_down; if delta_up <= delta_down { self + Duration::nanoseconds(delta_up.into()) } else { self - Duration::nanoseconds(delta_down.into()) } } else { self } } fn trunc_subsecs(self, digits: u16) -> T { let span = span_for_digits(digits); let delta_down = self.nanosecond() % span; if delta_down > 0 { self - Duration::nanoseconds(delta_down.into()) } else { self } } } fn span_for_digits(digits: u16) -> u32 { match digits { 0 => 1_000_000_000, 1 => 100_000_000, 2 => 10_000_000, 3 => 1_000_000, 4 => 100_000, 5 => 10_000, 6 => 1_000, 7 => 100, 8 => 10, _ => 1, } } #[cfg(test)] mod tests { use super::SubsecRound; use offset::{FixedOffset, TimeZone, Utc}; use Timelike; #[test] fn test_round() { let pst = FixedOffset::east(8 * 60 * 60); let dt = pst.ymd(2018, 1, 11).and_hms_nano(10, 5, 13, 084_660_684); assert_eq!(dt.round_subsecs(10), dt); assert_eq!(dt.round_subsecs(9), dt); assert_eq!(dt.round_subsecs(8).nanosecond(), 084_660_680); assert_eq!(dt.round_subsecs(7).nanosecond(), 084_660_700); assert_eq!(dt.round_subsecs(6).nanosecond(), 084_661_000); assert_eq!(dt.round_subsecs(5).nanosecond(), 084_660_000); assert_eq!(dt.round_subsecs(4).nanosecond(), 084_700_000); assert_eq!(dt.round_subsecs(3).nanosecond(), 085_000_000); assert_eq!(dt.round_subsecs(2).nanosecond(), 080_000_000); assert_eq!(dt.round_subsecs(1).nanosecond(), 100_000_000); assert_eq!(dt.round_subsecs(0).nanosecond(), 0); assert_eq!(dt.round_subsecs(0).second(), 13); let dt = Utc.ymd(2018, 1, 11).and_hms_nano(10, 5, 27, 750_500_000); assert_eq!(dt.round_subsecs(9), dt); assert_eq!(dt.round_subsecs(4), dt); assert_eq!(dt.round_subsecs(3).nanosecond(), 751_000_000); assert_eq!(dt.round_subsecs(2).nanosecond(), 750_000_000); assert_eq!(dt.round_subsecs(1).nanosecond(), 800_000_000); assert_eq!(dt.round_subsecs(0).nanosecond(), 0); assert_eq!(dt.round_subsecs(0).second(), 28); } #[test] fn test_round_leap_nanos() { let dt = Utc .ymd(2016, 12, 31) .and_hms_nano(23, 59, 59, 1_750_500_000); assert_eq!(dt.round_subsecs(9), dt); assert_eq!(dt.round_subsecs(4), dt); assert_eq!(dt.round_subsecs(2).nanosecond(), 1_750_000_000); assert_eq!(dt.round_subsecs(1).nanosecond(), 1_800_000_000); assert_eq!(dt.round_subsecs(1).second(), 59); assert_eq!(dt.round_subsecs(0).nanosecond(), 0); assert_eq!(dt.round_subsecs(0).second(), 0); } #[test] fn test_trunc() { let pst = FixedOffset::east(8 * 60 * 60); let dt = pst.ymd(2018, 1, 11).and_hms_nano(10, 5, 13, 084_660_684); assert_eq!(dt.trunc_subsecs(10), dt); assert_eq!(dt.trunc_subsecs(9), dt); assert_eq!(dt.trunc_subsecs(8).nanosecond(), 084_660_680); assert_eq!(dt.trunc_subsecs(7).nanosecond(), 084_660_600); assert_eq!(dt.trunc_subsecs(6).nanosecond(), 084_660_000); assert_eq!(dt.trunc_subsecs(5).nanosecond(), 084_660_000); assert_eq!(dt.trunc_subsecs(4).nanosecond(), 084_600_000); assert_eq!(dt.trunc_subsecs(3).nanosecond(), 084_000_000); assert_eq!(dt.trunc_subsecs(2).nanosecond(), 080_000_000); assert_eq!(dt.trunc_subsecs(1).nanosecond(), 0); assert_eq!(dt.trunc_subsecs(0).nanosecond(), 0); assert_eq!(dt.trunc_subsecs(0).second(), 13); let dt = pst.ymd(2018, 1, 11).and_hms_nano(10, 5, 27, 750_500_000); assert_eq!(dt.trunc_subsecs(9), dt); assert_eq!(dt.trunc_subsecs(4), dt); assert_eq!(dt.trunc_subsecs(3).nanosecond(), 750_000_000); assert_eq!(dt.trunc_subsecs(2).nanosecond(), 750_000_000); assert_eq!(dt.trunc_subsecs(1).nanosecond(), 700_000_000); assert_eq!(dt.trunc_subsecs(0).nanosecond(), 0); assert_eq!(dt.trunc_subsecs(0).second(), 27); } #[test] fn test_trunc_leap_nanos() { let dt = Utc .ymd(2016, 12, 31) .and_hms_nano(23, 59, 59, 1_750_500_000); assert_eq!(dt.trunc_subsecs(9), dt); assert_eq!(dt.trunc_subsecs(4), dt); assert_eq!(dt.trunc_subsecs(2).nanosecond(), 1_750_000_000); assert_eq!(dt.trunc_subsecs(1).nanosecond(), 1_700_000_000); assert_eq!(dt.trunc_subsecs(1).second(), 59); assert_eq!(dt.trunc_subsecs(0).nanosecond(), 1_000_000_000); assert_eq!(dt.trunc_subsecs(0).second(), 59); } }
use oldtime::Duration; use std::ops::{Add, Sub}; use Timelike; pub trait SubsecRound { fn round_subsecs(self, digits: u16) -> Self; fn trunc_subsecs(self, digits: u16) -> Self; } impl<T> SubsecRound for T where T: Timelike + Add<Duration, Output = T> + Sub<Duration, Output = T>, { fn round_subsecs(self, digits: u16) -> T { let span = span_for_digits(digits); let delta_down = self.nanosecond() % span; if delta_down > 0 { let delta_up = span - delta_down; if delta_up <= delta_down { self + Duration::nanoseconds(delta_up.into()) } else { self - Duration::nanoseconds(delta_down.into()) } } else { self } } fn trunc_subsecs(self, digits: u16) -> T { let span = span_for_digits(digits); let delta_down = self.nanosecond() % span; if delta_down > 0 { self - Duration::nanoseconds(delta_down.into()) } else { self } } } fn span_for_digits(digits: u16) -> u32 { match digits {
#[cfg(test)] mod tests { use super::SubsecRound; use offset::{FixedOffset, TimeZone, Utc}; use Timelike; #[test] fn test_round() { let pst = FixedOffset::east(8 * 60 * 60); let dt = pst.ymd(2018, 1, 11).and_hms_nano(10, 5, 13, 084_660_684); assert_eq!(dt.round_subsecs(10), dt); assert_eq!(dt.round_subsecs(9), dt); assert_eq!(dt.round_subsecs(8).nanosecond(), 084_660_680); assert_eq!(dt.round_subsecs(7).nanosecond(), 084_660_700); assert_eq!(dt.round_subsecs(6).nanosecond(), 084_661_000); assert_eq!(dt.round_subsecs(5).nanosecond(), 084_660_000); assert_eq!(dt.round_subsecs(4).nanosecond(), 084_700_000); assert_eq!(dt.round_subsecs(3).nanosecond(), 085_000_000); assert_eq!(dt.round_subsecs(2).nanosecond(), 080_000_000); assert_eq!(dt.round_subsecs(1).nanosecond(), 100_000_000); assert_eq!(dt.round_subsecs(0).nanosecond(), 0); assert_eq!(dt.round_subsecs(0).second(), 13); let dt = Utc.ymd(2018, 1, 11).and_hms_nano(10, 5, 27, 750_500_000); assert_eq!(dt.round_subsecs(9), dt); assert_eq!(dt.round_subsecs(4), dt); assert_eq!(dt.round_subsecs(3).nanosecond(), 751_000_000); assert_eq!(dt.round_subsecs(2).nanosecond(), 750_000_000); assert_eq!(dt.round_subsecs(1).nanosecond(), 800_000_000); assert_eq!(dt.round_subsecs(0).nanosecond(), 0); assert_eq!(dt.round_subsecs(0).second(), 28); } #[test] fn test_round_leap_nanos() { let dt = Utc .ymd(2016, 12, 31) .and_hms_nano(23, 59, 59, 1_750_500_000); assert_eq!(dt.round_subsecs(9), dt); assert_eq!(dt.round_subsecs(4), dt); assert_eq!(dt.round_subsecs(2).nanosecond(), 1_750_000_000); assert_eq!(dt.round_subsecs(1).nanosecond(), 1_800_000_000); assert_eq!(dt.round_subsecs(1).second(), 59); assert_eq!(dt.round_subsecs(0).nanosecond(), 0); assert_eq!(dt.round_subsecs(0).second(), 0); } #[test] fn test_trunc() { let pst = FixedOffset::east(8 * 60 * 60); let dt = pst.ymd(2018, 1, 11).and_hms_nano(10, 5, 13, 084_660_684); assert_eq!(dt.trunc_subsecs(10), dt); assert_eq!(dt.trunc_subsecs(9), dt); assert_eq!(dt.trunc_subsecs(8).nanosecond(), 084_660_680); assert_eq!(dt.trunc_subsecs(7).nanosecond(), 084_660_600); assert_eq!(dt.trunc_subsecs(6).nanosecond(), 084_660_000); assert_eq!(dt.trunc_subsecs(5).nanosecond(), 084_660_000); assert_eq!(dt.trunc_subsecs(4).nanosecond(), 084_600_000); assert_eq!(dt.trunc_subsecs(3).nanosecond(), 084_000_000); assert_eq!(dt.trunc_subsecs(2).nanosecond(), 080_000_000); assert_eq!(dt.trunc_subsecs(1).nanosecond(), 0); assert_eq!(dt.trunc_subsecs(0).nanosecond(), 0); assert_eq!(dt.trunc_subsecs(0).second(), 13); let dt = pst.ymd(2018, 1, 11).and_hms_nano(10, 5, 27, 750_500_000); assert_eq!(dt.trunc_subsecs(9), dt); assert_eq!(dt.trunc_subsecs(4), dt); assert_eq!(dt.trunc_subsecs(3).nanosecond(), 750_000_000); assert_eq!(dt.trunc_subsecs(2).nanosecond(), 750_000_000); assert_eq!(dt.trunc_subsecs(1).nanosecond(), 700_000_000); assert_eq!(dt.trunc_subsecs(0).nanosecond(), 0); assert_eq!(dt.trunc_subsecs(0).second(), 27); } #[test] fn test_trunc_leap_nanos() { let dt = Utc .ymd(2016, 12, 31) .and_hms_nano(23, 59, 59, 1_750_500_000); assert_eq!(dt.trunc_subsecs(9), dt); assert_eq!(dt.trunc_subsecs(4), dt); assert_eq!(dt.trunc_subsecs(2).nanosecond(), 1_750_000_000); assert_eq!(dt.trunc_subsecs(1).nanosecond(), 1_700_000_000); assert_eq!(dt.trunc_subsecs(1).second(), 59); assert_eq!(dt.trunc_subsecs(0).nanosecond(), 1_000_000_000); assert_eq!(dt.trunc_subsecs(0).second(), 59); } }
0 => 1_000_000_000, 1 => 100_000_000, 2 => 10_000_000, 3 => 1_000_000, 4 => 100_000, 5 => 10_000, 6 => 1_000, 7 => 100, 8 => 10, _ => 1, } }
function_block-function_prefix_line
[ { "content": "pub fn cycle_to_yo(cycle: u32) -> (u32, u32) {\n\n let (mut year_mod_400, mut ordinal0) = div_rem(cycle, 365);\n\n let delta = u32::from(YEAR_DELTAS[year_mod_400 as usize]);\n\n if ordinal0 < delta {\n\n year_mod_400 -= 1;\n\n ordinal0 += 365 - u32::from(YEAR_DELTAS[year_mod...
Rust
src/reader.rs
sayantangkhan/oxyscheme
742da72abbd719bf66898e46bd3913191f3d00fb
use crate::lexer::*; use crate::parser::{parse_datum, Datum}; use crate::*; use anyhow::Result; use std::{ fs::File, io::{BufRead, BufReader, Lines}, iter::{Enumerate, Peekable}, path::PathBuf, }; pub struct FileLexer { file: File, } impl FileLexer { pub fn new(filename: &str) -> Result<Self, CompilerError> { Ok(FileLexer { file: File::open(PathBuf::from(filename))?, }) } } impl IntoIterator for FileLexer { type Item = Result<TokenWithPosition, CompilerError>; type IntoIter = FileLexerIntoIter; fn into_iter(self) -> Self::IntoIter { let line_enumerator = BufReader::new(self.file).lines().enumerate(); let input_string = String::from(""); FileLexerIntoIter { line_enumerator, input_string, cursor_position: 0, line_number: 0, encountered_error: false, } } } pub struct FileLexerIntoIter { line_enumerator: Enumerate<Lines<BufReader<File>>>, input_string: String, cursor_position: usize, line_number: usize, encountered_error: bool, } impl Iterator for FileLexerIntoIter { type Item = Result<TokenWithPosition, CompilerError>; fn next(&mut self) -> Option<Self::Item> { if self.encountered_error { return None; } while self.input_string.len() <= self.cursor_position { if let Some((index, line_res)) = self.line_enumerator.next() { match line_res { Ok(line) => { self.input_string = line; self.cursor_position = 0; self.line_number = index + 1; } Err(e) => { self.encountered_error = true; return Some(Err(CompilerError::IOError(e))); } } } else { return None; } } match lex_input(&self.input_string[self.cursor_position..]) { Ok((leftover, parsed)) => { let token_with_position = TokenWithPosition { token: parsed, line: self.line_number, column: self.cursor_position, }; self.cursor_position = self.input_string.len() - leftover.len(); Some(Ok(token_with_position)) } Err(_) => { self.encountered_error = true; Some(Err(CompilerError::LexError( String::from(&self.input_string[self.cursor_position..]), self.line_number, self.cursor_position, ))) } } } } pub struct DatumIterator<I> where I: Iterator<Item = Result<TokenWithPosition, CompilerError>>, { token_stream: Peekable<I>, encountered_error: bool, } impl<I> DatumIterator<I> where I: Iterator<Item = Result<TokenWithPosition, CompilerError>>, { pub fn new(token_stream: I) -> Self { DatumIterator { token_stream: token_stream.peekable(), encountered_error: false, } } } impl<I> Iterator for DatumIterator<I> where I: Iterator<Item = Result<TokenWithPosition, CompilerError>>, { type Item = Result<Datum, CompilerError>; fn next(&mut self) -> Option<Self::Item> { if self.encountered_error { return None; } self.token_stream.peek()?; let datum_res = parse_datum(&mut self.token_stream); if datum_res.is_err() { self.encountered_error = true; } Some(datum_res) } }
use crate::lexer::*; use crate::parser::{parse_datum, Datum}; use crate::*; use anyhow::Result; use std::{ fs::File, io::{BufRead, BufReader, Lines}, iter::{Enumerate, Peekable}, path::PathBuf, }; pub struct FileLexer { file: File, } impl FileLexer { pub fn new(filename: &str) -> Result<Self, CompilerError> { Ok(FileLexer { file: File::open(PathBuf::from(filename))?, }) } } impl IntoIterator for FileLexer { type Item = Result<TokenWithPosition, CompilerError>; type IntoIter = FileLexerIntoIter; fn into_iter(self) -> Self::IntoIter { let line_enumerator = BufReader::new(self.file).lines().enumerate(); let input_string = String::from(""); FileLexerIntoIter { line_enumerator, input_string, cursor_position: 0, line_number: 0, encountered_error: false, } } } pub struct FileLexerIntoIter { line_enumerator: Enumerate<Lines<BufReader<File>>>, input_string: String, cursor_position: usize, line_number: usize, encountered_error: bool, } impl Iterator for FileLexerIntoIter { type Item = Result<TokenWithPosition, CompilerError>; fn next(&mut self) -> Option<Self::Item> { if self.encountered_error { return None; } while self.input_string.len() <= self.cursor_position { if let Some((index, line_res)) = self.line_enumerator.next() { match line_res { Ok(line) => { self.input_string = line; self.cursor_position = 0; self.line_number = index + 1; } Err(e) => { self.encountered_error = true; return Some(Err(CompilerError::IOError(e))); } } } else { return None; } } match lex_input(&self.input_string[self.cursor_position..]) { Ok((leftover, parsed)) => { let token_with_position = TokenWithPosition { token: parsed, line: self.line_number, column: self.cursor_position, }; self.cursor_position = self.input_string.len() - leftover.len(); Some(Ok(token_with_position)) } Err(_) => { self.encountered_error = true; Some(
) } } } } pub struct DatumIterator<I> where I: Iterator<Item = Result<TokenWithPosition, CompilerError>>, { token_stream: Peekable<I>, encountered_error: bool, } impl<I> DatumIterator<I> where I: Iterator<Item = Result<TokenWithPosition, CompilerError>>, { pub fn new(token_stream: I) -> Self { DatumIterator { token_stream: token_stream.peekable(), encountered_error: false, } } } impl<I> Iterator for DatumIterator<I> where I: Iterator<Item = Result<TokenWithPosition, CompilerError>>, { type Item = Result<Datum, CompilerError>; fn next(&mut self) -> Option<Self::Item> { if self.encountered_error { return None; } self.token_stream.peek()?; let datum_res = parse_datum(&mut self.token_stream); if datum_res.is_err() { self.encountered_error = true; } Some(datum_res) } }
Err(CompilerError::LexError( String::from(&self.input_string[self.cursor_position..]), self.line_number, self.cursor_position, ))
call_expression
[ { "content": "/// Parses a single `Datum` from the token stream\n\npub fn parse_datum<I>(token_stream: &mut Peekable<I>) -> Result<Datum, CompilerError>\n\nwhere\n\n I: Iterator<Item = Result<TokenWithPosition, CompilerError>>,\n\n{\n\n match token_stream.peek() {\n\n Some(Ok(TokenWithPosition {\n\...
Rust
src/storage/assembler.rs
ProgVal/smoltcp
1bde6e7ec45684019f191714c158e2f496eb49d0
use core::fmt; #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct Contig { hole_size: usize, data_size: usize } impl fmt::Display for Contig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.has_hole() { write!(f, "({})", self.hole_size)?; } if self.has_hole() && self.has_data() { write!(f, " ")?; } if self.has_data() { write!(f, "{}", self.data_size)?; } Ok(()) } } impl Contig { fn empty() -> Contig { Contig { hole_size: 0, data_size: 0 } } fn hole(size: usize) -> Contig { Contig { hole_size: size, data_size: 0 } } fn hole_and_data(hole_size: usize, data_size: usize) -> Contig { Contig { hole_size, data_size } } fn has_hole(&self) -> bool { self.hole_size != 0 } fn has_data(&self) -> bool { self.data_size != 0 } fn total_size(&self) -> usize { self.hole_size + self.data_size } fn is_empty(&self) -> bool { self.total_size() == 0 } fn expand_data_by(&mut self, size: usize) { self.data_size += size; } fn shrink_hole_by(&mut self, size: usize) { self.hole_size -= size; } fn shrink_hole_to(&mut self, size: usize) { debug_assert!(self.hole_size >= size); let total_size = self.total_size(); self.hole_size = size; self.data_size = total_size - size; } } const CONTIG_COUNT: usize = 4; #[derive(Debug)] #[cfg_attr(test, derive(PartialEq, Eq))] pub struct Assembler { contigs: [Contig; CONTIG_COUNT] } impl fmt::Display for Assembler { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[ ")?; for contig in self.contigs.iter() { if contig.is_empty() { break } write!(f, "{} ", contig)?; } write!(f, "]")?; Ok(()) } } impl Assembler { pub fn new(size: usize) -> Assembler { let mut contigs = [Contig::empty(); CONTIG_COUNT]; contigs[0] = Contig::hole(size); Assembler { contigs } } #[allow(dead_code)] pub(crate) fn total_size(&self) -> usize { self.contigs .iter() .map(|contig| contig.total_size()) .sum() } fn front(&self) -> Contig { self.contigs[0] } fn back(&self) -> Contig { self.contigs[self.contigs.len() - 1] } pub fn is_empty(&self) -> bool { !self.front().has_data() } fn remove_contig_at(&mut self, at: usize) -> &mut Contig { debug_assert!(!self.contigs[at].is_empty()); for i in at..self.contigs.len() - 1 { self.contigs[i] = self.contigs[i + 1]; if !self.contigs[i].has_data() { self.contigs[i + 1] = Contig::empty(); return &mut self.contigs[i] } } self.contigs[at] = Contig::empty(); &mut self.contigs[at] } fn add_contig_at(&mut self, at: usize) -> Result<&mut Contig, ()> { debug_assert!(!self.contigs[at].is_empty()); if !self.back().is_empty() { return Err(()) } for i in (at + 1..self.contigs.len()).rev() { self.contigs[i] = self.contigs[i - 1]; } self.contigs[at] = Contig::empty(); Ok(&mut self.contigs[at]) } pub fn add(&mut self, mut offset: usize, mut size: usize) -> Result<(), ()> { let mut index = 0; while index != self.contigs.len() && size != 0 { let contig = self.contigs[index]; if offset >= contig.total_size() { index += 1; } else if offset == 0 && size >= contig.hole_size && index > 0 { self.contigs[index - 1].expand_data_by(contig.total_size()); self.remove_contig_at(index); index += 0; } else if offset == 0 && size < contig.hole_size && index > 0 { self.contigs[index - 1].expand_data_by(size); self.contigs[index].shrink_hole_by(size); index += 1; } else if offset <= contig.hole_size && offset + size >= contig.hole_size { self.contigs[index].shrink_hole_to(offset); index += 1; } else if offset + size >= contig.hole_size { index += 1; } else if offset + size < contig.hole_size { self.contigs[index].shrink_hole_by(offset + size); let inserted = self.add_contig_at(index)?; *inserted = Contig::hole_and_data(offset, size); index += 2; } else { unreachable!() } if offset >= contig.total_size() { offset = offset.saturating_sub(contig.total_size()); } else { size = (offset + size).saturating_sub(contig.total_size()); offset = 0; } } debug_assert!(size == 0); Ok(()) } pub fn remove_front(&mut self) -> Option<usize> { let front = self.front(); if front.has_hole() { None } else { let last_hole = self.remove_contig_at(0); last_hole.hole_size += front.data_size; debug_assert!(front.data_size > 0); Some(front.data_size) } } } #[cfg(test)] mod test { use std::vec::Vec; use super::*; impl From<Vec<(usize, usize)>> for Assembler { fn from(vec: Vec<(usize, usize)>) -> Assembler { let mut contigs = [Contig::empty(); CONTIG_COUNT]; for (i, &(hole_size, data_size)) in vec.iter().enumerate() { contigs[i] = Contig { hole_size, data_size }; } Assembler { contigs } } } macro_rules! contigs { [$( $x:expr ),*] => ({ Assembler::from(vec![$( $x ),*]) }) } #[test] fn test_new() { let assr = Assembler::new(16); assert_eq!(assr.total_size(), 16); assert_eq!(assr, contigs![(16, 0)]); } #[test] fn test_empty_add_full() { let mut assr = Assembler::new(16); assert_eq!(assr.add(0, 16), Ok(())); assert_eq!(assr, contigs![(0, 16)]); } #[test] fn test_empty_add_front() { let mut assr = Assembler::new(16); assert_eq!(assr.add(0, 4), Ok(())); assert_eq!(assr, contigs![(0, 4), (12, 0)]); } #[test] fn test_empty_add_back() { let mut assr = Assembler::new(16); assert_eq!(assr.add(12, 4), Ok(())); assert_eq!(assr, contigs![(12, 4)]); } #[test] fn test_empty_add_mid() { let mut assr = Assembler::new(16); assert_eq!(assr.add(4, 8), Ok(())); assert_eq!(assr, contigs![(4, 8), (4, 0)]); } #[test] fn test_partial_add_front() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(0, 4), Ok(())); assert_eq!(assr, contigs![(0, 12), (4, 0)]); } #[test] fn test_partial_add_back() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(12, 4), Ok(())); assert_eq!(assr, contigs![(4, 12)]); } #[test] fn test_partial_add_front_overlap() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(0, 8), Ok(())); assert_eq!(assr, contigs![(0, 12), (4, 0)]); } #[test] fn test_partial_add_front_overlap_split() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(2, 6), Ok(())); assert_eq!(assr, contigs![(2, 10), (4, 0)]); } #[test] fn test_partial_add_back_overlap() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(8, 8), Ok(())); assert_eq!(assr, contigs![(4, 12)]); } #[test] fn test_partial_add_back_overlap_split() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(10, 4), Ok(())); assert_eq!(assr, contigs![(4, 10), (2, 0)]); } #[test] fn test_partial_add_both_overlap() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(0, 16), Ok(())); assert_eq!(assr, contigs![(0, 16)]); } #[test] fn test_partial_add_both_overlap_split() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(2, 12), Ok(())); assert_eq!(assr, contigs![(2, 12), (2, 0)]); } #[test] fn test_empty_remove_front() { let mut assr = contigs![(12, 0)]; assert_eq!(assr.remove_front(), None); } #[test] fn test_trailing_hole_remove_front() { let mut assr = contigs![(0, 4), (8, 0)]; assert_eq!(assr.remove_front(), Some(4)); assert_eq!(assr, contigs![(12, 0)]); } #[test] fn test_trailing_data_remove_front() { let mut assr = contigs![(0, 4), (4, 4)]; assert_eq!(assr.remove_front(), Some(4)); assert_eq!(assr, contigs![(4, 4), (4, 0)]); } }
use core::fmt; #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct Contig { hole_size: usize, data_size: usize } impl fmt::Display for Contig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.has_hole() { write!(f, "({})", self.hole_size)?; } if self.has_hole() && self.has_data() { write!(f, " ")?; } if self.has_data() { write!(f, "{}", self.data_size)?; } Ok(()) } } impl Contig { fn empty() -> Contig { Contig { hole_size: 0, data_size: 0 } } fn hole(size: usize) -> Contig { Contig { hole_size: size, data_size: 0 } } fn hole_and_data(hole_size: usize, data_size: usize) -> Contig { Contig { hole_size, data_size } } fn has_hole(&self) -> bool { self.hole_size != 0 } fn has_data(&self) -> bool { self.data_size != 0 } fn total_size(&self) -> usize { self.hole_size + self.data_size } fn is_empty(&self) -> bool { self.total_size() == 0 } fn expand_data_by(&mut self, size: usize) { self.data_size += size; } fn shrink_hole_by(&mut self, size: usize) { self.hole_size -= size; } fn shrink_hole_to(&mut self, size: usize) { debug_assert!(self.hole_size >= size); let total_size = self.total_size(); self.hole_size = size; self.data_size = total_size - size; } } const CONTIG_COUNT: usize = 4; #[derive(Debug)] #[cfg_attr(test, derive(PartialEq, Eq))] pub struct Assembler { contigs: [Contig; CONTIG_COUNT] } impl fmt::Display for Assembler { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[ ")?; for contig in self.contigs.iter() { if contig.is_empty() { break } write!(f, "{} ", contig)?; } write!(f, "]")?; Ok(()) } } impl Assembler { pub fn new(size: usize) -> Assembler { let mut contigs = [Contig::empty(); CONTIG_COUNT]; contigs[0] = Contig::hole(size); Assembler { contigs } } #[allow(dead_code)] pub(crate) fn total_size(&self) -> usize { self.contigs .iter() .map(|contig| contig.total_size()) .sum() } fn front(&self) -> Contig { self.contigs[0] } fn back(&self) -> Contig { self.contigs[self.contigs.len() - 1] } pub fn is_empty(&self) -> bool { !self.front().has_data() } fn remove_contig_at(&mut self, at: usize) -> &mut Contig { debug_assert!(!self.contigs[at].is_empty()); for i in at..self.contigs.len() - 1 { self.contigs[i] = self.contigs[i + 1]; if !self.contigs[i].has_data() { self.contigs[i + 1] = Contig::empty(); return &mut self.contigs[i] } } self.contigs[at] = Contig::empty(); &mut self.contigs[at] } fn add_contig_at(&mut self, at: usize) -> Result<&mut Contig, ()> { debug_assert!(!self.contigs[at].is_empty()); if !self.back().is_empty() { return Err(()) } for i in (at + 1..self.contigs.len()).rev() { self.contigs[i] = self.contigs[i - 1]; } self.contigs[at] = Contig::empty(); Ok(&mut self.contigs[at]) } pub fn add(&mut self, mut offset: usize, mut size: usize) -> Result<(), ()> { let mut index = 0; while index != self.contigs.len() && size != 0 { let contig = self.contigs[index]; if offset >= contig.total_size() { index += 1; } else if offset == 0 && size >= contig.hole_size && index > 0 { self.contigs[index - 1].expand_data_by(contig.total_size()); self.remove_contig_at(index); index += 0; } else if offset == 0 && size < contig.hole_size && index > 0 { self.contigs[index - 1].expand_data_by(size); self.contigs[index].shrink_hole_by(size); index += 1; } else
if offset >= contig.total_size() { offset = offset.saturating_sub(contig.total_size()); } else { size = (offset + size).saturating_sub(contig.total_size()); offset = 0; } } debug_assert!(size == 0); Ok(()) } pub fn remove_front(&mut self) -> Option<usize> { let front = self.front(); if front.has_hole() { None } else { let last_hole = self.remove_contig_at(0); last_hole.hole_size += front.data_size; debug_assert!(front.data_size > 0); Some(front.data_size) } } } #[cfg(test)] mod test { use std::vec::Vec; use super::*; impl From<Vec<(usize, usize)>> for Assembler { fn from(vec: Vec<(usize, usize)>) -> Assembler { let mut contigs = [Contig::empty(); CONTIG_COUNT]; for (i, &(hole_size, data_size)) in vec.iter().enumerate() { contigs[i] = Contig { hole_size, data_size }; } Assembler { contigs } } } macro_rules! contigs { [$( $x:expr ),*] => ({ Assembler::from(vec![$( $x ),*]) }) } #[test] fn test_new() { let assr = Assembler::new(16); assert_eq!(assr.total_size(), 16); assert_eq!(assr, contigs![(16, 0)]); } #[test] fn test_empty_add_full() { let mut assr = Assembler::new(16); assert_eq!(assr.add(0, 16), Ok(())); assert_eq!(assr, contigs![(0, 16)]); } #[test] fn test_empty_add_front() { let mut assr = Assembler::new(16); assert_eq!(assr.add(0, 4), Ok(())); assert_eq!(assr, contigs![(0, 4), (12, 0)]); } #[test] fn test_empty_add_back() { let mut assr = Assembler::new(16); assert_eq!(assr.add(12, 4), Ok(())); assert_eq!(assr, contigs![(12, 4)]); } #[test] fn test_empty_add_mid() { let mut assr = Assembler::new(16); assert_eq!(assr.add(4, 8), Ok(())); assert_eq!(assr, contigs![(4, 8), (4, 0)]); } #[test] fn test_partial_add_front() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(0, 4), Ok(())); assert_eq!(assr, contigs![(0, 12), (4, 0)]); } #[test] fn test_partial_add_back() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(12, 4), Ok(())); assert_eq!(assr, contigs![(4, 12)]); } #[test] fn test_partial_add_front_overlap() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(0, 8), Ok(())); assert_eq!(assr, contigs![(0, 12), (4, 0)]); } #[test] fn test_partial_add_front_overlap_split() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(2, 6), Ok(())); assert_eq!(assr, contigs![(2, 10), (4, 0)]); } #[test] fn test_partial_add_back_overlap() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(8, 8), Ok(())); assert_eq!(assr, contigs![(4, 12)]); } #[test] fn test_partial_add_back_overlap_split() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(10, 4), Ok(())); assert_eq!(assr, contigs![(4, 10), (2, 0)]); } #[test] fn test_partial_add_both_overlap() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(0, 16), Ok(())); assert_eq!(assr, contigs![(0, 16)]); } #[test] fn test_partial_add_both_overlap_split() { let mut assr = contigs![(4, 8), (4, 0)]; assert_eq!(assr.add(2, 12), Ok(())); assert_eq!(assr, contigs![(2, 12), (2, 0)]); } #[test] fn test_empty_remove_front() { let mut assr = contigs![(12, 0)]; assert_eq!(assr.remove_front(), None); } #[test] fn test_trailing_hole_remove_front() { let mut assr = contigs![(0, 4), (8, 0)]; assert_eq!(assr.remove_front(), Some(4)); assert_eq!(assr, contigs![(12, 0)]); } #[test] fn test_trailing_data_remove_front() { let mut assr = contigs![(0, 4), (4, 4)]; assert_eq!(assr.remove_front(), Some(4)); assert_eq!(assr, contigs![(4, 4), (4, 0)]); } }
if offset <= contig.hole_size && offset + size >= contig.hole_size { self.contigs[index].shrink_hole_to(offset); index += 1; } else if offset + size >= contig.hole_size { index += 1; } else if offset + size < contig.hole_size { self.contigs[index].shrink_hole_by(offset + size); let inserted = self.add_contig_at(index)?; *inserted = Contig::hole_and_data(offset, size); index += 2; } else { unreachable!() }
if_condition
[ { "content": "pub fn parse_middleware_options<D>(matches: &mut Matches, device: D, loopback: bool)\n\n -> FaultInjector<EthernetTracer<PcapWriter<D, Rc<PcapSink>>>>\n\n where D: for<'a> Device<'a>\n\n{\n\n let drop_chance = matches.opt_str(\"drop-chance\").map(|s| u8::from_str(&s).unwrap())\n\...
Rust
src/serde/mod.rs
soenkehahn/time
1860b1482e96e3973fbad634739eb21c5bc0190d
pub mod timestamp; use serde::de::Error as _; #[cfg(feature = "serde-human-readable")] use serde::ser::Error as _; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::error::ComponentRange; #[cfg(feature = "serde-human-readable")] use crate::{ error, format_description::{modifier, Component, FormatItem}, }; use crate::{Date, Duration, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset, Weekday}; #[cfg(feature = "serde-human-readable")] const DATE_FORMAT: &[FormatItem<'_>] = &[ FormatItem::Component(Component::Year(modifier::Year { repr: modifier::YearRepr::Full, iso_week_based: false, sign_is_mandatory: false, padding: modifier::Padding::Zero, })), FormatItem::Literal(b"-"), FormatItem::Component(Component::Month(modifier::Month { repr: modifier::MonthRepr::Numerical, padding: modifier::Padding::Zero, })), FormatItem::Literal(b"-"), FormatItem::Component(Component::Day(modifier::Day { padding: modifier::Padding::Zero, })), ]; impl Serialize for Date { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { #[cfg(feature = "serde-human-readable")] if serializer.is_human_readable() { return serializer.serialize_str(&match self.format(&DATE_FORMAT) { Ok(s) => s, Err(_) => return Err(S::Error::custom("failed formatting `Date`")), }); } (self.year(), self.ordinal()).serialize(serializer) } } impl<'a> Deserialize<'a> for Date { fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> { #[cfg(feature = "serde-human-readable")] if deserializer.is_human_readable() { return Self::parse(<&str>::deserialize(deserializer)?, &DATE_FORMAT) .map_err(error::Parse::to_invalid_serde_value::<D>); } let (year, ordinal) = Deserialize::deserialize(deserializer)?; Self::from_ordinal_date(year, ordinal).map_err(ComponentRange::to_invalid_serde_value::<D>) } } impl Serialize for Duration { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { #[cfg(feature = "serde-human-readable")] if serializer.is_human_readable() { return serializer.collect_str(&format_args!( "{}.{:>09}", self.whole_seconds(), self.subsec_nanoseconds().abs() )); } (self.whole_seconds(), self.subsec_nanoseconds()).serialize(serializer) } } impl<'a> Deserialize<'a> for Duration { fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> { #[cfg(feature = "serde-human-readable")] if deserializer.is_human_readable() { let s = <&str>::deserialize(deserializer)?; let dot = s.find('.').ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Str(s), &"a decimal point") })?; let (seconds, nanoseconds) = s.split_at(dot); let nanoseconds = &nanoseconds[1..]; let seconds = seconds.parse().map_err(|_| { serde::de::Error::invalid_value(serde::de::Unexpected::Str(seconds), &"a number") })?; let mut nanoseconds = nanoseconds.parse().map_err(|_| { serde::de::Error::invalid_value( serde::de::Unexpected::Str(nanoseconds), &"a number", ) })?; if seconds < 0 { nanoseconds *= -1; } return Ok(Self::new(seconds, nanoseconds)); } let (seconds, nanoseconds) = Deserialize::deserialize(deserializer)?; Ok(Self::new(seconds, nanoseconds)) } } #[cfg(feature = "serde-human-readable")] const OFFSET_DATE_TIME_FORMAT: &[FormatItem<'_>] = &[ FormatItem::Compound(DATE_FORMAT), FormatItem::Literal(b" "), FormatItem::Compound(TIME_FORMAT), FormatItem::Literal(b" "), FormatItem::Compound(UTC_OFFSET_FORMAT), ]; impl Serialize for OffsetDateTime { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { #[cfg(feature = "serde-human-readable")] if serializer.is_human_readable() { return serializer.serialize_str(&match self.format(&OFFSET_DATE_TIME_FORMAT) { Ok(s) => s, Err(_) => return Err(S::Error::custom("failed formatting `OffsetDateTime`")), }); } ( self.year(), self.ordinal(), self.hour(), self.minute(), self.second(), self.nanosecond(), self.offset.whole_hours(), self.offset.minutes_past_hour(), self.offset.seconds_past_minute(), ) .serialize(serializer) } } impl<'a> Deserialize<'a> for OffsetDateTime { fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> { #[cfg(feature = "serde-human-readable")] if deserializer.is_human_readable() { return Self::parse(<&str>::deserialize(deserializer)?, &OFFSET_DATE_TIME_FORMAT) .map_err(error::Parse::to_invalid_serde_value::<D>); } let ( year, ordinal, hour, minute, second, nanosecond, offset_hours, offset_minutes, offset_seconds, ) = Deserialize::deserialize(deserializer)?; Ok(Date::from_ordinal_date(year, ordinal) .map_err(ComponentRange::to_invalid_serde_value::<D>)? .with_hms_nano(hour, minute, second, nanosecond) .map_err(ComponentRange::to_invalid_serde_value::<D>)? .assume_offset( UtcOffset::from_hms(offset_hours, offset_minutes, offset_seconds) .map_err(ComponentRange::to_invalid_serde_value::<D>)?, )) } } #[cfg(feature = "serde-human-readable")] const PRIMITIVE_DATE_TIME_FORMAT: &[FormatItem<'_>] = &[ FormatItem::Compound(DATE_FORMAT), FormatItem::Literal(b" "), FormatItem::Compound(TIME_FORMAT), ]; impl Serialize for PrimitiveDateTime { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { #[cfg(feature = "serde-human-readable")] if serializer.is_human_readable() { return serializer.serialize_str(&match self.format(&PRIMITIVE_DATE_TIME_FORMAT) { Ok(s) => s, Err(_) => return Err(S::Error::custom("failed formatting `PrimitiveDateTime`")), }); } ( self.year(), self.ordinal(), self.hour(), self.minute(), self.second(), self.nanosecond(), ) .serialize(serializer) } } impl<'a> Deserialize<'a> for PrimitiveDateTime { fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> { #[cfg(feature = "serde-human-readable")] if deserializer.is_human_readable() { return Self::parse( <&str>::deserialize(deserializer)?, &PRIMITIVE_DATE_TIME_FORMAT, ) .map_err(error::Parse::to_invalid_serde_value::<D>); } let (year, ordinal, hour, minute, second, nanosecond) = Deserialize::deserialize(deserializer)?; Date::from_ordinal_date(year, ordinal) .map_err(ComponentRange::to_invalid_serde_value::<D>)? .with_hms_nano(hour, minute, second, nanosecond) .map_err(ComponentRange::to_invalid_serde_value::<D>) } } #[cfg(feature = "serde-human-readable")] const TIME_FORMAT: &[FormatItem<'_>] = &[ FormatItem::Component(Component::Hour(modifier::Hour { padding: modifier::Padding::Zero, is_12_hour_clock: false, })), FormatItem::Literal(b":"), FormatItem::Component(Component::Minute(modifier::Minute { padding: modifier::Padding::Zero, })), FormatItem::Literal(b":"), FormatItem::Component(Component::Second(modifier::Second { padding: modifier::Padding::Zero, })), FormatItem::Literal(b"."), FormatItem::Component(Component::Subsecond(modifier::Subsecond { digits: modifier::SubsecondDigits::OneOrMore, })), ]; impl Serialize for Time { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { #[cfg(feature = "serde-human-readable")] if serializer.is_human_readable() { return serializer.serialize_str(&match self.format(&TIME_FORMAT) { Ok(s) => s, Err(_) => return Err(S::Error::custom("failed formatting `Time`")), }); } (self.hour(), self.minute(), self.second(), self.nanosecond()).serialize(serializer) } } impl<'a> Deserialize<'a> for Time { fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> { #[cfg(feature = "serde-human-readable")] if deserializer.is_human_readable() { return Self::parse(<&str>::deserialize(deserializer)?, &TIME_FORMAT) .map_err(error::Parse::to_invalid_serde_value::<D>); } let (hour, minute, second, nanosecond) = Deserialize::deserialize(deserializer)?; Self::from_hms_nano(hour, minute, second, nanosecond) .map_err(ComponentRange::to_invalid_serde_value::<D>) } } #[cfg(feature = "serde-human-readable")] const UTC_OFFSET_FORMAT: &[FormatItem<'_>] = &[ FormatItem::Component(Component::OffsetHour(modifier::OffsetHour { sign_is_mandatory: true, padding: modifier::Padding::Zero, })), FormatItem::Literal(b":"), FormatItem::Component(Component::OffsetMinute(modifier::OffsetMinute { padding: modifier::Padding::Zero, })), FormatItem::Literal(b":"), FormatItem::Component(Component::OffsetSecond(modifier::OffsetSecond { padding: modifier::Padding::Zero, })), ]; impl Serialize for UtcOffset { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { #[cfg(feature = "serde-human-readable")] if serializer.is_human_readable() { return serializer.serialize_str(&match self.format(&UTC_OFFSET_FORMAT) { Ok(s) => s, Err(_) => return Err(S::Error::custom("failed formatting `UtcOffset`")), }); } ( self.whole_hours(), self.minutes_past_hour(), self.seconds_past_minute(), ) .serialize(serializer) } } impl<'a> Deserialize<'a> for UtcOffset { fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> { #[cfg(feature = "serde-human-readable")] if deserializer.is_human_readable() { return Self::parse(<&str>::deserialize(deserializer)?, &UTC_OFFSET_FORMAT) .map_err(error::Parse::to_invalid_serde_value::<D>); } let (hours, minutes, seconds) = Deserialize::deserialize(deserializer)?; Self::from_hms(hours, minutes, seconds).map_err(ComponentRange::to_invalid_serde_value::<D>) } } impl Serialize for Weekday { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { #[cfg(feature = "serde-human-readable")] if serializer.is_human_readable() { #[cfg(not(feature = "std"))] use alloc::string::ToString; return self.to_string().serialize(serializer); } self.number_from_monday().serialize(serializer) } } impl<'a> Deserialize<'a> for Weekday { fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> { #[cfg(feature = "serde-human-readable")] if deserializer.is_human_readable() { return match <&str>::deserialize(deserializer)? { "Monday" => Ok(Self::Monday), "Tuesday" => Ok(Self::Tuesday), "Wednesday" => Ok(Self::Wednesday), "Thursday" => Ok(Self::Thursday), "Friday" => Ok(Self::Friday), "Saturday" => Ok(Self::Saturday), "Sunday" => Ok(Self::Sunday), val => Err(D::Error::invalid_value( serde::de::Unexpected::Str(val), &"a day of the week", )), }; } match u8::deserialize(deserializer)? { 1 => Ok(Self::Monday), 2 => Ok(Self::Tuesday), 3 => Ok(Self::Wednesday), 4 => Ok(Self::Thursday), 5 => Ok(Self::Friday), 6 => Ok(Self::Saturday), 7 => Ok(Self::Sunday), val => Err(D::Error::invalid_value( serde::de::Unexpected::Unsigned(val.into()), &"a value in the range 1..=7", )), } } }
pub mod timestamp; use serde::de::Error as _; #[cfg(feature = "serde-human-readable")] use serde::ser::Error as _; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::error::ComponentRange; #[cfg(feature = "serde-human-readable")] use crate::{ error, format_description::{modifier, Component, FormatItem}, }; use crate::{Date, Duration, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset, Weekday}; #[cfg(feature = "serde-human-readable")] const DATE_FORMAT: &[FormatItem<'_>] = &[ FormatItem::Component(Component::Year(modifier::Year { repr: modifier::YearRepr::Full, iso_week_based: false, sign_is_mandatory: false, padding: modifier::Padding::Zero, })), FormatItem::Literal(b"-"), FormatItem::Component(Component::Month(modifier::Month { repr: modifier::MonthRepr::Numerical, padding: modifier::Padding::Zero, })), FormatItem::Literal(b"-"), FormatItem::Component(Component::Day(modifier::Day { padding: modifier::Padding::Zero, })), ]; impl Serialize for Date { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { #[cfg(feature = "serde-human-readable")] if serializer.is_human_readable() { return serializer.serialize_str(&match self.format(&DATE_FORMAT) { Ok(s) => s, Err(_) => return Err(S::Error::custom("failed formatting `Date`")), }); } (self.year(), self.ordinal()).serialize(serializer) } } impl<'a> Deserialize<'a> for Date { fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> { #[cfg(feature = "serde-human-readable")] if deserializer.is_human_readable() { return Self::parse(<&str>::deserialize(deserializer)?, &DATE_FORMAT) .map_err(error::Parse::to_invalid_serde_value::<D>); } let (year, ordinal) = Deserialize::deserialize(deserializer)?; Self::from_ordinal_date(year, ordinal).map_err(ComponentRange::to_invalid_serde_value::<D>) } } impl Serialize for Duration { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { #[cfg(feature = "serde-human-readable")] if serializer.is_human_readable() { return serializer.collect_str(&format_args!( "{}.{:>09}", self.whole_seconds(), self.subsec_nanoseconds().abs() )); } (self.whole_seconds(), self.subsec_nanoseconds()).serialize(serializer) } } impl<'a> Deserialize<'a> for Duration { fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> { #[cfg(feature = "serde-human-readable")] if deserializer.is_human_readable() { let s = <&str>::deserialize(deserializer)?; let dot = s.find('.').ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Str(s), &"a decimal point") })?; let (seconds, nanoseconds) = s.split_at(dot); let nanoseconds = &nanoseconds[1..]; let seconds = seconds.parse().map_err(|_| { serde::de::Error::invalid_value(serde::de::Unexpected::Str(seconds), &"a number") })?; let mut nanoseconds = nanoseconds.parse().map_err(|_| { serde::de::Error::invalid_value( serde::de::Unexpected::Str(nanoseconds), &"a number", ) })?; if seconds < 0 { nanoseconds *= -1; } return Ok(Self::new(seconds, nanoseconds)); } let (seconds, nanoseconds) = Deserialize::deserialize(deserializer)?; Ok(Self::new(seconds, nanoseconds)) } } #[cfg(feature = "serde-human-readable")] const OFFSET_DATE_TIME_FORMAT: &[FormatItem<'_>] = &[ FormatItem::Compound(DATE_FORMAT), FormatItem::Literal(b" "), FormatItem::Compound(TIME_FORMAT), FormatItem::Literal(b" "), FormatItem::Compound(UTC_OFFSET_FORMAT), ]; impl Serialize for OffsetDateTime { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { #[cfg(feature = "serde-human-readable")] if serializer.is_human_readable() { return serializer.serialize_str(&match self.format(&OFFSET_DATE_TIME_FORMAT) { Ok(s) => s, Err(_) => return Err(S::Error::custom("failed formatting `OffsetDateTime`")), }); } ( self.year(), self.ordinal(), self.hour(), self.minute(), self.second(), self.nanosecond(), self.offset.whole_hours(), self.offset.minutes_past_hour(), self.offset.seconds_past_minute(), ) .serialize(serializer) } } impl<'a> Deserialize<'a> for OffsetDateTime { fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> { #[cfg(feature = "serde-human-readable")] if deserializer.is_human_readable() { return Self::parse(<&str>::deserialize(deserializer)?, &OFFSET_DATE_TIME_FORMAT) .map_err(error::Parse::to_invalid_serde_value::<D>); } let ( year, ordinal, hour, minute, second, nanosecond, offset_hours, offset_minutes, offset_seconds, ) = Deserialize::deserialize(deserializer)?; Ok(Date::from_ordinal_date(year, ordinal) .map_err(ComponentRange::to_invalid_serde_value::<D>)? .with_hms_nano(hour, minute, second, nanosecond) .map_err(ComponentRange::to_invalid_serde_value::<D>)? .assume_offset( UtcOffset::from_hms(offset_hours, offset_minutes, offset_seconds) .map_err(ComponentRange::to_invalid_serde_value::<D>)?, )) } } #[cfg(feature = "serde-human-readable")] const PRIMITIVE_DATE_TIME_FORMAT: &[FormatItem<'_>] = &[ FormatItem::Compound(DATE_FORMAT), FormatItem::Literal(b" "), FormatItem::Compound(TIME_FORMAT), ]; impl Serialize for PrimitiveDateTime { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { #[cfg(feature = "serde-human-readable")] if serializer.is_human_readable() { return serializer.serialize_str(&match self.format(&PRIMITIVE_DATE_TIME_FORMAT) { Ok(s) => s, Err(_) => return Err(S::Error::custom("failed formatting `PrimitiveDateTime`")), }); } ( self.year(), self.ordinal(), self.hour(), self.minute(), self.second(), self.nanosecond(), ) .serialize(serializer) } } impl<'a> Deserialize<'a> for PrimitiveDateTime { fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> { #[cfg(feature = "serde-human-readable")] if deserializer.is_human_readable() { return Self::parse( <&str>::deserialize(deserializer)?, &PRIMITIVE_DATE_TIME_FORMAT, ) .map_err(error::Parse::to_invalid_serde_value::<D>); } let (year, ordinal, hour, minute, second, nanosecond) = Deserialize::deserialize(deserializer)?; Date::from_ordinal_date(year, ordinal) .map_err(ComponentRange::to_invalid_serde_value::<D>)? .with_hms_nano(hour, minute, second, nanosecond) .map_err(ComponentRange::to_invalid_serde_value::<D>) } } #[cfg(feature = "serde-human-readable")] const TIME_FORMAT: &[FormatItem<'_>] = &[ FormatItem::Component(Component::Hour(modifier::Hour { padding: modifier::Padding::Zero, is_12_hour_clock: false, })), FormatItem::Literal(b":"), FormatItem::Component(Component::Minute(modifier::Minute { padding: modifier::Padding::Zero, })), FormatItem::Literal(b":"), FormatItem::Component(Component::Second(modifier::Second { padding: modifier::Padding::Zero, })), FormatItem::Literal(b"."), FormatItem::Component(Component::Subsecond(modifier::Subsecond { digits: modifier::SubsecondDigits::OneOrMore, })), ]; impl Serialize for Time { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { #[cfg(feature = "serde-human-readable")] if serializer.is_human_readable() { return serializer.serialize_str(&match self.format(&TIME_FORMAT) { Ok(s) => s, Err(_) => return Err(S::Error::custom("failed formatting `Time`")), }); } (self.hour(), self.minute(), self.second(), self.nanosecond()).serialize(serializer) } } impl<'a> Deserialize<'a> for Time { fn deserialize<D: D
eturn serializer.serialize_str(&match self.format(&UTC_OFFSET_FORMAT) { Ok(s) => s, Err(_) => return Err(S::Error::custom("failed formatting `UtcOffset`")), }); } ( self.whole_hours(), self.minutes_past_hour(), self.seconds_past_minute(), ) .serialize(serializer) } } impl<'a> Deserialize<'a> for UtcOffset { fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> { #[cfg(feature = "serde-human-readable")] if deserializer.is_human_readable() { return Self::parse(<&str>::deserialize(deserializer)?, &UTC_OFFSET_FORMAT) .map_err(error::Parse::to_invalid_serde_value::<D>); } let (hours, minutes, seconds) = Deserialize::deserialize(deserializer)?; Self::from_hms(hours, minutes, seconds).map_err(ComponentRange::to_invalid_serde_value::<D>) } } impl Serialize for Weekday { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { #[cfg(feature = "serde-human-readable")] if serializer.is_human_readable() { #[cfg(not(feature = "std"))] use alloc::string::ToString; return self.to_string().serialize(serializer); } self.number_from_monday().serialize(serializer) } } impl<'a> Deserialize<'a> for Weekday { fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> { #[cfg(feature = "serde-human-readable")] if deserializer.is_human_readable() { return match <&str>::deserialize(deserializer)? { "Monday" => Ok(Self::Monday), "Tuesday" => Ok(Self::Tuesday), "Wednesday" => Ok(Self::Wednesday), "Thursday" => Ok(Self::Thursday), "Friday" => Ok(Self::Friday), "Saturday" => Ok(Self::Saturday), "Sunday" => Ok(Self::Sunday), val => Err(D::Error::invalid_value( serde::de::Unexpected::Str(val), &"a day of the week", )), }; } match u8::deserialize(deserializer)? { 1 => Ok(Self::Monday), 2 => Ok(Self::Tuesday), 3 => Ok(Self::Wednesday), 4 => Ok(Self::Thursday), 5 => Ok(Self::Friday), 6 => Ok(Self::Saturday), 7 => Ok(Self::Sunday), val => Err(D::Error::invalid_value( serde::de::Unexpected::Unsigned(val.into()), &"a value in the range 1..=7", )), } } }
eserializer<'a>>(deserializer: D) -> Result<Self, D::Error> { #[cfg(feature = "serde-human-readable")] if deserializer.is_human_readable() { return Self::parse(<&str>::deserialize(deserializer)?, &TIME_FORMAT) .map_err(error::Parse::to_invalid_serde_value::<D>); } let (hour, minute, second, nanosecond) = Deserialize::deserialize(deserializer)?; Self::from_hms_nano(hour, minute, second, nanosecond) .map_err(ComponentRange::to_invalid_serde_value::<D>) } } #[cfg(feature = "serde-human-readable")] const UTC_OFFSET_FORMAT: &[FormatItem<'_>] = &[ FormatItem::Component(Component::OffsetHour(modifier::OffsetHour { sign_is_mandatory: true, padding: modifier::Padding::Zero, })), FormatItem::Literal(b":"), FormatItem::Component(Component::OffsetMinute(modifier::OffsetMinute { padding: modifier::Padding::Zero, })), FormatItem::Literal(b":"), FormatItem::Component(Component::OffsetSecond(modifier::OffsetSecond { padding: modifier::Padding::Zero, })), ]; impl Serialize for UtcOffset { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { #[cfg(feature = "serde-human-readable")] if serializer.is_human_readable() { r
random
[ { "content": "/// Deserialize an `OffsetDateTime` from its Unix timestamp\n\npub fn deserialize<'a, D: Deserializer<'a>>(deserializer: D) -> Result<OffsetDateTime, D::Error> {\n\n i64::deserialize(deserializer).and_then(|timestamp| {\n\n OffsetDateTime::from_unix_timestamp(timestamp)\n\n .m...
Rust
crates/kitsune_p2p/direct/src/types/kdhash.rs
mhuesch/holochain
8cade151329117c40e47533449a2f842187c373a
use crate::*; use futures::future::{BoxFuture, FutureExt}; use kitsune_p2p::*; pub use kitsune_p2p_direct_api::KdHash; pub trait KdHashExt: Sized { fn to_kitsune_space(&self) -> Arc<KitsuneSpace>; fn from_kitsune_space(space: &KitsuneSpace) -> Self; fn to_kitsune_agent(&self) -> Arc<KitsuneAgent>; fn from_kitsune_agent(agent: &KitsuneAgent) -> Self; fn to_kitsune_op_hash(&self) -> Arc<KitsuneOpHash>; fn from_kitsune_op_hash(op_hash: &KitsuneOpHash) -> Self; fn to_kitsune_basis(&self) -> Arc<KitsuneBasis>; fn from_kitsune_basis(basis: &KitsuneBasis) -> Self; fn verify_signature( &self, data: sodoken::BufRead, signature: Arc<[u8; 64]>, ) -> BoxFuture<'static, bool>; fn from_data(data: &[u8]) -> BoxFuture<'static, KdResult<Self>>; fn from_coerced_pubkey(data: [u8; 32]) -> BoxFuture<'static, KdResult<Self>>; } impl KdHashExt for KdHash { fn to_kitsune_space(&self) -> Arc<KitsuneSpace> { Arc::new(KitsuneSpace(self.0 .1[3..].to_vec())) } fn from_kitsune_space(space: &KitsuneSpace) -> Self { (*arrayref::array_ref![&space.0, 0, 36]).into() } fn to_kitsune_agent(&self) -> Arc<KitsuneAgent> { Arc::new(KitsuneAgent(self.0 .1[3..].to_vec())) } fn from_kitsune_agent(agent: &KitsuneAgent) -> Self { (*arrayref::array_ref![&agent.0, 0, 36]).into() } fn to_kitsune_op_hash(&self) -> Arc<KitsuneOpHash> { Arc::new(KitsuneOpHash(self.0 .1[3..].to_vec())) } fn from_kitsune_op_hash(op_hash: &KitsuneOpHash) -> Self { (*arrayref::array_ref![&op_hash.0, 0, 36]).into() } fn to_kitsune_basis(&self) -> Arc<KitsuneBasis> { Arc::new(KitsuneBasis(self.0 .1[3..].to_vec())) } fn from_kitsune_basis(basis: &KitsuneBasis) -> Self { (*arrayref::array_ref![&basis.0, 0, 36]).into() } fn verify_signature( &self, data: sodoken::BufRead, signature: Arc<[u8; 64]>, ) -> BoxFuture<'static, bool> { let pk = sodoken::BufReadSized::new_no_lock(*self.as_core_bytes()); async move { async { let sig = sodoken::BufReadSized::new_no_lock(*signature); KdResult::Ok( sodoken::sign::verify_detached(sig, data, pk) .await .map_err(KdError::other)?, ) } .await .unwrap_or(false) } .boxed() } fn from_data(data: &[u8]) -> BoxFuture<'static, KdResult<Self>> { let r = sodoken::BufRead::new_no_lock(data); async move { let hash = <sodoken::BufWriteSized<32>>::new_no_lock(); sodoken::hash::blake2b::hash(hash.clone(), r) .await .map_err(KdError::other)?; let mut out = [0; 32]; out.copy_from_slice(&hash.read_lock()[0..32]); Self::from_coerced_pubkey(out).await } .boxed() } fn from_coerced_pubkey(data: [u8; 32]) -> BoxFuture<'static, KdResult<Self>> { async move { let r = sodoken::BufReadSized::new_no_lock(data); let loc = loc_hash(r).await?; let mut out = [0; 36]; out[0..32].copy_from_slice(&data); out[32..].copy_from_slice(&loc); Ok(out.into()) } .boxed() } } async fn loc_hash(d: sodoken::BufReadSized<32>) -> KdResult<[u8; 4]> { let mut out = [0; 4]; let hash = <sodoken::BufWriteSized<16>>::new_no_lock(); sodoken::hash::blake2b::hash(hash.clone(), d) .await .map_err(KdError::other)?; let hash = hash.read_lock(); out[0] = hash[0]; out[1] = hash[1]; out[2] = hash[2]; out[3] = hash[3]; for i in (4..16).step_by(4) { out[0] ^= hash[i]; out[1] ^= hash[i + 1]; out[2] ^= hash[i + 2]; out[3] ^= hash[i + 3]; } Ok(out) }
use crate::*; use futures::future::{BoxFuture, FutureExt}; use kitsune_p2p::*; pub use kitsune_p2p_direct_api::KdHash; pub trait KdHashExt: Sized { fn to_kitsune_space(&self) -> Arc<KitsuneSpace>; fn from_kitsune_space(space: &KitsuneSpace) -> Self; fn to_kitsune_agent(&self) -> Arc<KitsuneAgent>; fn from_kitsune_agent(agent: &KitsuneAgent) -> Self; fn to_kitsune_op_hash(&self) -> Arc<KitsuneOpHash>; fn from_kitsune_op_hash(op_hash: &KitsuneOpHash) -> Self; fn to_kitsune_basis(&self) -> Arc<KitsuneBasis>; fn from_kitsune_basis(basis: &KitsuneBasis) -> Self; fn verify_signature( &self, data: sodoken::BufRead,
out) }
signature: Arc<[u8; 64]>, ) -> BoxFuture<'static, bool>; fn from_data(data: &[u8]) -> BoxFuture<'static, KdResult<Self>>; fn from_coerced_pubkey(data: [u8; 32]) -> BoxFuture<'static, KdResult<Self>>; } impl KdHashExt for KdHash { fn to_kitsune_space(&self) -> Arc<KitsuneSpace> { Arc::new(KitsuneSpace(self.0 .1[3..].to_vec())) } fn from_kitsune_space(space: &KitsuneSpace) -> Self { (*arrayref::array_ref![&space.0, 0, 36]).into() } fn to_kitsune_agent(&self) -> Arc<KitsuneAgent> { Arc::new(KitsuneAgent(self.0 .1[3..].to_vec())) } fn from_kitsune_agent(agent: &KitsuneAgent) -> Self { (*arrayref::array_ref![&agent.0, 0, 36]).into() } fn to_kitsune_op_hash(&self) -> Arc<KitsuneOpHash> { Arc::new(KitsuneOpHash(self.0 .1[3..].to_vec())) } fn from_kitsune_op_hash(op_hash: &KitsuneOpHash) -> Self { (*arrayref::array_ref![&op_hash.0, 0, 36]).into() } fn to_kitsune_basis(&self) -> Arc<KitsuneBasis> { Arc::new(KitsuneBasis(self.0 .1[3..].to_vec())) } fn from_kitsune_basis(basis: &KitsuneBasis) -> Self { (*arrayref::array_ref![&basis.0, 0, 36]).into() } fn verify_signature( &self, data: sodoken::BufRead, signature: Arc<[u8; 64]>, ) -> BoxFuture<'static, bool> { let pk = sodoken::BufReadSized::new_no_lock(*self.as_core_bytes()); async move { async { let sig = sodoken::BufReadSized::new_no_lock(*signature); KdResult::Ok( sodoken::sign::verify_detached(sig, data, pk) .await .map_err(KdError::other)?, ) } .await .unwrap_or(false) } .boxed() } fn from_data(data: &[u8]) -> BoxFuture<'static, KdResult<Self>> { let r = sodoken::BufRead::new_no_lock(data); async move { let hash = <sodoken::BufWriteSized<32>>::new_no_lock(); sodoken::hash::blake2b::hash(hash.clone(), r) .await .map_err(KdError::other)?; let mut out = [0; 32]; out.copy_from_slice(&hash.read_lock()[0..32]); Self::from_coerced_pubkey(out).await } .boxed() } fn from_coerced_pubkey(data: [u8; 32]) -> BoxFuture<'static, KdResult<Self>> { async move { let r = sodoken::BufReadSized::new_no_lock(data); let loc = loc_hash(r).await?; let mut out = [0; 36]; out[0..32].copy_from_slice(&data); out[32..].copy_from_slice(&loc); Ok(out.into()) } .boxed() } } async fn loc_hash(d: sodoken::BufReadSized<32>) -> KdResult<[u8; 4]> { let mut out = [0; 4]; let hash = <sodoken::BufWriteSized<16>>::new_no_lock(); sodoken::hash::blake2b::hash(hash.clone(), d) .await .map_err(KdError::other)?; let hash = hash.read_lock(); out[0] = hash[0]; out[1] = hash[1]; out[2] = hash[2]; out[3] = hash[3]; for i in (4..16).step_by(4) { out[0] ^= hash[i]; out[1] ^= hash[i + 1]; out[2] ^= hash[i + 2]; out[3] ^= hash[i + 3]; } Ok(
random
[ { "content": "/// internal REPR for holo hash\n\npub fn holo_hash_encode(data: &[u8]) -> String {\n\n format!(\"u{}\", base64::encode_config(data, base64::URL_SAFE_NO_PAD),)\n\n}\n\n\n", "file_path": "crates/holo_hash/src/encode.rs", "rank": 1, "score": 254914.76057821707 }, { "content": ...
Rust
src/theorem.rs
MDeiml/attomath
4aac4dad3cd776dd2cb1602aa930c04c315d5186
use std::{cmp::Ordering, num::Wrapping}; use crate::{ dvr::DVR, error::ProofError, expression::{ is_operator, ChainSubstitution, ShiftSubstitution, Substitution, VariableSubstitution, WholeSubstitution, }, statement::OwnedStatement, types::*, }; #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)] pub struct Theorem { conclusion: OwnedStatement, assumptions: Vec<OwnedStatement>, dvrs: Vec<DVR>, } impl Theorem { pub fn conclusion(&self) -> &OwnedStatement { &self.conclusion } pub fn assumptions(&self) -> &[OwnedStatement] { &self.assumptions } pub fn dvrs(&self) -> &[DVR] { &self.dvrs } pub fn new( conclusion: OwnedStatement, assumptions: Vec<OwnedStatement>, dvrs: Vec<DVR>, ) -> Self { Theorem { conclusion, assumptions, dvrs, } } pub fn standardize(&mut self) { let max_var = self.max_var(); let mut var_map = vec![None; (Wrapping(max_var as usize) + Wrapping(1)).0]; let mut next_var = 0; self.conclusion .expression .standardize_range(&mut var_map, &mut next_var, ..); self.assumptions.sort_unstable(); self.assumptions.dedup(); let mut indexed_assumptions = self .assumptions .iter() .cloned() .enumerate() .map(|(a, b)| (b, a)) .collect::<Vec<_>>(); let normalized_assumptions = self .assumptions .drain(..) .map(|assumption| { let mut normalized = assumption; normalized.expression.standardize(); normalized }) .collect::<Vec<_>>(); indexed_assumptions.sort_unstable_by_key(|(_, index)| &normalized_assumptions[*index]); let mut temp_next_var = next_var; for (assumption, _) in indexed_assumptions.iter_mut() { assumption .expression .standardize_range(&mut var_map, &mut temp_next_var, ..); } for (i, v) in var_map.iter_mut().enumerate() { *v = if i < next_var as usize { Some(i as Identifier) } else { None }; } let mut var_maps = vec![var_map]; for assumptions in indexed_assumptions .group_by_mut(|(_, i), (_, j)| normalized_assumptions[*i] == normalized_assumptions[*j]) { let mut next_var1 = 0; let mut assumptions_min: Option<Vec<(OwnedStatement, usize)>> = None; let mut var_maps1 = Vec::new(); for var_map in var_maps.iter_mut() { let mut perm = assumptions.iter().cloned().collect::<Vec<_>>(); for (assumption, _) in perm.iter_mut() { assumption.expression.substitute_variables(&var_map); } let mut perm = Permutations::new(&mut perm); while let Some(permutation) = perm.next() { let mut var_map1 = var_map.clone(); next_var1 = next_var; for (assumption, _) in permutation.iter_mut() { assumption.expression.standardize_range( &mut var_map1, &mut next_var1, next_var.., ); } match assumptions_min .as_deref_mut() .map(|a_min| { permutation .iter() .map(|(a, _)| a) .cmp(a_min.iter().map(|(a, _)| a)) }) .unwrap_or(Ordering::Less) { Ordering::Equal => { var_maps1.push(var_map1); } Ordering::Less => { var_maps1.clear(); var_maps1.push(var_map1); assumptions_min = Some(permutation.iter().cloned().collect()); } Ordering::Greater => {} } } } var_maps = var_maps1; next_var = next_var1; assumptions.swap_with_slice(assumptions_min.unwrap().as_mut_slice()); } self.assumptions .extend(indexed_assumptions.into_iter().map(|(a, _)| a)); for dvr in self.dvrs.iter_mut() { *dvr = dvr .substitute(&VariableSubstitution::new(var_maps[0].as_slice()).unwrap()) .next() .unwrap() .unwrap(); } self.dvrs.sort_unstable(); self.dvrs.dedup(); } pub fn max_var(&self) -> Identifier { self.conclusion .expression .variables() .chain( self.assumptions .iter() .map(|st| st.expression.variables()) .flatten(), ) .filter(|symb| !is_operator(*symb)) .max() .unwrap_or(-1) } pub fn substitute<S: Substitution>(&self, substitution: &S) -> Result<Self, ProofError> { self.substitute_skip_assumption(substitution, None) } fn substitute_skip_assumption<S: Substitution>( &self, substitution: &S, skip_assumption: Option<usize>, ) -> Result<Self, ProofError> { let conclusion = self.conclusion.substitute(substitution); let assumptions: Vec<OwnedStatement> = self .assumptions .iter() .enumerate() .filter_map(|(i, a)| { if Some(i) == skip_assumption { None } else { Some(a) } }) .map(|a| a.substitute(substitution)) .collect(); let dvrs = self .dvrs .iter() .map(|dvr| dvr.substitute(substitution)) .flatten() .collect::<Result<Vec<_>, _>>()?; Ok(Theorem { conclusion, assumptions, dvrs, }) } pub fn combine(&self, other: &Theorem, index: usize) -> Result<Self, ProofError> { let max_var = self.max_var(); let mut substitution = WholeSubstitution::with_capacity((Wrapping(max_var as usize) + Wrapping(1)).0); other .conclusion .unify(&self.assumptions[index], &mut substitution)?; let shift = other.max_var() + 1; let shift_sub = ShiftSubstitution::new(shift); let substitution = ChainSubstitution { first: substitution, then: shift_sub, }; let mut t = self.substitute_skip_assumption(&substitution, Some(index))?; t.assumptions.extend_from_slice(&other.assumptions); t.assumptions.shrink_to_fit(); t.dvrs.extend_from_slice(&other.dvrs); t.dvrs.shrink_to_fit(); Ok(t) } } struct Permutations<'a, T> { sequence: &'a mut [T], counters: Vec<usize>, depth: usize, } impl<'a, T> Permutations<'a, T> { fn new(sequence: &'a mut [T]) -> Self { let length = sequence.len(); Permutations { sequence, counters: vec![0; length], depth: 0, } } fn next(&mut self) -> Option<&mut [T]> { if self.depth >= self.sequence.len() { return None; } if self.depth != 0 { while self.counters[self.depth] >= self.depth { self.counters[self.depth] = 0; self.depth += 1; if self.depth >= self.sequence.len() { return None; } } if self.depth % 2 == 0 { self.sequence.swap(0, self.depth); } else { self.sequence.swap(self.counters[self.depth], self.depth); } self.counters[self.depth] += 1; self.depth = 1; Some(&mut self.sequence) } else { self.depth = 1; Some(&mut self.sequence) } } } #[cfg(test)] mod tests { use super::*; #[test] fn permutations() { let mut arr = [0, 1, 2, 3]; let mut perm = Permutations::new(&mut arr); let mut counter = 0; while let Some(_) = perm.next() { counter += 1; } assert_eq!(counter, 24); } }
use std::{cmp::Ordering, num::Wrapping}; use crate::{ dvr::DVR, error::ProofError, expression::{ is_operator, ChainSubstitution, ShiftSubstitution, Substitution, VariableSubstitution, WholeSubstitution, }, statement::OwnedStatement, types::*, }; #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)] pub struct Theorem { conclusion: OwnedStatement, assumptions: Vec<OwnedStatement>, dvrs: Vec<DVR>, } impl Theorem { pub fn conclusion(&self) -> &OwnedStatement { &self.conclusion } pub fn assumptions(&self) -> &[OwnedStatement] { &self.assumptions } pub fn dvrs(&self) -> &[DVR] { &self.dvrs } pub fn new( conclusion: OwnedStatement, assumptions: Vec<OwnedStatement>, dvrs: Vec<DVR>, ) -> Self { Theorem { conclusion, assumptions, dvrs, } } pub fn standardize(&mut self) { let max_var = self.max_var(); let mut var_map = vec![None; (Wrapping(max_var as usize) + Wrapping(1)).0]; let mut next_var = 0; self.conclusion .expression .standardize_range(&mut var_map, &mut next_var, ..); self.assumptions.sort_unstable(); self.assumptions.dedup(); let mut indexed_assumptions = self .assumptions .iter() .cloned() .enumerate() .map(|(a, b)| (b, a)) .collect::<Vec<_>>(); let normalized_assumptions = self .assumptions .drain(..) .map(|assumption| { let mut normalized = assumption; normalized.expression.standardize(); normalized }) .collect::<Vec<_>>(); indexed_assumptions.sort_unstable_by_key(|(_, index)| &normalized_assumptions[*index]); let mut temp_next_var = next_var; for (assumption, _) in indexed_assumptions.iter_mut() { assumption .expression .standardize_range(&mut var_map, &mut temp_next_var, ..); } for (i, v) in var_map.iter_mut().enumerate() { *v = if i < next_var as usize { Some(i as Identifier) } else { None }; } let mut var_maps = vec![var_map]; for assumptions in indexed_assumptions .group_by_mut(|(_, i), (_, j)| normalized_assumptions[*i] == normalized_assumptions[*j]) { let mut next_var1 = 0; let mut assumptions_min: Option<Vec<(OwnedStatement, usize)>> = None; let mut var_maps1 = Vec::new(); for var_map in var_maps.iter_mut() { let mut perm = assumptions.iter().cloned().collect::<Vec<_>>(); for (assumption, _) in perm.iter_mut() { assumption.expression.substitute_variables(&var_map); } let mut perm = Permutations::new(&mut perm); while let Some(permutation) = perm.next() { let mut var_map1 = var_map.clone(); next_var1 = next_var; for (assumption, _) in permutation.iter_mut() { assumption.expression.standardize_range( &mut var_map1, &mut next_var1, next_var.., ); } match assumptions_min .as_deref_mut() .map(|a_min| { permutation .iter() .map(|(a, _)| a) .cmp(a_min.iter().map(|(a, _)| a)) }) .unwrap_or(Ordering::Less) { Ordering::Equal => { var_maps1.push(var_map1); } Ordering::Less => { var_maps1.clear(); var_maps1.push(var_map1); assumptions_min = Some(permutation.iter().cloned().collect()); } Ordering::Greater => {} } } } var_maps = var_maps1; next_var = next_var1; assumptions.swap_with_slice(assumptions_min.unwrap().as_mut_slice()); } self.assumptions .extend(indexed_assumptions.into_iter().map(|(a, _)| a)); for dvr in self.dvrs.iter_mut() { *dvr = dvr .substitute(&VariableSubstitution::new(var_maps[0].as_slice()).unwrap()) .next() .unwrap() .unwrap(); } self.dvrs.sort_unstable(); self.dvrs.dedup(); } pub fn max_var(&self) -> Identifier { self.conclusion .expression .variables() .chain( self.
pub fn substitute<S: Substitution>(&self, substitution: &S) -> Result<Self, ProofError> { self.substitute_skip_assumption(substitution, None) } fn substitute_skip_assumption<S: Substitution>( &self, substitution: &S, skip_assumption: Option<usize>, ) -> Result<Self, ProofError> { let conclusion = self.conclusion.substitute(substitution); let assumptions: Vec<OwnedStatement> = self .assumptions .iter() .enumerate() .filter_map(|(i, a)| { if Some(i) == skip_assumption { None } else { Some(a) } }) .map(|a| a.substitute(substitution)) .collect(); let dvrs = self .dvrs .iter() .map(|dvr| dvr.substitute(substitution)) .flatten() .collect::<Result<Vec<_>, _>>()?; Ok(Theorem { conclusion, assumptions, dvrs, }) } pub fn combine(&self, other: &Theorem, index: usize) -> Result<Self, ProofError> { let max_var = self.max_var(); let mut substitution = WholeSubstitution::with_capacity((Wrapping(max_var as usize) + Wrapping(1)).0); other .conclusion .unify(&self.assumptions[index], &mut substitution)?; let shift = other.max_var() + 1; let shift_sub = ShiftSubstitution::new(shift); let substitution = ChainSubstitution { first: substitution, then: shift_sub, }; let mut t = self.substitute_skip_assumption(&substitution, Some(index))?; t.assumptions.extend_from_slice(&other.assumptions); t.assumptions.shrink_to_fit(); t.dvrs.extend_from_slice(&other.dvrs); t.dvrs.shrink_to_fit(); Ok(t) } } struct Permutations<'a, T> { sequence: &'a mut [T], counters: Vec<usize>, depth: usize, } impl<'a, T> Permutations<'a, T> { fn new(sequence: &'a mut [T]) -> Self { let length = sequence.len(); Permutations { sequence, counters: vec![0; length], depth: 0, } } fn next(&mut self) -> Option<&mut [T]> { if self.depth >= self.sequence.len() { return None; } if self.depth != 0 { while self.counters[self.depth] >= self.depth { self.counters[self.depth] = 0; self.depth += 1; if self.depth >= self.sequence.len() { return None; } } if self.depth % 2 == 0 { self.sequence.swap(0, self.depth); } else { self.sequence.swap(self.counters[self.depth], self.depth); } self.counters[self.depth] += 1; self.depth = 1; Some(&mut self.sequence) } else { self.depth = 1; Some(&mut self.sequence) } } } #[cfg(test)] mod tests { use super::*; #[test] fn permutations() { let mut arr = [0, 1, 2, 3]; let mut perm = Permutations::new(&mut arr); let mut counter = 0; while let Some(_) = perm.next() { counter += 1; } assert_eq!(counter, 24); } }
assumptions .iter() .map(|st| st.expression.variables()) .flatten(), ) .filter(|symb| !is_operator(*symb)) .max() .unwrap_or(-1) }
function_block-function_prefixed
[ { "content": "/// Tests whether the given identifier is an operator.\n\n///\n\n/// Operators occupy the range `(Identifier::MIN ..= -1)`.\n\n/// The special value `Identifier::MIN` is also an operator.\n\n///\n\n/// # Example\n\n/// ```\n\n/// use attomath::{expression::is_operator, Identifier};\n\n///\n\n/// a...
Rust
libpf-rs/src/filter.rs
kckeiks/pf-rs
608fb83a3b583eb03af63a61d90d7dba0d70d296
use std::fs::File; use std::io::Write; use std::path::Path; use anyhow::Result; use tempfile::tempdir; use crate::bpf::{BPFLink, BPFObj}; use crate::bpfcode::{ DEFINES, EVAL_BOTH_IPVER, EVAL_NOOP, EVAL_ONLY_IP4, EVAL_ONLY_IP6, INCLUDE_HEADERS, IP4RULES_MAPS, IP4_EVAL_FUNCS, IP6RULES_MAPS, IP6_EVAL_FUNCS, PARSERS, PROGRAM, STRUCTS, VMLINUX, }; use crate::error::Error; use crate::rule::{Action, InnerRule, RawRule, Rule}; use crate::{bpf, compile}; #[derive(Debug)] pub struct Filter { default_act: Action, ipv4_rules: Vec<RawRule>, ipv6_rules: Vec<RawRule>, } impl Filter { pub fn new() -> Self { Filter { default_act: Action::Pass, ipv4_rules: Vec::new(), ipv6_rules: Vec::new(), } } pub fn add_rule(&mut self, rule: Rule) { match rule.get_rule() { InnerRule::IPv6Rule(r) => self.ipv6_rules.push(r), InnerRule::IPv4Rule(r) => self.ipv4_rules.push(r), InnerRule::DefaultRule(a) => self.default_act = a, } } pub fn load_on(self, ifindex: i32) -> Result<BPFLink> { let mut bpf_obj = self .generate_and_load() .map_err(|e| Error::Internal(e.to_string()))?; for (i, rule) in self.ipv4_rules.into_iter().enumerate() { let initial_value = bincode2::serialize(&rule).map_err(|e| Error::Internal(e.to_string()))?; let index = bincode2::serialize(&(i as u32)).map_err(|e| Error::Internal(e.to_string()))?; bpf_obj .update_map("ipv4_rules", &index, &initial_value, 0) .map_err(|e| Error::Internal(e.to_string()))?; } for (i, rule) in self.ipv6_rules.into_iter().enumerate() { let initial_value = bincode2::serialize(&rule).map_err(|e| Error::Internal(e.to_string()))?; let index = bincode2::serialize(&(i as u32)).map_err(|e| Error::Internal(e.to_string()))?; bpf_obj .update_map("ipv6_rules", &index, &initial_value, 0) .map_err(|e| Error::Internal(e.to_string()))?; } let link = bpf_obj .attach_prog(ifindex) .map_err(|e| Error::Internal(e.to_string()))?; Ok(link) } pub fn generate_src(self) -> Result<()> { let filename = "pfdebug"; let src_dir = Path::new("./target/"); let hdr_path = src_dir.join("vmlinux.h"); let _hdr = generate_vmlinux_file(hdr_path.as_path())?; let src_path = src_dir.join(format!("{}.bpf.c", filename)); self.generate_src_file(src_path.as_path())?; let obj_path = src_dir.join(format!("{}.o", filename)); compile::compile(src_path.as_path(), obj_path.as_path())?; Ok(()) } fn generate_and_load(&self) -> Result<BPFObj> { let filename = "pf"; let src_dir = tempdir().expect("error creating temp dir"); let hdr_path = src_dir.path().join("vmlinux.h"); let hdr = generate_vmlinux_file(hdr_path.as_path())?; let src_path = src_dir.path().join(format!("{}.bpf.c", filename)); let src = self.generate_src_file(src_path.as_path())?; let obj_dir = tempdir().expect("error creating temp dir"); let obj_path = obj_dir.path().join(format!("{}.o", filename)); compile::compile(src_path.as_path(), obj_path.as_path())?; let bpf_obj = bpf::BPFObj::load_from_file(obj_path).map_err(|e| Error::Internal(e.to_string()))?; drop(hdr); drop(src); if let Err(e) = src_dir.close() { println!("error closing dir: {}", e.to_string()); } if let Err(e) = obj_dir.close() { println!("error closing dir: {}", e.to_string()); } Ok(bpf_obj) } fn generate_src_file(&self, path: &Path) -> Result<File> { let mut src = File::create(path).map_err(|e| Error::Internal(e.to_string()))?; src.write_all(INCLUDE_HEADERS.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; src.write_all(DEFINES.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; src.write_all( format!( "\ #define DEFAULT_ACTION {}\n\ #define IPV4_RULE_COUNT {}\n\ #define IPV6_RULE_COUNT {}\n", self.default_act as u32, self.ipv4_rules.len(), self.ipv6_rules.len() ) .as_bytes(), ) .map_err(|e| Error::Internal(e.to_string()))?; src.write_all(STRUCTS.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; src.write_all(PARSERS.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; if !self.ipv4_rules.is_empty() { src.write_all(IP4RULES_MAPS.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; src.write_all(IP4_EVAL_FUNCS.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; } if !self.ipv6_rules.is_empty() { src.write_all(IP6RULES_MAPS.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; src.write_all(IP6_EVAL_FUNCS.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; } match (self.ipv6_rules.is_empty(), self.ipv4_rules.is_empty()) { (true, true) => src .write_all(EVAL_NOOP.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?, (true, false) => src .write_all(EVAL_ONLY_IP4.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?, (false, true) => src .write_all(EVAL_ONLY_IP6.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?, (false, false) => src .write_all(EVAL_BOTH_IPVER.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?, } src.write_all(PROGRAM.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; Ok(src) } } fn generate_vmlinux_file(path: &Path) -> Result<File> { let mut hdr = File::create(path).map_err(|e| Error::Internal(e.to_string()))?; if let Err(e) = hdr.write_all(VMLINUX.as_bytes()) { panic!("{}", e.to_string()); } Ok(hdr) }
use std::fs::File; use std::io::Write; use std::path::Path; use anyhow::Result; use tempfile::tempdir; use crate::bpf::{BPFLink, BPFObj}; use crate::bpfcode::{ DEFINES, EVAL_BOTH_IPVER, EVAL_NOOP, EVAL_ONLY_IP4, EVAL_ONLY_IP6, INCLUDE_HEADERS, IP4RULES_MAPS, IP4_EVAL_FUNCS, IP6RULES_MAPS, IP6_EVAL_FUNCS, PARSERS, PROGRAM, STRUCTS, VMLINUX, }; use crate::error::Error; use crate::rule::{Action, InnerRule, RawRule, Rule}; use crate::{bpf, compile}; #[derive(Debug)] pub struct Filter { default_act: Action, ipv4_rules: Vec<RawRule>, ipv6_rules: Vec<RawRule>, } impl Filter { pub fn new() -> Self { Filter { default_act: Action::Pass, ipv4_rules: Vec::new(), ipv6_rules: Vec::new(), } } pub fn add_rule(&mut self, rule: Rule) { match rule.get_rule() { InnerRule::IPv6Rule(r) => self.ipv6_rules.push(r), InnerRule::IPv4Rule(r) => self.ipv4_rules.push(r), InnerRule::DefaultRule(a) => self.default_act = a, } } pub fn load_on(self, ifindex: i32) -> Result<BPFLink> { let mut bpf_obj = self .generate_and_load() .map_err(|e| Error::Internal(e.to_string()))?; for (i, rule) in self.ipv4_rules.into_iter().enumerate() { let initial_value = bincode2::serialize(&rule).map_err(|e| Error::Internal(e.to_string()))?; let index = bincode2::serialize(&(i as u32)).map_err(|e| Error::Internal(e.to_string()))?; bpf_obj
.map_err(|e| Error::Internal(e.to_string()))?; } let link = bpf_obj .attach_prog(ifindex) .map_err(|e| Error::Internal(e.to_string()))?; Ok(link) } pub fn generate_src(self) -> Result<()> { let filename = "pfdebug"; let src_dir = Path::new("./target/"); let hdr_path = src_dir.join("vmlinux.h"); let _hdr = generate_vmlinux_file(hdr_path.as_path())?; let src_path = src_dir.join(format!("{}.bpf.c", filename)); self.generate_src_file(src_path.as_path())?; let obj_path = src_dir.join(format!("{}.o", filename)); compile::compile(src_path.as_path(), obj_path.as_path())?; Ok(()) } fn generate_and_load(&self) -> Result<BPFObj> { let filename = "pf"; let src_dir = tempdir().expect("error creating temp dir"); let hdr_path = src_dir.path().join("vmlinux.h"); let hdr = generate_vmlinux_file(hdr_path.as_path())?; let src_path = src_dir.path().join(format!("{}.bpf.c", filename)); let src = self.generate_src_file(src_path.as_path())?; let obj_dir = tempdir().expect("error creating temp dir"); let obj_path = obj_dir.path().join(format!("{}.o", filename)); compile::compile(src_path.as_path(), obj_path.as_path())?; let bpf_obj = bpf::BPFObj::load_from_file(obj_path).map_err(|e| Error::Internal(e.to_string()))?; drop(hdr); drop(src); if let Err(e) = src_dir.close() { println!("error closing dir: {}", e.to_string()); } if let Err(e) = obj_dir.close() { println!("error closing dir: {}", e.to_string()); } Ok(bpf_obj) } fn generate_src_file(&self, path: &Path) -> Result<File> { let mut src = File::create(path).map_err(|e| Error::Internal(e.to_string()))?; src.write_all(INCLUDE_HEADERS.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; src.write_all(DEFINES.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; src.write_all( format!( "\ #define DEFAULT_ACTION {}\n\ #define IPV4_RULE_COUNT {}\n\ #define IPV6_RULE_COUNT {}\n", self.default_act as u32, self.ipv4_rules.len(), self.ipv6_rules.len() ) .as_bytes(), ) .map_err(|e| Error::Internal(e.to_string()))?; src.write_all(STRUCTS.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; src.write_all(PARSERS.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; if !self.ipv4_rules.is_empty() { src.write_all(IP4RULES_MAPS.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; src.write_all(IP4_EVAL_FUNCS.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; } if !self.ipv6_rules.is_empty() { src.write_all(IP6RULES_MAPS.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; src.write_all(IP6_EVAL_FUNCS.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; } match (self.ipv6_rules.is_empty(), self.ipv4_rules.is_empty()) { (true, true) => src .write_all(EVAL_NOOP.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?, (true, false) => src .write_all(EVAL_ONLY_IP4.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?, (false, true) => src .write_all(EVAL_ONLY_IP6.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?, (false, false) => src .write_all(EVAL_BOTH_IPVER.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?, } src.write_all(PROGRAM.as_bytes()) .map_err(|e| Error::Internal(e.to_string()))?; Ok(src) } } fn generate_vmlinux_file(path: &Path) -> Result<File> { let mut hdr = File::create(path).map_err(|e| Error::Internal(e.to_string()))?; if let Err(e) = hdr.write_all(VMLINUX.as_bytes()) { panic!("{}", e.to_string()); } Ok(hdr) }
.update_map("ipv4_rules", &index, &initial_value, 0) .map_err(|e| Error::Internal(e.to_string()))?; } for (i, rule) in self.ipv6_rules.into_iter().enumerate() { let initial_value = bincode2::serialize(&rule).map_err(|e| Error::Internal(e.to_string()))?; let index = bincode2::serialize(&(i as u32)).map_err(|e| Error::Internal(e.to_string()))?; bpf_obj .update_map("ipv6_rules", &index, &initial_value, 0)
random
[ { "content": "pub fn load_filter(rules: Vec<Rule>, ifindex: i32) -> Result<BPFLink> {\n\n let mut f = Filter::new();\n\n for r in rules.into_iter() {\n\n f.add_rule(r);\n\n }\n\n Ok(f.load_on(ifindex)?)\n\n}\n\n\n", "file_path": "pf-rs/src/main.rs", "rank": 0, "score": 148013.1963...
Rust
src/bin/wasmtime.rs
erights/wasmtime
a5823896b70aab5f7675c5ff7651e37324c88262
#![deny( missing_docs, trivial_numeric_casts, unused_extern_crates, unstable_features )] #![warn(unused_import_braces)] #![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../clippy.toml")))] #![cfg_attr( feature = "cargo-clippy", allow(clippy::new_without_default, clippy::new_without_default_derive) )] #![cfg_attr( feature = "cargo-clippy", warn( clippy::float_arithmetic, clippy::mut_mut, clippy::nonminimal_bool, clippy::option_map_unwrap_or, clippy::option_map_unwrap_or_else, clippy::unicode_not_nfc, clippy::use_self ) )] use anyhow::{bail, Context as _, Result}; use docopt::Docopt; use serde::Deserialize; use std::path::{Component, Path}; use std::{collections::HashMap, ffi::OsStr, fs::File, process::exit}; use wasi_common::preopen_dir; use wasmtime::{Config, Engine, HostRef, Instance, Module, Store}; use wasmtime_cli::pick_compilation_strategy; use wasmtime_environ::{cache_create_new_config, cache_init}; use wasmtime_environ::{settings, settings::Configurable}; use wasmtime_interface_types::ModuleData; use wasmtime_jit::Features; use wasmtime_wasi::create_wasi_instance; use wasmtime_wasi::old::snapshot_0::create_wasi_instance as create_wasi_instance_snapshot_0; #[cfg(feature = "wasi-c")] use wasmtime_wasi_c::instantiate_wasi_c; const USAGE: &str = " Wasm runner. Takes a binary (wasm) or text (wat) WebAssembly module and instantiates it, including calling the start function if one is present. Additional functions given with --invoke are then called. Usage: wasmtime [-odg] [--enable-simd] [--wasi-c] [--disable-cache | \ --cache-config=<cache_config_file>] [--preload=<wasm>...] [--env=<env>...] [--dir=<dir>...] \ [--mapdir=<mapping>...] [--lightbeam | --cranelift] <file> [<arg>...] wasmtime [-odg] [--enable-simd] [--wasi-c] [--disable-cache | \ --cache-config=<cache_config_file>] [--env=<env>...] [--dir=<dir>...] \ [--mapdir=<mapping>...] --invoke=<fn> [--lightbeam | --cranelift] <file> [<arg>...] wasmtime --create-cache-config [--cache-config=<cache_config_file>] wasmtime --help | --version Options: --invoke=<fn> name of function to run -o, --optimize runs optimization passes on the translated functions --disable-cache disables cache system --cache-config=<cache_config_file> use specified cache configuration; can be used with --create-cache-config to specify custom file --create-cache-config creates default configuration and writes it to the disk, use with --cache-config to specify custom config file instead of default one -g generate debug information -d, --debug enable debug output on stderr/stdout --lightbeam use Lightbeam for all compilation --cranelift use Cranelift for all compilation --enable-simd enable proposed SIMD instructions --wasi-c enable the wasi-c implementation of `wasi_unstable` --preload=<wasm> load an additional wasm module before loading the main module --env=<env> pass an environment variable (\"key=value\") to the program --dir=<dir> grant access to the given host directory --mapdir=<mapping> where <mapping> has the form <wasmdir>::<hostdir>, grant access to the given host directory with the given wasm directory name -h, --help print this help message --version print the Cranelift version "; #[derive(Deserialize, Debug, Clone)] struct Args { arg_file: String, arg_arg: Vec<String>, flag_optimize: bool, flag_disable_cache: bool, flag_cache_config: Option<String>, flag_create_cache_config: bool, flag_debug: bool, flag_g: bool, flag_enable_simd: bool, flag_lightbeam: bool, flag_cranelift: bool, flag_invoke: Option<String>, flag_preload: Vec<String>, flag_env: Vec<String>, flag_dir: Vec<String>, flag_mapdir: Vec<String>, flag_wasi_c: bool, } fn compute_preopen_dirs(flag_dir: &[String], flag_mapdir: &[String]) -> Vec<(String, File)> { let mut preopen_dirs = Vec::new(); for dir in flag_dir { let preopen_dir = preopen_dir(dir).unwrap_or_else(|err| { println!("error while pre-opening directory {}: {}", dir, err); exit(1); }); preopen_dirs.push((dir.clone(), preopen_dir)); } for mapdir in flag_mapdir { let parts: Vec<&str> = mapdir.split("::").collect(); if parts.len() != 2 { println!( "--mapdir argument must contain exactly one double colon ('::'), separating a \ guest directory name and a host directory name" ); exit(1); } let (key, value) = (parts[0], parts[1]); let preopen_dir = preopen_dir(value).unwrap_or_else(|err| { println!("error while pre-opening directory {}: {}", value, err); exit(1); }); preopen_dirs.push((key.to_string(), preopen_dir)); } preopen_dirs } fn compute_argv(argv0: &str, arg_arg: &[String]) -> Vec<String> { let mut result = Vec::new(); result.push( Path::new(argv0) .components() .next_back() .map(Component::as_os_str) .and_then(OsStr::to_str) .unwrap_or("") .to_owned(), ); for arg in arg_arg { result.push(arg.to_owned()); } result } fn compute_environ(flag_env: &[String]) -> Vec<(String, String)> { let mut result = Vec::new(); for env in flag_env { let split = env.splitn(2, '=').collect::<Vec<_>>(); if split.len() != 2 { println!( "environment variables must be of the form \"key=value\"; got \"{}\"", env ); } result.push((split[0].to_owned(), split[1].to_owned())); } result } fn main() -> Result<()> { let version = env!("CARGO_PKG_VERSION"); let args: Args = Docopt::new(USAGE) .and_then(|d| { d.help(true) .version(Some(String::from(version))) .deserialize() }) .unwrap_or_else(|e| e.exit()); let log_config = if args.flag_debug { pretty_env_logger::init(); None } else { let prefix = "wasmtime.dbg."; wasmtime_cli::init_file_per_thread_logger(prefix); Some(prefix) }; if args.flag_create_cache_config { match cache_create_new_config(args.flag_cache_config) { Ok(path) => { println!( "Successfully created new configuation file at {}", path.display() ); return Ok(()); } Err(err) => { eprintln!("Error: {}", err); exit(1); } } } let errors = cache_init( !args.flag_disable_cache, args.flag_cache_config.as_ref(), log_config, ); if !errors.is_empty() { eprintln!("Cache initialization failed. Errors:"); for e in errors { eprintln!("-> {}", e); } exit(1); } let mut flag_builder = settings::builder(); let mut features: Features = Default::default(); flag_builder.enable("avoid_div_traps")?; let debug_info = args.flag_g; if cfg!(debug_assertions) { flag_builder.enable("enable_verifier")?; } if args.flag_enable_simd { flag_builder.enable("enable_simd")?; features.simd = true; } if args.flag_optimize { flag_builder.set("opt_level", "speed")?; } let strategy = pick_compilation_strategy(args.flag_cranelift, args.flag_lightbeam); let mut config = Config::new(); config .features(features) .flags(settings::Flags::new(flag_builder)) .debug_info(debug_info) .strategy(strategy); let engine = HostRef::new(Engine::new(&config)); let store = HostRef::new(Store::new(&engine)); let mut module_registry = HashMap::new(); let preopen_dirs = compute_preopen_dirs(&args.flag_dir, &args.flag_mapdir); let argv = compute_argv(&args.arg_file, &args.arg_arg); let environ = compute_environ(&args.flag_env); let wasi_unstable = HostRef::new(if args.flag_wasi_c { #[cfg(feature = "wasi-c")] { let global_exports = store.borrow().global_exports().clone(); let handle = instantiate_wasi_c(global_exports, &preopen_dirs, &argv, &environ)?; Instance::from_handle(&store, handle) } #[cfg(not(feature = "wasi-c"))] { bail!("wasi-c feature not enabled at build time") } } else { create_wasi_instance_snapshot_0(&store, &preopen_dirs, &argv, &environ)? }); let wasi_snapshot_preview1 = HostRef::new(create_wasi_instance( &store, &preopen_dirs, &argv, &environ, )?); module_registry.insert("wasi_unstable".to_owned(), wasi_unstable); module_registry.insert("wasi_snapshot_preview1".to_owned(), wasi_snapshot_preview1); for filename in &args.flag_preload { let path = Path::new(&filename); instantiate_module(&store, &module_registry, path) .with_context(|| format!("failed to process preload at `{}`", path.display()))?; } let path = Path::new(&args.arg_file); handle_module(&store, &module_registry, &args, path) .with_context(|| format!("failed to process main module `{}`", path.display()))?; Ok(()) } fn instantiate_module( store: &HostRef<Store>, module_registry: &HashMap<String, HostRef<Instance>>, path: &Path, ) -> Result<(HostRef<Instance>, HostRef<Module>, Vec<u8>)> { let data = wat::parse_file(path.to_path_buf())?; let module = HostRef::new(Module::new(store, &data)?); let imports = module .borrow() .imports() .iter() .map(|i| { let module_name = i.module(); if let Some(instance) = module_registry.get(module_name) { let field_name = i.name(); if let Some(export) = instance.borrow().find_export_by_name(field_name) { Ok(export.clone()) } else { bail!( "Import {} was not found in module {}", field_name, module_name ) } } else { bail!("Import module {} was not found", module_name) } }) .collect::<Result<Vec<_>, _>>()?; let instance = HostRef::new(Instance::new(store, &module, &imports)?); Ok((instance, module, data)) } fn handle_module( store: &HostRef<Store>, module_registry: &HashMap<String, HostRef<Instance>>, args: &Args, path: &Path, ) -> Result<()> { let (instance, module, data) = instantiate_module(store, module_registry, path)?; if let Some(f) = &args.flag_invoke { let data = ModuleData::new(&data)?; invoke_export(instance, &data, f, args)?; } else if module .borrow() .exports() .iter() .find(|export| export.name().is_empty()) .is_some() { let data = ModuleData::new(&data)?; invoke_export(instance, &data, "", args)?; } else { let data = ModuleData::new(&data)?; invoke_export(instance, &data, "_start", args)?; } Ok(()) } fn invoke_export( instance: HostRef<Instance>, data: &ModuleData, name: &str, args: &Args, ) -> Result<()> { use wasm_webidl_bindings::ast; use wasmtime_interface_types::Value; let mut handle = instance.borrow().handle().clone(); let binding = data.binding_for_export(&mut handle, name)?; if binding.param_types()?.len() > 0 { eprintln!( "warning: using `--invoke` with a function that takes arguments \ is experimental and may break in the future" ); } let mut values = Vec::new(); let mut args = args.arg_arg.iter(); for ty in binding.param_types()? { let val = match args.next() { Some(s) => s, None => bail!("not enough arguments for `{}`", name), }; values.push(match ty { ast::WebidlScalarType::Long => Value::I32(val.parse()?), ast::WebidlScalarType::LongLong => Value::I64(val.parse()?), ast::WebidlScalarType::UnsignedLong => Value::U32(val.parse()?), ast::WebidlScalarType::UnsignedLongLong => Value::U64(val.parse()?), ast::WebidlScalarType::Float | ast::WebidlScalarType::UnrestrictedFloat => { Value::F32(val.parse()?) } ast::WebidlScalarType::Double | ast::WebidlScalarType::UnrestrictedDouble => { Value::F64(val.parse()?) } ast::WebidlScalarType::DomString => Value::String(val.to_string()), t => bail!("unsupported argument type {:?}", t), }); } let results = data .invoke_export(&instance, name, &values) .with_context(|| format!("failed to invoke `{}`", name))?; if results.len() > 0 { eprintln!( "warning: using `--invoke` with a function that returns values \ is experimental and may break in the future" ); } for result in results { println!("{}", result); } Ok(()) }
#![deny( missing_docs, trivial_numeric_casts, unused_extern_crates, unstable_features )] #![warn(unused_import_braces)] #![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../clippy.toml")))] #![cfg_attr( feature = "cargo-clippy", allow(clippy::new_without_default, clippy::new_without_default_derive) )] #![cfg_attr( feature = "cargo-clippy", warn( clippy::float_arithmetic, clippy::mut_mut, clippy::nonminimal_bool, clippy::option_map_unwrap_or, clippy::option_map_unwrap_or_else, clippy::unicode_not_nfc, clippy::use_self ) )] use anyhow::{bail, Context as _, Result}; use docopt::Docopt; use serde::Deserialize; use std::path::{Component, Path}; use std::{collections::HashMap, ffi::OsStr, fs::File, process::exit}; use wasi_common::preopen_dir; use wasmtime::{Config, Engine, HostRef, Instance, Module, Store}; use wasmtime_cli::pick_compilation_strategy; use wasmtime_environ::{cache_create_new_config, cache_init}; use wasmtime_environ::{settings, settings::Configurable}; use wasmtime_interface_types::ModuleData; use wasmtime_jit::Features; use wasmtime_wasi::create_wasi_instance; use wasmtime_wasi::old::snapshot_0::create_wasi_instance as create_wasi_instance_snapshot_0; #[cfg(feature = "wasi-c")] use wasmtime_wasi_c::instantiate_wasi_c; const USAGE: &str = " Wasm runner. Takes a binary (wasm) or text (wat) WebAssembly module and instantiates it, including calling the start function if one is present. Additional functions given with --invoke are then called. Usage: wasmtime [-odg] [--enable-simd] [--wasi-c] [--disable-cache | \ --cache-config=<cache_config_file>] [--preload=<wasm>...] [--env=<env>...] [--dir=<dir>...] \ [--mapdir=<mapping>...] [--lightbeam | --cranelift] <file> [<arg>...] wasmtime [-odg] [--enable-simd] [--wasi-c] [--disable-cache | \ --cache-config=<cache_config_file>] [--env=<env>...] [--dir=<dir>...] \ [--mapdir=<mapping>...] --invoke=<fn> [--lightbeam | --cranelift] <file> [<arg>...] wasmtime --create-cache-config [--cache-config=<cache_config_file>] wasmtime --help | --version Options: --invoke=<fn> name of function to run -o, --optimize runs optimization passes on the translated functions --disable-cache disables cache system --cache-config=<cache_config_file> use specified cache configuration; can be used with --create-cache-config to specify custom file --create-cache-config creates default configuration and writes it to the disk, use with --cache-config to specify custom config file instead of default one -g generate debug information -d, --debug enable debug output on stderr/stdout --lightbeam use Lightbeam for all compilation --cranelift use Cranelift for all compilation --enable-simd enable proposed SIMD instructions --wasi-c enable the wasi-c implementation of `wasi_unstable` --preload=<wasm> load an additional wasm module before loading the main module --env=<env> pass an environment variable (\"key=value\") to the program --dir=<dir> grant access to the given host directory --mapdir=<mapping> where <mapping> has the form <wasmdir>::<hostdir>, grant access to the given host directory with the given wasm directory name -h, --help print this help message --version print the Cranelift version "; #[derive(Deserialize, Debug, Clone)] struct Args { arg_file: String, arg_arg: Vec<String>, flag_optimize: bool, flag_disable_cache: bool, flag_cache_config: Option<String>, flag_create_cache_config: bool, flag_debug: bool, flag_g: bool, flag_enable_simd: bool, flag_lightbeam: bool, flag_cranelift: bool, flag_invoke: Option<String>, flag_preload: Vec<String>, flag_env: Vec<String>, flag_dir: Vec<String>, flag_mapdir: Vec<String>, flag_wasi_c: bool, } fn compute_preopen_dirs(flag_dir: &[String], flag_mapdir: &[String]) -> Vec<(String, File)> { let mut preopen_dirs = Vec::new(); for dir in flag_dir { let preopen_dir = preopen_dir(dir).unwrap_or_else(|err| { println!("error while pre-opening directory {}: {}", dir, err); exit(1); }); preopen_dirs.push((dir.clone(), preopen_dir)); } for mapdir in flag_mapdir { let parts: Vec<&str> = mapdir.split("::").collect(); if parts.len() != 2 { println!( "--mapdir argument must contain exactly one double colon ('::'), separating a \ guest directory name and a host directory name" ); exit(1); } let (key, value) = (parts[0], parts[1]); let preopen_dir = preopen_dir(value).unwrap_or_else(|err| { println!("error while pre-opening directory {}: {}", value, err); exit(1); }); preopen_dirs.push((key.to_string(), preopen_dir)); } preopen_dirs } fn compute_argv(argv0: &str, arg_arg: &[String]) -> Vec<String> { let mut result = Vec::new(); result.push( Path::new(argv0) .components() .next_back() .map(Component::as_os_str) .and_then(OsStr::to_str) .unwrap_or("") .to_owned(), ); for arg in arg_arg { result.push(arg.to_owned()); } result } fn compute_environ(flag_env: &[String]) -> Vec<(String, String)> { let mut result = Vec::new(); for env in flag_env { let split = env.splitn(2, '=').collect::<Vec<_>>(); if split.len() != 2 { println!( "environment variables must be of the form \"key=value\"; got \"{}\"", env ); } result.push((split[0].to_owned(), split[1].to_owned())); } result } fn main() -> Result<()> { let version = env!("CARGO_PKG_VERSION"); let args: Args = Docopt::new(USAGE) .and_then(|d| { d.help(true) .version(Some(String::from(version))) .deserialize() }) .unwrap_or_else(|e| e.exit()); let log_config = if args.flag_debug { pretty_env_logger::init(); None } else { let prefix = "wasmtime.dbg."; wasmtime_cli::init_file_per_thread_logger(prefix); Some(prefix) }; if args.flag_create_cache_config { match cache_create_new_config(args.flag_cache_config) { Ok(path) => { println!( "Successfully created new configuation file at {}", path.display() ); return Ok(()); } Err(err) => { eprintln!("Error: {}", err); exit(1); } } } let errors = cache_init( !args.flag_disable_cache, args.flag_cache_config.as_ref(), log_config, );
let mut flag_builder = settings::builder(); let mut features: Features = Default::default(); flag_builder.enable("avoid_div_traps")?; let debug_info = args.flag_g; if cfg!(debug_assertions) { flag_builder.enable("enable_verifier")?; } if args.flag_enable_simd { flag_builder.enable("enable_simd")?; features.simd = true; } if args.flag_optimize { flag_builder.set("opt_level", "speed")?; } let strategy = pick_compilation_strategy(args.flag_cranelift, args.flag_lightbeam); let mut config = Config::new(); config .features(features) .flags(settings::Flags::new(flag_builder)) .debug_info(debug_info) .strategy(strategy); let engine = HostRef::new(Engine::new(&config)); let store = HostRef::new(Store::new(&engine)); let mut module_registry = HashMap::new(); let preopen_dirs = compute_preopen_dirs(&args.flag_dir, &args.flag_mapdir); let argv = compute_argv(&args.arg_file, &args.arg_arg); let environ = compute_environ(&args.flag_env); let wasi_unstable = HostRef::new(if args.flag_wasi_c { #[cfg(feature = "wasi-c")] { let global_exports = store.borrow().global_exports().clone(); let handle = instantiate_wasi_c(global_exports, &preopen_dirs, &argv, &environ)?; Instance::from_handle(&store, handle) } #[cfg(not(feature = "wasi-c"))] { bail!("wasi-c feature not enabled at build time") } } else { create_wasi_instance_snapshot_0(&store, &preopen_dirs, &argv, &environ)? }); let wasi_snapshot_preview1 = HostRef::new(create_wasi_instance( &store, &preopen_dirs, &argv, &environ, )?); module_registry.insert("wasi_unstable".to_owned(), wasi_unstable); module_registry.insert("wasi_snapshot_preview1".to_owned(), wasi_snapshot_preview1); for filename in &args.flag_preload { let path = Path::new(&filename); instantiate_module(&store, &module_registry, path) .with_context(|| format!("failed to process preload at `{}`", path.display()))?; } let path = Path::new(&args.arg_file); handle_module(&store, &module_registry, &args, path) .with_context(|| format!("failed to process main module `{}`", path.display()))?; Ok(()) } fn instantiate_module( store: &HostRef<Store>, module_registry: &HashMap<String, HostRef<Instance>>, path: &Path, ) -> Result<(HostRef<Instance>, HostRef<Module>, Vec<u8>)> { let data = wat::parse_file(path.to_path_buf())?; let module = HostRef::new(Module::new(store, &data)?); let imports = module .borrow() .imports() .iter() .map(|i| { let module_name = i.module(); if let Some(instance) = module_registry.get(module_name) { let field_name = i.name(); if let Some(export) = instance.borrow().find_export_by_name(field_name) { Ok(export.clone()) } else { bail!( "Import {} was not found in module {}", field_name, module_name ) } } else { bail!("Import module {} was not found", module_name) } }) .collect::<Result<Vec<_>, _>>()?; let instance = HostRef::new(Instance::new(store, &module, &imports)?); Ok((instance, module, data)) } fn handle_module( store: &HostRef<Store>, module_registry: &HashMap<String, HostRef<Instance>>, args: &Args, path: &Path, ) -> Result<()> { let (instance, module, data) = instantiate_module(store, module_registry, path)?; if let Some(f) = &args.flag_invoke { let data = ModuleData::new(&data)?; invoke_export(instance, &data, f, args)?; } else if module .borrow() .exports() .iter() .find(|export| export.name().is_empty()) .is_some() { let data = ModuleData::new(&data)?; invoke_export(instance, &data, "", args)?; } else { let data = ModuleData::new(&data)?; invoke_export(instance, &data, "_start", args)?; } Ok(()) } fn invoke_export( instance: HostRef<Instance>, data: &ModuleData, name: &str, args: &Args, ) -> Result<()> { use wasm_webidl_bindings::ast; use wasmtime_interface_types::Value; let mut handle = instance.borrow().handle().clone(); let binding = data.binding_for_export(&mut handle, name)?; if binding.param_types()?.len() > 0 { eprintln!( "warning: using `--invoke` with a function that takes arguments \ is experimental and may break in the future" ); } let mut values = Vec::new(); let mut args = args.arg_arg.iter(); for ty in binding.param_types()? { let val = match args.next() { Some(s) => s, None => bail!("not enough arguments for `{}`", name), }; values.push(match ty { ast::WebidlScalarType::Long => Value::I32(val.parse()?), ast::WebidlScalarType::LongLong => Value::I64(val.parse()?), ast::WebidlScalarType::UnsignedLong => Value::U32(val.parse()?), ast::WebidlScalarType::UnsignedLongLong => Value::U64(val.parse()?), ast::WebidlScalarType::Float | ast::WebidlScalarType::UnrestrictedFloat => { Value::F32(val.parse()?) } ast::WebidlScalarType::Double | ast::WebidlScalarType::UnrestrictedDouble => { Value::F64(val.parse()?) } ast::WebidlScalarType::DomString => Value::String(val.to_string()), t => bail!("unsupported argument type {:?}", t), }); } let results = data .invoke_export(&instance, name, &values) .with_context(|| format!("failed to invoke `{}`", name))?; if results.len() > 0 { eprintln!( "warning: using `--invoke` with a function that returns values \ is experimental and may break in the future" ); } for result in results { println!("{}", result); } Ok(()) }
if !errors.is_empty() { eprintln!("Cache initialization failed. Errors:"); for e in errors { eprintln!("-> {}", e); } exit(1); }
if_condition
[ { "content": "fn write_stats_file(path: &Path, stats: &ModuleCacheStatistics) -> bool {\n\n toml::to_string_pretty(&stats)\n\n .map_err(|err| {\n\n warn!(\n\n \"Failed to serialize stats file, path: {}, err: {}\",\n\n path.display(),\n\n err\n\n ...
Rust
src/io/read/take.rs
mvucenovic/async-std
98c79f4ff90e92de0ebec103709c9c41badc3dbd
use std::cmp; use std::pin::Pin; use crate::io::{self, BufRead, Read}; use crate::task::{Context, Poll}; #[derive(Debug)] pub struct Take<T> { pub(crate) inner: T, pub(crate) limit: u64, } impl<T> Take<T> { pub fn limit(&self) -> u64 { self.limit } pub fn set_limit(&mut self, limit: u64) { self.limit = limit; } pub fn into_inner(self) -> T { self.inner } pub fn get_ref(&self) -> &T { &self.inner } pub fn get_mut(&mut self) -> &mut T { &mut self.inner } } impl<T: Read + Unpin> Read for Take<T> { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { let Self { inner, limit } = &mut *self; take_read_internal(Pin::new(inner), cx, buf, limit) } } pub fn take_read_internal<R: Read + ?Sized>( mut rd: Pin<&mut R>, cx: &mut Context<'_>, buf: &mut [u8], limit: &mut u64, ) -> Poll<io::Result<usize>> { if *limit == 0 { return Poll::Ready(Ok(0)); } let max = cmp::min(buf.len() as u64, *limit) as usize; match futures_core::ready!(rd.as_mut().poll_read(cx, &mut buf[..max])) { Ok(n) => { *limit -= n as u64; Poll::Ready(Ok(n)) } Err(e) => Poll::Ready(Err(e)), } } impl<T: BufRead + Unpin> BufRead for Take<T> { fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> { let Self { inner, limit } = unsafe { self.get_unchecked_mut() }; let inner = unsafe { Pin::new_unchecked(inner) }; if *limit == 0 { return Poll::Ready(Ok(&[])); } match futures_core::ready!(inner.poll_fill_buf(cx)) { Ok(buf) => { let cap = cmp::min(buf.len() as u64, *limit) as usize; Poll::Ready(Ok(&buf[..cap])) } Err(e) => Poll::Ready(Err(e)), } } fn consume(mut self: Pin<&mut Self>, amt: usize) { let amt = cmp::min(amt as u64, self.limit) as usize; self.limit -= amt as u64; let rd = Pin::new(&mut self.inner); rd.consume(amt); } } #[cfg(test)] mod tests { use crate::io; use crate::prelude::*; use crate::task; #[test] fn test_take_basics() -> std::io::Result<()> { let source: io::Cursor<Vec<u8>> = io::Cursor::new(vec![0, 1, 2, 3, 4, 5, 6, 7, 8]); task::block_on(async move { let mut buffer = [0u8; 5]; let mut handle = source.take(5); handle.read(&mut buffer).await?; assert_eq!(buffer, [0, 1, 2, 3, 4]); assert_eq!(handle.read(&mut buffer).await.unwrap(), 0); Ok(()) }) } }
use std::cmp; use std::pin::Pin; use crate::io::{self, BufRead, Read}; use crate::task::{Context, Poll}; #[derive(Debug)] pub struct Take<T> { pub(crate) inner: T, pub(crate) limit: u64, } impl<T> Take<T> { pub fn limit(&self) -> u64 { self.limit } pub fn set_limit(&mut self, limit: u64) { self.limit = limit; } pub fn into_inner(self) -> T { self.inner } pub fn get_ref(&self) -> &T { &self.inner } pub fn get_mut(&mut self) -> &mut T { &mut self.inner } } impl<T: Read + Unpin> Read for Take<T> { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { let Self { inner, limit } = &mut *self; take_read_internal(Pin::new(inner), cx, buf, limit) } }
impl<T: BufRead + Unpin> BufRead for Take<T> { fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> { let Self { inner, limit } = unsafe { self.get_unchecked_mut() }; let inner = unsafe { Pin::new_unchecked(inner) }; if *limit == 0 { return Poll::Ready(Ok(&[])); } match futures_core::ready!(inner.poll_fill_buf(cx)) { Ok(buf) => { let cap = cmp::min(buf.len() as u64, *limit) as usize; Poll::Ready(Ok(&buf[..cap])) } Err(e) => Poll::Ready(Err(e)), } } fn consume(mut self: Pin<&mut Self>, amt: usize) { let amt = cmp::min(amt as u64, self.limit) as usize; self.limit -= amt as u64; let rd = Pin::new(&mut self.inner); rd.consume(amt); } } #[cfg(test)] mod tests { use crate::io; use crate::prelude::*; use crate::task; #[test] fn test_take_basics() -> std::io::Result<()> { let source: io::Cursor<Vec<u8>> = io::Cursor::new(vec![0, 1, 2, 3, 4, 5, 6, 7, 8]); task::block_on(async move { let mut buffer = [0u8; 5]; let mut handle = source.take(5); handle.read(&mut buffer).await?; assert_eq!(buffer, [0, 1, 2, 3, 4]); assert_eq!(handle.read(&mut buffer).await.unwrap(), 0); Ok(()) }) } }
pub fn take_read_internal<R: Read + ?Sized>( mut rd: Pin<&mut R>, cx: &mut Context<'_>, buf: &mut [u8], limit: &mut u64, ) -> Poll<io::Result<usize>> { if *limit == 0 { return Poll::Ready(Ok(0)); } let max = cmp::min(buf.len() as u64, *limit) as usize; match futures_core::ready!(rd.as_mut().poll_read(cx, &mut buf[..max])) { Ok(n) => { *limit -= n as u64; Poll::Ready(Ok(n)) } Err(e) => Poll::Ready(Err(e)), } }
function_block-full_function
[ { "content": "pub fn read_line_internal<R: BufRead + ?Sized>(\n\n reader: Pin<&mut R>,\n\n cx: &mut Context<'_>,\n\n buf: &mut String,\n\n bytes: &mut Vec<u8>,\n\n read: &mut usize,\n\n) -> Poll<io::Result<usize>> {\n\n let ret = futures_core::ready!(read_until_internal(reader, cx, b'\\n', byt...
Rust
src/simulation.rs
Phraeyll/rballistics-flat
451ec376bd22f98059d5dd22c05896d9b458133d
use crate::{ consts::{FRAC_PI_2, PI}, error::{Error, Result}, my_quantity, projectiles::ProjectileImpl, units::{ celsius, fahrenheit, foot_per_second, grain, inch, inch_of_mercury, kelvin, kilogram, meter, meter_per_second, meter_per_second_squared, mile_per_hour, pascal, radian, second, Acceleration, Angle, Length, Mass, MyQuantity, Pressure, ThermodynamicTemperature, Time, Velocity, }, Numeric, }; use std::ops::DerefMut; #[derive(Debug)] pub struct Simulation<T> { pub(crate) flags: Flags, pub(crate) projectile: T, pub(crate) scope: Scope, pub(crate) atmosphere: Atmosphere, pub(crate) wind: Wind, pub(crate) shooter: Shooter, pub(crate) time_step: Time, } #[derive(Debug)] pub struct Atmosphere { pub(crate) temperature: ThermodynamicTemperature, pub(crate) pressure: Pressure, pub(crate) humidity: Numeric, } #[derive(Debug)] pub struct Flags { pub(crate) coriolis: bool, pub(crate) drag: bool, pub(crate) gravity: bool, } #[derive(Debug)] pub struct Scope { pub(crate) yaw: Angle, pub(crate) pitch: Angle, pub(crate) roll: Angle, pub(crate) height: Length, pub(crate) offset: Length, } #[derive(Debug)] pub struct Shooter { pub(crate) yaw: Angle, pub(crate) pitch: Angle, pub(crate) roll: Angle, pub(crate) lattitude: Angle, pub(crate) gravity: Acceleration, } #[derive(Debug)] pub struct Wind { pub(crate) yaw: Angle, pub(crate) pitch: Angle, pub(crate) roll: Angle, pub(crate) velocity: Velocity, } #[derive(Debug)] pub struct SimulationBuilder<T> { pub(crate) builder: Simulation<T>, } impl<T> From<SimulationBuilder<T>> for Simulation<T> { fn from(other: SimulationBuilder<T>) -> Self { Self { ..other.builder } } } impl<T> From<Simulation<T>> for SimulationBuilder<T> { fn from(other: Simulation<T>) -> Self { Self { builder: other } } } impl<T> Default for SimulationBuilder<T> where T: From<ProjectileImpl>, { fn default() -> Self { Self { builder: Simulation { flags: Flags { coriolis: true, drag: true, gravity: true, }, projectile: From::from(ProjectileImpl { caliber: Length::new::<inch>(0.264), weight: Mass::new::<grain>(140.0), bc: 0.305, velocity: Velocity::new::<foot_per_second>(2710.0), }), scope: Scope { yaw: Angle::new::<radian>(0.0), pitch: Angle::new::<radian>(0.0), roll: Angle::new::<radian>(0.0), height: Length::new::<inch>(1.5), offset: Length::new::<inch>(0.0), }, atmosphere: Atmosphere { temperature: ThermodynamicTemperature::new::<fahrenheit>(68.0), pressure: Pressure::new::<inch_of_mercury>(29.92), humidity: 0.0, }, wind: Wind { yaw: Angle::new::<radian>(0.0), pitch: Angle::new::<radian>(0.0), roll: Angle::new::<radian>(0.0), velocity: Velocity::new::<mile_per_hour>(0.0), }, shooter: Shooter { yaw: Angle::new::<radian>(0.0), pitch: Angle::new::<radian>(0.0), roll: Angle::new::<radian>(0.0), lattitude: Angle::new::<radian>(0.0), gravity: my_quantity!(-9.806_65), }, time_step: Time::new::<second>(0.000_001), }, } } } impl<T> SimulationBuilder<T> where T: From<ProjectileImpl>, { pub fn new() -> Self { Default::default() } } impl<T> SimulationBuilder<T> { pub fn init(self) -> Simulation<T> { From::from(self) } pub fn set_time_step(mut self, value: Time) -> Result<Self> { let min = Time::new::<second>(0.0); let max = Time::new::<second>(0.1); if value > min && value <= max { self.builder.time_step = value; Ok(self) } else { Err(Error::OutOfRange { min: min.get::<second>(), max: max.get::<second>(), }) } } pub fn set_temperature(mut self, value: ThermodynamicTemperature) -> Result<Self> { let min = ThermodynamicTemperature::new::<celsius>(-80.0); let max = ThermodynamicTemperature::new::<celsius>(50.0); if value >= min && value <= max { self.builder.atmosphere.temperature = value; Ok(self) } else { Err(Error::OutOfRange { min: min.get::<kelvin>(), max: max.get::<kelvin>(), }) } } pub fn set_pressure(mut self, value: Pressure) -> Result<Self> { if value.is_sign_positive() { self.builder.atmosphere.pressure = value; Ok(self) } else { Err(Error::PositiveExpected(value.get::<pascal>())) } } pub fn set_humidity(mut self, value: Numeric) -> Result<Self> { let (min, max) = (0.0, 1.0); if value >= min && value <= max { self.builder.atmosphere.humidity = value; Ok(self) } else { Err(Error::OutOfRange { min, max }) } } pub fn use_coriolis(mut self, value: bool) -> Self { self.builder.flags.coriolis = value; self } pub fn use_drag(mut self, value: bool) -> Self { self.builder.flags.drag = value; self } pub fn use_gravity(mut self, value: bool) -> Self { self.builder.flags.gravity = value; self } pub fn set_shot_angle(mut self, value: Angle) -> Result<Self> { let min = Angle::new::<radian>(-FRAC_PI_2); let max = Angle::new::<radian>(FRAC_PI_2); if value >= min && value <= max { self.builder.shooter.pitch = value; Ok(self) } else { Err(Error::OutOfRange { min: min.get::<radian>(), max: max.get::<radian>(), }) } } pub fn set_lattitude(mut self, value: Angle) -> Result<Self> { let min = Angle::new::<radian>(-FRAC_PI_2); let max = Angle::new::<radian>(FRAC_PI_2); if value >= min && value <= max { self.builder.shooter.lattitude = value; Ok(self) } else { Err(Error::OutOfRange { min: min.get::<radian>(), max: max.get::<radian>(), }) } } pub fn set_bearing(mut self, value: Angle) -> Result<Self> { let min = Angle::new::<radian>(-2.0 * PI); let max = Angle::new::<radian>(2.0 * PI); if value >= min && value <= max { self.builder.shooter.yaw = value; Ok(self) } else { Err(Error::OutOfRange { min: min.get::<radian>(), max: max.get::<radian>(), }) } } pub fn set_gravity(mut self, value: Acceleration) -> Result<Self> { if value.is_sign_negative() { self.builder.shooter.gravity = value; Ok(self) } else { Err(Error::NegativeExpected( value.get::<meter_per_second_squared>(), )) } } pub fn set_wind_speed(mut self, value: Velocity) -> Result<Self> { if value.is_sign_positive() { self.builder.wind.velocity = value; Ok(self) } else { Err(Error::PositiveExpected(value.get::<meter_per_second>())) } } pub fn set_wind_angle(mut self, value: Angle) -> Result<Self> { let min = Angle::new::<radian>(-2.0 * PI); let max = Angle::new::<radian>(2.0 * PI); if value >= min && value <= max { self.builder.wind.yaw = value; Ok(self) } else { Err(Error::OutOfRange { min: min.get::<radian>(), max: max.get::<radian>(), }) } } pub fn set_scope_height(mut self, value: Length) -> Self { self.builder.scope.height = value; self } pub fn set_scope_offset(mut self, value: Length) -> Self { self.builder.scope.offset = value; self } pub fn set_scope_pitch(mut self, value: Angle) -> Self { self.builder.scope.pitch = value; self } pub fn set_scope_yaw(mut self, value: Angle) -> Self { self.builder.scope.yaw = value; self } pub fn set_scope_roll(mut self, value: Angle) -> Self { self.builder.scope.roll = value; self } } impl<T> SimulationBuilder<T> where T: DerefMut<Target = ProjectileImpl>, { pub fn set_caliber(mut self, value: Length) -> Result<Self> { if value.is_sign_positive() { self.builder.projectile.caliber = value; Ok(self) } else { Err(Error::PositiveExpected(value.get::<meter>())) } } pub fn set_velocity(mut self, value: Velocity) -> Result<Self> { if value.is_sign_positive() { self.builder.projectile.velocity = value; Ok(self) } else { Err(Error::PositiveExpected(value.get::<meter_per_second>())) } } pub fn set_mass(mut self, value: Mass) -> Result<Self> { if value.is_sign_positive() { self.builder.projectile.weight = value; Ok(self) } else { Err(Error::PositiveExpected(value.get::<kilogram>())) } } pub fn set_bc(mut self, value: Numeric) -> Result<Self> { if value.is_sign_positive() { self.builder.projectile.bc = value; Ok(self) } else { Err(Error::PositiveExpected(value)) } } }
use crate::{ consts::{FRAC_PI_2, PI}, error::{Error, Result}, my_quantity, projectiles::ProjectileImpl, units::{ celsius, fahrenheit, foot_per_second, grain, inch, inch_of_mercury, kelvin, kilogram, meter, meter_per_second, meter_per_second_squared, mile_per_hour, pascal, radian, second, Acceleration, Angle, Length, Mass, MyQuantity, Pressure, ThermodynamicTemperature, Time, Velocity, }, Numeric, }; use std::ops::DerefMut; #[derive(Debug)] pub struct Simulation<T> { pub(crate) flags: Flags, pub(crate) projectile: T, pub(crate) scope: Scope, pub(crate) atmosphere: Atmosphere, pub(crate) wind: Wind, pub(crate) shooter: Shooter, pub(crate) time_step: Time, } #[derive(Debug)] pub struct Atmosphere { pub(crate) temperature: ThermodynamicTemperature, pub(crate) pressure: Pressure, pub(crate) humidity: Numeric, } #[derive(Debug)] pub struct Flags { pub(crate) coriolis: bool, pub(crate) drag: bool, pub(crate) gravity: bool, } #[derive(Debug)] pub struct Scope { pub(crate) yaw: Angle, pub(crate) pitch: Angle, pub(crate) roll: Angle, pub(crate) height: Length, pub(crate) offset: Length, } #[derive(Debug)] pub struct Shooter { pub(crate) yaw: Angle, pub(crate) pitch: Angle, pub(crate) roll: Angle, pub(crate) lattitude: Angle, pub(crate) gravity: Acceleration, } #[derive(Debug)] pub struct Wind { pub(crate) yaw: Angle, pub(crate) pitch: Angle, pub(crate) roll: Angle, pub(crate) velocity: Velocity, } #[derive(Debug)] pub struct SimulationBuilder<T> { pub(crate) builder: Simulation<T>, } impl<T> From<SimulationBuilder<T>> for Simulation<T> { fn from(other: SimulationBuilder<T>) -> Self { Self { ..other.builder } } } impl<T> From<Simulation<T>> for SimulationBuilder<T> { fn from(other: Simulation<T>) -> Self { Self { builder: other } } } impl<T> Default for SimulationBuilder<T> where T: From<ProjectileImpl>, { fn default() -> Self { Self { builder: Simulation { flags: Flags { coriolis: true, drag: true, gravity: true, }, projectile: From::from(ProjectileImpl { caliber: Length::new::<inch>(0.264), weight: Mass::new::<grain>(140.0), bc: 0.305, velocity: Velocity::new::<foot_per_second>(2710.0), }), scope: Scope { yaw: Angle::new::<radian>(0.0), pitch: Angle::new::<radian>(0.0), roll: Angle::new::<radian>(0.0), height: Length::new::<inch>(1.5), offset: Length::new::<inch>(0.0), }, atmosphere: Atmosphere { temperature: ThermodynamicTemperature::new::<fahrenheit>(68.0), pressure: Pressure::new::<inch_of_mercury>(29.92), humidity: 0.0, }, wind: Wind { yaw: Angle::new::<radian>(0.0), pitch: Angle::new::<radian>(0.0), roll: Angle::new::<radian>(0.0), velocity: Velocity::new::<mile_per_hour>(0.0), }, shooter: Shooter { yaw: Angle::new::<radian>(0.0), pitch: Angle::new::<radian>(0.0), roll: Angle::new::<radian>(0.0), lattitude: Angle::new::<radian>(0.0), gravity: my_quantity!(-9.806_65), }, time_step: Time::new::<second>(0.000_001), }, } } } impl<T> SimulationBuilder<T> where T: From<ProjectileImpl>, { pub fn new() -> Self { Default::default() } } impl<T> SimulationBuilder<T> { pub fn init(self) -> Simulation<T> { From::from(self) } pub fn set_time_step(mut self, value: Time) -> Result<Self> { let min = Time::new::<second>(0.0); let max = Time::new::<second>(0.1); if value > min && value <= max { self.builder.time_step = value; Ok(self) } else { Err(Error::OutOfRange { min: min.get::<second>(), max: max.get::<second>(), }) } } pub fn set_temperature(mut self, value: ThermodynamicTemperature) -> Result<Self> { let min = ThermodynamicTemperature::new::<celsius>(-80.0); let max = ThermodynamicTemperature::new::<celsius>(50.0); if value >= min && value <= max { self.builder.atmosphere.temperature = value; Ok(self) } else { Err(Error::OutOfRange { min: min.get::<kelvin>(), max: max.get::<kelvin>(), }) } } pub fn set_pressure(mut self, value: Pressure) -> Result<Self> { if value.is_sign_positive() { self.builder.atmosphere.pressure = value; Ok(self) } else { Err(Error::PositiveExpected(value.get::<pascal>())) } } pub fn set_humidity(mut self, value: Numeric) -> Result<Self> { let (min, max) = (0.0, 1.0); if value >= min && value <= max { self.builder.atmosphere.humidity = value; Ok(self) } else { Err(Error::OutOfRange { min, max }) } } pub fn use_coriolis(mut self, value: bool) -> Self { self.builder.flags.coriolis = value; self } pub fn use_drag(mut self, value: bool) -> Self { self.builder.flags.drag = value; self } pub fn use_gravity(mut self, value: bool) -> Self { self.builder.flags.gravity = value; self } pub fn set_shot_angle(mut self, value: Angle) -> Result<Self> { let min = Angle::new::<radian>(-FRAC_PI_2); let max = Angle::new::<radian>(FRAC_PI_2); if value >= min && value <= max { self.builder.shooter.pitch = value; Ok(self) } else { Err(Error::OutOfRange { min: min.get::<radian>(), max: max.get::<radian>(), }) } } pub fn set_lattitude(mut self, value: Angle) -> Result<Self> { let min = Angle::new::<radian>(-FRAC_PI_2); let max = Angle::new::<radian>(FRAC_PI_2); if value >= min && value <= max { self.builder.shooter.lattitude = value; Ok(self) } else { Err(Error::OutOfRange { min: min.get::<radian>(), max: max.get::<radian>(), }) } } pub fn set_bearing(mut self, value: Angle) -> Result<Self> { let min = Angle::new::<radian>(-2.0 * PI); let max = Angle::new::<radian>(2.0 * PI); if value >= min && value <= max { self.builder.shooter.yaw = value; Ok(self) } else { Err(Error::OutOfRange { min: min.get::<radian>(), max: max.get::<radian>(), }) } } pub fn set_gravity(mut self, value: Acceleration) -> Result<Self> { if value.is_sign_negative() { self.builder.shooter.gravity = value; Ok(self) } else { Err(Error::NegativeExpected( value.get::<meter_per_second_squared>(), )) } } pub fn set_wind_speed(mut self, value: Velocity) -> Resu
pub fn set_wind_angle(mut self, value: Angle) -> Result<Self> { let min = Angle::new::<radian>(-2.0 * PI); let max = Angle::new::<radian>(2.0 * PI); if value >= min && value <= max { self.builder.wind.yaw = value; Ok(self) } else { Err(Error::OutOfRange { min: min.get::<radian>(), max: max.get::<radian>(), }) } } pub fn set_scope_height(mut self, value: Length) -> Self { self.builder.scope.height = value; self } pub fn set_scope_offset(mut self, value: Length) -> Self { self.builder.scope.offset = value; self } pub fn set_scope_pitch(mut self, value: Angle) -> Self { self.builder.scope.pitch = value; self } pub fn set_scope_yaw(mut self, value: Angle) -> Self { self.builder.scope.yaw = value; self } pub fn set_scope_roll(mut self, value: Angle) -> Self { self.builder.scope.roll = value; self } } impl<T> SimulationBuilder<T> where T: DerefMut<Target = ProjectileImpl>, { pub fn set_caliber(mut self, value: Length) -> Result<Self> { if value.is_sign_positive() { self.builder.projectile.caliber = value; Ok(self) } else { Err(Error::PositiveExpected(value.get::<meter>())) } } pub fn set_velocity(mut self, value: Velocity) -> Result<Self> { if value.is_sign_positive() { self.builder.projectile.velocity = value; Ok(self) } else { Err(Error::PositiveExpected(value.get::<meter_per_second>())) } } pub fn set_mass(mut self, value: Mass) -> Result<Self> { if value.is_sign_positive() { self.builder.projectile.weight = value; Ok(self) } else { Err(Error::PositiveExpected(value.get::<kilogram>())) } } pub fn set_bc(mut self, value: Numeric) -> Result<Self> { if value.is_sign_positive() { self.builder.projectile.bc = value; Ok(self) } else { Err(Error::PositiveExpected(value)) } } }
lt<Self> { if value.is_sign_positive() { self.builder.wind.velocity = value; Ok(self) } else { Err(Error::PositiveExpected(value.get::<meter_per_second>())) } }
function_block-function_prefixed
[ { "content": "pub fn table() -> NumericMap {\n\n float_btree_map![\n\n 0.00 => 0.1710,\n\n 0.05 => 0.1719,\n\n 0.10 => 0.1727,\n\n 0.15 => 0.1732,\n\n 0.20 => 0.1734,\n\n 0.25 => 0.1730,\n\n 0.30 => 0.1718,\n\n 0.35 => 0.1696,\n\n 0.40 =...
Rust
src/stream.rs
jws121295/dansible
4c32335b048560352135480ab0216ff5be6bd8fa
use byteorder::{BigEndian, ByteOrder, ReadBytesExt}; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::io::{Cursor, Seek, SeekFrom}; use session::{Session, PacketHandler}; pub enum Response<H, S = H> { Continue(H), Spawn(S), Close, } impl <H: Handler + 'static> Response<H> { pub fn boxed(self) -> Response<Box<Handler>> { match self { Response::Continue(handler) => Response::Continue(Box::new(handler)), Response::Spawn(handler) => Response::Spawn(Box::new(handler)), Response::Close => Response::Close, } } } pub trait Handler: Send { fn on_create(self, channel_id: ChannelId, session: &Session) -> Response<Self> where Self: Sized; fn on_header(self, header_id: u8, header_data: &[u8], session: &Session) -> Response<Self> where Self: Sized; fn on_data(self, data: &[u8], session: &Session) -> Response<Self> where Self: Sized; fn on_error(self, session: &Session) -> Response<Self> where Self: Sized; fn on_close(self, session: &Session) -> Response<Self> where Self: Sized; fn box_on_create(self: Box<Self>, channel_id: ChannelId, session: &Session) -> Response<Box<Handler>>; fn box_on_header(self: Box<Self>, header_id: u8, header_data: &[u8], session: &Session) -> Response<Box<Handler>>; fn box_on_data(self: Box<Self>, data: &[u8], session: &Session) -> Response<Box<Handler>>; fn box_on_error(self: Box<Self>, session: &Session) -> Response<Box<Handler>>; fn box_on_close(self: Box<Self>, session: &Session) -> Response<Box<Handler>>; } pub type ChannelId = u16; enum ChannelMode { Header, Data } struct Channel(ChannelMode, Box<Handler>); impl Channel { fn handle_packet(self, cmd: u8, data: Vec<u8>, session: &Session) -> Response<Self, Box<Handler>> { let Channel(mode, mut handler) = self; let mut packet = Cursor::new(&data as &[u8]); packet.read_u16::<BigEndian>().unwrap(); if cmd == 0xa { println!("error: {} {}", data.len(), packet.read_u16::<BigEndian>().unwrap()); return match handler.box_on_error(session) { Response::Continue(_) => Response::Close, Response::Spawn(f) => Response::Spawn(f), Response::Close => Response::Close, }; } match mode { ChannelMode::Header => { let mut length = 0; while packet.position() < data.len() as u64 { length = packet.read_u16::<BigEndian>().unwrap(); if length > 0 { let header_id = packet.read_u8().unwrap(); let header_data = &data[packet.position() as usize .. packet.position() as usize + length as usize - 1]; handler = match handler.box_on_header(header_id, header_data, session) { Response::Continue(handler) => handler, Response::Spawn(f) => return Response::Spawn(f), Response::Close => return Response::Close, }; packet.seek(SeekFrom::Current(length as i64 - 1)).unwrap(); } } if length == 0 { Response::Continue(Channel(ChannelMode::Data, handler)) } else { Response::Continue(Channel(ChannelMode::Header, handler)) } } ChannelMode::Data => { if packet.position() < data.len() as u64 { let event_data = &data[packet.position() as usize..]; match handler.box_on_data(event_data, session) { Response::Continue(handler) => Response::Continue(Channel(ChannelMode::Data, handler)), Response::Spawn(f) => Response::Spawn(f), Response::Close => Response::Close, } } else { match handler.box_on_close(session) { Response::Continue(_) => Response::Close, Response::Spawn(f) => Response::Spawn(f), Response::Close => Response::Close, } } } } } } pub struct StreamManager { next_id: ChannelId, channels: HashMap<ChannelId, Option<Channel>>, } impl StreamManager { pub fn new() -> StreamManager { StreamManager { next_id: 0, channels: HashMap::new(), } } pub fn create(&mut self, handler: Box<Handler>, session: &Session) { let channel_id = self.next_id; self.next_id += 1; trace!("allocated stream {}", channel_id); match handler.box_on_create(channel_id, session) { Response::Continue(handler) => { self.channels.insert(channel_id, Some(Channel(ChannelMode::Header, handler))); } Response::Spawn(handler) => self.create(handler, session), Response::Close => (), } } } impl PacketHandler for StreamManager { fn handle(&mut self, cmd: u8, data: Vec<u8>, session: &Session) { let id: ChannelId = BigEndian::read_u16(&data[0..2]); let spawn = if let Entry::Occupied(mut entry) = self.channels.entry(id) { if let Some(channel) = entry.get_mut().take() { match channel.handle_packet(cmd, data, session) { Response::Continue(channel) => { entry.insert(Some(channel)); None } Response::Spawn(f) => { entry.remove(); Some(f) } Response::Close => { entry.remove(); None } } } else { None } } else { None }; if let Some(s) = spawn { self.create(s, session); } } }
use byteorder::{BigEndian, ByteOrder, ReadBytesExt}; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::io::{Cursor, Seek, SeekFrom}; use session::{Session, PacketHandler}; pub enum Response<H, S = H> { Continue(H), Spawn(S), Close, } impl <H: Handler + 'static> Response<H> { pub fn boxed(self) -> Response<Box<Handler>> { match self { Response::Continue(handler) => Response::Continue(Box::new(handler)), Response::Spawn(handler) => Response::Spawn(Box::new(handler)), Response::Close => Response::Close, } } } pub trait Handler: Send { fn on_create(self, channel_id: ChannelId, session: &Session) -> Response<Self> where Self: Sized; fn on_header(self, header_id: u8, header_data: &[u8], session: &Session) -> Response<Self> where Self: Sized; fn on_data(self, data: &[u8], session: &Session) -> Response<Self> where Self: Sized; fn on_error(self, session: &Session) -> Response<Self> where Self: Sized; fn on_close(self, session: &Session) -> Response<Self> where Self: Sized; fn box_on_create(self: Box<Self>, channel_id: ChannelId, session: &Session) -> Response<Box<Handler>>; fn box_on_header(self: Box<Self>, header_id: u8, header_data: &[u8], session: &Session) -> Response<Box<Handler>>; fn box_on_data(self: Box<Self>, data: &[u8], session: &Session) -> Response<Box<Handler>>; fn box_on_error(self: Box<Self>, session: &Session) -> Response<Box<Handler>>; fn box_on_close(self: Box<Self>, session: &Session) -> Response<Box<Handler>>; } pub type ChannelId = u16; enum ChannelMode { Header, Data } struct Channel(ChannelMode, Box<Handler>); impl Channel { fn handle_packet(self, cmd: u8, data: Vec<u8>, session: &Session) -> Response<Self, Box<Handler>> { let Channel(mode, mut handler) = self; let mut packet = Cursor::new(&data as &[u8]); packet.read_u16::<BigEndian>().unwrap(); if cmd == 0xa { println!("error: {} {}", data.len(), packet.read_u16::<BigEndian>().unwrap()); return match handler.box_on_error(session) { Response::Continue(_) => Response::Close, Response::Spawn(f) => Response::Spawn(f), Response::Close => Response::Close, }; } match mode { ChannelMode::Header => { let mut length = 0; while packet.position() < data.len() as u64 { length = packet.read_u16::<BigEndian>().unwrap(); if length > 0 { let header_id = packet.read_u8().unwrap(); let header_data = &data[packet.position() as usize .. packet.position() as usize + length as usize - 1]; handler = match handler.box_on_header(header_id, header_data, session) { Response::Continue(handler) => handler, Response::Spawn(f) => return Response::Spawn(f), Response::Close => return Response::Close, }; packet.seek(SeekFrom::Current(length as i64 - 1)).unwrap(); } } if length == 0 { Response::Continue(Channel(ChannelMode::Data, handler)) } else { Response::Continue(Channel(ChannelMode::Header, handler)) } } ChannelMode::Data => { if packet.position() < data.len() as u64 { let event_data = &data[packet.position() as usize..]; match handler.box_on_data(event_data, session) { Response::Continue(handler) => Response::Continue(Channel(ChannelMode::Data, handler)), Response::Spawn(f) => Response::Spawn(f), Response::Close => Response::Close, } } else { match handler.box_on_close(session) { Response::Continue(_) => Response::Close, Response::Spawn(f) => Response::Spawn(f), Response::Close => Response::Close, } } } } } } pub struct StreamManager { next_id: ChannelId, channels: HashMap<ChannelId, Option<Channel>>, } impl StreamManager { pub fn new() -> StreamManager { StreamManager { next_id: 0, channels: HashMap::new(), } }
} impl PacketHandler for StreamManager { fn handle(&mut self, cmd: u8, data: Vec<u8>, session: &Session) { let id: ChannelId = BigEndian::read_u16(&data[0..2]); let spawn = if let Entry::Occupied(mut entry) = self.channels.entry(id) { if let Some(channel) = entry.get_mut().take() { match channel.handle_packet(cmd, data, session) { Response::Continue(channel) => { entry.insert(Some(channel)); None } Response::Spawn(f) => { entry.remove(); Some(f) } Response::Close => { entry.remove(); None } } } else { None } } else { None }; if let Some(s) = spawn { self.create(s, session); } } }
pub fn create(&mut self, handler: Box<Handler>, session: &Session) { let channel_id = self.next_id; self.next_id += 1; trace!("allocated stream {}", channel_id); match handler.box_on_create(channel_id, session) { Response::Continue(handler) => { self.channels.insert(channel_id, Some(Channel(ChannelMode::Header, handler))); } Response::Spawn(handler) => self.create(handler, session), Response::Close => (), } }
function_block-full_function
[ { "content": "pub trait Handler : Sized + Send + 'static {\n\n fn on_header(self, header_id: u8, header_data: &[u8], session: &Session) -> Response<Self>;\n\n fn on_data(self, offset: usize, data: &[u8], session: &Session) -> Response<Self>;\n\n fn on_eof(self, session: &Session) -> Response<Self>;\n\n...
Rust
butane/tests/common/pg.rs
DimmKG/butane
fcf9dcddb3e55f827daa9f54a6f276a9fce84903
use butane::db::{Backend, Connection, ConnectionSpec}; use once_cell::sync::Lazy; use std::io::{BufRead, BufReader, Read, Write}; use std::path::PathBuf; use std::process::{ChildStderr, Command, Stdio}; use uuid_for_test::Uuid; pub fn pg_connection() -> (Connection, PgSetupData) { let backend = butane::db::get_backend("pg").unwrap(); let data = pg_setup(); (backend.connect(&pg_connstr(&data)).unwrap(), data) } pub fn pg_connspec() -> (ConnectionSpec, PgSetupData) { let data = pg_setup(); ( ConnectionSpec::new(butane::db::pg::BACKEND_NAME, pg_connstr(&data)), data, ) } struct PgServerState { pub dir: PathBuf, pub sockdir: PathBuf, pub proc: std::process::Child, pub stderr: BufReader<ChildStderr>, } impl Drop for PgServerState { fn drop(&mut self) { self.proc.kill().ok(); let mut buf = String::new(); self.stderr.read_to_string(&mut buf).unwrap(); eprintln!("postgres stderr is {}", buf); std::fs::remove_dir_all(&self.dir).unwrap(); } } pub struct PgSetupData { pub connstr: String, } fn create_tmp_server() -> PgServerState { eprintln!("create tmp server"); let dir = std::env::current_dir() .unwrap() .join("tmp_pg") .join(Uuid::new_v4().to_string()); std::fs::create_dir_all(&dir).unwrap(); let output = Command::new("initdb") .arg("-D") .arg(&dir) .arg("-U") .arg("postgres") .output() .expect("failed to run initdb"); if !output.status.success() { std::io::stdout().write_all(&output.stdout).unwrap(); std::io::stderr().write_all(&output.stderr).unwrap(); panic!("postgres initdb failed") } let sockdir = dir.join("socket"); std::fs::create_dir(&sockdir).unwrap(); let mut proc = Command::new("postgres") .arg("-D") .arg(&dir) .arg("-k") .arg(&sockdir) .arg("-h") .arg("") .stderr(Stdio::piped()) .spawn() .expect("failed to run postgres"); let mut buf = String::new(); let mut stderr = BufReader::new(proc.stderr.take().unwrap()); loop { buf.clear(); stderr.read_line(&mut buf).unwrap(); if buf.contains("ready to accept connections") { break; } if proc.try_wait().unwrap().is_some() { buf.clear(); stderr.read_to_string(&mut buf).unwrap(); eprint!("{}", buf); panic!("postgres process died"); } } eprintln!("createdtmp server!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); PgServerState { dir, sockdir, proc, stderr, } } static TMP_SERVER: Lazy<PgServerState> = Lazy::new(|| create_tmp_server()); pub fn pg_setup() -> PgSetupData { eprintln!("pg_setup"); let connstr = match std::env::var("BUTANE_PG_CONNSTR") { Ok(connstr) => connstr, Err(_) => { let server = &TMP_SERVER; let host = server.sockdir.to_str().unwrap(); format!("host={} user=postgres", host) } }; let new_dbname = format!("butane_test_{}", Uuid::new_v4().to_simple()); eprintln!("new db is `{}`", &new_dbname); let mut conn = butane::db::connect(&ConnectionSpec::new("pg", &connstr)).unwrap(); conn.execute(format!("CREATE DATABASE {};", new_dbname)) .unwrap(); let connstr = format!("{} dbname={}", connstr, new_dbname); PgSetupData { connstr } } pub fn pg_teardown(_data: PgSetupData) { } pub fn pg_connstr(data: &PgSetupData) -> String { data.connstr.clone() }
use butane::db::{Backend, Connection, ConnectionSpec}; use once_cell::sync::Lazy; use std::io::{BufRead, BufReader, Read, Write}; use std::path::PathBuf; use std::process::{ChildStderr, Command, Stdio}; use uuid_for_test::Uuid; pub fn pg_connection() -> (Connection, PgSetupData) { let backend = butane::db::get_backend("pg").unwrap(); let data = pg_setup(); (backend.connect(&pg_connstr(&data)).unwrap(), data) } pub fn pg_connspec() -> (ConnectionSpec, PgSetupData) { let data = pg_setup(); ( ConnectionSpec::new(butane::db::pg::BACKEND_NAME, pg_connstr(&data)), data, ) } struct PgServerState { pub dir: PathBuf, pub sockdir: PathBuf, pub proc: std::process::Child, pub stderr: BufReader<ChildStderr>, } impl Drop for PgServerState { fn drop(&mut self) { self.proc.kill().ok(); let mut buf = String::new(); self.stderr.read_to_string(&mut buf).unwrap(); eprintln!("postgres stderr is {}", buf); std::fs::remove_dir_all(&self.dir).unwrap(); } } pub struct PgSetupData { pub connstr: String, } fn create_tmp_server() -> PgServerState { eprintln!("create tmp server"); let dir = std::env::current_dir() .unwrap() .join("tmp_pg") .join(Uuid::new_v4().to_string()); std::fs::create_dir_all(&dir).unwrap(); let output = Command::new("initdb") .arg("-D") .arg(&dir) .arg("-U") .arg("postgres") .output() .expect("failed to run initdb"); if !output.status.success() { std::io::stdout().write_all(&output.stdout).unwrap(); std::io::stderr().write_all(&output.stderr).unwrap(); panic!("postgres initdb failed") } let sockdir = dir.join("socket"); std::fs::create_dir(&sockdir).unwrap(); let mut proc = Command::new("postgres") .arg("-D") .arg(&dir) .arg("-k") .arg(&sockdir) .arg("-h") .arg("") .stderr(Stdio::piped()) .spawn() .expect("failed to run postgres"); let mut buf = String::new(); let mut stderr = BufReader::new(proc.stderr.take().unwrap()); loop { buf.clear(); stderr.read_line(&mut buf).unwrap(); if buf.contains("ready to accept connections") { break; }
} eprintln!("createdtmp server!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); PgServerState { dir, sockdir, proc, stderr, } } static TMP_SERVER: Lazy<PgServerState> = Lazy::new(|| create_tmp_server()); pub fn pg_setup() -> PgSetupData { eprintln!("pg_setup"); let connstr = match std::env::var("BUTANE_PG_CONNSTR") { Ok(connstr) => connstr, Err(_) => { let server = &TMP_SERVER; let host = server.sockdir.to_str().unwrap(); format!("host={} user=postgres", host) } }; let new_dbname = format!("butane_test_{}", Uuid::new_v4().to_simple()); eprintln!("new db is `{}`", &new_dbname); let mut conn = butane::db::connect(&ConnectionSpec::new("pg", &connstr)).unwrap(); conn.execute(format!("CREATE DATABASE {};", new_dbname)) .unwrap(); let connstr = format!("{} dbname={}", connstr, new_dbname); PgSetupData { connstr } } pub fn pg_teardown(_data: PgSetupData) { } pub fn pg_connstr(data: &PgSetupData) -> String { data.connstr.clone() }
if proc.try_wait().unwrap().is_some() { buf.clear(); stderr.read_to_string(&mut buf).unwrap(); eprint!("{}", buf); panic!("postgres process died"); }
if_condition
[ { "content": "pub fn sql_order(order: &[Order], w: &mut impl Write) {\n\n write!(w, \" ORDER BY \").unwrap();\n\n order.iter().fold(\"\", |sep, o| {\n\n let sql_dir = match o.direction {\n\n OrderDirection::Ascending => \"ASC\",\n\n OrderDirection::Descending => \"DESC\",\n\n ...
Rust
pretend/examples/responses.rs
orzogc/pretend
75824a5638b38e93bb9fe4cf35d2a59faf1053cc
use pretend::{pretend, Json, JsonResult, Pretend, Response, Result, Url}; use pretend_reqwest::Client; use serde::Deserialize; #[derive(Clone, Debug, Deserialize)] struct Contributor { login: String, } type Contributors = Vec<Contributor>; #[derive(Clone, Debug, Deserialize)] struct GithubError { message: String, } type ContributorsResult = JsonResult<Contributors, GithubError>; #[pretend] trait Github { #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn string(&self, repo: &str) -> Result<String>; #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn string_response(&self, repo: &str) -> Result<Response<String>>; #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn bytes(&self, repo: &str) -> Result<Vec<u8>>; #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn bytes_response(&self, repo: &str) -> Result<Response<Vec<u8>>>; #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn json(&self, repo: &str) -> Result<Json<Contributors>>; #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn json_response(&self, repo: &str) -> Result<Response<Json<Contributors>>>; #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn json_result(&self, repo: &str) -> Result<ContributorsResult>; #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn json_result_response(&self, repo: &str) -> Result<Response<ContributorsResult>>; } fn create_pretend() -> impl Github { let url = Url::parse("https://api.github.com").unwrap(); Pretend::for_client(Client::default()).with_url(url) } #[tokio::main] async fn main() { let pretend = create_pretend(); let result = pretend.string("pretend").await.unwrap(); println!("{}", result); let result = pretend.string_response("pretend").await.unwrap(); println!("HTTP {}, {}", result.status(), result.body()); let result = pretend.bytes("pretend").await.unwrap(); let body = String::from_utf8_lossy(&result); println!("{}", body); let result = pretend.bytes_response("pretend").await.unwrap(); let body = String::from_utf8_lossy(result.body()); println!("HTTP {}, {}", result.status(), body); let result = pretend.json("pretend").await.unwrap(); println!("{:?}", result.value()); let result = pretend.json_response("pretend").await.unwrap(); println!("HTTP {}, {:?}", result.status(), result.body()); let result = pretend.json_result("pretend").await.unwrap(); println!("{:?}", result); let result = pretend.json_result_response("pretend").await.unwrap(); println!("HTTP {}, {:?}", result.status(), result.body()); let result = pretend.string("non-existing").await; assert!(result.is_err()); let result = pretend.bytes("non-existing").await; assert!(result.is_err()); let result = pretend.json("non-existing").await; assert!(result.is_err()); let result = pretend.string_response("non-existing").await.unwrap(); assert_eq!(result.status().as_u16(), 404); let result = pretend.bytes_response("non-existing").await.unwrap(); assert_eq!(result.status().as_u16(), 404); let result = pretend.json_response("non-existing").await; assert!(result.is_err()); let result = pretend.json_result("non-existing").await.unwrap(); println!("{:?}", result); let result = pretend.json_result_response("non-existing").await.unwrap(); println!("HTTP {}, {:?}", result.status(), result.body()); }
use pretend::{pretend, Json, JsonResult, Pretend, Response, Result, Url}; use pretend_reqwest::Client; use serde::Deserialize; #[derive(Clone, Debug, Deserialize)] struct Contributor { login: String, } type Contributors = Vec<Contributor>; #[derive(Clone, Debug, Deserialize)] struct GithubError { message: String, } type ContributorsResult = JsonResult<Contributors, GithubError>; #[pretend] trait Github { #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn string(&self, repo: &str) -> Result<String>; #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn string_response(&self, repo: &str) -> Result<Response<String>>; #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn bytes(&self, repo: &str) -> Result<Vec<u8>>; #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn bytes_response(&self, repo: &str) -> Result<Response<Vec<u8>>>; #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn json(&self, repo: &str) -> Result<Json<Contributors>>; #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn json_response(&self, repo: &str) -> Result<Response<Json<Contributors>>>; #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn json_result(&self, repo: &str) -> Result<ContributorsResult>; #[request(method = "GET", path = "/repos/SfietKonstantin/{repo}/contributors")] #[header(name = "User-Agent", value = "pretend example")] async fn json_result_response(&self, repo: &str) -> Result<Response<ContributorsResult>>; } fn create_pretend() -> impl Github { let url = Url::parse("https://api.github.com").unwrap(); Pretend::for_client(Client::default()).with_url(url) } #[tokio::main] async fn main() { let pretend = create_pretend(); let result = pretend.string("pretend").await.unwrap(); println!("{}", result); let result = pretend.string_response("pretend").await.unwrap(); println!("HTTP {}, {}", result.status(), result.body()); let result = pretend.bytes("pretend").await.unwrap(); let body = String::from_utf8_lossy(&result); println!("{}", body); let result = pretend.bytes_response("pretend").await.unwrap(); let body = String::from_utf8_lossy(result.body()); println!("HTTP {}, {}", result.status(), body); let result = pretend.json("pretend").await.unwrap(); println!("{:?}", result.value()); let result = pretend.json_response("pretend").await.unwrap(); println!("HTTP {}, {:?}", result.status(), result.body()); let result = pretend.json_result("pretend").await.unwrap(); println!("{:?}", result); let result = preten
d.json_result_response("pretend").await.unwrap(); println!("HTTP {}, {:?}", result.status(), result.body()); let result = pretend.string("non-existing").await; assert!(result.is_err()); let result = pretend.bytes("non-existing").await; assert!(result.is_err()); let result = pretend.json("non-existing").await; assert!(result.is_err()); let result = pretend.string_response("non-existing").await.unwrap(); assert_eq!(result.status().as_u16(), 404); let result = pretend.bytes_response("non-existing").await.unwrap(); assert_eq!(result.status().as_u16(), 404); let result = pretend.json_response("non-existing").await; assert!(result.is_err()); let result = pretend.json_result("non-existing").await.unwrap(); println!("{:?}", result); let result = pretend.json_result_response("non-existing").await.unwrap(); println!("HTTP {}, {:?}", result.status(), result.body()); }
function_block-function_prefixed
[ { "content": "fn create_pretend() -> impl HttpBin {\n\n let url = Url::parse(\"https://httpbin.org\").unwrap();\n\n Pretend::for_client(Client::default()).with_url(url)\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() {\n\n let pretend = create_pretend();\n\n\n\n let result = pretend.post_string_ref(\"...
Rust
src/state.rs
virome/amethyst
f6cbdfe6e5c38838190e59a35b6e6d35115af0cb
use amethyst_input::is_close_requested; use ecs::prelude::World; use {GameData, StateEvent}; pub struct StateData<'a, T> where T: 'a, { pub world: &'a mut World, pub data: &'a mut T, } impl<'a, T> StateData<'a, T> where T: 'a, { pub fn new(world: &'a mut World, data: &'a mut T) -> Self { StateData { world, data } } } pub enum Trans<T, E> { None, Pop, Push(Box<State<T, E>>), Switch(Box<State<T, E>>), Quit, } pub type EmptyTrans = Trans<(), ()>; pub type SimpleTrans<'a, 'b> = Trans<GameData<'a, 'b>, ()>; pub trait State<T, E: Send + Sync + 'static> { fn on_start(&mut self, _data: StateData<T>) {} fn on_stop(&mut self, _data: StateData<T>) {} fn on_pause(&mut self, _data: StateData<T>) {} fn on_resume(&mut self, _data: StateData<T>) {} fn handle_event(&mut self, _data: StateData<T>, _event: StateEvent<E>) -> Trans<T, E> { Trans::None } fn fixed_update(&mut self, _data: StateData<T>) -> Trans<T, E> { Trans::None } fn update(&mut self, _data: StateData<T>) -> Trans<T, E> { Trans::None } } pub trait EmptyState { fn on_start(&mut self, _data: StateData<()>) {} fn on_stop(&mut self, _data: StateData<()>) {} fn on_pause(&mut self, _data: StateData<()>) {} fn on_resume(&mut self, _data: StateData<()>) {} fn handle_event(&mut self, _data: StateData<()>, event: StateEvent<()>) -> EmptyTrans { if let StateEvent::Window(event) = &event { if is_close_requested(&event) { Trans::Quit } else { Trans::None } } else { Trans::None } } fn fixed_update(&mut self, _data: StateData<()>) -> EmptyTrans { Trans::None } fn update(&mut self, _data: StateData<()>) -> EmptyTrans { Trans::None } } impl<T: EmptyState> State<(), ()> for T { fn on_start(&mut self, data: StateData<()>) { self.on_start(data) } fn on_stop(&mut self, data: StateData<()>) { self.on_stop(data) } fn on_pause(&mut self, data: StateData<()>) { self.on_pause(data) } fn on_resume(&mut self, data: StateData<()>) { self.on_resume(data) } fn handle_event(&mut self, data: StateData<()>, event: StateEvent<()>) -> EmptyTrans { self.handle_event(data, event) } fn fixed_update(&mut self, data: StateData<()>) -> EmptyTrans { self.fixed_update(data) } fn update(&mut self, data: StateData<()>) -> EmptyTrans { self.update(data) } } pub trait SimpleState<'a, 'b> { fn on_start(&mut self, _data: StateData<GameData>) {} fn on_stop(&mut self, _data: StateData<GameData>) {} fn on_pause(&mut self, _data: StateData<GameData>) {} fn on_resume(&mut self, _data: StateData<GameData>) {} fn handle_event( &mut self, _data: StateData<GameData>, event: StateEvent<()>, ) -> SimpleTrans<'a, 'b> { if let StateEvent::Window(event) = &event { if is_close_requested(&event) { Trans::Quit } else { Trans::None } } else { Trans::None } } fn fixed_update(&mut self, _data: StateData<GameData>) -> SimpleTrans<'a, 'b> { Trans::None } fn update(&mut self, _data: &mut StateData<GameData>) -> SimpleTrans<'a, 'b> { Trans::None } } impl<'a, 'b, T: SimpleState<'a, 'b>> State<GameData<'a, 'b>, ()> for T { fn on_start(&mut self, data: StateData<GameData>) { self.on_start(data) } fn on_stop(&mut self, data: StateData<GameData>) { self.on_stop(data) } fn on_pause(&mut self, data: StateData<GameData>) { self.on_pause(data) } fn on_resume(&mut self, data: StateData<GameData>) { self.on_resume(data) } fn handle_event( &mut self, data: StateData<GameData>, event: StateEvent<()>, ) -> SimpleTrans<'a, 'b> { self.handle_event(data, event) } fn fixed_update(&mut self, data: StateData<GameData>) -> SimpleTrans<'a, 'b> { self.fixed_update(data) } fn update(&mut self, mut data: StateData<GameData>) -> SimpleTrans<'a, 'b> { let r = self.update(&mut data); data.data.update(&data.world); r } } #[derive(Derivative)] #[derivative(Debug)] pub struct StateMachine<'a, T, E> { running: bool, #[derivative(Debug = "ignore")] state_stack: Vec<Box<State<T, E> + 'a>>, } impl<'a, T, E: Send + Sync + 'static> StateMachine<'a, T, E> { pub fn new<S: State<T, E> + 'a>(initial_state: S) -> StateMachine<'a, T, E> { StateMachine { running: false, state_stack: vec![Box::new(initial_state)], } } pub fn is_running(&self) -> bool { self.running } pub fn start(&mut self, data: StateData<T>) { if !self.running { let state = self.state_stack.last_mut().unwrap(); state.on_start(data); self.running = true; } } pub fn handle_event(&mut self, data: StateData<T>, event: StateEvent<E>) { let StateData { world, data } = data; if self.running { let trans = match self.state_stack.last_mut() { Some(state) => state.handle_event(StateData { world, data }, event), None => Trans::None, }; self.transition(trans, StateData { world, data }); } } pub fn fixed_update(&mut self, data: StateData<T>) { let StateData { world, data } = data; if self.running { let trans = match self.state_stack.last_mut() { Some(state) => state.fixed_update(StateData { world, data }), None => Trans::None, }; self.transition(trans, StateData { world, data }); } } pub fn update(&mut self, data: StateData<T>) { let StateData { world, data } = data; if self.running { let trans = match self.state_stack.last_mut() { Some(state) => state.update(StateData { world, data }), None => Trans::None, }; self.transition(trans, StateData { world, data }); } } fn transition(&mut self, request: Trans<T, E>, data: StateData<T>) { if self.running { match request { Trans::None => (), Trans::Pop => self.pop(data), Trans::Push(state) => self.push(state, data), Trans::Switch(state) => self.switch(state, data), Trans::Quit => self.stop(data), } } } fn switch(&mut self, state: Box<State<T, E>>, data: StateData<T>) { if self.running { let StateData { world, data } = data; if let Some(mut state) = self.state_stack.pop() { state.on_stop(StateData { world, data }); } self.state_stack.push(state); let state = self.state_stack.last_mut().unwrap(); state.on_start(StateData { world, data }); } } fn push(&mut self, state: Box<State<T, E>>, data: StateData<T>) { if self.running { let StateData { world, data } = data; if let Some(state) = self.state_stack.last_mut() { state.on_pause(StateData { world, data }); } self.state_stack.push(state); let state = self.state_stack.last_mut().unwrap(); state.on_start(StateData { world, data }); } } fn pop(&mut self, data: StateData<T>) { if self.running { let StateData { world, data } = data; if let Some(mut state) = self.state_stack.pop() { state.on_stop(StateData { world, data }); } if let Some(state) = self.state_stack.last_mut() { state.on_resume(StateData { world, data }); } else { self.running = false; } } } pub(crate) fn stop(&mut self, data: StateData<T>) { if self.running { let StateData { world, data } = data; while let Some(mut state) = self.state_stack.pop() { state.on_stop(StateData { world, data }); } self.running = false; } } } #[cfg(test)] mod tests { use super::*; struct State1(u8); struct State2; impl State<(), ()> for State1 { fn update(&mut self, _: StateData<()>) -> Trans<(), ()> { if self.0 > 0 { self.0 -= 1; Trans::None } else { Trans::Switch(Box::new(State2)) } } } impl State<(), ()> for State2 { fn update(&mut self, _: StateData<()>) -> Trans<(), ()> { Trans::Pop } } #[test] fn switch_pop() { use ecs::prelude::World; let mut world = World::new(); let mut sm = StateMachine::new(State1(7)); sm.start(StateData::new(&mut world, &mut ())); for _ in 0..8 { sm.update(StateData::new(&mut world, &mut ())); assert!(sm.is_running()); } sm.update(StateData::new(&mut world, &mut ())); assert!(!sm.is_running()); } }
use amethyst_input::is_close_requested; use ecs::prelude::World; use {GameData, StateEvent}; pub struct StateData<'a, T> where T: 'a, { pub world: &'a mut World, pub data: &'a mut T, } impl<'a, T> StateData<'a, T> where T: 'a, { pub fn new(world: &'a mut World, data: &'a mut T) -> Self { StateData { world, data } } } pub enum Trans<T, E> { None, Pop, Push(Box<State<T, E>>), Switch(Box<State<T, E>>), Quit, } pub type EmptyTrans = Trans<(), ()>; pub type SimpleTrans<'a, 'b> = Trans<GameData<'a, 'b>, ()>; pub trait State<T, E: Send + Sync + 'static> { fn on_start(&mut self, _data: StateData<T>) {} fn on_stop(&mut self, _data: StateData<T>) {} fn on_pause(&mut self, _data: StateData<T>) {} fn on_resume(&mut self, _data: StateData<T>) {} fn handle_event(&mut self, _data: StateData<T>, _event: StateEvent<E>) -> Trans<T, E> { Trans::None } fn fixed_update(&mut self, _data: StateData<T>) -> Trans<T, E> { Trans::None } fn update(&mut self, _data: StateData<T>) -> Trans<T, E> { Trans::None } } pub trait EmptyState { fn on_start(&mut self, _data: StateData<()>) {} fn on_stop(&mut self, _data: StateData<()>) {} fn on_pause(&mut self, _data: StateData<()>) {} fn on_resume(&mut self, _data: StateData<()>) {} fn handle_event(&mut self, _data: StateData<()>, event: StateEvent<()>) -> EmptyTrans { if let StateEvent::Window(event) = &event { if is_close_requested(&event) { Trans::Quit } else { Trans::None } } else { Trans::None } } fn fixed_update(&mut self, _data: StateData<()>) -> EmptyTrans { Trans::None } fn update(&mut self, _data: StateData<()>) -> EmptyTrans { Trans::None } } impl<T: EmptyState> State<(), ()> for T { fn on_start(&mut self, data: StateData<()>) { self.on_start(data) } fn on_stop(&mut self, data: StateData<()>) { self.on_stop(data) } fn on_pause(&mut self, data: StateData<()>) { self.on_pause(data) } fn on_resume(&mut self, data: StateData<()>) { self.on_resume(data) } fn handle_event(&mut self, data: StateData<()>, event: StateEvent<()>) -> EmptyTrans { self.handle_event(data, event) } fn fixed_update(&mut self, data: StateData<()>) -> EmptyTrans { self.fixed_update(data) } fn update(&mut self, data: StateData<()>) -> EmptyTrans { self.update(data) } } pub trait SimpleState<'a, 'b> { fn on_start(&mut self, _data: StateData<GameData>) {} fn on_stop(&mut self, _data: StateData<GameData>) {} fn on_pause(&mut self, _data: StateData<GameData>) {} fn on_resume(&mut self, _data: StateData<GameData>) {} fn handle_event( &mut self, _data: StateData<GameData>, event: StateEvent<()>, ) -> SimpleTrans<'a, 'b> { if let StateEvent::Window(event) = &event { if is_close_requested(&event) { Trans::Quit } else { Trans::None } } else { Trans::None } } fn fixed_update(&mut self, _data: StateData<GameData>) -> SimpleTrans<'a, 'b> { Trans::None } fn update(&mut self, _data: &mut StateData<GameData>) -> SimpleTrans<'a, 'b> { Trans::None } } impl<'a, 'b, T: SimpleState<'a, 'b>> State<GameData<'a, 'b>, ()> for T { fn on_start(&mut self, data: StateData<GameData>) { self.on_start(data) } fn on_stop(&mut self, data: StateData<GameData>) { self.on_stop(data) } fn on_pause(&mut self, data: StateData<GameData>) { self.on_pause(data) } fn on_resume(&mut self, data: StateData<GameData>) { self.on_resume(data) } fn handle_event( &mut self, data: StateData<GameData>, event: StateEvent<()>, ) -> SimpleTrans<'a, 'b> { self.handle_event(data, event) } fn fixed_update(&mut self, data: StateData<GameData>) -> SimpleTrans<'a, 'b> { self.fixed_update(data) } fn update(&mut self, mut data: StateData<GameData>) -> SimpleTrans<'a, 'b> { let r = self.update(&mut data); data.data.update(&data.world); r } } #[derive(Derivative)] #[derivative(Debug)] pub struct StateMachine<'a, T, E> { running: bool, #[derivative(Debug = "ignore")] state_stack: Vec<Box<State<T, E> + 'a>>, } impl<'a, T, E: Send + Sync + 'static> StateMachine<'a, T, E> { pub fn new<S: State<T, E> + 'a>(initial_state: S) -> StateMachine<'a, T, E> { StateMachine { running: false, state_stack: vec![Box::new(initial_state)], } } pub fn is_running(&self) -> bool { self.running } pub fn start(&mut self, data: StateData<T>) { if !self.running { let state = self.state_stack.last_mut().unwrap(); state.on_start(data); self.running = true; } } pub fn handle_event(&mut self, data: StateData<T>, event: StateEvent<E>) { let StateData { world, data } = data; if self.running { let trans = match self.state_stack.last_mut() { Some(state) => state.handle_event(StateData { world, data }, event), None => Trans::None, }; self.transition(trans, StateData { world, data }); } }
pub fn update(&mut self, data: StateData<T>) { let StateData { world, data } = data; if self.running { let trans = match self.state_stack.last_mut() { Some(state) => state.update(StateData { world, data }), None => Trans::None, }; self.transition(trans, StateData { world, data }); } } fn transition(&mut self, request: Trans<T, E>, data: StateData<T>) { if self.running { match request { Trans::None => (), Trans::Pop => self.pop(data), Trans::Push(state) => self.push(state, data), Trans::Switch(state) => self.switch(state, data), Trans::Quit => self.stop(data), } } } fn switch(&mut self, state: Box<State<T, E>>, data: StateData<T>) { if self.running { let StateData { world, data } = data; if let Some(mut state) = self.state_stack.pop() { state.on_stop(StateData { world, data }); } self.state_stack.push(state); let state = self.state_stack.last_mut().unwrap(); state.on_start(StateData { world, data }); } } fn push(&mut self, state: Box<State<T, E>>, data: StateData<T>) { if self.running { let StateData { world, data } = data; if let Some(state) = self.state_stack.last_mut() { state.on_pause(StateData { world, data }); } self.state_stack.push(state); let state = self.state_stack.last_mut().unwrap(); state.on_start(StateData { world, data }); } } fn pop(&mut self, data: StateData<T>) { if self.running { let StateData { world, data } = data; if let Some(mut state) = self.state_stack.pop() { state.on_stop(StateData { world, data }); } if let Some(state) = self.state_stack.last_mut() { state.on_resume(StateData { world, data }); } else { self.running = false; } } } pub(crate) fn stop(&mut self, data: StateData<T>) { if self.running { let StateData { world, data } = data; while let Some(mut state) = self.state_stack.pop() { state.on_stop(StateData { world, data }); } self.running = false; } } } #[cfg(test)] mod tests { use super::*; struct State1(u8); struct State2; impl State<(), ()> for State1 { fn update(&mut self, _: StateData<()>) -> Trans<(), ()> { if self.0 > 0 { self.0 -= 1; Trans::None } else { Trans::Switch(Box::new(State2)) } } } impl State<(), ()> for State2 { fn update(&mut self, _: StateData<()>) -> Trans<(), ()> { Trans::Pop } } #[test] fn switch_pop() { use ecs::prelude::World; let mut world = World::new(); let mut sm = StateMachine::new(State1(7)); sm.start(StateData::new(&mut world, &mut ())); for _ in 0..8 { sm.update(StateData::new(&mut world, &mut ())); assert!(sm.is_running()); } sm.update(StateData::new(&mut world, &mut ())); assert!(!sm.is_running()); } }
pub fn fixed_update(&mut self, data: StateData<T>) { let StateData { world, data } = data; if self.running { let trans = match self.state_stack.last_mut() { Some(state) => state.fixed_update(StateData { world, data }), None => Trans::None, }; self.transition(trans, StateData { world, data }); } }
function_block-full_function
[ { "content": "/// Master trait used to define animation sampling on a component\n\npub trait AnimationSampling: Send + Sync + 'static + for<'b> ApplyData<'b> {\n\n /// The interpolation primitive\n\n type Primitive: InterpolationPrimitive + Clone + Copy + Send + Sync + 'static;\n\n /// An independent g...
Rust
src/scene/mesh/vertex.rs
jackos/Fyrox
4b293733bda8e1a0a774aaf82554ac8930afdd8b
use crate::core::visitor::{Visit, VisitResult, Visitor}; use crate::{ core::algebra::{Vector2, Vector3, Vector4}, scene::mesh::buffer::{ VertexAttributeDataType, VertexAttributeDescriptor, VertexAttributeUsage, }, }; use std::hash::{Hash, Hasher}; #[derive(Copy, Clone, Debug, Default)] #[repr(C)] pub struct StaticVertex { pub position: Vector3<f32>, pub tex_coord: Vector2<f32>, pub normal: Vector3<f32>, pub tangent: Vector4<f32>, } impl StaticVertex { pub fn from_pos_uv(position: Vector3<f32>, tex_coord: Vector2<f32>) -> Self { Self { position, tex_coord, normal: Vector3::new(0.0, 1.0, 0.0), tangent: Vector4::default(), } } pub fn from_pos_uv_normal( position: Vector3<f32>, tex_coord: Vector2<f32>, normal: Vector3<f32>, ) -> Self { Self { position, tex_coord, normal, tangent: Vector4::default(), } } pub fn layout() -> &'static [VertexAttributeDescriptor] { static LAYOUT: [VertexAttributeDescriptor; 4] = [ VertexAttributeDescriptor { usage: VertexAttributeUsage::Position, data_type: VertexAttributeDataType::F32, size: 3, divisor: 0, shader_location: 0, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::TexCoord0, data_type: VertexAttributeDataType::F32, size: 2, divisor: 0, shader_location: 1, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::Normal, data_type: VertexAttributeDataType::F32, size: 3, divisor: 0, shader_location: 2, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::Tangent, data_type: VertexAttributeDataType::F32, size: 4, divisor: 0, shader_location: 3, }, ]; &LAYOUT } } impl PartialEq for StaticVertex { fn eq(&self, other: &Self) -> bool { self.position == other.position && self.tex_coord == other.tex_coord && self.normal == other.normal && self.tangent == other.tangent } } impl Hash for StaticVertex { fn hash<H: Hasher>(&self, state: &mut H) { #[allow(unsafe_code)] unsafe { let bytes = self as *const Self as *const u8; state.write(std::slice::from_raw_parts( bytes, std::mem::size_of::<Self>(), )) } } } #[derive(Copy, Clone, Debug, Default)] #[repr(C)] pub struct AnimatedVertex { pub position: Vector3<f32>, pub tex_coord: Vector2<f32>, pub normal: Vector3<f32>, pub tangent: Vector4<f32>, pub bone_weights: [f32; 4], pub bone_indices: [u8; 4], } impl AnimatedVertex { pub fn layout() -> &'static [VertexAttributeDescriptor] { static LAYOUT: [VertexAttributeDescriptor; 6] = [ VertexAttributeDescriptor { usage: VertexAttributeUsage::Position, data_type: VertexAttributeDataType::F32, size: 3, divisor: 0, shader_location: 0, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::TexCoord0, data_type: VertexAttributeDataType::F32, size: 2, divisor: 0, shader_location: 1, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::Normal, data_type: VertexAttributeDataType::F32, size: 3, divisor: 0, shader_location: 2, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::Tangent, data_type: VertexAttributeDataType::F32, size: 4, divisor: 0, shader_location: 3, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::BoneWeight, data_type: VertexAttributeDataType::F32, size: 4, divisor: 0, shader_location: 4, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::BoneIndices, data_type: VertexAttributeDataType::U8, size: 4, divisor: 0, shader_location: 5, }, ]; &LAYOUT } } impl PartialEq for AnimatedVertex { fn eq(&self, other: &Self) -> bool { self.position == other.position && self.tex_coord == other.tex_coord && self.normal == other.normal && self.tangent == other.tangent && self.bone_weights == other.bone_weights && self.bone_indices == other.bone_indices } } impl Hash for AnimatedVertex { fn hash<H: Hasher>(&self, state: &mut H) { #[allow(unsafe_code)] unsafe { let bytes = self as *const Self as *const u8; state.write(std::slice::from_raw_parts( bytes, std::mem::size_of::<Self>(), )) } } } #[derive(Copy, Clone, Debug, Default)] #[repr(C)] pub struct SimpleVertex { pub position: Vector3<f32>, } impl SimpleVertex { pub fn new(x: f32, y: f32, z: f32) -> Self { Self { position: Vector3::new(x, y, z), } } pub fn layout() -> &'static [VertexAttributeDescriptor] { static LAYOUT: [VertexAttributeDescriptor; 1] = [VertexAttributeDescriptor { usage: VertexAttributeUsage::Position, data_type: VertexAttributeDataType::F32, size: 3, divisor: 0, shader_location: 0, }]; &LAYOUT } } impl PartialEq for SimpleVertex { fn eq(&self, other: &Self) -> bool { self.position == other.position } } impl Hash for SimpleVertex { fn hash<H: Hasher>(&self, state: &mut H) { #[allow(unsafe_code)] unsafe { let bytes = self as *const Self as *const u8; state.write(std::slice::from_raw_parts( bytes, std::mem::size_of::<Self>(), )) } } } #[derive(Copy, Clone, Debug, Default)] #[repr(C)] pub struct OldVertex { pub position: Vector3<f32>, pub tex_coord: Vector2<f32>, pub normal: Vector3<f32>, pub tangent: Vector4<f32>, pub bone_weights: [f32; 4], pub bone_indices: [u8; 4], pub second_tex_coord: Vector2<f32>, } impl Visit for OldVertex { fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult { visitor.enter_region(name)?; self.position.visit("Position", visitor)?; self.tex_coord.visit("TexCoord", visitor)?; self.second_tex_coord.visit("SecondTexCoord", visitor)?; self.normal.visit("Normal", visitor)?; self.tangent.visit("Tangent", visitor)?; self.bone_weights[0].visit("Weight0", visitor)?; self.bone_weights[1].visit("Weight1", visitor)?; self.bone_weights[2].visit("Weight2", visitor)?; self.bone_weights[3].visit("Weight3", visitor)?; self.bone_indices[0].visit("BoneIndex0", visitor)?; self.bone_indices[1].visit("BoneIndex1", visitor)?; self.bone_indices[2].visit("BoneIndex2", visitor)?; self.bone_indices[3].visit("BoneIndex3", visitor)?; visitor.leave_region() } } impl OldVertex { pub fn layout() -> &'static [VertexAttributeDescriptor] { static LAYOUT: [VertexAttributeDescriptor; 7] = [ VertexAttributeDescriptor { usage: VertexAttributeUsage::Position, data_type: VertexAttributeDataType::F32, size: 3, divisor: 0, shader_location: 0, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::TexCoord0, data_type: VertexAttributeDataType::F32, size: 2, divisor: 0, shader_location: 1, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::Normal, data_type: VertexAttributeDataType::F32, size: 3, divisor: 0, shader_location: 2, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::Tangent, data_type: VertexAttributeDataType::F32, size: 4, divisor: 0, shader_location: 3, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::BoneWeight, data_type: VertexAttributeDataType::F32, size: 4, divisor: 0, shader_location: 4, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::BoneIndices, data_type: VertexAttributeDataType::U8, size: 4, divisor: 0, shader_location: 5, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::TexCoord1, data_type: VertexAttributeDataType::F32, size: 2, divisor: 0, shader_location: 6, }, ]; &LAYOUT } }
use crate::core::visitor::{Visit, VisitResult, Visitor}; use crate::{ core::algebra::{Vector2, Vector3, Vector4}, scene::mesh::buffer::{ VertexAttributeDataType, VertexAttributeDescriptor, VertexAttributeUsage, }, }; use std::hash::{Hash, Hasher}; #[derive(Copy, Clone, Debug, Default)] #[repr(C)] pub struct StaticVertex { pub position: Vector3<f32>, pub tex_coord: Vector2<f32>, pub normal: Vector3<f32>, pub tangent: Vector4<f32>, } impl StaticVertex { pub fn from_pos_uv(position: Vector3<f32>, tex_coord: Vector2<f32>) -> Self { Self { position, tex_coord, normal: Vector3::new(0.0, 1.0, 0.0), tangent: Vector4::default(), } } pub fn from_pos_uv_normal( position: Vector3<f32>, tex_coord: Vector2<f32>, normal: Vector3<f32>, ) -> Self { Self { position, tex_coord, normal, tangent: Vector4::default(), } } pub fn layout() -> &'static [VertexAttributeDescriptor] { static LAYOUT: [VertexAttributeDescriptor; 4] = [ VertexAttributeDescriptor { usage: VertexAttributeUsage::Position, data_type: VertexAttributeDataType::F32, size: 3, divisor: 0, shader_location: 0, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::TexCoord0, data_type: VertexAttributeDataType::F32, size: 2, divisor: 0, shader_location: 1, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::Normal, data_type: VertexAttributeDataType::F32, size: 3, divisor: 0, shader_location: 2, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::Tangent, data_type: VertexAttributeDataType::F32, size: 4, divisor: 0, shader_location: 3, }, ]; &LAYOUT } } impl PartialEq for StaticVertex { fn eq(&self, other: &Self) -> bool { self.position == other.position && self.tex_coord == other.tex_coord && self.normal == other.normal && self.tangent == other.tangent } } impl Hash for StaticVertex { fn hash<H: Hasher>(&self, state: &mut H) { #[allow(unsafe_code)] unsafe { let bytes = self as *const Self as *const u8; state.write(std::slice::from_raw_parts( bytes, std::mem::size_of::<Self>(), )) } } } #[derive(Copy, Clone, Debug, Default)] #[repr(C)] pub struct AnimatedVertex { pub position: Vector3<f32>, pub tex_coord: Vector2<f32>, pub normal: Vector3<f32>, pub tangent: Vector4<f32>, pub bone_weights: [f32; 4], pub bone_indices: [u8; 4], } impl AnimatedVertex { pub fn layout() -> &'static [VertexAttributeDescriptor] { static LAYOUT: [VertexAttributeDescriptor; 6] = [ VertexAttributeDescriptor { usage: VertexAttributeUsage::Position, data_type: VertexAttributeDataType::F32, size: 3, divisor: 0, shader_location: 0, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::TexCoord0, data_type: VertexAttributeDataType::F32, size: 2, divisor: 0, shader_location: 1, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::Normal, data_type: VertexAttributeDataType::F32, size: 3, divisor: 0, shader_location: 2, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::Tangent, data_type: VertexAttributeDataType::F32, size: 4, divisor: 0, shader_location: 3, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::BoneWeight, data_type: VertexAttributeDataType::F32, size: 4, divisor: 0, shader_location: 4, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::BoneIndices, data_type: VertexAttributeDataType::U8, size: 4, divisor: 0, shader_location: 5, }, ]; &LAYOUT } } impl PartialEq for AnimatedVertex { fn eq(&self, other: &Self) -> bool { self.position == other.position && self.tex_coord == other.tex_coord && self.normal == other.normal && self.tangent == other.tangent && self.bone_weights == other.bone_weights && self.bone_indices == other.bone_indices } } impl Hash for AnimatedVertex { fn hash<H: Hasher>(&self, state: &mut H) { #[allow(unsafe_code)] unsafe { let bytes = self as *const Self as *const u8; state.write(std::slice::from_raw_parts( bytes, std::mem::size_of::<Self>(), )) } } } #[derive(Copy, Clone, Debug, Default)] #[repr(C)] pub struct SimpleVertex { pub position: Vector3<f32>, } impl SimpleVertex { pub fn new(x: f32, y: f32, z: f32) -> Self { Self { position: Vector3::new(x, y, z), } } pub fn layout() -> &'static [VertexAttributeDescriptor] { static LAYOUT: [VertexAttributeDescriptor; 1] = [VertexAttributeDescriptor { usage: VertexAttributeUsage::Position, data_type: VertexAttributeDataType::F32, size: 3, divisor: 0, shader_location: 0, }]; &LAYOUT } } impl PartialEq for SimpleVertex { fn eq(&self, other: &Self) -> bool { self.position == other.position } } impl Hash for SimpleVertex { fn hash<H: Hasher>(&self, state: &mut H) { #[allow(unsafe_code)] unsafe { let bytes = self as *const Self as *const u8; state.write(std::slice::from_raw_parts( bytes, std::mem::size_of::<Self>(), )) } } } #[derive(Copy, Clone, Debug, Default)] #[repr(C)] pub struct OldVertex { pub position: Vector3<f32>, pub tex_coord: Vector2<f32>, pub normal: Vector3<f32>, pub tangent: Vector4<f32>, pub bone_weights: [f32; 4], pub bone_indices: [u8; 4], pub second_tex_coord: Vector2<f32>, } impl Visit for OldVertex { fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult { visitor.enter_region(name)?; self.position.visit("Position", visitor)?; self.tex_coord.visit("TexCoord", visitor)?; self.second_tex_coord.visit("SecondTexCoord", visitor)?; self.normal.visit("Normal", visitor)?; self.tangent.visit("Tangent", visitor)?; self.bone_weights[0].visit("Weight0", visitor)?; self.bone_weights
visitor)?; self.bone_indices[1].visit("BoneIndex1", visitor)?; self.bone_indices[2].visit("BoneIndex2", visitor)?; self.bone_indices[3].visit("BoneIndex3", visitor)?; visitor.leave_region() } } impl OldVertex { pub fn layout() -> &'static [VertexAttributeDescriptor] { static LAYOUT: [VertexAttributeDescriptor; 7] = [ VertexAttributeDescriptor { usage: VertexAttributeUsage::Position, data_type: VertexAttributeDataType::F32, size: 3, divisor: 0, shader_location: 0, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::TexCoord0, data_type: VertexAttributeDataType::F32, size: 2, divisor: 0, shader_location: 1, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::Normal, data_type: VertexAttributeDataType::F32, size: 3, divisor: 0, shader_location: 2, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::Tangent, data_type: VertexAttributeDataType::F32, size: 4, divisor: 0, shader_location: 3, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::BoneWeight, data_type: VertexAttributeDataType::F32, size: 4, divisor: 0, shader_location: 4, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::BoneIndices, data_type: VertexAttributeDataType::U8, size: 4, divisor: 0, shader_location: 5, }, VertexAttributeDescriptor { usage: VertexAttributeUsage::TexCoord1, data_type: VertexAttributeDataType::F32, size: 2, divisor: 0, shader_location: 6, }, ]; &LAYOUT } }
[1].visit("Weight1", visitor)?; self.bone_weights[2].visit("Weight2", visitor)?; self.bone_weights[3].visit("Weight3", visitor)?; self.bone_indices[0].visit("BoneIndex0",
function_block-random_span
[ { "content": "/// Performs hashing of a sized value by interpreting it as raw memory.\n\npub fn hash_as_bytes<T: Sized, H: Hasher>(value: &T, hasher: &mut H) {\n\n hasher.write(value_as_u8_slice(value))\n\n}\n", "file_path": "src/utils/mod.rs", "rank": 0, "score": 527698.0130796023 }, { "...
Rust
flare-agent/src/profile/tree.rs
kylixs/flare-profiler
dd27371476b1326a50b1d753a5a6e9bc4cf7c67b
use std::collections::HashMap; use std::rc::*; use std::borrow::Cow; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use std::sync::RwLock; use std::sync::Arc; use time::Duration; use thread::*; use log::{debug, info, warn}; use native::{JavaLong, JavaMethod}; use std::collections::hash_map::IterMut; static CALL_COUNT: AtomicUsize = AtomicUsize::new(0); fn get_next_nodeid() { CALL_COUNT.fetch_add(1, Ordering::SeqCst); } pub struct TreeArena { thread_trees: HashMap<JavaLong, CallStackTree>, } impl TreeArena { pub fn new() -> TreeArena { TreeArena { thread_trees: HashMap::new(), } } pub fn get_all_call_trees(&self) -> &HashMap<JavaLong, CallStackTree>{ &self.thread_trees } pub fn get_call_tree(&mut self, thread: &Thread) -> &mut CallStackTree { self.thread_trees.entry(thread.thread_id).or_insert_with(||{ CallStackTree::new(thread.thread_id, &thread.name) }); self.thread_trees.get_mut(&thread.thread_id).unwrap() } pub fn format_call_tree(&mut self, thread: &Thread, compact: bool) -> String { match self.thread_trees.get(&thread.thread_id) { Some(thread_data) => { println!("call tree of thread: [{}] [{}]", thread.thread_id, thread.name); thread_data.format_call_tree(compact) }, None => { println!("call tree not found of thread: [{}] [{}]", thread.thread_id, thread.name); String::from("[call tree not found]") } } } pub fn print_all(&self) { for (thread_id,thread_data) in self.thread_trees.iter() { println!("call tree of thread: [{}]", thread_id); println!("{}", thread_data.format_call_tree(false)); } } pub fn clear(&mut self) { self.thread_trees.clear(); println!("clear trace data"); } } pub struct CallStackTree { nodes: Vec<TreeNode>, root_node: NodeId, top_call_stack_node: NodeId, pub total_duration: i64, pub thread_id: JavaLong } impl CallStackTree { pub fn new(thread_id: JavaLong, thread_name: &str) -> CallStackTree { CallStackTree { nodes: vec![TreeNode::newRootNode(thread_name)], root_node: NodeId { index: 0 }, top_call_stack_node: NodeId { index: 0 }, total_duration: 0, thread_id: thread_id } } pub fn reset_top_call_stack_node(&mut self) { self.top_call_stack_node = self.root_node; } pub fn begin_call(&mut self, method_id: &JavaMethod) -> bool { let topNode = self.get_top_node(); match topNode.find_child(method_id) { Some(child_id) => { let node = self.get_node(child_id); self.top_call_stack_node = node.data.node_id.clone(); true }, None => { let next_index = self.nodes.len(); let topNode = self.get_mut_top_node(); let node_data = TreeNode::newCallNode(topNode, next_index, method_id); self.top_call_stack_node = node_data.data.node_id.clone(); self.nodes.push(node_data); false } } } pub fn end_call(&mut self, method_id: JavaMethod, call_name: &String, duration: i64) { let top_node = self.get_mut_top_node(); if top_node.data.name == *call_name { top_node.data.call_duration += duration; top_node.data.call_count += 1; debug!("end_call: {} {}, call_count:{}", call_name, duration, top_node.data.call_count); match &top_node.parent { Some(nodeid) => { self.top_call_stack_node = nodeid.clone(); }, None => { println!("parent node not found, pop call stack failed, call_name: {}, stack: {}, depth: {}", call_name, top_node.data.name, top_node.data.depth) } } } else { println!("call name mismatch, pop call stack failed, call_name: {}, top_node:{}, stack:{}, depth: {} ", call_name, top_node.data.name, top_node.data.name, top_node.data.depth); } } pub fn end_last_call(&mut self, total_duration: i64) { let last_duration = self.total_duration; let top_node = self.get_mut_top_node(); if(last_duration > 0){ top_node.data.call_duration += (total_duration - last_duration); } top_node.data.call_count += 1; self.total_duration = total_duration; } pub fn format_call_tree(&self, compact: bool) -> String { let mut result = String::with_capacity(8192); self.format_tree_node(&mut result,&self.root_node, compact); result } pub fn format_tree_node(&self, result: &mut String, nodeid: &NodeId, compact: bool) { let node = self.get_node(&nodeid); if compact { result.push_str(&node.data.depth.to_string()); result.push_str(","); } else { for x in 0..node.data.depth { result.push_str(" "); } } let mut call_duration = node.data.call_duration; if nodeid.index == 0 { for child in node.children.values() { call_duration += self.get_node(&child).data.call_duration; } }else { } let duration = call_duration/1000_000; result.push_str(&node.data.name); result.push_str(","); result.push_str(&node.data.call_count.to_string()); result.push_str(","); result.push_str(&duration.to_string()); result.push_str("\n"); for child in node.children.values() { self.format_tree_node(result,&child, compact); } } pub fn get_top_node(&self) -> &TreeNode { &self.nodes[self.top_call_stack_node.index] } pub fn get_mut_top_node(&mut self) -> &mut TreeNode { self.nodes.get_mut(self.top_call_stack_node.index).unwrap() } pub fn get_node(&self, node_id: &NodeId) -> &TreeNode { &self.nodes[node_id.index] } pub fn get_mut_node(&mut self, node_id: &NodeId) -> &mut TreeNode { &mut self.nodes[node_id.index] } pub fn get_root_node(&self) -> &TreeNode { &self.nodes[self.root_node.index] } } #[derive(Clone)] pub struct NodeData { pub node_id: NodeId, pub depth: u32, pub name: String, pub call_count: u32, pub call_duration: i64, pub children_size: u32 } #[derive(Clone, Copy)] pub struct NodeId { index: usize, } #[derive( Clone)] pub struct TreeNode { id: u64, pub data: NodeData, parent: Option<NodeId>, children: HashMap<u64, NodeId> } impl TreeNode { pub fn newRootNode(name: &str) -> TreeNode { TreeNode{ id: 0, data : NodeData { node_id: NodeId{index:0}, depth: 0, name: name.to_string(), call_count: 0, call_duration: 0, children_size: 0, }, parent: None, children: HashMap::new() } } pub fn newCallNode(parentNode: &mut TreeNode, next_index: usize, method_id: &JavaMethod) -> TreeNode { let node_id = NodeId{index:next_index}; parentNode.children.insert(*method_id as u64, node_id.clone()); parentNode.data.children_size += 1; TreeNode{ id: *method_id as u64, data : NodeData { node_id: node_id, name: String::new(), depth: parentNode.data.depth + 1, call_count: 0, call_duration: 0, children_size: 0, }, parent: Some(parentNode.data.node_id.clone()), children: HashMap::new(), } } fn find_child(&self, method_id: &JavaMethod) -> Option<&NodeId> { let key = *method_id as u64; self.children.get(&key) } }
use std::collections::HashMap; use std::rc::*; use std::borrow::Cow; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use std::sync::RwLock; use std::sync::Arc; use time::Duration; use thread::*; use log::{debug, info, warn}; use native::{JavaLong, JavaMethod}; use std::collections::hash_map::IterMut; static CALL_COUNT: AtomicUsize = AtomicUsize::new(0); fn get_next_nodeid() { CALL_COUNT.fetch_add(1, Ordering::SeqCst); } pub struct TreeArena { thread_trees: HashMap<JavaLong, CallStackTree>, } impl TreeArena { pub fn new() -> TreeArena { TreeArena { thread_trees: HashMap::new(), } } pub fn get_all_call_trees(&self) -> &HashMap<JavaLong, CallStackTree>{ &self.thread_trees } pub fn get_call_tree(&mut self, thread: &Thread) -> &mut CallStackTree { self.thread_trees.entry(thread.thread_id).or_insert_with(||{ CallStackTree::new(thread.thread_id, &thread.name) }); self.thread_trees.get_mut(&thread.thread_id).unwrap() } pub fn format_call_tree(&mut self, thread: &Thread, compact: bool) -> String { match self.thread_trees.get(&thread.thread_id) { Some(thread_data) => { println!("call tree of thread: [{}] [{}]", thread.thread_id, thread.name); thread_data.format_call_tree(compact) }, None => { println!("call tree not found of thread: [{}] [{}]", thread.thread_id, thread.name); String::from("[call tree not found]") } } } pub fn print_all(&self) { for (thread_id,thread_data) in self.thread_trees.iter() { println!("call tree of thread: [{}]", thread_id); println!("{}", thread_data.format_call_tree(false)); } } pub fn clear(&mut self) { self.thread_trees.clear(); println!("clear trace data"); } } pub struct CallStackTree { nodes: Vec<TreeNode>, root_node: NodeId, top_call_stack_node: NodeId, pub total_duration: i64, pub thread_id: JavaLong } impl CallStackTree { pub fn new(thread_id: JavaLong, thread_name: &st
pub fn reset_top_call_stack_node(&mut self) { self.top_call_stack_node = self.root_node; } pub fn begin_call(&mut self, method_id: &JavaMethod) -> bool { let topNode = self.get_top_node(); match topNode.find_child(method_id) { Some(child_id) => { let node = self.get_node(child_id); self.top_call_stack_node = node.data.node_id.clone(); true }, None => { let next_index = self.nodes.len(); let topNode = self.get_mut_top_node(); let node_data = TreeNode::newCallNode(topNode, next_index, method_id); self.top_call_stack_node = node_data.data.node_id.clone(); self.nodes.push(node_data); false } } } pub fn end_call(&mut self, method_id: JavaMethod, call_name: &String, duration: i64) { let top_node = self.get_mut_top_node(); if top_node.data.name == *call_name { top_node.data.call_duration += duration; top_node.data.call_count += 1; debug!("end_call: {} {}, call_count:{}", call_name, duration, top_node.data.call_count); match &top_node.parent { Some(nodeid) => { self.top_call_stack_node = nodeid.clone(); }, None => { println!("parent node not found, pop call stack failed, call_name: {}, stack: {}, depth: {}", call_name, top_node.data.name, top_node.data.depth) } } } else { println!("call name mismatch, pop call stack failed, call_name: {}, top_node:{}, stack:{}, depth: {} ", call_name, top_node.data.name, top_node.data.name, top_node.data.depth); } } pub fn end_last_call(&mut self, total_duration: i64) { let last_duration = self.total_duration; let top_node = self.get_mut_top_node(); if(last_duration > 0){ top_node.data.call_duration += (total_duration - last_duration); } top_node.data.call_count += 1; self.total_duration = total_duration; } pub fn format_call_tree(&self, compact: bool) -> String { let mut result = String::with_capacity(8192); self.format_tree_node(&mut result,&self.root_node, compact); result } pub fn format_tree_node(&self, result: &mut String, nodeid: &NodeId, compact: bool) { let node = self.get_node(&nodeid); if compact { result.push_str(&node.data.depth.to_string()); result.push_str(","); } else { for x in 0..node.data.depth { result.push_str(" "); } } let mut call_duration = node.data.call_duration; if nodeid.index == 0 { for child in node.children.values() { call_duration += self.get_node(&child).data.call_duration; } }else { } let duration = call_duration/1000_000; result.push_str(&node.data.name); result.push_str(","); result.push_str(&node.data.call_count.to_string()); result.push_str(","); result.push_str(&duration.to_string()); result.push_str("\n"); for child in node.children.values() { self.format_tree_node(result,&child, compact); } } pub fn get_top_node(&self) -> &TreeNode { &self.nodes[self.top_call_stack_node.index] } pub fn get_mut_top_node(&mut self) -> &mut TreeNode { self.nodes.get_mut(self.top_call_stack_node.index).unwrap() } pub fn get_node(&self, node_id: &NodeId) -> &TreeNode { &self.nodes[node_id.index] } pub fn get_mut_node(&mut self, node_id: &NodeId) -> &mut TreeNode { &mut self.nodes[node_id.index] } pub fn get_root_node(&self) -> &TreeNode { &self.nodes[self.root_node.index] } } #[derive(Clone)] pub struct NodeData { pub node_id: NodeId, pub depth: u32, pub name: String, pub call_count: u32, pub call_duration: i64, pub children_size: u32 } #[derive(Clone, Copy)] pub struct NodeId { index: usize, } #[derive( Clone)] pub struct TreeNode { id: u64, pub data: NodeData, parent: Option<NodeId>, children: HashMap<u64, NodeId> } impl TreeNode { pub fn newRootNode(name: &str) -> TreeNode { TreeNode{ id: 0, data : NodeData { node_id: NodeId{index:0}, depth: 0, name: name.to_string(), call_count: 0, call_duration: 0, children_size: 0, }, parent: None, children: HashMap::new() } } pub fn newCallNode(parentNode: &mut TreeNode, next_index: usize, method_id: &JavaMethod) -> TreeNode { let node_id = NodeId{index:next_index}; parentNode.children.insert(*method_id as u64, node_id.clone()); parentNode.data.children_size += 1; TreeNode{ id: *method_id as u64, data : NodeData { node_id: node_id, name: String::new(), depth: parentNode.data.depth + 1, call_count: 0, call_duration: 0, children_size: 0, }, parent: Some(parentNode.data.node_id.clone()), children: HashMap::new(), } } fn find_child(&self, method_id: &JavaMethod) -> Option<&NodeId> { let key = *method_id as u64; self.children.get(&key) } }
r) -> CallStackTree { CallStackTree { nodes: vec![TreeNode::newRootNode(thread_name)], root_node: NodeId { index: 0 }, top_call_stack_node: NodeId { index: 0 }, total_duration: 0, thread_id: thread_id } }
function_block-function_prefixed
[ { "content": "fn get_stack_traces(jvmenv: &Box<Environment>, thread_info_map: &mut HashMap<JavaLong, ThreadInfo>, update_cpu_time: bool) -> Result<Vec<JavaStackTrace>, NativeError> {\n\n let mut stack_traces = vec![];\n\n match jvmenv.get_all_threads() {\n\n Err(e) => {\n\n println!(\"ge...
Rust
src/arch/intel/interrupt/x2apic/local_apic.rs
VenmoTools/libarch
589bd07a2fdcd3dfc16adbbb8f6c5d720fd3cb0c
use bit_field::BitField; use crate::arch::intel::chips::flags::LocalAPICFlags; use crate::arch::intel::interrupt::ApicInfo; use crate::arch::intel::interrupt::x2apic::consts::*; use crate::arch::intel::interrupt::x2apic::register::{IpiAllShorthand, IpiDeliveryMode, IpiDestMode, LocalApicRegisters, TimerDivide, TimerMode}; #[derive(Debug)] pub struct LocalApic { timer_vector: usize, error_vector: usize, spurious_vector: usize, timer_mode: TimerMode, timer_divide: TimerDivide, timer_initial: u32, ipi_destination_mode: IpiDestMode, regs: LocalApicRegisters, } impl From<ApicInfo> for LocalApic { fn from(info: ApicInfo) -> Self { LocalApic { timer_vector: info.timer_vector.expect("missing timer vector"), error_vector: info.error_vector.expect("missing error vector"), spurious_vector: info.spurious_vector.expect("missing spurious vector"), timer_mode: info.timer_mode.unwrap_or(TimerMode::Periodic), timer_divide: info.timer_divide.unwrap_or(TimerDivide::Div256), timer_initial: info.timer_initial.unwrap_or(10_000_000), ipi_destination_mode: info .ipi_destination_mode .unwrap_or(IpiDestMode::Physical), regs: LocalApicRegisters::new(), } } } impl LocalApic { pub unsafe fn enable(&mut self) { self.x2apic_mode_enable(); self.remap_lvt_entries(); self.configure_timer(); self.enable_timer(); self.disable_local_interrupt_pins(); self.software_enable(); } pub unsafe fn disable(&mut self) { self.regs.set_base_bit(BASE_APIC_ENABLE, false); } pub unsafe fn end_of_interrupt(&mut self) { self.regs.write_eoi(0); } pub unsafe fn is_bsp(&self) -> bool { self.regs.base_bit(BASE_BSP) } pub unsafe fn id(&self) -> u32 { self.regs.id() as u32 } pub unsafe fn version(&self) -> u8 { self.regs.version_bit_range(VERSION_NR) as u8 } pub unsafe fn max_lvt_entry(&self) -> u8 { self.regs.version_bit_range(VERSION_MAX_LVT_ENTRY) as u8 } pub unsafe fn has_eoi_bcast_suppression(&self) -> bool { self.regs.version_bit(VERSION_EOI_BCAST_SUPPRESSION) } pub unsafe fn error_flags(&self) -> LocalAPICFlags { LocalAPICFlags::from_bits_truncate(self.regs.error() as u8) } pub unsafe fn enable_timer(&mut self) { self.regs.set_lvt_timer_bit(LVT_TIMER_MASK, false); } pub unsafe fn disable_timer(&mut self) { self.regs.set_lvt_timer_bit(LVT_TIMER_MASK, true); } pub unsafe fn set_timer_mode(&mut self, mode: TimerMode) { self.timer_mode = mode; self.regs.set_lvt_timer_bit_range(LVT_TIMER_MODE, mode.into()); } pub unsafe fn set_timer_divide(&mut self, divide: TimerDivide) { self.timer_divide = divide; self.regs .set_tdcr_bit_range(TDCR_DIVIDE_VALUE, divide.into()); } pub unsafe fn set_timer_initial(&mut self, initial: u32) { self.timer_initial = initial; self.regs.write_ticr(u64::from(initial)); } pub unsafe fn set_logical_id(&mut self, dest: u32) { self.regs.write_ldr(u64::from(dest)); } pub unsafe fn send_ipi(&mut self, vector: u8, dest: u32) { let mut icr_val = self.format_icr(vector, IpiDeliveryMode::Fixed); icr_val.set_bits(ICR_DESTINATION, u64::from(dest)); self.regs.write_icr(icr_val); } pub unsafe fn send_ipi_all(&mut self, vector: u8, who: IpiAllShorthand) { let mut icr_val = self.format_icr(vector, IpiDeliveryMode::Fixed); icr_val.set_bits(ICR_DEST_SHORTHAND, who.into()); self.regs.write_icr(icr_val); } pub unsafe fn send_lowest_priority_ipi(&mut self, vector: u8, dest: u32) { let mut icr_val = self.format_icr(vector, IpiDeliveryMode::LowestPriority); icr_val.set_bits(ICR_DESTINATION, u64::from(dest)); self.regs.write_icr(icr_val); } pub unsafe fn send_lowest_priority_ipi_all( &mut self, vector: u8, who: IpiAllShorthand, ) { let mut icr_val = self.format_icr(vector, IpiDeliveryMode::LowestPriority); icr_val.set_bits(ICR_DEST_SHORTHAND, who.into()); self.regs.write_icr(icr_val); } pub unsafe fn send_smi(&mut self, dest: u32) { let mut icr_val = self.format_icr(0, IpiDeliveryMode::SystemManagement); icr_val.set_bits(ICR_DESTINATION, u64::from(dest)); self.regs.write_icr(icr_val); } pub unsafe fn send_smi_all(&mut self, who: IpiAllShorthand) { let mut icr_val = self.format_icr(0, IpiDeliveryMode::SystemManagement); icr_val.set_bits(ICR_DEST_SHORTHAND, who.into()); self.regs.write_icr(icr_val); } pub unsafe fn send_nmi(&mut self, dest: u32) { let mut icr_val = self.format_icr(0, IpiDeliveryMode::NonMaskable); icr_val.set_bits(ICR_DESTINATION, u64::from(dest)); self.regs.write_icr(icr_val); } pub unsafe fn send_nmi_all(&mut self, who: IpiAllShorthand) { let mut icr_val = self.format_icr(0, IpiDeliveryMode::NonMaskable); icr_val.set_bits(ICR_DEST_SHORTHAND, who.into()); self.regs.write_icr(icr_val); } pub unsafe fn send_sipi(&mut self, vector: u8, dest: u32) { let mut icr_val = self.format_icr(vector, IpiDeliveryMode::StartUp); icr_val.set_bits(ICR_DESTINATION, u64::from(dest)); self.regs.write_icr(icr_val); } pub unsafe fn send_sipi_all(&mut self, vector: u8) { let mut icr_val = self.format_icr(vector, IpiDeliveryMode::StartUp); icr_val.set_bits( ICR_DEST_SHORTHAND, IpiAllShorthand::AllExcludingSelf.into(), ); self.regs.write_icr(icr_val); } pub unsafe fn send_ipi_self(&mut self, vector: u8) { self.regs.write_self_ipi(u64::from(vector)); } fn format_icr(&self, vector: u8, mode: IpiDeliveryMode) -> u64 { let mut icr_val = 0; icr_val.set_bits(ICR_VECTOR, u64::from(vector)); icr_val.set_bits(ICR_DELIVERY_MODE, mode.into()); icr_val.set_bit( ICR_DESTINATION_MODE, self.ipi_destination_mode == IpiDestMode::Logical, ); icr_val.set_bit(ICR_LEVEL, true); icr_val } unsafe fn x2apic_mode_enable(&mut self) { self.regs.set_base_bit(BASE_X2APIC_ENABLE, true); } unsafe fn software_enable(&mut self) { self.regs.set_sivr_bit(SIVR_APIC_SOFTWARE_ENABLE, true); } unsafe fn remap_lvt_entries(&mut self) { self.regs.set_lvt_timer_bit_range( LVT_TIMER_VECTOR, self.timer_vector as u64, ); self.regs.set_lvt_error_bit_range( LVT_ERROR_VECTOR, self.error_vector as u64, ); self.regs .set_sivr_bit_range(SIVR_VECTOR, self.spurious_vector as u64); } unsafe fn configure_timer(&mut self) { self.regs .set_lvt_timer_bit_range(LVT_TIMER_MODE, self.timer_mode.into()); self.regs .set_tdcr_bit_range(TDCR_DIVIDE_VALUE, self.timer_divide.into()); self.regs.write_ticr(u64::from(self.timer_initial)); } unsafe fn disable_local_interrupt_pins(&mut self) { self.regs.write_lvt_lint0(0); self.regs.write_lvt_lint1(0); } }
use bit_field::BitField; use crate::arch::intel::chips::flags::LocalAPICFlags; use crate::arch::intel::interrupt::ApicInfo; use crate::arch::intel::interrupt::x2apic::consts::*; use crate::arch::intel::interrupt::x2apic::register::{IpiAllShorthand, IpiDeliveryMode, IpiDestMode, LocalApicRegisters, TimerDivide, TimerMode}; #[derive(Debug)] pub struct LocalApic { timer_vector: usize, error_vector: usize, spurious_vector: usize, timer_mode: TimerMode, timer_divide: TimerDivide, timer_initial: u32, ipi_destination_mode: IpiDestMode, regs: LocalApicRegisters, } impl From<ApicInfo> for LocalApic { fn from(info: ApicInfo) -> Self { LocalApic { timer_vector: info.timer_vector.expect("missing timer vector"), error_vector: info.error_vector.expect("missing error vector"), spurious_vector: info.spurious_vector.expect("missing spurious vector"), timer_mode: info.timer_mode.unwrap_or(TimerMode::Periodic), timer_divide: info.timer_divide.unwrap_or(TimerDivide::Div256), timer_initial: info.timer_initial.unwrap_or(10_000_000), ipi_destination_mode: info .ipi_destination_mode .unwrap_or(IpiDestMode::Physical), regs: LocalApicRegisters::new(), } } } impl LocalApic { pub unsafe fn enable(&mut self) { self.x2apic_mode_enable(); self.remap_lvt_entries(); self.configure_timer(); self.enable_timer(); self.disable_local_interrupt_pins(); self.software_enable(); } pub unsafe fn disable(&mut self) { self.regs.set_base_bit(BASE_APIC_ENABLE, false); } pub unsafe fn end_of_interrupt(&mut self) { self.regs.write_eoi(0); } pub unsafe fn is_bsp(&self) -> bool { self.regs.base_bit(BASE_BSP) } pub unsafe fn id(&self) -> u32 { self.regs.id() as u32 } pub unsafe fn version(&self) -> u8 { self.regs.version_bit_range(VERSION_NR) as u8 } pub unsafe fn max_lvt_entry(&self) -> u8 { self.regs.version_bit_range(VERSION_MAX_LVT_ENTRY) as u8 } pub unsafe fn has_eoi_bcast_suppression(&self) -> bool { self.regs.version_bit(VERSION_EOI_BCAST_SUPPRESSION) } pub unsafe fn error_flags(&self) -> LocalAPICFlags { LocalAPICFlags::from_bits_truncate(self.regs.error() as u8) } pub unsafe fn enable_timer(&mut self) { self.regs.set_lvt_timer_bit(LVT_TIMER_MASK, false); } pub unsafe fn disable_timer(&mut self) { self.regs.set_lvt_timer_bit(LVT_TIMER_MASK, true); } pub unsafe fn set_timer_mode(&mut self, mode: TimerMode) { self.timer_mode = mode; self.regs.set_lvt_timer_bit_range(LVT_TIMER_MODE, mode.into()); } pub unsafe fn set_timer_divide(&mut self, divide: TimerDivide) { self.timer_divide = divide; self.regs .set_tdcr_bit_range(TDCR_DIVIDE_VALUE, divide.into()); } pub unsafe fn set_timer_initial(&mut self, initial: u32) { self.timer_initial = initial; self.regs.write_ticr(u64::from(initial)); } pub unsafe fn set_logical_id(&mut self, dest: u32) { self.regs.write_ldr(u64::from(dest)); } pub unsafe fn send_ipi(&mut self, vector: u8, dest: u32) { let mut icr_val = self.format_icr(vector, IpiDeliveryMode::Fixed); icr_val.set_bits(ICR_DESTINATION, u64::from(dest)); self.regs.write_icr(icr_val); } pub unsafe fn send_ipi_all(&mut self, vector: u8, who: IpiAllShorthand) { let mut icr_val = self.format_icr(vector, IpiDeliveryMode::Fixed); icr_val.set_bits(ICR_DEST_SHORTHAND, who.into()); self.regs.write_icr(icr_val); } pub unsafe fn send_lowest_priority_ipi(&mut self, vector: u8, dest: u32) { let mut icr_val = self.format_icr(vector, IpiDeliveryMode::LowestPriority); icr_val.set_bits(ICR_DESTINATION, u64::from(dest)); self.regs.write_icr(icr_val); } pub unsafe fn send_lowest_priority_ipi_all( &mut self, vector: u8, who: IpiAllShorthand, ) { let mut icr_val = self.format_icr(vector, IpiDeliveryMode::LowestPriority); icr_val.set_bits(ICR_DEST_SHORTHAND, who.into()); self.regs.write_icr(icr_val); } pub unsafe fn send_smi(&mut self, dest: u32) { let mut icr_val = self.format_icr(0, IpiDeliveryMode::SystemManagement); icr_val.set_bits(ICR_DESTINATION, u64::from(dest)); self.regs.write_icr(icr_val); } pub unsafe fn send_smi_all(&mut self, who: IpiAllShorthand) { let mut icr_val = self.format_icr(0, IpiDeliveryMode::SystemManagement); icr_val.set_bits(ICR_DEST_SHORTHAND, who.into()); self.regs.write_icr(icr_val); } pub unsafe fn send_nmi(&mut self, dest: u32) { let mut icr_val = self.format_icr(0, IpiDeliveryMode::NonMaskable); icr_val.set_bits(ICR_DESTINATION, u64::from(dest)); self.regs.write_icr(icr_val); } pub unsafe fn send_nmi_all(&mut self, who: IpiAllShorthand) {
pub unsafe fn send_sipi(&mut self, vector: u8, dest: u32) { let mut icr_val = self.format_icr(vector, IpiDeliveryMode::StartUp); icr_val.set_bits(ICR_DESTINATION, u64::from(dest)); self.regs.write_icr(icr_val); } pub unsafe fn send_sipi_all(&mut self, vector: u8) { let mut icr_val = self.format_icr(vector, IpiDeliveryMode::StartUp); icr_val.set_bits( ICR_DEST_SHORTHAND, IpiAllShorthand::AllExcludingSelf.into(), ); self.regs.write_icr(icr_val); } pub unsafe fn send_ipi_self(&mut self, vector: u8) { self.regs.write_self_ipi(u64::from(vector)); } fn format_icr(&self, vector: u8, mode: IpiDeliveryMode) -> u64 { let mut icr_val = 0; icr_val.set_bits(ICR_VECTOR, u64::from(vector)); icr_val.set_bits(ICR_DELIVERY_MODE, mode.into()); icr_val.set_bit( ICR_DESTINATION_MODE, self.ipi_destination_mode == IpiDestMode::Logical, ); icr_val.set_bit(ICR_LEVEL, true); icr_val } unsafe fn x2apic_mode_enable(&mut self) { self.regs.set_base_bit(BASE_X2APIC_ENABLE, true); } unsafe fn software_enable(&mut self) { self.regs.set_sivr_bit(SIVR_APIC_SOFTWARE_ENABLE, true); } unsafe fn remap_lvt_entries(&mut self) { self.regs.set_lvt_timer_bit_range( LVT_TIMER_VECTOR, self.timer_vector as u64, ); self.regs.set_lvt_error_bit_range( LVT_ERROR_VECTOR, self.error_vector as u64, ); self.regs .set_sivr_bit_range(SIVR_VECTOR, self.spurious_vector as u64); } unsafe fn configure_timer(&mut self) { self.regs .set_lvt_timer_bit_range(LVT_TIMER_MODE, self.timer_mode.into()); self.regs .set_tdcr_bit_range(TDCR_DIVIDE_VALUE, self.timer_divide.into()); self.regs.write_ticr(u64::from(self.timer_initial)); } unsafe fn disable_local_interrupt_pins(&mut self) { self.regs.write_lvt_lint0(0); self.regs.write_lvt_lint1(0); } }
let mut icr_val = self.format_icr(0, IpiDeliveryMode::NonMaskable); icr_val.set_bits(ICR_DEST_SHORTHAND, who.into()); self.regs.write_icr(icr_val); }
function_block-function_prefix_line
[ { "content": "// Gets the upper segment selector for `irq`\n\npub fn hi(irq: u8) -> u32 {\n\n lo(irq) + 1\n\n}\n\n\n\n\n\nimpl IrqMode {\n\n pub(super) fn as_u32(self) -> u32 {\n\n self as u32\n\n }\n\n}\n\n\n\n/// The IOAPIC structure.\n\n#[derive(Debug)]\n\npub struct IoApic {\n\n regs: IoA...
Rust
src/server/mod.rs
Twixes/metrobaza
edc5bfa8080b91fffdf13276ec2f79d340582963
use crate::config; use crate::constructs::components::Validatable; use crate::executor::{ExecutorPayload, QueryResult}; use crate::sql::parse_statement; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Method, Request, Response, Server, StatusCode}; use serde::{ser::SerializeMap, Serialize, Serializer}; use std::collections::HashMap; use std::{convert, net, str::FromStr}; use thiserror::Error; use tokio::sync::{mpsc, oneshot}; use tokio::time; use tracing::*; use ulid::Ulid; #[derive(Error, Debug, PartialEq)] #[error("ServerError: {0}")] pub struct ServerError(pub String); impl Serialize for ServerError { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut map = serializer.serialize_map(Some(2))?; map.serialize_entry("type", "server")?; map.serialize_entry("message", &self.0)?; map.end() } } async fn process_post( executor_tx: mpsc::Sender<ExecutorPayload>, body: &str, ) -> (StatusCode, String) { let statement = parse_statement(&body); if let Err(parsing_error) = statement { return ( StatusCode::BAD_REQUEST, serde_json::to_string(&parsing_error).unwrap(), ); } let statement = statement.unwrap(); if let Err(validation_error) = statement.validate() { return ( StatusCode::BAD_REQUEST, serde_json::to_string(&validation_error).unwrap(), ); } let (resp_tx, resp_rx) = oneshot::channel::<QueryResult>(); if let Err(_) = executor_tx.send((statement, resp_tx)).await { return ( StatusCode::INTERNAL_SERVER_ERROR, serde_json::to_string(&ServerError("The query executor has disengaged.".into())) .unwrap(), ); } let query_result = resp_rx.await; ( StatusCode::OK, serde_json::to_string_pretty(&query_result.unwrap()).unwrap(), ) } async fn process_get( _executor_tx: mpsc::Sender<ExecutorPayload>, query: Option<&str>, ) -> (StatusCode, String) { if let Some(query_string) = query { if let Ok(query_map) = serde_urlencoded::from_str::<HashMap<String, String>>(query_string) { if let Some(query) = query_map.get("query") { (StatusCode::OK, query.to_string()) } else { (StatusCode::BAD_REQUEST, "TODO: No query param".to_string()) } } else { ( StatusCode::BAD_REQUEST, "TODO: Bad query string".to_string(), ) } } else { (StatusCode::BAD_REQUEST, "TODO: No query string".to_string()) } } async fn echo( executor_tx: mpsc::Sender<ExecutorPayload>, req: Request<Body>, ) -> Result<Response<Body>, hyper::Error> { let timer = time::Instant::now(); let request_id = Ulid::new(); debug!("⚡️ Received request ID {}", request_id); let response_builder = Response::builder().header("Content-Type", "application/json"); let result = match (req.uri().path(), req.method()) { ("/", &Method::POST) => { let body_bytes = hyper::body::to_bytes(req.into_body()).await?; let body = String::from_utf8(body_bytes.into_iter().collect()).unwrap(); let (status_code, response_string) = process_post(executor_tx, &body).await; Ok(response_builder .header("Content-Type", "application/json") .status(status_code) .body(Body::from(response_string)) .unwrap()) } ("/", &Method::GET) => { let query = req.uri().query(); let (status_code, response_string) = process_get(executor_tx, query).await; Ok(response_builder .status(status_code) .body(Body::from(response_string)) .unwrap()) } ("/", _) => Ok(response_builder .status(StatusCode::METHOD_NOT_ALLOWED) .body(Body::default()) .unwrap()), _ => Ok(response_builder .status(StatusCode::NOT_FOUND) .body(Body::default()) .unwrap()), }; debug!( "🪃 Finished request ID {} in {} µs", request_id, timer.elapsed().as_micros() ); result } async fn shutdown_signal() { tokio::signal::ctrl_c() .await .expect("Failed to install Ctrl+C signal handler"); info!("💤 Shutting down gracefully..."); } pub async fn start_server(config: &config::Config, executor_tx: mpsc::Sender<ExecutorPayload>) { let tcp_listen_address = net::SocketAddr::new( net::IpAddr::from_str(&config.tcp_listen_host).unwrap(), config.tcp_listen_port, ); let server = Server::bind(&tcp_listen_address) .serve(make_service_fn(move |_conn| { let executor_tx = executor_tx.clone(); async move { Ok::<_, convert::Infallible>(service_fn(move |req| echo(executor_tx.clone(), req))) } })) .with_graceful_shutdown(shutdown_signal()); info!("👂 Server listening on {}...", tcp_listen_address); if let Err(e) = server.await { error!("‼️ Encountered server error: {}", e); } else { debug!("⏹ Server no longer listening"); } }
use crate::config; use crate::constructs::components::Validatable; use crate::executor::{ExecutorPayload, QueryResult}; use crate::sql::parse_statement; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Method, Request, Response, Server, StatusCode}; use serde::{ser::SerializeMap, Serialize, Serializer}; use std::collections::HashMap; use std::{convert, net, str::FromStr}; use thiserror::Error; use tokio::sync::{mpsc, oneshot}; use tokio::time; use tracing::*; use ulid::Ulid; #[derive(Error, Debug, PartialEq)] #[error("ServerError: {0}")] pub struct ServerError(pub String); impl Serialize for ServerError { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut map = serializer.serialize_map(Some(2))?; map.serialize_entry("type", "server")?; map.serialize_entry("message", &self.0)?; map.end() } } async fn process_post( executor_tx: mpsc::Sender<ExecutorPayload>, body: &str, ) -> (StatusCode, String) { let statement = parse_statement(&body); if let Err(parsing_error) = statement { return ( StatusCode::BAD_REQUEST, serde_json::to_string(&parsing_error).unwrap(), ); } let statement = statement.unwrap(); if let Err(validation_error) = statement.validate() { return ( StatusCode::BAD_REQUEST, serde_json::to_string(&validation_error).unwrap(), ); } let (resp_tx, resp_rx) = oneshot::channel::<QueryResult>(); if let Err(_) = executor_tx.send((statement, resp_tx)).await { return ( StatusCode::INTERNAL_SERVER_ERROR, serde_json::to_string(&ServerError("The query executor has disengaged.".into())) .unwrap(), ); } let query_result = resp_rx.await; ( StatusCode::OK, serde_json::to_string_pretty(&query_result.unwrap()).unwrap(), ) } async fn process_get( _executor_tx: mpsc::Sender<ExecutorPayload>, query: Option<&str>, ) -> (StatusCode, String) { if let Some(query_string) = query { if let Ok(query_map) = serde_urlencoded::from_str::<HashMap<String, String>>(query_string) { if let Some(query) = query_map.get("query") { (StatusCode::OK, query.to_string()) } else { (StatusCode::BAD_REQUEST, "TODO: No query param".to_string()) } } else { ( StatusCode::BAD_REQUEST, "TODO: Bad query string".to_string(), ) } } else { (StatusCode::BAD_REQUEST, "TODO: No query string".to_string()) } } async fn echo( executor_tx: mpsc::Sender<ExecutorPayload>, req: Request<Body>, ) -> Result<Response<Body>, hyper::Error> { let timer = time::Instant::now(); let request_id = Ulid::new(); debug!("⚡️ Received request ID {}", request_id); let response_builder = Response::builder().header("Content-Type", "application/json"); let result = match (req.uri().path(), req.method()) { ("/", &Method::POST) => { let body_bytes = hyper::body::to_bytes(req.into_body()).await?; let body = String::from_utf8(body_bytes.into_iter().collect()).unwrap(); let (status_code, response_string) = process_post(executor_tx, &body).await; Ok(response_builder .header("Content-Type", "application/json") .status(status_code) .body(Body::from(response_string)) .unwrap()) } ("/", &Method::GET) => { let query = req.uri().query(); let (status_code, response_string) = process_get(executor_tx, query).await; Ok(response_builder .status(status_code) .body(Body::from(response_string)) .unwrap()) } ("/", _) => Ok(response_builder .status(StatusCode::METHOD_NOT_ALLOWED) .body(Body::default()) .unwrap()), _ => Ok(response_builder .status(StatusCode::NOT_FOUND) .body(Body::default()) .unwrap()), }; debug!( "🪃 Finished request ID {} in {} µs", request_id, timer.elapsed().as_micros() ); result } async fn shutdown_signal() { tokio::signal::ctrl_c() .await .expect("Failed to install Ctrl+C signal handler"); info!("💤 Shutting down gracefully..."); } pub async fn start_server(config: &config::Config, executor_tx: mpsc::Sender<ExecutorPayload>) { let tcp_listen_address = net::SocketAddr::new( net::IpAddr::from_str(&config.tcp_listen_host).unwrap(), config.tcp_listen_port, ); let server = Server::bind(&tcp_listen_address) .serve(
) .with_graceful_shutdown(shutdown_signal()); info!("👂 Server listening on {}...", tcp_listen_address); if let Err(e) = server.await { error!("‼️ Encountered server error: {}", e); } else { debug!("⏹ Server no longer listening"); } }
make_service_fn(move |_conn| { let executor_tx = executor_tx.clone(); async move { Ok::<_, convert::Infallible>(service_fn(move |req| echo(executor_tx.clone(), req))) } })
call_expression
[ { "content": "pub fn parse_statement(input: &str) -> Result<Statement, SyntaxError> {\n\n let tokens = tokenize_statement(input);\n\n let ExpectOk {\n\n rest,\n\n outcome: found_token_first,\n\n ..\n\n } = expect_next_token(\n\n &tokens,\n\n &format!(\"{} or {}\", Key...
Rust
crates/core/src/config/mod.rs
seank-com/ajour
b4f29e4b7526a91b03e7e73388dc2f5966950968
use crate::catalog; use crate::error::FilesystemError; use crate::repository::CompressionFormat; use glob::MatchOptions; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::fs::create_dir_all; use std::path::{Path, PathBuf}; mod addons; mod wow; use crate::fs::PersistentData; pub use crate::config::addons::Addons; pub use crate::config::wow::{Flavor, Wow}; #[derive(Deserialize, Serialize, Debug, PartialEq, Default, Clone)] pub struct Config { #[serde(default)] pub wow: Wow, #[serde(default)] pub addons: Addons, pub theme: Option<String>, #[serde(default)] pub column_config: ColumnConfig, pub window_size: Option<(u32, u32)>, pub scale: Option<f64>, pub backup_directory: Option<PathBuf>, #[serde(default)] pub backup_addons: bool, #[serde(default)] pub backup_wtf: bool, #[serde(default)] pub backup_config: bool, #[serde(default)] pub hide_ignored_addons: bool, #[serde(default)] pub self_update_channel: SelfUpdateChannel, #[serde(default)] pub weak_auras_account: HashMap<Flavor, String>, #[serde(default = "default_true")] pub alternating_row_colors: bool, #[serde(default)] pub language: Language, #[serde(default)] pub catalog_source: Option<catalog::Source>, #[serde(default)] pub auto_update: bool, #[serde(default)] pub compression_format: CompressionFormat, #[serde(default)] #[cfg(target_os = "windows")] pub close_to_tray: bool, #[serde(default)] #[cfg(target_os = "windows")] pub autostart: bool, #[serde(default)] #[cfg(target_os = "windows")] pub start_closed_to_tray: bool, } impl Config { pub fn add_wow_directories(&mut self, path: PathBuf, flavor: Option<Flavor>) { if let Some(flavor) = flavor { let flavor_path = self.get_flavor_directory_for_flavor(&flavor, &path); if flavor_path.exists() { self.wow.directories.insert(flavor, flavor_path); } } else { let flavors = &Flavor::ALL[..]; for flavor in flavors { let flavor_path = self.get_flavor_directory_for_flavor(flavor, &path); if flavor_path.exists() { self.wow.directories.insert(*flavor, flavor_path); } } } } pub fn get_flavor_directory_for_flavor(&self, flavor: &Flavor, path: &Path) -> PathBuf { path.join(&flavor.folder_name()) } pub fn get_root_directory_for_flavor(&self, flavor: &Flavor) -> Option<PathBuf> { self.wow .directories .get(flavor) .map(|p| p.parent().unwrap().to_path_buf()) } pub fn get_addon_directory_for_flavor(&self, flavor: &Flavor) -> Option<PathBuf> { let dir = self.wow.directories.get(flavor); match dir { Some(dir) => { let mut addon_dir = dir.join("Interface/AddOns"); if !addon_dir.exists() { let options = MatchOptions { case_sensitive: false, ..Default::default() }; let pattern = format!("{}/?nterface/?ddons", dir.display()); for path in glob::glob_with(&pattern, options).unwrap().flatten() { addon_dir = path; } } if dir.exists() && !addon_dir.exists() { let _ = create_dir_all(&addon_dir); } Some(addon_dir) } None => None, } } pub fn get_download_directory_for_flavor(&self, flavor: Flavor) -> Option<PathBuf> { self.wow.directories.get(&flavor).cloned() } pub fn get_wtf_directory_for_flavor(&self, flavor: &Flavor) -> Option<PathBuf> { let dir = self.wow.directories.get(flavor); match dir { Some(dir) => { let mut addon_dir = dir.join("WTF"); if !addon_dir.exists() { let options = MatchOptions { case_sensitive: false, ..Default::default() }; let pattern = format!("{}/?tf", dir.display()); for path in glob::glob_with(&pattern, options).unwrap().flatten() { addon_dir = path; } } Some(addon_dir) } None => None, } } } impl PersistentData for Config { fn relative_path() -> PathBuf { PathBuf::from("ajour.yml") } } #[derive(Deserialize, Serialize, Debug, PartialEq, Clone)] pub enum ColumnConfig { V1 { local_version_width: u16, remote_version_width: u16, status_width: u16, }, V2 { columns: Vec<ColumnConfigV2>, }, V3 { my_addons_columns: Vec<ColumnConfigV2>, catalog_columns: Vec<ColumnConfigV2>, #[serde(default)] aura_columns: Vec<ColumnConfigV2>, }, } #[derive(Deserialize, Serialize, Debug, PartialEq, Clone)] pub struct ColumnConfigV2 { pub key: String, pub width: Option<u16>, pub hidden: bool, } impl Default for ColumnConfig { fn default() -> Self { ColumnConfig::V1 { local_version_width: 150, remote_version_width: 150, status_width: 85, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum SelfUpdateChannel { Stable, Beta, } impl SelfUpdateChannel { pub const fn all() -> [Self; 2] { [SelfUpdateChannel::Stable, SelfUpdateChannel::Beta] } } impl Default for SelfUpdateChannel { fn default() -> Self { SelfUpdateChannel::Stable } } impl Display for SelfUpdateChannel { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let s = match self { SelfUpdateChannel::Stable => "Stable", SelfUpdateChannel::Beta => "Beta", }; write!(f, "{}", s) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Hash, PartialOrd, Ord)] pub enum Language { Czech, Norwegian, English, Danish, German, French, Hungarian, Portuguese, Russian, Slovak, Swedish, Spanish, Turkish, Ukrainian, } impl std::fmt::Display for Language { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match self { Language::Czech => "Čeština", Language::Danish => "Dansk", Language::English => "English", Language::French => "Français", Language::German => "Deutsch", Language::Hungarian => "Magyar", Language::Norwegian => "Norsk Bokmål", Language::Portuguese => "Português", Language::Russian => "Pусский", Language::Slovak => "Slovenčina", Language::Spanish => "Español", Language::Swedish => "Svenska", Language::Turkish => "Türkçe", Language::Ukrainian => "Yкраїнська", } ) } } impl Language { pub const ALL: [Language; 14] = [ Language::Czech, Language::Danish, Language::German, Language::English, Language::Spanish, Language::French, Language::Hungarian, Language::Norwegian, Language::Portuguese, Language::Russian, Language::Slovak, Language::Swedish, Language::Turkish, Language::Ukrainian, ]; pub const fn language_code(self) -> &'static str { match self { Language::Czech => "cs_CZ", Language::English => "en_US", Language::Danish => "da_DK", Language::German => "de_DE", Language::French => "fr_FR", Language::Russian => "ru_RU", Language::Swedish => "se_SE", Language::Spanish => "es_ES", Language::Hungarian => "hu_HU", Language::Norwegian => "nb_NO", Language::Slovak => "sk_SK", Language::Turkish => "tr_TR", Language::Portuguese => "pt_PT", Language::Ukrainian => "uk_UA", } } } impl Default for Language { fn default() -> Language { Language::English } } pub async fn load_config() -> Result<Config, FilesystemError> { log::debug!("loading config"); Ok(Config::load_or_default()?) } const fn default_true() -> bool { true }
use crate::catalog; use crate::error::FilesystemError; use crate::repository::CompressionFormat; use glob::MatchOptions; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::fs::create_dir_all; use std::path::{Path, PathBuf}; mod addons; mod wow; use crate::fs::PersistentData; pub use crate::config::addons::Addons; pub use crate::config::wow::{Flavor, Wow}; #[derive(Deserialize, Serialize, Debug, PartialEq, Default, Clone)] pub struct Config { #[serde(default)] pub wow: Wow, #[serde(default)] pub addons: Addons, pub theme: Option<String>, #[serde(default)] pub column_config: ColumnConfig, pub window_size: Option<(u32, u32)>, pub scale: Option<f64>, pub backup_directory: Option<PathBuf>, #[serde(default)] pub backup_addons: bool, #[serde(default)] pub backup_wtf: bool, #[serde(default)] pub backup_config: bool, #[serde(default)] pub hide_ignored_addons: bool, #[serde(default)] pub self_update_channel: SelfUpdateChannel, #[serde(default)] pub weak_auras_account: HashMap<Flavor, String>, #[serde(default = "default_true")] pub alternating_row_colors: bool, #[serde(default)] pub language: Language, #[serde(default)] pub catalog_source: Option<catalog::Source>, #[serde(default)] pub auto_update: bool, #[serde(default)] pub compression_format: CompressionFormat, #[serde(default)] #[cfg(target_os = "windows")] pub close_to_tray: bool, #[serde(default)] #[cfg(target_os = "windows")] pub autostart: bool, #[serde(default)] #[cfg(target_os = "windows")] pub start_closed_to_tray: bool, } impl Config { pub fn add_wow_directories(&mut self, path: PathBuf, flavor: Option<Flavor>) { if let Some(flavor) = flavor { let flavor_path = self.get_flavor_directory_for_flavor(&flavor, &path); if flavor_path.exists() { self.wow.directories.insert(flavor, flavor_path); } } else { let flavors = &Flavor::ALL[..]; for flavor in flavors { let flavor_path = self.get_flavor_directory_for_flavor(flavor, &path); if flavor_path.exists() { self.wow.directories.insert(*flavor, flavor_path); } } } } pub fn get_flavor_directory_for_flavor(&self, flavor: &Flavor, path: &Path) -> PathBuf { path.join(&flavor.folder_name()) } pub fn get_root_directory_for_flavor(&self, flavor: &Flavor) -> Option<PathBuf> { self.wow .directories .get(flavor) .map(|p| p.parent().unwrap().to_path_buf()) } pub fn get_addon_directory_for_flavor(&self, flavor: &Flavor) -> Option<PathBuf> { let dir = self.wow.directories.get(flavor); match dir { Some(dir) => { let mut addon_dir = dir.join("Interface/AddOns"); if !addon_dir.exists() { let options = MatchOptions { case_sensitive: false, ..Default::default() }; let pattern = format!("{}/?nterface/?ddons", dir.display()); for path in glob::glob_with(&pattern, options).unwrap().flatten() { addon_dir = path; } } if dir.exists() && !addon_dir.exists() { let _ = create_dir_all(&addon_dir); } Some(addon_dir) } None => None, } } pub fn get_download_directory_for_flavor(&self, flavor: Flavor) -> Option<PathBuf> { self.wow.directories.get(&flavor).cloned() } pub fn get_wtf_directory_for_flavor(&self, flavor: &Flavor) -> Option<PathBuf> { let dir = self.wow.directories.get(flavor); match dir { Some(dir) => { let mut addon_dir = dir.join("WTF"); if !addon_dir.exists() { let options = MatchOptions { case_sensitive: false, ..Default::default() }; let pattern = format!("{}/?tf", dir.display()); for path in glob::glob_with(&pattern, options).unwrap().flatten() { addon_dir = path; } } Some(addon_dir) } None => None, } } } impl PersistentData for Config { fn relative_path() -> PathBuf { PathBuf::from("ajour.yml") } } #[derive(Deserialize, Serialize, Debug, PartialEq, Clone)] pub enum ColumnConfig { V1 { local_version_width: u16, remote_version_width: u16, status_width: u16, }, V2 { columns: Vec<ColumnConfigV2>, }, V3 { my_addons_columns: Vec<ColumnConfigV2>, catalog_columns: Vec<ColumnConfigV2>, #[serde(default)] aura_columns: Vec<ColumnConfigV2>, }, } #[derive(Deserialize, Serialize, Debug, PartialEq, Clone)] pub struct ColumnConfigV2 { pub key: String, pub width: Option<u16>, pub hidden: bool, } impl Default for ColumnConfig { fn default() -> Self { ColumnConfig::V1 { local_version_width: 150, remote_version_width: 150, status_width: 85, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum SelfUpdateChannel { Stable, Beta, } impl SelfUpdateChannel { pub const fn all() -> [Self; 2] { [SelfUpdateChannel::Stable, SelfUpdateChannel::Beta] } } impl Default for SelfUpdateChannel { fn default() -> Self { SelfUpdateChannel::Stable } } impl Display for SelfUpdateChannel {
} #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Hash, PartialOrd, Ord)] pub enum Language { Czech, Norwegian, English, Danish, German, French, Hungarian, Portuguese, Russian, Slovak, Swedish, Spanish, Turkish, Ukrainian, } impl std::fmt::Display for Language { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match self { Language::Czech => "Čeština", Language::Danish => "Dansk", Language::English => "English", Language::French => "Français", Language::German => "Deutsch", Language::Hungarian => "Magyar", Language::Norwegian => "Norsk Bokmål", Language::Portuguese => "Português", Language::Russian => "Pусский", Language::Slovak => "Slovenčina", Language::Spanish => "Español", Language::Swedish => "Svenska", Language::Turkish => "Türkçe", Language::Ukrainian => "Yкраїнська", } ) } } impl Language { pub const ALL: [Language; 14] = [ Language::Czech, Language::Danish, Language::German, Language::English, Language::Spanish, Language::French, Language::Hungarian, Language::Norwegian, Language::Portuguese, Language::Russian, Language::Slovak, Language::Swedish, Language::Turkish, Language::Ukrainian, ]; pub const fn language_code(self) -> &'static str { match self { Language::Czech => "cs_CZ", Language::English => "en_US", Language::Danish => "da_DK", Language::German => "de_DE", Language::French => "fr_FR", Language::Russian => "ru_RU", Language::Swedish => "se_SE", Language::Spanish => "es_ES", Language::Hungarian => "hu_HU", Language::Norwegian => "nb_NO", Language::Slovak => "sk_SK", Language::Turkish => "tr_TR", Language::Portuguese => "pt_PT", Language::Ukrainian => "uk_UA", } } } impl Default for Language { fn default() -> Language { Language::English } } pub async fn load_config() -> Result<Config, FilesystemError> { log::debug!("loading config"); Ok(Config::load_or_default()?) } const fn default_true() -> bool { true }
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let s = match self { SelfUpdateChannel::Stable => "Stable", SelfUpdateChannel::Beta => "Beta", }; write!(f, "{}", s) }
function_block-full_function
[ { "content": "pub fn path_add(path: PathBuf, flavor: Option<Flavor>) -> Result<()> {\n\n task::block_on(async {\n\n log::debug!(\"Adding {:?} from {:?} to known directories\", flavor, &path);\n\n let mut config = load_config().await?;\n\n config.add_wow_directories(path, flavor);\n\n ...
Rust
src/parsers/apache2/mod.rs
u-siem/usiem-apache-httpd
c19d21c8fe0bacb86ff6eebf9c4e0e708e7d8714
use chrono::prelude::{TimeZone, Utc}; use std::borrow::Cow; use usiem::components::common::LogParsingError; use usiem::events::common::{HttpMethod, WebProtocol}; use usiem::events::field::{SiemField, SiemIp}; use usiem::events::webserver::{WebServerEvent, WebServerOutcome}; use usiem::events::{SiemEvent, SiemLog}; pub fn parse_log_combinedio(log: SiemLog) -> Result<SiemLog, LogParsingError> { let log_line = log.message(); let start_log_pos = match log_line.find("\"") { Some(val) => val, None => return Err(LogParsingError::NoValidParser(log)), }; let log_header = &log_line[..start_log_pos]; let (pre_data, event_created) = match log_header.find('[') { Some(v1) => match log_header.find(']') { Some(v2) => { if (v2 - v1) > 27 || (v2 - v1) < 24 { return Err(LogParsingError::NoValidParser(log)); } else { (&log_header[..v1-1],&log_header[v1 + 1..v2]) } } None => return Err(LogParsingError::NoValidParser(log)), }, None => return Err(LogParsingError::NoValidParser(log)), }; let event_created = match Utc.datetime_from_str(event_created, "%d/%b/%Y:%H:%M:%S %z") { Ok(timestamp) => timestamp.timestamp_millis(), Err(_err) => return Err(LogParsingError::NoValidParser(log)), }; let log_content = &log_line[start_log_pos..]; let fields = extract_fields(log_content); let pre_fields = extract_fields(pre_data); let (http_method, url, version) = match fields.get(0) { Some(v) => match extract_http_content(v) { Ok((method, url, version)) => (method, url, version), Err(_) => return Err(LogParsingError::NoValidParser(log)), }, None => return Err(LogParsingError::NoValidParser(log)), }; let (http_protocol, http_version) = match version.find('/') { Some(p) => (parse_http_protocol(&version[..p]), &version[(p+1)..]), None => (parse_http_protocol(version), ""), }; let http_code = match fields.get(1) { Some(v) => match v.parse::<u32>() { Ok(v) => v, Err(_) => return Err(LogParsingError::NoValidParser(log)), }, None => return Err(LogParsingError::NoValidParser(log)), }; let referer = match fields.get(3) { Some(v) => { if *v == "-" { "" }else{ v } }, None => return Err(LogParsingError::NoValidParser(log)), }; let user_agent = match fields.get(4) { Some(v) => { if *v == "-" { "" }else{ v } }, None => return Err(LogParsingError::NoValidParser(log)), }; let in_bytes = match fields.get(5) { Some(v) => match v.parse::<u32>() { Ok(v) => v, Err(_) => 0, }, None => 0, }; let out_bytes = match fields.get(6) { Some(v) => match v.parse::<u32>() { Ok(v) => v, Err(_) => 0, }, None => 0, }; let (url_path, url_query, url_extension) = extract_url_parts(url); let pre_size = pre_fields.len(); let user_name = match pre_fields.get(pre_size - 1) { Some(v) => match *v { "-" => Cow::Borrowed(""), _ => Cow::Owned(v.to_string()) }, None => return Err(LogParsingError::NoValidParser(log)), }; let (source_ip, source_host) = match pre_fields.get(pre_size - 3) { Some(v) => match SiemIp::from_ip_str(v) { Ok(ip) => (ip, (*v).to_string()), Err(_) => (SiemIp::V4(0), (*v).to_string()) }, None => return Err(LogParsingError::NoValidParser(log)), }; let (destination_ip, destination_host) = if pre_size >= 4 { match pre_fields.get(pre_size - 4) { Some(v) => match SiemIp::from_ip_str(v) { Ok(ip) => (Some(ip), Some(v.to_string())), Err(_) => (None, Some(v.to_string())) }, None => (None,None) } }else{ (None,None) }; let http_version = match http_version { "" => None, _ => Some(SiemField::from_str(http_version.to_string())) }; let mut log = SiemLog::new( log_line.to_string(), log.event_received(), log.origin().clone(), ); log.set_category(Cow::Borrowed("Web Server")); log.set_product(Cow::Borrowed("Apache")); log.set_service(Cow::Borrowed("Web Server")); let outcome = if http_code < 400 { WebServerOutcome::ALLOW }else{ WebServerOutcome::BLOCK }; log.set_event(SiemEvent::WebServer(WebServerEvent { source_ip, destination_ip, destination_port: 80, in_bytes, out_bytes, http_code, http_method: parse_http_method(http_method), duration: 0.0, user_agent: Cow::Owned(user_agent.to_string()), url_full: Cow::Owned(url.to_string()), url_domain: Cow::Borrowed(""), url_path: Cow::Owned(url_path.to_string()), url_query: Cow::Owned(url_query.to_string()), url_extension: Cow::Owned(url_extension.to_string()), protocol: http_protocol, user_name, mime_type: Cow::Borrowed(""), outcome })); log.set_event_created(event_created); log.add_field("source.hostname", SiemField::from_str(source_host)); match http_version { Some(v) => {log.add_field("http.version", v);}, None => {} }; match destination_host { Some(v) => { log.add_field("destination.hostname", SiemField::from_str(v)); }, None => {} }; match referer { "" => {} _ => { log.add_field( "http.request.referrer", SiemField::Text(Cow::Owned(referer.to_string())), ); } }; Ok(log) } pub fn parse_http_method(method: &str) -> HttpMethod { match method { "GET" => HttpMethod::GET, "HEAD" => HttpMethod::HEAD, "POST" => HttpMethod::POST, "PUT" => HttpMethod::PUT, "PATCH" => HttpMethod::PATCH, "OPTIONS" => HttpMethod::OPTIONS, "CONNECT" => HttpMethod::CONNECT, _ => HttpMethod::UNKNOWN(method.to_uppercase()), } } pub fn parse_http_protocol(version: &str) -> WebProtocol { let proto = match version.find('/') { Some(p) => &version[..p], None => version, }; match proto { "HTTP" => WebProtocol::HTTP, "WS" => WebProtocol::WS, "WSS" => WebProtocol::WSS, "FTP" => WebProtocol::FTP, _ => WebProtocol::UNKNOWN(proto.to_uppercase()), } } pub fn extract_http_content<'a>( message: &'a str, ) -> Result<(&'a str, &'a str, &'a str), &'static str> { let mut splited = message.split(' '); let method = match splited.next() { Some(mt) => mt, None => return Err("No method"), }; let url = match splited.next() { Some(mt) => mt, None => return Err("No URL"), }; let version = match splited.next() { Some(mt) => mt, None => return Err("No version"), }; Ok((method, url, version)) } pub fn extract_url_parts<'a>(url: &'a str) -> (&'a str, &'a str, &'a str) { let pos = match url.find('?') { Some(v) => v, None => url.len(), }; let path = &url[..pos]; let query = &url[pos..]; let extension = match path.rfind('.') { Some(v) => { if (path.len() - v) > 8 { "" } else { &path[v+1..] } } None => "", }; (path, query, extension) } pub fn extract_fields<'a>(message: &'a str) -> Vec<&'a str> { let mut field_map = Vec::with_capacity(80); let mut start_field = 0; let mut is_string = false; for (i, c) in message.char_indices() { if c == '"' { if is_string { if start_field != i { field_map.push(&message[start_field..i]); } start_field = i + 1; } else { start_field = i + 1; } is_string = !is_string; } else if !is_string && c == ' ' { if start_field != i { field_map.push(&message[start_field..i]); } start_field = i + 1; } } field_map.push(&message[start_field..]); field_map } #[cfg(test)] mod filterlog_tests { use super::{extract_fields, parse_log_combinedio}; use usiem::events::field::{SiemIp, SiemField}; use usiem::events::SiemLog; use usiem::events::field_dictionary; #[test] fn test_extract_fields() { let log = "\"GET / HTTP/1.1\" 304 - \"-\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:85.0) Gecko/20100101 Firefox/85.0\" 465 164"; let map = extract_fields(log); assert_eq!(map.get(0), Some(&"GET / HTTP/1.1")); assert_eq!(map.get(1), Some(&"304")); assert_eq!(map.get(2), Some(&"-")); assert_eq!(map.get(3), Some(&"-")); assert_eq!( map.get(4), Some(&"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:85.0) Gecko/20100101 Firefox/85.0") ); assert_eq!(map.get(5), Some(&"465")); assert_eq!(map.get(6), Some(&"164")); } #[test] fn test_parse_combinedio() { let log = "172.17.0.1 - - [23/Feb/2021:20:39:35 +0000] \"GET / HTTP/1.1\" 304 - \"-\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:85.0) Gecko/20100101 Firefox/85.0\" 465 164"; let log = SiemLog::new(log.to_string(), 0, SiemIp::V4(0)); let siem_log = parse_log_combinedio(log); match siem_log { Ok(log) => { assert_eq!(log.service(), "Web Server"); assert_eq!(log.field(field_dictionary::HTTP_REQUEST_METHOD), Some(&SiemField::from_str("GET"))); assert_eq!(log.field(field_dictionary::HTTP_RESPONSE_STATUS_CODE), Some(&SiemField::U32(304))); assert_eq!(log.field(field_dictionary::SOURCE_BYTES), Some(&SiemField::U32(164))); assert_eq!(log.field(field_dictionary::DESTINATION_BYTES), Some(&SiemField::U32(465))); assert_eq!(log.field(field_dictionary::URL_PATH), Some(&SiemField::from_str("/"))); assert_eq!(log.field("user_agent.original"), Some(&SiemField::from_str("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:85.0) Gecko/20100101 Firefox/85.0"))); assert_eq!(log.field(field_dictionary::SOURCE_IP), Some(&SiemField::IP(SiemIp::from_ip_str("172.17.0.1").unwrap()))); assert_eq!(log.field("http.version"), Some(&SiemField::from_str("1.1"))); } Err(_) => assert_eq!(1, 0), } } }
use chrono::prelude::{TimeZone, Utc}; use std::borrow::Cow; use usiem::components::common::LogParsingError; use usiem::events::common::{HttpMethod, WebProtocol}; use usiem::events::field::{SiemField, SiemIp}; use usiem::events::webserver::{WebServerEvent, WebServerOutcome}; use usiem::events::{SiemEvent, SiemLog}; pub fn parse_log_combinedio(log: SiemLog) -> Result<SiemLog, LogParsingError> { let log_line = log.message(); let start_log_pos = match log_line.find("\"") { Some(val) => val, None => return Err(LogParsingError::NoValidParser(log)), }; let log_header = &log_line[..start_log_pos]; let (pre_data, event_created) = match log_header.find('[') { Some(v1) => match log_header.find(']') { Some(v2) => { if (v2 - v1) > 27 || (v2 - v1) < 24 { return Err(LogParsingError::NoValidParser(log)); } else { (&log_header[..v1-1],&log_header[v1 + 1..v2]) } } None => return Err(LogParsingError::NoValidParser(log)), }, None => return Err(LogParsingError::NoValidParser(log)), }; let event_created = match Utc.datetime_from_str(event_created, "%d/%b/%Y:%H:%M:%S %z") { Ok(timestamp) => timestamp.timestamp_millis(), Err(_err) => return Err(LogParsingError::NoValidParser(log)), }; let log_content = &log_line[start_log_pos..]; let fields = extract_fields(log_content); let pre_fields = extract_fields(pre_data); let (http_method, url, version) = match fields.get(0) { Some(v) => match extract_http_content(v) { Ok((method, url, version)) => (method, url, version), Err(_) => return Err(LogParsingError::NoValidParser(log)), }, None => return Err(LogParsingError::NoValidParser(log)), }; let (http_protocol, http_version) = match version.find('/') { Some(p) => (parse_http_protocol(&version[..p]), &version[(p+1)..]), None => (parse_http_protocol(version), ""), }; let http_code = match fields.get(1) { Some(v) => match v.parse::<u32>() { Ok(v) => v, Err(_) => return Err(LogParsingError::NoValidParser(log)), }, None => return Err(LogParsingError::NoValidParser(log)), }; let referer = match fields.get(3) { Some(v) => { if *v == "-" { "" }else{ v } }, None => return Err(LogParsingError::NoValidParser(log)), }; let user_agent = match fields.get(4) { Some(v) => { if *v == "-" { "" }else{ v } }, None => return Err(LogParsingError::NoValidParser(log)), }; let in_bytes = match fields.get(5) { Some(v) => match v.parse::<u32>() { Ok(v) => v, Err(_) => 0, }, None => 0, }; let out_bytes = match fields.get(6) { Some(v) => match v.parse::<u32>() { Ok(v) => v, Err(_) => 0, }, None => 0, }; let (url_path, url_query, url_extension) = extract_url_parts(url); let pre_size = pre_fields.len(); let user_name = match pre_fields.get(pre_size - 1) { Some(v) => match *v { "-" => Cow::Borrowed(""), _ => Cow::Owned(v.to_string()) }, None => return Err(LogParsingError::NoValidParser(log)), }; let (source_ip, source_host) = match pre_fields.get(pre_size - 3) { Some(v) => match SiemIp::from_ip_str(v) { Ok(ip) => (ip, (*v).to_string()), Err(_) => (SiemIp::V4(0), (*v).to_string()) }, None => return Err(LogParsingError::NoValidParser(log)), }; let (destination_ip, destination_host) = if pre_size >= 4 { match pre_fields.get(pre_size - 4) { Some(v) => match SiemIp::from_ip_str(v) { Ok(ip) => (Some(ip), Some(v.to_string())), Err(_) => (None, Some(v.to_string())) }, None => (None,None) } }else{ (None,None) }; let http_version = match http_version { "" => None, _ => Some(SiemField::from_str(http_version.to_string())) }; let mut log = SiemLog::new( log_line.to_string(), log.event_received(), log.origin().clone(), ); log.set_category(Cow::Borrowed("Web Server")); log.set_product(Cow::Borrowed("Apache")); log.set_service(Cow::Borrowed("Web Server")); let outcome = if http_code < 400 { WebServerOutcome::ALLOW }else{ WebServerOutcome::BLOCK }; log.set_event(SiemEvent::WebServer(WebServerEvent { source_ip, destination_ip, destination_port: 80, in_bytes, out_bytes, http_code, http_method: parse_http_method(http_method), duration: 0.0, user_agent: Cow::Owned(user_agent.to_string()), url_full: Cow::Owned(url.to_string()), url_domain: Cow::Borrowed(""), url_path: Cow::Owned(url_path.to_string()), url_query: Cow::Owned(url_query.to_string()), url_extension: Cow::Owned(url_extension.to_string()), protocol: http_protocol, user_name, mime_type: Cow::Borrowed(""), outcome })); log.set_event_created(event_created); log.add_field("source.hostname", SiemField::from_str(source_host)); match http_version { Some(v) => {log.add_field("http.version", v);}, None => {} }; match destination_host { Some(v) => { log.add_field("destination.hostname", SiemField::from_str(v)); }, None => {} }; match referer { "" => {} _ => { log.add_field( "http.request.referrer", SiemField::Text(Cow::Owned(referer.to_string())), ); } }; Ok(log) } pub fn parse_http_method(method: &str) -> HttpMethod { match method { "GET" => HttpMethod::GET, "HEAD" => HttpMethod::HEAD, "POST" => HttpMethod::POST, "PUT" => HttpMethod::PUT, "PATCH" => HttpMethod::PATCH, "OPTIONS" => HttpMethod::OPTIONS, "CONNECT" => HttpMethod::CONNECT, _ => HttpMethod::UNKNOWN(method.to_uppercase()), } } pub fn parse_http_protocol(version: &str) -> WebProtocol {
pub fn extract_http_content<'a>( message: &'a str, ) -> Result<(&'a str, &'a str, &'a str), &'static str> { let mut splited = message.split(' '); let method = match splited.next() { Some(mt) => mt, None => return Err("No method"), }; let url = match splited.next() { Some(mt) => mt, None => return Err("No URL"), }; let version = match splited.next() { Some(mt) => mt, None => return Err("No version"), }; Ok((method, url, version)) } pub fn extract_url_parts<'a>(url: &'a str) -> (&'a str, &'a str, &'a str) { let pos = match url.find('?') { Some(v) => v, None => url.len(), }; let path = &url[..pos]; let query = &url[pos..]; let extension = match path.rfind('.') { Some(v) => { if (path.len() - v) > 8 { "" } else { &path[v+1..] } } None => "", }; (path, query, extension) } pub fn extract_fields<'a>(message: &'a str) -> Vec<&'a str> { let mut field_map = Vec::with_capacity(80); let mut start_field = 0; let mut is_string = false; for (i, c) in message.char_indices() { if c == '"' { if is_string { if start_field != i { field_map.push(&message[start_field..i]); } start_field = i + 1; } else { start_field = i + 1; } is_string = !is_string; } else if !is_string && c == ' ' { if start_field != i { field_map.push(&message[start_field..i]); } start_field = i + 1; } } field_map.push(&message[start_field..]); field_map } #[cfg(test)] mod filterlog_tests { use super::{extract_fields, parse_log_combinedio}; use usiem::events::field::{SiemIp, SiemField}; use usiem::events::SiemLog; use usiem::events::field_dictionary; #[test] fn test_extract_fields() { let log = "\"GET / HTTP/1.1\" 304 - \"-\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:85.0) Gecko/20100101 Firefox/85.0\" 465 164"; let map = extract_fields(log); assert_eq!(map.get(0), Some(&"GET / HTTP/1.1")); assert_eq!(map.get(1), Some(&"304")); assert_eq!(map.get(2), Some(&"-")); assert_eq!(map.get(3), Some(&"-")); assert_eq!( map.get(4), Some(&"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:85.0) Gecko/20100101 Firefox/85.0") ); assert_eq!(map.get(5), Some(&"465")); assert_eq!(map.get(6), Some(&"164")); } #[test] fn test_parse_combinedio() { let log = "172.17.0.1 - - [23/Feb/2021:20:39:35 +0000] \"GET / HTTP/1.1\" 304 - \"-\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:85.0) Gecko/20100101 Firefox/85.0\" 465 164"; let log = SiemLog::new(log.to_string(), 0, SiemIp::V4(0)); let siem_log = parse_log_combinedio(log); match siem_log { Ok(log) => { assert_eq!(log.service(), "Web Server"); assert_eq!(log.field(field_dictionary::HTTP_REQUEST_METHOD), Some(&SiemField::from_str("GET"))); assert_eq!(log.field(field_dictionary::HTTP_RESPONSE_STATUS_CODE), Some(&SiemField::U32(304))); assert_eq!(log.field(field_dictionary::SOURCE_BYTES), Some(&SiemField::U32(164))); assert_eq!(log.field(field_dictionary::DESTINATION_BYTES), Some(&SiemField::U32(465))); assert_eq!(log.field(field_dictionary::URL_PATH), Some(&SiemField::from_str("/"))); assert_eq!(log.field("user_agent.original"), Some(&SiemField::from_str("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:85.0) Gecko/20100101 Firefox/85.0"))); assert_eq!(log.field(field_dictionary::SOURCE_IP), Some(&SiemField::IP(SiemIp::from_ip_str("172.17.0.1").unwrap()))); assert_eq!(log.field("http.version"), Some(&SiemField::from_str("1.1"))); } Err(_) => assert_eq!(1, 0), } } }
let proto = match version.find('/') { Some(p) => &version[..p], None => version, }; match proto { "HTTP" => WebProtocol::HTTP, "WS" => WebProtocol::WS, "WSS" => WebProtocol::WSS, "FTP" => WebProtocol::FTP, _ => WebProtocol::UNKNOWN(proto.to_uppercase()), } }
function_block-function_prefix_line
[ { "content": "/// Always use JSON format. Easy ato process and with more information.\n\npub fn parse_log_json(mut log: SiemLog) -> Result<SiemLog, LogParsingError> {\n\n let mod_log = match log.event() {\n\n SiemEvent::Unknown => {\n\n //Check JSON and extract\n\n let log_line =...
Rust
src/http/ctr.rs
zaksabeast/libctr-rs
556cf4857866db512ae415fd33f17131178ab465
use super::{ get_httpc_service_raw_handle, httpc_add_post_data_ascii, httpc_add_request_header_field, httpc_begin_request, httpc_create_context, httpc_initialize_connection_session, httpc_receive_data_with_timeout, httpc_set_proxy_default, httpc_set_socket_buffer_size, DefaultRootCert, HttpContextHandle, RequestMethod, RequestStatus, }; use crate::{ ipc::ThreadCommandBuilder, res::CtrResult, srv::get_service_handle_direct, utils::base64_encode, Handle, }; pub struct HttpContext { session_handle: Handle, context_handle: HttpContextHandle, } #[cfg_attr(not(target_os = "horizon"), mocktopus::macros::mockable)] impl HttpContext { pub fn new(url: &str, method: RequestMethod) -> CtrResult<Self> { let context_handle = httpc_create_context(method, url)?; let session_handle = get_service_handle_direct("http:C")?; httpc_initialize_connection_session(&session_handle, &context_handle)?; httpc_set_proxy_default(&session_handle, &context_handle)?; Ok(Self { session_handle, context_handle, }) } pub fn add_default_cert(&self, cert: DefaultRootCert) -> CtrResult<()> { let mut command = ThreadCommandBuilder::new(0x25u16); unsafe { command.push(self.context_handle.get_raw()) }; command.push(cert); let mut parser = command.build().send_sync_request(&self.session_handle)?; parser.pop_result()?; Ok(()) } pub fn set_client_cert_default(&self) -> CtrResult<()> { let mut command = ThreadCommandBuilder::new(0x28u16); unsafe { command.push(self.context_handle.get_raw()) }; command.push(0x40u32); let mut parser = command.build().send_sync_request(&self.session_handle)?; parser.pop_result()?; Ok(()) } pub fn add_header(&self, header_name: &str, value: &str) -> CtrResult<()> { httpc_add_request_header_field( &self.session_handle, &self.context_handle, header_name, value, ) } pub fn add_post_ascii_field(&self, post_field_name: &str, value: &str) -> CtrResult<()> { httpc_add_post_data_ascii( &self.session_handle, &self.context_handle, post_field_name, value, ) } pub fn add_post_base64_field<T: AsRef<[u8]>>( &self, post_field_name: &str, value: T, ) -> CtrResult<()> { self.add_post_ascii_field(post_field_name, &base64_encode(value)) } pub fn set_socket_buffer_size(&self, socket_buffer_size: u32) -> CtrResult<()> { httpc_set_socket_buffer_size(&self.session_handle, socket_buffer_size) } pub fn get_download_size_state(&self) -> CtrResult<(u32, u32)> { let mut command = ThreadCommandBuilder::new(0x6u16); unsafe { command.push(self.context_handle.get_raw()) }; let mut parser = command .build() .send_sync_request_with_raw_handle(get_httpc_service_raw_handle())?; parser.pop_result()?; Ok((parser.pop(), parser.pop())) } pub fn cancel_connection(&self) -> CtrResult<()> { let mut command = ThreadCommandBuilder::new(0x4u16); unsafe { command.push(self.context_handle.get_raw()) }; let mut parser = command .build() .send_sync_request_with_raw_handle(get_httpc_service_raw_handle())?; parser.pop_result()?; Ok(()) } pub fn download_data_into_buffer_with_timeout( &self, out_buffer: &mut [u8], nanosecond_timeout: u64, ) -> CtrResult<()> { httpc_begin_request(&self.session_handle, &self.context_handle)?; httpc_receive_data_with_timeout( &self.session_handle, &self.context_handle, out_buffer, nanosecond_timeout, )?; let (downloaded_size, _content_size) = self.get_download_size_state()?; if out_buffer.len() < (downloaded_size as usize) { self.cancel_connection()?; } Ok(()) } pub fn download_data_into_buffer(&self, out_buffer: &mut [u8]) -> CtrResult<()> { self.download_data_into_buffer_with_timeout(out_buffer, 60000000000) } pub fn get_response_status_code(&self) -> CtrResult<u32> { let mut command = ThreadCommandBuilder::new(0x22u16); unsafe { command.push(self.context_handle.get_raw()) }; let mut parser = command.build().send_sync_request(&self.session_handle)?; parser.pop_result()?; Ok(parser.pop()) } pub fn get_request_status(&self) -> CtrResult<RequestStatus> { let mut command = ThreadCommandBuilder::new(0x4u16); unsafe { command.push(self.context_handle.get_raw()) }; let mut parser = command .build() .send_sync_request_with_raw_handle(get_httpc_service_raw_handle())?; parser.pop_result()?; Ok(parser.pop().into()) } }
use super::{ get_httpc_service_raw_handle, httpc_add_post_data_ascii, httpc_add_request_header_field, httpc_begin_request, httpc_create_context, httpc_initialize_connection_session, httpc_receive_data_with_timeout, httpc_set_proxy_default, httpc_set_socket_buffer_size, DefaultRootCert, HttpContextHandle, RequestMethod, RequestStatus, }; use crate::{ ipc::ThreadCommandBuilder, res::CtrResult, srv::get_service_handle_direct, utils::base64_encode, Handle, }; pub struct HttpContext { session_handle: Handle, context_handle: HttpContextHandle, } #[cfg_attr(not(target_os = "horizon"), mocktopus::macros::mockable)] impl HttpContext { pub fn new(url: &str, method: RequestMethod) -> CtrResult<Self> { let context_handle = httpc_create_context(method, url)?; let session_handle = get_service_handle_direct("http:C")?; httpc_initialize_connection_session(&session_handle, &context_handle)?; httpc_set_proxy_default(&session_handle, &context_handle)?; Ok(Self { session_handle, context_handle, }) }
pub fn set_client_cert_default(&self) -> CtrResult<()> { let mut command = ThreadCommandBuilder::new(0x28u16); unsafe { command.push(self.context_handle.get_raw()) }; command.push(0x40u32); let mut parser = command.build().send_sync_request(&self.session_handle)?; parser.pop_result()?; Ok(()) } pub fn add_header(&self, header_name: &str, value: &str) -> CtrResult<()> { httpc_add_request_header_field( &self.session_handle, &self.context_handle, header_name, value, ) } pub fn add_post_ascii_field(&self, post_field_name: &str, value: &str) -> CtrResult<()> { httpc_add_post_data_ascii( &self.session_handle, &self.context_handle, post_field_name, value, ) } pub fn add_post_base64_field<T: AsRef<[u8]>>( &self, post_field_name: &str, value: T, ) -> CtrResult<()> { self.add_post_ascii_field(post_field_name, &base64_encode(value)) } pub fn set_socket_buffer_size(&self, socket_buffer_size: u32) -> CtrResult<()> { httpc_set_socket_buffer_size(&self.session_handle, socket_buffer_size) } pub fn get_download_size_state(&self) -> CtrResult<(u32, u32)> { let mut command = ThreadCommandBuilder::new(0x6u16); unsafe { command.push(self.context_handle.get_raw()) }; let mut parser = command .build() .send_sync_request_with_raw_handle(get_httpc_service_raw_handle())?; parser.pop_result()?; Ok((parser.pop(), parser.pop())) } pub fn cancel_connection(&self) -> CtrResult<()> { let mut command = ThreadCommandBuilder::new(0x4u16); unsafe { command.push(self.context_handle.get_raw()) }; let mut parser = command .build() .send_sync_request_with_raw_handle(get_httpc_service_raw_handle())?; parser.pop_result()?; Ok(()) } pub fn download_data_into_buffer_with_timeout( &self, out_buffer: &mut [u8], nanosecond_timeout: u64, ) -> CtrResult<()> { httpc_begin_request(&self.session_handle, &self.context_handle)?; httpc_receive_data_with_timeout( &self.session_handle, &self.context_handle, out_buffer, nanosecond_timeout, )?; let (downloaded_size, _content_size) = self.get_download_size_state()?; if out_buffer.len() < (downloaded_size as usize) { self.cancel_connection()?; } Ok(()) } pub fn download_data_into_buffer(&self, out_buffer: &mut [u8]) -> CtrResult<()> { self.download_data_into_buffer_with_timeout(out_buffer, 60000000000) } pub fn get_response_status_code(&self) -> CtrResult<u32> { let mut command = ThreadCommandBuilder::new(0x22u16); unsafe { command.push(self.context_handle.get_raw()) }; let mut parser = command.build().send_sync_request(&self.session_handle)?; parser.pop_result()?; Ok(parser.pop()) } pub fn get_request_status(&self) -> CtrResult<RequestStatus> { let mut command = ThreadCommandBuilder::new(0x4u16); unsafe { command.push(self.context_handle.get_raw()) }; let mut parser = command .build() .send_sync_request_with_raw_handle(get_httpc_service_raw_handle())?; parser.pop_result()?; Ok(parser.pop().into()) } }
pub fn add_default_cert(&self, cert: DefaultRootCert) -> CtrResult<()> { let mut command = ThreadCommandBuilder::new(0x25u16); unsafe { command.push(self.context_handle.get_raw()) }; command.push(cert); let mut parser = command.build().send_sync_request(&self.session_handle)?; parser.pop_result()?; Ok(()) }
function_block-full_function
[ { "content": "#[cfg_attr(not(target_os = \"horizon\"), mocktopus::macros::mockable)]\n\npub fn get_service_handle_direct(_name: &str) -> CtrResult<Handle> {\n\n Ok(0.into())\n\n}\n", "file_path": "src/srv/mock.rs", "rank": 0, "score": 195878.7015791129 }, { "content": "pub fn get_service_...
Rust
vendor/aho-corasick/src/packed/pattern.rs
47565647456/evtx
fbb2a713d335f5208bb6675f4f158babd6f2f389
use std::cmp; use std::fmt; use std::mem; use std::u16; use std::usize; use crate::packed::api::MatchKind; pub type PatternID = u16; #[derive(Clone, Debug)] pub struct Patterns { kind: MatchKind, by_id: Vec<Vec<u8>>, order: Vec<PatternID>, minimum_len: usize, max_pattern_id: PatternID, total_pattern_bytes: usize, } impl Patterns { pub fn new() -> Patterns { Patterns { kind: MatchKind::default(), by_id: vec![], order: vec![], minimum_len: usize::MAX, max_pattern_id: 0, total_pattern_bytes: 0, } } pub fn add(&mut self, bytes: &[u8]) { assert!(!bytes.is_empty()); assert!(self.by_id.len() <= u16::MAX as usize); let id = self.by_id.len() as u16; self.max_pattern_id = id; self.order.push(id); self.by_id.push(bytes.to_vec()); self.minimum_len = cmp::min(self.minimum_len, bytes.len()); self.total_pattern_bytes += bytes.len(); } pub fn set_match_kind(&mut self, kind: MatchKind) { match kind { MatchKind::LeftmostFirst => { self.order.sort(); } MatchKind::LeftmostLongest => { let (order, by_id) = (&mut self.order, &mut self.by_id); order.sort_by(|&id1, &id2| { by_id[id1 as usize] .len() .cmp(&by_id[id2 as usize].len()) .reverse() }); } MatchKind::__Nonexhaustive => unreachable!(), } } pub fn len(&self) -> usize { self.by_id.len() } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn heap_bytes(&self) -> usize { self.order.len() * mem::size_of::<PatternID>() + self.by_id.len() * mem::size_of::<Vec<u8>>() + self.total_pattern_bytes } pub fn reset(&mut self) { self.kind = MatchKind::default(); self.by_id.clear(); self.order.clear(); self.minimum_len = usize::MAX; self.max_pattern_id = 0; } pub fn max_pattern_id(&self) -> PatternID { assert_eq!((self.max_pattern_id + 1) as usize, self.len()); self.max_pattern_id } pub fn minimum_len(&self) -> usize { self.minimum_len } pub fn match_kind(&self) -> &MatchKind { &self.kind } pub fn get(&self, id: PatternID) -> Pattern<'_> { Pattern(&self.by_id[id as usize]) } #[cfg(target_arch = "x86_64")] pub unsafe fn get_unchecked(&self, id: PatternID) -> Pattern<'_> { Pattern(self.by_id.get_unchecked(id as usize)) } pub fn iter(&self) -> PatternIter<'_> { PatternIter { patterns: self, i: 0 } } } #[derive(Debug)] pub struct PatternIter<'p> { patterns: &'p Patterns, i: usize, } impl<'p> Iterator for PatternIter<'p> { type Item = (PatternID, Pattern<'p>); fn next(&mut self) -> Option<(PatternID, Pattern<'p>)> { if self.i >= self.patterns.len() { return None; } let id = self.patterns.order[self.i]; let p = self.patterns.get(id); self.i += 1; Some((id, p)) } } #[derive(Clone)] pub struct Pattern<'a>(&'a [u8]); impl<'a> fmt::Debug for Pattern<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Pattern") .field("lit", &String::from_utf8_lossy(&self.0)) .finish() } } impl<'p> Pattern<'p> { pub fn len(&self) -> usize { self.0.len() } pub fn bytes(&self) -> &[u8] { &self.0 } #[cfg(target_arch = "x86_64")] pub fn low_nybbles(&self, len: usize) -> Vec<u8> { let mut nybs = vec![]; for &b in self.bytes().iter().take(len) { nybs.push(b & 0xF); } nybs } #[inline(always)] pub fn is_prefix(&self, bytes: &[u8]) -> bool { self.len() <= bytes.len() && self.equals(&bytes[..self.len()]) } #[inline(always)] pub fn equals(&self, bytes: &[u8]) -> bool { if self.len() != bytes.len() { return false; } if self.len() < 8 { for (&b1, &b2) in self.bytes().iter().zip(bytes) { if b1 != b2 { return false; } } return true; } let mut p1 = self.bytes().as_ptr(); let mut p2 = bytes.as_ptr(); let p1end = self.bytes()[self.len() - 8..].as_ptr(); let p2end = bytes[bytes.len() - 8..].as_ptr(); unsafe { while p1 < p1end { let v1 = (p1 as *const u64).read_unaligned(); let v2 = (p2 as *const u64).read_unaligned(); if v1 != v2 { return false; } p1 = p1.add(8); p2 = p2.add(8); } let v1 = (p1end as *const u64).read_unaligned(); let v2 = (p2end as *const u64).read_unaligned(); v1 == v2 } } }
use std::cmp; use std::fmt; use std::mem; use std::u16; use std::usize; use crate::packed::api::MatchKind; pub type PatternID = u16; #[derive(Clone, Debug)] pub struct Patterns { kind: MatchKind, by_id: Vec<Vec<u8>>, order: Vec<PatternID>, minimum_len: usize, max_pattern_id: PatternID, total_pattern_bytes: usize, } impl Patterns { pub fn new() -> Patterns { Patterns { kind: MatchKind::default(), by_id: vec![], order: vec![], minimum_len: usize::MAX, max_pattern_id: 0, total_pattern_bytes: 0, } } pub fn add(&mut self, bytes: &[u8]) { assert!(!bytes.is_empty()); assert!(self.by_id.len() <= u16::MAX as usize); let id = self.by_id.len() as u16; self.max_pattern_id = id; self.order.push(id); self.by_id.push(bytes.to_vec()); self.minimum_len = cmp::min(self.minimum_len, bytes.len()); self.total_pattern_bytes += bytes.len(); } pub fn set_match_kind(&mut self, kind: MatchKind) { match kind { MatchKind::LeftmostFirst => { self.order.sort(); } MatchKind::LeftmostLong
unreachable!(), } } pub fn len(&self) -> usize { self.by_id.len() } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn heap_bytes(&self) -> usize { self.order.len() * mem::size_of::<PatternID>() + self.by_id.len() * mem::size_of::<Vec<u8>>() + self.total_pattern_bytes } pub fn reset(&mut self) { self.kind = MatchKind::default(); self.by_id.clear(); self.order.clear(); self.minimum_len = usize::MAX; self.max_pattern_id = 0; } pub fn max_pattern_id(&self) -> PatternID { assert_eq!((self.max_pattern_id + 1) as usize, self.len()); self.max_pattern_id } pub fn minimum_len(&self) -> usize { self.minimum_len } pub fn match_kind(&self) -> &MatchKind { &self.kind } pub fn get(&self, id: PatternID) -> Pattern<'_> { Pattern(&self.by_id[id as usize]) } #[cfg(target_arch = "x86_64")] pub unsafe fn get_unchecked(&self, id: PatternID) -> Pattern<'_> { Pattern(self.by_id.get_unchecked(id as usize)) } pub fn iter(&self) -> PatternIter<'_> { PatternIter { patterns: self, i: 0 } } } #[derive(Debug)] pub struct PatternIter<'p> { patterns: &'p Patterns, i: usize, } impl<'p> Iterator for PatternIter<'p> { type Item = (PatternID, Pattern<'p>); fn next(&mut self) -> Option<(PatternID, Pattern<'p>)> { if self.i >= self.patterns.len() { return None; } let id = self.patterns.order[self.i]; let p = self.patterns.get(id); self.i += 1; Some((id, p)) } } #[derive(Clone)] pub struct Pattern<'a>(&'a [u8]); impl<'a> fmt::Debug for Pattern<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Pattern") .field("lit", &String::from_utf8_lossy(&self.0)) .finish() } } impl<'p> Pattern<'p> { pub fn len(&self) -> usize { self.0.len() } pub fn bytes(&self) -> &[u8] { &self.0 } #[cfg(target_arch = "x86_64")] pub fn low_nybbles(&self, len: usize) -> Vec<u8> { let mut nybs = vec![]; for &b in self.bytes().iter().take(len) { nybs.push(b & 0xF); } nybs } #[inline(always)] pub fn is_prefix(&self, bytes: &[u8]) -> bool { self.len() <= bytes.len() && self.equals(&bytes[..self.len()]) } #[inline(always)] pub fn equals(&self, bytes: &[u8]) -> bool { if self.len() != bytes.len() { return false; } if self.len() < 8 { for (&b1, &b2) in self.bytes().iter().zip(bytes) { if b1 != b2 { return false; } } return true; } let mut p1 = self.bytes().as_ptr(); let mut p2 = bytes.as_ptr(); let p1end = self.bytes()[self.len() - 8..].as_ptr(); let p2end = bytes[bytes.len() - 8..].as_ptr(); unsafe { while p1 < p1end { let v1 = (p1 as *const u64).read_unaligned(); let v2 = (p2 as *const u64).read_unaligned(); if v1 != v2 { return false; } p1 = p1.add(8); p2 = p2.add(8); } let v1 = (p1end as *const u64).read_unaligned(); let v2 = (p2end as *const u64).read_unaligned(); v1 == v2 } } }
est => { let (order, by_id) = (&mut self.order, &mut self.by_id); order.sort_by(|&id1, &id2| { by_id[id1 as usize] .len() .cmp(&by_id[id2 as usize].len()) .reverse() }); } MatchKind::__Nonexhaustive =>
function_block-random_span
[ { "content": "#[inline]\n\npub fn checksum_ieee(data: &[u8]) -> u32 {\n\n let mut hasher = Hasher::new();\n\n hasher.update(data);\n\n hasher.finalize()\n\n}\n\n\n\n// Rust runs the tests concurrently, so unless we synchronize logging access\n\n// it will crash when attempting to run `cargo test` with ...
Rust
examples/compute/main.rs
hasenbanck/asche
a205c4364b9e425d3bd6b1b73e12c949a51e1e18
use erupt::vk; use asche::{CommandBufferSemaphore, QueueConfiguration, Queues}; fn main() -> Result<(), asche::AscheError> { let event_loop = winit::event_loop::EventLoop::new(); let window = winit::window::WindowBuilder::new() .with_title("asche - compute example") .with_inner_size(winit::dpi::PhysicalSize::new(1920, 1080)) .build(&event_loop) .unwrap(); #[cfg(feature = "tracing")] { let filter = tracing_subscriber::EnvFilter::from_default_env(); tracing_subscriber::fmt().with_env_filter(filter).init(); } let instance = asche::Instance::new( &window, asche::InstanceConfiguration { app_name: "compute example", app_version: asche::Version { major: 1, minor: 0, patch: 0, }, engine_name: "engine example", engine_version: asche::Version { major: 1, minor: 0, patch: 0, }, extensions: vec![], }, )?; let (device, _, queues) = unsafe { instance.request_device(asche::DeviceConfiguration { queue_configuration: QueueConfiguration { compute_queues: vec![1.0], graphics_queues: vec![], transfer_queues: vec![], }, ..Default::default() }) }?; let Queues { mut compute_queues, graphics_queues: _graphics_queues, transfer_queues: _transfer_queues, } = queues; let mut app = Application::new(device, compute_queues.pop().unwrap())?; app.compute()?; Ok(()) } #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] pub enum Lifetime { Buffer, } impl asche::Lifetime for Lifetime {} struct Application { device: asche::Device<Lifetime>, compute_queue: asche::ComputeQueue, compute_command_pool: asche::ComputeCommandPool, pipeline: asche::ComputePipeline, pipeline_layout: asche::PipelineLayout, timeline: asche::TimelineSemaphore, timeline_value: u64, descriptor_set_layout: asche::DescriptorSetLayout, descriptor_pool: asche::DescriptorPool, } impl Drop for Application { fn drop(&mut self) { unsafe { self.device .wait_idle() .expect("couldn't wait for device to become idle while dropping") } } } impl Application { fn new( device: asche::Device<Lifetime>, mut compute_queue: asche::ComputeQueue, ) -> Result<Self, asche::AscheError> { let comp_module = unsafe { device.create_shader_module( "Compute Shader Module", include_bytes!("shader/compute.comp.spv"), ) }?; let mainfunctionname = std::ffi::CString::new("main").unwrap(); let compute_shader_stage = vk::PipelineShaderStageCreateInfoBuilder::new() .stage(vk::ShaderStageFlagBits::COMPUTE) .module(comp_module.raw()) .name(&mainfunctionname); let bindings = [vk::DescriptorSetLayoutBindingBuilder::new() .binding(0) .descriptor_count(1) .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) .stage_flags(vk::ShaderStageFlags::COMPUTE)]; let layout_info = vk::DescriptorSetLayoutCreateInfoBuilder::new().bindings(&bindings); let descriptor_set_layout = unsafe { device.create_descriptor_set_layout("Compute Descriptor Set Layout", layout_info) }?; let pool_sizes = [vk::DescriptorPoolSizeBuilder::new() .descriptor_count(1) ._type(vk::DescriptorType::STORAGE_BUFFER)]; let descriptor_pool = unsafe { device.create_descriptor_pool(&asche::DescriptorPoolDescriptor { name: "Compute Descriptor Pool", max_sets: 16, pool_sizes: &pool_sizes, flags: None, }) }?; let layouts = [descriptor_set_layout.raw()]; let pipeline_layout = vk::PipelineLayoutCreateInfoBuilder::new().set_layouts(&layouts); let pipeline_layout = unsafe { device.create_pipeline_layout("Compute Pipeline Layout", pipeline_layout) }?; let pipeline_info = vk::ComputePipelineCreateInfoBuilder::new() .layout(pipeline_layout.raw()) .stage(compute_shader_stage.build()); let pipeline = unsafe { device.create_compute_pipeline("Compute Pipeline", pipeline_info) }?; let compute_command_pool = unsafe { compute_queue.create_command_pool() }?; let timeline_value = 0; let timeline = unsafe { device.create_timeline_semaphore("Compute Timeline", timeline_value) }?; Ok(Self { device, compute_queue, compute_command_pool, pipeline, pipeline_layout, timeline, timeline_value, descriptor_set_layout, descriptor_pool, }) } fn compute(&mut self) -> Result<(), asche::AscheError> { const ELEMENTS: usize = 64 * 1024; const DATA_SIZE: u64 = (ELEMENTS * std::mem::size_of::<u32>()) as u64; let mut data: Vec<u32> = vec![0; ELEMENTS]; data.iter_mut() .enumerate() .for_each(|(id, x)| *x = id as u32); let mut buffer = unsafe { self.device.create_buffer(&asche::BufferDescriptor::<_> { name: "Input Buffer", usage: vk::BufferUsageFlags::STORAGE_BUFFER, memory_location: vk_alloc::MemoryLocation::CpuToGpu, lifetime: Lifetime::Buffer, sharing_mode: vk::SharingMode::EXCLUSIVE, queues: vk::QueueFlags::COMPUTE, size: DATA_SIZE, flags: None, }) }?; unsafe { let data_slice = buffer .mapped_slice_mut()? .expect("data buffer allocation was not mapped"); data_slice[..].clone_from_slice(bytemuck::cast_slice(&data)); buffer.flush()?; } let compute_buffer = unsafe { self.compute_command_pool.create_command_buffer( &[CommandBufferSemaphore::Timeline { semaphore: self.timeline.handle(), stage: vk::PipelineStageFlags2KHR::NONE_KHR, value: self.timeline_value, }], &[CommandBufferSemaphore::Timeline { semaphore: self.timeline.handle(), stage: vk::PipelineStageFlags2KHR::NONE_KHR, value: self.timeline_value + 1, }], ) }?; let set = unsafe { self.descriptor_pool.create_descriptor_set( "Compute Descriptor Set", &self.descriptor_set_layout, None, ) }?; let buffer_info = [vk::DescriptorBufferInfoBuilder::new() .buffer(buffer.raw()) .offset(0) .range(DATA_SIZE)]; let write = vk::WriteDescriptorSetBuilder::new() .dst_set(set.raw()) .dst_binding(0) .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) .buffer_info(&buffer_info); unsafe { self.device.update_descriptor_sets(&[write], &[]) }; unsafe { let encoder = compute_buffer.record()?; encoder.bind_pipeline(&self.pipeline); encoder.bind_descriptor_sets(self.pipeline_layout.raw(), 0, &[set.raw()], &[]); encoder.dispatch(1024, 1, 1); drop(encoder); self.compute_queue.submit(&compute_buffer, None)?; self.timeline_value += 1; self.timeline.wait_for_value(self.timeline_value)?; } unsafe { let data_slice = buffer .mapped_slice() .expect("data buffer allocation was not mapped") .unwrap(); data[..].clone_from_slice(bytemuck::cast_slice(data_slice)); } data.iter() .enumerate() .for_each(|(id, output)| assert_eq!((id * 42) as u32, *output)); Ok(()) } }
use erupt::vk; use asche::{CommandBufferSemaphore, QueueConfiguration, Queues}; fn main() -> Result<(), asche::AscheError> { let event_loop = winit::event_loop::EventLoop::new(); let window = winit::window::WindowBuilder::new() .with_title("asche - compute example") .with_inner_size(winit::dpi::PhysicalSize::new(1920, 1080)) .build(&event_loop) .unwrap(); #[cfg(feature = "tracing")] { let filter = tracing_subscriber::EnvFilter::from_default_env(); tracing_subscriber::fmt().with_env_filter(filter).init(); }
t app = Application::new(device, compute_queues.pop().unwrap())?; app.compute()?; Ok(()) } #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] pub enum Lifetime { Buffer, } impl asche::Lifetime for Lifetime {} struct Application { device: asche::Device<Lifetime>, compute_queue: asche::ComputeQueue, compute_command_pool: asche::ComputeCommandPool, pipeline: asche::ComputePipeline, pipeline_layout: asche::PipelineLayout, timeline: asche::TimelineSemaphore, timeline_value: u64, descriptor_set_layout: asche::DescriptorSetLayout, descriptor_pool: asche::DescriptorPool, } impl Drop for Application { fn drop(&mut self) { unsafe { self.device .wait_idle() .expect("couldn't wait for device to become idle while dropping") } } } impl Application { fn new( device: asche::Device<Lifetime>, mut compute_queue: asche::ComputeQueue, ) -> Result<Self, asche::AscheError> { let comp_module = unsafe { device.create_shader_module( "Compute Shader Module", include_bytes!("shader/compute.comp.spv"), ) }?; let mainfunctionname = std::ffi::CString::new("main").unwrap(); let compute_shader_stage = vk::PipelineShaderStageCreateInfoBuilder::new() .stage(vk::ShaderStageFlagBits::COMPUTE) .module(comp_module.raw()) .name(&mainfunctionname); let bindings = [vk::DescriptorSetLayoutBindingBuilder::new() .binding(0) .descriptor_count(1) .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) .stage_flags(vk::ShaderStageFlags::COMPUTE)]; let layout_info = vk::DescriptorSetLayoutCreateInfoBuilder::new().bindings(&bindings); let descriptor_set_layout = unsafe { device.create_descriptor_set_layout("Compute Descriptor Set Layout", layout_info) }?; let pool_sizes = [vk::DescriptorPoolSizeBuilder::new() .descriptor_count(1) ._type(vk::DescriptorType::STORAGE_BUFFER)]; let descriptor_pool = unsafe { device.create_descriptor_pool(&asche::DescriptorPoolDescriptor { name: "Compute Descriptor Pool", max_sets: 16, pool_sizes: &pool_sizes, flags: None, }) }?; let layouts = [descriptor_set_layout.raw()]; let pipeline_layout = vk::PipelineLayoutCreateInfoBuilder::new().set_layouts(&layouts); let pipeline_layout = unsafe { device.create_pipeline_layout("Compute Pipeline Layout", pipeline_layout) }?; let pipeline_info = vk::ComputePipelineCreateInfoBuilder::new() .layout(pipeline_layout.raw()) .stage(compute_shader_stage.build()); let pipeline = unsafe { device.create_compute_pipeline("Compute Pipeline", pipeline_info) }?; let compute_command_pool = unsafe { compute_queue.create_command_pool() }?; let timeline_value = 0; let timeline = unsafe { device.create_timeline_semaphore("Compute Timeline", timeline_value) }?; Ok(Self { device, compute_queue, compute_command_pool, pipeline, pipeline_layout, timeline, timeline_value, descriptor_set_layout, descriptor_pool, }) } fn compute(&mut self) -> Result<(), asche::AscheError> { const ELEMENTS: usize = 64 * 1024; const DATA_SIZE: u64 = (ELEMENTS * std::mem::size_of::<u32>()) as u64; let mut data: Vec<u32> = vec![0; ELEMENTS]; data.iter_mut() .enumerate() .for_each(|(id, x)| *x = id as u32); let mut buffer = unsafe { self.device.create_buffer(&asche::BufferDescriptor::<_> { name: "Input Buffer", usage: vk::BufferUsageFlags::STORAGE_BUFFER, memory_location: vk_alloc::MemoryLocation::CpuToGpu, lifetime: Lifetime::Buffer, sharing_mode: vk::SharingMode::EXCLUSIVE, queues: vk::QueueFlags::COMPUTE, size: DATA_SIZE, flags: None, }) }?; unsafe { let data_slice = buffer .mapped_slice_mut()? .expect("data buffer allocation was not mapped"); data_slice[..].clone_from_slice(bytemuck::cast_slice(&data)); buffer.flush()?; } let compute_buffer = unsafe { self.compute_command_pool.create_command_buffer( &[CommandBufferSemaphore::Timeline { semaphore: self.timeline.handle(), stage: vk::PipelineStageFlags2KHR::NONE_KHR, value: self.timeline_value, }], &[CommandBufferSemaphore::Timeline { semaphore: self.timeline.handle(), stage: vk::PipelineStageFlags2KHR::NONE_KHR, value: self.timeline_value + 1, }], ) }?; let set = unsafe { self.descriptor_pool.create_descriptor_set( "Compute Descriptor Set", &self.descriptor_set_layout, None, ) }?; let buffer_info = [vk::DescriptorBufferInfoBuilder::new() .buffer(buffer.raw()) .offset(0) .range(DATA_SIZE)]; let write = vk::WriteDescriptorSetBuilder::new() .dst_set(set.raw()) .dst_binding(0) .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) .buffer_info(&buffer_info); unsafe { self.device.update_descriptor_sets(&[write], &[]) }; unsafe { let encoder = compute_buffer.record()?; encoder.bind_pipeline(&self.pipeline); encoder.bind_descriptor_sets(self.pipeline_layout.raw(), 0, &[set.raw()], &[]); encoder.dispatch(1024, 1, 1); drop(encoder); self.compute_queue.submit(&compute_buffer, None)?; self.timeline_value += 1; self.timeline.wait_for_value(self.timeline_value)?; } unsafe { let data_slice = buffer .mapped_slice() .expect("data buffer allocation was not mapped") .unwrap(); data[..].clone_from_slice(bytemuck::cast_slice(data_slice)); } data.iter() .enumerate() .for_each(|(id, output)| assert_eq!((id * 42) as u32, *output)); Ok(()) } }
let instance = asche::Instance::new( &window, asche::InstanceConfiguration { app_name: "compute example", app_version: asche::Version { major: 1, minor: 0, patch: 0, }, engine_name: "engine example", engine_version: asche::Version { major: 1, minor: 0, patch: 0, }, extensions: vec![], }, )?; let (device, _, queues) = unsafe { instance.request_device(asche::DeviceConfiguration { queue_configuration: QueueConfiguration { compute_queues: vec![1.0], graphics_queues: vec![], transfer_queues: vec![], }, ..Default::default() }) }?; let Queues { mut compute_queues, graphics_queues: _graphics_queues, transfer_queues: _transfer_queues, } = queues; let mu
function_block-random_span
[ { "content": "fn main() -> Result<()> {\n\n let event_loop = winit::event_loop::EventLoop::new();\n\n let window = winit::window::WindowBuilder::new()\n\n .with_title(\"asche - raytracing example\")\n\n .with_inner_size(winit::dpi::PhysicalSize::new(1920, 1080))\n\n .build(&event_loop...
Rust
src/cargo/lib.rs
jakerr/cargo
f0762dfc1340c24ad87fa59027d5308c96867393
#![crate_name="cargo"] #![crate_type="rlib"] #![feature(macro_rules, phase)] #![feature(default_type_params)] #![deny(bad_style, unused)] extern crate libc; extern crate regex; extern crate serialize; extern crate term; extern crate time; #[phase(plugin)] extern crate regex_macros; #[phase(plugin, link)] extern crate log; extern crate curl; extern crate docopt; extern crate flate2; extern crate git2; extern crate glob; extern crate semver; extern crate tar; extern crate toml; extern crate url; #[cfg(test)] extern crate hamcrest; use std::os; use std::io::stdio::{stdout_raw, stderr_raw}; use std::io::{mod, stdout, stderr}; use serialize::{Decoder, Encoder, Decodable, Encodable, json}; use docopt::FlagParser; use core::{Shell, MultiShell, ShellConfig}; use term::color::{BLACK}; pub use util::{CargoError, CliError, CliResult, human}; macro_rules! some( ($e:expr) => ( match $e { Some(e) => e, None => return None } ) ) mod cargo { pub use super::util; } #[macro_export] macro_rules! try ( ($expr:expr) => ({ use cargo::util::FromError; match $expr.map_err(FromError::from_error) { Ok(val) => val, Err(err) => return Err(err) } }) ) macro_rules! raw_try ( ($expr:expr) => ({ match $expr { Ok(val) => val, Err(err) => return Err(err) } }) ) pub mod core; pub mod ops; pub mod sources; pub mod util; pub trait RepresentsJSON : Decodable<json::Decoder, json::DecoderError> {} impl<T: Decodable<json::Decoder, json::DecoderError>> RepresentsJSON for T {} pub fn execute_main<'a, T: FlagParser, U: RepresentsJSON, V: Encodable<json::Encoder<'a>, io::IoError>>( exec: fn(T, U, &mut MultiShell) -> CliResult<Option<V>>, options_first: bool) { off_the_main_thread(proc() { process::<V>(|rest, shell| call_main(exec, shell, rest, options_first)); }); } pub fn call_main<'a, T: FlagParser, U: RepresentsJSON, V: Encodable<json::Encoder<'a>, io::IoError>>( exec: fn(T, U, &mut MultiShell) -> CliResult<Option<V>>, shell: &mut MultiShell, args: &[String], options_first: bool) -> CliResult<Option<V>> { let flags = try!(flags_from_args::<T>(args, options_first)); let json = try!(json_from_stdin::<U>()); exec(flags, json, shell) } pub fn execute_main_without_stdin<'a, T: FlagParser, V: Encodable<json::Encoder<'a>, io::IoError>>( exec: fn(T, &mut MultiShell) -> CliResult<Option<V>>, options_first: bool) { off_the_main_thread(proc() { process::<V>(|rest, shell| call_main_without_stdin(exec, shell, rest, options_first)); }); } pub fn call_main_without_stdin<'a, T: FlagParser, V: Encodable<json::Encoder<'a>, io::IoError>>( exec: fn(T, &mut MultiShell) -> CliResult<Option<V>>, shell: &mut MultiShell, args: &[String], options_first: bool) -> CliResult<Option<V>> { let flags = try!(flags_from_args::<T>(args, options_first)); exec(flags, shell) } fn process<'a, V: Encodable<json::Encoder<'a>, io::IoError>>( callback: |&[String], &mut MultiShell| -> CliResult<Option<V>>) { let mut shell = shell(true); let mut args = os::args(); args.remove(0); process_executed(callback(args.as_slice(), &mut shell), &mut shell) } pub fn process_executed<'a, T: Encodable<json::Encoder<'a>, io::IoError>>( result: CliResult<Option<T>>, shell: &mut MultiShell) { match result { Err(e) => handle_error(e, shell), Ok(encodable) => { encodable.map(|encodable| { let encoded = json::encode(&encodable); println!("{}", encoded); }); } } } pub fn shell(verbose: bool) -> MultiShell<'static> { let tty = stderr_raw().isatty(); let stderr = box stderr() as Box<Writer>; let config = ShellConfig { color: true, verbose: verbose, tty: tty }; let err = Shell::create(stderr, config); let tty = stdout_raw().isatty(); let stdout = box stdout() as Box<Writer>; let config = ShellConfig { color: true, verbose: verbose, tty: tty }; let out = Shell::create(stdout, config); MultiShell::new(out, err, verbose) } pub fn handle_error(err: CliError, shell: &mut MultiShell) { log!(4, "handle_error; err={}", err); let CliError { error, exit_code, unknown } = err; if unknown { let _ = shell.error("An unknown error occurred"); } else if error.to_string().len() > 0 { let _ = shell.error(error.to_string()); } if error.cause().is_some() || unknown { let _ = shell.concise(|shell| { shell.err().say("\nTo learn more, run the command again with --verbose.", BLACK) }); } let _ = shell.verbose(|shell| { if unknown { let _ = shell.error(error.to_string()); } error.detail().map(|detail| { let _ = shell.err().say(format!("{}", detail), BLACK); }); error.cause().map(|err| { let _ = handle_cause(err, shell); }); Ok(()) }); std::os::set_exit_status(exit_code as int); } fn handle_cause(err: &CargoError, shell: &mut MultiShell) { let _ = shell.err().say("\nCaused by:", BLACK); let _ = shell.err().say(format!(" {}", err.description()), BLACK); err.cause().map(|e| handle_cause(e, shell)); } pub fn version() -> String { format!("cargo {}", match option_env!("CFG_VERSION") { Some(s) => s.to_string(), None => format!("{}.{}.{}{}", env!("CARGO_PKG_VERSION_MAJOR"), env!("CARGO_PKG_VERSION_MINOR"), env!("CARGO_PKG_VERSION_PATCH"), option_env!("CARGO_PKG_VERSION_PRE").unwrap_or("")) }) } fn flags_from_args<T: FlagParser>(args: &[String], options_first: bool) -> CliResult<T> { let args = args.iter().map(|a| a.as_slice()).collect::<Vec<&str>>(); let config = docopt::Config { options_first: options_first, help: true, version: Some(version()), }; FlagParser::parse_args(config, args.as_slice()).map_err(|e| { let code = if e.fatal() {1} else {0}; CliError::from_error(e, code) }) } fn json_from_stdin<T: RepresentsJSON>() -> CliResult<T> { let mut reader = io::stdin(); let input = try!(reader.read_to_string().map_err(|_| { CliError::new("Standard in did not exist or was not UTF-8", 1) })); let json = try!(json::from_str(input.as_slice()).map_err(|_| { CliError::new("Could not parse standard in as JSON", 1) })); let mut decoder = json::Decoder::new(json); Decodable::decode(&mut decoder).map_err(|_| { CliError::new("Could not process standard in as input", 1) }) } fn off_the_main_thread(p: proc():Send) { let (tx, rx) = channel(); spawn(proc() { p(); tx.send(()); }); if rx.recv_opt().is_err() { std::os::set_exit_status(std::rt::DEFAULT_ERROR_CODE); } }
#![crate_name="cargo"] #![crate_type="rlib"] #![feature(macro_rules, phase)] #![feature(default_type_params)] #![deny(bad_style, unused)] extern crate libc; extern crate regex; extern crate serialize; extern crate term; extern crate time; #[phase(plugin)] extern crate regex_macros; #[phase(plugin, link)] extern crate log; extern crate curl; extern crate docopt; extern crate flate2; extern crate git2; extern crate glob; extern crate semver; extern crate tar; extern crate toml; extern crate url; #[cfg(test)] extern crate hamcrest; use std::os; use std::io::stdio::{stdout_raw, stderr_raw}; use std::io::{mod, stdout, stderr}; use serialize::{Decoder, Encoder, Decodable, Encodable, json}; use docopt::FlagParser; use core::{Shell, MultiShell, ShellConfig}; use term::color::{BLACK}; pub use util::{CargoError, CliError, CliResult, human}; macro_rules! some( ($e:expr) => ( match $e { Some(e) => e, None => return None } ) ) mod cargo { pub use super::util; } #[macro_export] macro_rules! try ( ($expr:expr) => ({ use cargo::util::FromError; match $expr.map_err(FromError::from_error) { Ok(val) => val, Err(err) => return Err(err) } }) ) macro_rules! raw_try ( ($expr:expr) => ({ match $expr { Ok(val) => val, Err(err) => return Err(err) } }) ) pub mod core; pub mod ops; pub mod sources; pub mod util; pub trait RepresentsJSON : Decodable<json::Decoder, json::DecoderError> {} impl<T: Decodable<json::Decoder, json::DecoderError>> RepresentsJSON for T {} pub fn execute_main<'a, T: FlagParser, U: RepresentsJSON, V: Encodable<json::Encoder<'a>, io::IoError>>( exec: fn(T, U, &mut MultiShell) -> CliResult<Option<V>>, options_first: bool) { off_the_main_thread(proc() { process::<V>(|rest, shell| call_main(exec, shell, rest, options_first)); }); } pub fn call_main<'a, T: FlagParser, U: RepresentsJSON, V: Encodable<json::Encoder<'a>, io::IoError>>( exec: fn(T, U, &mut MultiShell) -> CliResult<Option<V>>, shell: &mut MultiShell, args: &[String], options_first: bool) -> CliResult<Option<V>> { let flags = try!(flags_from_args::<T>(args, options_first)); let json = try!(json_from_stdin::<U>()); exec(flags, json, shell) } pub fn execute_main_without_stdin<'a, T: FlagParser, V: Encodable<json::Encoder<'a>, io::IoError>>( exec: fn(T, &mut MultiShell) -> CliResult<Option<V>>, options_first: bool) { off_the_main_thread(proc() { process::<V>(|rest, shell| call_main_without_stdin(exec, shell, rest, options_first)); }); } pub fn call_main_without_stdin<'a, T: FlagParser, V: Encodable<json::Encoder<'a>, io::IoError>>( exec: fn(T, &mut MultiShell) -> CliResult<Option<V>>, shell: &mut MultiShell, args: &[String], options_first: bool) -> CliResult<Option<V>> { let flags = try!(flags_from_args::<T>(args, options_first)); exec(flags, shell) } fn process<'a, V: Encodable<json::Encoder<'a>, io::IoError>>( callback: |&[String], &mut MultiShell| -> CliResult<Option<V>>) { let mut shell = shell(true); let mut args = os::args(); args.remove(0); process_executed(callback(args.as_slice(), &mut shell), &mut shell) } pub fn process_executed<'a, T: Encodable<json::Encoder<'a>, io::IoError>>( result: CliResult<Option<T>>, shell: &mut MultiShel
pub fn shell(verbose: bool) -> MultiShell<'static> { let tty = stderr_raw().isatty(); let stderr = box stderr() as Box<Writer>; let config = ShellConfig { color: true, verbose: verbose, tty: tty }; let err = Shell::create(stderr, config); let tty = stdout_raw().isatty(); let stdout = box stdout() as Box<Writer>; let config = ShellConfig { color: true, verbose: verbose, tty: tty }; let out = Shell::create(stdout, config); MultiShell::new(out, err, verbose) } pub fn handle_error(err: CliError, shell: &mut MultiShell) { log!(4, "handle_error; err={}", err); let CliError { error, exit_code, unknown } = err; if unknown { let _ = shell.error("An unknown error occurred"); } else if error.to_string().len() > 0 { let _ = shell.error(error.to_string()); } if error.cause().is_some() || unknown { let _ = shell.concise(|shell| { shell.err().say("\nTo learn more, run the command again with --verbose.", BLACK) }); } let _ = shell.verbose(|shell| { if unknown { let _ = shell.error(error.to_string()); } error.detail().map(|detail| { let _ = shell.err().say(format!("{}", detail), BLACK); }); error.cause().map(|err| { let _ = handle_cause(err, shell); }); Ok(()) }); std::os::set_exit_status(exit_code as int); } fn handle_cause(err: &CargoError, shell: &mut MultiShell) { let _ = shell.err().say("\nCaused by:", BLACK); let _ = shell.err().say(format!(" {}", err.description()), BLACK); err.cause().map(|e| handle_cause(e, shell)); } pub fn version() -> String { format!("cargo {}", match option_env!("CFG_VERSION") { Some(s) => s.to_string(), None => format!("{}.{}.{}{}", env!("CARGO_PKG_VERSION_MAJOR"), env!("CARGO_PKG_VERSION_MINOR"), env!("CARGO_PKG_VERSION_PATCH"), option_env!("CARGO_PKG_VERSION_PRE").unwrap_or("")) }) } fn flags_from_args<T: FlagParser>(args: &[String], options_first: bool) -> CliResult<T> { let args = args.iter().map(|a| a.as_slice()).collect::<Vec<&str>>(); let config = docopt::Config { options_first: options_first, help: true, version: Some(version()), }; FlagParser::parse_args(config, args.as_slice()).map_err(|e| { let code = if e.fatal() {1} else {0}; CliError::from_error(e, code) }) } fn json_from_stdin<T: RepresentsJSON>() -> CliResult<T> { let mut reader = io::stdin(); let input = try!(reader.read_to_string().map_err(|_| { CliError::new("Standard in did not exist or was not UTF-8", 1) })); let json = try!(json::from_str(input.as_slice()).map_err(|_| { CliError::new("Could not parse standard in as JSON", 1) })); let mut decoder = json::Decoder::new(json); Decodable::decode(&mut decoder).map_err(|_| { CliError::new("Could not process standard in as input", 1) }) } fn off_the_main_thread(p: proc():Send) { let (tx, rx) = channel(); spawn(proc() { p(); tx.send(()); }); if rx.recv_opt().is_err() { std::os::set_exit_status(std::rt::DEFAULT_ERROR_CODE); } }
l) { match result { Err(e) => handle_error(e, shell), Ok(encodable) => { encodable.map(|encodable| { let encoded = json::encode(&encodable); println!("{}", encoded); }); } } }
function_block-function_prefixed
[ { "content": "pub fn upload_login(shell: &mut MultiShell, token: String) -> CargoResult<()> {\n\n let config = try!(Config::new(shell, None, None));\n\n let UploadConfig { host, token: _ } = try!(upload_configuration());\n\n let mut map = HashMap::new();\n\n let p = os::getcwd();\n\n match host {...
Rust
kernel/net/tcp_socket.rs
castarco/kerla
52b15dbfcbf537bdad5b982d4d5cae3a9c7ae743
use crate::{ arch::SpinLock, fs::{ inode::{FileLike, PollStatus}, opened_file::OpenOptions, }, net::{socket::SockAddr, RecvFromFlags}, user_buffer::UserBuffer, user_buffer::{UserBufReader, UserBufWriter, UserBufferMut}, }; use crate::{ arch::SpinLockGuard, result::{Errno, Result}, }; use alloc::{collections::BTreeSet, sync::Arc, vec::Vec}; use core::{cmp::min, convert::TryInto, fmt}; use crossbeam::atomic::AtomicCell; use smoltcp::socket::{SocketRef, TcpSocketBuffer}; use smoltcp::wire::{IpAddress, IpEndpoint, Ipv4Address}; use super::{process_packets, SOCKETS, SOCKET_WAIT_QUEUE}; const BACKLOG_MAX: usize = 8; static INUSE_ENDPOINTS: SpinLock<BTreeSet<u16>> = SpinLock::new(BTreeSet::new()); fn get_ready_backlog_index( sockets: &mut smoltcp::socket::SocketSet, backlogs: &[Arc<TcpSocket>], ) -> Option<usize> { backlogs.iter().position(|sock| { let smol_socket: SocketRef<'_, smoltcp::socket::TcpSocket> = sockets.get(sock.handle); smol_socket.may_recv() || smol_socket.may_send() }) } pub struct TcpSocket { handle: smoltcp::socket::SocketHandle, local_endpoint: AtomicCell<Option<IpEndpoint>>, backlogs: SpinLock<Vec<Arc<TcpSocket>>>, num_backlogs: AtomicCell<usize>, } impl TcpSocket { pub fn new() -> Arc<TcpSocket> { let rx_buffer = TcpSocketBuffer::new(vec![0; 4096]); let tx_buffer = TcpSocketBuffer::new(vec![0; 4096]); let inner = smoltcp::socket::TcpSocket::new(rx_buffer, tx_buffer); let handle = SOCKETS.lock().add(inner); Arc::new(TcpSocket { handle, local_endpoint: AtomicCell::new(None), backlogs: SpinLock::new(Vec::new()), num_backlogs: AtomicCell::new(0), }) } fn refill_backlog_sockets( &self, backlogs: &mut SpinLockGuard<'_, Vec<Arc<TcpSocket>>>, ) -> Result<()> { let local_endpoint = match self.local_endpoint.load() { Some(local_endpoint) => local_endpoint, None => return Err(Errno::EINVAL.into()), }; for _ in 0..(self.num_backlogs.load() - backlogs.len()) { let socket = TcpSocket::new(); SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(socket.handle) .listen(local_endpoint)?; backlogs.push(socket); } Ok(()) } } impl FileLike for TcpSocket { fn listen(&self, backlog: i32) -> Result<()> { let mut backlogs = self.backlogs.lock(); let new_num_backlogs = min(backlog as usize, BACKLOG_MAX); backlogs.truncate(new_num_backlogs); self.num_backlogs.store(new_num_backlogs); self.refill_backlog_sockets(&mut backlogs) } fn accept(&self, _options: &OpenOptions) -> Result<(Arc<dyn FileLike>, SockAddr)> { SOCKET_WAIT_QUEUE.sleep_signalable_until(|| { let mut sockets = SOCKETS.lock(); let mut backlogs = self.backlogs.lock(); match get_ready_backlog_index(&mut *sockets, &*backlogs) { Some(index) => { let socket = backlogs.remove(index); drop(sockets); self.refill_backlog_sockets(&mut backlogs)?; let mut sockets_lock = SOCKETS.lock(); let smol_socket: SocketRef<'_, smoltcp::socket::TcpSocket> = sockets_lock.get(socket.handle); Ok(Some(( socket as Arc<dyn FileLike>, smol_socket.remote_endpoint().into(), ))) } None => { Ok(None) } } }) } fn bind(&self, sockaddr: SockAddr) -> Result<()> { self.local_endpoint.store(Some(sockaddr.try_into()?)); Ok(()) } fn getsockname(&self) -> Result<SockAddr> { let endpoint = SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(self.handle) .local_endpoint(); if endpoint.addr.is_unspecified() { return Err(Errno::ENOTCONN.into()); } Ok(endpoint.into()) } fn getpeername(&self) -> Result<SockAddr> { let endpoint = SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(self.handle) .remote_endpoint(); if endpoint.addr.is_unspecified() { return Err(Errno::ENOTCONN.into()); } Ok(endpoint.into()) } fn connect(&self, sockaddr: SockAddr, _options: &OpenOptions) -> Result<()> { let remote_endpoint: IpEndpoint = sockaddr.try_into()?; let mut inuse_endpoints = INUSE_ENDPOINTS.lock(); let mut local_endpoint = self.local_endpoint.load().unwrap_or(IpEndpoint { addr: IpAddress::Ipv4(Ipv4Address::UNSPECIFIED), port: 0, }); if local_endpoint.port == 0 { let mut port = 50000; while inuse_endpoints.contains(&port) { if port == u16::MAX { return Err(Errno::EAGAIN.into()); } port += 1; } local_endpoint.port = port; } SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(self.handle) .connect(remote_endpoint, local_endpoint)?; inuse_endpoints.insert(remote_endpoint.port); drop(inuse_endpoints); process_packets(); SOCKET_WAIT_QUEUE.sleep_signalable_until(|| { if SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(self.handle) .may_send() { Ok(Some(())) } else { Ok(None) } }) } fn write(&self, _offset: usize, buf: UserBuffer<'_>, _options: &OpenOptions) -> Result<usize> { let mut total_len = 0; let mut reader = UserBufReader::from(buf); loop { let copied_len = SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(self.handle) .send(|dst| { let copied_len = reader.read_bytes(dst).unwrap_or(0); (copied_len, copied_len) }); process_packets(); match copied_len { Ok(0) => { return Ok(total_len); } Ok(copied_len) => { total_len += copied_len; } Err(err) => return Err(err.into()), } } } fn read(&self, _offset: usize, buf: UserBufferMut<'_>, options: &OpenOptions) -> Result<usize> { let mut writer = UserBufWriter::from(buf); SOCKET_WAIT_QUEUE.sleep_signalable_until(|| { let copied_len = SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(self.handle) .recv(|src| { let copied_len = writer.write_bytes(src).unwrap_or(0); (copied_len, copied_len) }); match copied_len { Ok(0) | Err(smoltcp::Error::Exhausted) => { if options.nonblock { Err(Errno::EAGAIN.into()) } else { Ok(None) } } Ok(copied_len) => { Ok(Some(copied_len)) } Err(err) => Err(err.into()), } }) } fn sendto( &self, buf: UserBuffer<'_>, sockaddr: Option<SockAddr>, options: &OpenOptions, ) -> Result<usize> { if sockaddr.is_some() { return Err(Errno::EINVAL.into()); } self.write(0, buf, options) } fn recvfrom( &self, buf: UserBufferMut<'_>, _flags: RecvFromFlags, options: &OpenOptions, ) -> Result<(usize, SockAddr)> { Ok((self.read(0, buf, options)?, self.getpeername()?)) } fn poll(&self) -> Result<PollStatus> { let mut status = PollStatus::empty(); let mut sockets = SOCKETS.lock(); if get_ready_backlog_index(&mut *sockets, &*self.backlogs.lock()).is_some() { status |= PollStatus::POLLIN; } let socket = sockets.get::<smoltcp::socket::TcpSocket>(self.handle); if socket.can_recv() { status |= PollStatus::POLLIN; } if socket.can_send() { status |= PollStatus::POLLOUT; } Ok(status) } } impl fmt::Debug for TcpSocket { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TcpSocket").finish() } }
use crate::{ arch::SpinLock, fs::{ inode::{FileLike, PollStatus}, opened_file::OpenOptions, }, net::{socket::SockAddr, RecvFromFlags}, user_buffer::UserBuffer, user_buffer::{UserBufReader, UserBufWriter, UserBufferMut}, }; use crate::{ arch::SpinLockGuard, result::{Errno, Result}, }; use alloc::{collections::BTreeSet, sync::Arc, vec::Vec}; use core::{cmp::min, convert::TryInto, fmt}; use crossbeam::atomic::AtomicCell; use smoltcp::socket::{SocketRef, TcpSocketBuffer}; use smoltcp::wire::{IpAddress, IpEndpoint, Ipv4Address}; use super::{process_packets, SOCKETS, SOCKET_WAIT_QUEUE}; const BACKLOG_MAX: usize = 8; static INUSE_ENDPOINTS: SpinLock<BTreeSet<u16>> = SpinLock::new(BTreeSet::new()); fn get_ready_backlog_index( sockets: &mut smoltcp::socket::SocketSet, backlogs: &[Arc<TcpSocket>], ) -> Option<usize> { backlogs.iter().position(|sock| { let smol_socket: SocketRef<'_, smoltcp::socket::TcpSocket> = sockets.get(sock.handle); smol_socket.may_recv() || smol_socket.may_send() }) } pub struct TcpSocket { handle: smoltcp::socket::SocketHandle, local_endpoint: AtomicCell<Option<IpEndpoint>>, backlogs: SpinLock<Vec<Arc<TcpSocket>>>, num_backlogs: AtomicCell<usize>, } impl TcpSocket { pub fn new() -> Arc<TcpSocket> { let rx_buffer = TcpSocketBuffer::new(vec![0; 4096]); let tx_buffer = TcpSocketBuffer::new(vec![0; 4096]); let inner = smoltcp::socket::TcpSocket::new(rx_buffer, tx_buffer); let handle = SOCKETS.lock().add(inner); Arc::new(TcpSocket { handle, local_endpoint: AtomicCell::new(None), backlogs: SpinLock::new(Vec::new()), num_backlogs: AtomicCell::new(0), }) } fn refill_backlog_sockets( &self, backlogs: &mut SpinLockGuard<'_, Vec<Arc<TcpSocket>>>, ) -> Result<()> { let local_endpoint = match self.local_endpoint.load() { Some(local_endpoint) => local_endpoint, None => return Err(Errno::EINVAL.into()), }; for _ in 0..(self.num_backlogs.load() - backlogs.len()) { let socket = TcpSocket::new(); SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(socket.handle) .listen(local_endpoint)?; backlogs.push(socket); } Ok(()) } } impl FileLike for TcpSocket { fn listen(&self, backlog: i32) -> Result<()> { let mut backlogs = self.backlogs.lock(); let new_num_backlogs = min(backlog as usize, BACKLOG_MAX); backlogs.truncate(new_num_backlogs); self.num_backlogs.store(new_num_backlogs); self.refill_backlog_sockets(&mut backlogs) } fn accept(&self, _options: &OpenOptions) -> Result<(Arc<dyn FileLike>, SockAddr)> { SOCKET_WAIT_QUEUE.sleep_signalable_until(|| { let mut sockets = SOCKETS.lock(); let mut backlogs = self.backlogs.lock(); match get_ready_backlog_index(&mut *sockets, &*backlogs) { Some(index) => { let socket = backlogs.remove(index); drop(sockets); self.refill_backlog_sockets(&mut backlogs)?; let mut sockets_lock = SOCKETS.lock(); let smol_socket: SocketRef<'_, smoltcp::socket::TcpSocket> = sockets_lock.get(socket.handle); Ok(Some(( socket as Arc<dyn FileLike>, smol_socket.remote_endpoint().into(), ))) } None => { Ok(None) } } }) } fn bind(&self, sockaddr: SockAddr) -> Result<()> { self.local_endpoint.store(Some(sockaddr.try_into()?)); Ok(()) }
fn getpeername(&self) -> Result<SockAddr> { let endpoint = SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(self.handle) .remote_endpoint(); if endpoint.addr.is_unspecified() { return Err(Errno::ENOTCONN.into()); } Ok(endpoint.into()) } fn connect(&self, sockaddr: SockAddr, _options: &OpenOptions) -> Result<()> { let remote_endpoint: IpEndpoint = sockaddr.try_into()?; let mut inuse_endpoints = INUSE_ENDPOINTS.lock(); let mut local_endpoint = self.local_endpoint.load().unwrap_or(IpEndpoint { addr: IpAddress::Ipv4(Ipv4Address::UNSPECIFIED), port: 0, }); if local_endpoint.port == 0 { let mut port = 50000; while inuse_endpoints.contains(&port) { if port == u16::MAX { return Err(Errno::EAGAIN.into()); } port += 1; } local_endpoint.port = port; } SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(self.handle) .connect(remote_endpoint, local_endpoint)?; inuse_endpoints.insert(remote_endpoint.port); drop(inuse_endpoints); process_packets(); SOCKET_WAIT_QUEUE.sleep_signalable_until(|| { if SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(self.handle) .may_send() { Ok(Some(())) } else { Ok(None) } }) } fn write(&self, _offset: usize, buf: UserBuffer<'_>, _options: &OpenOptions) -> Result<usize> { let mut total_len = 0; let mut reader = UserBufReader::from(buf); loop { let copied_len = SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(self.handle) .send(|dst| { let copied_len = reader.read_bytes(dst).unwrap_or(0); (copied_len, copied_len) }); process_packets(); match copied_len { Ok(0) => { return Ok(total_len); } Ok(copied_len) => { total_len += copied_len; } Err(err) => return Err(err.into()), } } } fn read(&self, _offset: usize, buf: UserBufferMut<'_>, options: &OpenOptions) -> Result<usize> { let mut writer = UserBufWriter::from(buf); SOCKET_WAIT_QUEUE.sleep_signalable_until(|| { let copied_len = SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(self.handle) .recv(|src| { let copied_len = writer.write_bytes(src).unwrap_or(0); (copied_len, copied_len) }); match copied_len { Ok(0) | Err(smoltcp::Error::Exhausted) => { if options.nonblock { Err(Errno::EAGAIN.into()) } else { Ok(None) } } Ok(copied_len) => { Ok(Some(copied_len)) } Err(err) => Err(err.into()), } }) } fn sendto( &self, buf: UserBuffer<'_>, sockaddr: Option<SockAddr>, options: &OpenOptions, ) -> Result<usize> { if sockaddr.is_some() { return Err(Errno::EINVAL.into()); } self.write(0, buf, options) } fn recvfrom( &self, buf: UserBufferMut<'_>, _flags: RecvFromFlags, options: &OpenOptions, ) -> Result<(usize, SockAddr)> { Ok((self.read(0, buf, options)?, self.getpeername()?)) } fn poll(&self) -> Result<PollStatus> { let mut status = PollStatus::empty(); let mut sockets = SOCKETS.lock(); if get_ready_backlog_index(&mut *sockets, &*self.backlogs.lock()).is_some() { status |= PollStatus::POLLIN; } let socket = sockets.get::<smoltcp::socket::TcpSocket>(self.handle); if socket.can_recv() { status |= PollStatus::POLLIN; } if socket.can_send() { status |= PollStatus::POLLOUT; } Ok(status) } } impl fmt::Debug for TcpSocket { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TcpSocket").finish() } }
fn getsockname(&self) -> Result<SockAddr> { let endpoint = SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(self.handle) .local_endpoint(); if endpoint.addr.is_unspecified() { return Err(Errno::ENOTCONN.into()); } Ok(endpoint.into()) }
function_block-full_function
[ { "content": "pub fn read_secure_random(buf: UserBufferMut<'_>) -> Result<usize> {\n\n // TODO: Implement arch-agnostic CRNG which does not fully depends on RDRAND.\n\n\n\n UserBufWriter::from(buf).write_with(|slice| {\n\n let valid = unsafe { rdrand_slice(slice) };\n\n if valid {\n\n ...
Rust
dao_factory/lib.rs
RainbowcityFoundation/RainbowDAO-Protocol-Ink-milestone_2
82757d337bea22dcb8e08b4759c47ec02d67a140
#![cfg_attr(not(feature = "std"), no_std)] #![feature(const_fn_trait_bound)] extern crate alloc; use ink_lang as ink; #[allow(unused_imports)] #[ink::contract] mod dao_factory { use alloc::string::String; use ink_prelude::vec::Vec; use ink_prelude::collections::BTreeMap; use ink_storage::{ traits::{ PackedLayout, SpreadLayout, }, collections::HashMap as StorageHashMap, }; use template_manager::TemplateManager; use template_manager::DAOTemplate; use dao_manager::DAOManager; const TEMPLATE_INIT_BALANCE: u128 = 1000 * 1_000_000_000_000; const DAO_INIT_BALANCE: u128 = 1000 * 1_000_000_000_000; #[derive(scale::Encode, scale::Decode, Clone, SpreadLayout, PackedLayout)] #[cfg_attr( feature = "std", derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout) )] #[derive(Debug)] pub struct DAOInstance { id: u64, owner: AccountId, size: u64, name: String, logo: String, desc: String, dao_manager: DAOManager, dao_manager_addr: AccountId, } #[ink(storage)] pub struct DaoFactory { owner: AccountId, template_addr: Option<AccountId>, template: Option<TemplateManager>, instance_index:u64, instance_map: StorageHashMap<u64, DAOInstance>, instance_map_by_owner: StorageHashMap<AccountId, Vec<u64>>, } #[ink(event)] pub struct InstanceDAO { #[ink(topic)] index: u64, #[ink(topic)] owner: Option<AccountId>, #[ink(topic)] dao_addr: AccountId, } impl DaoFactory { #[ink(constructor)] pub fn new() -> Self { Self { owner: Self::env().caller(), template_addr: None, template: None, instance_index:0, instance_map: StorageHashMap::new(), instance_map_by_owner: StorageHashMap::new(), } } #[ink(message)] pub fn init_factory (&mut self, template_code_hash: Hash, version:u128) -> bool { let salt = version.to_le_bytes(); let instance_params = TemplateManager::new(self.owner) .endowment(TEMPLATE_INIT_BALANCE) .code_hash(template_code_hash) .salt_bytes(&salt) .params(); let init_result = ink_env::instantiate_contract(&instance_params); let contract_addr = init_result.expect("failed at instantiating the `TemplateManager` contract"); let contract_instance = ink_env::call::FromAccountId::from_account_id(contract_addr); self.template = Some(contract_instance); self.template_addr = Some(contract_addr); true } #[ink(message)] pub fn init_dao_by_template( &mut self, dao_manager_code_hash:Hash, controller: AccountId, controller_type:u32, category:String ) -> bool { assert_eq!(self.instance_index + 1 > self.instance_index, true); let salt = self.instance_index.to_le_bytes(); let dao_instance_params = DAOManager::new(self.env().caller(),controller, self.instance_index,controller_type,category) .endowment(DAO_INIT_BALANCE) .code_hash(dao_manager_code_hash) .salt_bytes(salt) .params(); let dao_init_result = ink_env::instantiate_contract(&dao_instance_params); let dao_addr = dao_init_result.expect("failed at instantiating the `DAO Instance` contract"); let dao_instance: DAOManager = ink_env::call::FromAccountId::from_account_id(dao_addr); self.env().emit_event(InstanceDAO { index: self.instance_index, owner: Some(controller), dao_addr: dao_addr, }); let id_list = self.instance_map_by_owner.entry(controller.clone()).or_insert(Vec::new()); id_list.push(self.instance_index); self.instance_map.insert(self.instance_index, DAOInstance { id: self.instance_index, owner: controller, size: 0, name: String::from(""), logo: String::from(""), desc: String::from(""), dao_manager: dao_instance, dao_manager_addr: dao_addr, }); self.instance_index += 1; true } #[ink(message)] pub fn query_template_by_index(&self, index: u64) -> DAOTemplate { self.template.as_ref().unwrap().query_template_by_index(index) } #[ink(message)] pub fn get_dao_by_index(&self,id:u64) -> DAOInstance { self.instance_map.get(&id).unwrap().clone() } #[ink(message)] pub fn get_daos_by_owner(&self) -> Vec<u64> { let user = self.env().caller(); let list = self.instance_map_by_owner.get(&user).unwrap().clone(); list } #[ink(message)] pub fn list_dao(&self) -> Vec<DAOInstance> { let mut dao_vec = Vec::new(); let mut iter = self.instance_map.values(); let mut dao = iter.next(); while dao.is_some() { dao_vec.push(dao.unwrap().clone()); dao = iter.next(); } dao_vec } #[ink(message)] pub fn joined_dao(&mut self,index:u64) -> bool { let user = self.env().caller(); let id_list = self.instance_map_by_owner.entry(user.clone()).or_insert(Vec::new()); id_list.push(index); true } } #[cfg(test)] mod tests { use super::*; use ink_lang as ink; #[ink::test] fn it_works() { let mut dao_factory = DaoFactory::new(); assert!(dao_factory.joined_dao(0) == true); } #[ink::test] fn test_dao_length() { let dao_factory = DaoFactory::new(); let list = dao_factory.list_dao(); assert!(list.len() == 0); } } }
#![cfg_attr(not(feature = "std"), no_std)] #![feature(const_fn_trait_bound)] extern crate alloc; use ink_lang as ink; #[allow(unused_imports)] #[ink::contract] mod dao_factory { use alloc::string::String; use ink_prelude::vec::Vec; use ink_prelude::collections::BTreeMap; use ink_storage::{ traits::{ PackedLayout, SpreadLayout, }, collections::HashMap as StorageHashMap, }; use template_manager::TemplateManager; use template_manager::DAOTemplate; use dao_manager::DAOManager; const TEMPLATE_INIT_BALANCE: u128 = 1000 * 1_000_000_000_000; const DAO_INIT_BALANCE: u128 = 1000 * 1_000_000_000_000; #[derive(scale::Encode, scale::Decode, Clone, SpreadLayout, PackedLayout)] #[cfg_attr( feature = "std", derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout) )] #[d
shMap::new(), instance_map_by_owner: StorageHashMap::new(), } } #[ink(message)] pub fn init_factory (&mut self, template_code_hash: Hash, version:u128) -> bool { let salt = version.to_le_bytes(); let instance_params = TemplateManager::new(self.owner) .endowment(TEMPLATE_INIT_BALANCE) .code_hash(template_code_hash) .salt_bytes(&salt) .params(); let init_result = ink_env::instantiate_contract(&instance_params); let contract_addr = init_result.expect("failed at instantiating the `TemplateManager` contract"); let contract_instance = ink_env::call::FromAccountId::from_account_id(contract_addr); self.template = Some(contract_instance); self.template_addr = Some(contract_addr); true } #[ink(message)] pub fn init_dao_by_template( &mut self, dao_manager_code_hash:Hash, controller: AccountId, controller_type:u32, category:String ) -> bool { assert_eq!(self.instance_index + 1 > self.instance_index, true); let salt = self.instance_index.to_le_bytes(); let dao_instance_params = DAOManager::new(self.env().caller(),controller, self.instance_index,controller_type,category) .endowment(DAO_INIT_BALANCE) .code_hash(dao_manager_code_hash) .salt_bytes(salt) .params(); let dao_init_result = ink_env::instantiate_contract(&dao_instance_params); let dao_addr = dao_init_result.expect("failed at instantiating the `DAO Instance` contract"); let dao_instance: DAOManager = ink_env::call::FromAccountId::from_account_id(dao_addr); self.env().emit_event(InstanceDAO { index: self.instance_index, owner: Some(controller), dao_addr: dao_addr, }); let id_list = self.instance_map_by_owner.entry(controller.clone()).or_insert(Vec::new()); id_list.push(self.instance_index); self.instance_map.insert(self.instance_index, DAOInstance { id: self.instance_index, owner: controller, size: 0, name: String::from(""), logo: String::from(""), desc: String::from(""), dao_manager: dao_instance, dao_manager_addr: dao_addr, }); self.instance_index += 1; true } #[ink(message)] pub fn query_template_by_index(&self, index: u64) -> DAOTemplate { self.template.as_ref().unwrap().query_template_by_index(index) } #[ink(message)] pub fn get_dao_by_index(&self,id:u64) -> DAOInstance { self.instance_map.get(&id).unwrap().clone() } #[ink(message)] pub fn get_daos_by_owner(&self) -> Vec<u64> { let user = self.env().caller(); let list = self.instance_map_by_owner.get(&user).unwrap().clone(); list } #[ink(message)] pub fn list_dao(&self) -> Vec<DAOInstance> { let mut dao_vec = Vec::new(); let mut iter = self.instance_map.values(); let mut dao = iter.next(); while dao.is_some() { dao_vec.push(dao.unwrap().clone()); dao = iter.next(); } dao_vec } #[ink(message)] pub fn joined_dao(&mut self,index:u64) -> bool { let user = self.env().caller(); let id_list = self.instance_map_by_owner.entry(user.clone()).or_insert(Vec::new()); id_list.push(index); true } } #[cfg(test)] mod tests { use super::*; use ink_lang as ink; #[ink::test] fn it_works() { let mut dao_factory = DaoFactory::new(); assert!(dao_factory.joined_dao(0) == true); } #[ink::test] fn test_dao_length() { let dao_factory = DaoFactory::new(); let list = dao_factory.list_dao(); assert!(list.len() == 0); } } }
erive(Debug)] pub struct DAOInstance { id: u64, owner: AccountId, size: u64, name: String, logo: String, desc: String, dao_manager: DAOManager, dao_manager_addr: AccountId, } #[ink(storage)] pub struct DaoFactory { owner: AccountId, template_addr: Option<AccountId>, template: Option<TemplateManager>, instance_index:u64, instance_map: StorageHashMap<u64, DAOInstance>, instance_map_by_owner: StorageHashMap<AccountId, Vec<u64>>, } #[ink(event)] pub struct InstanceDAO { #[ink(topic)] index: u64, #[ink(topic)] owner: Option<AccountId>, #[ink(topic)] dao_addr: AccountId, } impl DaoFactory { #[ink(constructor)] pub fn new() -> Self { Self { owner: Self::env().caller(), template_addr: None, template: None, instance_index:0, instance_map: StorageHa
random
[ { "content": "/// Returns a new dynamic storage allocation.\n\npub fn alloc() -> DynamicAllocation {\n\n init::on_instance(DynamicAllocator::alloc)\n\n}\n\n\n", "file_path": "ink/crates/storage/src/alloc/mod.rs", "rank": 0, "score": 228000.94545688984 }, { "content": "/// Implemented by t...
Rust
src/wallet/state/log.rs
SebastienGllmt/cardano-cli
2470fe2dcb036226ade6f8c80a56d0610a623767
use storage_units::{append, utils::{serialize, lock::{self, Lock}}}; use std::{path::{PathBuf}, fmt, result, io::{self, Read, Write}, error}; use cardano::{block::{BlockDate, HeaderHash, types::EpochSlotId}}; use super::{ptr::{StatePtr}, utxo::{UTxO}}; use serde; use serde_yaml; #[derive(Debug)] pub enum Error { LogNotFound, IoError(io::Error), LogFormatError(String), LockError(lock::Error), AppendError(append::Error), UnsupportedLogFormat(Vec<u8>) } impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Error::IoError(e) } } impl From<lock::Error> for Error { fn from(e: lock::Error) -> Self { Error::LockError(e) } } impl From<append::Error> for Error { fn from(e: append::Error) -> Self { match e { append::Error::NotFound => Error::LogNotFound, _ => Error::AppendError(e) } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::LogNotFound => write!(f, "Log file not found"), Error::IoError(_) => write!(f, "I/O Error"), Error::LogFormatError(err) => write!(f, "Log format error: `{}`", err), Error::LockError(_) => write!(f, "Log's Lock file error"), Error::AppendError(_) => write!(f, "Error when appending data to the log file"), Error::UnsupportedLogFormat(_) => { write!(f, "Unsupported Log format (tried to deserialize log of unknown encoding or log is corrupted)") } } } } impl error::Error for Error { fn cause(&self) -> Option<& error::Error> { match self { Error::LogNotFound => None, Error::IoError(ref err) => Some(err), Error::LogFormatError(_) => None, Error::LockError(ref err) => Some(err), Error::AppendError(ref err) => Some(err), Error::UnsupportedLogFormat(_) => None, } } } pub type Result<T> = result::Result<T, Error>; const MAGIC : &'static [u8] = b"EVT1"; #[derive(Debug, Serialize, Deserialize)] pub enum Log<A> { Checkpoint(StatePtr), ReceivedFund(StatePtr, UTxO<A>), SpentFund(StatePtr, UTxO<A>) } impl<A: serde::Serialize> Log<A> { fn serialise(&self) -> Result<Vec<u8>> { let mut writer = Vec::with_capacity(64); let ptr = self.ptr(); let date = ptr.latest_block_date(); writer.write_all(b"EVT1")?; writer.write_all(ptr.latest_known_hash.as_ref())?; match date { BlockDate::Genesis(i) => { serialize::utils::write_u64(&mut writer, i as u64)?; serialize::utils::write_u64(&mut writer, u64::max_value())?; }, BlockDate::Normal(i) => { serialize::utils::write_u64(&mut writer, i.epoch as u64)?; serialize::utils::write_u64(&mut writer, i.slotid as u64)?; }, } match self { Log::Checkpoint(_) => { serialize::utils::write_u32(&mut writer, 1)?; serialize::utils::write_u64(&mut writer, 0)?; }, Log::ReceivedFund(_, utxo) => { serialize::utils::write_u32(&mut writer, 2)?; serialize::utils::write_u64(&mut writer, 0)?; serde_yaml::to_writer(&mut writer, utxo).map_err(|e| { Error::LogFormatError(format!("log format error: {:?}", e)) })?; }, Log::SpentFund(_, utxo) => { serialize::utils::write_u32(&mut writer, 3)?; serialize::utils::write_u64(&mut writer, 0)?; serde_yaml::to_writer(&mut writer, utxo).map_err(|e| { Error::LogFormatError(format!("log format error: {:?}", e)) })?; }, } Ok(writer) } } impl<A> Log<A> where for<'de> A: serde::Deserialize<'de> { fn deserisalise(bytes: &[u8]) -> Result<Self> { let mut reader = bytes; { let mut magic = [0u8; 4]; reader.read_exact(&mut magic)?; if magic != MAGIC { return Err(Error::UnsupportedLogFormat(magic.iter().cloned().collect())); } } let ptr = { let mut hash = [0;32]; reader.read_exact(&mut hash)?; let gen = serialize::utils::read_u64(&mut reader)?; let slot = serialize::utils::read_u64(&mut reader)?; let hh = HeaderHash::from(hash); let bd = if slot == 0xFFFFFFFFFFFFFFFF { BlockDate::Genesis(gen as u64) } else { BlockDate::Normal(EpochSlotId { epoch: gen as u64, slotid: slot as u16 }) }; StatePtr::new(bd, hh) }; let t = { let t = serialize::utils::read_u32(&mut reader)?; let b = serialize::utils::read_u64(&mut reader)?; debug_assert!(b == 0u64); t }; match t { 1 => Ok(Log::Checkpoint(ptr)), 2 => { let utxo = serde_yaml::from_slice(reader).map_err(|e| Error::LogFormatError(format!("log format error: {:?}", e)) )?; Ok(Log::ReceivedFund(ptr, utxo)) }, 3 => { let utxo = serde_yaml::from_slice(reader).map_err(|e| Error::LogFormatError(format!("log format error: {:?}", e)) )?; Ok(Log::SpentFund(ptr, utxo)) }, _ => { panic!("cannot parse log event of type: `{}'", t) } } } } impl<A> Log<A> { pub fn ptr<'a>(&'a self) -> &'a StatePtr { match self { Log::Checkpoint(ptr) => ptr, Log::ReceivedFund(ptr, _) => ptr, Log::SpentFund(ptr, _) => ptr, } } pub fn map<F, U>(self, f: F) -> Log<U> where F: FnOnce(A) -> U { match self { Log::Checkpoint(ptr) => Log::Checkpoint(ptr), Log::ReceivedFund(ptr, utxo) => Log::ReceivedFund(ptr, utxo.map(f)), Log::SpentFund(ptr, utxo) => Log::SpentFund(ptr, utxo.map(f)), } } } impl<A: fmt::Display> fmt::Display for Log<A> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Log::Checkpoint(ptr) => write!(f, "Checkpoint at: {}", ptr), Log::ReceivedFund(ptr, utxo) => write!(f, "Received funds at: {} {}", ptr, utxo), Log::SpentFund(ptr, utxo) => write!(f, "Spent funds at: {} {}", ptr, utxo), } } } const WALLET_LOG_FILE : &'static str = "LOG"; pub struct LogLock(lock::Lock); impl LogLock { pub fn acquire_wallet_log_lock(wallet_path: PathBuf) -> Result<Self> { Ok(LogLock(Lock::lock(wallet_path.join(WALLET_LOG_FILE))?)) } pub fn delete_wallet_log_lock(self, wallet_path: PathBuf) -> ::std::io::Result<()> { let file = wallet_path.join(WALLET_LOG_FILE); ::std::fs::remove_file(file) } } pub struct LogReader(append::Reader); impl LogReader { pub fn open(locked: LogLock) -> Result<Self> { Ok(LogReader(append::Reader::open(locked.0)?)) } pub fn release_lock(self) -> LogLock { LogLock(self.0.close()) } pub fn into_iter<A>(self) -> LogIterator<A> where for<'de> A: serde::Deserialize<'de> { LogIterator {reader: self, _log_type: ::std::marker::PhantomData } } pub fn next<A>(&mut self) -> Result<Option<Log<A>>> where for<'de> A: serde::Deserialize<'de> { match self.0.next()? { None => Ok(None), Some(bytes) => { let log = Log::deserisalise(&bytes)?; Ok(Some(log)) } } } } pub struct LogIterator<A> { reader: LogReader, _log_type: ::std::marker::PhantomData<A> } impl<A> Iterator for LogIterator<A> where for<'de> A: serde::Deserialize<'de> { type Item = Result<Log<A>>; fn next(&mut self) -> Option<Self::Item> { match self.reader.next() { Err(err) => Some(Err(err)), Ok(None) => None, Ok(Some(log)) => Some(Ok(log)) } } } pub struct LogWriter(append::Writer); impl LogWriter { pub fn open(locked: LogLock) -> Result<Self> { Ok(LogWriter(append::Writer::open(locked.0)?)) } pub fn release_lock(self) -> LogLock { LogLock(self.0.close()) } pub fn append<A: serde::Serialize+fmt::Debug>(&mut self, log: &Log<A>) -> Result<()> { Ok(self.0.append_bytes(&log.serialise()?)?) } }
use storage_units::{append, utils::{serialize, lock::{self, Lock}}}; use std::{path::{PathBuf}, fmt, result, io::{self, Read, Write}, error}; use cardano::{block::{BlockDate, HeaderHash, types::EpochSlotId}}; use super::{ptr::{StatePtr}, utxo::{UTxO}}; use serde; use serde_yaml; #[derive(Debug)] pub enum Error { LogNotFound, IoError(io::Error), LogFormatError(String), LockError(lock::Error), AppendError(append::Error), UnsupportedLogFormat(Vec<u8>) } impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Error::IoError(e) } } impl From<lock::Error> for Error { fn from(e: lock::Error) -> Self { Error::LockError(e) } } impl From<append::Error> for Error { fn from(e: append::Error) -> Self { match e { append::Error::NotFound => Error::LogNotFound, _ => Error::AppendError(e) } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::LogNotFound => write!(f, "Log file not found"), Error::IoError(_) => write!(f, "I/O Error"), Error::LogFormatError(err) => write!(f, "Log format error: `{}`", err), Error::LockError(_) => write!(f, "Log's Lock file error"), Error::AppendError(_) => write!(f, "Error when appending data to the log file"), Error::UnsupportedLogFormat(_) => { write!(f, "Unsupported Log format (tried to deserialize log of unknown encoding or log is corrupted)") } } } } impl error::Error for Error { fn cause(&self) -> Option<& error::Error> { match self { Error::LogNotFound => None, Error::IoError(ref err) => Some(err), Error::LogFormatError(_) => None, Error::LockError(ref err) => Some(err), Error::AppendError(ref err) => Some(err), Error::UnsupportedLogFormat(_) => None, } } } pub type Result<T> = result::Result<T, Error>; const MAGIC : &'static [u8] = b"EVT1"; #[derive(Debug, Serialize, Deserialize)] pub enum Log<A> { Checkpoint(StatePtr), ReceivedFund(StatePtr, UTxO<A>), SpentFund(StatePtr, UTxO<A>) } impl<A: serde::Serialize> Log<A> { fn serialise(&self) -> Result<Vec<u8>> { let mut writer = Vec::with_capacity(64); let ptr = self.ptr(); let date = ptr.latest_block_date(); writer.write_all(b"EVT1")?; writer.write_all(ptr.latest_known_hash.as_ref())?; match date { BlockDate::Genesis(i) => { serialize::utils::write_u64(&mut writer, i as u64)?; serialize::utils::write_u64(&mut writer, u64::max_value())?; }, BlockDate::Normal(i) => { serialize::utils::write_u64(&mut writer, i.epoch as u64)?; serialize::utils::write_u64(&mut writer, i.slotid as u64)?; }, } match self { Log::Checkpoint(_) => { serialize::utils::write_u32(&mut writer, 1)?; serialize::utils::write_u64(&mut writer, 0)?; }, Log::ReceivedFund(_, utxo) => { serialize::utils::write_u32(&mut writer, 2)?; serialize::utils::write_u64(&mut writer, 0)?; serde_yaml::to_writer(&mut writer, utxo).map_err(|e| {
:utils::read_u32(&mut reader)?; let b = serialize::utils::read_u64(&mut reader)?; debug_assert!(b == 0u64); t }; match t { 1 => Ok(Log::Checkpoint(ptr)), 2 => { let utxo = serde_yaml::from_slice(reader).map_err(|e| Error::LogFormatError(format!("log format error: {:?}", e)) )?; Ok(Log::ReceivedFund(ptr, utxo)) }, 3 => { let utxo = serde_yaml::from_slice(reader).map_err(|e| Error::LogFormatError(format!("log format error: {:?}", e)) )?; Ok(Log::SpentFund(ptr, utxo)) }, _ => { panic!("cannot parse log event of type: `{}'", t) } } } } impl<A> Log<A> { pub fn ptr<'a>(&'a self) -> &'a StatePtr { match self { Log::Checkpoint(ptr) => ptr, Log::ReceivedFund(ptr, _) => ptr, Log::SpentFund(ptr, _) => ptr, } } pub fn map<F, U>(self, f: F) -> Log<U> where F: FnOnce(A) -> U { match self { Log::Checkpoint(ptr) => Log::Checkpoint(ptr), Log::ReceivedFund(ptr, utxo) => Log::ReceivedFund(ptr, utxo.map(f)), Log::SpentFund(ptr, utxo) => Log::SpentFund(ptr, utxo.map(f)), } } } impl<A: fmt::Display> fmt::Display for Log<A> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Log::Checkpoint(ptr) => write!(f, "Checkpoint at: {}", ptr), Log::ReceivedFund(ptr, utxo) => write!(f, "Received funds at: {} {}", ptr, utxo), Log::SpentFund(ptr, utxo) => write!(f, "Spent funds at: {} {}", ptr, utxo), } } } const WALLET_LOG_FILE : &'static str = "LOG"; pub struct LogLock(lock::Lock); impl LogLock { pub fn acquire_wallet_log_lock(wallet_path: PathBuf) -> Result<Self> { Ok(LogLock(Lock::lock(wallet_path.join(WALLET_LOG_FILE))?)) } pub fn delete_wallet_log_lock(self, wallet_path: PathBuf) -> ::std::io::Result<()> { let file = wallet_path.join(WALLET_LOG_FILE); ::std::fs::remove_file(file) } } pub struct LogReader(append::Reader); impl LogReader { pub fn open(locked: LogLock) -> Result<Self> { Ok(LogReader(append::Reader::open(locked.0)?)) } pub fn release_lock(self) -> LogLock { LogLock(self.0.close()) } pub fn into_iter<A>(self) -> LogIterator<A> where for<'de> A: serde::Deserialize<'de> { LogIterator {reader: self, _log_type: ::std::marker::PhantomData } } pub fn next<A>(&mut self) -> Result<Option<Log<A>>> where for<'de> A: serde::Deserialize<'de> { match self.0.next()? { None => Ok(None), Some(bytes) => { let log = Log::deserisalise(&bytes)?; Ok(Some(log)) } } } } pub struct LogIterator<A> { reader: LogReader, _log_type: ::std::marker::PhantomData<A> } impl<A> Iterator for LogIterator<A> where for<'de> A: serde::Deserialize<'de> { type Item = Result<Log<A>>; fn next(&mut self) -> Option<Self::Item> { match self.reader.next() { Err(err) => Some(Err(err)), Ok(None) => None, Ok(Some(log)) => Some(Ok(log)) } } } pub struct LogWriter(append::Writer); impl LogWriter { pub fn open(locked: LogLock) -> Result<Self> { Ok(LogWriter(append::Writer::open(locked.0)?)) } pub fn release_lock(self) -> LogLock { LogLock(self.0.close()) } pub fn append<A: serde::Serialize+fmt::Debug>(&mut self, log: &Log<A>) -> Result<()> { Ok(self.0.append_bytes(&log.serialise()?)?) } }
Error::LogFormatError(format!("log format error: {:?}", e)) })?; }, Log::SpentFund(_, utxo) => { serialize::utils::write_u32(&mut writer, 3)?; serialize::utils::write_u64(&mut writer, 0)?; serde_yaml::to_writer(&mut writer, utxo).map_err(|e| { Error::LogFormatError(format!("log format error: {:?}", e)) })?; }, } Ok(writer) } } impl<A> Log<A> where for<'de> A: serde::Deserialize<'de> { fn deserisalise(bytes: &[u8]) -> Result<Self> { let mut reader = bytes; { let mut magic = [0u8; 4]; reader.read_exact(&mut magic)?; if magic != MAGIC { return Err(Error::UnsupportedLogFormat(magic.iter().cloned().collect())); } } let ptr = { let mut hash = [0;32]; reader.read_exact(&mut hash)?; let gen = serialize::utils::read_u64(&mut reader)?; let slot = serialize::utils::read_u64(&mut reader)?; let hh = HeaderHash::from(hash); let bd = if slot == 0xFFFFFFFFFFFFFFFF { BlockDate::Genesis(gen as u64) } else { BlockDate::Normal(EpochSlotId { epoch: gen as u64, slotid: slot as u16 }) }; StatePtr::new(bd, hh) }; let t = { let t = serialize:
random
[ { "content": "pub fn decrypt(password: &Password, data: &[u8]) -> Option<Vec<u8>> {\n\n let mut reader = data;\n\n let mut salt = [0;SALT_SIZE];\n\n let mut nonce = [0;NONCE_SIZE];\n\n let mut key = [0;KEY_SIZE];\n\n let len = data.len() - TAG_SIZE - SALT_SIZE - NONCE_SIZE;\n\n let mut b...
Rust
src/librustc/middle/typeck/check/writeback.rs
ehsanul/rust
7156ded5bcf6831a6da22688d08f71985fdc81df
use middle::pat_util; use middle::ty; use middle::typeck::astconv::AstConv; use middle::typeck::check::FnCtxt; use middle::typeck::infer::{force_all, resolve_all, resolve_region}; use middle::typeck::infer::resolve_type; use middle::typeck::infer; use middle::typeck::{MethodCall, MethodCallee}; use middle::typeck::{vtable_res, vtable_origin}; use middle::typeck::{vtable_static, vtable_param}; use middle::typeck::write_substs_to_tcx; use middle::typeck::write_ty_to_tcx; use util::ppaux; use util::ppaux::Repr; use std::vec_ng::Vec; use syntax::ast; use syntax::codemap::Span; use syntax::print::pprust::pat_to_str; use syntax::visit; use syntax::visit::Visitor; fn resolve_type_vars_in_type(fcx: @FnCtxt, sp: Span, typ: ty::t) -> Option<ty::t> { if !ty::type_needs_infer(typ) { return Some(typ); } match resolve_type(fcx.infcx(), typ, resolve_all | force_all) { Ok(new_type) => return Some(new_type), Err(e) => { if !fcx.ccx.tcx.sess.has_errors() { fcx.ccx.tcx.sess.span_err( sp, format!("cannot determine a type \ for this expression: {}", infer::fixup_err_to_str(e))) } return None; } } } fn resolve_type_vars_in_types(fcx: @FnCtxt, sp: Span, tys: &[ty::t]) -> Vec<ty::t> { tys.iter().map(|t| { match resolve_type_vars_in_type(fcx, sp, *t) { Some(t1) => t1, None => ty::mk_err() } }).collect() } fn resolve_method_map_entry(wbcx: &mut WbCtxt, sp: Span, method_call: MethodCall) { let fcx = wbcx.fcx; let tcx = fcx.ccx.tcx; match fcx.inh.method_map.borrow().get().find(&method_call) { Some(method) => { debug!("writeback::resolve_method_map_entry(call={:?}, entry={:?})", method_call, method.repr(tcx)); let method_ty = match resolve_type_vars_in_type(fcx, sp, method.ty) { Some(t) => t, None => { wbcx.success = false; return; } }; let mut new_tps = Vec::new(); for &subst in method.substs.tps.iter() { match resolve_type_vars_in_type(fcx, sp, subst) { Some(t) => new_tps.push(t), None => { wbcx.success = false; return; } } } let new_method = MethodCallee { origin: method.origin, ty: method_ty, substs: ty::substs { tps: new_tps, regions: ty::ErasedRegions, self_ty: None } }; fcx.ccx.method_map.borrow_mut().get().insert(method_call, new_method); } None => {} } } fn resolve_vtable_map_entry(fcx: @FnCtxt, sp: Span, id: ast::NodeId) { match fcx.inh.vtable_map.borrow().get().find_copy(&id) { Some(origins) => { let r_origins = resolve_origins(fcx, sp, origins); fcx.ccx.vtable_map.borrow_mut().get().insert(id, r_origins); debug!("writeback::resolve_vtable_map_entry(id={}, vtables={:?})", id, r_origins.repr(fcx.tcx())); } None => {} } fn resolve_origins(fcx: @FnCtxt, sp: Span, vtbls: vtable_res) -> vtable_res { @vtbls.map(|os| @os.map(|o| resolve_origin(fcx, sp, o))) } fn resolve_origin(fcx: @FnCtxt, sp: Span, origin: &vtable_origin) -> vtable_origin { match origin { &vtable_static(def_id, ref tys, origins) => { let r_tys = resolve_type_vars_in_types(fcx, sp, tys.as_slice()); let r_origins = resolve_origins(fcx, sp, origins); vtable_static(def_id, r_tys, r_origins) } &vtable_param(n, b) => { vtable_param(n, b) } } } } fn resolve_type_vars_for_node(wbcx: &mut WbCtxt, sp: Span, id: ast::NodeId) -> Option<ty::t> { let fcx = wbcx.fcx; let tcx = fcx.ccx.tcx; let adjustment = fcx.inh.adjustments.borrow().get().find_copy(&id); match adjustment { None => (), Some(adjustment) => { match *adjustment { ty::AutoAddEnv(r, s) => { match resolve_region(fcx.infcx(), r, resolve_all | force_all) { Err(e) => { tcx.sess.span_err( sp, format!("cannot resolve bound for closure: \ {}", infer::fixup_err_to_str(e))); } Ok(r1) => { match tcx.def_map.borrow().get().find(&id) { Some(&ast::DefFn(..)) | Some(&ast::DefStaticMethod(..)) | Some(&ast::DefVariant(..)) | Some(&ast::DefStruct(_)) => {} _ => tcx.sess.span_err(sp, "cannot coerce non-statically resolved bare fn") } let resolved_adj = @ty::AutoAddEnv(r1, s); debug!("Adjustments for node {}: {:?}", id, resolved_adj); tcx.adjustments.borrow_mut().get().insert(id, resolved_adj); } } } ty::AutoDerefRef(adj) => { for autoderef in range(0, adj.autoderefs) { let method_call = MethodCall::autoderef(id, autoderef as u32); resolve_method_map_entry(wbcx, sp, method_call); } let fixup_region = |r| { match resolve_region(fcx.infcx(), r, resolve_all | force_all) { Ok(r1) => r1, Err(e) => { tcx.sess.span_err( sp, format!("cannot resolve scope of borrow: \ {}", infer::fixup_err_to_str(e))); r } } }; let resolved_autoref = match adj.autoref { None => None, Some(ref r) => Some(r.map_region(fixup_region)) }; let resolved_adj = @ty::AutoDerefRef(ty::AutoDerefRef { autoderefs: adj.autoderefs, autoref: resolved_autoref, }); debug!("Adjustments for node {}: {:?}", id, resolved_adj); tcx.adjustments.borrow_mut().get().insert(id, resolved_adj); } ty::AutoObject(..) => { debug!("Adjustments for node {}: {:?}", id, adjustment); tcx.adjustments.borrow_mut().get().insert(id, adjustment); } } } } let n_ty = fcx.node_ty(id); match resolve_type_vars_in_type(fcx, sp, n_ty) { None => { wbcx.success = false; return None; } Some(t) => { debug!("resolve_type_vars_for_node(id={}, n_ty={}, t={})", id, ppaux::ty_to_str(tcx, n_ty), ppaux::ty_to_str(tcx, t)); write_ty_to_tcx(tcx, id, t); let mut ret = Some(t); fcx.opt_node_ty_substs(id, |substs| { let mut new_tps = Vec::new(); for subst in substs.tps.iter() { match resolve_type_vars_in_type(fcx, sp, *subst) { Some(t) => new_tps.push(t), None => { wbcx.success = false; ret = None; break } } } write_substs_to_tcx(tcx, id, new_tps); ret.is_some() }); ret } } } struct WbCtxt { fcx: @FnCtxt, success: bool, } fn visit_stmt(s: &ast::Stmt, wbcx: &mut WbCtxt) { if !wbcx.success { return; } resolve_type_vars_for_node(wbcx, s.span, ty::stmt_node_id(s)); visit::walk_stmt(wbcx, s, ()); } fn visit_expr(e: &ast::Expr, wbcx: &mut WbCtxt) { if !wbcx.success { return; } resolve_type_vars_for_node(wbcx, e.span, e.id); resolve_method_map_entry(wbcx, e.span, MethodCall::expr(e.id)); resolve_vtable_map_entry(wbcx.fcx, e.span, e.id); match e.node { ast::ExprFnBlock(ref decl, _) | ast::ExprProc(ref decl, _) => { for input in decl.inputs.iter() { let _ = resolve_type_vars_for_node(wbcx, e.span, input.id); } } _ => {} } visit::walk_expr(wbcx, e, ()); } fn visit_block(b: &ast::Block, wbcx: &mut WbCtxt) { if !wbcx.success { return; } resolve_type_vars_for_node(wbcx, b.span, b.id); visit::walk_block(wbcx, b, ()); } fn visit_pat(p: &ast::Pat, wbcx: &mut WbCtxt) { if !wbcx.success { return; } resolve_type_vars_for_node(wbcx, p.span, p.id); debug!("Type for pattern binding {} (id {}) resolved to {}", pat_to_str(p), p.id, wbcx.fcx.infcx().ty_to_str( ty::node_id_to_type(wbcx.fcx.ccx.tcx, p.id))); visit::walk_pat(wbcx, p, ()); } fn visit_local(l: &ast::Local, wbcx: &mut WbCtxt) { if !wbcx.success { return; } let var_ty = wbcx.fcx.local_ty(l.span, l.id); match resolve_type(wbcx.fcx.infcx(), var_ty, resolve_all | force_all) { Ok(lty) => { debug!("Type for local {} (id {}) resolved to {}", pat_to_str(l.pat), l.id, wbcx.fcx.infcx().ty_to_str(lty)); write_ty_to_tcx(wbcx.fcx.ccx.tcx, l.id, lty); } Err(e) => { wbcx.fcx.ccx.tcx.sess.span_err( l.span, format!("cannot determine a type \ for this local variable: {}", infer::fixup_err_to_str(e))); wbcx.success = false; } } visit::walk_local(wbcx, l, ()); } fn visit_item(_item: &ast::Item, _wbcx: &mut WbCtxt) { } impl Visitor<()> for WbCtxt { fn visit_item(&mut self, i: &ast::Item, _: ()) { visit_item(i, self); } fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) { visit_stmt(s, self); } fn visit_expr(&mut self, ex:&ast::Expr, _: ()) { visit_expr(ex, self); } fn visit_block(&mut self, b: &ast::Block, _: ()) { visit_block(b, self); } fn visit_pat(&mut self, p: &ast::Pat, _: ()) { visit_pat(p, self); } fn visit_local(&mut self, l: &ast::Local, _: ()) { visit_local(l, self); } fn visit_ty(&mut self, _t: &ast::Ty, _: ()) {} } fn resolve_upvar_borrow_map(wbcx: &mut WbCtxt) { if !wbcx.success { return; } let fcx = wbcx.fcx; let tcx = fcx.tcx(); let upvar_borrow_map = fcx.inh.upvar_borrow_map.borrow(); for (upvar_id, upvar_borrow) in upvar_borrow_map.get().iter() { let r = upvar_borrow.region; match resolve_region(fcx.infcx(), r, resolve_all | force_all) { Ok(r) => { let new_upvar_borrow = ty::UpvarBorrow { kind: upvar_borrow.kind, region: r }; debug!("Upvar borrow for {} resolved to {}", upvar_id.repr(tcx), new_upvar_borrow.repr(tcx)); let mut tcx_upvar_borrow_map = tcx.upvar_borrow_map.borrow_mut(); tcx_upvar_borrow_map.get().insert(*upvar_id, new_upvar_borrow); } Err(e) => { let span = ty::expr_span(tcx, upvar_id.closure_expr_id); fcx.ccx.tcx.sess.span_err( span, format!("cannot resolve lifetime for \ captured variable `{}`: {}", ty::local_var_name_str(tcx, upvar_id.var_id).get().to_str(), infer::fixup_err_to_str(e))); wbcx.success = false; } }; } } pub fn resolve_type_vars_in_expr(fcx: @FnCtxt, e: &ast::Expr) -> bool { let mut wbcx = WbCtxt { fcx: fcx, success: true }; let wbcx = &mut wbcx; wbcx.visit_expr(e, ()); resolve_upvar_borrow_map(wbcx); return wbcx.success; } pub fn resolve_type_vars_in_fn(fcx: @FnCtxt, decl: &ast::FnDecl, blk: &ast::Block) -> bool { let mut wbcx = WbCtxt { fcx: fcx, success: true }; let wbcx = &mut wbcx; wbcx.visit_block(blk, ()); for arg in decl.inputs.iter() { wbcx.visit_pat(arg.pat, ()); if !pat_util::pat_is_binding(fcx.tcx().def_map, arg.pat) { resolve_type_vars_for_node(wbcx, arg.pat.span, arg.pat.id); } } resolve_upvar_borrow_map(wbcx); return wbcx.success; }
use middle::pat_util; use middle::ty; use middle::typeck::astconv::AstConv; use middle::typeck::check::FnCtxt; use middle::typeck::infer::{force_all, resolve_all, resolve_region}; use middle::typeck::infer::resolve_type; use middle::typeck::infer; use middle::typeck::{MethodCall, MethodCallee}; use middle::typeck::{vtable_res, vtable_origin}; use middle::typeck::{vtable_static, vtable_param}; use middle::typeck::write_substs_to_tcx; use middle::typeck::write_ty_to_tcx; use util::ppaux; use util::ppaux::Repr; use std::vec_ng::Vec; use syntax::ast; use syntax::codemap::Span; use syntax::print::pprust::pat_to_str; use syntax::visit; use syntax::visit::Visitor; fn resolve_type_vars_in_type(fcx: @FnCtxt, sp: Span, typ: ty::t) -> Option<ty::t> { if !ty::type_needs_infer(typ) { return Some(typ); } match resolve_type(fcx.infcx(), typ, resolve_all | force_all) { Ok(new_type) => return Some(new_type), Err(e) => { if !fcx.ccx.tcx.sess.has_errors() { fcx.ccx.tcx.sess.span_err( sp, format!("cannot determine a type \ for this expression: {}", infer::fixup_err_to_str(e))) } return None; } } } fn resolve_type_vars_in_types(fcx: @FnCtxt, sp: Span, tys: &[ty::t]) -> Vec<ty::t> { tys.iter().map(|t| { match resolve_type_vars_in_type(fcx, sp, *t) { Some(t1) => t1, None => ty::mk_err() } }).collect() } fn resolve_method_map_entry(wbcx: &mut WbCtxt, sp: Span, method_call: MethodCall) { let fcx = wbcx.fcx; let tcx = fcx.ccx.tcx; match fcx.inh.method_map.borrow().get().find(&method_call) { Some(method) => { debug!("writeback::resolve_method_map_entry(call={:?}, entry={:?})", method_call, method.repr(tcx)); let method_ty = match resolve_type_vars_in_type(fcx, sp, method.ty) { Some(t) => t, None => { wbcx.success = false; return; } }; let mut new_tps = Vec::new(); for &subst in method.substs.tps.iter() { match resolve_type_vars_in_type(fcx, sp, subst) { Some(t) => new_tps.push(t), None => { wbcx.success = false; return; } } } let new_method = MethodCallee { origin: method.origin, ty: method_ty, substs: ty::substs { tps: new_tps, regions: ty::ErasedRegions, self_ty: None } }; fcx.ccx.method_map.borrow_mut().get().insert(method_call, new_method); } None => {} } } fn resolve_vtable_map_entry(fcx: @FnCtxt, sp: Span, id: ast::NodeId) { match fcx.inh.vtable_map.borrow().get().find_copy(&id) { Some(origins) => { let r_origins = resolve_origins(fcx, sp, origins); fcx.ccx.vtable_map.borrow_mut().get().insert(id, r_origins); debug!("writeback::resolve_vtable_map_entry(id={}, vtables={:?})", id, r_origins.repr(fcx.tcx())); } None => {} } fn resolve_origins(fcx: @FnCtxt, sp: Span, vtbls: vtable_res) -> vtable_res { @vtbls.map(|os| @os.map(|o| resolve_origin(fcx, sp, o))) } fn resolve_origin(fcx: @FnCtxt, sp: Span, origin: &vtable_origin) -> vtable_origin { match origin { &vtable_static(def_id, ref tys, origins) => { let r_tys = resolve_type_vars_in_types(fcx, sp, tys.as_slice()); let r_origins = resolve_origins(fcx, sp, origins); vtable_static(def_id, r_tys, r_origins) } &vtable_param(n, b) => { vtable_param(n, b) } } } } fn resolve_type_vars_for_node(wbcx: &mut WbCtxt, sp: Span, id: ast::NodeId) -> Option<ty::t> { let fcx = wbcx.fcx; let tcx = fcx.ccx.tcx; let adjustment = fcx.inh.adjustments.borrow().get().find_copy(&id); match adjustment { None => (), Some(adjustment) => { match *adjustment { ty::AutoAddEnv(r, s) => { match
{ Err(e) => { tcx.sess.span_err( sp, format!("cannot resolve bound for closure: \ {}", infer::fixup_err_to_str(e))); } Ok(r1) => { match tcx.def_map.borrow().get().find(&id) { Some(&ast::DefFn(..)) | Some(&ast::DefStaticMethod(..)) | Some(&ast::DefVariant(..)) | Some(&ast::DefStruct(_)) => {} _ => tcx.sess.span_err(sp, "cannot coerce non-statically resolved bare fn") } let resolved_adj = @ty::AutoAddEnv(r1, s); debug!("Adjustments for node {}: {:?}", id, resolved_adj); tcx.adjustments.borrow_mut().get().insert(id, resolved_adj); } } } ty::AutoDerefRef(adj) => { for autoderef in range(0, adj.autoderefs) { let method_call = MethodCall::autoderef(id, autoderef as u32); resolve_method_map_entry(wbcx, sp, method_call); } let fixup_region = |r| { match resolve_region(fcx.infcx(), r, resolve_all | force_all) { Ok(r1) => r1, Err(e) => { tcx.sess.span_err( sp, format!("cannot resolve scope of borrow: \ {}", infer::fixup_err_to_str(e))); r } } }; let resolved_autoref = match adj.autoref { None => None, Some(ref r) => Some(r.map_region(fixup_region)) }; let resolved_adj = @ty::AutoDerefRef(ty::AutoDerefRef { autoderefs: adj.autoderefs, autoref: resolved_autoref, }); debug!("Adjustments for node {}: {:?}", id, resolved_adj); tcx.adjustments.borrow_mut().get().insert(id, resolved_adj); } ty::AutoObject(..) => { debug!("Adjustments for node {}: {:?}", id, adjustment); tcx.adjustments.borrow_mut().get().insert(id, adjustment); } } } } let n_ty = fcx.node_ty(id); match resolve_type_vars_in_type(fcx, sp, n_ty) { None => { wbcx.success = false; return None; } Some(t) => { debug!("resolve_type_vars_for_node(id={}, n_ty={}, t={})", id, ppaux::ty_to_str(tcx, n_ty), ppaux::ty_to_str(tcx, t)); write_ty_to_tcx(tcx, id, t); let mut ret = Some(t); fcx.opt_node_ty_substs(id, |substs| { let mut new_tps = Vec::new(); for subst in substs.tps.iter() { match resolve_type_vars_in_type(fcx, sp, *subst) { Some(t) => new_tps.push(t), None => { wbcx.success = false; ret = None; break } } } write_substs_to_tcx(tcx, id, new_tps); ret.is_some() }); ret } } } struct WbCtxt { fcx: @FnCtxt, success: bool, } fn visit_stmt(s: &ast::Stmt, wbcx: &mut WbCtxt) { if !wbcx.success { return; } resolve_type_vars_for_node(wbcx, s.span, ty::stmt_node_id(s)); visit::walk_stmt(wbcx, s, ()); } fn visit_expr(e: &ast::Expr, wbcx: &mut WbCtxt) { if !wbcx.success { return; } resolve_type_vars_for_node(wbcx, e.span, e.id); resolve_method_map_entry(wbcx, e.span, MethodCall::expr(e.id)); resolve_vtable_map_entry(wbcx.fcx, e.span, e.id); match e.node { ast::ExprFnBlock(ref decl, _) | ast::ExprProc(ref decl, _) => { for input in decl.inputs.iter() { let _ = resolve_type_vars_for_node(wbcx, e.span, input.id); } } _ => {} } visit::walk_expr(wbcx, e, ()); } fn visit_block(b: &ast::Block, wbcx: &mut WbCtxt) { if !wbcx.success { return; } resolve_type_vars_for_node(wbcx, b.span, b.id); visit::walk_block(wbcx, b, ()); } fn visit_pat(p: &ast::Pat, wbcx: &mut WbCtxt) { if !wbcx.success { return; } resolve_type_vars_for_node(wbcx, p.span, p.id); debug!("Type for pattern binding {} (id {}) resolved to {}", pat_to_str(p), p.id, wbcx.fcx.infcx().ty_to_str( ty::node_id_to_type(wbcx.fcx.ccx.tcx, p.id))); visit::walk_pat(wbcx, p, ()); } fn visit_local(l: &ast::Local, wbcx: &mut WbCtxt) { if !wbcx.success { return; } let var_ty = wbcx.fcx.local_ty(l.span, l.id); match resolve_type(wbcx.fcx.infcx(), var_ty, resolve_all | force_all) { Ok(lty) => { debug!("Type for local {} (id {}) resolved to {}", pat_to_str(l.pat), l.id, wbcx.fcx.infcx().ty_to_str(lty)); write_ty_to_tcx(wbcx.fcx.ccx.tcx, l.id, lty); } Err(e) => { wbcx.fcx.ccx.tcx.sess.span_err( l.span, format!("cannot determine a type \ for this local variable: {}", infer::fixup_err_to_str(e))); wbcx.success = false; } } visit::walk_local(wbcx, l, ()); } fn visit_item(_item: &ast::Item, _wbcx: &mut WbCtxt) { } impl Visitor<()> for WbCtxt { fn visit_item(&mut self, i: &ast::Item, _: ()) { visit_item(i, self); } fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) { visit_stmt(s, self); } fn visit_expr(&mut self, ex:&ast::Expr, _: ()) { visit_expr(ex, self); } fn visit_block(&mut self, b: &ast::Block, _: ()) { visit_block(b, self); } fn visit_pat(&mut self, p: &ast::Pat, _: ()) { visit_pat(p, self); } fn visit_local(&mut self, l: &ast::Local, _: ()) { visit_local(l, self); } fn visit_ty(&mut self, _t: &ast::Ty, _: ()) {} } fn resolve_upvar_borrow_map(wbcx: &mut WbCtxt) { if !wbcx.success { return; } let fcx = wbcx.fcx; let tcx = fcx.tcx(); let upvar_borrow_map = fcx.inh.upvar_borrow_map.borrow(); for (upvar_id, upvar_borrow) in upvar_borrow_map.get().iter() { let r = upvar_borrow.region; match resolve_region(fcx.infcx(), r, resolve_all | force_all) { Ok(r) => { let new_upvar_borrow = ty::UpvarBorrow { kind: upvar_borrow.kind, region: r }; debug!("Upvar borrow for {} resolved to {}", upvar_id.repr(tcx), new_upvar_borrow.repr(tcx)); let mut tcx_upvar_borrow_map = tcx.upvar_borrow_map.borrow_mut(); tcx_upvar_borrow_map.get().insert(*upvar_id, new_upvar_borrow); } Err(e) => { let span = ty::expr_span(tcx, upvar_id.closure_expr_id); fcx.ccx.tcx.sess.span_err( span, format!("cannot resolve lifetime for \ captured variable `{}`: {}", ty::local_var_name_str(tcx, upvar_id.var_id).get().to_str(), infer::fixup_err_to_str(e))); wbcx.success = false; } }; } } pub fn resolve_type_vars_in_expr(fcx: @FnCtxt, e: &ast::Expr) -> bool { let mut wbcx = WbCtxt { fcx: fcx, success: true }; let wbcx = &mut wbcx; wbcx.visit_expr(e, ()); resolve_upvar_borrow_map(wbcx); return wbcx.success; } pub fn resolve_type_vars_in_fn(fcx: @FnCtxt, decl: &ast::FnDecl, blk: &ast::Block) -> bool { let mut wbcx = WbCtxt { fcx: fcx, success: true }; let wbcx = &mut wbcx; wbcx.visit_block(blk, ()); for arg in decl.inputs.iter() { wbcx.visit_pat(arg.pat, ()); if !pat_util::pat_is_binding(fcx.tcx().def_map, arg.pat) { resolve_type_vars_for_node(wbcx, arg.pat.span, arg.pat.id); } } resolve_upvar_borrow_map(wbcx); return wbcx.success; }
resolve_region(fcx.infcx(), r, resolve_all | force_all)
call_expression
[ { "content": "pub fn type_is_region_ptr(fcx: @FnCtxt, sp: Span, typ: ty::t) -> bool {\n\n let typ_s = structurally_resolved_type(fcx, sp, typ);\n\n return ty::type_is_region_ptr(typ_s);\n\n}\n\n\n", "file_path": "src/librustc/middle/typeck/check/mod.rs", "rank": 0, "score": 681692.0685702388 ...
Rust
src/unixuser.rs
giganteous/webdav-server-rs
3fa3e9f63f9894d4658c9c1923f416f60acf8712
use std; use std::ffi::{CStr, OsStr}; use std::io; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use tokio::task::block_in_place; #[derive(Debug)] pub struct User { pub name: String, pub passwd: String, pub gecos: String, pub uid: u32, pub gid: u32, pub groups: Vec<u32>, pub dir: PathBuf, pub shell: PathBuf, } unsafe fn cptr_to_osstr<'a>(c: *const libc::c_char) -> &'a OsStr { let bytes = CStr::from_ptr(c).to_bytes(); OsStr::from_bytes(&bytes) } unsafe fn cptr_to_path<'a>(c: *const libc::c_char) -> &'a Path { Path::new(cptr_to_osstr(c)) } unsafe fn to_user(pwd: &libc::passwd) -> User { let cs_name = CStr::from_ptr(pwd.pw_name); let cs_passwd = CStr::from_ptr(pwd.pw_passwd); let cs_gecos = CStr::from_ptr(pwd.pw_gecos); let cs_dir = cptr_to_path(pwd.pw_dir); let cs_shell = cptr_to_path(pwd.pw_shell); User { name: cs_name.to_string_lossy().into_owned(), passwd: cs_passwd.to_string_lossy().into_owned(), gecos: cs_gecos.to_string_lossy().into_owned(), dir: cs_dir.to_path_buf(), shell: cs_shell.to_path_buf(), uid: pwd.pw_uid, gid: pwd.pw_gid, groups: Vec::new(), } } impl User { pub fn by_name(name: &str, with_groups: bool) -> Result<User, io::Error> { let mut buf = [0u8; 1024]; let mut pwd: libc::passwd = unsafe { std::mem::zeroed() }; let mut result: *mut libc::passwd = std::ptr::null_mut(); let cname = match std::ffi::CString::new(name) { Ok(un) => un, Err(_) => return Err(io::Error::from_raw_os_error(libc::ENOENT)), }; let ret = unsafe { libc::getpwnam_r( cname.as_ptr(), &mut pwd as *mut _, buf.as_mut_ptr() as *mut _, buf.len() as libc::size_t, &mut result as *mut _, ) }; if ret != 0 { return Err(io::Error::from_raw_os_error(ret)); } if result.is_null() { return Err(io::Error::from_raw_os_error(libc::ENOENT)); } let mut user = unsafe { to_user(&pwd) }; if with_groups { let mut ngroups = (buf.len() / std::mem::size_of::<libc::gid_t>()) as libc::c_int; let ret = unsafe { libc::getgrouplist( cname.as_ptr(), user.gid as libc::gid_t, buf.as_mut_ptr() as *mut _, &mut ngroups as *mut _, ) }; if ret >= 0 && ngroups > 0 { let mut groups_vec = Vec::with_capacity(ngroups as usize); let groups = unsafe { std::slice::from_raw_parts(buf.as_ptr() as *const libc::gid_t, ngroups as usize) }; groups_vec.extend(groups.iter().map(|&g| g as u32).filter(|&g| g != user.gid)); user.groups = groups_vec; } } Ok(user) } /* pub fn by_uid(uid: u32) -> Result<User, io::Error> { let mut buf = [0; 1024]; let mut pwd: libc::passwd = unsafe { std::mem::zeroed() }; let mut result: *mut libc::passwd = std::ptr::null_mut(); let ret = unsafe { getpwuid_r( uid, &mut pwd as *mut _, buf.as_mut_ptr(), buf.len() as libc::size_t, &mut result as *mut _, ) }; if ret == 0 { if result.is_null() { return Err(io::Error::from_raw_os_error(libc::ENOENT)); } let p = unsafe { to_user(&pwd) }; Ok(p) } else { Err(io::Error::from_raw_os_error(ret)) } } */ pub async fn by_name_async(name: &str, with_groups: bool) -> Result<User, io::Error> { block_in_place(move || User::by_name(name, with_groups)) } }
use std; use std::ffi::{CStr, OsStr}; use std::io; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use tokio::task::block_in_place; #[derive(Debug)] pub struct User { pub name: String, pub passwd: String, pub gecos: String, pub uid: u32, pub gid: u32, pub groups: Vec<u32>, pub dir: PathBuf, pub shell: PathBuf, } unsafe fn cptr_to_osstr<'a>(c: *const libc::c_char) -> &'a OsStr { let bytes = CStr::from_ptr(c).to_bytes(); OsStr::from_bytes(&bytes) } unsafe fn cptr_to_path<'a>(c: *const libc::c_char) -> &'a Path { Path::new(cptr_to_osstr(c)) } unsafe fn to_user(pwd: &libc::passwd) -> User { let cs_name = CStr::from_ptr(pwd.pw_name); let cs_passwd = CStr::from_ptr(pwd.pw_passwd); let cs_gecos = CStr::from_ptr(pwd.pw_gecos); let cs_dir = cptr_to_path(pwd.pw_dir); let cs_shell = cptr_to_path(pwd.pw_shel
impl User { pub fn by_name(name: &str, with_groups: bool) -> Result<User, io::Error> { let mut buf = [0u8; 1024]; let mut pwd: libc::passwd = unsafe { std::mem::zeroed() }; let mut result: *mut libc::passwd = std::ptr::null_mut(); let cname = match std::ffi::CString::new(name) { Ok(un) => un, Err(_) => return Err(io::Error::from_raw_os_error(libc::ENOENT)), }; let ret = unsafe { libc::getpwnam_r( cname.as_ptr(), &mut pwd as *mut _, buf.as_mut_ptr() as *mut _, buf.len() as libc::size_t, &mut result as *mut _, ) }; if ret != 0 { return Err(io::Error::from_raw_os_error(ret)); } if result.is_null() { return Err(io::Error::from_raw_os_error(libc::ENOENT)); } let mut user = unsafe { to_user(&pwd) }; if with_groups { let mut ngroups = (buf.len() / std::mem::size_of::<libc::gid_t>()) as libc::c_int; let ret = unsafe { libc::getgrouplist( cname.as_ptr(), user.gid as libc::gid_t, buf.as_mut_ptr() as *mut _, &mut ngroups as *mut _, ) }; if ret >= 0 && ngroups > 0 { let mut groups_vec = Vec::with_capacity(ngroups as usize); let groups = unsafe { std::slice::from_raw_parts(buf.as_ptr() as *const libc::gid_t, ngroups as usize) }; groups_vec.extend(groups.iter().map(|&g| g as u32).filter(|&g| g != user.gid)); user.groups = groups_vec; } } Ok(user) } /* pub fn by_uid(uid: u32) -> Result<User, io::Error> { let mut buf = [0; 1024]; let mut pwd: libc::passwd = unsafe { std::mem::zeroed() }; let mut result: *mut libc::passwd = std::ptr::null_mut(); let ret = unsafe { getpwuid_r( uid, &mut pwd as *mut _, buf.as_mut_ptr(), buf.len() as libc::size_t, &mut result as *mut _, ) }; if ret == 0 { if result.is_null() { return Err(io::Error::from_raw_os_error(libc::ENOENT)); } let p = unsafe { to_user(&pwd) }; Ok(p) } else { Err(io::Error::from_raw_os_error(ret)) } } */ pub async fn by_name_async(name: &str, with_groups: bool) -> Result<User, io::Error> { block_in_place(move || User::by_name(name, with_groups)) } }
l); User { name: cs_name.to_string_lossy().into_owned(), passwd: cs_passwd.to_string_lossy().into_owned(), gecos: cs_gecos.to_string_lossy().into_owned(), dir: cs_dir.to_path_buf(), shell: cs_shell.to_path_buf(), uid: pwd.pw_uid, gid: pwd.pw_gid, groups: Vec::new(), } }
function_block-function_prefixed
[]
Rust
tests/get_write_configurations_util/mod.rs
jakehamtexas/constance_rs
b923d35865c5d88eb7791efccf67f2b0e0b8d8e4
use std::collections::HashMap; pub mod dotnet_object_like_enum_buffer; pub mod dotnet_object_like_enum_with_description_buffer; pub mod dotnet_simple_enum_buffer; pub mod dotnet_simple_enum_with_description_buffer; pub mod dotnet_string_enum_buffer; pub mod dotnet_string_enum_with_description_buffer; pub mod rust_simple_enum_buffer; pub mod rust_simple_enum_with_description_buffer; pub mod rust_string_enum_buffer; pub mod rust_string_enum_with_description_buffer; pub mod typescript_object_like_enum_buffer; pub mod typescript_object_like_enum_with_description_buffer; pub mod typescript_simple_enum_buffer; pub mod typescript_simple_enum_with_description_buffer; pub mod typescript_string_enum_buffer; pub mod typescript_string_enum_with_description_buffer; use constance::{ testing_only::{ Column, Language, ObjectLike, SimpleEnum, StringEnum, TableConstant, TableIdentifier, ValueWithDescription, NUMBER_TYPE, STRING_TYPE, }, types::OutputOptions, }; pub fn get_table_constants_for_filename_test() -> Vec<TableConstant> { vec![TableConstant::SimpleEnum(SimpleEnum { identifier: TableIdentifier { object_name: "test_enum".to_string(), ..TableIdentifier::default() }, ..SimpleEnum::default() })] } pub fn get_table_constants_for_simple_enum_buffer_test() -> Vec<TableConstant> { let mut map = HashMap::new(); map.insert( "test1".to_string(), ValueWithDescription { value: "5".to_string(), description: None, }, ); map.insert( "test2".to_string(), ValueWithDescription { value: "7".to_string(), description: None, }, ); vec![TableConstant::SimpleEnum(SimpleEnum { identifier: TableIdentifier { object_name: "test_enum".to_string(), ..TableIdentifier::default() }, map, })] } pub fn get_table_constants_for_string_enum_buffer_test() -> Vec<TableConstant> { let mut map = HashMap::new(); map.insert( "test1".to_string(), ValueWithDescription { value: "test1".to_string(), description: None, }, ); map.insert( "test2".to_string(), ValueWithDescription { value: "test2".to_string(), description: None, }, ); vec![TableConstant::StringEnum(StringEnum { identifier: TableIdentifier { object_name: "test_enum".to_string(), ..TableIdentifier::default() }, map, })] } pub fn get_table_constants_for_simple_enum_with_description_buffer_test() -> Vec<TableConstant> { let mut map = HashMap::new(); map.insert( "test1".to_string(), ValueWithDescription { value: "5".to_string(), description: Some("description5".to_string()), }, ); map.insert( "test2".to_string(), ValueWithDescription { value: "7".to_string(), description: Some("description7".to_string()), }, ); vec![TableConstant::SimpleEnum(SimpleEnum { identifier: TableIdentifier { object_name: "test_enum".to_string(), ..TableIdentifier::default() }, map, })] } pub fn get_table_constants_for_string_enum_with_description_buffer_test() -> Vec<TableConstant> { let mut map = HashMap::new(); map.insert( "test1".to_string(), ValueWithDescription { value: "test1".to_string(), description: Some("description5".to_string()), }, ); map.insert( "test2".to_string(), ValueWithDescription { value: "test2".to_string(), description: Some("description7".to_string()), }, ); vec![TableConstant::StringEnum(StringEnum { identifier: TableIdentifier { object_name: "test_enum".to_string(), ..TableIdentifier::default() }, map, })] } pub fn get_table_constants_for_object_like_buffer_test() -> Vec<TableConstant> { let mut map = HashMap::new(); map.insert( ValueWithDescription { value: "test1".to_string(), description: None, }, vec![ ( Column { name: "first".to_string(), data_type: STRING_TYPE.to_string(), }, "first1".to_string(), ), ( Column { name: "second".to_string(), data_type: NUMBER_TYPE.to_string(), }, "1".to_string(), ), ], ); map.insert( ValueWithDescription { value: "test2".to_string(), description: None, }, vec![ ( Column { name: "first".to_string(), data_type: STRING_TYPE.to_string(), }, "first2".to_string(), ), ( Column { name: "second".to_string(), data_type: NUMBER_TYPE.to_string(), }, "2".to_string(), ), ], ); vec![TableConstant::ObjectLike(ObjectLike { identifier: TableIdentifier { object_name: "test_enum".to_string(), ..TableIdentifier::default() }, map, })] } pub fn get_table_constants_for_object_like_with_description_buffer_test() -> Vec<TableConstant> { let mut map = HashMap::new(); map.insert( ValueWithDescription { value: "test1".to_string(), description: Some("description1".to_string()), }, vec![ ( Column { name: "first".to_string(), data_type: STRING_TYPE.to_string(), }, "first1".to_string(), ), ( Column { name: "second".to_string(), data_type: NUMBER_TYPE.to_string(), }, "1".to_string(), ), ], ); map.insert( ValueWithDescription { value: "test2".to_string(), description: Some("description2".to_string()), }, vec![ ( Column { name: "first".to_string(), data_type: STRING_TYPE.to_string(), }, "first2".to_string(), ), ( Column { name: "second".to_string(), data_type: NUMBER_TYPE.to_string(), }, "2".to_string(), ), ], ); vec![TableConstant::ObjectLike(ObjectLike { identifier: TableIdentifier { object_name: "test_enum".to_string(), ..TableIdentifier::default() }, map, })] } pub fn get_output_options_for_filename_test(lang: Language) -> OutputOptions { OutputOptions { language_targets: Some(vec![lang.to_string()]), ..OutputOptions::default() } }
use std::collections::HashMap; pub mod dotnet_object_like_enum_buffer; pub mod dotnet_object_like_enum_with_description_buffer; pub mod dotnet_simple_enum_buffer; pub mod dotnet_simple_enum_with_description_buffer; pub mod dotnet_string_enum_buffer; pub mod dotnet_string_enum_with_description_buffer; pub mod rust_simple_enum_buffer; pub mod rust_simple_enum_with_description_buffer; pub mod rust_string_enum_buffer; pub mod rust_string_enum_with_description_buffer; pub mod typescript_object_like_enum_buffer; pub mod typescript_object_like_enum_with_description_buffer; pub mod typescript_simple_enum_buffer; pub mod typescript_simple_enum_with_description_buffer; pub mod typescript_string_enum_buffer; pub mod typescript_string_enum_with_description_buffer; use constance::{ testing_only::{ Column, Language, ObjectLike, SimpleEnum, StringEnum, TableConstant, TableIdentifier, ValueWithDescription, NUMBER_TYPE, STRING_TYPE, }, types::OutputOptions, }; pub fn get_table_constants_for_filename_test() -> Vec<TableConstant> { vec![TableConstant::SimpleEnum(SimpleEnum { identifier: TableIdentifier { object_name: "test_enum".to_string(), ..TableIdentifier::default() }, ..SimpleEnum::default() })] } pub fn get_table_constants_for_simple_enum_buffer_test() -> Vec<TableConstant> { let mut map = HashMap::new(); map.insert( "test1".to_string(), ValueWithDescription { value: "5".to_string(), description: None, }, ); map.insert( "test2".to_string(), ValueWithDescription { value: "7".to_string(), description: None, }, ); vec![TableConstant::SimpleEnum(SimpleEnum { identifier: TableIdentifier { object_name: "test_enum".to_string(), ..TableIdentifier::default() }, map, })] } pub fn get_table_constants_for_string_enum_buffer_test() -> Vec<TableConstant> { let mut map = HashMap::new(); map.insert( "test1".to_string(), ValueWithDescription { value: "test1".to_string(), description: None, }, ); map.insert( "test2".to_string(), ValueWithDescription { value: "test2".to_string(), description: None, }, ); vec![TableConstant::StringEnum(StringEnum { identifier: TableIdentifier { object_name: "test_enum".to_string(), ..TableIdentifier::default() }, map, })] } pub fn get_table_constants_for_simple_enum_with_description_buffer_test() -> Vec<TableConstant> { let mut map = HashMap::new(); map.insert( "test1".to_string(), ValueWithDescription { value: "5".to_string(), description: Some("description5".to_string()), }, ); map.insert( "test2".to_string(), ValueWithDescription { value: "7".to_string(), description: Some("description7".to_string()), }, ); vec![TableConstant::SimpleEnum(SimpleEnum { identifier: TableIdentifier { object_name: "test_enum".to_string(), ..TableIdentifier::default() }, map, })] } pub fn get_table_constants_for_string_enum_with_description_buffer_test() -> Vec<TableConstant> { let mut map = HashMap::new(); map.insert( "test1".to_string(), ValueWithDescription { value: "test1".to_string(), description: Some("description5".to_string()), }, ); map.insert( "test2".to_string(), ValueWithDescription { value: "test2".to_string(), description: Some("description7".to_string()), }, ); vec![TableConstant::StringEnum(StringEnum { identifier: TableIdentifier { object_name: "test_enum".to_string(), ..TableIdentifier::default() }, map, })] } pub fn get_table_constants_for_object_like_buffer_test() -> Vec<TableConstant> { let mut map = HashMap::new(); map.insert( ValueWithDescription { value: "test1".to_string(), description: None, }, vec![ ( Column { name: "first".to_string(), data_type: STRING_TYPE.to_string(), }, "first1".to_string(), ), (
pub fn get_table_constants_for_object_like_with_description_buffer_test() -> Vec<TableConstant> { let mut map = HashMap::new(); map.insert( ValueWithDescription { value: "test1".to_string(), description: Some("description1".to_string()), }, vec![ ( Column { name: "first".to_string(), data_type: STRING_TYPE.to_string(), }, "first1".to_string(), ), ( Column { name: "second".to_string(), data_type: NUMBER_TYPE.to_string(), }, "1".to_string(), ), ], ); map.insert( ValueWithDescription { value: "test2".to_string(), description: Some("description2".to_string()), }, vec![ ( Column { name: "first".to_string(), data_type: STRING_TYPE.to_string(), }, "first2".to_string(), ), ( Column { name: "second".to_string(), data_type: NUMBER_TYPE.to_string(), }, "2".to_string(), ), ], ); vec![TableConstant::ObjectLike(ObjectLike { identifier: TableIdentifier { object_name: "test_enum".to_string(), ..TableIdentifier::default() }, map, })] } pub fn get_output_options_for_filename_test(lang: Language) -> OutputOptions { OutputOptions { language_targets: Some(vec![lang.to_string()]), ..OutputOptions::default() } }
Column { name: "second".to_string(), data_type: NUMBER_TYPE.to_string(), }, "1".to_string(), ), ], ); map.insert( ValueWithDescription { value: "test2".to_string(), description: None, }, vec![ ( Column { name: "first".to_string(), data_type: STRING_TYPE.to_string(), }, "first2".to_string(), ), ( Column { name: "second".to_string(), data_type: NUMBER_TYPE.to_string(), }, "2".to_string(), ), ], ); vec![TableConstant::ObjectLike(ObjectLike { identifier: TableIdentifier { object_name: "test_enum".to_string(), ..TableIdentifier::default() }, map, })] }
function_block-function_prefix_line
[ { "content": "fn get_constructor_for_object_like(class_name: &str, columns: &Vec<&Column>) -> String {\n\n let constructor_first_line = format!(\"private {}(\", pascal_case(class_name));\n\n let args = columns\n\n .iter()\n\n .map(|Column { data_type, name }| {\n\n format!(\n\n ...
Rust
src/sinks/util/tcp.rs
parampavar/vector
83bd797ff6a05fb3246a2442a701db3a85e323b5
use std::{ io::ErrorKind, net::SocketAddr, pin::Pin, task::{Context, Poll}, time::Duration, }; use async_trait::async_trait; use bytes::{Bytes, BytesMut}; use futures::{stream::BoxStream, task::noop_waker_ref, SinkExt, StreamExt}; use serde::{Deserialize, Serialize}; use snafu::{ResultExt, Snafu}; use tokio::{ io::{AsyncRead, ReadBuf}, net::TcpStream, time::sleep, }; use tokio_util::codec::Encoder; use vector_core::{buffers::Acker, ByteSizeOf}; use crate::{ config::SinkContext, dns, event::Event, internal_events::{ ConnectionOpen, OpenGauge, SocketMode, TcpSocketConnectionError, TcpSocketConnectionEstablished, TcpSocketConnectionShutdown, TcpSocketError, }, sink::VecSinkExt, sinks::{ util::{ encoding::Transformer, retries::ExponentialBackoff, socket_bytes_sink::{BytesSink, ShutdownCheck}, EncodedEvent, SinkBuildError, StreamSink, }, Healthcheck, VectorSink, }, tcp::TcpKeepaliveConfig, tls::{MaybeTlsSettings, MaybeTlsStream, TlsEnableableConfig, TlsError}, }; #[derive(Debug, Snafu)] enum TcpError { #[snafu(display("Connect error: {}", source))] ConnectError { source: TlsError }, #[snafu(display("Unable to resolve DNS: {}", source))] DnsError { source: dns::DnsError }, #[snafu(display("No addresses returned."))] NoAddresses, #[snafu(display("Send error: {}", source))] SendError { source: tokio::io::Error }, } #[derive(Deserialize, Serialize, Debug, Clone)] pub struct TcpSinkConfig { address: String, keepalive: Option<TcpKeepaliveConfig>, tls: Option<TlsEnableableConfig>, send_buffer_bytes: Option<usize>, } impl TcpSinkConfig { pub const fn new( address: String, keepalive: Option<TcpKeepaliveConfig>, tls: Option<TlsEnableableConfig>, send_buffer_bytes: Option<usize>, ) -> Self { Self { address, keepalive, tls, send_buffer_bytes, } } pub const fn from_address(address: String) -> Self { Self { address, keepalive: None, tls: None, send_buffer_bytes: None, } } pub fn build( &self, cx: SinkContext, transformer: Transformer, encoder: impl Encoder<Event, Error = codecs::encoding::Error> + Clone + Send + Sync + 'static, ) -> crate::Result<(VectorSink, Healthcheck)> { let uri = self.address.parse::<http::Uri>()?; let host = uri.host().ok_or(SinkBuildError::MissingHost)?.to_string(); let port = uri.port_u16().ok_or(SinkBuildError::MissingPort)?; let tls = MaybeTlsSettings::from_config(&self.tls, false)?; let connector = TcpConnector::new(host, port, self.keepalive, tls, self.send_buffer_bytes); let sink = TcpSink::new(connector.clone(), cx.acker(), transformer, encoder); Ok(( VectorSink::from_event_streamsink(sink), Box::pin(async move { connector.healthcheck().await }), )) } } #[derive(Clone)] struct TcpConnector { host: String, port: u16, keepalive: Option<TcpKeepaliveConfig>, tls: MaybeTlsSettings, send_buffer_bytes: Option<usize>, } impl TcpConnector { const fn new( host: String, port: u16, keepalive: Option<TcpKeepaliveConfig>, tls: MaybeTlsSettings, send_buffer_bytes: Option<usize>, ) -> Self { Self { host, port, keepalive, tls, send_buffer_bytes, } } #[cfg(test)] fn from_host_port(host: String, port: u16) -> Self { Self::new(host, port, None, None.into(), None) } const fn fresh_backoff() -> ExponentialBackoff { ExponentialBackoff::from_millis(2) .factor(250) .max_delay(Duration::from_secs(60)) } async fn connect(&self) -> Result<MaybeTlsStream<TcpStream>, TcpError> { let ip = dns::Resolver .lookup_ip(self.host.clone()) .await .context(DnsSnafu)? .next() .ok_or(TcpError::NoAddresses)?; let addr = SocketAddr::new(ip, self.port); self.tls .connect(&self.host, &addr) .await .context(ConnectSnafu) .map(|mut maybe_tls| { if let Some(keepalive) = self.keepalive { if let Err(error) = maybe_tls.set_keepalive(keepalive) { warn!(message = "Failed configuring TCP keepalive.", %error); } } if let Some(send_buffer_bytes) = self.send_buffer_bytes { if let Err(error) = maybe_tls.set_send_buffer_bytes(send_buffer_bytes) { warn!(message = "Failed configuring send buffer size on TCP socket.", %error); } } maybe_tls }) } async fn connect_backoff(&self) -> MaybeTlsStream<TcpStream> { let mut backoff = Self::fresh_backoff(); loop { match self.connect().await { Ok(socket) => { emit!(TcpSocketConnectionEstablished { peer_addr: socket.peer_addr().ok(), }); return socket; } Err(error) => { emit!(TcpSocketConnectionError { error }); sleep(backoff.next().unwrap()).await; } } } } async fn healthcheck(&self) -> crate::Result<()> { self.connect().await.map(|_| ()).map_err(Into::into) } } struct TcpSink<E> where E: Encoder<Event, Error = codecs::encoding::Error> + Clone + Send + Sync, { connector: TcpConnector, acker: Acker, transformer: Transformer, encoder: E, } impl<E> TcpSink<E> where E: Encoder<Event, Error = codecs::encoding::Error> + Clone + Send + Sync + 'static, { fn new(connector: TcpConnector, acker: Acker, transformer: Transformer, encoder: E) -> Self { Self { connector, acker, transformer, encoder, } } async fn connect(&self) -> BytesSink<MaybeTlsStream<TcpStream>> { let stream = self.connector.connect_backoff().await; BytesSink::new( stream, Self::shutdown_check, self.acker.clone(), SocketMode::Tcp, ) } fn shutdown_check(stream: &mut MaybeTlsStream<TcpStream>) -> ShutdownCheck { let mut cx = Context::from_waker(noop_waker_ref()); let mut buf = [0u8; 1]; let mut buf = ReadBuf::new(&mut buf); match Pin::new(stream).poll_read(&mut cx, &mut buf) { Poll::Ready(Err(error)) => ShutdownCheck::Error(error), Poll::Ready(Ok(())) if buf.filled().is_empty() => { ShutdownCheck::Close("ShutdownCheck::Close") } _ => ShutdownCheck::Alive, } } } #[async_trait] impl<E> StreamSink<Event> for TcpSink<E> where E: Encoder<Event, Error = codecs::encoding::Error> + Clone + Send + Sync + Sync + 'static, { async fn run(self: Box<Self>, input: BoxStream<'_, Event>) -> Result<(), ()> { let mut encoder = self.encoder.clone(); let mut input = input .map(|mut event| { let byte_size = event.size_of(); let finalizers = event.metadata_mut().take_finalizers(); self.transformer.transform(&mut event); let mut bytes = BytesMut::new(); if encoder.encode(event, &mut bytes).is_ok() { let item = bytes.freeze(); EncodedEvent { item, finalizers, byte_size, } } else { EncodedEvent::new(Bytes::new(), 0) } }) .peekable(); while Pin::new(&mut input).peek().await.is_some() { let mut sink = self.connect().await; let _open_token = OpenGauge::new().open(|count| emit!(ConnectionOpen { count })); let result = match sink .send_all_peekable(&mut (&mut input).map(|item| item.item).peekable()) .await { Ok(()) => sink.close().await, Err(error) => Err(error), }; if let Err(error) = result { if error.kind() == ErrorKind::Other && error.to_string() == "ShutdownCheck::Close" { emit!(TcpSocketConnectionShutdown {}); } else { emit!(TcpSocketError { error }); } } } Ok(()) } } #[cfg(test)] mod test { use tokio::net::TcpListener; use super::*; use crate::test_util::{next_addr, trace_init}; #[tokio::test] async fn healthcheck() { trace_init(); let addr = next_addr(); let _listener = TcpListener::bind(&addr).await.unwrap(); let good = TcpConnector::from_host_port(addr.ip().to_string(), addr.port()); assert!(good.healthcheck().await.is_ok()); let addr = next_addr(); let bad = TcpConnector::from_host_port(addr.ip().to_string(), addr.port()); assert!(bad.healthcheck().await.is_err()); } }
use std::{ io::ErrorKind, net::SocketAddr, pin::Pin, task::{Context, Poll}, time::Duration, }; use async_trait::async_trait; use bytes::{Bytes, BytesMut}; use futures::{stream::BoxStream, task::noop_waker_ref, SinkExt, StreamExt}; use serde::{Deserialize, Serialize}; use snafu::{ResultExt, Snafu}; use tokio::{ io::{AsyncRead, ReadBuf}, net::TcpStream, time::sleep, }; use tokio_util::codec::Encoder; use vector_core::{buffers::Acker, ByteSizeOf}; use crate::{ config::SinkContext, dns, event::Event, internal_events::{ ConnectionOpen, OpenGauge, SocketMode, TcpSocketConnectionError, TcpSocketConnectionEstablished, TcpSocketConnectionShutdown, TcpSocketError, }, sink::VecSinkExt, sinks::{ util::{ encoding::Transformer, retries::ExponentialBackoff, socket_bytes_sink::{BytesSink, ShutdownCheck}, EncodedEvent, SinkBuildError, StreamSink, }, Healthcheck, VectorSink, }, tcp::TcpKeepaliveConfig, tls::{MaybeTlsSettings, MaybeTlsStream, TlsEnableableConfig, TlsError}, }; #[derive(Debug, Snafu)] enum TcpError { #[snafu(display("Connect error: {}", source))] ConnectError { source: TlsError }, #[snafu(display("Unable to resolve DNS: {}", source))] DnsError { source: dns::DnsError }, #[snafu(display("No addresses returned."))] NoAddresses, #[snafu(display("Send error: {}", source))] SendError { source: tokio::io::Error }, } #[derive(Deserialize, Serialize, Debug, Clone)] pub struct TcpSinkConfig { address: String, keepalive: Option<TcpKeepaliveConfig>, tls: Option<TlsEnableableConfig>, send_buffer_bytes: Option<usize>, } impl TcpSinkConfig { pub const fn new( address: String, keepalive: Option<TcpKeepaliveConfig>, tls: Option<TlsEnableableConfig>, send_buffer_bytes: Option<usize>, ) -> Self { Self { address, keepalive, tls, send_buffer_bytes, } } pub const fn from_address(address: String) -> Self { Self { address, keepalive: None, tls: None, send_buffer_bytes: None, } } pub fn build( &self, cx: SinkContext, transformer: Transformer, encoder: impl Encoder<Event, Error = codecs::encoding::Error> + Clone + Send + Sync + 'static, ) -> crate::Result<(VectorSink, Healthcheck)> { let uri = self.address.parse::<http::Uri>()?; let host = uri.host().ok_or(SinkBuildError::MissingHost)?.to_string(); let port = uri.port_u16().ok_or(SinkBuildError::MissingPort)?; let tls = MaybeTlsSettings::from_config(&self.tls, false)?; let connector = TcpConnector::new(host, port, self.keepalive, tls, self.send_buffer_bytes); let sink = TcpSink::new(connector.clone(), cx.acker(), transformer, encoder); Ok(( VectorSink::from_event_streamsink(sink), Box::pin(async move { connector.healthcheck().await }), )) } } #[derive(Clone)] struct TcpConnector { host: String, port: u16, keepalive: Option<TcpKeepaliveConfig>, tls: MaybeTlsSettings, send_buffer_bytes: Option<usize>, } impl TcpConnector { const fn new( host: String, port: u16, keepalive: Option<TcpKeepaliveConfig>, tls: MaybeTlsSettings, send_buffer_bytes: Option<usize>, ) -> Self { Self { host, port, keepalive, tls, send_buffer_bytes, } } #[cfg(test)] fn from_host_port(host: String, port: u16) -> Self { Self::new(host, port, None, None.into(), None) } const fn fresh_backoff() -> ExponentialBackoff { ExponentialBackoff::from_millis(2) .factor(250) .max_delay(Duration::from_secs(60)) } async fn connect(&self) -> Result<MaybeTlsStream<TcpStream>, TcpError> { let ip = dns::Resolver .lookup_ip(self.host.clone()) .await .context(DnsSnafu)? .next() .ok_or(TcpError::NoAddresses)?; let addr = SocketAddr::new(ip, self.port); self.tls .connect(&self.host, &addr) .await .context(ConnectSnafu) .map(|mut maybe_tls| { if let Some(keepalive) = self.keepalive { if let Err(error) = maybe_tls.set_keepalive(keepalive) { warn!(message = "Failed configuring TCP keepalive.", %error); } } if let Some(send_buffer_bytes) = self.send_buffer_bytes {
} maybe_tls }) } async fn connect_backoff(&self) -> MaybeTlsStream<TcpStream> { let mut backoff = Self::fresh_backoff(); loop { match self.connect().await { Ok(socket) => { emit!(TcpSocketConnectionEstablished { peer_addr: socket.peer_addr().ok(), }); return socket; } Err(error) => { emit!(TcpSocketConnectionError { error }); sleep(backoff.next().unwrap()).await; } } } } async fn healthcheck(&self) -> crate::Result<()> { self.connect().await.map(|_| ()).map_err(Into::into) } } struct TcpSink<E> where E: Encoder<Event, Error = codecs::encoding::Error> + Clone + Send + Sync, { connector: TcpConnector, acker: Acker, transformer: Transformer, encoder: E, } impl<E> TcpSink<E> where E: Encoder<Event, Error = codecs::encoding::Error> + Clone + Send + Sync + 'static, { fn new(connector: TcpConnector, acker: Acker, transformer: Transformer, encoder: E) -> Self { Self { connector, acker, transformer, encoder, } } async fn connect(&self) -> BytesSink<MaybeTlsStream<TcpStream>> { let stream = self.connector.connect_backoff().await; BytesSink::new( stream, Self::shutdown_check, self.acker.clone(), SocketMode::Tcp, ) } fn shutdown_check(stream: &mut MaybeTlsStream<TcpStream>) -> ShutdownCheck { let mut cx = Context::from_waker(noop_waker_ref()); let mut buf = [0u8; 1]; let mut buf = ReadBuf::new(&mut buf); match Pin::new(stream).poll_read(&mut cx, &mut buf) { Poll::Ready(Err(error)) => ShutdownCheck::Error(error), Poll::Ready(Ok(())) if buf.filled().is_empty() => { ShutdownCheck::Close("ShutdownCheck::Close") } _ => ShutdownCheck::Alive, } } } #[async_trait] impl<E> StreamSink<Event> for TcpSink<E> where E: Encoder<Event, Error = codecs::encoding::Error> + Clone + Send + Sync + Sync + 'static, { async fn run(self: Box<Self>, input: BoxStream<'_, Event>) -> Result<(), ()> { let mut encoder = self.encoder.clone(); let mut input = input .map(|mut event| { let byte_size = event.size_of(); let finalizers = event.metadata_mut().take_finalizers(); self.transformer.transform(&mut event); let mut bytes = BytesMut::new(); if encoder.encode(event, &mut bytes).is_ok() { let item = bytes.freeze(); EncodedEvent { item, finalizers, byte_size, } } else { EncodedEvent::new(Bytes::new(), 0) } }) .peekable(); while Pin::new(&mut input).peek().await.is_some() { let mut sink = self.connect().await; let _open_token = OpenGauge::new().open(|count| emit!(ConnectionOpen { count })); let result = match sink .send_all_peekable(&mut (&mut input).map(|item| item.item).peekable()) .await { Ok(()) => sink.close().await, Err(error) => Err(error), }; if let Err(error) = result { if error.kind() == ErrorKind::Other && error.to_string() == "ShutdownCheck::Close" { emit!(TcpSocketConnectionShutdown {}); } else { emit!(TcpSocketError { error }); } } } Ok(()) } } #[cfg(test)] mod test { use tokio::net::TcpListener; use super::*; use crate::test_util::{next_addr, trace_init}; #[tokio::test] async fn healthcheck() { trace_init(); let addr = next_addr(); let _listener = TcpListener::bind(&addr).await.unwrap(); let good = TcpConnector::from_host_port(addr.ip().to_string(), addr.port()); assert!(good.healthcheck().await.is_ok()); let addr = next_addr(); let bad = TcpConnector::from_host_port(addr.ip().to_string(), addr.port()); assert!(bad.healthcheck().await.is_err()); } }
if let Err(error) = maybe_tls.set_send_buffer_bytes(send_buffer_bytes) { warn!(message = "Failed configuring send buffer size on TCP socket.", %error); }
if_condition
[ { "content": "pub trait TcpSource: Clone + Send + Sync + 'static\n\nwhere\n\n <<Self as TcpSource>::Decoder as tokio_util::codec::Decoder>::Item: std::marker::Send,\n\n{\n\n // Should be default: `std::io::Error`.\n\n // Right now this is unstable: https://github.com/rust-lang/rust/issues/29661\n\n ...
Rust
delsum-lib/src/fletcher/mod.rs
8051Enthusiast/delsum
5605cd8343cb8ba3133eea31610968cd3c6444d4
mod rev; use crate::bitnum::{BitNum, Modnum}; use crate::checksum::{CheckBuilderErr, Digest, LinearCheck}; use crate::endian::{Endian, WordSpec}; use crate::keyval::KeyValIter; use num_traits::{One, Zero}; pub use rev::reverse_fletcher; #[cfg(feature = "parallel")] pub use rev::reverse_fletcher_para; use std::fmt::Display; use std::str::FromStr; #[derive(Clone, Debug)] pub struct FletcherBuilder<Sum: Modnum> { width: Option<usize>, module: Option<Sum>, init: Option<Sum>, addout: Option<Sum::Double>, swap: Option<bool>, input_endian: Option<Endian>, output_endian: Option<Endian>, wordsize: Option<usize>, check: Option<Sum::Double>, name: Option<String>, } impl<S: Modnum> FletcherBuilder<S> { pub fn width(&mut self, w: usize) -> &mut Self { self.width = Some(w); self } pub fn module(&mut self, m: S) -> &mut Self { self.module = Some(m); self } pub fn init(&mut self, i: S) -> &mut Self { self.init = Some(i); self } pub fn addout(&mut self, o: S::Double) -> &mut Self { self.addout = Some(o); self } pub fn swap(&mut self, s: bool) -> &mut Self { self.swap = Some(s); self } pub fn inendian(&mut self, e: Endian) -> &mut Self { self.input_endian = Some(e); self } pub fn wordsize(&mut self, n: usize) -> &mut Self { self.wordsize = Some(n); self } pub fn outendian(&mut self, e: Endian) -> &mut Self { self.output_endian = Some(e); self } pub fn check(&mut self, c: S::Double) -> &mut Self { self.check = Some(c); self } pub fn name(&mut self, n: &str) -> &mut Self { self.name = Some(String::from(n)); self } pub fn build(&self) -> Result<Fletcher<S>, CheckBuilderErr> { let init = self.init.unwrap_or_else(S::zero); let addout = self.addout.unwrap_or_else(S::Double::zero); let hwidth = match self.width { None => return Err(CheckBuilderErr::MissingParameter("width")), Some(w) => { if w % 2 != 0 || w > addout.bits() { return Err(CheckBuilderErr::ValueOutOfRange("width")); } else { w / 2 } } }; let mask = (S::Double::one() << hwidth) - S::Double::one(); let module = self.module.unwrap_or_else(S::zero); let wordsize = self.wordsize.unwrap_or(8); if wordsize == 0 || wordsize % 8 != 0 || wordsize > 64 { return Err(CheckBuilderErr::ValueOutOfRange("wordsize")); } let wordspec = WordSpec { input_endian: self.input_endian.unwrap_or(Endian::Big), wordsize, output_endian: self.output_endian.unwrap_or(Endian::Big), }; let mut fletch = Fletcher { hwidth, module, init, addout, swap: self.swap.unwrap_or(false), wordspec, mask, name: self.name.clone(), }; let (mut s, mut c) = fletch.from_compact(addout); if !module.is_zero() { s = s % module; c = c % module; fletch.init = init % module; } else { fletch.init = init; }; fletch.addout = fletch.to_compact((s, c)); match self.check { Some(chk) => { if fletch.digest(&b"123456789"[..]).unwrap() != chk { println!("{:x?}", fletch.digest(&b"123456789"[..]).unwrap()); Err(CheckBuilderErr::CheckFail) } else { Ok(fletch) } } None => Ok(fletch), } } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct Fletcher<Sum: Modnum> { hwidth: usize, module: Sum, init: Sum, addout: Sum::Double, swap: bool, wordspec: WordSpec, mask: Sum::Double, name: Option<String>, } impl<Sum: Modnum> Display for Fletcher<Sum> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.name { Some(n) => write!(f, "{}", n), None => { write!( f, "fletcher width={} module={:#x} init={:#x} addout={:#x} swap={}", 2 * self.hwidth, self.module, self.init, self.addout, self.swap )?; if self.wordspec.word_bytes() != 1 { write!( f, " in_endian={} wordsize={}", self.wordspec.input_endian, self.wordspec.wordsize )?; }; if self.hwidth * 2 > 8 { write!(f, " out_endian={}", self.wordspec.output_endian)?; }; Ok(()) } } } } impl<Sum: Modnum> Fletcher<Sum> { pub fn with_options() -> FletcherBuilder<Sum> { FletcherBuilder { width: None, module: None, init: None, addout: None, swap: None, input_endian: None, output_endian: None, wordsize: None, check: None, name: None, } } fn from_compact(&self, x: Sum::Double) -> (Sum, Sum) { let l = Sum::from_double(x & self.mask); let h = Sum::from_double((x >> self.hwidth) & self.mask); if self.swap { (h, l) } else { (l, h) } } fn to_compact(&self, (s, c): (Sum, Sum)) -> Sum::Double { let (l, h) = if self.swap { (c, s) } else { (s, c) }; (Sum::Double::from(l) & self.mask) ^ (Sum::Double::from(h) & self.mask) << self.hwidth } } impl<Sum: Modnum> FromStr for FletcherBuilder<Sum> { fn from_str(s: &str) -> Result<FletcherBuilder<Sum>, CheckBuilderErr> { let mut fletch = Fletcher::<Sum>::with_options(); for x in KeyValIter::new(s) { let (current_key, current_val) = match x { Err(key) => return Err(CheckBuilderErr::MalformedString(key)), Ok(s) => s, }; let fletch_op = match current_key.as_str() { "width" => usize::from_str(&current_val).ok().map(|x| fletch.width(x)), "module" => Sum::from_hex(&current_val).ok().map(|x| fletch.module(x)), "init" => Sum::from_hex(&current_val).ok().map(|x| fletch.init(x)), "addout" => Sum::Double::from_hex(&current_val) .ok() .map(|x| fletch.addout(x)), "swap" => bool::from_str(&current_val).ok().map(|x| fletch.swap(x)), "in_endian" => Endian::from_str(&current_val) .ok() .map(|x| fletch.inendian(x)), "wordsize" => usize::from_str(&current_val) .ok() .map(|x| fletch.wordsize(x)), "out_endian" => Endian::from_str(&current_val) .ok() .map(|x| fletch.outendian(x)), "check" => Sum::Double::from_hex(&current_val) .ok() .map(|x| fletch.check(x)), "name" => Some(fletch.name(&current_val)), _ => return Err(CheckBuilderErr::UnknownKey(current_key)), }; match fletch_op { Some(f) => fletch = f.clone(), None => return Err(CheckBuilderErr::MalformedString(current_key)), } } Ok(fletch) } type Err = CheckBuilderErr; } impl<Sum: Modnum> FromStr for Fletcher<Sum> { fn from_str(s: &str) -> Result<Fletcher<Sum>, CheckBuilderErr> { FletcherBuilder::<Sum>::from_str(s)?.build() } type Err = CheckBuilderErr; } impl<S: Modnum> Digest for Fletcher<S> { type Sum = S::Double; fn init(&self) -> Self::Sum { self.to_compact((self.init, S::zero())) } fn dig_word(&self, sum: Self::Sum, word: u64) -> Self::Sum { let (mut s, mut c) = self.from_compact(sum); let modword = S::mod_from(word, &self.module); s = S::add_mod(s, &modword, &self.module); c = S::add_mod(c, &s, &self.module); self.to_compact((s, c)) } fn finalize(&self, sum: Self::Sum) -> Self::Sum { self.add(sum, &self.addout) } fn to_bytes(&self, s: Self::Sum) -> Vec<u8> { self.wordspec.output_to_bytes(s, 2 * self.hwidth) } fn wordspec(&self) -> WordSpec { self.wordspec } } impl<S: Modnum> LinearCheck for Fletcher<S> { type Shift = S; fn init_shift(&self) -> Self::Shift { S::zero() } fn inc_shift(&self, shift: Self::Shift) -> Self::Shift { S::add_mod(shift, &S::one(), &self.module) } fn shift(&self, sum: Self::Sum, shift: &Self::Shift) -> Self::Sum { let (s, mut c) = self.from_compact(sum); let shift_diff = S::mul_mod(s, shift, &self.module); c = S::add_mod(c, &shift_diff, &self.module); self.to_compact((s, c)) } fn add(&self, sum_a: Self::Sum, sum_b: &Self::Sum) -> Self::Sum { let (sa, ca) = self.from_compact(sum_a); let (sb, cb) = self.from_compact(*sum_b); let sum_s = sa.add_mod(&sb, &self.module); let sum_c = ca.add_mod(&cb, &self.module); self.to_compact((sum_s, sum_c)) } fn negate(&self, sum: Self::Sum) -> Self::Sum { let (s, c) = self.from_compact(sum); self.to_compact((s.neg_mod(&self.module), c.neg_mod(&self.module))) } } #[cfg(test)] mod tests { use super::*; use crate::checksum::tests::{check_example, test_find, test_prop, test_shifts}; use std::str::FromStr; #[test] fn adler32() { let adel = Fletcher::<u16>::with_options() .width(32) .init(1) .module(65521) .check(0x091e01de) .build() .unwrap(); test_shifts(&adel); test_find(&adel); test_prop(&adel); check_example(&adel, 0x81bfd25f); let nobel = Fletcher::with_options() .width(32) .init(1u32) .module(65521) .check(0x091e01de) .build() .unwrap(); test_shifts(&nobel); test_find(&nobel); test_prop(&adel); check_example(&nobel, 0x81bfd25f); } #[test] fn fletcher16() { let f16 = Fletcher::with_options() .width(16) .module(0xffu8) .check(0x1ede) .build() .unwrap(); test_shifts(&f16); test_find(&f16); test_prop(&f16); check_example(&f16, 0x7815); } #[test] fn fletcher8() { let f8 = Fletcher::<u8>::from_str("width=8 module=f init=0 addout=0 swap=false check=0xc") .unwrap(); test_shifts(&f8); test_prop(&f8); check_example(&f8, 0x6); } }
mod rev; use crate::bitnum::{BitNum, Modnum}; use crate::checksum::{CheckBuilderErr, Digest, LinearCheck}; use crate::endian::{Endian, WordSpec}; use crate::keyval::KeyValIter; use num_traits::{One, Zero}; pub use rev::reverse_fletcher; #[cfg(feature = "parallel")] pub use rev::reverse_fletcher_para; use std::fmt::Display; use std::str::FromStr; #[derive(Clone, Debug)] pub struct FletcherBuilder<Sum: Modnum> { width: Option<usize>, module: Option<Sum>, init: Option<Sum>, addout: Option<Sum::Double>, swap: Option<bool>, input_endian: Option<Endian>, output_endian: Option<Endian>, wordsize: Option<usize>, check: Option<Sum::Double>, name: Option<String>, } impl<S: Modnum> FletcherBuilder<S> { pub fn width(&mut self, w: usize) -> &mut Self { self.width = Some(w); self } pub fn module(&mut self, m: S) -> &mut Self { self.module = Some(m); self } pub fn init(&mut self, i: S) -> &mut Self { self.init = Some(i); self } pub fn addout(&mut self, o: S::Double) -> &mut Self { self.addout = Some(o); self } pub fn swap(&mut self, s: bool) -> &mut Self { self.swap = Some(s); self } pub fn inendian(&mut self, e: Endian) -> &mut Self { self.input_endian = Some(e); self } pub fn wordsize(&mut self, n: usize) -> &mut Self { self.wordsize = Some(n); self } pub fn outendian(&mut self, e: Endian) -> &mut Self { self.output_endian = Some(e); self } pub fn check(&mut self, c: S::Double) -> &mut Self { self.check = Some(c); self } pub fn name(&mut self, n: &str) -> &mut Self { self.name = Some(String::from(n)); self } pub fn build(&self) -> Result<Fletcher<S>, CheckBuilderErr> { let init = self.init.unwrap_or_else(S::zero); let addout = self.addout.unwrap_or_else(S::Double::zero); let hwidth = match self.width { None => return Err(CheckBuilderErr::MissingParameter("width")), Some(w) => { if w % 2 != 0 || w > addout.bits() { return Err(CheckBuilderErr::ValueOutOfRange("width")); } else { w / 2 } } }; let mask = (S::Double::one() << hwidth) - S::Double::one(); let module = self.module.unwrap_or_else(S::zero); let wordsize = self.wordsize.unwrap_or(8); if wordsize == 0 || wordsize % 8 != 0 || wordsize > 64 { return Err(CheckBuilderErr::ValueOutOfRange("wordsize")); } let wordspec = WordSpec { input_endian: self.input_endian.unwrap_or(Endian::Big), wordsize, output_endian: self.output_endian.unwrap_or(Endian::Big), }; let mut fletch = Fletcher { hwidth, module, init, addout, swap: self.swap.unwrap_or(false), wordspec, mask, name: self.name.clone(), }; let (mut s, mut c) = fletch.from_compact(addout); if !module.is_zero() { s = s % module; c = c % module; fletch.init = init % module; } else { fletch.init = init; }; fletch.addout = fletch.to_compact((s, c)); match self.check { Some(chk) => { if fletch.digest(&b"123456789"[..]).unwrap() != chk { println!("{:x?}", fletch.digest(&b"123456789"[..]).unwrap()); Err(CheckBuilderErr::CheckFail) } else { Ok(fletch) } } None => Ok(fletch), } } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct Fletcher<Sum: Modnum> { hwidth: usize, module: Sum, init: Sum, addout: Sum::Double, swap: bool, wordspec: WordSpec, mask: Sum::Double, name: Option<String>, } impl<Sum: Modnum> Display for Fletcher<Sum> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.name { Some(n) => write!(f, "{}", n), None => { write!( f, "fletcher width={} module={:#x} init={:#x} addout={:#x} swap={}", 2 * self.hwidth, self.module, self.init, self.addout, self.swap )?; if self.wordspec.word_bytes() != 1 { write!( f, " in_endian={} wordsize={}", self.wordspec.input_endian, self.wordspec.wordsize )?; }; if self.hwidth * 2 > 8 { write!(f, " out_endian={}", self.wordspec.output_endian)?; }; Ok(()) } } } } impl<Sum: Modnum> Fletcher<Sum> { pub fn with_options() -> FletcherBuilder<Sum> { FletcherBuilder { width: None, module: None, init: None, addout: None, swap: None, input_endian: None, output_endian: None, wordsize: None, check: None, name: None, } } fn from_compact(&self, x: Sum::Double) -> (Sum, Sum) { let l = Sum::from_double(x & self.mask); let h = Sum::from_double((x >> self.hwidth) & self.mask); if self.swap { (h, l) } else { (l, h) } } fn to_compact(&self, (s, c): (Sum, Sum)) -> Sum::Double { let (l, h) = if self.swap { (c, s) } else { (s, c) }; (Sum::Double::from(l) & self.mask) ^ (Sum::Double::from(h) & self.mask) << self.hwidth } } impl<Sum: Modnum> FromStr for FletcherBuilder<Sum> { fn from_str(s: &str) -> Result<FletcherBuilder<Sum>, CheckBuilderErr> { let mut fletch = Fletcher::<Sum>::with_options(); for x in KeyValIter::new(s) { let (current_key, current_val) =
; let fletch_op = match current_key.as_str() { "width" => usize::from_str(&current_val).ok().map(|x| fletch.width(x)), "module" => Sum::from_hex(&current_val).ok().map(|x| fletch.module(x)), "init" => Sum::from_hex(&current_val).ok().map(|x| fletch.init(x)), "addout" => Sum::Double::from_hex(&current_val) .ok() .map(|x| fletch.addout(x)), "swap" => bool::from_str(&current_val).ok().map(|x| fletch.swap(x)), "in_endian" => Endian::from_str(&current_val) .ok() .map(|x| fletch.inendian(x)), "wordsize" => usize::from_str(&current_val) .ok() .map(|x| fletch.wordsize(x)), "out_endian" => Endian::from_str(&current_val) .ok() .map(|x| fletch.outendian(x)), "check" => Sum::Double::from_hex(&current_val) .ok() .map(|x| fletch.check(x)), "name" => Some(fletch.name(&current_val)), _ => return Err(CheckBuilderErr::UnknownKey(current_key)), }; match fletch_op { Some(f) => fletch = f.clone(), None => return Err(CheckBuilderErr::MalformedString(current_key)), } } Ok(fletch) } type Err = CheckBuilderErr; } impl<Sum: Modnum> FromStr for Fletcher<Sum> { fn from_str(s: &str) -> Result<Fletcher<Sum>, CheckBuilderErr> { FletcherBuilder::<Sum>::from_str(s)?.build() } type Err = CheckBuilderErr; } impl<S: Modnum> Digest for Fletcher<S> { type Sum = S::Double; fn init(&self) -> Self::Sum { self.to_compact((self.init, S::zero())) } fn dig_word(&self, sum: Self::Sum, word: u64) -> Self::Sum { let (mut s, mut c) = self.from_compact(sum); let modword = S::mod_from(word, &self.module); s = S::add_mod(s, &modword, &self.module); c = S::add_mod(c, &s, &self.module); self.to_compact((s, c)) } fn finalize(&self, sum: Self::Sum) -> Self::Sum { self.add(sum, &self.addout) } fn to_bytes(&self, s: Self::Sum) -> Vec<u8> { self.wordspec.output_to_bytes(s, 2 * self.hwidth) } fn wordspec(&self) -> WordSpec { self.wordspec } } impl<S: Modnum> LinearCheck for Fletcher<S> { type Shift = S; fn init_shift(&self) -> Self::Shift { S::zero() } fn inc_shift(&self, shift: Self::Shift) -> Self::Shift { S::add_mod(shift, &S::one(), &self.module) } fn shift(&self, sum: Self::Sum, shift: &Self::Shift) -> Self::Sum { let (s, mut c) = self.from_compact(sum); let shift_diff = S::mul_mod(s, shift, &self.module); c = S::add_mod(c, &shift_diff, &self.module); self.to_compact((s, c)) } fn add(&self, sum_a: Self::Sum, sum_b: &Self::Sum) -> Self::Sum { let (sa, ca) = self.from_compact(sum_a); let (sb, cb) = self.from_compact(*sum_b); let sum_s = sa.add_mod(&sb, &self.module); let sum_c = ca.add_mod(&cb, &self.module); self.to_compact((sum_s, sum_c)) } fn negate(&self, sum: Self::Sum) -> Self::Sum { let (s, c) = self.from_compact(sum); self.to_compact((s.neg_mod(&self.module), c.neg_mod(&self.module))) } } #[cfg(test)] mod tests { use super::*; use crate::checksum::tests::{check_example, test_find, test_prop, test_shifts}; use std::str::FromStr; #[test] fn adler32() { let adel = Fletcher::<u16>::with_options() .width(32) .init(1) .module(65521) .check(0x091e01de) .build() .unwrap(); test_shifts(&adel); test_find(&adel); test_prop(&adel); check_example(&adel, 0x81bfd25f); let nobel = Fletcher::with_options() .width(32) .init(1u32) .module(65521) .check(0x091e01de) .build() .unwrap(); test_shifts(&nobel); test_find(&nobel); test_prop(&adel); check_example(&nobel, 0x81bfd25f); } #[test] fn fletcher16() { let f16 = Fletcher::with_options() .width(16) .module(0xffu8) .check(0x1ede) .build() .unwrap(); test_shifts(&f16); test_find(&f16); test_prop(&f16); check_example(&f16, 0x7815); } #[test] fn fletcher8() { let f8 = Fletcher::<u8>::from_str("width=8 module=f init=0 addout=0 swap=false check=0xc") .unwrap(); test_shifts(&f8); test_prop(&f8); check_example(&f8, 0x6); } }
match x { Err(key) => return Err(CheckBuilderErr::MalformedString(key)), Ok(s) => s, }
if_condition
[ { "content": "fn glue_sum(mut s1: u64, mut s2: u64, width: usize, swap: bool) -> u128 {\n\n if swap {\n\n std::mem::swap(&mut s1, &mut s2);\n\n }\n\n (s1 as u128) | ((s2 as u128) << (width / 2))\n\n}\n\n\n", "file_path": "delsum-lib/src/fletcher/rev.rs", "rank": 0, "score": 242015.56...
Rust
src/r3_port_riscv/src/timer/cfg.rs
yvt/r3
cafe6078fa8a649a6e1c5969c625c2a127a91027
use r3::kernel::InterruptNum; #[macro_export] macro_rules! use_timer { (unsafe impl PortTimer for $ty:ty) => { const _: () = { use $crate::r3::{ kernel::{cfg::CfgBuilder, PortTimer, UTicks}, utils::Init, }; use $crate::r3_portkit::tickless; use $crate::{timer, Timer, TimerOptions}; impl PortTimer for $ty { const MAX_TICK_COUNT: UTicks = u32::MAX; const MAX_TIMEOUT: UTicks = u32::MAX; unsafe fn tick_count() -> UTicks { unsafe { timer::imp::tick_count::<Self>() } } unsafe fn pend_tick() { unsafe { timer::imp::pend_tick::<Self>() } } unsafe fn pend_tick_after(tick_count_delta: UTicks) { unsafe { timer::imp::pend_tick_after::<Self>(tick_count_delta) } } } impl Timer for $ty { unsafe fn init() { unsafe { timer::imp::init::<Self>() } } } const TICKLESS_CFG: tickless::TicklessCfg = match tickless::TicklessCfg::new(tickless::TicklessOptions { hw_freq_num: <$ty as TimerOptions>::FREQUENCY, hw_freq_denom: <$ty as TimerOptions>::FREQUENCY_DENOMINATOR, hw_headroom_ticks: <$ty as TimerOptions>::HEADROOM, force_full_hw_period: true, resettable: !<$ty as TimerOptions>::RESET_MTIME, }) { Ok(x) => x, Err(e) => e.panic(), }; static mut TIMER_STATE: tickless::TicklessState<TICKLESS_CFG> = Init::INIT; unsafe impl timer::imp::TimerInstance for $ty { const TICKLESS_CFG: tickless::TicklessCfg = TICKLESS_CFG; type TicklessState = tickless::TicklessState<TICKLESS_CFG>; fn tickless_state() -> *mut Self::TicklessState { unsafe { core::ptr::addr_of_mut!(TIMER_STATE) } } } impl $ty { pub const fn configure_timer(b: &mut CfgBuilder<Self>) { timer::imp::configure(b); } } }; }; } pub trait TimerOptions { const MTIME_PTR: usize; const MTIMECMP_PTR: usize; const RESET_MTIME: bool = true; const FREQUENCY: u64; const FREQUENCY_DENOMINATOR: u64 = 1; const HEADROOM: u32 = min128( Self::FREQUENCY as u128 * 60 / Self::FREQUENCY_DENOMINATOR as u128, 0x40000000, ) as u32; const INTERRUPT_NUM: InterruptNum = crate::INTERRUPT_TIMER; } const fn min128(x: u128, y: u128) -> u128 { if x < y { x } else { y } }
use r3::kernel::InterruptNum; #[macro_export] macro_rules! use_timer { (unsafe impl PortTimer for $ty:ty) => { const _: () = { use $crate::r3::{ kernel::{cfg::CfgBuilder, PortTimer, UTicks}, utils::Init, }; use $crate::r3_portkit::tickless; use $crate::{timer, Timer, TimerOptions}; impl PortTimer for $ty { const MAX_TICK_COUNT: UTicks = u32::MAX; const MAX_TIMEOUT: UTicks = u32::MAX; unsafe fn tick_count() -> UTicks { unsafe { timer::imp::tick_count::<Self>() } } unsafe fn pend_tick() { unsafe { timer::imp::pend_tick::<Self>() } } unsafe fn pend_tick_after(tick_count_delta:
const RESET_MTIME: bool = true; const FREQUENCY: u64; const FREQUENCY_DENOMINATOR: u64 = 1; const HEADROOM: u32 = min128( Self::FREQUENCY as u128 * 60 / Self::FREQUENCY_DENOMINATOR as u128, 0x40000000, ) as u32; const INTERRUPT_NUM: InterruptNum = crate::INTERRUPT_TIMER; } const fn min128(x: u128, y: u128) -> u128 { if x < y { x } else { y } }
UTicks) { unsafe { timer::imp::pend_tick_after::<Self>(tick_count_delta) } } } impl Timer for $ty { unsafe fn init() { unsafe { timer::imp::init::<Self>() } } } const TICKLESS_CFG: tickless::TicklessCfg = match tickless::TicklessCfg::new(tickless::TicklessOptions { hw_freq_num: <$ty as TimerOptions>::FREQUENCY, hw_freq_denom: <$ty as TimerOptions>::FREQUENCY_DENOMINATOR, hw_headroom_ticks: <$ty as TimerOptions>::HEADROOM, force_full_hw_period: true, resettable: !<$ty as TimerOptions>::RESET_MTIME, }) { Ok(x) => x, Err(e) => e.panic(), }; static mut TIMER_STATE: tickless::TicklessState<TICKLESS_CFG> = Init::INIT; unsafe impl timer::imp::TimerInstance for $ty { const TICKLESS_CFG: tickless::TicklessCfg = TICKLESS_CFG; type TicklessState = tickless::TicklessState<TICKLESS_CFG>; fn tickless_state() -> *mut Self::TicklessState { unsafe { core::ptr::addr_of_mut!(TIMER_STATE) } } } impl $ty { pub const fn configure_timer(b: &mut CfgBuilder<Self>) { timer::imp::configure(b); } } }; }; } pub trait TimerOptions { const MTIME_PTR: usize; const MTIMECMP_PTR: usize;
random
[ { "content": "#[cfg(not(arm))]\n\nfn interrupt_free<R>(_: impl FnOnce() -> R) -> R {\n\n unreachable!();\n\n}\n\n\n", "file_path": "src/arm_semihosting/src/export.rs", "rank": 0, "score": 194965.27888413682 }, { "content": "#[cfg(not(target_arch = \"arm\"))]\n\nfn interrupt_free<T>(_: imp...
Rust
rain_server/src/governor/tasks/instance.rs
baajur/rain
477948554150760164c6fe48eac27bcf06c7933b
use chrono::{DateTime, Utc}; use futures::Future; use rain_core::{comm::*, errors::*}; use error_chain::bail; use governor::graph::{ExecutorRef, TaskRef, TaskState}; use governor::rpc::executor::data_output_from_spec; use governor::state::State; use governor::tasks; pub struct TaskInstance { task_ref: TaskRef, cancel_sender: Option<::futures::unsync::oneshot::Sender<()>>, start_timestamp: DateTime<Utc>, } pub type TaskFuture = Future<Item = (), Error = Error>; pub type TaskResult = Result<Box<TaskFuture>>; fn fail_unknown_type(_state: &mut State, task_ref: TaskRef) -> TaskResult { bail!("Unknown task type {}", task_ref.get().spec.task_type) } struct KillOnDrop { executor_ref: Option<ExecutorRef>, } impl KillOnDrop { pub fn new(executor_ref: ExecutorRef) -> Self { KillOnDrop { executor_ref: Some(executor_ref), } } pub fn deactive(&mut self) -> ExecutorRef { ::std::mem::replace(&mut self.executor_ref, None).unwrap() } } impl Drop for KillOnDrop { fn drop(&mut self) { if let Some(ref sw) = self.executor_ref { sw.get_mut().kill(); } } } impl TaskInstance { pub fn start(state: &mut State, task_ref: TaskRef) { { let mut task = task_ref.get_mut(); state.alloc_resources(&task.spec.resources); task.state = TaskState::Running; state.task_updated(&task_ref); } let task_fn = { let task = task_ref.get(); let task_type: &str = task.spec.task_type.as_ref(); match task_type { task_type if !task_type.starts_with("buildin/") => Self::start_task_in_executor, "buildin/run" => tasks::run::task_run, "buildin/concat" => tasks::basic::task_concat, "buildin/open" => tasks::basic::task_open, "buildin/export" => tasks::basic::task_export, "buildin/slice_directory" => tasks::basic::task_slice_directory, "buildin/make_directory" => tasks::basic::task_make_directory, "buildin/sleep" => tasks::basic::task_sleep, _ => fail_unknown_type, } }; let future: Box<TaskFuture> = match task_fn(state, task_ref.clone()) { Ok(f) => f, Err(e) => { state.unregister_task(&task_ref); let mut task = task_ref.get_mut(); state.free_resources(&task.spec.resources); task.set_failed(e.description().to_string()); state.task_updated(&task_ref); return; } }; let (sender, receiver) = ::futures::unsync::oneshot::channel::<()>(); let task_id = task_ref.get().spec.id; let instance = TaskInstance { task_ref: task_ref, cancel_sender: Some(sender), start_timestamp: Utc::now(), }; let state_ref = state.self_ref(); state.graph.running_tasks.insert(task_id, instance); state.spawn_panic_on_error( future .map(|()| true) .select(receiver.map(|()| false).map_err(|_| unreachable!())) .then(move |r| { let mut state = state_ref.get_mut(); let instance = state.graph.running_tasks.remove(&task_id).unwrap(); state.task_updated(&instance.task_ref); state.unregister_task(&instance.task_ref); let mut task = instance.task_ref.get_mut(); state.free_resources(&task.spec.resources); task.info.governor = format!("{}", state.governor_id()); task.info.start_time = instance.start_timestamp.to_rfc3339(); task.info.duration = Some( Utc::now() .signed_duration_since(instance.start_timestamp) .num_milliseconds() as f32 * 0.001f32, ); match r { Ok((true, _)) => { let all_finished = task.outputs.iter().all(|o| o.get().is_finished()); if !all_finished { task.set_failed("Some of outputs were not produced".into()); } else { for output in &task.outputs { state.object_is_finished(output); } log::debug!("Task was successfully finished"); task.state = TaskState::Finished; } } Ok((false, _)) => { log::debug!("Task {} was terminated", task.spec.id); task.set_failed("Task terminated by server".into()); } Err((e, _)) => { task.set_failed(e.description().to_string()); } }; Ok(()) }), ); } pub fn stop(&mut self) { let cancel_sender = ::std::mem::replace(&mut self.cancel_sender, None); if let Some(sender) = cancel_sender { sender.send(()).unwrap(); } else { log::debug!("Task stopping is already in progress"); } } fn start_task_in_executor(state: &mut State, task_ref: TaskRef) -> TaskResult { let future = { let task = task_ref.get(); let first: &str = task.spec.task_type.split('/').next().unwrap(); state.get_executor(first)? }; let state_ref = state.self_ref(); Ok(Box::new(future.and_then(move |executor_ref| { let mut sw_wrapper = KillOnDrop::new(executor_ref.clone()); let task_ref2 = task_ref.clone(); let task = task_ref2.get(); let executor_ref2 = executor_ref.clone(); let mut executor = executor_ref2.get_mut(); executor.send_task(&task, &executor_ref).then(move |r| { sw_wrapper.deactive(); match r { Ok(ResultMsg { task: task_id, info, success, outputs, cached_objects, }) => { let result: Result<()> = { let mut task = task_ref.get_mut(); let executor = executor_ref.get(); let work_dir = executor.work_dir(); assert!(task.spec.id == task_id); task.info = info; if success { log::debug!("Task id={} finished in executor", task.spec.id); for (co, output) in outputs.into_iter().zip(&task.outputs) { let mut o = output.get_mut(); o.info = co.info.clone(); let data = data_output_from_spec( &state_ref.get(), work_dir, co, o.spec.data_type, )?; o.set_data(data)?; } Ok(()) } else { log::debug!("Task id={} failed in executor", task.spec.id); Err("Task failed in executor".into()) } }; let mut state = state_ref.get_mut(); for object_id in cached_objects { let obj_ref = state.graph.objects.get(&object_id).unwrap(); obj_ref .get_mut() .executor_cache .insert(executor_ref.clone()); } state.graph.idle_executors.insert(executor_ref); result } Err(_) => Err(format!( "Lost connection to executor\n{}", executor_ref .get() .get_log_tails(state_ref.get().log_dir(), 4096) ).into()), } }) }))) } }
use chrono::{DateTime, Utc}; use futures::Future; use rain_core::{comm::*, errors::*}; use error_chain::bail; use governor::graph::{ExecutorRef, TaskRef, TaskState}; use governor::rpc::executor::data_output_from_spec; use governor::state::State; use governor::tasks; pub struct TaskInstance { task_ref: TaskRef, cancel_sender: Option<::futures::unsync::oneshot::Sender<()>>, start_timestamp: DateTime<Utc>, } pub type TaskFuture = Future<Item = (), Error = Error>; pub type TaskResult = Result<Box<TaskFuture>>; fn fail_unknown_type(_state: &mut State, task_ref: TaskRef) -> TaskResult { bail!("Unknown task type {}", task_ref.get().spec.task_type) } struct KillOnDrop { executor_ref: Option<ExecutorRef>, } impl KillOnDrop { pub fn new(execut
terminated", task.spec.id); task.set_failed("Task terminated by server".into()); } Err((e, _)) => { task.set_failed(e.description().to_string()); } }; Ok(()) }), ); } pub fn stop(&mut self) { let cancel_sender = ::std::mem::replace(&mut self.cancel_sender, None); if let Some(sender) = cancel_sender { sender.send(()).unwrap(); } else { log::debug!("Task stopping is already in progress"); } } fn start_task_in_executor(state: &mut State, task_ref: TaskRef) -> TaskResult { let future = { let task = task_ref.get(); let first: &str = task.spec.task_type.split('/').next().unwrap(); state.get_executor(first)? }; let state_ref = state.self_ref(); Ok(Box::new(future.and_then(move |executor_ref| { let mut sw_wrapper = KillOnDrop::new(executor_ref.clone()); let task_ref2 = task_ref.clone(); let task = task_ref2.get(); let executor_ref2 = executor_ref.clone(); let mut executor = executor_ref2.get_mut(); executor.send_task(&task, &executor_ref).then(move |r| { sw_wrapper.deactive(); match r { Ok(ResultMsg { task: task_id, info, success, outputs, cached_objects, }) => { let result: Result<()> = { let mut task = task_ref.get_mut(); let executor = executor_ref.get(); let work_dir = executor.work_dir(); assert!(task.spec.id == task_id); task.info = info; if success { log::debug!("Task id={} finished in executor", task.spec.id); for (co, output) in outputs.into_iter().zip(&task.outputs) { let mut o = output.get_mut(); o.info = co.info.clone(); let data = data_output_from_spec( &state_ref.get(), work_dir, co, o.spec.data_type, )?; o.set_data(data)?; } Ok(()) } else { log::debug!("Task id={} failed in executor", task.spec.id); Err("Task failed in executor".into()) } }; let mut state = state_ref.get_mut(); for object_id in cached_objects { let obj_ref = state.graph.objects.get(&object_id).unwrap(); obj_ref .get_mut() .executor_cache .insert(executor_ref.clone()); } state.graph.idle_executors.insert(executor_ref); result } Err(_) => Err(format!( "Lost connection to executor\n{}", executor_ref .get() .get_log_tails(state_ref.get().log_dir(), 4096) ).into()), } }) }))) } }
or_ref: ExecutorRef) -> Self { KillOnDrop { executor_ref: Some(executor_ref), } } pub fn deactive(&mut self) -> ExecutorRef { ::std::mem::replace(&mut self.executor_ref, None).unwrap() } } impl Drop for KillOnDrop { fn drop(&mut self) { if let Some(ref sw) = self.executor_ref { sw.get_mut().kill(); } } } impl TaskInstance { pub fn start(state: &mut State, task_ref: TaskRef) { { let mut task = task_ref.get_mut(); state.alloc_resources(&task.spec.resources); task.state = TaskState::Running; state.task_updated(&task_ref); } let task_fn = { let task = task_ref.get(); let task_type: &str = task.spec.task_type.as_ref(); match task_type { task_type if !task_type.starts_with("buildin/") => Self::start_task_in_executor, "buildin/run" => tasks::run::task_run, "buildin/concat" => tasks::basic::task_concat, "buildin/open" => tasks::basic::task_open, "buildin/export" => tasks::basic::task_export, "buildin/slice_directory" => tasks::basic::task_slice_directory, "buildin/make_directory" => tasks::basic::task_make_directory, "buildin/sleep" => tasks::basic::task_sleep, _ => fail_unknown_type, } }; let future: Box<TaskFuture> = match task_fn(state, task_ref.clone()) { Ok(f) => f, Err(e) => { state.unregister_task(&task_ref); let mut task = task_ref.get_mut(); state.free_resources(&task.spec.resources); task.set_failed(e.description().to_string()); state.task_updated(&task_ref); return; } }; let (sender, receiver) = ::futures::unsync::oneshot::channel::<()>(); let task_id = task_ref.get().spec.id; let instance = TaskInstance { task_ref: task_ref, cancel_sender: Some(sender), start_timestamp: Utc::now(), }; let state_ref = state.self_ref(); state.graph.running_tasks.insert(task_id, instance); state.spawn_panic_on_error( future .map(|()| true) .select(receiver.map(|()| false).map_err(|_| unreachable!())) .then(move |r| { let mut state = state_ref.get_mut(); let instance = state.graph.running_tasks.remove(&task_id).unwrap(); state.task_updated(&instance.task_ref); state.unregister_task(&instance.task_ref); let mut task = instance.task_ref.get_mut(); state.free_resources(&task.spec.resources); task.info.governor = format!("{}", state.governor_id()); task.info.start_time = instance.start_timestamp.to_rfc3339(); task.info.duration = Some( Utc::now() .signed_duration_since(instance.start_timestamp) .num_milliseconds() as f32 * 0.001f32, ); match r { Ok((true, _)) => { let all_finished = task.outputs.iter().all(|o| o.get().is_finished()); if !all_finished { task.set_failed("Some of outputs were not produced".into()); } else { for output in &task.outputs { state.object_is_finished(output); } log::debug!("Task was successfully finished"); task.state = TaskState::Finished; } } Ok((false, _)) => { log::debug!("Task {} was
random
[]
Rust
src/lua_tables.rs
perdumonocle/pm_rlua
eb09eba488249f47aaba4709a49108526f939a22
use std::marker::PhantomData; use libc; use td_clua::{self, lua_State}; use LuaGuard; use LuaPush; use LuaRead; pub struct LuaTable { table: *mut lua_State, pop: i32, index: i32, } impl LuaRead for LuaTable { fn lua_read_with_pop(lua: *mut lua_State, index: i32, pop: i32) -> Option<LuaTable> { if unsafe { td_clua::lua_istable(lua, index) } { for _ in 0..pop { unsafe { td_clua::lua_pushnil(lua); } } Some(LuaTable { table: lua, pop: pop, index: index, }) } else { None } } } impl Drop for LuaTable { fn drop(&mut self) { if self.pop != 0 { unsafe { td_clua::lua_pop(self.table, self.pop); }; self.pop = 0; } } } pub struct LuaTableIterator<'t, K, V> { table: &'t mut LuaTable, finished: bool, marker: PhantomData<(K, V)>, } impl LuaTable { pub fn into_inner(self) -> *mut lua_State { self.table } pub fn iter<K, V>(&mut self) -> LuaTableIterator<K, V> { unsafe { td_clua::lua_pushnil(self.table) }; LuaTableIterator { table: self, finished: false, marker: PhantomData, } } pub fn query<'a, R, I>(&'a mut self, index: I) -> Option<R> where R: LuaRead, I: LuaPush, { index.push_to_lua(self.table); unsafe { td_clua::lua_gettable( self.table, if self.index > 0 { self.index } else { self.index - 1 }, ); } let _guard = LuaGuard::new(self.table, 1); LuaRead::lua_read_with_pop(self.table, -1, 1) } pub fn set<I, V>(&mut self, index: I, value: V) where I: LuaPush, V: LuaPush, { index.push_to_lua(self.table); value.push_to_lua(self.table); unsafe { td_clua::lua_settable( self.table, if self.index > 0 { self.index } else { self.index - 2 }, ); } } pub fn register<I>(&mut self, index: I, func: extern "C" fn(*mut lua_State) -> libc::c_int) where I: LuaPush, { index.push_to_lua(self.table); unsafe { td_clua::lua_pushcfunction(self.table, func); td_clua::lua_settable( self.table, if self.index > 0 { self.index } else { self.index - 2 }, ); } } pub fn empty_table<I>(&mut self, index: I) -> LuaTable where I: LuaPush + Clone, { index.clone().push_to_lua(self.table); unsafe { td_clua::lua_newtable(self.table); td_clua::lua_settable( self.table, if self.index > 0 { self.index } else { self.index - 2 }, ); } self.query(index).unwrap() } pub fn table_len(&mut self) -> usize { unsafe { td_clua::lua_rawlen(self.table, self.index) } } pub fn get_or_create_metatable(&mut self) -> LuaTable { let result = unsafe { td_clua::lua_getmetatable(self.table, self.index) }; if result == 0 { unsafe { td_clua::lua_newtable(self.table); td_clua::lua_setmetatable(self.table, -2); let r = td_clua::lua_getmetatable(self.table, self.index); assert!(r != 0); } } LuaTable { table: self.table, pop: 1, index: -1, } } } impl<'t, K, V> Iterator for LuaTableIterator<'t, K, V> where K: LuaRead + 'static, V: LuaRead + 'static, { type Item = Option<(K, V)>; fn next(&mut self) -> Option<Option<(K, V)>> { if self.finished { return None; } let state = self.table.table; if unsafe { !td_clua::lua_istable(state, -2) || td_clua::lua_next(state, -2) == 0 } { self.finished = true; return None; } let key = LuaRead::lua_read_at_position(state, -2); let value = LuaRead::lua_read_at_position(state, -1); unsafe { td_clua::lua_pop(state, 1) }; if key.is_none() || value.is_none() { Some(None) } else { Some(Some((key.unwrap(), value.unwrap()))) } } } impl<'t, K, V> Drop for LuaTableIterator<'t, K, V> { fn drop(&mut self) { if !self.finished { unsafe { td_clua::lua_pop(self.table.table, 1) } } } }
use std::marker::PhantomData; use libc; use td_clua::{self, lua_State}; use LuaGuard; use LuaPush; use LuaRead; pub struct LuaTable { table: *mut lua_State, pop: i32, index: i32, } impl LuaRead for LuaTable { fn lua_read_with_pop(lua: *mut lua_State, index: i32, pop: i32) -> Option<LuaTable> { if unsafe { td_clua::lua_istable(lua, index) } { for _ in 0..pop { unsafe { td_clua::lua_pushnil(lua); } } Some(LuaTable { table: lua, pop: pop, index: index, }) } else { None } } } impl Drop for LuaTable { fn drop(&mut self) {
} } pub struct LuaTableIterator<'t, K, V> { table: &'t mut LuaTable, finished: bool, marker: PhantomData<(K, V)>, } impl LuaTable { pub fn into_inner(self) -> *mut lua_State { self.table } pub fn iter<K, V>(&mut self) -> LuaTableIterator<K, V> { unsafe { td_clua::lua_pushnil(self.table) }; LuaTableIterator { table: self, finished: false, marker: PhantomData, } } pub fn query<'a, R, I>(&'a mut self, index: I) -> Option<R> where R: LuaRead, I: LuaPush, { index.push_to_lua(self.table); unsafe { td_clua::lua_gettable( self.table, if self.index > 0 { self.index } else { self.index - 1 }, ); } let _guard = LuaGuard::new(self.table, 1); LuaRead::lua_read_with_pop(self.table, -1, 1) } pub fn set<I, V>(&mut self, index: I, value: V) where I: LuaPush, V: LuaPush, { index.push_to_lua(self.table); value.push_to_lua(self.table); unsafe { td_clua::lua_settable( self.table, if self.index > 0 { self.index } else { self.index - 2 }, ); } } pub fn register<I>(&mut self, index: I, func: extern "C" fn(*mut lua_State) -> libc::c_int) where I: LuaPush, { index.push_to_lua(self.table); unsafe { td_clua::lua_pushcfunction(self.table, func); td_clua::lua_settable( self.table, if self.index > 0 { self.index } else { self.index - 2 }, ); } } pub fn empty_table<I>(&mut self, index: I) -> LuaTable where I: LuaPush + Clone, { index.clone().push_to_lua(self.table); unsafe { td_clua::lua_newtable(self.table); td_clua::lua_settable( self.table, if self.index > 0 { self.index } else { self.index - 2 }, ); } self.query(index).unwrap() } pub fn table_len(&mut self) -> usize { unsafe { td_clua::lua_rawlen(self.table, self.index) } } pub fn get_or_create_metatable(&mut self) -> LuaTable { let result = unsafe { td_clua::lua_getmetatable(self.table, self.index) }; if result == 0 { unsafe { td_clua::lua_newtable(self.table); td_clua::lua_setmetatable(self.table, -2); let r = td_clua::lua_getmetatable(self.table, self.index); assert!(r != 0); } } LuaTable { table: self.table, pop: 1, index: -1, } } } impl<'t, K, V> Iterator for LuaTableIterator<'t, K, V> where K: LuaRead + 'static, V: LuaRead + 'static, { type Item = Option<(K, V)>; fn next(&mut self) -> Option<Option<(K, V)>> { if self.finished { return None; } let state = self.table.table; if unsafe { !td_clua::lua_istable(state, -2) || td_clua::lua_next(state, -2) == 0 } { self.finished = true; return None; } let key = LuaRead::lua_read_at_position(state, -2); let value = LuaRead::lua_read_at_position(state, -1); unsafe { td_clua::lua_pop(state, 1) }; if key.is_none() || value.is_none() { Some(None) } else { Some(Some((key.unwrap(), value.unwrap()))) } } } impl<'t, K, V> Drop for LuaTableIterator<'t, K, V> { fn drop(&mut self) { if !self.finished { unsafe { td_clua::lua_pop(self.table.table, 1) } } } }
if self.pop != 0 { unsafe { td_clua::lua_pop(self.table, self.pop); }; self.pop = 0; }
if_condition
[ { "content": "///\n\npub fn read_userdata<'t, T>(lua: *mut td_clua::lua_State, index: i32) -> Option<&'t mut T>\n\nwhere\n\n T: 'static + Any,\n\n{\n\n unsafe {\n\n let expected_typeid = format!(\"{:?}\", TypeId::of::<T>());\n\n let data_ptr = td_clua::lua_touserdata(lua, index);\n\n ...
Rust
tokens/src/tests_events.rs
ajuna-network/open-runtime-module-library
070457de18d26d2daed6abdfa57d8a951a525605
#![cfg(test)] use super::*; use frame_support::assert_ok; use mock::{Event, *}; #[test] fn pallet_multicurrency_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as MultiCurrency<AccountId>>::transfer(DOT, &ALICE, &BOB, 10)); System::assert_last_event(Event::Tokens(crate::Event::Transfer { currency_id: DOT, from: ALICE, to: BOB, amount: 10, })); assert_ok!(<Tokens as MultiCurrency<AccountId>>::deposit(DOT, &ALICE, 10)); System::assert_last_event(Event::Tokens(crate::Event::Deposited { currency_id: DOT, who: ALICE, amount: 10, })); assert_ok!(<Tokens as MultiCurrency<AccountId>>::withdraw(DOT, &ALICE, 10)); System::assert_last_event(Event::Tokens(crate::Event::Withdrawn { currency_id: DOT, who: ALICE, amount: 10, })); assert_ok!(<Tokens as MultiReservableCurrency<AccountId>>::reserve(DOT, &ALICE, 50)); assert_eq!(<Tokens as MultiCurrency<AccountId>>::slash(DOT, &ALICE, 60), 0); System::assert_last_event(Event::Tokens(crate::Event::Slashed { currency_id: DOT, who: ALICE, free_amount: 40, reserved_amount: 20, })); }); } #[test] fn pallet_multicurrency_extended_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as MultiCurrencyExtended<AccountId>>::update_balance( DOT, &ALICE, 500 )); System::assert_last_event(Event::Tokens(crate::Event::Deposited { currency_id: DOT, who: ALICE, amount: 500, })); assert_ok!(<Tokens as MultiCurrencyExtended<AccountId>>::update_balance( DOT, &ALICE, -500 )); System::assert_last_event(Event::Tokens(crate::Event::Withdrawn { currency_id: DOT, who: ALICE, amount: 500, })); }); } #[test] fn pallet_multi_lockable_currency_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as MultiLockableCurrency<AccountId>>::set_lock( [0u8; 8], DOT, &ALICE, 10 )); System::assert_last_event(Event::Tokens(crate::Event::LockSet { lock_id: [0u8; 8], currency_id: DOT, who: ALICE, amount: 10, })); assert_ok!(<Tokens as MultiLockableCurrency<AccountId>>::remove_lock( [0u8; 8], DOT, &ALICE )); System::assert_last_event(Event::Tokens(crate::Event::LockRemoved { lock_id: [0u8; 8], currency_id: DOT, who: ALICE, })); }); } #[test] fn pallet_multi_reservable_currency_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 1000), (BOB, DOT, 1000)]) .build() .execute_with(|| { assert_ok!(<Tokens as MultiReservableCurrency<AccountId>>::reserve( DOT, &ALICE, 500 )); System::assert_last_event(Event::Tokens(crate::Event::Reserved { currency_id: DOT, who: ALICE, amount: 500, })); assert_eq!( <Tokens as MultiReservableCurrency<AccountId>>::slash_reserved(DOT, &ALICE, 300), 0 ); System::assert_last_event(Event::Tokens(crate::Event::Slashed { currency_id: DOT, who: ALICE, free_amount: 0, reserved_amount: 300, })); assert_eq!( <Tokens as MultiReservableCurrency<AccountId>>::unreserve(DOT, &ALICE, 100), 0 ); System::assert_last_event(Event::Tokens(crate::Event::Unreserved { currency_id: DOT, who: ALICE, amount: 100, })); assert_ok!(<Tokens as MultiReservableCurrency<AccountId>>::repatriate_reserved( DOT, &ALICE, &BOB, 100, BalanceStatus::Free )); System::assert_last_event(Event::Tokens(crate::Event::ReserveRepatriated { currency_id: DOT, from: ALICE, to: BOB, amount: 100, status: BalanceStatus::Free, })); }); } #[test] fn pallet_fungibles_mutate_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as fungibles::Mutate<AccountId>>::mint_into(DOT, &ALICE, 500)); System::assert_last_event(Event::Tokens(crate::Event::Deposited { currency_id: DOT, who: ALICE, amount: 500, })); assert_ok!(<Tokens as fungibles::Mutate<AccountId>>::burn_from(DOT, &ALICE, 500)); System::assert_last_event(Event::Tokens(crate::Event::Withdrawn { currency_id: DOT, who: ALICE, amount: 500, })); }); } #[test] fn pallet_fungibles_transfer_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as fungibles::Transfer<AccountId>>::transfer( DOT, &ALICE, &BOB, 50, true )); System::assert_last_event(Event::Tokens(crate::Event::Transfer { currency_id: DOT, from: ALICE, to: BOB, amount: 50, })); }); } #[test] fn pallet_fungibles_unbalanced_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as MultiReservableCurrency<AccountId>>::reserve(DOT, &ALICE, 50)); assert_ok!(<Tokens as fungibles::Unbalanced<AccountId>>::set_balance( DOT, &ALICE, 500 )); System::assert_last_event(Event::Tokens(crate::Event::BalanceSet { currency_id: DOT, who: ALICE, free: 500, reserved: 50, })); <Tokens as fungibles::Unbalanced<AccountId>>::set_total_issuance(DOT, 1000); System::assert_last_event(Event::Tokens(crate::Event::TotalIssuanceSet { currency_id: DOT, amount: 1000, })); }); } #[test] fn pallet_fungibles_mutate_hold_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as fungibles::MutateHold<AccountId>>::hold(DOT, &ALICE, 50)); System::assert_last_event(Event::Tokens(crate::Event::Reserved { currency_id: DOT, who: ALICE, amount: 50, })); assert_ok!(<Tokens as fungibles::MutateHold<AccountId>>::transfer_held( DOT, &ALICE, &BOB, 50, true, true )); System::assert_last_event(Event::Tokens(crate::Event::ReserveRepatriated { currency_id: DOT, from: ALICE, to: BOB, amount: 50, status: BalanceStatus::Reserved, })); System::reset_events(); assert_eq!( <Tokens as fungibles::MutateHold<AccountId>>::release(DOT, &BOB, 50, true), Ok(50) ); System::assert_last_event(Event::Tokens(crate::Event::Unreserved { currency_id: DOT, who: BOB, amount: 50, })); }); } #[test] fn currency_adapter_pallet_currency_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100)]) .build() .execute_with(|| { std::mem::forget(<MockCurrencyAdapter as PalletCurrency<AccountId>>::burn(500)); System::assert_last_event(Event::Tokens(crate::Event::TotalIssuanceSet { currency_id: DOT, amount: 0, })); std::mem::forget(<MockCurrencyAdapter as PalletCurrency<AccountId>>::issue(200)); System::assert_last_event(Event::Tokens(crate::Event::TotalIssuanceSet { currency_id: DOT, amount: 200, })); assert_ok!(<MockCurrencyAdapter as PalletCurrency<AccountId>>::transfer( &ALICE, &BOB, 50, ExistenceRequirement::AllowDeath )); System::assert_last_event(Event::Tokens(crate::Event::Transfer { currency_id: DOT, from: ALICE, to: BOB, amount: 50, })); assert_ok!(<Tokens as MultiReservableCurrency<AccountId>>::reserve(DOT, &BOB, 50)); std::mem::forget(<MockCurrencyAdapter as PalletCurrency<AccountId>>::slash(&BOB, 110)); System::assert_last_event(Event::Tokens(crate::Event::Slashed { currency_id: DOT, who: BOB, free_amount: 100, reserved_amount: 10, })); std::mem::forget(<MockCurrencyAdapter as PalletCurrency<AccountId>>::make_free_balance_be(&BOB, 200)); System::assert_last_event(Event::Tokens(crate::Event::BalanceSet { currency_id: DOT, who: BOB, free: 200, reserved: 40, })); }); }
#![cfg(test)] use super::*; use frame_support::assert_ok; use mock::{Event, *}; #[test] fn pallet_multicurrency_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as MultiCurrency<AccountId>>::transfer(DOT, &ALICE, &BOB, 10)); System::assert_last_event(Event::Tokens(crate::Event::Transfer { currency_id: DOT, from: ALICE, to: BOB, amount: 10, })); assert_ok!(<Tokens as MultiCurrency<AccountId>>::deposit(DOT, &ALICE, 10)); System::assert_last_event(Event::Tokens(crate::Event::Deposited { currency_id: DOT, who: ALICE, amount: 10, })); assert_ok!(<Tokens as MultiCurrency<AccountId>>::withdraw(DOT, &ALICE, 10)); System::assert_last_event(Event::Tokens(crate::Event::Withdrawn { currency_id: DOT, who: ALICE, amount: 10, })); assert_ok!(<Tokens as MultiReservableCurrency<AccountId>>::reserve(DOT, &ALICE, 50)); assert_eq!(<Tokens as MultiCurrency<AccountId>>::slash(DOT, &ALICE, 60), 0); System::assert_last_event(Event::Tokens(crate::Event::Slashed { currency_id: DOT, who: ALICE, free_amount: 40, reserved_amount: 20, })); }); } #[test] fn pallet_multicurrency_extend
] fn pallet_fungibles_unbalanced_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as MultiReservableCurrency<AccountId>>::reserve(DOT, &ALICE, 50)); assert_ok!(<Tokens as fungibles::Unbalanced<AccountId>>::set_balance( DOT, &ALICE, 500 )); System::assert_last_event(Event::Tokens(crate::Event::BalanceSet { currency_id: DOT, who: ALICE, free: 500, reserved: 50, })); <Tokens as fungibles::Unbalanced<AccountId>>::set_total_issuance(DOT, 1000); System::assert_last_event(Event::Tokens(crate::Event::TotalIssuanceSet { currency_id: DOT, amount: 1000, })); }); } #[test] fn pallet_fungibles_mutate_hold_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as fungibles::MutateHold<AccountId>>::hold(DOT, &ALICE, 50)); System::assert_last_event(Event::Tokens(crate::Event::Reserved { currency_id: DOT, who: ALICE, amount: 50, })); assert_ok!(<Tokens as fungibles::MutateHold<AccountId>>::transfer_held( DOT, &ALICE, &BOB, 50, true, true )); System::assert_last_event(Event::Tokens(crate::Event::ReserveRepatriated { currency_id: DOT, from: ALICE, to: BOB, amount: 50, status: BalanceStatus::Reserved, })); System::reset_events(); assert_eq!( <Tokens as fungibles::MutateHold<AccountId>>::release(DOT, &BOB, 50, true), Ok(50) ); System::assert_last_event(Event::Tokens(crate::Event::Unreserved { currency_id: DOT, who: BOB, amount: 50, })); }); } #[test] fn currency_adapter_pallet_currency_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100)]) .build() .execute_with(|| { std::mem::forget(<MockCurrencyAdapter as PalletCurrency<AccountId>>::burn(500)); System::assert_last_event(Event::Tokens(crate::Event::TotalIssuanceSet { currency_id: DOT, amount: 0, })); std::mem::forget(<MockCurrencyAdapter as PalletCurrency<AccountId>>::issue(200)); System::assert_last_event(Event::Tokens(crate::Event::TotalIssuanceSet { currency_id: DOT, amount: 200, })); assert_ok!(<MockCurrencyAdapter as PalletCurrency<AccountId>>::transfer( &ALICE, &BOB, 50, ExistenceRequirement::AllowDeath )); System::assert_last_event(Event::Tokens(crate::Event::Transfer { currency_id: DOT, from: ALICE, to: BOB, amount: 50, })); assert_ok!(<Tokens as MultiReservableCurrency<AccountId>>::reserve(DOT, &BOB, 50)); std::mem::forget(<MockCurrencyAdapter as PalletCurrency<AccountId>>::slash(&BOB, 110)); System::assert_last_event(Event::Tokens(crate::Event::Slashed { currency_id: DOT, who: BOB, free_amount: 100, reserved_amount: 10, })); std::mem::forget(<MockCurrencyAdapter as PalletCurrency<AccountId>>::make_free_balance_be(&BOB, 200)); System::assert_last_event(Event::Tokens(crate::Event::BalanceSet { currency_id: DOT, who: BOB, free: 200, reserved: 40, })); }); }
ed_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as MultiCurrencyExtended<AccountId>>::update_balance( DOT, &ALICE, 500 )); System::assert_last_event(Event::Tokens(crate::Event::Deposited { currency_id: DOT, who: ALICE, amount: 500, })); assert_ok!(<Tokens as MultiCurrencyExtended<AccountId>>::update_balance( DOT, &ALICE, -500 )); System::assert_last_event(Event::Tokens(crate::Event::Withdrawn { currency_id: DOT, who: ALICE, amount: 500, })); }); } #[test] fn pallet_multi_lockable_currency_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as MultiLockableCurrency<AccountId>>::set_lock( [0u8; 8], DOT, &ALICE, 10 )); System::assert_last_event(Event::Tokens(crate::Event::LockSet { lock_id: [0u8; 8], currency_id: DOT, who: ALICE, amount: 10, })); assert_ok!(<Tokens as MultiLockableCurrency<AccountId>>::remove_lock( [0u8; 8], DOT, &ALICE )); System::assert_last_event(Event::Tokens(crate::Event::LockRemoved { lock_id: [0u8; 8], currency_id: DOT, who: ALICE, })); }); } #[test] fn pallet_multi_reservable_currency_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 1000), (BOB, DOT, 1000)]) .build() .execute_with(|| { assert_ok!(<Tokens as MultiReservableCurrency<AccountId>>::reserve( DOT, &ALICE, 500 )); System::assert_last_event(Event::Tokens(crate::Event::Reserved { currency_id: DOT, who: ALICE, amount: 500, })); assert_eq!( <Tokens as MultiReservableCurrency<AccountId>>::slash_reserved(DOT, &ALICE, 300), 0 ); System::assert_last_event(Event::Tokens(crate::Event::Slashed { currency_id: DOT, who: ALICE, free_amount: 0, reserved_amount: 300, })); assert_eq!( <Tokens as MultiReservableCurrency<AccountId>>::unreserve(DOT, &ALICE, 100), 0 ); System::assert_last_event(Event::Tokens(crate::Event::Unreserved { currency_id: DOT, who: ALICE, amount: 100, })); assert_ok!(<Tokens as MultiReservableCurrency<AccountId>>::repatriate_reserved( DOT, &ALICE, &BOB, 100, BalanceStatus::Free )); System::assert_last_event(Event::Tokens(crate::Event::ReserveRepatriated { currency_id: DOT, from: ALICE, to: BOB, amount: 100, status: BalanceStatus::Free, })); }); } #[test] fn pallet_fungibles_mutate_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as fungibles::Mutate<AccountId>>::mint_into(DOT, &ALICE, 500)); System::assert_last_event(Event::Tokens(crate::Event::Deposited { currency_id: DOT, who: ALICE, amount: 500, })); assert_ok!(<Tokens as fungibles::Mutate<AccountId>>::burn_from(DOT, &ALICE, 500)); System::assert_last_event(Event::Tokens(crate::Event::Withdrawn { currency_id: DOT, who: ALICE, amount: 500, })); }); } #[test] fn pallet_fungibles_transfer_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as fungibles::Transfer<AccountId>>::transfer( DOT, &ALICE, &BOB, 50, true )); System::assert_last_event(Event::Tokens(crate::Event::Transfer { currency_id: DOT, from: ALICE, to: BOB, amount: 50, })); }); } #[test
random
[ { "content": "fn concrete_fungible(amount: u128) -> MultiAsset {\n\n\t(MOCK_CONCRETE_FUNGIBLE_ID, amount).into()\n\n}\n\n\n", "file_path": "unknown-tokens/src/tests.rs", "rank": 0, "score": 182153.9216231135 }, { "content": "fn abstract_fungible(amount: u128) -> MultiAsset {\n\n\t(mock_abstr...
Rust
alvr/common/src/audio.rs
zarik5/ALVR
7ed89fc8525647d058fa812af8be88f23f8a17a0
use crate::*; #[cfg(windows)] use std::ptr; #[cfg(windows)] use widestring::*; #[cfg(windows)] use winapi::{ shared::{winerror::*, wtypes::VT_LPWSTR}, um::{ combaseapi::*, coml2api::STGM_READ, functiondiscoverykeys_devpkey::PKEY_Device_FriendlyName, mmdeviceapi::*, objbase::CoInitialize, propidl::PROPVARIANT, propsys::IPropertyStore, }, Class, Interface, }; #[cfg(windows)] use wio::com::ComPtr; #[derive(serde::Serialize)] pub struct AudioDevicesDesc { pub list: Vec<(String, String)>, pub default: Option<String>, } #[cfg(windows)] fn get_device_name(mm_device: ComPtr<IMMDevice>) -> StrResult<String> { unsafe { let mut property_store_ptr: *mut IPropertyStore = ptr::null_mut(); let hr = mm_device.OpenPropertyStore(STGM_READ, &mut property_store_ptr as _); if FAILED(hr) { return trace_str!("IMMDevice::OpenPropertyStore failed: hr = 0x{:08x}", hr); } let property_store = ComPtr::from_raw(property_store_ptr); let mut prop_variant = PROPVARIANT::default(); let hr = property_store.GetValue(&PKEY_Device_FriendlyName, &mut prop_variant); if FAILED(hr) { return trace_str!("IPropertyStore::GetValue failed: hr = 0x{:08x}", hr); } if prop_variant.vt as u32 != VT_LPWSTR { return trace_str!( "PKEY_Device_FriendlyName variant type is {} - expected VT_LPWSTR", prop_variant.vt ); } let res = trace_err!(U16CStr::from_ptr_str(*prop_variant.data.pwszVal()).to_string()); let hr = PropVariantClear(&mut prop_variant); if FAILED(hr) { return trace_str!("PropVariantClear failed: hr = 0x{:08x}", hr); } res } } #[cfg(windows)] fn get_audio_device_id_and_name(device: ComPtr<IMMDevice>) -> StrResult<(String, String)> { let id_str = unsafe { let mut id_str_ptr = ptr::null_mut(); device.GetId(&mut id_str_ptr); let id_str = trace_err!(U16CStr::from_ptr_str(id_str_ptr).to_string())?; CoTaskMemFree(id_str_ptr as _); id_str }; Ok((id_str, get_device_name(device)?)) } #[cfg(not(windows))] pub fn output_audio_devices() -> StrResult<AudioDevicesDesc> { todo!() } #[cfg(windows)] pub fn output_audio_devices() -> StrResult<AudioDevicesDesc> { let mut device_list = vec![]; unsafe { CoInitialize(ptr::null_mut()); let mut mm_device_enumerator_ptr: *mut IMMDeviceEnumerator = ptr::null_mut(); let hr = CoCreateInstance( &MMDeviceEnumerator::uuidof(), ptr::null_mut(), CLSCTX_ALL, &IMMDeviceEnumerator::uuidof(), &mut mm_device_enumerator_ptr as *mut _ as _, ); if FAILED(hr) { return trace_str!( "CoCreateInstance(IMMDeviceEnumerator) failed: hr = 0x{:08x}", hr ); } let mm_device_enumerator = ComPtr::from_raw(mm_device_enumerator_ptr); let mut default_mm_device_ptr: *mut IMMDevice = ptr::null_mut(); let hr = mm_device_enumerator.GetDefaultAudioEndpoint( eRender, eConsole, &mut default_mm_device_ptr as *mut _, ); if hr == HRESULT_FROM_WIN32(ERROR_NOT_FOUND) { return trace_str!("No default audio endpoint found. No audio device?"); } if FAILED(hr) { return trace_str!( "IMMDeviceEnumerator::GetDefaultAudioEndpoint failed: hr = 0x{:08x}", hr ); } let default_mm_device = ComPtr::from_raw(default_mm_device_ptr); let (default_id, default_name) = get_audio_device_id_and_name(default_mm_device)?; device_list.push((default_id.clone(), default_name.clone())); let mut mm_device_collection_ptr: *mut IMMDeviceCollection = ptr::null_mut(); let hr = mm_device_enumerator.EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &mut mm_device_collection_ptr as _, ); if FAILED(hr) { return trace_str!( "IMMDeviceEnumerator::EnumAudioEndpoints failed: hr = 0x{:08x}", hr ); } let mm_device_collection = ComPtr::from_raw(mm_device_collection_ptr); #[allow(unused_mut)] let mut count = 0; let hr = mm_device_collection.GetCount(&count); if FAILED(hr) { return trace_str!("IMMDeviceCollection::GetCount failed: hr = 0x{:08x}", hr); } debug!("Active render endpoints found: {}", count); debug!("DefaultDevice:{} ID:{}", default_name, default_id); for i in 0..count { let mut mm_device_ptr: *mut IMMDevice = ptr::null_mut(); let hr = mm_device_collection.Item(i, &mut mm_device_ptr as _); if FAILED(hr) { warn!("Crash!"); return trace_str!("IMMDeviceCollection::Item failed: hr = 0x{:08x}", hr); } let mm_device = ComPtr::from_raw(mm_device_ptr); let (id, name) = get_audio_device_id_and_name(mm_device)?; if id == default_id { continue; } debug!("Device{}:{} ID:{}", i, name, id); device_list.push((id, name)); } } let default = device_list.get(0).map(|dev| dev.0.clone()); let audio_devices_desc = AudioDevicesDesc { list: device_list, default, }; Ok(audio_devices_desc) }
use crate::*; #[cfg(windows)] use std::ptr; #[cfg(windows)] use widestring::*; #[cfg(windows)] use winapi::{ shared::{winerror::*, wtypes::VT_LPWSTR}, um::{ combaseapi::*, coml2api::STGM_READ, functiondiscoverykeys_devpkey::PKEY_Device_FriendlyName, mmdeviceapi::*, objbase::CoInitialize, propidl::PROPVARIANT, propsys::IPropertyStore, }, Class, Interface, }; #[cfg(windows)] use wio::com::ComPtr; #[derive(serde::Serialize)] pub struct AudioDevicesDesc { pub list: Vec<(String, String)>, pub default: Option<String>, } #[cfg(windows)] fn get_device_name(mm_device: ComPtr<IMMDevice>) -> StrResult<String> { unsafe { let mut property_store_ptr: *mut IPropertyStore = ptr::null_mut(); let hr = mm_device.OpenPropertyStore(STGM_READ, &mut property_store_ptr as _); if FAILED(hr) { return trace_str!("IMMDevice::OpenPropertyStore failed: hr = 0x{:08x}", hr); } let property_store = ComPtr::from_raw(property_store_ptr); let mut prop_variant = PROPVARIANT::default(); let hr = property_store.GetValue(&PKEY_Device_FriendlyName, &mut prop_variant); if FAILED(hr) { return trace_str!("IPropertyStore::GetValue failed: hr = 0x{:08x}", hr); } if prop_variant.vt as u32 != VT_LPWSTR { return trace_str!( "PKEY_Device_FriendlyName variant type is {} - expected VT_LPWSTR", prop_variant.vt ); } let res = trace_err!(U16CStr::from_ptr_str(*prop_variant.data.pwszVal()).to_string()); let hr = PropVariantClear(&mut prop_variant); if FAILED(hr) { return trace_str!("PropVariantClear failed: hr = 0x{:08x}", hr); } res } } #[cfg(windows)] fn get_audio_device_id_and_name(device: ComPtr<IMMDevice>) -> StrResult<(String, String)> { let id_str = unsafe { let mut id_str_ptr = ptr::null_mut(); device.GetId(&mut id_str_ptr); let id_str = trace_err!(U16CStr::from_ptr_str(id_str_ptr).to_string())?; CoTaskMemFree(id_str_ptr as _); id_str }; Ok((id_str, get_device_name(device)?)) } #[cfg(not(windows))] pub fn output_audio_devices() -> StrResult<AudioDevicesDesc> { todo!() } #[cfg(windows)] pub fn output_audio_devices() -> StrResult<AudioDevicesDesc> { let mut device_list = vec![]; unsafe { CoInitialize(ptr::null_mut()); let mut mm_device_enumerator_ptr: *mut IMMDeviceEnumerator = ptr::null_mut(); let hr = CoCreateInstance( &MMDeviceEnumerator::uuidof(), ptr::null_mut(), CLSCTX_ALL, &IMMDeviceEnumerator::uuidof(), &mut mm_device_enumerator_ptr as *mut _ as _, ); if FAILED(hr) { return trace_str!( "CoCreateInstance(IMMDeviceEnumerator) failed: hr = 0x{:08x}", hr ); } let mm_device_enumerator = ComPtr::from_raw(mm_device_enumerator_ptr); let mut default_mm_device_ptr: *mut IMMDevice = ptr::null_mut(); let hr = mm_device_enumerator.GetDefaultAudioEndpoint( eRender, eConsole, &mut default_mm_device_ptr as *mut _, ); if hr == HRESULT_FROM_WIN32(ERROR_NOT_FOUND) { return trace_str!("No default audio endpoint found. No audio device?"); } if FAILED(hr) { return trace_str!( "IMMDeviceEnumerator::GetDefaultAudioEndpoint failed: hr = 0x{:08x}", hr ); } let default_mm_device = ComPtr::from_raw(default_mm_device_ptr); let (default_id, default_name) = get_audio_device_id_and_name(default_mm_device)?; device_list.push((default_id.clone(), default_name.clone())); let mut mm_device_collection_ptr: *mut IMMDeviceCollection = ptr::null_mut(); let hr = mm_device_enumerator.EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &mut mm_device_collection_ptr as _, ); if FAILED(hr) { return trace_str!( "IMMDeviceEnumerator::EnumAudioEndpoints failed: hr = 0x{:08x}", hr ); } let mm_device_collection = ComPtr::from_raw(mm_device_collection_ptr); #[allow(unused_mut)] let mut count = 0;
let hr = mm_device_collection.GetCount(&count); if FAILED(hr) { return trace_str!("IMMDeviceCollection::GetCount failed: hr = 0x{:08x}", hr); } debug!("Active render endpoints found: {}", count); debug!("DefaultDevice:{} ID:{}", default_name, default_id); for i in 0..count { let mut mm_device_ptr: *mut IMMDevice = ptr::null_mut(); let hr = mm_device_collection.Item(i, &mut mm_device_ptr as _); if FAILED(hr) { warn!("Crash!"); return trace_str!("IMMDeviceCollection::Item failed: hr = 0x{:08x}", hr); } let mm_device = ComPtr::from_raw(mm_device_ptr); let (id, name) = get_audio_device_id_and_name(mm_device)?; if id == default_id { continue; } debug!("Device{}:{} ID:{}", i, name, id); device_list.push((id, name)); } } let default = device_list.get(0).map(|dev| dev.0.clone()); let audio_devices_desc = AudioDevicesDesc { list: device_list, default, }; Ok(audio_devices_desc) }
function_block-function_prefix_line
[ { "content": "#[cfg(windows)]\n\npub fn get_windows_device_id(device: &AudioDevice) -> StrResult<String> {\n\n unsafe {\n\n let mm_device = get_windows_device(device)?;\n\n\n\n let mut id_str_ptr = ptr::null_mut();\n\n mm_device.GetId(&mut id_str_ptr);\n\n let id_str = trace_err!(...
Rust
tests/tests.rs
zhiburt/bumpalo
38054c706cda77a07a07c3eda27bbeb6ee93a706
use bumpalo::Bump; use std::alloc::Layout; use std::mem; use std::usize; #[test] fn can_iterate_over_allocated_things() { let mut bump = Bump::new(); const MAX: u64 = 131_072; let mut chunk_ends = vec![]; let mut last = None; for i in 0..MAX { let this = bump.alloc(i); assert_eq!(*this, i); let this = this as *const _ as usize; if match last { Some(last) if last - mem::size_of::<u64>() == this => false, _ => true, } { let chunk_end = this + mem::size_of::<u64>(); println!("new chunk ending @ 0x{:x}", chunk_end); assert!( !chunk_ends.contains(&chunk_end), "should not have already allocated this chunk" ); chunk_ends.push(chunk_end); } last = Some(this); } let mut seen = vec![false; MAX as usize]; chunk_ends.reverse(); for ch in bump.iter_allocated_chunks() { let chunk_end = ch.as_ptr() as usize + ch.len(); println!("iter chunk ending @ {:#x}", chunk_end); assert_eq!( chunk_ends.pop().unwrap(), chunk_end, "should iterate over each chunk once, in order they were allocated in" ); let (before, mid, after) = unsafe { ch.align_to::<u64>() }; assert!(before.is_empty()); assert!(after.is_empty()); for i in mid { assert!(*i < MAX, "{} < {} (aka {:x} < {:x})", i, MAX, i, MAX); seen[*i as usize] = true; } } assert!(seen.iter().all(|s| *s)); } #[test] #[should_panic(expected = "out of memory")] fn oom_instead_of_bump_pointer_overflow() { let bump = Bump::new(); let x = bump.alloc(0_u8); let p = x as *mut u8 as usize; let size = usize::MAX - p + 1; let align = 1; let layout = match Layout::from_size_align(size, align) { Err(e) => { eprintln!("Layout::from_size_align errored: {}", e); return; } Ok(l) => l, }; bump.alloc_layout(layout); } #[test] fn force_new_chunk_fits_well() { let b = Bump::new(); b.alloc_layout(Layout::from_size_align(1, 1).unwrap()); b.alloc_layout(Layout::from_size_align(100_001, 1).unwrap()); b.alloc_layout(Layout::from_size_align(100_003, 1).unwrap()); } #[test] fn alloc_with_strong_alignment() { let b = Bump::new(); b.alloc_layout(Layout::from_size_align(4096, 64).unwrap()); } #[test] fn alloc_slice_copy() { let b = Bump::new(); let src: &[u16] = &[0xFEED, 0xFACE, 0xA7, 0xCAFE]; let dst = b.alloc_slice_copy(src); assert_eq!(src, dst); } #[test] fn alloc_slice_clone() { let b = Bump::new(); let src = vec![vec![0], vec![1, 2], vec![3, 4, 5], vec![6, 7, 8, 9]]; let dst = b.alloc_slice_clone(&src); assert_eq!(src, dst); } #[test] fn small_size_and_large_align() { let b = Bump::new(); let layout = std::alloc::Layout::from_size_align(1, 0x1000).unwrap(); b.alloc_layout(layout); } fn with_capacity_helper<I, T>(iter: I) where T: Copy + Eq, I: Clone + Iterator<Item = T>, { for &initial_size in &[0, 1, 8, 11, 0x1000, 0x12345] { let mut b = Bump::with_capacity(initial_size); for v in iter.clone() { b.alloc(v); } let pushed_values = b.iter_allocated_chunks().flat_map(|c| { let (before, mid, after) = unsafe { c.align_to::<T>() }; assert!(before.is_empty()); assert!(after.is_empty()); mid.iter().rev().copied() }); assert!(pushed_values.eq(iter.clone())); } } #[test] fn with_capacity_test() { with_capacity_helper(0u8..255); with_capacity_helper(0u16..10000); with_capacity_helper(0u32..10000); with_capacity_helper(0u64..10000); with_capacity_helper(0u128..10000); } #[test] fn test_reset() { let mut b = Bump::new(); for i in 0u64..10_000 { b.alloc(i); } assert!(b.iter_allocated_chunks().count() > 1); let last_chunk = b.iter_allocated_chunks().last().unwrap(); let start = last_chunk.as_ptr() as usize; let end = start + last_chunk.len(); dbg!((start, end)); b.reset(); assert_eq!(end - mem::size_of::<u64>(), b.alloc(0u64) as *const u64 as usize); assert_eq!(b.iter_allocated_chunks().count(), 1); }
use bumpalo::Bump; use std::alloc::Layout; use std::mem; use std::usize; #[test] fn can_iterate_over_allocated_things() { let mut bump = Bump::new(); const MAX: u64 = 131_072; let mut chunk_ends = vec![]; let mut last = None; for i in 0..MAX { let this = bump.alloc(i); assert_eq!(*this, i); let this = this as *const _ as usize; if match last { Some(last) if last - mem::size_of::<u64>() == this => false, _ => true, } { let chunk_end = this + mem::size_of::<u64>(); println!("new chunk ending @ 0x{:x}", chunk_end); assert!( !chunk_ends.contains(&chunk_end), "should not have already allocated this chunk" ); chunk_ends.push(chunk_end); } last = Some(this); } let mut seen = vec![false; MAX as usize]; chunk_ends.reverse(); for ch in bump.iter_allocated_chunks() { let chunk_end = ch.as_ptr() as usize + ch.len(); println!("iter chunk ending @ {:#x}", chunk_end); assert_eq!( chunk_ends.pop().unwrap(), chunk_end, "should iterate over each chunk once, in order they were allocated in" ); let (before, mid, after) = unsafe { ch.align_to::<u64>() }; assert!(before.is_empty()); assert!(after.is_empty()); for i in mid { assert!(*i < MAX, "{} < {} (aka {:x} < {:x})", i, MAX, i, MAX); seen[*i as usize] = true; } } assert!(seen.iter().all(|s| *s)); } #[test] #[should_panic(expected = "out of memory")] fn oom_instead_of_bump_pointer_overflow() { let bump = Bump::new(); let x = bump.alloc(0_u8); let p = x as *mut u8 as usize; let size = usize::MAX - p + 1; let align = 1; let layout = match Layout::from_size_al
().copied() }); assert!(pushed_values.eq(iter.clone())); } } #[test] fn with_capacity_test() { with_capacity_helper(0u8..255); with_capacity_helper(0u16..10000); with_capacity_helper(0u32..10000); with_capacity_helper(0u64..10000); with_capacity_helper(0u128..10000); } #[test] fn test_reset() { let mut b = Bump::new(); for i in 0u64..10_000 { b.alloc(i); } assert!(b.iter_allocated_chunks().count() > 1); let last_chunk = b.iter_allocated_chunks().last().unwrap(); let start = last_chunk.as_ptr() as usize; let end = start + last_chunk.len(); dbg!((start, end)); b.reset(); assert_eq!(end - mem::size_of::<u64>(), b.alloc(0u64) as *const u64 as usize); assert_eq!(b.iter_allocated_chunks().count(), 1); }
ign(size, align) { Err(e) => { eprintln!("Layout::from_size_align errored: {}", e); return; } Ok(l) => l, }; bump.alloc_layout(layout); } #[test] fn force_new_chunk_fits_well() { let b = Bump::new(); b.alloc_layout(Layout::from_size_align(1, 1).unwrap()); b.alloc_layout(Layout::from_size_align(100_001, 1).unwrap()); b.alloc_layout(Layout::from_size_align(100_003, 1).unwrap()); } #[test] fn alloc_with_strong_alignment() { let b = Bump::new(); b.alloc_layout(Layout::from_size_align(4096, 64).unwrap()); } #[test] fn alloc_slice_copy() { let b = Bump::new(); let src: &[u16] = &[0xFEED, 0xFACE, 0xA7, 0xCAFE]; let dst = b.alloc_slice_copy(src); assert_eq!(src, dst); } #[test] fn alloc_slice_clone() { let b = Bump::new(); let src = vec![vec![0], vec![1, 2], vec![3, 4, 5], vec![6, 7, 8, 9]]; let dst = b.alloc_slice_clone(&src); assert_eq!(src, dst); } #[test] fn small_size_and_large_align() { let b = Bump::new(); let layout = std::alloc::Layout::from_size_align(1, 0x1000).unwrap(); b.alloc_layout(layout); } fn with_capacity_helper<I, T>(iter: I) where T: Copy + Eq, I: Clone + Iterator<Item = T>, { for &initial_size in &[0, 1, 8, 11, 0x1000, 0x12345] { let mut b = Bump::with_capacity(initial_size); for v in iter.clone() { b.alloc(v); } let pushed_values = b.iter_allocated_chunks().flat_map(|c| { let (before, mid, after) = unsafe { c.align_to::<T>() }; assert!(before.is_empty()); assert!(after.is_empty()); mid.iter().rev
random
[ { "content": "fn size_align<T>() -> (usize, usize) {\n\n (mem::size_of::<T>(), mem::align_of::<T>())\n\n}\n\n\n\n/// The `AllocErr` error indicates an allocation failure\n\n/// that may be due to resource exhaustion or to\n\n/// something wrong when combining the given input arguments with this\n\n/// alloca...
Rust
artichoke-backend/src/convert/fixnum.rs
Talljoe/artichoke
36ed5eba078a9fbf3cb4d5c8f7407d0a773d2d6e
use std::convert::TryFrom; use crate::convert::{BoxIntoRubyError, UnboxRubyError}; use crate::core::{Convert, TryConvert}; use crate::exception::Exception; use crate::sys; use crate::types::{Int, Ruby, Rust}; use crate::value::Value; use crate::Artichoke; impl Convert<u8, Value> for Artichoke { #[inline] fn convert(&self, value: u8) -> Value { self.convert(Int::from(value)) } } impl Convert<u16, Value> for Artichoke { #[inline] fn convert(&self, value: u16) -> Value { self.convert(Int::from(value)) } } impl Convert<u32, Value> for Artichoke { #[inline] fn convert(&self, value: u32) -> Value { self.convert(Int::from(value)) } } impl TryConvert<u64, Value> for Artichoke { type Error = Exception; fn try_convert(&self, value: u64) -> Result<Value, Self::Error> { if let Ok(value) = Int::try_from(value) { let fixnum = unsafe { sys::mrb_sys_fixnum_value(value) }; Ok(Value::from(fixnum)) } else { Err(Exception::from(BoxIntoRubyError::new( Rust::UnsignedInt, Ruby::Fixnum, ))) } } } impl TryConvert<usize, Value> for Artichoke { type Error = Exception; fn try_convert(&self, value: usize) -> Result<Value, Self::Error> { if let Ok(value) = Int::try_from(value) { let fixnum = unsafe { sys::mrb_sys_fixnum_value(value) }; Ok(Value::from(fixnum)) } else { Err(Exception::from(BoxIntoRubyError::new( Rust::UnsignedInt, Ruby::Fixnum, ))) } } } impl Convert<i8, Value> for Artichoke { #[inline] fn convert(&self, value: i8) -> Value { self.convert(Int::from(value)) } } impl Convert<i16, Value> for Artichoke { #[inline] fn convert(&self, value: i16) -> Value { self.convert(Int::from(value)) } } impl Convert<i32, Value> for Artichoke { #[inline] fn convert(&self, value: i32) -> Value { self.convert(Int::from(value)) } } impl TryConvert<isize, Value> for Artichoke { type Error = Exception; fn try_convert(&self, value: isize) -> Result<Value, Self::Error> { if let Ok(value) = Int::try_from(value) { let fixnum = unsafe { sys::mrb_sys_fixnum_value(value) }; Ok(Value::from(fixnum)) } else { Err(Exception::from(BoxIntoRubyError::new( Rust::SignedInt, Ruby::Fixnum, ))) } } } impl Convert<Int, Value> for Artichoke { #[inline] fn convert(&self, value: Int) -> Value { let fixnum = unsafe { sys::mrb_sys_fixnum_value(value) }; Value::from(fixnum) } } impl TryConvert<Value, Int> for Artichoke { type Error = Exception; fn try_convert(&self, value: Value) -> Result<Int, Self::Error> { if let Ruby::Fixnum = value.ruby_type() { let inner = value.inner(); Ok(unsafe { sys::mrb_sys_fixnum_to_cint(inner) }) } else { Err(Exception::from(UnboxRubyError::new( &value, Rust::SignedInt, ))) } } } impl TryConvert<Value, u32> for Artichoke { type Error = Exception; fn try_convert(&self, value: Value) -> Result<u32, Self::Error> { if let Ruby::Fixnum = value.ruby_type() { let inner = value.inner(); let num = unsafe { sys::mrb_sys_fixnum_to_cint(inner) }; let num = u32::try_from(num).map_err(|_| UnboxRubyError::new(&value, Rust::UnsignedInt))?; Ok(num) } else { Err(Exception::from(UnboxRubyError::new( &value, Rust::SignedInt, ))) } } } impl TryConvert<Value, usize> for Artichoke { type Error = Exception; fn try_convert(&self, value: Value) -> Result<usize, Self::Error> { if let Ruby::Fixnum = value.ruby_type() { let inner = value.inner(); let num = unsafe { sys::mrb_sys_fixnum_to_cint(inner) }; let num = usize::try_from(num).map_err(|_| UnboxRubyError::new(&value, Rust::UnsignedInt))?; Ok(num) } else { Err(Exception::from(UnboxRubyError::new( &value, Rust::SignedInt, ))) } } } #[cfg(test)] mod tests { use quickcheck_macros::quickcheck; use crate::test::prelude::*; #[test] fn fail_convert() { let mut interp = crate::interpreter().unwrap(); let value = interp.eval(b"Object.new").unwrap(); let result = value.try_into::<Int>(&interp); assert!(result.is_err()); } #[quickcheck] fn convert_to_fixnum(i: Int) -> bool { let interp = crate::interpreter().unwrap(); let value = interp.convert(i); value.ruby_type() == Ruby::Fixnum } #[quickcheck] fn fixnum_with_value(i: Int) -> bool { let interp = crate::interpreter().unwrap(); let value = interp.convert(i); let inner = value.inner(); let cint = unsafe { sys::mrb_sys_fixnum_to_cint(inner) }; cint == i } #[quickcheck] fn roundtrip(i: Int) -> bool { let interp = crate::interpreter().unwrap(); let value = interp.convert(i); let value = value.try_into::<Int>(&interp).unwrap(); value == i } #[quickcheck] fn roundtrip_err(b: bool) -> bool { let interp = crate::interpreter().unwrap(); let value = interp.convert(b); let value = value.try_into::<Int>(&interp); value.is_err() } #[test] fn fixnum_to_usize() { let interp = crate::interpreter().unwrap(); let value = Convert::<_, Value>::convert(&interp, 100); let value = value.try_into::<usize>(&interp).unwrap(); assert_eq!(100, value); let value = Convert::<_, Value>::convert(&interp, -100); let value = value.try_into::<usize>(&interp); assert!(value.is_err()); } }
use std::convert::TryFrom; use crate::convert::{BoxIntoRubyError, UnboxRubyError}; use crate::core::{Convert, TryConvert}; use crate::exception::Exception; use crate::sys; use crate::types::{Int, Ruby, Rust}; use crate::value::Value; use crate::Artichoke; impl Convert<u8, Value> for Artichoke { #[inline] fn convert(&self, value: u8) -> Value { self.convert(Int::from(value)) } } impl Convert<u16, Value> for Artichoke { #[inline] fn convert(&self, value: u16) -> Value { self.convert(Int::from(value)) } } impl Convert<u32, Value> for Artichoke { #[inline] fn convert(&self, value: u32) -> Value { self.convert(Int::from(value)) } } impl TryConvert<u64, Value> for Artichoke { type Error = Exception; fn try_convert(&self, value: u64) -> Result<Value, Self::Error> { if let Ok(value) = Int::try_from(value) { let fixnum = unsafe { sys::mrb_sys_fixnum_value(value) }; Ok(Value::from(fixnum)) } else { Err(Exception::from(BoxIntoRubyError::new( Rust::UnsignedInt, Ruby::Fixnum, ))) } } } impl TryConvert<usize, Value> for Artichoke { type Error = Exception; fn try_convert(&self, value: usize) -> Result<Value, Self::Error> { if let Ok(value) = Int::try_from(value) { let fixnum = unsafe { sys::mrb_sys_fixnum_value(value) }; Ok(Value::from(fixnum)) } else { Err(Exception::from(BoxIntoRubyError::new( Rust::UnsignedInt, Ruby::Fixnum, ))) } } } impl Convert<i8, Value> for Artichoke { #[inline] fn convert(&self, value: i8) -> Value { self.convert(Int::from(value)) } } impl Convert<i16, Value> for Artichoke { #[inline] fn convert(&self, value: i16) -> Value { self.convert(Int::from(value)) } } impl Convert<i32, Value> for Artichoke { #[inline] fn convert(&self, value: i32) -> Value { self.convert(Int::from(value)) } } impl TryConvert<isize, Value> for Artichoke { type Error = Exception; fn try_convert(&self, value: isize) -> Result<Value, Self::Error> { if let Ok(value) = Int::try_from(value) { let fixnum = unsafe { sys::mrb_sys_fixnum_value(value) }; Ok(Value::from(fixnum)) } else { Err(Exception::from(BoxIntoRubyError::new( Rust::SignedInt, Ruby::Fixnum, ))) } } } impl Convert<Int, Value> for Artichoke { #[inline] fn convert(&self, value: Int) -> Value { let fixnum = unsafe { sys::mrb_sys_fixnum_value(value) }; Value::from(fixnum) } } impl TryConvert<Value, Int> for Artichoke { type Error = Exception; fn try_convert(&self, value: Value) -> Result<Int, Self::Error> { if let Ruby::Fixnum = value.ruby_type() { let inner = value.inner(); Ok(unsafe { sys::mrb_sys_fixnum_to_cint(inner) }) } else { Err(Exception::from(UnboxRubyError::new( &value, Rust::SignedInt, ))) } } } impl TryConvert<Value, u32> for Artichoke { type Error = Exception; fn try_convert(&self, value: Value) -> Result<u32, Self::Error> { if let Ruby::Fixnum = value.ruby_type() { let inner = value.inner(); let num = unsafe { sys::mrb_sys_fixnum_to_cint(inner) }; let num = u32::try_from(num).map_err(|_| UnboxRubyError::new(&value, Rust::UnsignedInt))?; Ok(num) } else { Err(Exception::from(UnboxRubyError::new( &value, Rust::SignedInt, ))) } } } impl TryConvert<Value, usize> for Artichoke { type Error = Exception; fn try_convert(&self, value: Value) -> Result<usize, Self::Error> { if let Ruby::Fixnum = value.ruby_type() { let inner = value.inner(); let num = unsafe { sys::mrb_sys_fixnum_to_cint(inner) }; let num = usize::try_from(num).map_err(|_| UnboxRubyError::new(&value, Rust::UnsignedInt))?; Ok(num) } else { Err(Exception::from(UnboxRubyError::new( &value, Rust::SignedInt, ))) } } } #[cfg(test)] mod tests { use quickcheck_macros::quickcheck; use crate::test::prelude::*; #[test] fn fail_convert() { let mut interp = crate::interpreter().unwrap(); let value = interp.eval(b"Object.new").unwrap(); let result = value.try_into::<Int>(&interp); assert!(result.is_err()); } #[quickcheck] fn convert_to_fixnum(i: Int) -> bool { let interp = crate::interpreter().unwrap(); let value = interp.convert(i); value.ruby_type() == Ruby::Fixnum } #[quickcheck] fn fixnum_with_value(i: Int) -> bool { let interp = crate::interpreter().unwrap(); let value = interp.convert(i); let inner = value.inner(); let cint = unsafe { sys::mrb_sys_fixnum_to_cint(inner) }; cint == i } #[quickcheck] fn roundtrip(i: Int) -> bool { let interp = crate::interpreter().unwrap(); let value = interp.convert(i); let value = value.try_into::<Int>(&interp).unwrap(); value == i } #[quickcheck] fn roundtrip_err(b: bool) -> bool { let interp = crate::interpreter().unwrap(); let value = interp.convert(b); let value = value.try_into::<Int>(&interp); value.is_err() } #[test]
}
fn fixnum_to_usize() { let interp = crate::interpreter().unwrap(); let value = Convert::<_, Value>::convert(&interp, 100); let value = value.try_into::<usize>(&interp).unwrap(); assert_eq!(100, value); let value = Convert::<_, Value>::convert(&interp, -100); let value = value.try_into::<usize>(&interp); assert!(value.is_err()); }
function_block-full_function
[ { "content": "#[cfg(feature = \"core-math-extra\")]\n\npub fn frexp(interp: &mut Artichoke, value: Value) -> Result<(Fp, Int), Exception> {\n\n let value = value_to_float(interp, value)?;\n\n let (fraction, exponent) = libm::frexp(value);\n\n Ok((fraction, exponent.into()))\n\n}\n\n\n", "file_path"...
Rust
garnet/bin/odu/src/file_target.rs
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
use { crate::common_operations::pwrite, crate::io_packet::{IoPacket, IoPacketType, TimeInterval}, crate::operations::{OperationType, PipelineStages}, crate::target::{Error, Target, TargetOps, TargetType}, log::debug, log::error, std::{ fs::{File, OpenOptions}, ops::Range, os::unix::io::AsRawFd, process, result::Result, sync::Arc, time::Instant, }, }; #[derive(Clone)] pub struct FileIoPacket { io_sequence_number: u64, seed: u64, stage_timestamps: [TimeInterval; PipelineStages::stage_count()], operation_type: OperationType, offset_range: Range<u64>, io_result: Option<Error>, target: TargetType, buffer: Vec<u8>, } impl FileIoPacket { pub fn new( operation_type: OperationType, io_sequence_number: u64, seed: u64, offset_range: Range<u64>, target: TargetType, ) -> FileIoPacket { let buffer = vec![0; offset_range.end as usize - offset_range.start as usize]; FileIoPacket { operation_type, io_sequence_number, seed, stage_timestamps: [TimeInterval::new(); PipelineStages::stage_count()], offset_range: offset_range.clone(), io_result: None, target, buffer, } } } impl IoPacket for FileIoPacket { fn operation_type(&self) -> OperationType { self.operation_type } fn timestamp_stage_start(&mut self, stage: PipelineStages) { self.stage_timestamps[stage.stage_number()].start(); } fn timestamp_stage_end(&mut self, stage: PipelineStages) { self.stage_timestamps[stage.stage_number()].end(); } fn sequence_number(&self) -> u64 { self.io_sequence_number } fn stage_timestamps(&self) -> &[TimeInterval; PipelineStages::stage_count()] { &self.stage_timestamps } fn interval_to_u64(&self, stage: PipelineStages) -> (u64, u64) { self.stage_timestamps[stage.stage_number()].interval_to_u64(&self.target.start_instant()) } fn io_offset_range(&self) -> Range<u64> { self.offset_range.clone() } fn do_io(&mut self) { self.target.clone().do_io(self) } fn is_complete(&self) -> bool { self.target.clone().is_complete(self) } fn verify_needs_io(&self) -> bool { self.target.clone().verify_needs_io(self) } fn generate_verify_io(&mut self) { self.target.clone().generate_verify_io(self) } fn verify(&mut self, verify_packet: &dyn IoPacket) -> bool { self.target.clone().verify(self, verify_packet) } fn get_error(&self) -> Result<(), Error> { match &self.io_result { Some(error) => Err(error.clone()), None => Ok(()), } } fn set_error(&mut self, io_error: Error) { self.io_result = Some(io_error); } fn buffer_mut(&mut self) -> &mut Vec<u8> { &mut self.buffer } fn buffer(&mut self) -> &Vec<u8> { &self.buffer } } pub struct FileBlockingTarget { #[allow(unused)] name: String, file: File, target_unique_id: u64, offset_range: Range<u64>, start_instant: Instant, } impl FileBlockingTarget { pub fn new( name: String, target_unique_id: u64, offset_range: Range<u64>, start_instant: Instant, ) -> TargetType { let file = OpenOptions::new().write(true).append(false).open(&name).unwrap(); Arc::new(Box::new(FileBlockingTarget { name, file, target_unique_id, offset_range, start_instant, })) } fn write(&self, io_packet: &mut dyn IoPacket) { let offset_range = io_packet.io_offset_range().clone(); if offset_range.start < self.offset_range.start || offset_range.end > self.offset_range.end { io_packet.set_error(Error::OffsetOutOfRange); return; } let raw_fd = self.file.as_raw_fd().clone(); let b = io_packet.buffer_mut(); let ret = pwrite(raw_fd, b, offset_range.start as i64); if let Err(err) = ret { return io_packet.set_error(err); } } fn open(&self, io_packet: &mut dyn IoPacket) { error!("open not yet supported {}", io_packet.sequence_number()); process::abort(); } fn exit(&self, io_packet: &mut dyn IoPacket) { debug!("Nothing to do for exit path {}", io_packet.sequence_number()); } } impl Target for FileBlockingTarget { fn setup(&mut self, _file_name: &String, _range: Range<u64>) -> Result<(), Error> { Ok(()) } fn create_io_packet( &self, operation_type: OperationType, seq: u64, seed: u64, io_offset_range: Range<u64>, target: TargetType, ) -> IoPacketType { Box::new(FileIoPacket::new(operation_type, seq, seed, io_offset_range, target)) } fn id(&self) -> u64 { self.target_unique_id } fn supported_ops() -> &'static TargetOps where Self: Sized, { &TargetOps { write: true, open: false } } fn allowed_ops() -> &'static TargetOps where Self: Sized, { &TargetOps { write: true, open: false } } fn do_io(&self, io_packet: &mut dyn IoPacket) { match io_packet.operation_type() { OperationType::Write => self.write(io_packet), OperationType::Open => self.open(io_packet), OperationType::Exit => self.exit(io_packet), _ => { error!("Unsupported operation"); process::abort(); } }; } fn is_complete(&self, io_packet: &dyn IoPacket) -> bool { match io_packet.operation_type() { OperationType::Write | OperationType::Open | OperationType::Exit => true, _ => { error!("Complete for unsupported operation"); process::abort(); } } } fn verify_needs_io(&self, io_packet: &dyn IoPacket) -> bool { match io_packet.operation_type() { OperationType::Write | OperationType::Open | OperationType::Exit => false, _ => { error!("verify_needs_io for unsupported operation"); process::abort(); } } } fn generate_verify_io(&self, io_packet: &mut dyn IoPacket) { match io_packet.operation_type() { _ => { error!("generate_verify_io for unsupported operation"); process::abort(); } }; } fn verify(&self, io_packet: &mut dyn IoPacket, _verify_packet: &dyn IoPacket) -> bool { match io_packet.operation_type() { OperationType::Write | OperationType::Exit => true, _ => { error!("verify for unsupported operation"); process::abort(); } } } fn start_instant(&self) -> Instant { self.start_instant } } #[cfg(test)] mod tests { use { crate::file_target::FileBlockingTarget, crate::operations::OperationType, crate::target::{Error, TargetType}, std::{fs, fs::File, time::Instant}, }; static FILE_LENGTH: u64 = 1 * 1024 * 1024; fn setup(file_name: &String) -> TargetType { let f = File::create(&file_name).unwrap(); f.set_len(FILE_LENGTH).unwrap(); let start_instant = Instant::now(); FileBlockingTarget::new(file_name.to_string(), 0, 0..FILE_LENGTH, start_instant) } fn teardown(file_name: &String) { fs::remove_file(file_name).unwrap(); } #[test] fn simple_write() { let file_name = "/tmp/odu-file_target-simple_write-file01".to_string(); let target = setup(&file_name); let mut io_packet = target.create_io_packet(OperationType::Write, 0, 0, 0..4096, target.clone()); let mut _buffer = io_packet.buffer_mut(); io_packet.do_io(); assert_eq!(io_packet.is_complete(), true); io_packet.get_error().unwrap(); teardown(&file_name); } #[test] fn write_failure() { let file_name = "/tmp/odu-file_target-write_failure-file01".to_string(); let target = setup(&file_name); let mut io_packet = target.create_io_packet( OperationType::Write, 0, 0, (2 * FILE_LENGTH)..(3 * FILE_LENGTH), target.clone(), ); let mut _buffer = io_packet.buffer_mut(); io_packet.do_io(); assert_eq!(io_packet.is_complete(), true); assert_eq!(io_packet.get_error().is_err(), true); assert_eq!(io_packet.get_error().err(), Some(Error::OffsetOutOfRange)); teardown(&file_name); } }
use { crate::common_operations::pwrite, crate::io_packet::{IoPacket, IoPacketType, TimeInterval}, crate::operations::{OperationType, PipelineStages}, crate::target::{Error, Target, TargetOps, TargetType}, log::debug, log::error, std::{ fs::{File, OpenOptions}, ops::Range, os::unix::io::AsRawFd, process, result::Result, sync::Arc, time::Instant, }, }; #[derive(Clone)] pub struct FileIoPacket { io_sequence_number: u64, seed: u64, stage_timestamps: [TimeInterval; PipelineStages::stage_count()], operation_type: OperationType, offset_range: Range<u64>, io_result: Option<Error>, target: TargetType, buffer: Vec<u8>, } impl FileIoPacket { pub fn new( operation_type: OperationType, io_sequence_number: u64, seed: u64, offset_range: Range<u64>, target: TargetType, ) -> FileIoPacket { let buffer = vec![0; offset_range.end as usize - offset_range.start as usize]; FileIoPacket { operation_type, io_sequence_number, seed, stage_timestamps: [TimeInterval::new(); PipelineStages::stage_count()], offset_range: offset_range.clone(), io_result: None, target, buffer, } } } impl IoPacket for FileIoPacket { fn operation_type(&self) -> OperationType { self.operation_type } fn timestamp_stage_start(&mut self, stage: PipelineStages) { self.stage_timestamps[stage.stage_number()].start(); } fn timestamp_stage_end(&mut self, stage: PipelineStages) { self.stage_timestamps[stage.stage_number()].end(); } fn sequence_number(&self) -> u64 { self.io_sequence_number } fn stage_timestamps(&self) -> &[TimeInterval; PipelineStages::stage_count()] { &self.stage_timestamps } fn interval_to_u64(&self, stage: PipelineStages) -> (u64, u64) { self.stage_timestamps[stage.stage_number()].interval_to_u64(&self.target.start_instant()) } fn io_offset_range(&self) -> Range<u64> { self.offset_range.clone() } fn do_io(&mut self) { self.target.clone().do_io(self) } fn is_complete(&self) -> bool { self.target.clone().is_complete(self) } fn verify_needs_io(&self) -> bool { self.target.clone().verify_needs_io(self) } fn generate_verify_io(&mut self) { self.target.clone().generate_verify_io(self) } fn verify(&mut self, verify_packet: &dyn IoPacket) -> bool { self.target.clone().verify(self, verify_packet) } fn get_error(&self) -> Result<(), Error> { match &self.io_result { Some(error) => Err(error.clone()), None => Ok(()), } } fn set_error(&mut self, io_error: Error) { self.io_result = Some(io_error); } fn buffer_mut(&mut self) -> &mut Vec<u8> { &mut self.buffer } fn buffer(&mut self) -> &Vec<u8> { &self.buffer } } pub struct FileBlockingTarget { #[allow(unused)] name: String, file: File, target_unique_id: u64, offset_range: Range<u64>, start_instant: Instant, } impl FileBlockingTarget { pub fn new( name: String, target_unique_id: u64, offset_range: Range<u64>, start_instant: Instant, ) -> TargetType { let file = OpenOptions::new().write(true).append(false).open(&name).unwrap(); Arc::new(Box::new(FileBlockingTarget { name, file, target_unique_id, offset_range, start_instant, })) } fn write(&self, io_packet: &mut dyn IoPacket) { let offset_range = io_packet.io_offset_range().clone(); if offset_range.start < self.offset_range.start || offset_range.end > self.offset_range.end { io_packet.set_error(Error::OffsetOutOfRange); return; } let raw_fd = self.file.as_raw_fd().clone(); let b = io_packet.buffer_mut(); let ret = pwrite(raw_fd, b, offset_range.start as i64); if let Err(err) = ret { return io_packet.set_error(err); } } fn open(&self, io_packet: &mut dyn IoPacket) { error!("open not yet supported {}", io_packet.sequence_number()); process::abort(); } fn exit(&self, io_packet: &mut dyn IoPacket) { debug!("Nothing to do for exit path {}", io_packet.sequence_number()); } } impl Target for FileBlockingTarget { fn setup(&mut self, _file_name: &String, _range: Range<u64>) -> Result<(), Error> { Ok(()) } fn create_io_packet( &self, operation_type: OperationType, seq: u64,
tionType::Write | OperationType::Exit => true, _ => { error!("verify for unsupported operation"); process::abort(); } } } fn start_instant(&self) -> Instant { self.start_instant } } #[cfg(test)] mod tests { use { crate::file_target::FileBlockingTarget, crate::operations::OperationType, crate::target::{Error, TargetType}, std::{fs, fs::File, time::Instant}, }; static FILE_LENGTH: u64 = 1 * 1024 * 1024; fn setup(file_name: &String) -> TargetType { let f = File::create(&file_name).unwrap(); f.set_len(FILE_LENGTH).unwrap(); let start_instant = Instant::now(); FileBlockingTarget::new(file_name.to_string(), 0, 0..FILE_LENGTH, start_instant) } fn teardown(file_name: &String) { fs::remove_file(file_name).unwrap(); } #[test] fn simple_write() { let file_name = "/tmp/odu-file_target-simple_write-file01".to_string(); let target = setup(&file_name); let mut io_packet = target.create_io_packet(OperationType::Write, 0, 0, 0..4096, target.clone()); let mut _buffer = io_packet.buffer_mut(); io_packet.do_io(); assert_eq!(io_packet.is_complete(), true); io_packet.get_error().unwrap(); teardown(&file_name); } #[test] fn write_failure() { let file_name = "/tmp/odu-file_target-write_failure-file01".to_string(); let target = setup(&file_name); let mut io_packet = target.create_io_packet( OperationType::Write, 0, 0, (2 * FILE_LENGTH)..(3 * FILE_LENGTH), target.clone(), ); let mut _buffer = io_packet.buffer_mut(); io_packet.do_io(); assert_eq!(io_packet.is_complete(), true); assert_eq!(io_packet.get_error().is_err(), true); assert_eq!(io_packet.get_error().err(), Some(Error::OffsetOutOfRange)); teardown(&file_name); } }
seed: u64, io_offset_range: Range<u64>, target: TargetType, ) -> IoPacketType { Box::new(FileIoPacket::new(operation_type, seq, seed, io_offset_range, target)) } fn id(&self) -> u64 { self.target_unique_id } fn supported_ops() -> &'static TargetOps where Self: Sized, { &TargetOps { write: true, open: false } } fn allowed_ops() -> &'static TargetOps where Self: Sized, { &TargetOps { write: true, open: false } } fn do_io(&self, io_packet: &mut dyn IoPacket) { match io_packet.operation_type() { OperationType::Write => self.write(io_packet), OperationType::Open => self.open(io_packet), OperationType::Exit => self.exit(io_packet), _ => { error!("Unsupported operation"); process::abort(); } }; } fn is_complete(&self, io_packet: &dyn IoPacket) -> bool { match io_packet.operation_type() { OperationType::Write | OperationType::Open | OperationType::Exit => true, _ => { error!("Complete for unsupported operation"); process::abort(); } } } fn verify_needs_io(&self, io_packet: &dyn IoPacket) -> bool { match io_packet.operation_type() { OperationType::Write | OperationType::Open | OperationType::Exit => false, _ => { error!("verify_needs_io for unsupported operation"); process::abort(); } } } fn generate_verify_io(&self, io_packet: &mut dyn IoPacket) { match io_packet.operation_type() { _ => { error!("generate_verify_io for unsupported operation"); process::abort(); } }; } fn verify(&self, io_packet: &mut dyn IoPacket, _verify_packet: &dyn IoPacket) -> bool { match io_packet.operation_type() { Opera
random
[]
Rust
src/raytracer/ray.rs
infinityb/rust-raytracer
4177c241c4630b822a308d982894134f0751d7d2
use std::f64::INFINITY; use raytracer::Intersection; use scene::Scene; use vec3::Vec3; #[cfg(test)] use geometry::prim::Prim; #[cfg(test)] use geometry::prims::Sphere; #[cfg(test)] use light::light::Light; #[cfg(test)] use material::materials::FlatMaterial; pub struct Ray { pub origin: Vec3, pub direction: Vec3, pub inverse_dir: Vec3, pub signs: [bool; 3], } impl Ray { pub fn new(origin: Vec3, direction: Vec3) -> Ray { let inv_x = 1.0 / direction.x; let inv_y = 1.0 / direction.y; let inv_z = 1.0 / direction.z; Ray { origin: origin, direction: direction, inverse_dir: Vec3 { x: inv_x, y: inv_y, z: inv_z }, signs: [ inv_x > 0.0, inv_y > 0.0, inv_z > 0.0 ] } } pub fn get_nearest_hit<'a>(&'a self, scene: &'a Scene) -> Option<Intersection<'a>> { let t_min = 0.000001; let mut nearest_hit = None; let mut nearest_t = INFINITY; for prim in scene.octree.intersect_iter(self) { let intersection = prim.intersects(self, t_min, nearest_t); nearest_hit = match intersection { Some(intersection) => { if intersection.t > t_min && intersection.t < nearest_t { nearest_t = intersection.t; Some(intersection) } else { nearest_hit } }, None => nearest_hit }; } nearest_hit } pub fn perturb(&self, magnitude: f64) -> Ray { let rand_vec = Vec3::random() * magnitude; let corrected_rand_vec = if rand_vec.dot(&self.direction) < 0.0 { rand_vec * -1.0 } else { rand_vec }; let direction = (corrected_rand_vec + self.direction).unit(); Ray::new(self.origin, direction) } } #[test] fn it_gets_the_nearest_hit() { let lights: Vec<Box<Light+Send+Sync>> = Vec::new(); let mut prims: Vec<Box<Prim+Send+Sync>> = Vec::new(); let mat = FlatMaterial { color: Vec3::one() }; let sphere_top = Sphere { center: Vec3::zero(), radius: 1.0, material: Box::new(mat.clone()), }; let sphere_mid = Sphere { center: Vec3 { x: -1.0, y: 0.0, z: 0.0 }, radius: 1.0, material: Box::new(mat.clone()), }; let sphere_bot = Sphere { center: Vec3 { x: -2.0, y: 0.0, z: 0.0 }, radius: 1.0, material: Box::new(mat.clone()), }; prims.push(Box::new(sphere_top)); prims.push(Box::new(sphere_mid)); prims.push(Box::new(sphere_bot)); println!("Generating octree..."); let octree = prims.into_iter().collect(); println!("Octree generated..."); let scene = Scene { lights: lights, background: Vec3::one(), octree: octree, skybox: None }; let intersecting_ray = Ray::new( Vec3 { x: 10.0, y: 0.0, z: 0.0 }, Vec3 { x: -1.0, y: 0.0, z: 0.0 } ); let intersection = intersecting_ray.get_nearest_hit(&scene); assert_eq!(1.0, intersection.unwrap().position.x); let non_intersecting_ray = Ray::new( Vec3 { x: 10.0, y: 0.0, z: 0.0 }, Vec3 { x: 1.0, y: 0.0, z: 0.0 }); let non_intersection = non_intersecting_ray.get_nearest_hit(&scene); assert!(non_intersection.is_none()); }
use std::f64::INFINITY; use raytracer::Intersection; use scene::Scene; use vec3::Vec3; #[cfg(test)] use geometry::prim::Prim; #[cfg(test)] use geometry::prims::Sphere; #[cfg(test)] use light::light::Light; #[cfg(test)] use material::materials::FlatMaterial; pub struct Ray { pub origin: Vec3, pub direction: Vec3, pub inverse_dir: Vec3, pub signs: [bool; 3], } impl Ray { pub fn new(origin: Vec3, direction: Vec3) -> Ray { let inv_x = 1.0 / direction.x; let inv_y = 1.0 / direction.y; let inv_z = 1.0 / direction.z; Ray { origin: origin, direction: direction, inverse_dir: Vec3 { x: inv_x, y: inv_y, z: inv_z }, signs: [ inv_x > 0.0, inv_y > 0.0, inv_z > 0.0 ] } } pub fn get_nearest_hit<'a>(&'a self, scene: &'a Scene) -> Option<Intersection<'a>> { let t_min = 0.000001; let mut nearest_hit = None; let mut nearest_t = INFINITY; for prim in scene.octree.intersect_iter(self) { let intersection = prim.intersects(self, t_min, nearest_t); nearest_hit = match intersection { Some(intersection) => { if intersection.t > t_min && intersection.t < nearest_t { nearest_t = intersection.t; Some(intersection) } else { nearest_hit } }, None => nearest_hit }; } nearest_hit } pub fn perturb(&self, magnitude: f64) -> Ray { let rand_vec = Vec3::random() * magnitude; let corrected_rand_vec = if rand_vec.dot(&self.direction) < 0.0 { rand_vec * -1.0 } else { rand_vec }; let direction = (corrected_rand_vec + self.direction).unit(); Ray::new(self.origin, direction) } } #[test]
fn it_gets_the_nearest_hit() { let lights: Vec<Box<Light+Send+Sync>> = Vec::new(); let mut prims: Vec<Box<Prim+Send+Sync>> = Vec::new(); let mat = FlatMaterial { color: Vec3::one() }; let sphere_top = Sphere { center: Vec3::zero(), radius: 1.0, material: Box::new(mat.clone()), }; let sphere_mid = Sphere { center: Vec3 { x: -1.0, y: 0.0, z: 0.0 }, radius: 1.0, material: Box::new(mat.clone()), }; let sphere_bot = Sphere { center: Vec3 { x: -2.0, y: 0.0, z: 0.0 }, radius: 1.0, material: Box::new(mat.clone()), }; prims.push(Box::new(sphere_top)); prims.push(Box::new(sphere_mid)); prims.push(Box::new(sphere_bot)); println!("Generating octree..."); let octree = prims.into_iter().collect(); println!("Octree generated..."); let scene = Scene { lights: lights, background: Vec3::one(), octree: octree, skybox: None }; let intersecting_ray = Ray::new( Vec3 { x: 10.0, y: 0.0, z: 0.0 }, Vec3 { x: -1.0, y: 0.0, z: 0.0 } ); let intersection = intersecting_ray.get_nearest_hit(&scene); assert_eq!(1.0, intersection.unwrap().position.x); let non_intersecting_ray = Ray::new( Vec3 { x: 10.0, y: 0.0, z: 0.0 }, Vec3 { x: 1.0, y: 0.0, z: 0.0 }); let non_intersection = non_intersecting_ray.get_nearest_hit(&scene); assert!(non_intersection.is_none()); }
function_block-full_function
[ { "content": "pub fn get_scene() -> Scene {\n\n let mut lights: Vec<Box<Light+Send+Sync>> = Vec::new();\n\n lights.push(Box::new(SphereLight { position: Vec3 { x: 8.0, y: 8.0, z: 0.0 }, color: Vec3 { x: 1.0, y: 0.8, z: 0.4}, radius: 0.5 }));\n\n lights.push(Box::new(SphereLight { position: Vec3 { x: 8....
Rust
relm4-examples/examples/grid_factory.rs
Hofer-Julian/relm4
bc8ea3f027a801126f767e93a3b04e20df4ca714
use gtk::prelude::{BoxExt, ButtonExt, GtkWindowExt}; use relm4::factory::{Factory, FactoryPrototype, FactoryVec, GridPosition}; use relm4::Sender; use relm4::*; struct AppWidgets { main: gtk::ApplicationWindow, gen_grid: gtk::Grid, } #[derive(Debug)] enum AppMsg { Add, Remove, Clicked(usize), } struct Data { counter: u8, } struct AppModel { data: FactoryVec<Data>, counter: u8, } impl Model for AppModel { type Msg = AppMsg; type Widgets = AppWidgets; type Components = (); } impl Widgets<AppModel, ()> for AppWidgets { type Root = gtk::ApplicationWindow; fn init_view(_model: &AppModel, _components: &(), sender: Sender<AppMsg>) -> Self { let main = gtk::ApplicationWindowBuilder::new() .default_width(300) .default_height(200) .build(); let main_box = gtk::Box::builder() .orientation(gtk::Orientation::Vertical) .margin_end(5) .margin_top(5) .margin_start(5) .margin_bottom(5) .spacing(5) .build(); let gen_grid = gtk::Grid::builder() .orientation(gtk::Orientation::Vertical) .margin_end(5) .margin_top(5) .margin_start(5) .margin_bottom(5) .row_spacing(5) .column_spacing(5) .column_homogeneous(true) .build(); let add = gtk::Button::with_label("Add"); let remove = gtk::Button::with_label("Remove"); main_box.append(&add); main_box.append(&remove); main_box.append(&gen_grid); main.set_child(Some(&main_box)); let cloned_sender = sender.clone(); add.connect_clicked(move |_| { cloned_sender.send(AppMsg::Add).unwrap(); }); remove.connect_clicked(move |_| { sender.send(AppMsg::Remove).unwrap(); }); AppWidgets { main, gen_grid } } fn view(&mut self, model: &AppModel, sender: Sender<AppMsg>) { model.data.generate(&self.gen_grid, sender); } fn root_widget(&self) -> gtk::ApplicationWindow { self.main.clone() } } impl AppUpdate for AppModel { fn update(&mut self, msg: AppMsg, _components: &(), _sender: Sender<AppMsg>) -> bool { match msg { AppMsg::Add => { self.data.push(Data { counter: self.counter, }); self.counter += 1; } AppMsg::Remove => { self.data.pop(); } AppMsg::Clicked(index) => { if let Some(data) = self.data.get_mut(index) { data.counter = data.counter.wrapping_sub(1); } } } true } } struct FactoryWidgets { button: gtk::Button, } impl FactoryPrototype for Data { type Factory = FactoryVec<Self>; type Widgets = FactoryWidgets; type Root = gtk::Button; type View = gtk::Grid; type Msg = AppMsg; fn generate(&self, index: &usize, sender: Sender<AppMsg>) -> FactoryWidgets { let button = gtk::Button::with_label(&self.counter.to_string()); let index = *index; button.connect_clicked(move |_| { sender.send(AppMsg::Clicked(index)).unwrap(); }); FactoryWidgets { button } } fn position(&self, index: &usize) -> GridPosition { let index = *index as i32; let row = index / 5; let column = (index % 5) * 2 + row % 2; GridPosition { column, row, width: 1, height: 1, } } fn update(&self, _index: &usize, widgets: &FactoryWidgets) { widgets.button.set_label(&self.counter.to_string()); } fn get_root(widgets: &FactoryWidgets) -> &gtk::Button { &widgets.button } } fn main() { let model = AppModel { data: FactoryVec::new(), counter: 0, }; let relm = RelmApp::new(model); relm.run(); }
use gtk::prelude::{BoxExt, ButtonExt, GtkWindowExt}; use relm4::factory::{Factory, FactoryPrototype, FactoryVec, GridPosition}; use relm4::Sender; use relm4::*; struct AppWidgets { main: gtk::ApplicationWindow, gen_grid: gtk::Grid, } #[derive(Debug)] enum AppMsg { Add, Remove, Clicked(usize), } struct Data { counter: u8, } struct AppModel { data: FactoryVec<Data>, counter: u8, } impl Model for AppModel { type Msg = AppMsg; type Widgets = AppWidgets; type Components = (); } impl Widgets<AppModel, ()> for AppWidgets { type Root = gtk::ApplicationWindow; fn init_view(_model: &AppModel, _components: &(), sender: Sender<AppMsg>) -> Self { let main = gtk::ApplicationWindowBuilder::new() .default_width(300) .default_height(200) .build(); let main_box = gtk::Box::builder() .orientation(gtk::Orientation::Vertical) .margin_end(5) .margin_top(5) .margin_start(5) .margin_bottom(5) .spacing(5) .build(); let gen_grid = gtk::Grid::builder() .orientation(gtk::Orientation::Vertical) .margin_end(5) .
fn view(&mut self, model: &AppModel, sender: Sender<AppMsg>) { model.data.generate(&self.gen_grid, sender); } fn root_widget(&self) -> gtk::ApplicationWindow { self.main.clone() } } impl AppUpdate for AppModel { fn update(&mut self, msg: AppMsg, _components: &(), _sender: Sender<AppMsg>) -> bool { match msg { AppMsg::Add => { self.data.push(Data { counter: self.counter, }); self.counter += 1; } AppMsg::Remove => { self.data.pop(); } AppMsg::Clicked(index) => { if let Some(data) = self.data.get_mut(index) { data.counter = data.counter.wrapping_sub(1); } } } true } } struct FactoryWidgets { button: gtk::Button, } impl FactoryPrototype for Data { type Factory = FactoryVec<Self>; type Widgets = FactoryWidgets; type Root = gtk::Button; type View = gtk::Grid; type Msg = AppMsg; fn generate(&self, index: &usize, sender: Sender<AppMsg>) -> FactoryWidgets { let button = gtk::Button::with_label(&self.counter.to_string()); let index = *index; button.connect_clicked(move |_| { sender.send(AppMsg::Clicked(index)).unwrap(); }); FactoryWidgets { button } } fn position(&self, index: &usize) -> GridPosition { let index = *index as i32; let row = index / 5; let column = (index % 5) * 2 + row % 2; GridPosition { column, row, width: 1, height: 1, } } fn update(&self, _index: &usize, widgets: &FactoryWidgets) { widgets.button.set_label(&self.counter.to_string()); } fn get_root(widgets: &FactoryWidgets) -> &gtk::Button { &widgets.button } } fn main() { let model = AppModel { data: FactoryVec::new(), counter: 0, }; let relm = RelmApp::new(model); relm.run(); }
margin_top(5) .margin_start(5) .margin_bottom(5) .row_spacing(5) .column_spacing(5) .column_homogeneous(true) .build(); let add = gtk::Button::with_label("Add"); let remove = gtk::Button::with_label("Remove"); main_box.append(&add); main_box.append(&remove); main_box.append(&gen_grid); main.set_child(Some(&main_box)); let cloned_sender = sender.clone(); add.connect_clicked(move |_| { cloned_sender.send(AppMsg::Add).unwrap(); }); remove.connect_clicked(move |_| { sender.send(AppMsg::Remove).unwrap(); }); AppWidgets { main, gen_grid } }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let model = AppModel {\n\n mode: AppMode::View,\n\n };\n\n let relm = RelmApp::new(model);\n\n relm.run();\n\n}\n", "file_path": "relm4-examples/examples/components.rs", "rank": 0, "score": 212890.8310617418 }, { "content": "fn main() {\n\n ...
Rust
src/elem/wrap/ymerge_wrap.rs
dbeck/minions_rs
b731c8c5c0e6f52013cb56f20a76ecccfe94dc7f
use lossyq::spsc::{Sender}; use super::super::super::{Task, Message, ChannelWrapper, ChannelId, SenderName, ReceiverChannelId, SenderChannelId, ChannelPosition }; use super::super::connectable::{ConnectableY}; use super::super::identified_input::{IdentifiedInput}; use super::super::counter::{OutputCounter, InputCounter}; use super::super::ymerge::{YMerge}; pub struct YMergeWrap<InputValueA: Send, InputErrorA: Send, InputValueB: Send, InputErrorB: Send, OutputValue: Send, OutputError: Send> { name : String, state : Box<YMerge<InputValueA=InputValueA, InputErrorA=InputErrorA, InputValueB=InputValueB, InputErrorB=InputErrorB, OutputValue=OutputValue, OutputError=OutputError>+Send>, input_a_rx : ChannelWrapper<InputValueA, InputErrorA>, input_b_rx : ChannelWrapper<InputValueB, InputErrorB>, output_tx : Sender<Message<OutputValue, OutputError>>, } pub fn new<InputValueA: Send, InputErrorA: Send, InputValueB: Send, InputErrorB: Send, OutputValue: Send, OutputError: Send>( name : String, state : Box<YMerge<InputValueA=InputValueA, InputErrorA=InputErrorA, InputValueB=InputValueB, InputErrorB=InputErrorB, OutputValue=OutputValue, OutputError=OutputError>+Send>, input_a_rx : ChannelWrapper<InputValueA, InputErrorA>, input_b_rx : ChannelWrapper<InputValueB, InputErrorB>, output_tx : Sender<Message<OutputValue, OutputError>>) -> YMergeWrap<InputValueA, InputErrorA, InputValueB, InputErrorB, OutputValue, OutputError> { YMergeWrap{ name: name, state: state, input_a_rx: input_a_rx, input_b_rx: input_b_rx, output_tx: output_tx } } impl<InputValueA: Send, InputErrorA: Send, InputValueB: Send, InputErrorB: Send, OutputValue: Send, OutputError: Send> IdentifiedInput for YMergeWrap<InputValueA, InputErrorA, InputValueB, InputErrorB, OutputValue, OutputError> { fn get_input_id(&self, ch_id: ReceiverChannelId) -> Option<(ChannelId, SenderName)> { if ch_id.0 > 1 { None } else if ch_id.0 == 0 { match &self.input_a_rx { &ChannelWrapper::ConnectedReceiver(ref channel_id, ref _receiver, ref sender_name) => { Some((*channel_id, sender_name.clone())) }, _ => None } } else { match &self.input_b_rx { &ChannelWrapper::ConnectedReceiver(ref channel_id, ref _receiver, ref sender_name) => { Some((*channel_id, sender_name.clone())) }, _ => None } } } } impl<InputValueA: Send, InputErrorA: Send, InputValueB: Send, InputErrorB: Send, OutputValue: Send, OutputError: Send> InputCounter for YMergeWrap<InputValueA, InputErrorA, InputValueB, InputErrorB, OutputValue, OutputError> { fn get_rx_count(&self, ch_id: ReceiverChannelId) -> usize { if ch_id.0 > 1 { 0 } else if ch_id.0 == 0 { match &self.input_a_rx { &ChannelWrapper::ConnectedReceiver(ref _channel_id, ref receiver, ref _sender_name) => { receiver.seqno() }, _ => 0 } } else { match &self.input_b_rx { &ChannelWrapper::ConnectedReceiver(ref _channel_id, ref receiver, ref _sender_name) => { receiver.seqno() }, _ => 0 } } } } impl<InputValueA: Send, InputErrorA: Send, InputValueB: Send, InputErrorB: Send, OutputValue: Send, OutputError: Send> OutputCounter for YMergeWrap<InputValueA, InputErrorA, InputValueB, InputErrorB, OutputValue, OutputError> { fn get_tx_count(&self, ch_id: SenderChannelId) -> usize { if ch_id.0 == 0 { self.output_tx.seqno() } else { 0 } } } impl<InputValueA: Send, InputErrorA: Send, InputValueB: Send, InputErrorB: Send, OutputValue: Send, OutputError: Send> ConnectableY for YMergeWrap<InputValueA, InputErrorA, InputValueB, InputErrorB, OutputValue, OutputError> { type InputValueA = InputValueA; type InputErrorA = InputErrorA; type InputValueB = InputValueB; type InputErrorB = InputErrorB; fn input_a(&mut self) -> &mut ChannelWrapper<InputValueA, InputErrorA> { &mut self.input_a_rx } fn input_b(&mut self) -> &mut ChannelWrapper<InputValueB, InputErrorB> { &mut self.input_b_rx } } impl<InputValueA: Send, InputErrorA: Send, InputValueB: Send, InputErrorB: Send, OutputValue: Send, OutputError: Send> Task for YMergeWrap<InputValueA, InputErrorA, InputValueB, InputErrorB, OutputValue, OutputError> { fn execute(&mut self, stop: &mut bool) { self.state.process(&mut self.input_a_rx, &mut self.input_b_rx, &mut self.output_tx, stop); } fn name(&self) -> &String { &self.name } fn input_count(&self) -> usize { 2 } fn output_count(&self) -> usize { 1 } fn input_id(&self, ch_id: ReceiverChannelId) -> Option<(ChannelId, SenderName)> { self.get_input_id(ch_id) } fn input_channel_pos(&self, ch_id: ReceiverChannelId) -> ChannelPosition { ChannelPosition( self.get_rx_count(ch_id) ) } fn output_channel_pos(&self, ch_id: SenderChannelId) -> ChannelPosition { ChannelPosition( self.get_tx_count(ch_id) ) } }
use lossyq::spsc::{Sender}; use super::super::super::{Task, Message, ChannelWrapper, ChannelId, SenderName, ReceiverChannelId, SenderChannelId, ChannelPosition }; use super::super::connectable::{ConnectableY}; use super::super::identified_input::{IdentifiedInput}; use super::super::counter::{OutputCounter, InputCounter}; use super::super::ymerge::{YMerge}; pub struct YMergeWrap<InputValueA: Send, InputErrorA: Send, InputValueB: Send, InputErrorB: Send, OutputValue: Send, OutputError: Send> { name : String, state : Box<YMerge<InputValueA=InputValueA, InputErrorA=InputErrorA, InputValueB=InputValueB, InputErrorB=InputErrorB, OutputValue=OutputValue, OutputError=OutputError>+Send>, input_a_rx : ChannelWrapper<InputValueA, InputErrorA>, input_b_rx : ChannelWrapper<InputValueB, InputErrorB>, output_tx : Sender<Message<OutputValue, OutputError>>, } pub fn new<InputValueA: Send, InputErrorA: Send, InputValueB: Send, InputErrorB: Send, OutputValue: Send, OutputError: Send>( name : String, state : Box<YMerge<InputValueA=InputValueA, InputErrorA=InputErrorA, InputValueB=InputValueB, InputErrorB=InputErrorB, OutputValue=OutputValue, OutputError=OutputError>+Send>, input_a_rx : ChannelWrapper<InputValueA, InputErrorA>, input_b_rx : ChannelWrapper<InputValueB, InputErrorB>, output_tx : Sender<Message<OutputValue, OutputError>>) -> YMergeWrap<InputValueA, InputErrorA, InputValueB, InputErrorB, OutputValue, OutputError> { YMergeWrap{ name: name, state: state, input_a_rx: input_a_rx, input_b_rx: input_b_rx, output_tx: output_tx } } impl<InputValueA: Send, InputErrorA: Send, InputValueB: Send, InputErrorB: Send, OutputValue: Send, OutputError: Send> IdentifiedInput for YMergeWrap<InputValueA, InputErrorA, InputValueB, InputErrorB, OutputValue, OutputError> { fn get_input_id(&self, ch_id: ReceiverChannelId) -> Option<(ChannelId, SenderName)> { if ch_id.0 > 1 { None } else if ch_id.0 == 0 { match &self.input_a_rx { &ChannelWrapper::ConnectedReceiver(ref channel_id, ref _receiver, ref sender_name) => { Some((*channel_id, sender_name.clone())) }, _ => None } } else { match &self.input_b_rx { &ChannelWrapper::ConnectedReceiver(ref channel_id, ref _receiver, ref sender_name) => { Some((*channel_id, sender_name.clone())) }, _ => None } } } } impl<InputValueA: Send, InputErrorA: Send, InputValueB: Send, InputErrorB: Send, OutputValue: Send, OutputError: Send> InputCounter for YMergeWrap<InputValueA, InputErrorA, InputValueB, InputErrorB, OutputValue, OutputError> { fn get_rx_count(&self, ch_id: ReceiverChannelId) -> usize { if ch_id.0 > 1 { 0 } else if ch_id.0 == 0 {
} else { match &self.input_b_rx { &ChannelWrapper::ConnectedReceiver(ref _channel_id, ref receiver, ref _sender_name) => { receiver.seqno() }, _ => 0 } } } } impl<InputValueA: Send, InputErrorA: Send, InputValueB: Send, InputErrorB: Send, OutputValue: Send, OutputError: Send> OutputCounter for YMergeWrap<InputValueA, InputErrorA, InputValueB, InputErrorB, OutputValue, OutputError> { fn get_tx_count(&self, ch_id: SenderChannelId) -> usize { if ch_id.0 == 0 { self.output_tx.seqno() } else { 0 } } } impl<InputValueA: Send, InputErrorA: Send, InputValueB: Send, InputErrorB: Send, OutputValue: Send, OutputError: Send> ConnectableY for YMergeWrap<InputValueA, InputErrorA, InputValueB, InputErrorB, OutputValue, OutputError> { type InputValueA = InputValueA; type InputErrorA = InputErrorA; type InputValueB = InputValueB; type InputErrorB = InputErrorB; fn input_a(&mut self) -> &mut ChannelWrapper<InputValueA, InputErrorA> { &mut self.input_a_rx } fn input_b(&mut self) -> &mut ChannelWrapper<InputValueB, InputErrorB> { &mut self.input_b_rx } } impl<InputValueA: Send, InputErrorA: Send, InputValueB: Send, InputErrorB: Send, OutputValue: Send, OutputError: Send> Task for YMergeWrap<InputValueA, InputErrorA, InputValueB, InputErrorB, OutputValue, OutputError> { fn execute(&mut self, stop: &mut bool) { self.state.process(&mut self.input_a_rx, &mut self.input_b_rx, &mut self.output_tx, stop); } fn name(&self) -> &String { &self.name } fn input_count(&self) -> usize { 2 } fn output_count(&self) -> usize { 1 } fn input_id(&self, ch_id: ReceiverChannelId) -> Option<(ChannelId, SenderName)> { self.get_input_id(ch_id) } fn input_channel_pos(&self, ch_id: ReceiverChannelId) -> ChannelPosition { ChannelPosition( self.get_rx_count(ch_id) ) } fn output_channel_pos(&self, ch_id: SenderChannelId) -> ChannelPosition { ChannelPosition( self.get_tx_count(ch_id) ) } }
match &self.input_a_rx { &ChannelWrapper::ConnectedReceiver(ref _channel_id, ref receiver, ref _sender_name) => { receiver.seqno() }, _ => 0 }
if_condition
[ { "content": "pub fn new<InputValueA: Send, InputErrorA: Send,\n\n InputValueB: Send, InputErrorB: Send,\n\n OutputValue: Send, OutputError: Send>(\n\n name : &str,\n\n output_q_size : usize,\n\n ymerge : Box<YMerge<InputValueA=InputValueA, InputErrorA=Input...
Rust
src/level1.rs
DGriffin91/Bevy-BakedGI-Demo
b919d7fe6e4b6a472e2a41ff25d94c1c40966ce9
use bevy::prelude::*; use crate::custom_material::{ CustomMaterial, MaterialProperties, MaterialSetProp, MaterialTexture, }; use crate::emissive_material::EmissiveMaterial; pub fn setup_room( commands: &mut Commands, custom_materials: &mut Assets<CustomMaterial>, emissive_materials: &mut Assets<EmissiveMaterial>, asset_server: &Res<AssetServer>, ) { let variation_texture = MaterialTexture::new(asset_server, "textures/detail.jpg", "variation_texture"); let base_texture = MaterialTexture::new(asset_server, "textures/concrete.jpg", "base_texture"); let walls_texture = MaterialTexture::new(asset_server, "textures/concrete3.jpg", "walls_texture"); let reflection_texture = MaterialTexture::new( asset_server, "textures/scene1/reflection.jpg", "reflection_texture", ); let objects_lightmap = MaterialTexture::new( asset_server, "textures/scene1/objects_lightmap.jpg", "objects_lightmap", ); let building_objects = asset_server.load("models/scene1/building.glb#Mesh0/Primitive0"); let material_properties = MaterialProperties { lightmap: MaterialSetProp { scale: 1.0, contrast: 1.8, brightness: 3.1, blend: 1.0, }, base_a: MaterialSetProp { scale: 8.5, contrast: 0.33, brightness: 2.0, blend: 1.0, }, base_b: MaterialSetProp { scale: 30.0, contrast: 0.3, brightness: 2.2, blend: 1.0, }, vary_a: MaterialSetProp { scale: 0.14, contrast: 0.77, brightness: 4.2, blend: 0.057, }, vary_b: MaterialSetProp { scale: 5.0, contrast: 0.14, brightness: 1.05, blend: 1.0, }, reflection: MaterialSetProp { scale: 1.0, contrast: 3.0, brightness: 0.115, blend: 1.0, }, walls: MaterialSetProp { scale: 10.5, contrast: 0.53, brightness: 1.6, blend: 1.0, }, reflection_mask: MaterialSetProp { scale: 0.033, contrast: 2.3, brightness: 40.0, blend: 1.0, }, mist: MaterialSetProp { scale: 0.032, contrast: 1.0, brightness: 1.0, blend: 0.567, }, directional_light_blend: 0.6, }; let material = custom_materials.add(CustomMaterial { material_properties, textures: [ objects_lightmap, base_texture.clone(), variation_texture.clone(), reflection_texture.clone(), walls_texture.clone(), ], }); commands.spawn().insert_bundle(MaterialMeshBundle { mesh: building_objects, transform: Transform::from_xyz(0.0, 0.0, 0.0), material, ..Default::default() }); let main_lightmap = MaterialTexture::new( asset_server, "textures/scene1/main_lightmap.jpg", "main_lightmap", ); let building_main = asset_server.load("models/scene1/building.glb#Mesh1/Primitive0"); let material = custom_materials.add(CustomMaterial { material_properties, textures: [ main_lightmap, base_texture, variation_texture, reflection_texture, walls_texture, ], }); commands.spawn().insert_bundle(MaterialMeshBundle { mesh: building_main, transform: Transform::from_xyz(0.0, 0.0, 0.0), material, ..Default::default() }); let skybox_texture = asset_server.load("textures/scene1/skybox.jpg"); let skybox = asset_server.load("models/scene1/skybox.glb#Mesh0/Primitive0"); commands.spawn().insert_bundle(MaterialMeshBundle { mesh: skybox, transform: Transform::from_xyz(0.0, 0.0, 0.0).with_scale(Vec3::new(10.0, 10.0, 10.0)), material: emissive_materials.add(EmissiveMaterial { emissive: Color::WHITE, emissive_texture: Some(skybox_texture), }), ..Default::default() }); let size: f32 = 50.0; commands.spawn_bundle(DirectionalLightBundle { directional_light: DirectionalLight { shadow_projection: OrthographicProjection { left: -size * 4.0, right: size * 2.0, bottom: -size * 2.0, top: size * 1.0, near: -size * 2.0, far: size * 1.0, ..Default::default() }, illuminance: 100000.0, shadows_enabled: true, ..Default::default() }, transform: Transform { translation: Vec3::new(0.0, 0.0, 0.0), rotation: Quat::from_euler( EulerRot::XYZ, (-14.0f32).to_radians(), -(192.0 - 180.0f32).to_radians(), 0.0, ), ..Default::default() }, ..Default::default() }); commands.spawn_bundle(PointLightBundle { transform: Transform::from_xyz(0.0, 5.0, 100.0), point_light: PointLight { intensity: 30000.0, range: 1000.0, radius: 100.0, color: Color::rgb(0.5, 0.45, 1.0), shadows_enabled: false, ..Default::default() }, ..Default::default() }); let lamp_locations = [ Vec3::new(-10.0, 17.0, -16.0), Vec3::new(10.0, 17.0, -16.0), ]; for lamp_loc in lamp_locations { commands.spawn_bundle(PointLightBundle { transform: Transform::from_xyz(lamp_loc.x, lamp_loc.y, lamp_loc.z), point_light: PointLight { intensity: 500.0, range: 1000.0, radius: 10.0, color: Color::rgb(1.0, 1.0, 1.0), shadows_enabled: false, ..Default::default() }, ..Default::default() }); } asset_server.watch_for_changes().unwrap(); }
use bevy::prelude::*; use crate::custom_material::{ CustomMaterial, MaterialProperties, MaterialSetProp, MaterialTexture, }; use crate::emissive_material::EmissiveMaterial; pub fn setup_room( commands: &mut Commands, custom_materials: &mut Assets<CustomMaterial>, emissive_materials: &mut Assets<EmissiveMaterial>, asset_server: &Res<AssetServer>, ) { let variation_texture = MaterialTexture::new(asset_server, "textures/detail.jpg", "variation_texture"); let base_texture = MaterialTexture::new(asset_server, "textures/concrete.jpg", "base_texture"); let walls_texture = MaterialTexture::new(asset_server, "textures/concrete3.jpg", "walls_texture");
let objects_lightmap = MaterialTexture::new( asset_server, "textures/scene1/objects_lightmap.jpg", "objects_lightmap", ); let building_objects = asset_server.load("models/scene1/building.glb#Mesh0/Primitive0"); let material_properties = MaterialProperties { lightmap: MaterialSetProp { scale: 1.0, contrast: 1.8, brightness: 3.1, blend: 1.0, }, base_a: MaterialSetProp { scale: 8.5, contrast: 0.33, brightness: 2.0, blend: 1.0, }, base_b: MaterialSetProp { scale: 30.0, contrast: 0.3, brightness: 2.2, blend: 1.0, }, vary_a: MaterialSetProp { scale: 0.14, contrast: 0.77, brightness: 4.2, blend: 0.057, }, vary_b: MaterialSetProp { scale: 5.0, contrast: 0.14, brightness: 1.05, blend: 1.0, }, reflection: MaterialSetProp { scale: 1.0, contrast: 3.0, brightness: 0.115, blend: 1.0, }, walls: MaterialSetProp { scale: 10.5, contrast: 0.53, brightness: 1.6, blend: 1.0, }, reflection_mask: MaterialSetProp { scale: 0.033, contrast: 2.3, brightness: 40.0, blend: 1.0, }, mist: MaterialSetProp { scale: 0.032, contrast: 1.0, brightness: 1.0, blend: 0.567, }, directional_light_blend: 0.6, }; let material = custom_materials.add(CustomMaterial { material_properties, textures: [ objects_lightmap, base_texture.clone(), variation_texture.clone(), reflection_texture.clone(), walls_texture.clone(), ], }); commands.spawn().insert_bundle(MaterialMeshBundle { mesh: building_objects, transform: Transform::from_xyz(0.0, 0.0, 0.0), material, ..Default::default() }); let main_lightmap = MaterialTexture::new( asset_server, "textures/scene1/main_lightmap.jpg", "main_lightmap", ); let building_main = asset_server.load("models/scene1/building.glb#Mesh1/Primitive0"); let material = custom_materials.add(CustomMaterial { material_properties, textures: [ main_lightmap, base_texture, variation_texture, reflection_texture, walls_texture, ], }); commands.spawn().insert_bundle(MaterialMeshBundle { mesh: building_main, transform: Transform::from_xyz(0.0, 0.0, 0.0), material, ..Default::default() }); let skybox_texture = asset_server.load("textures/scene1/skybox.jpg"); let skybox = asset_server.load("models/scene1/skybox.glb#Mesh0/Primitive0"); commands.spawn().insert_bundle(MaterialMeshBundle { mesh: skybox, transform: Transform::from_xyz(0.0, 0.0, 0.0).with_scale(Vec3::new(10.0, 10.0, 10.0)), material: emissive_materials.add(EmissiveMaterial { emissive: Color::WHITE, emissive_texture: Some(skybox_texture), }), ..Default::default() }); let size: f32 = 50.0; commands.spawn_bundle(DirectionalLightBundle { directional_light: DirectionalLight { shadow_projection: OrthographicProjection { left: -size * 4.0, right: size * 2.0, bottom: -size * 2.0, top: size * 1.0, near: -size * 2.0, far: size * 1.0, ..Default::default() }, illuminance: 100000.0, shadows_enabled: true, ..Default::default() }, transform: Transform { translation: Vec3::new(0.0, 0.0, 0.0), rotation: Quat::from_euler( EulerRot::XYZ, (-14.0f32).to_radians(), -(192.0 - 180.0f32).to_radians(), 0.0, ), ..Default::default() }, ..Default::default() }); commands.spawn_bundle(PointLightBundle { transform: Transform::from_xyz(0.0, 5.0, 100.0), point_light: PointLight { intensity: 30000.0, range: 1000.0, radius: 100.0, color: Color::rgb(0.5, 0.45, 1.0), shadows_enabled: false, ..Default::default() }, ..Default::default() }); let lamp_locations = [ Vec3::new(-10.0, 17.0, -16.0), Vec3::new(10.0, 17.0, -16.0), ]; for lamp_loc in lamp_locations { commands.spawn_bundle(PointLightBundle { transform: Transform::from_xyz(lamp_loc.x, lamp_loc.y, lamp_loc.z), point_light: PointLight { intensity: 500.0, range: 1000.0, radius: 10.0, color: Color::rgb(1.0, 1.0, 1.0), shadows_enabled: false, ..Default::default() }, ..Default::default() }); } asset_server.watch_for_changes().unwrap(); }
let reflection_texture = MaterialTexture::new( asset_server, "textures/scene1/reflection.jpg", "reflection_texture", );
assignment_statement
[ { "content": "fn player(commands: &mut Commands) {\n\n commands.spawn_bundle(UnrealCameraBundle::new(\n\n UnrealCameraController::default(),\n\n PerspectiveCameraBundle::default(),\n\n Vec3::new(-30.0, 3.0, -3.0),\n\n Vec3::new(0.0, 3.0, -3.0),\n\n ));\n\n}\n\n\n", "file_pa...
Rust
diesel/src/pg/expression/array_comparison.rs
robertmaloney/diesel
332ba12617ff05e5077fc1879caf83fe2e7fd8ff
use std::marker::PhantomData; use backend::*; use expression::{AsExpression, Expression, SelectableExpression, NonAggregate}; use pg::{Pg, PgQueryBuilder}; use query_builder::*; use query_builder::debug::DebugQueryBuilder; use result::QueryResult; use types::{Array, HasSqlType}; pub fn any<ST, T>(vals: T) -> Any<T::Expression, ST> where Pg: HasSqlType<ST>, T: AsExpression<Array<ST>>, { Any::new(vals.as_expression()) } pub fn all<ST, T>(vals: T) -> All<T::Expression, ST> where Pg: HasSqlType<ST>, T: AsExpression<Array<ST>>, { All::new(vals.as_expression()) } #[doc(hidden)] #[derive(Debug, Copy, Clone)] pub struct Any<Expr, ST> { expr: Expr, _marker: PhantomData<ST>, } impl<Expr, ST> Any<Expr, ST> { fn new(expr: Expr) -> Self { Any { expr: expr, _marker: PhantomData, } } } impl<Expr, ST> Expression for Any<Expr, ST> where Pg: HasSqlType<ST>, Expr: Expression<SqlType=Array<ST>>, { type SqlType = ST; } impl<Expr, ST> QueryFragment<Pg> for Any<Expr, ST> where Expr: QueryFragment<Pg>, { fn to_sql(&self, out: &mut PgQueryBuilder) -> BuildQueryResult { out.push_sql("ANY("); try!(self.expr.to_sql(out)); out.push_sql(")"); Ok(()) } fn collect_binds(&self, out: &mut <Pg as Backend>::BindCollector) -> QueryResult<()> { try!(self.expr.collect_binds(out)); Ok(()) } fn is_safe_to_cache_prepared(&self) -> bool { self.expr.is_safe_to_cache_prepared() } } impl<Expr, ST> QueryFragment<Debug> for Any<Expr, ST> where Expr: QueryFragment<Debug>, { fn to_sql(&self, out: &mut DebugQueryBuilder) -> BuildQueryResult { out.push_sql("ANY("); try!(self.expr.to_sql(out)); out.push_sql(")"); Ok(()) } fn collect_binds(&self, out: &mut <Debug as Backend>::BindCollector) -> QueryResult<()> { try!(self.expr.collect_binds(out)); Ok(()) } fn is_safe_to_cache_prepared(&self) -> bool { self.expr.is_safe_to_cache_prepared() } } impl_query_id!(Any<Expr, ST>); impl<Expr, ST, QS> SelectableExpression<QS> for Any<Expr, ST> where Pg: HasSqlType<ST>, Any<Expr, ST>: Expression, Expr: SelectableExpression<QS>, { } impl<Expr, ST> NonAggregate for Any<Expr, ST> where Expr: NonAggregate, Any<Expr, ST>: Expression, { } #[doc(hidden)] #[derive(Debug, Copy, Clone)] pub struct All<Expr, ST> { expr: Expr, _marker: PhantomData<ST>, } impl<Expr, ST> All<Expr, ST> { fn new(expr: Expr) -> Self { All { expr: expr, _marker: PhantomData, } } } impl<Expr, ST> Expression for All<Expr, ST> where Pg: HasSqlType<ST>, Expr: Expression<SqlType=Array<ST>>, { type SqlType = ST; } impl<Expr, ST> QueryFragment<Pg> for All<Expr, ST> where Expr: QueryFragment<Pg>, { fn to_sql(&self, out: &mut PgQueryBuilder) -> BuildQueryResult { out.push_sql("ALL("); try!(self.expr.to_sql(out)); out.push_sql(")"); Ok(()) } fn collect_binds(&self, out: &mut <Pg as Backend>::BindCollector) -> QueryResult<()> { try!(self.expr.collect_binds(out)); Ok(()) } fn is_safe_to_cache_prepared(&self) -> bool { self.expr.is_safe_to_cache_prepared() } } impl<Expr, ST> QueryFragment<Debug> for All<Expr, ST> where Expr: QueryFragment<Debug>, { fn to_sql(&self, out: &mut DebugQueryBuilder) -> BuildQueryResult { out.push_sql("ALL("); try!(self.expr.to_sql(out)); out.push_sql(")"); Ok(()) } fn collect_binds(&self, out: &mut <Debug as Backend>::BindCollector) -> QueryResult<()> { try!(self.expr.collect_binds(out)); Ok(()) } fn is_safe_to_cache_prepared(&self) -> bool { self.expr.is_safe_to_cache_prepared() } } impl_query_id!(All<Expr, ST>); impl<Expr, ST, QS> SelectableExpression<QS> for All<Expr, ST> where Pg: HasSqlType<ST>, All<Expr, ST>: Expression, Expr: SelectableExpression<QS>, { } impl<Expr, ST> NonAggregate for All<Expr, ST> where Expr: NonAggregate, All<Expr, ST>: Expression, { }
use std::marker::PhantomData; use backend::*; use expression::{AsExpression, Expression, SelectableExpression, NonAggregate}; use pg::{Pg, PgQueryBuilder}; use query_builder::*; use query_builder::debug::DebugQueryBuilder; use result::QueryResult; use types::{Array, HasSqlType}; pub fn any<ST, T>(vals: T) -> Any<T::Expression, ST> where Pg: HasSqlType<ST>, T: AsExpression<Array<ST>>, { Any::new(vals.as_expression()) } pub fn all<ST, T>(vals: T) -> All<T::Expression, ST> where Pg: HasSqlType<ST>, T: AsExpression<Array<ST>>, { All::new(vals.as_expression()) } #[doc(hidden)] #[derive(Debug, Copy, Clone)] pub struct Any<Expr, ST> { expr: Expr, _marker: PhantomData<ST>, } impl<Expr, ST> Any<Expr, ST> { fn new(expr: Expr) -> Self { Any { expr: expr, _marker: PhantomData, } } } impl<Expr, ST> Expression for Any<Expr, ST> where Pg: HasSqlType<ST>, Expr: Expression<SqlType=Array<ST>>, { type SqlType = ST; } impl<Expr, ST> QueryFragment<Pg> for Any<Expr, ST> where Expr: QueryFragment<Pg>, { fn to_sql(&self, out: &mut PgQueryBuilder) -> BuildQueryResult { out.push_sql("ANY("); try!(self.expr.to_sql(out)); out.push_sql(")"); Ok(()) } fn collect_binds(&self, out: &mut <Pg as Backend>::BindCollector) -> QueryResult<()> { try!(self.expr.collect_binds(out)); Ok(()) } fn is_safe_to_cache_prepared(&self) -> bool { self.expr.is_safe_to_cache_prepared() } } impl<Expr, ST> QueryFragment<Debug> for Any<Expr, ST> where Expr: QueryFragment<Debug>, { fn to_sql(&self, out: &mut DebugQueryBuilder) -> BuildQueryResult { out.push_sql("ANY("); try!(self.expr.to_sql(out)); out.push_sql(")"); Ok(()) } fn collect_binds(&self, out: &mut <Debug as Backend>::BindCollector) -> QueryResult<()> { try!(self.expr.collect_binds(out)); Ok(()) } fn is_safe_to_cache_prepared(&self) -> bool { self.expr.is_safe_to_cache_prepared() } }
QS>, { } impl<Expr, ST> NonAggregate for Any<Expr, ST> where Expr: NonAggregate, Any<Expr, ST>: Expression, { } #[doc(hidden)] #[derive(Debug, Copy, Clone)] pub struct All<Expr, ST> { expr: Expr, _marker: PhantomData<ST>, } impl<Expr, ST> All<Expr, ST> { fn new(expr: Expr) -> Self { All { expr: expr, _marker: PhantomData, } } } impl<Expr, ST> Expression for All<Expr, ST> where Pg: HasSqlType<ST>, Expr: Expression<SqlType=Array<ST>>, { type SqlType = ST; } impl<Expr, ST> QueryFragment<Pg> for All<Expr, ST> where Expr: QueryFragment<Pg>, { fn to_sql(&self, out: &mut PgQueryBuilder) -> BuildQueryResult { out.push_sql("ALL("); try!(self.expr.to_sql(out)); out.push_sql(")"); Ok(()) } fn collect_binds(&self, out: &mut <Pg as Backend>::BindCollector) -> QueryResult<()> { try!(self.expr.collect_binds(out)); Ok(()) } fn is_safe_to_cache_prepared(&self) -> bool { self.expr.is_safe_to_cache_prepared() } } impl<Expr, ST> QueryFragment<Debug> for All<Expr, ST> where Expr: QueryFragment<Debug>, { fn to_sql(&self, out: &mut DebugQueryBuilder) -> BuildQueryResult { out.push_sql("ALL("); try!(self.expr.to_sql(out)); out.push_sql(")"); Ok(()) } fn collect_binds(&self, out: &mut <Debug as Backend>::BindCollector) -> QueryResult<()> { try!(self.expr.collect_binds(out)); Ok(()) } fn is_safe_to_cache_prepared(&self) -> bool { self.expr.is_safe_to_cache_prepared() } } impl_query_id!(All<Expr, ST>); impl<Expr, ST, QS> SelectableExpression<QS> for All<Expr, ST> where Pg: HasSqlType<ST>, All<Expr, ST>: Expression, Expr: SelectableExpression<QS>, { } impl<Expr, ST> NonAggregate for All<Expr, ST> where Expr: NonAggregate, All<Expr, ST>: Expression, { }
impl_query_id!(Any<Expr, ST>); impl<Expr, ST, QS> SelectableExpression<QS> for Any<Expr, ST> where Pg: HasSqlType<ST>, Any<Expr, ST>: Expression, Expr: SelectableExpression<
random
[ { "content": "pub trait ArrayExpressionMethods<ST>: Expression<SqlType=Array<ST>> + Sized {\n\n /// Compares two arrays for common elements, using the `&&` operator in\n\n /// the final SQL\n\n ///\n\n /// # Example\n\n ///\n\n /// ```rust\n\n /// # #[macro_use] extern crate diesel;\n\n ...
Rust
components/zcash_address/src/kind/unified/f4jumble.rs
MixinNetwork/librustzcash
9be36f3e54127fc2e6a30a70625eddfb12367d40
use blake2b_simd::{Params as Blake2bParams, OUTBYTES}; use std::cmp::min; use std::ops::RangeInclusive; #[cfg(test)] mod test_vectors; const VALID_LENGTH: RangeInclusive<usize> = 48..=16448; macro_rules! H_PERS { ( $i:expr ) => { [ 85, 65, 95, 70, 52, 74, 117, 109, 98, 108, 101, 95, 72, 95, $i, 0, ] }; } macro_rules! G_PERS { ( $i:expr, $j:expr ) => { [ 85, 65, 95, 70, 52, 74, 117, 109, 98, 108, 101, 95, 71, 95, $i, $j, ] }; } struct Hashes { l_l: usize, l_r: usize, } impl Hashes { fn new(message_length: usize) -> Self { let l_l = min(OUTBYTES, message_length / 2); let l_r = message_length - l_l; Hashes { l_l, l_r } } fn h(&self, i: u8, u: &[u8]) -> Vec<u8> { Blake2bParams::new() .hash_length(self.l_l) .personal(&H_PERS!(i)) .hash(&u) .as_ref() .to_vec() } fn g(&self, i: u8, u: &[u8]) -> Vec<u8> { (0..ceildiv(self.l_r, OUTBYTES)) .flat_map(|j| { Blake2bParams::new() .hash_length(OUTBYTES) .personal(&G_PERS!(i, j as u8)) .hash(u) .as_ref() .to_vec() .into_iter() }) .take(self.l_r) .collect() } } fn xor(a: &[u8], b: &[u8]) -> Vec<u8> { a.iter().zip(b.iter()).map(|(a0, b0)| a0 ^ b0).collect() } fn ceildiv(num: usize, den: usize) -> usize { (num + den - 1) / den } #[allow(clippy::many_single_char_names)] pub fn f4jumble(a: &[u8]) -> Option<Vec<u8>> { if VALID_LENGTH.contains(&a.len()) { let hashes = Hashes::new(a.len()); let (a, b) = a.split_at(hashes.l_l); let x = xor(b, &hashes.g(0, a)); let y = xor(a, &hashes.h(0, &x)); let d = xor(&x, &hashes.g(1, &y)); let mut c = xor(&y, &hashes.h(1, &d)); c.extend(d); Some(c) } else { None } } #[allow(clippy::many_single_char_names)] pub fn f4jumble_inv(c: &[u8]) -> Option<Vec<u8>> { if VALID_LENGTH.contains(&c.len()) { let hashes = Hashes::new(c.len()); let (c, d) = c.split_at(hashes.l_l); let y = xor(c, &hashes.h(1, d)); let x = xor(d, &hashes.g(1, &y)); let mut a = xor(&y, &hashes.h(0, &x)); let b = xor(&x, &hashes.g(0, &a)); a.extend(b); Some(a) } else { None } } #[cfg(test)] mod tests { use proptest::collection::vec; use proptest::prelude::*; use super::{f4jumble, f4jumble_inv, test_vectors::test_vectors, VALID_LENGTH}; #[test] fn h_pers() { assert_eq!(&H_PERS!(7), b"UA_F4Jumble_H_\x07\x00"); } #[test] fn g_pers() { assert_eq!(&G_PERS!(7, 13), b"UA_F4Jumble_G_\x07\x0d"); } proptest! { #[test] fn f4jumble_roundtrip(msg in vec(any::<u8>(), VALID_LENGTH)) { let jumbled = f4jumble(&msg).unwrap(); let jumbled_len = jumbled.len(); prop_assert_eq!( msg.len(), jumbled_len, "Jumbled length {} was not equal to message length {}", jumbled_len, msg.len() ); let unjumbled = f4jumble_inv(&jumbled).unwrap(); prop_assert_eq!( jumbled_len, unjumbled.len(), "Unjumbled length {} was not equal to jumbled length {}", unjumbled.len(), jumbled_len ); prop_assert_eq!(msg, unjumbled, "Unjumbled message did not match original message."); } } #[test] fn f4jumble_check_vectors() { for v in test_vectors() { let jumbled = f4jumble(&v.normal).unwrap(); assert_eq!(jumbled, v.jumbled); let unjumbled = f4jumble_inv(&v.jumbled).unwrap(); assert_eq!(unjumbled, v.normal); } } }
use blake2b_simd::{Params as Blake2bParams, OUTBYTES}; use std::cmp::min; use std::ops::RangeInclusive; #[cfg(test)] mod test_vectors; const VALID_LENGTH: RangeInclusive<usize> = 48..=16448; macro_rules! H_PERS { ( $i:expr ) => { [ 85, 65, 95, 70, 52, 74, 117, 109, 98, 108, 101, 95, 72, 95, $i, 0, ] }; } macro_rules! G_PERS { ( $i:expr, $j:expr ) => { [ 85, 65, 95, 70, 52, 74, 117, 109, 98, 108, 101, 95, 71, 95, $i, $j, ] }; } struct Hashes { l_l: usize, l_r: usize, } impl Hashes { fn new(message_length: usize) -> Self { let l_l = min(OUTBYTES, message_length / 2); let l_r = message_length - l_l; Hashes { l_l, l_r } } fn h(&self, i: u8, u: &[u8]) -> Vec<u8> { Blake2bParams::new() .hash_length(self.l_l) .personal(&H_PERS!(i)) .hash(&u) .as_ref() .to_vec() } fn g(&self, i: u8, u: &[u8]) -> Vec<u8> { (0..ceildiv(self.l_r, OUTBYTES)) .flat_map(|j| { Blake2bParams::new() .hash_length(OUTBYTES) .personal(&G_PERS!(i, j as u8)) .hash(u) .as_ref() .to_vec() .into_iter() }) .take(self.l_r) .collect() } } fn xor(a: &[u8], b: &[u8]) -> Vec<u8> { a.iter().zip(b.iter()).map(|(a0, b0)| a0 ^ b0).collect() } fn ceildiv(num: usize, den: usize) -> usize { (num + den - 1) / den } #[allow(clippy::many_single_char_names)] pub fn f4jumble(a: &[u8]) -> Option<Vec<u8>> { if VALID_LENGTH.contains(&a.len()) { let hashes = Hashes::new(a.len()); let (a, b) = a.split_at(hashes.l_l); let x = xor(b, &hashes.g(0, a)); let y = xor(a, &hashes.h(0, &x)); let d = xor(&x, &hashes.g(1, &y)); let mut c = xor(&y, &hashes.h(1, &d)); c.extend(d); Some(c) } else { None } } #[allow(clippy::many_single_char_names)]
#[cfg(test)] mod tests { use proptest::collection::vec; use proptest::prelude::*; use super::{f4jumble, f4jumble_inv, test_vectors::test_vectors, VALID_LENGTH}; #[test] fn h_pers() { assert_eq!(&H_PERS!(7), b"UA_F4Jumble_H_\x07\x00"); } #[test] fn g_pers() { assert_eq!(&G_PERS!(7, 13), b"UA_F4Jumble_G_\x07\x0d"); } proptest! { #[test] fn f4jumble_roundtrip(msg in vec(any::<u8>(), VALID_LENGTH)) { let jumbled = f4jumble(&msg).unwrap(); let jumbled_len = jumbled.len(); prop_assert_eq!( msg.len(), jumbled_len, "Jumbled length {} was not equal to message length {}", jumbled_len, msg.len() ); let unjumbled = f4jumble_inv(&jumbled).unwrap(); prop_assert_eq!( jumbled_len, unjumbled.len(), "Unjumbled length {} was not equal to jumbled length {}", unjumbled.len(), jumbled_len ); prop_assert_eq!(msg, unjumbled, "Unjumbled message did not match original message."); } } #[test] fn f4jumble_check_vectors() { for v in test_vectors() { let jumbled = f4jumble(&v.normal).unwrap(); assert_eq!(jumbled, v.jumbled); let unjumbled = f4jumble_inv(&v.jumbled).unwrap(); assert_eq!(unjumbled, v.normal); } } }
pub fn f4jumble_inv(c: &[u8]) -> Option<Vec<u8>> { if VALID_LENGTH.contains(&c.len()) { let hashes = Hashes::new(c.len()); let (c, d) = c.split_at(hashes.l_l); let y = xor(c, &hashes.h(1, d)); let x = xor(d, &hashes.g(1, &y)); let mut a = xor(&y, &hashes.h(0, &x)); let b = xor(&x, &hashes.g(0, &a)); a.extend(b); Some(a) } else { None } }
function_block-full_function
[ { "content": "/// Compute a parent node in the Sapling commitment tree given its two children.\n\npub fn merkle_hash(depth: usize, lhs: &[u8; 32], rhs: &[u8; 32]) -> [u8; 32] {\n\n let lhs = {\n\n let mut tmp = [false; 256];\n\n for (a, b) in tmp.iter_mut().zip(lhs.as_bits::<Lsb0>()) {\n\n ...
Rust
src/peer.rs
ckampfe/manix
fd1e5cf309b125dca6a17bf3fe67c8eff0a8d17d
use crate::peer_protocol; use crate::{signals, Begin, Index, InfoHash, Length, PeerId}; use futures_util::sink::SinkExt; use futures_util::StreamExt; use std::convert::TryInto; use tokio::time::{Interval, MissedTickBehavior}; use tracing::{debug, error, info, instrument}; #[derive(Debug)] pub(crate) struct PeerOptions { pub(crate) connection: tokio_util::codec::Framed<tokio::net::TcpStream, peer_protocol::MessageCodec>, pub(crate) peer_id: PeerId, pub(crate) remote_peer_id: PeerId, pub(crate) info_hash: InfoHash, pub(crate) peer_to_torrent_tx: tokio::sync::mpsc::Sender<signals::PeerToTorrent>, pub(crate) torrent_to_peer_rx: tokio::sync::mpsc::Receiver<signals::TorrentToPeer>, pub(crate) global_permit: tokio::sync::OwnedSemaphorePermit, pub(crate) torrent_permit: tokio::sync::OwnedSemaphorePermit, pub(crate) piece_length: usize, pub(crate) chunk_length: usize, pub(crate) choke_state: ChokeState, pub(crate) interest_state: InterestState, } #[derive(Debug)] pub(crate) struct Peer { connection: tokio_util::codec::Framed<tokio::net::TcpStream, peer_protocol::MessageCodec>, peer_id: PeerId, remote_peer_id: PeerId, info_hash: InfoHash, peer_to_torrent_tx: tokio::sync::mpsc::Sender<signals::PeerToTorrent>, torrent_to_peer_rx: tokio::sync::mpsc::Receiver<signals::TorrentToPeer>, global_permit: tokio::sync::OwnedSemaphorePermit, torrent_permit: tokio::sync::OwnedSemaphorePermit, choke_state: ChokeState, interest_state: InterestState, piece_length: usize, chunk_length: usize, } impl Peer { #[instrument] pub(crate) fn new(options: PeerOptions) -> Self { Self { connection: options.connection, peer_id: options.peer_id, remote_peer_id: options.remote_peer_id, info_hash: options.info_hash, peer_to_torrent_tx: options.peer_to_torrent_tx, torrent_to_peer_rx: options.torrent_to_peer_rx, global_permit: options.global_permit, torrent_permit: options.torrent_permit, choke_state: ChokeState::Choked, interest_state: InterestState::NotInterested, piece_length: options.piece_length, chunk_length: options.chunk_length, } } #[instrument(skip(self))] pub(crate) async fn event_loop(mut self) -> Result<(), std::io::Error> { info!( "registering remote peer id {:?} with owning torrent", self.remote_peer_id.to_string() ); let current_bitfield = self.request_current_bifield().await?.await.map_err(|_e| { std::io::Error::new( std::io::ErrorKind::BrokenPipe, "TODO handle this oneshot channel error", ) })?; info!("got bitfield from owning torrent"); self.send_bitfield(current_bitfield).await?; info!("Sent bitfield to peer"); self.send_unchoke().await?; info!("Sent unchoke to peer"); self.send_interested().await?; info!("Sent interested"); let Timers { mut keepalive } = self.start_timers().await; info!("Started peer timers"); loop { tokio::select! { result = Peer::receive_message(&mut self.connection) => { match result { Some(Ok(message)) => { match message { peer_protocol::Message::Keepalive => { info!("Receieved keepalive from peer") }, peer_protocol::Message::Choke => { info!("Received choke from peer"); self.send_choke().await? }, peer_protocol::Message::Unchoke => { info!("Received unchoke from peer"); self.send_unchoke().await?; }, peer_protocol::Message::Interested => { info!("Received interested from peer"); }, peer_protocol::Message::NotInterested => { info!("Received not interested from peer"); }, peer_protocol::Message::Have { index: _ } => todo!(), peer_protocol::Message::Bitfield { bitfield } => { info!("Received bitfield from peer"); self.report_bitfield(bitfield).await?; }, peer_protocol::Message::Request { index: _, begin: _, length: _ } => todo!(), peer_protocol::Message::Piece { index, begin, chunk: _ } => { info!("Received piece ({}, {})", index, begin) }, peer_protocol::Message::Cancel { index: _, begin: _, length: _ } => todo!(), } } Some(Err(e)) => { error!("{:#?}", e.to_string()); self.deregister_with_owning_torrent().await?; return Err(e); } None => { info!("remote peer hung up"); self.deregister_with_owning_torrent().await?; return Ok(()) }, } } result = Peer::receive_message_from_owning_torrent(&mut self.torrent_to_peer_rx) => { match result { Some(message) => match message { signals::TorrentToPeer::Choke => { self.choke_state = ChokeState::Choked; self.send_choke().await? }, signals::TorrentToPeer::NotChoked => { self.choke_state = ChokeState::NotChoked; self.send_unchoke().await? }, signals::TorrentToPeer::Interested => { self.interest_state = InterestState::Interested; self.send_interested().await? }, signals::TorrentToPeer::NotInterested => { self.interest_state = InterestState::NotInterested; self.send_not_interested().await? }, signals::TorrentToPeer::GetPiece(index) => { let offsets = peer_protocol::chunk_offsets_lengths(self.piece_length, self.chunk_length); for (chunk_offset, chunk_length) in offsets { self.send_request( index.try_into().unwrap(), chunk_offset.try_into().unwrap(), chunk_length.try_into().unwrap() ).await?; } } }, None => { debug!("Torrent to peer channel closed, disconnecting"); return Ok(()); }, } } _ = keepalive.tick() => { info!("sent keepalive"); self.send_keepalive().await?; } } } } #[instrument(skip(self))] async fn start_timers(&self) -> Timers { let mut keepalive = tokio::time::interval(std::time::Duration::from_secs(30)); keepalive.set_missed_tick_behavior(MissedTickBehavior::Burst); Timers { keepalive } } #[instrument(skip(self))] async fn send_keepalive(&mut self) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Keepalive).await } #[instrument(skip(self))] async fn send_choke(&mut self) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Choke).await } #[instrument(skip(self))] async fn send_unchoke(&mut self) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Unchoke).await } #[instrument(skip(self))] async fn send_interested(&mut self) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Interested).await } #[instrument(skip(self))] async fn send_not_interested(&mut self) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::NotInterested) .await } #[instrument(skip(self))] async fn send_have(&mut self, index: Index) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Have { index }) .await } #[instrument(skip(self))] async fn send_bitfield( &mut self, bitfield: peer_protocol::Bitfield, ) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Bitfield { bitfield }) .await } #[instrument(skip(self))] async fn send_request( &mut self, index: Index, begin: Begin, length: Length, ) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Request { index, begin, length, }) .await } #[instrument(skip(self, chunk))] async fn send_piece( &mut self, index: Index, begin: Begin, chunk: Vec<u8>, ) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Piece { index, begin, chunk, }) .await } #[instrument(skip(self))] async fn send_cancel( &mut self, index: Index, begin: Begin, length: Length, ) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Cancel { index, begin, length, }) .await } async fn send_message( &mut self, message: peer_protocol::Message, ) -> Result<(), std::io::Error> { self.connection.send(message).await?; self.connection.flush().await } async fn receive_message( connection: &mut tokio_util::codec::Framed< tokio::net::TcpStream, peer_protocol::MessageCodec, >, ) -> Option<Result<peer_protocol::Message, std::io::Error>> { connection.next().await } #[instrument(skip(self))] async fn deregister_with_owning_torrent(&mut self) -> Result<(), std::io::Error> { self.send_to_owned_torrent(signals::PeerToTorrent::Deregister { remote_peer_id: self.remote_peer_id, }) .await } #[instrument(skip(self))] async fn request_current_bifield( &self, ) -> Result<tokio::sync::oneshot::Receiver<peer_protocol::Bitfield>, std::io::Error> { let (tx, rx) = tokio::sync::oneshot::channel(); self.send_to_owned_torrent(signals::PeerToTorrent::RequestBitfield { remote_peer_id: self.remote_peer_id, responder: tx, }) .await?; Ok(rx) } #[instrument(skip(self))] async fn report_bitfield( &self, bitfield: peer_protocol::Bitfield, ) -> Result<(), std::io::Error> { self.send_to_owned_torrent(signals::PeerToTorrent::Bitfield { remote_peer_id: self.remote_peer_id, bitfield, }) .await?; Ok(()) } #[instrument(skip(self))] async fn send_to_owned_torrent( &self, message: signals::PeerToTorrent, ) -> Result<(), std::io::Error> { self.peer_to_torrent_tx .send(message) .await .map_err(|e| std::io::Error::new(std::io::ErrorKind::BrokenPipe, e.to_string())) } #[instrument(skip(rx))] async fn receive_message_from_owning_torrent( rx: &mut tokio::sync::mpsc::Receiver<signals::TorrentToPeer>, ) -> Option<signals::TorrentToPeer> { rx.recv().await } } struct Timers { keepalive: Interval, } #[derive(Debug)] pub(crate) enum ChokeState { Choked, NotChoked, } #[derive(Debug)] pub(crate) enum InterestState { Interested, NotInterested, }
use crate::peer_protocol; use crate::{signals, Begin, Index, InfoHash, Length, PeerId}; use futures_util::sink::SinkExt; use futures_util::StreamExt; use std::convert::TryInto; use tokio::time::{Interval, MissedTickBehavior}; use tracing::{debug, error, info, instrument}; #[derive(Debug)] pub(crate) struct PeerOptions { pub(crate) connection: tokio_util::codec::Framed<tokio::net::TcpStream, peer_protocol::MessageCodec>, pub(crate) peer_id: PeerId, pub(crate) remote_peer_id: PeerId, pub(crate) info_hash: InfoHash, pub(crate) peer_to_torrent_tx: tokio::sync::mpsc::Sender<signals::PeerToTorrent>, pub(crate) torrent_to_peer_rx: tokio::sync::mpsc::Receiver<signals::TorrentToPeer>, pub(crate) global_permit: tokio::sync::OwnedSemaphorePermit, pub(crate) torrent_permit: tokio::sync::OwnedSemaphorePermit, pub(crate) piece_length: usize, pub(crate) chunk_length: usize, pub(crate) choke_state: ChokeState, pub(crate) interest_state: InterestState, } #[derive(Debug)] pub(crate) struct Peer { connection: tokio_util::codec::Framed<tokio::net::TcpStream, peer_protocol::MessageCodec>, peer_id: PeerId, remote_peer_id: PeerId, info_hash: InfoHash, peer_to_torrent_tx: tokio::sync::mpsc::Sender<signals::PeerToTorrent>, torrent_to_peer_rx: tokio::sync::mpsc::Receiver<signals::TorrentToPeer>, global_permit: tokio::sync::OwnedSemaphorePermit, torrent_permit: tokio::sync::OwnedSemaphorePermit, choke_state: ChokeState, interest_state: InterestState, piece_length: usize, chunk_length: usize, } impl Peer { #[instrument] pub(crate) fn new(options: PeerOptions) -> Self { Self { connection: options.connection, peer_id: options.peer_id, remote_peer_id: options.remote_peer_id, info_hash: options.info_hash, peer_to_torrent_tx: options.peer_to_torrent_tx, torrent_to_peer_rx: options.torrent_to_peer_rx, global_permit: options.global_permit, torrent_permit: options.torrent_permit, choke_state: ChokeState::Choked, interest_state: InterestState::NotInterested, piece_length: options.piece_length, chunk_length: options.chunk_length, } } #[instrument(skip(self))] pub(crate) async fn event_loop(mut self) -> Result<(), std::io::Error> { info!( "registering remote peer id {:?} with owning torrent", self.remote_peer_id.to_string() ); let current_bitfield = self.request_current_bifield().await?.await.map_err(|_e| { std::io::Error::new( std::io::ErrorKind::BrokenPipe, "TODO handle this oneshot channel error", ) })?; info!("got bitfield from owning torrent"); self.send_bitfield(current_bitfield).await?; info!("Sent bitfield to peer"); self.send_unchoke().await?; info!("Sent unchoke to peer"); self.send_interested().await?; info!("Sent interested"); let Timers { mut keepalive } = self.start_timers().await; info!("Started peer timers"); loop { tokio::select! { result = Peer::receive_message(&mut self.connection) => { match result { Some(Ok(message)) => { match message { peer_protocol::Message::Keepalive => { info!("Receieved keepalive from peer") }, peer_protocol::Message::Choke => { info!("Received choke from peer"); self.send_choke().await? }, peer_protocol::Message::Unchoke => { info!("Received unchoke from peer"); self.send_unchoke().await?; }, peer_protocol::Message::Interested => { info!("Received interested from peer"); }, peer_protocol::Message::NotInterested => { info!("Received not interested from peer"); }, peer_protocol::Message::Have { index: _ } => todo!(), peer_protocol::Message::Bitfield { bitfield } => { info!("Received bitfield from peer"); self.report_bitfield(bitfield).await?; }, peer_protocol::Message::Request { index: _, begin: _, length: _ } => todo!(), peer_protocol::Message::Piece { index, begin, chunk: _ } => { info!("Received piece ({}, {})", index, begin) }, peer_protocol::Message::Cancel { index: _, begin: _, length: _ } => todo!(), } } Some(Err(e)) => { error!("{:#?}", e.to_string()); self.deregister_with_owning_torrent().await?; return Err(e); } None => { info!("remote peer hung up"); self.deregister_with_owning_torrent().await?; return Ok(()) }, } } result = Peer::receive_message_from_owning_torrent(&mut self.torrent_to_peer_rx) => { match result { Some(message) => match message { signals::TorrentToPeer::Choke => { self.choke_state = ChokeState::Choked; self.send_choke().await? }, signals::TorrentToPeer::NotChoked => { self.choke_state = ChokeState::NotChoked; self.send_unchoke().await? }, signals::TorrentToPeer::Interested => { self.interest_state = InterestState::Interested; self.send_interested().await? }, signals::TorrentToPeer::NotInterested => { self.interest_state = InterestState::NotInterested; self.send_not_interested().await? }, signals::TorrentToPeer::GetPiece(index) => { let offsets = peer_protocol::chunk_offsets_lengths(self.piece_length, self.chunk_length); for (chunk_offset, chunk_length) in offsets { self.send_request( index.try_into().unwrap(), chunk_offset.try_into().unwrap(), chunk_length.try_into().unwrap() ).await?; } } }, None => { debug!("Torrent to peer channel closed, disconnecting"); return Ok(()); }, } } _ = keepalive.tick() => { info!("sent keepalive"); self.send_keepalive().await?; } } } } #[instrument(skip(self))] async fn start_timers(&self) -> Timers { let mut keepalive = tokio::time::interval(std::time::Duration::from_secs(30)); keepalive.set_missed_tick_behavior(MissedTickBehavior::Burst); Timers { keepalive } } #[instrument(skip(self))] async fn send_keepalive(&mut self) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Keepalive).await } #[instrument(skip(self))] async fn send_choke(&mut self) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Choke).await } #[instrument(skip(self))] async fn send_unchoke(&mut self) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Unchoke).await } #[instrument(skip(self))] async fn send_interested(&mut self) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Interested).await } #[instrument(skip(self))] async fn send_not_interested(&mut self) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::NotInterested) .await } #[instrument(skip(self))] async fn send_have(&mut self, index: Index) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Have { index }) .await } #[instrument(skip(self))] async fn send_bitfield( &mut self, bitfield: peer_protoc
#[instrument(skip(self))] async fn send_request( &mut self, index: Index, begin: Begin, length: Length, ) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Request { index, begin, length, }) .await } #[instrument(skip(self, chunk))] async fn send_piece( &mut self, index: Index, begin: Begin, chunk: Vec<u8>, ) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Piece { index, begin, chunk, }) .await } #[instrument(skip(self))] async fn send_cancel( &mut self, index: Index, begin: Begin, length: Length, ) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Cancel { index, begin, length, }) .await } async fn send_message( &mut self, message: peer_protocol::Message, ) -> Result<(), std::io::Error> { self.connection.send(message).await?; self.connection.flush().await } async fn receive_message( connection: &mut tokio_util::codec::Framed< tokio::net::TcpStream, peer_protocol::MessageCodec, >, ) -> Option<Result<peer_protocol::Message, std::io::Error>> { connection.next().await } #[instrument(skip(self))] async fn deregister_with_owning_torrent(&mut self) -> Result<(), std::io::Error> { self.send_to_owned_torrent(signals::PeerToTorrent::Deregister { remote_peer_id: self.remote_peer_id, }) .await } #[instrument(skip(self))] async fn request_current_bifield( &self, ) -> Result<tokio::sync::oneshot::Receiver<peer_protocol::Bitfield>, std::io::Error> { let (tx, rx) = tokio::sync::oneshot::channel(); self.send_to_owned_torrent(signals::PeerToTorrent::RequestBitfield { remote_peer_id: self.remote_peer_id, responder: tx, }) .await?; Ok(rx) } #[instrument(skip(self))] async fn report_bitfield( &self, bitfield: peer_protocol::Bitfield, ) -> Result<(), std::io::Error> { self.send_to_owned_torrent(signals::PeerToTorrent::Bitfield { remote_peer_id: self.remote_peer_id, bitfield, }) .await?; Ok(()) } #[instrument(skip(self))] async fn send_to_owned_torrent( &self, message: signals::PeerToTorrent, ) -> Result<(), std::io::Error> { self.peer_to_torrent_tx .send(message) .await .map_err(|e| std::io::Error::new(std::io::ErrorKind::BrokenPipe, e.to_string())) } #[instrument(skip(rx))] async fn receive_message_from_owning_torrent( rx: &mut tokio::sync::mpsc::Receiver<signals::TorrentToPeer>, ) -> Option<signals::TorrentToPeer> { rx.recv().await } } struct Timers { keepalive: Interval, } #[derive(Debug)] pub(crate) enum ChokeState { Choked, NotChoked, } #[derive(Debug)] pub(crate) enum InterestState { Interested, NotInterested, }
ol::Bitfield, ) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Bitfield { bitfield }) .await }
function_block-function_prefixed
[ { "content": "fn info_hash(bencode: &nom_bencode::Bencode) -> InfoHash {\n\n match bencode {\n\n nom_bencode::Bencode::Dictionary(d) => {\n\n let info = d.get(&b\"info\".to_vec()).unwrap();\n\n let encoded = info.encode();\n\n InfoHash(hash(&encoded))\n\n }\n\n ...
Rust
src/coords.rs
mabruzzo/nmea0183
fd1a2d8a62cbcb6f3a9aeecabae88f7b81e850eb
use core::convert::TryFrom; #[derive(Debug, PartialEq, Clone)] pub enum Hemisphere { North, South, East, West, } #[derive(Debug, PartialEq, Clone)] pub struct Latitude { pub degrees: u8, pub minutes: u8, pub seconds: f32, pub hemisphere: Hemisphere, } impl TryFrom<f32> for Latitude { type Error = &'static str; fn try_from(value: f32) -> Result<Self, Self::Error> { TryFrom::try_from(value as f64) } } impl TryFrom<f64> for Latitude { type Error = &'static str; fn try_from(from: f64) -> Result<Self, Self::Error> { if from >= 90f64 || from <= -90f64 { Err("Latitude is not in range -90 to 90 degrees!") } else { let (value, hemisphere) = if from >= 0f64 { (from, Hemisphere::North) } else { (-from, Hemisphere::South) }; let degrees = value as u8; let min_sec = (value - degrees as f64) * 60f64; let minutes = min_sec as u8; let seconds = ((min_sec - minutes as f64) * 60f64) as f32; Ok({ Latitude { degrees, minutes, seconds, hemisphere, } }) } } } impl Latitude { pub(crate) fn parse( coord: Option<&str>, hemi: Option<&str>, ) -> Result<Option<Self>, &'static str> { match (coord, hemi) { (Some(lat), Some(lat_hemi)) if lat.len() == 0 && lat_hemi.len() == 0 => Ok(None), (Some(lat), Some(lat_hemi)) => { if lat.len() < 4 { return Err("Latitude field is too short!"); } let hemisphere = match lat_hemi { "N" => Hemisphere::North, "S" => Hemisphere::South, _ => return Err("Latitude hemisphere field has wrong format!"), }; let degrees = lat[..2] .parse::<u8>() .map_err(|_| "Wrong latitude field format")?; let min_sec = lat[2..] .parse::<f64>() .map_err(|_| "Wrong latitude field format")?; let minutes = min_sec as u8; let seconds = ((min_sec - minutes as f64) * 60f64) as f32; Ok(Some(Latitude { degrees, minutes, seconds, hemisphere, })) } (None, Some(_)) => Err("Could not parse latitude from hemisphere only"), (Some(_), None) => Err("Could not parse latitude from coordinate only"), (None, None) => Ok(None), } } pub fn as_f64(&self) -> f64 { let result = self.degrees as f64 + (self.minutes as f64) / 60f64 + (self.seconds as f64) / 3600f64; match self.hemisphere { Hemisphere::North => result, Hemisphere::South => -result, Hemisphere::East => panic!("Wrong East hemisphere for latitude!"), Hemisphere::West => panic!("Wrong West hemisphere for latitude!"), } } pub fn is_north(&self) -> bool { self.hemisphere == Hemisphere::North } pub fn is_south(&self) -> bool { self.hemisphere == Hemisphere::South } } #[derive(Debug, PartialEq, Clone)] pub struct Longitude { pub degrees: u8, pub minutes: u8, pub seconds: f32, pub hemisphere: Hemisphere, } impl TryFrom<f32> for Longitude { type Error = &'static str; fn try_from(value: f32) -> Result<Self, Self::Error> { TryFrom::try_from(value as f64) } } impl TryFrom<f64> for Longitude { type Error = &'static str; fn try_from(from: f64) -> Result<Self, Self::Error> { if from >= 180f64 || from <= -180f64 { Err("Latitude is not in range -180 to 180 degrees!") } else { let (value, hemisphere) = if from >= 0f64 { (from, Hemisphere::East) } else { (-from, Hemisphere::West) }; let degrees = value as u8; let min_sec = (value - degrees as f64) * 60f64; let minutes = min_sec as u8; let seconds = ((min_sec - minutes as f64) * 60f64) as f32; Ok({ Longitude { degrees, minutes, seconds, hemisphere, } }) } } } impl Longitude { pub(crate) fn parse( coord: Option<&str>, hemi: Option<&str>, ) -> Result<Option<Self>, &'static str> { match (coord, hemi) { (Some(lon), Some(lon_hemi)) if lon.len() == 0 && lon_hemi.len() == 0 => Ok(None), (Some(lon), Some(lon_hemi)) => { if lon.len() < 5 { return Err("Longitude field is too short!"); } let hemisphere = match lon_hemi { "E" => Hemisphere::East, "W" => Hemisphere::West, _ => return Err("Longitude hemisphere field has wrong format!"), }; let degrees = lon[..3] .parse::<u8>() .map_err(|_| "Wrong longitude field format")?; let min_sec = lon[3..] .parse::<f64>() .map_err(|_| "Wrong longitude field format")?; let minutes = min_sec as u8; let seconds = ((min_sec - minutes as f64) * 60f64) as f32; Ok(Some(Longitude { degrees, minutes, seconds, hemisphere, })) } (None, Some(_)) => Err("Could not parse longitude from hemisphere only"), (Some(_), None) => Err("Could not parse longitude from coordinate only"), (None, None) => Ok(None), } } pub fn as_f64(&self) -> f64 { let result = self.degrees as f64 + (self.minutes as f64) / 60f64 + (self.seconds as f64) / 3600f64; match self.hemisphere { Hemisphere::West => -result, Hemisphere::East => result, Hemisphere::North => panic!("Wrong North hemisphere for latitude!"), Hemisphere::South => panic!("Wrong South hemisphere for latitude!"), } } pub fn is_west(&self) -> bool { self.hemisphere == Hemisphere::West } pub fn is_east(&self) -> bool { self.hemisphere == Hemisphere::East } } #[derive(Debug, PartialEq, Clone)] pub struct Altitude { pub meters: f32, } impl Altitude { pub(crate) fn parse(input: Option<&str>) -> Result<Option<Self>, &'static str> { match input { Some("") => Ok(None), Some(alt) => Ok(Some(Altitude { meters: alt .parse::<f32>() .map_err(|_| "Wrong altitude field format")?, })), _ => Ok(None), } } } #[derive(Debug, PartialEq, Clone)] pub struct Speed { knots: f32, } impl Speed { pub fn from_knots(speed: f32) -> Speed { Speed { knots: speed } } pub fn from_mps(speed: f32) -> Speed { Speed { knots: speed * 1.94384f32, } } pub fn from_mph(speed: f32) -> Speed { Speed { knots: speed * 0.868976f32, } } pub fn from_kph(speed: f32) -> Speed { Speed { knots: speed * 0.539957f32, } } pub fn as_knots(&self) -> f32 { self.knots } pub fn as_kph(&self) -> f32 { self.knots * 1.852 } pub fn as_mph(&self) -> f32 { self.knots * 1.15078 } pub fn as_mps(&self) -> f32 { self.knots * 0.514444 } pub(crate) fn parse(input: Option<&str>) -> Result<Option<Self>, &'static str> { match input { Some(speed) if speed.len() == 0 => Ok(None), Some(speed) => speed .parse::<f32>() .map_err(|_| "Wrong speed field format") .and_then(|knots| Ok(Some(Speed { knots }))), _ => Ok(None), } } } #[derive(Debug, PartialEq, Clone)] pub struct Course { pub degrees: f32, } impl From<f32> for Course { fn from(value: f32) -> Self { Course { degrees: value } } } impl Course { pub(crate) fn parse(input: Option<&str>) -> Result<Option<Self>, &'static str> { match input { Some(course) if course.len() == 0 => Ok(None), Some(course) => course .parse::<f32>() .map_err(|_| "Wrong course field format") .and_then(|degrees| Ok(Some(Course { degrees }))), _ => Ok(None), } } } #[derive(Debug, PartialEq, Clone)] pub struct MagneticCourse { degrees: f32, } impl From<f32> for MagneticCourse { fn from(value: f32) -> Self { MagneticCourse { degrees: value } } } impl MagneticCourse { pub(crate) fn parse_from_str(input: Option<&str>) -> Result<Option<Self>, &'static str> { match input { Some(course) if course.len() == 0 => Ok(None), Some(course) => course .parse::<f32>() .map_err(|_| "Wrong course field format") .and_then(|degrees| Ok(Some(MagneticCourse { degrees }))), _ => Ok(None), } } pub(crate) fn parse_from_mvar_mdir( true_course: &Option<Course>, mvar: Option<&str>, mdir: Option<&str>, ) -> Result<Option<Self>, &'static str> { if let (Some(course), Some(variation), Some(direction)) = (true_course, mvar, mdir) { if variation.len() == 0 && direction.len() == 0 { Ok(None) } else { let magnetic = variation .parse::<f32>() .map_err(|_| "Wrong magnetic variation field format!")?; match direction { "E" => Ok(Some(MagneticCourse { degrees: course.degrees - magnetic, })), "W" => Ok(Some(MagneticCourse { degrees: course.degrees + magnetic, })), _ => Err("Wrong direction field for magnetic variation"), } } } else { Ok(None) } } }
use core::convert::TryFrom; #[derive(Debug, PartialEq, Clone)] pub enum Hemisphere { North, South, East, West, } #[derive(Debug, PartialEq, Clone)] pub struct Latitude { pub degrees: u8, pub minutes: u8, pub seconds: f32, pub hemisphere: Hemisphere, } impl TryFrom<f32> for Latitude { type Error = &'static str; fn try_from(value: f32) -> Result<Self, Self::Error> { TryFrom::try_from(value as f64) } } impl TryFrom<f64> for Latitude { type Error = &'static str; fn try_from(from: f64) -> Result<Self, Self::Error> { if from >= 90f64 || from <= -90f64 { Err("Latitude is not in range -90 to 90 degrees!") } else { let (value, hemisphere) = if from >= 0f64 { (from, Hemisphere::North) } else { (-from, Hemisphere::South) }; let degrees = value as u8; let min_sec = (value - degrees as f64) * 60f64; let minutes = min_sec as u8; let seconds = ((min_sec - minutes as f64) * 60f64) as f32; Ok({ Latitude { degrees, minutes, seconds, hemisphere, } }) } } } impl Latitude { pub(crate) fn parse( coord: Option<&str>, hemi: Option<&str>, ) -> Result<Option<Self>, &'static str> { match (coord, hemi) { (Some(lat), Some(lat_hemi)) if lat.len() == 0 && lat_hemi.len() == 0 => Ok(None), (Some(lat), Some(lat_hemi)) => { if lat.len() < 4 { return Err("Latitude field is too short!"); } let hemisphere = match lat_hemi { "N" => Hemisphere::North, "S" => Hemisphere::South, _ => return Err("Latitude hemisphere field has wrong format!"), }; let degrees = lat[..2] .parse::<u8>() .map_err(|_| "Wrong latitude field format")?; let min_sec = lat[2..] .parse::<f64>() .map_err(|_| "Wrong latitude field format")?; let minutes = min_sec as u8; let seconds = ((min_sec - minutes as f64) * 60f64) as f32; Ok(Some(Latitude { degrees, minutes, seconds, hemisphere, })) } (None, Some(_)) => Err("Could not parse latitude from hemisphere only"), (Some(_), None) => Err("Could not parse latitude from coordinate only"), (None, None) => Ok(None), } } pub fn as_f64(&self) -> f64 { let result = self.degrees as f64 + (self.minutes as f64) / 60f64 + (self.seconds as f64) / 3600f64; match self.hemisphere { Hemisphere::North => result, Hemisphere::South => -result, Hemisphere::East => panic!("Wrong East hemisphere for latitude!"), Hemisphere::West => panic!("Wrong West hemisphere for latitude!"), } } pub fn is_north(&self) -> bool { self.hemisphere == Hemisphere::North } pub fn is_south(&self) -> bool { self.hemisphere == Hemisphere::South } } #[derive(Debug, PartialEq, Clone)] pub struct Longitude { pub degrees: u8, pub minutes: u8, pub seconds: f32, pub hemisphere: Hemisphere, } impl TryFrom<f32> for Longitude { type Error = &'static str; fn try_from(value: f32) -> Result<Self, Self::Error> { TryFrom::try_from(value as f64) } } impl TryFrom<f64> for Longitude { type Error = &'static str; fn try_from(from: f64) -> Result<Self, Self::Error> { if from >= 180f64 || from <= -180f64 { Err("Latitude is not in range -180 to 180 degrees!") } else { let (value, hemisphere) = if from >= 0f64 { (from, Hemisphere::East) } else { (-from, Hemisphere::West) }; let degrees = value as u8; let min_sec = (value - degrees as f64) * 60f64; let minutes = min_sec as u8; let seconds = ((min_sec - minutes as f64) * 60f64) as f32; Ok({ Longitude { degrees, minutes, seconds, hemisphere, } }) } } } impl Longitude { pub(crate) fn parse( coord: Option<&str>, hemi: Option<&str>, ) -> Result<Option<Self>, &'static str> { match (coord, hemi) { (Some(lon), Some(lon_hemi)) if lon.len() == 0 && lon_hemi.len() == 0 => Ok(None), (Some(lon), Some(lon_hemi)) => { if lon.len() < 5 { return Err("Longitude field is too short!"); } let hemisphere = match lon_hemi { "E" => Hemisphere::East, "W" => Hemisphere::West, _ => return Err("Longitude hemisphere field has wrong format!"), }; let degrees = lon[..3] .parse::<u8>() .map_err(|_| "Wrong longitude field format")?; let min_sec = lon[3..] .parse::<f64>() .map_err(|_| "Wrong longitude field format")?; let minutes = min_sec as u8; let seconds = ((min_sec - minutes as f64) * 60f64) as f32; Ok(Some(Longitude { degrees, minutes, seconds, hemisphere, })) } (None, Some(_)) => Err("Could not parse longitude from hemisphere only"), (Some(_), None) => Err("Could not parse longitude from coordinate only"), (None, None) => Ok(None), } } pub fn as_f64(&self) -> f64 { let result = self.degrees as f64 + (self.minutes as f64) / 60f64 + (self.seconds as f64) / 3600f64; match self.hemisphere { Hemisphere::West => -result, Hemisphere::East => result, Hemisphere::North => panic!("Wrong North hemisphere for latitude!"), Hemisphere::South => panic!("Wrong South hemisphere for latitude!"), } } pub fn is_west(&self) -> bool { self.hemisphere == Hemisphere::West } pub fn is_east(&self) -> bool { self.hemisphere == Hemisphere::East } } #[derive(Debug, PartialEq, Clone)] pub struct Altitude { pub meters: f32, } impl Altitude { pub(crate) fn parse(input: Option<&str>) -> Result<Option<Self>, &'static str> { match input { Some("") => Ok(None), Some(alt) => Ok(Some(Altitude { meters: alt .parse::<f32>() .map_err(|_| "Wrong altitude field format")?, })), _ => Ok(None), } } } #[derive(Debug, PartialEq, Clone)] pub struct Speed { knots: f32, } impl Speed { pub fn from_knots(speed: f32) -> Speed { Speed { knots: speed } } pub fn from_mps(speed: f32) -> Speed { Speed { knots: speed * 1.94384f32, } } pub fn from_mph(speed: f32) -> Speed { Speed { knots: speed * 0.868976f32, } } pub fn from_kph(speed: f32) -> Speed { Speed { knots: speed * 0.539957f32, } } pub fn as_knots(&self) -> f32 { self.knots } pub fn as_kph(&self) -> f32 { self.knots * 1.852 } pub fn as_mph(&self) -> f32 { self.knots * 1.15078 } pub fn as_mps(&self) -> f32 { self.knots * 0.514444 } pub(crate) fn parse(input: Option<&str>) -> Result<Option<Self>, &'static str> { match input { Some(speed) if speed.len() == 0 => Ok(None), Some(speed) => speed .
} #[derive(Debug, PartialEq, Clone)] pub struct Course { pub degrees: f32, } impl From<f32> for Course { fn from(value: f32) -> Self { Course { degrees: value } } } impl Course { pub(crate) fn parse(input: Option<&str>) -> Result<Option<Self>, &'static str> { match input { Some(course) if course.len() == 0 => Ok(None), Some(course) => course .parse::<f32>() .map_err(|_| "Wrong course field format") .and_then(|degrees| Ok(Some(Course { degrees }))), _ => Ok(None), } } } #[derive(Debug, PartialEq, Clone)] pub struct MagneticCourse { degrees: f32, } impl From<f32> for MagneticCourse { fn from(value: f32) -> Self { MagneticCourse { degrees: value } } } impl MagneticCourse { pub(crate) fn parse_from_str(input: Option<&str>) -> Result<Option<Self>, &'static str> { match input { Some(course) if course.len() == 0 => Ok(None), Some(course) => course .parse::<f32>() .map_err(|_| "Wrong course field format") .and_then(|degrees| Ok(Some(MagneticCourse { degrees }))), _ => Ok(None), } } pub(crate) fn parse_from_mvar_mdir( true_course: &Option<Course>, mvar: Option<&str>, mdir: Option<&str>, ) -> Result<Option<Self>, &'static str> { if let (Some(course), Some(variation), Some(direction)) = (true_course, mvar, mdir) { if variation.len() == 0 && direction.len() == 0 { Ok(None) } else { let magnetic = variation .parse::<f32>() .map_err(|_| "Wrong magnetic variation field format!")?; match direction { "E" => Ok(Some(MagneticCourse { degrees: course.degrees - magnetic, })), "W" => Ok(Some(MagneticCourse { degrees: course.degrees + magnetic, })), _ => Err("Wrong direction field for magnetic variation"), } } } else { Ok(None) } } }
parse::<f32>() .map_err(|_| "Wrong speed field format") .and_then(|knots| Ok(Some(Speed { knots }))), _ => Ok(None), } }
function_block-function_prefix_line
[ { "content": "fn from_ascii(bytes: &[u8]) -> Result<&str, &'static str> {\n\n if bytes.iter().all(|b| *b < 128) {\n\n Ok(unsafe { core::str::from_utf8_unchecked(bytes) })\n\n } else {\n\n Err(\"Not an ascii!\")\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": ...
Rust
src/channel/bolt/keyset.rs
LNP-WG/lnp-core
f8a24a0a61ae7a1c0a87020fde3caf90320e2c6d
use std::collections::BTreeMap; use amplify::DumbDefault; #[cfg(feature = "serde")] use amplify::ToYamlString; use bitcoin::util::bip32::{ChildNumber, ExtendedPrivKey, KeySource}; use p2p::legacy::{AcceptChannel, ChannelType, OpenChannel}; use secp256k1::{PublicKey, Secp256k1}; use wallet::hd::HardenedIndex; use wallet::scripts::PubkeyScript; #[derive(Clone, PartialEq, Eq, Debug, StrictEncode, StrictDecode)] #[cfg_attr( feature = "serde", derive(Display, Serialize, Deserialize), serde(crate = "serde_crate"), display(LocalPubkey::to_yaml_string) )] pub struct LocalPubkey { pub key: PublicKey, pub source: KeySource, } impl LocalPubkey { #[inline] pub fn to_bip32_derivation_map(&self) -> BTreeMap<PublicKey, KeySource> { bmap! { self.key => self.source.clone() } } #[inline] pub fn to_bitcoin_pk(&self) -> bitcoin::PublicKey { bitcoin::PublicKey::new(self.key) } } #[derive(Clone, PartialEq, Eq, Debug, StrictEncode, StrictDecode)] #[cfg_attr( feature = "serde", derive(Display, Serialize, Deserialize), serde(crate = "serde_crate"), display(LocalKeyset::to_yaml_string) )] pub struct LocalKeyset { pub funding_pubkey: LocalPubkey, pub revocation_basepoint: LocalPubkey, pub payment_basepoint: LocalPubkey, pub delayed_payment_basepoint: LocalPubkey, pub htlc_basepoint: LocalPubkey, pub first_per_commitment_point: LocalPubkey, pub shutdown_scriptpubkey: Option<PubkeyScript>, pub static_remotekey: bool, } #[derive(Clone, PartialEq, Eq, Debug, StrictEncode, StrictDecode)] #[cfg_attr( feature = "serde", derive(Display, Serialize, Deserialize), serde(crate = "serde_crate"), display(RemoteKeyset::to_yaml_string) )] pub struct RemoteKeyset { pub funding_pubkey: PublicKey, pub revocation_basepoint: PublicKey, pub payment_basepoint: PublicKey, pub delayed_payment_basepoint: PublicKey, pub htlc_basepoint: PublicKey, pub first_per_commitment_point: PublicKey, pub shutdown_scriptpubkey: Option<PubkeyScript>, pub static_remotekey: bool, } #[cfg(feature = "serde")] impl ToYamlString for LocalPubkey {} #[cfg(feature = "serde")] impl ToYamlString for LocalKeyset {} #[cfg(feature = "serde")] impl ToYamlString for RemoteKeyset {} impl From<&OpenChannel> for RemoteKeyset { fn from(open_channel: &OpenChannel) -> Self { Self { funding_pubkey: open_channel.funding_pubkey, revocation_basepoint: open_channel.revocation_basepoint, payment_basepoint: open_channel.payment_point, delayed_payment_basepoint: open_channel.delayed_payment_basepoint, htlc_basepoint: open_channel.htlc_basepoint, first_per_commitment_point: open_channel.first_per_commitment_point, shutdown_scriptpubkey: open_channel.shutdown_scriptpubkey.clone(), static_remotekey: false, } } } impl From<&AcceptChannel> for RemoteKeyset { fn from(accept_channel: &AcceptChannel) -> Self { Self { funding_pubkey: accept_channel.funding_pubkey, revocation_basepoint: accept_channel.revocation_basepoint, payment_basepoint: accept_channel.payment_point, delayed_payment_basepoint: accept_channel.delayed_payment_basepoint, htlc_basepoint: accept_channel.htlc_basepoint, first_per_commitment_point: accept_channel .first_per_commitment_point, shutdown_scriptpubkey: accept_channel.shutdown_scriptpubkey.clone(), static_remotekey: accept_channel .channel_type .map(ChannelType::has_static_remotekey) .unwrap_or_default(), } } } impl DumbDefault for LocalPubkey { fn dumb_default() -> Self { LocalPubkey { key: dumb_pubkey!(), source: KeySource::default(), } } } impl DumbDefault for LocalKeyset { fn dumb_default() -> Self { Self { funding_pubkey: DumbDefault::dumb_default(), revocation_basepoint: DumbDefault::dumb_default(), payment_basepoint: DumbDefault::dumb_default(), delayed_payment_basepoint: DumbDefault::dumb_default(), htlc_basepoint: DumbDefault::dumb_default(), first_per_commitment_point: DumbDefault::dumb_default(), shutdown_scriptpubkey: None, static_remotekey: false, } } } impl DumbDefault for RemoteKeyset { fn dumb_default() -> Self { Self { funding_pubkey: dumb_pubkey!(), revocation_basepoint: dumb_pubkey!(), payment_basepoint: dumb_pubkey!(), delayed_payment_basepoint: dumb_pubkey!(), htlc_basepoint: dumb_pubkey!(), first_per_commitment_point: dumb_pubkey!(), shutdown_scriptpubkey: None, static_remotekey: false, } } } impl LocalKeyset { pub fn with<C: secp256k1::Signing>( secp: &Secp256k1<C>, channel_source: KeySource, channel_xpriv: ExtendedPrivKey, shutdown_scriptpubkey: Option<PubkeyScript>, ) -> Self { let fingerpint = channel_source.0; let keys = (0u16..=6) .into_iter() .map(HardenedIndex::from) .map(ChildNumber::from) .map(|index| [index]) .map(|path| { let derivation_path = channel_source.1.clone().extend(path); let seckey = channel_xpriv .derive_priv(secp, &path) .expect("negligible probability") .private_key; LocalPubkey { key: PublicKey::from_secret_key(secp, &seckey), source: (fingerpint, derivation_path), } }) .collect::<Vec<_>>(); Self { funding_pubkey: keys[0].clone(), revocation_basepoint: keys[3].clone(), payment_basepoint: keys[1].clone(), delayed_payment_basepoint: keys[2].clone(), htlc_basepoint: keys[5].clone(), first_per_commitment_point: keys[4].clone(), shutdown_scriptpubkey, static_remotekey: false, } } }
use std::collections::BTreeMap; use amplify::DumbDefault; #[cfg(feature = "serde")] use amplify::ToYamlString; use bitcoin::util::bip32::{ChildNumber, ExtendedPrivKey, KeySource}; use p2p::legacy::{AcceptChannel, ChannelType, OpenChannel}; use secp256k1::{PublicKey, Secp256k1}; use wallet::hd::HardenedIndex; use wallet::scripts::PubkeyScript; #[derive(Clone, PartialEq, Eq, Debug, StrictEncode, StrictDecode)] #[cfg_attr( feature = "serde", derive(Display, Serialize, Deserialize), serde(crate = "serde_crate"), display(LocalPubkey::to_yaml_string) )] pub struct LocalPubkey { pub key: PublicKey, pub source: KeySource, } impl LocalPubkey { #[inline] pub fn to_bip32_derivation_map(&self) -> BTreeMap<PublicKey, KeySource> { bmap! { self.key => self.source.clone() } } #[inline] pub fn to_bitcoin_pk(&self) -> bitcoin::PublicKey { bitcoin::PublicKey::new(self.key) } } #[derive(Clone, PartialEq, Eq, Debug, StrictEncode, StrictDecode)] #[cfg_attr( feature = "serde", derive(Display, Serialize, Deserialize), serde(crate = "serde_crate"), display(LocalKeyset::to_yaml_string) )] pub struct LocalKeyset { pub funding_pubkey: LocalPubkey, pub revocation_basepoint: LocalPubkey, pub payment_basepoint: LocalPubkey, pub delayed_payment_basepoint: LocalPubkey, pub htlc_basepoint: LocalPubkey, pub first_per_commitment_point: LocalPubkey, pub shutdown_scriptpubkey: Option<PubkeyScript>, pub static_remotekey: bool, } #[derive(Clone, PartialEq, Eq, Debug, StrictEncode, StrictDecode)] #[cfg_attr( feature = "serde", derive(Display, Serialize, Deserialize), serde(crate = "serde_crate"), display(RemoteKeyset::to_yaml_string) )] pub struct RemoteKeyset { pub funding_pubkey: PublicKey, pub revocation_basepoint: PublicKey, pub payment_basepoint: PublicKey, pub delayed_payment_basepoint: PublicKey, pub htlc_basepoint: PublicKey, pub first_per_commitment_point: PublicKey, pub shutdown_scriptpubkey: Option<PubkeyScript>, pub static_remotekey: bool, } #[cfg(feature = "serde")] impl ToYamlString for LocalPubkey {} #[cfg(feature = "serde")] impl ToYamlString for LocalKeyset {} #[cfg(feature = "serde")] impl ToYamlString for RemoteKeyset {} impl From<&OpenChannel> for RemoteKeyset { fn from(open_channel: &OpenChannel) -> Self { Self { funding_pubkey: open_channel.funding_pubkey, revocation_basepoint: open_channel.revocation_basepoint, payment_basepoint: open_channel.payment_point, delayed_payment_basepoint: open_channel.delayed_payment_basepoint, htlc_basepoint: open_channel.htlc_basepoint, first_per_commitment_point: open_channel.first_per_commitment_point, shutdown_scriptpubkey: open_channel.shutdown_scriptpubkey.clone(), static_remotekey: false, } } } impl From<&AcceptChannel> for RemoteKeyset { fn from(accept_channel: &AcceptChannel) -> Self { Self { funding_pubkey: accept_channel.funding_pubkey, revocation_basepoint: accept_channel.revocation_basepoint, payment_basepoint: accept_channel.payment_point, delayed_payment_basepoint: accept_channel.delayed_payment_basepoint, htlc_basepoint: accept_channel.htlc_basepoint, first_per_commitment_point: accept_channel .first_per_commitment_point, shutdown_scriptpubkey: accept_channel.shutdown_scriptpubkey.clone(), static_remotekey: accept_channel .channel_type .map(ChannelType::has_static_remotekey) .unwrap_or_default(), } } } impl DumbDefault for LocalPubkey { fn dumb_default() -> Self { LocalPubkey { key: dumb_pubkey!(), source: KeySource::default(), } } } impl DumbDefault for LocalKeyset { fn dumb_default() -> Self { Self { funding_pubkey: DumbDefault::dumb_default(),
} impl DumbDefault for RemoteKeyset { fn dumb_default() -> Self { Self { funding_pubkey: dumb_pubkey!(), revocation_basepoint: dumb_pubkey!(), payment_basepoint: dumb_pubkey!(), delayed_payment_basepoint: dumb_pubkey!(), htlc_basepoint: dumb_pubkey!(), first_per_commitment_point: dumb_pubkey!(), shutdown_scriptpubkey: None, static_remotekey: false, } } } impl LocalKeyset { pub fn with<C: secp256k1::Signing>( secp: &Secp256k1<C>, channel_source: KeySource, channel_xpriv: ExtendedPrivKey, shutdown_scriptpubkey: Option<PubkeyScript>, ) -> Self { let fingerpint = channel_source.0; let keys = (0u16..=6) .into_iter() .map(HardenedIndex::from) .map(ChildNumber::from) .map(|index| [index]) .map(|path| { let derivation_path = channel_source.1.clone().extend(path); let seckey = channel_xpriv .derive_priv(secp, &path) .expect("negligible probability") .private_key; LocalPubkey { key: PublicKey::from_secret_key(secp, &seckey), source: (fingerpint, derivation_path), } }) .collect::<Vec<_>>(); Self { funding_pubkey: keys[0].clone(), revocation_basepoint: keys[3].clone(), payment_basepoint: keys[1].clone(), delayed_payment_basepoint: keys[2].clone(), htlc_basepoint: keys[5].clone(), first_per_commitment_point: keys[4].clone(), shutdown_scriptpubkey, static_remotekey: false, } } }
revocation_basepoint: DumbDefault::dumb_default(), payment_basepoint: DumbDefault::dumb_default(), delayed_payment_basepoint: DumbDefault::dumb_default(), htlc_basepoint: DumbDefault::dumb_default(), first_per_commitment_point: DumbDefault::dumb_default(), shutdown_scriptpubkey: None, static_remotekey: false, } }
function_block-function_prefix_line
[ { "content": "fn lnp_out_channel_funding_key() -> ProprietaryKey {\n\n ProprietaryKey {\n\n prefix: PSBT_LNP_PROPRIETARY_PREFIX.to_vec(),\n\n subtype: PSBT_OUT_LNP_CHANNEL_FUNDING,\n\n key: vec![],\n\n }\n\n}\n\n\n", "file_path": "src/channel/funding.rs", "rank": 0, "score...
Rust
keymanager-lib/src/policy.rs
keks/oasis-core
37479c75e5f94ffc03222cba6edd0624c1280d25
use std::{ collections::{HashMap, HashSet}, sync::RwLock, }; use anyhow::Result; use lazy_static::lazy_static; use sgx_isa::Keypolicy; use tiny_keccak::sha3_256; use oasis_core_keymanager_api_common::*; use oasis_core_runtime::{ common::{ cbor, runtime::RuntimeId, sgx::{ avr::EnclaveIdentity, seal::{seal, unseal}, }, }, enclave_rpc::Context as RpcContext, runtime_context, storage::StorageContext, }; use crate::context::Context as KmContext; lazy_static! { static ref POLICY: Policy = Policy::new(); } const POLICY_STORAGE_KEY: &'static [u8] = b"keymanager_policy"; const POLICY_SEAL_CONTEXT: &'static [u8] = b"Ekiden Keymanager Seal policy v0"; pub struct Policy { inner: RwLock<Inner>, } struct Inner { policy: Option<CachedPolicy>, } impl Policy { fn new() -> Self { Self { inner: RwLock::new(Inner { policy: None }), } } pub fn unsafe_skip() -> bool { option_env!("OASIS_UNSAFE_SKIP_KM_POLICY").is_some() } pub fn global<'a>() -> &'a Policy { &POLICY } pub fn init(&self, ctx: &mut RpcContext, raw_policy: &Vec<u8>) -> Result<Vec<u8>> { if Self::unsafe_skip() { return Ok(vec![]); } let mut inner = self.inner.write().unwrap(); let old_policy = match inner.policy.as_ref() { Some(old_policy) => old_policy.clone(), None => match Self::load_policy() { Some(old_policy) => old_policy, None => CachedPolicy::default(), }, }; let new_policy = CachedPolicy::parse(raw_policy)?; let rctx = runtime_context!(ctx, KmContext); if rctx.runtime_id != new_policy.runtime_id { return Err(KeyManagerError::PolicyInvalid.into()); } if old_policy.serial > new_policy.serial { return Err(KeyManagerError::PolicyRollback.into()); } else if old_policy.serial == new_policy.serial { if old_policy.checksum != new_policy.checksum { return Err(KeyManagerError::PolicyChanged.into()); } inner.policy = Some(old_policy.clone()); return Ok(old_policy.checksum.clone()); } Self::save_raw_policy(raw_policy); let new_checksum = new_policy.checksum.clone(); inner.policy = Some(new_policy); Ok(new_checksum) } pub fn may_get_or_create_keys( &self, remote_enclave: &EnclaveIdentity, req: &RequestIds, ) -> Result<()> { let inner = self.inner.read().unwrap(); let policy = match inner.policy.as_ref() { Some(policy) => policy, None => return Err(KeyManagerError::InvalidAuthentication.into()), }; match policy.may_get_or_create_keys(remote_enclave, req) { true => Ok(()), false => Err(KeyManagerError::InvalidAuthentication.into()), } } pub fn may_replicate_master_secret(&self, remote_enclave: &EnclaveIdentity) -> Result<()> { #[cfg(target_env = "sgx")] { let our_id = EnclaveIdentity::current().expect("failed to query MRENCLAVE/MRSIGNER"); if our_id == *remote_enclave { return Ok(()); } } let inner = self.inner.read().unwrap(); let policy = match inner.policy.as_ref() { Some(policy) => policy, None => return Err(KeyManagerError::InvalidAuthentication.into()), }; match policy.may_replicate_master_secret(remote_enclave) { true => Ok(()), false => Err(KeyManagerError::InvalidAuthentication.into()), } } pub fn may_replicate_from(&self) -> Option<HashSet<EnclaveIdentity>> { let inner = self.inner.read().unwrap(); let mut src_set = match inner.policy.as_ref() { Some(policy) => policy.may_replicate_from.clone(), None => HashSet::new(), }; match EnclaveIdentity::current() { Some(id) => { src_set.insert(id); } None => {} }; match src_set.is_empty() { true => None, false => Some(src_set), } } fn load_policy() -> Option<CachedPolicy> { let ciphertext = StorageContext::with_current(|_mkvs, untrusted_local| { untrusted_local.get(POLICY_STORAGE_KEY.to_vec()) }) .unwrap(); unseal(Keypolicy::MRENCLAVE, &POLICY_SEAL_CONTEXT, &ciphertext).map(|plaintext| { CachedPolicy::parse(&plaintext).expect("failed to deserialize persisted policy") }) } fn save_raw_policy(raw_policy: &Vec<u8>) { let ciphertext = seal(Keypolicy::MRENCLAVE, &POLICY_SEAL_CONTEXT, &raw_policy); StorageContext::with_current(|_mkvs, untrusted_local| { untrusted_local.insert(POLICY_STORAGE_KEY.to_vec(), ciphertext) }) .expect("failed to persist master secret"); } } #[derive(Clone, Debug)] struct CachedPolicy { pub checksum: Vec<u8>, pub serial: u32, pub runtime_id: RuntimeId, pub may_query: HashMap<RuntimeId, HashSet<EnclaveIdentity>>, pub may_replicate: HashSet<EnclaveIdentity>, pub may_replicate_from: HashSet<EnclaveIdentity>, } impl CachedPolicy { fn parse(raw: &Vec<u8>) -> Result<Self> { let untrusted_policy: SignedPolicySGX = cbor::from_slice(&raw)?; let policy = untrusted_policy.verify()?; let mut cached_policy = Self::default(); cached_policy.checksum = sha3_256(&raw).to_vec(); cached_policy.serial = policy.serial; cached_policy.runtime_id = policy.id; let enclave_identity = match EnclaveIdentity::current() { Some(enclave_identity) => enclave_identity, None => return Ok(cached_policy), }; let enclave_policy = match policy.enclaves.get(&enclave_identity) { Some(enclave_policy) => enclave_policy, None => return Ok(cached_policy), }; for (rt_id, ids) in &enclave_policy.may_query { let mut query_ids = HashSet::new(); for e_id in ids { query_ids.insert(e_id.clone()); } cached_policy.may_query.insert(*rt_id, query_ids); } for e_id in &enclave_policy.may_replicate { cached_policy.may_replicate.insert(e_id.clone()); } for (e_id, other_policy) in &policy.enclaves { if other_policy.may_replicate.contains(&enclave_identity) { cached_policy.may_replicate_from.insert(e_id.clone()); } } Ok(cached_policy) } fn default() -> Self { CachedPolicy { checksum: vec![], serial: 0, runtime_id: RuntimeId::default(), may_query: HashMap::new(), may_replicate: HashSet::new(), may_replicate_from: HashSet::new(), } } fn may_get_or_create_keys(&self, remote_enclave: &EnclaveIdentity, req: &RequestIds) -> bool { let may_query = match self.may_query.get(&req.runtime_id) { Some(may_query) => may_query, None => return false, }; may_query.contains(remote_enclave) } fn may_replicate_master_secret(&self, remote_enclave: &EnclaveIdentity) -> bool { self.may_replicate.contains(remote_enclave) } }
use std::{ collections::{HashMap, HashSet}, sync::RwLock, }; use anyhow::Result; use lazy_static::lazy_static; use sgx_isa::Keypolicy; use tiny_keccak::sha3_256; use oasis_core_keymanager_api_common::*; use oasis_core_runtime::{ common::{ cbor, runtime::RuntimeId, sgx::{ avr::EnclaveIdentity, seal::{seal, unseal}, }, }, enclave_rpc::Context as RpcContext, runtime_context, storage::StorageContext, }; use crate::context::Context as KmContext; lazy_static! { static ref POLICY: Policy = Policy::new(); } const POLICY_STORAGE_KEY: &'static [u8] = b"keymanager_policy"; const POLICY_SEAL_CONTEXT: &'static [u8] = b"Ekiden Keymanager Seal policy v0"; pub struct Policy { inner: RwLock<Inner>, } struct Inner { policy: Option<CachedPolicy>, } impl Policy { fn new() -> Self { Self { inner: RwLock::new(Inner { policy: None }), } } pub fn unsafe_skip() -> bool { option_env!("OASIS_UNSAFE_SKIP_KM_POLICY").is_some() } pub fn global<'a>() -> &'a Policy { &POLICY } pub fn init(&self, ctx: &mut RpcContext, raw_policy: &Vec<u8>) -> Result<Vec<u8>> { if Self::unsafe_skip() { return Ok(vec![]); } let mut inner = self.inner.write().unwrap(); let old_policy = match inner.policy.as_ref() { Some(old_policy) => old_policy.clone(), None => match Self::load_policy() { Some(old_policy) => old_policy, None => CachedPolicy::default(), }, }; let new_policy = CachedPolicy::parse(raw_policy)?; let rctx = runtime_context!(ctx, KmContext); if rctx.runtime_id != new_policy.runtime_id { return Err(KeyManagerError::PolicyInvalid.into()); } if old_policy.serial > new_policy.serial { return Err(KeyManagerError::PolicyRollback.into()); } else if old_policy.serial == new_policy.serial { if old_policy.checksum != new_policy.checksum { return Err(KeyManagerError::PolicyChanged.into()); } inner.policy = Some(old_policy.clone()); return Ok(old_policy.checksum.clone()); } Self::save_raw_policy(raw_policy); let new_checksum = new_policy.checksum.clone(); inner.policy = Some(new_policy); Ok(new_checksum) } pub fn may_get_or_create_keys( &self, remote_enclave: &EnclaveIdentity, req: &RequestIds, ) -> Result<()> { let inner = self.inner.read().unwrap(); let policy = match inner.policy.as_ref() { Some(policy) => policy, None => return Err(KeyManagerError::InvalidAuthentication.into()), }; match policy.may_get_or_create_keys(remote_enclave, req) { true => Ok(()), false => Err(KeyManagerError::InvalidAuthentication.into()), } } pub fn may_replicate_master_secret(&self, remote_enclave: &EnclaveIdentity) -> Result<()> { #[cfg(target_env = "sgx")] { let our_id = EnclaveIdentity::current().expect("failed to query MRENCLAVE/MRSIGNER"); if our_id == *remote_enclave { return Ok(()); } } let inner = self.inner.read().unwrap(); let policy = match inner.policy.as_ref() { Some(policy) => policy, None => return Err(KeyManagerError::InvalidAuthentication.into()), }; match policy.may_replicate_master_secret(remote_enclave) { true => Ok(()), false => Err(KeyManagerError::InvalidAuthentication.into()), } } pub fn may_replicate_from(&self) -> Option<HashSet<EnclaveIdentity>> { let inner = self.inner.read().unwrap(); let mut src_set = match inner.policy.as_ref() { Some(policy) => policy.may_replicate_from.clone(), None => HashSet::new(), }; match EnclaveIdentity::current() { Some(id) => { src_set.insert(id); } None => {} }; match src_set.is_empty() { true => None, false => Some(src_set), } } fn load_policy() -> Option<CachedPolicy> { let ciphertext = StorageContext::with_current(|_mkvs, untrusted_local| { untrusted_local.get(POLICY_STORAGE_KEY.to_vec()) }) .unwrap(); unseal(Keypolicy::MRENCLAVE, &POLICY_SEAL_CONTEXT, &ciphertext).map(|plaintext| { CachedPolicy::parse(&plaintext).expect("failed to deserialize persisted policy") }) } fn save_raw_policy(raw_policy: &Vec<u8>) { let ciphertext = seal(Keypolicy::MRENCLAVE, &POLICY_SEAL_CONTEXT, &raw_policy); StorageContext::with_current(|_mkvs, untrusted_local| { untrusted_local.insert(POLICY_STORAGE_KEY.to_vec(), ciphertext) }) .expect("failed to persist master secret"); } } #[derive(Clone, Debug)] struct CachedPolicy { pub checksum: Vec<u8>, pub serial: u32, pub runtime_id: RuntimeId, pub may_query: HashMap<RuntimeId, HashSet<EnclaveIdentity>>, pub may_replicate: HashSet<EnclaveIdentity>, pub may_replicate_from: HashSet<EnclaveIdentity>, } impl CachedPolicy { fn parse(raw: &Vec<u8>) -> Result<Self> {
te_enclave: &EnclaveIdentity, req: &RequestIds) -> bool { let may_query = match self.may_query.get(&req.runtime_id) { Some(may_query) => may_query, None => return false, }; may_query.contains(remote_enclave) } fn may_replicate_master_secret(&self, remote_enclave: &EnclaveIdentity) -> bool { self.may_replicate.contains(remote_enclave) } }
let untrusted_policy: SignedPolicySGX = cbor::from_slice(&raw)?; let policy = untrusted_policy.verify()?; let mut cached_policy = Self::default(); cached_policy.checksum = sha3_256(&raw).to_vec(); cached_policy.serial = policy.serial; cached_policy.runtime_id = policy.id; let enclave_identity = match EnclaveIdentity::current() { Some(enclave_identity) => enclave_identity, None => return Ok(cached_policy), }; let enclave_policy = match policy.enclaves.get(&enclave_identity) { Some(enclave_policy) => enclave_policy, None => return Ok(cached_policy), }; for (rt_id, ids) in &enclave_policy.may_query { let mut query_ids = HashSet::new(); for e_id in ids { query_ids.insert(e_id.clone()); } cached_policy.may_query.insert(*rt_id, query_ids); } for e_id in &enclave_policy.may_replicate { cached_policy.may_replicate.insert(e_id.clone()); } for (e_id, other_policy) in &policy.enclaves { if other_policy.may_replicate.contains(&enclave_identity) { cached_policy.may_replicate_from.insert(e_id.clone()); } } Ok(cached_policy) } fn default() -> Self { CachedPolicy { checksum: vec![], serial: 0, runtime_id: RuntimeId::default(), may_query: HashMap::new(), may_replicate: HashSet::new(), may_replicate_from: HashSet::new(), } } fn may_get_or_create_keys(&self, remo
random
[ { "content": "/// Unseal a previously sealed secret to the enclave.\n\n///\n\n/// The `context` field is a domain separation tag.\n\n///\n\n/// # Panics\n\n///\n\n/// All parsing and authentication errors of the ciphertext are fatal and\n\n/// will result in a panic.\n\npub fn unseal(key_policy: Keypolicy, cont...
Rust
core_nodes/src/abc.rs
alec-deason/virtual_modular
77857488c4b573522807430855c83bfc3d588647
use generic_array::{arr, typenum::*}; use std::collections::HashMap; use virtual_modular_graph::{Node, Ports, BLOCK_SIZE}; #[derive(Clone, Debug)] pub struct ABCSequence { line: Vec<abc_parser::datatypes::MusicSymbol>, key: HashMap<char, abc_parser::datatypes::Accidental>, idx: usize, clock: u32, sounding: Option<f32>, current_duration: f32, triggered: bool, } impl ABCSequence { pub fn new(tune: &str) -> Option<Self> { let parsed = abc_parser::abc::tune(tune).ok()?; let key = parsed .header .info .iter() .find(|f| f.0 == 'K') .map(|f| f.1.clone()) .unwrap_or("C".to_string()); let key: HashMap<_, _> = match key.as_str() { "C" => vec![], "G" => vec![('F', abc_parser::datatypes::Accidental::Sharp)], _ => panic!(), } .into_iter() .collect(); let mut line: Vec<_> = parsed .body .unwrap() .music .into_iter() .map(|l| l.symbols.clone()) .flatten() .collect(); line.retain(|s| match s { abc_parser::datatypes::MusicSymbol::Rest(abc_parser::datatypes::Rest::Note(..)) => true, abc_parser::datatypes::MusicSymbol::Note { .. } => true, _ => false, }); let mut r = Self { line, key, idx: 0, clock: 0, current_duration: 0.0, sounding: None, triggered: false, }; let dur = r.duration(0); r.clock = dur; r.current_duration = dur as f32 / 24.0; r.sounding = r.freq(0); Some(r) } } fn accidental_to_freq_multiplier(accidental: &abc_parser::datatypes::Accidental) -> f32 { let semitones = match accidental { abc_parser::datatypes::Accidental::Sharp => 1, abc_parser::datatypes::Accidental::Flat => -1, abc_parser::datatypes::Accidental::Natural => 0, abc_parser::datatypes::Accidental::DoubleSharp => 2, abc_parser::datatypes::Accidental::DoubleFlat => -2, }; 2.0f32.powf((semitones * 100) as f32 / 1200.0) } impl ABCSequence { fn freq(&self, idx: usize) -> Option<f32> { if let abc_parser::datatypes::MusicSymbol::Note { note, octave, accidental, .. } = self.line[idx] { if accidental.is_some() { todo!() } let mut base = match note { abc_parser::datatypes::Note::C => 16.35, abc_parser::datatypes::Note::D => 18.35, abc_parser::datatypes::Note::E => 20.60, abc_parser::datatypes::Note::F => 21.83, abc_parser::datatypes::Note::G => 24.50, abc_parser::datatypes::Note::A => 27.50, abc_parser::datatypes::Note::B => 30.87, }; let accidental = match note { abc_parser::datatypes::Note::C => self.key.get(&'C'), abc_parser::datatypes::Note::D => self.key.get(&'D'), abc_parser::datatypes::Note::E => self.key.get(&'E'), abc_parser::datatypes::Note::F => self.key.get(&'F'), abc_parser::datatypes::Note::G => self.key.get(&'G'), abc_parser::datatypes::Note::A => self.key.get(&'A'), abc_parser::datatypes::Note::B => self.key.get(&'B'), }; if let Some(accidental) = accidental { base *= accidental_to_freq_multiplier(accidental); } Some(base * 2.0f32.powi(octave as i32 + 2)) } else { panic!() } } fn duration(&self, idx: usize) -> u32 { match self.line[idx] { abc_parser::datatypes::MusicSymbol::Rest(abc_parser::datatypes::Rest::Note( _length, )) => { unimplemented!() } abc_parser::datatypes::MusicSymbol::Note { length, .. } => (length * 24.0) as u32, _ => panic!("{:?}", self.line[idx]), } } } impl Node for ABCSequence { type Input = U1; type Output = U4; #[inline] fn process(&mut self, input: Ports<Self::Input>) -> Ports<Self::Output> { let trigger = input[0]; let mut r_freq = [0.0f32; BLOCK_SIZE]; let mut r_gate = [0.0f32; BLOCK_SIZE]; let mut r_eoc = [0.0f32; BLOCK_SIZE]; let mut r_dur = [0.0f32; BLOCK_SIZE]; for i in 0..BLOCK_SIZE { if trigger[i] > 0.5 { if !self.triggered { self.triggered = true; self.clock -= 1; } } else { self.triggered = false; } if self.clock == 0 { self.idx = self.idx + 1; if self.idx >= self.line.len() { self.idx = 0; r_eoc[i] = 1.0; } self.clock = self.duration(self.idx); self.current_duration = self.clock as f32 / 24.0; self.sounding = self.freq(self.idx); r_gate[i] = 0.0; } else { r_gate[i] = if self.sounding.is_some() { 1.0 } else { 0.0 }; } r_freq[i] = self.sounding.unwrap_or(0.0); r_dur[i] = self.current_duration; } arr![[f32; BLOCK_SIZE]; r_freq, r_gate, r_eoc, r_dur] } }
use generic_array::{arr, typenum::*}; use std::collections::HashMap; use virtual_modular_graph::{Node, Ports, BLOCK_SIZE}; #[derive(Clone, Debug)] pub struct ABCSequence { line: Vec<abc_parser::datatypes::MusicSymbol>, key: HashMap<char, abc_parser::datatypes::Accidental>, idx: usize, clock: u32, sounding: Option<f32>, current_duration: f32, triggered: bool, } impl ABCSequence { pub fn new(tune: &str) -> Option<Self> { let parsed = abc_parser::abc::tune(tune).ok()?; let key = parsed .header .info .iter() .find(|f| f.0 == 'K') .map(|f| f.1.clone()) .unwrap_or("C".to_string()); let key: HashMap<_, _> = match key.as_str() { "C" => vec![], "G" => vec![('F', abc_parser::datatypes::Accidental::Sharp)], _ => panic!(), } .into_iter() .collect(); let mut line: Vec<_> = parsed .body .unwrap() .music .into_iter() .map(|l| l.symbols.clone()) .flatten() .collect(); line.retain(|s| match s { abc_parser::datatypes::MusicSymbol::Rest(abc_parser::datatypes::Rest::Note(..)) => true, abc_parser::datatypes::MusicSymbol::Note { .. } => true, _ => false, }); let mut r = Self { line, key, idx: 0, clock: 0, current_duration: 0.0, sounding: None, triggered: false, }; let dur = r.duration(0); r.clock = dur; r.current_duration = dur as f32 / 24.0; r.sounding = r.freq(0); Some(r) } } fn accidental_to_freq_multiplier(accidental: &abc_parser::datatypes::Accidental) -> f32 { let semitones = match accidental { abc_parser::datatypes::Accidental::Sharp => 1, abc_parser::datatypes::Accidental::Flat => -1, abc_parser::datatypes::Accidental::Natural => 0, abc_parser::datatypes::Accidental::DoubleSharp => 2, abc_parser::datatypes::Accidental::DoubleFlat => -2, }; 2.0f32.powf((semitones * 100) as f32 / 1200.0) } impl ABCSequence { fn freq(&self, idx: usize) -> Option<f32> { if let abc_parser::datatypes::MusicSymbol::Note { note, octave, accidental, .. } = self.line[idx] { if accidental.is_some() { todo!() } let mut base = match note { abc_parser::datatypes::Note::C => 16.35, abc_parser::datatypes::Note::D => 18.35, abc_parser::datatypes::Note::E => 20.60, abc_parser::datatypes::Note::F => 21.83, abc_parser::datatypes::Note::G => 24.50, abc_parser::datatypes::Note::A => 27.50, abc_parser::datatypes::Note::B => 30.87, }; let accidental = match note { abc_parser::datatypes::Note::C => self.key.get(&'C'), abc_parser::datatypes::Note::D => self.key.get(&'D'), abc_parser::datatypes::Note::E => self.key.get(&'E'), abc_parser::datatypes::Note::F => self.key.get(&'F'), abc_parser::datatypes::Note::G => self.key.get(&'G'), abc_parser::datatypes::Note::A => self.key.get(&'A'), abc_parser::datatypes::Note::B => self.key.get(&'B'), }; if let Some(accidental) = accidental { base *= accidental_to_freq_multiplier(accidental); } Some(base * 2.0f32.powi(octave as i32 + 2)) } else { panic!() } }
} impl Node for ABCSequence { type Input = U1; type Output = U4; #[inline] fn process(&mut self, input: Ports<Self::Input>) -> Ports<Self::Output> { let trigger = input[0]; let mut r_freq = [0.0f32; BLOCK_SIZE]; let mut r_gate = [0.0f32; BLOCK_SIZE]; let mut r_eoc = [0.0f32; BLOCK_SIZE]; let mut r_dur = [0.0f32; BLOCK_SIZE]; for i in 0..BLOCK_SIZE { if trigger[i] > 0.5 { if !self.triggered { self.triggered = true; self.clock -= 1; } } else { self.triggered = false; } if self.clock == 0 { self.idx = self.idx + 1; if self.idx >= self.line.len() { self.idx = 0; r_eoc[i] = 1.0; } self.clock = self.duration(self.idx); self.current_duration = self.clock as f32 / 24.0; self.sounding = self.freq(self.idx); r_gate[i] = 0.0; } else { r_gate[i] = if self.sounding.is_some() { 1.0 } else { 0.0 }; } r_freq[i] = self.sounding.unwrap_or(0.0); r_dur[i] = self.current_duration; } arr![[f32; BLOCK_SIZE]; r_freq, r_gate, r_eoc, r_dur] } }
fn duration(&self, idx: usize) -> u32 { match self.line[idx] { abc_parser::datatypes::MusicSymbol::Rest(abc_parser::datatypes::Rest::Note( _length, )) => { unimplemented!() } abc_parser::datatypes::MusicSymbol::Note { length, .. } => (length * 24.0) as u32, _ => panic!("{:?}", self.line[idx]), } }
function_block-full_function
[ { "content": "fn make_euclidian_rhythm(pulses: u32, len: u32, steps: &mut Vec<bool>) {\n\n steps.resize(len as usize, false);\n\n steps.fill(false);\n\n let mut bucket = 0;\n\n for step in steps.iter_mut() {\n\n bucket += pulses;\n\n if bucket >= len {\n\n bucket -= len;\n\n...
Rust
imgui/src/widget/tab.rs
eiz/imgui-rs
1ef9393f3253e4318e50219cd3c93fc98beeb578
use crate::sys; use crate::Ui; use bitflags::bitflags; use std::ptr; bitflags! { #[repr(transparent)] pub struct TabBarFlags: u32 { const REORDERABLE = sys::ImGuiTabBarFlags_Reorderable; const AUTO_SELECT_NEW_TABS = sys::ImGuiTabBarFlags_AutoSelectNewTabs; const TAB_LIST_POPUP_BUTTON = sys::ImGuiTabBarFlags_TabListPopupButton; const NO_CLOSE_WITH_MIDDLE_MOUSE_BUTTON = sys::ImGuiTabBarFlags_NoCloseWithMiddleMouseButton; const NO_TAB_LIST_SCROLLING_BUTTONS = sys::ImGuiTabBarFlags_NoTabListScrollingButtons; const NO_TOOLTIP = sys::ImGuiTabBarFlags_NoTooltip; const FITTING_POLICY_RESIZE_DOWN = sys::ImGuiTabBarFlags_FittingPolicyResizeDown; const FITTING_POLICY_SCROLL = sys::ImGuiTabBarFlags_FittingPolicyScroll; const FITTING_POLICY_MASK = sys::ImGuiTabBarFlags_FittingPolicyMask_; const FITTING_POLICY_DEFAULT = sys::ImGuiTabBarFlags_FittingPolicyDefault_; } } bitflags! { #[repr(transparent)] pub struct TabItemFlags: u32 { const UNSAVED_DOCUMENT = sys::ImGuiTabItemFlags_UnsavedDocument; const SET_SELECTED = sys::ImGuiTabItemFlags_SetSelected; const NO_CLOSE_WITH_MIDDLE_MOUSE_BUTTON = sys::ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; const NO_PUSH_ID = sys::ImGuiTabItemFlags_NoPushId; const NO_TOOLTIP = sys::ImGuiTabItemFlags_NoTooltip; const NO_REORDER = sys::ImGuiTabItemFlags_NoReorder; const LEADING = sys::ImGuiTabItemFlags_Leading; const TRAILING = sys::ImGuiTabItemFlags_Trailing; } } pub struct TabBar<T> { id: T, flags: TabBarFlags, } impl<T: AsRef<str>> TabBar<T> { #[inline] #[doc(alias = "BeginTabBar")] pub fn new(id: T) -> Self { Self { id, flags: TabBarFlags::empty(), } } #[inline] pub fn reorderable(mut self, value: bool) -> Self { self.flags.set(TabBarFlags::REORDERABLE, value); self } #[inline] pub fn flags(mut self, flags: TabBarFlags) -> Self { self.flags = flags; self } #[must_use] pub fn begin(self, ui: &Ui) -> Option<TabBarToken<'_>> { ui.tab_bar_with_flags(self.id, self.flags) } pub fn build<R, F: FnOnce() -> R>(self, ui: &Ui, f: F) -> Option<R> { self.begin(ui).map(|_tab| f()) } } create_token!( pub struct TabBarToken<'ui>; drop { sys::igEndTabBar() } ); pub struct TabItem<'a, T> { label: T, opened: Option<&'a mut bool>, flags: TabItemFlags, } impl<'a, T: AsRef<str>> TabItem<'a, T> { #[doc(alias = "BeginTabItem")] pub fn new(name: T) -> Self { Self { label: name, opened: None, flags: TabItemFlags::empty(), } } #[inline] pub fn opened(mut self, opened: &'a mut bool) -> Self { self.opened = Some(opened); self } #[inline] pub fn flags(mut self, flags: TabItemFlags) -> Self { self.flags = flags; self } #[must_use] pub fn begin(self, ui: &Ui) -> Option<TabItemToken<'_>> { ui.tab_item_with_flags(self.label, self.opened, self.flags) } pub fn build<R, F: FnOnce() -> R>(self, ui: &Ui, f: F) -> Option<R> { self.begin(ui).map(|_tab| f()) } } create_token!( pub struct TabItemToken<'ui>; drop { sys::igEndTabItem() } ); impl Ui { pub fn tab_bar(&self, id: impl AsRef<str>) -> Option<TabBarToken<'_>> { self.tab_bar_with_flags(id, TabBarFlags::empty()) } pub fn tab_bar_with_flags( &self, id: impl AsRef<str>, flags: TabBarFlags, ) -> Option<TabBarToken<'_>> { let should_render = unsafe { sys::igBeginTabBar(self.scratch_txt(id), flags.bits() as i32) }; if should_render { Some(TabBarToken::new(self)) } else { unsafe { sys::igEndTabBar() }; None } } pub fn tab_item(&self, label: impl AsRef<str>) -> Option<TabItemToken<'_>> { self.tab_item_with_flags(label, None, TabItemFlags::empty()) } pub fn tab_item_with_opened( &self, label: impl AsRef<str>, opened: &mut bool, ) -> Option<TabItemToken<'_>> { self.tab_item_with_flags(label, Some(opened), TabItemFlags::empty()) } pub fn tab_item_button_with_flags(&self, label: impl AsRef<str>, flags: TabItemFlags) -> bool { unsafe { sys::igTabItemButton(self.scratch_txt(label), flags.bits() as i32) } } pub fn tab_item_with_flags( &self, label: impl AsRef<str>, opened: Option<&mut bool>, flags: TabItemFlags, ) -> Option<TabItemToken<'_>> { let should_render = unsafe { sys::igBeginTabItem( self.scratch_txt(label), opened.map(|x| x as *mut bool).unwrap_or(ptr::null_mut()), flags.bits() as i32, ) }; if should_render { Some(TabItemToken::new(self)) } else { None } } }
use crate::sys; use crate::Ui; use bitflags::bitflags; use std::ptr; bitflags! { #[repr(transparent)] pub struct TabBarFlags: u32 { const REORDERABLE = sys::ImGuiTabBarFlags_Reorderable; const AUTO_SELECT_NEW_TABS = sys::ImGuiTabBarFlags_AutoSelectNewTabs; const TAB_LIST_POPUP_BUTTON = sys::ImGuiTabBarFlags_TabListPopupButton; const NO_CLOSE_WITH_MIDDLE_MOUSE_BUTTON = sys::ImGuiTabBarFlags_NoCloseWithMiddleMouseButton; const NO_TAB_LIST_SCROLLING_BUTTONS = sys::ImGuiTabBarFlags_NoTabListScrollingButtons; const NO_TOOLTIP = sys::ImGuiTabBarFlags_NoTooltip; const FITTING_POLICY_RESIZE_DOWN = sys::ImGuiTabBarFlags_FittingPolicyResizeDown; const FITTING_POLICY_SCROLL = sys::ImGuiTabBarFlags_FittingPolicyScroll; const FITTING_POLICY_MASK = sys::ImGuiTabBarFlags_FittingPolicyMask_; const FITTING_POLICY_DEFAULT = sys::ImGuiTabBarFlags_FittingPolicyDefault_; } } bitflags! { #[repr(transparent)] pub struct TabItemFlags: u32 { const UNSAVED_DOCUMENT = sys::ImGuiTabItemFlags_UnsavedDocument; const SET_SELECTED = sys::ImGuiTabItemFlags_SetSelected; const NO_CLOSE_WITH_MIDDLE_MOUSE_BUTTON = sys::ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; const NO_PUSH_ID = sys::ImGuiTabItemFlags_NoPushId; const NO_TOOLTIP = sys::ImGuiTabItemFlags_NoTooltip; const NO_REORDER = sys::ImGuiTabItemFlags_NoReorder; const LEADING = sys::ImGuiTabItemFlags_Leading; const TRAILING = sys::ImGuiTabItemFlags_Trailing; } } pub struct TabBar<T> { id: T, flags: TabBarFlags, } impl<T: AsRef<str>> TabBar<T> { #[inline] #[doc(alias = "BeginTabBar")] pub fn new(id: T) -> Self { Self { id, flags: TabBarFlags::empty(), } } #[inline] pub fn reorderable(mut self, value: bool) -> Self { self.flags.set(TabBarFlags::REORDERABLE, value); self } #[inline] pub fn flags(mut self, flags: TabBarFlags) -> Self { self.flags = flags; self } #[must_use] pub fn begin(self, ui: &Ui) -> Option<TabBarToken<'_>> { ui.tab_bar_with_flags(self.id, self.flags) } pub fn build<R, F: FnOnce() -> R>(self, ui: &Ui, f: F) -> Option<R> { self.begin(ui).map(|_tab| f()) } } create_token!( pub struct TabBarToken<'ui>; drop { sys::igEndTabBar() } ); pub struct TabItem<'a, T> { label: T, opened: Option<&'a mut bool>, flags: TabItemFlags, } impl<'a, T: AsRef<str>> TabItem<'a, T> { #[doc(alias = "BeginTabItem")] pub fn new(name: T) -> Self { Self { label: name, opened: None, flags: TabItemFlags::empty(), } } #[inline] pub fn opened(mut self, opened: &'a mut bool) -> Self { self.opened = Some(opened); self } #[inline] pub fn flags(mut self, flags: TabItemFlags) -> Self { self.flags = flags; self } #[must_use] pub fn begin(self, ui: &Ui) -> Option<TabItemToken<'_>> { ui.tab_item_with_flags(self.label, self.opened, self.flags) } pub fn build<R, F: FnOnce() -> R>(self, ui: &Ui, f: F) -> Option<R> { self.begin(ui).map(|_tab| f()) } } create_token!( pub struct TabItemToken<'ui>; drop { sys::igEndTabItem() } ); impl Ui { pub fn tab_bar(&self, id: impl AsRef<str>) -> Option<TabBarToken<'_>> { self.tab_bar_with_flags(id, TabBarFlags::empty()) } pub fn tab_bar_with_flags( &self, id: impl AsRef<str>, flags: TabBarFlags, ) -> Option<TabBarToken<'_>> { let should_render = unsafe { sys::igBeginTabBar(self.scratch_txt(id), flags.bits() as i32) }; if should_render { Some(TabBarToken::new(self)) } else { unsafe { sys::igEndTabBar() }; None } } pub fn tab_item(&self, label: impl AsRef<str>) -> Option<TabItemToken<'_>> { self.tab_item_with_flags(label, None, TabItemFlags::empty()) } pub fn tab_item_with_opened( &self, label: impl AsRef<str>, opened: &mut bool, ) -> Option<TabItemToken<'_>> { self.tab_item_with_flags(label, Some(opened), TabItemFlags::empty()) } pub fn tab_item_button_with_flags(&self, label: impl AsRef<str>, flags: TabItemFlags) -> bool { unsafe { sys::igTabItemButton(self.scratch_txt(label), flags.bits() as i32) } } pub fn tab_item_with_flags( &self, label: impl AsRef<str>, opened: Option<&mut bool>, flags: TabItemFlags, ) -> Option<TabItemToken<'_>> {
if should_render { Some(TabItemToken::new(self)) } else { None } } }
let should_render = unsafe { sys::igBeginTabItem( self.scratch_txt(label), opened.map(|x| x as *mut bool).unwrap_or(ptr::null_mut()), flags.bits() as i32, ) };
assignment_statement
[ { "content": "fn show_test_window(ui: &Ui, state: &mut State, opened: &mut bool) {\n\n if state.show_app_main_menu_bar {\n\n show_example_app_main_menu_bar(ui, state)\n\n }\n\n if state.show_app_auto_resize {\n\n show_example_app_auto_resize(\n\n ui,\n\n &mut state.a...
Rust
bolero-generator/src/uniform.rs
zhassan-aws/bolero
04a73b946da7241c188816524aaaec60d60658a3
use crate::{bounded::BoundExt, driver::DriverMode}; use core::ops::{Bound, RangeBounds}; pub trait Uniform: Sized { fn sample<F: FillBytes>(fill: &mut F, min: Bound<&Self>, max: Bound<&Self>) -> Option<Self>; } pub trait FillBytes { fn mode(&self) -> DriverMode; fn fill_bytes(&mut self, bytes: &mut [u8]) -> Option<()>; } macro_rules! uniform_int { ($ty:ident, $unsigned:ident $(, $smaller:ident)?) => { impl Uniform for $ty { #[inline] fn sample<F: FillBytes>(fill: &mut F, min: Bound<&$ty>, max: Bound<&$ty>) -> Option<$ty> { match (min, max) { (Bound::Unbounded, Bound::Unbounded) | (Bound::Unbounded, Bound::Included(&$ty::MAX)) | (Bound::Included(&$ty::MIN), Bound::Unbounded) | (Bound::Included(&$ty::MIN), Bound::Included(&$ty::MAX)) => { let mut bytes = [0u8; core::mem::size_of::<$ty>()]; fill.fill_bytes(&mut bytes)?; return Some(<$ty>::from_le_bytes(bytes)); } (Bound::Included(&x), Bound::Included(&y)) if x == y => { return Some(x); } (Bound::Included(&x), Bound::Excluded(&y)) if x + 1 == y => { return Some(x); } _ => {} } if fill.mode() == DriverMode::Direct { return Self::sample(fill, Bound::Unbounded, Bound::Unbounded) .filter(|value| (min, max).contains(value)); } let lower = match min { Bound::Included(&v) => v, Bound::Excluded(v) => v.saturating_add(1), Bound::Unbounded => $ty::MIN, }; let upper = match max { Bound::Included(&v) => v, Bound::Excluded(v) => v.saturating_sub(1), Bound::Unbounded => $ty::MAX, }; let (lower, upper) = if upper > lower { (lower, upper) } else { (upper, lower) }; let range = upper.wrapping_sub(lower) as $unsigned; if range == 0 { return Some(lower); } $({ use core::convert::TryInto; if let Ok(range) = range.try_into() { let value: $smaller = Uniform::sample(fill, Bound::Unbounded, Bound::Included(&range))?; let value = value as $ty; let value = lower.wrapping_add(value); if cfg!(test) { assert!((min, max).contains(&value), "{:?} < {} < {:?}", min, value, max); } return Some(value); } })? let value: $unsigned = Uniform::sample(fill, Bound::Unbounded, Bound::Unbounded)?; let value = value % range; let value = value as $ty; let value = lower.wrapping_add(value); if cfg!(test) { assert!((min, max).contains(&value), "{:?} < {} < {:?}", min, value, max); } Some(value) } } }; } uniform_int!(u8, u8); uniform_int!(i8, u8); uniform_int!(u16, u16, u8); uniform_int!(i16, u16, u8); uniform_int!(u32, u32, u16); uniform_int!(i32, u32, u16); uniform_int!(u64, u64, u32); uniform_int!(i64, u64, u32); uniform_int!(u128, u128, u64); uniform_int!(i128, u128, u64); uniform_int!(usize, usize, u64); uniform_int!(isize, usize, u64); impl Uniform for char { #[inline] fn sample<F: FillBytes>(fill: &mut F, min: Bound<&Self>, max: Bound<&Self>) -> Option<Self> { if fill.mode() == DriverMode::Direct { let value = u32::sample(fill, Bound::Unbounded, Bound::Unbounded)?; return char::from_u32(value); } const START: u32 = 0xD800; const LEN: u32 = 0xE000 - START; fn map_to_u32(c: &char) -> u32 { match *c as u32 { c if c >= START => c - LEN, c => c, } } let lower = BoundExt::map(min, map_to_u32); let upper = match max { Bound::Excluded(v) => Bound::Excluded(map_to_u32(v)), Bound::Included(v) => Bound::Included(map_to_u32(v)), Bound::Unbounded => Bound::Included(map_to_u32(&char::MAX)), }; let mut value = u32::sample(fill, BoundExt::as_ref(&lower), BoundExt::as_ref(&upper))?; if value >= START { value += LEN; } char::from_u32(value) } }
use crate::{bounded::BoundExt, driver::DriverMode}; use core::ops::{Bound, RangeBounds}; pub trait Uniform: Sized { fn sample<F: FillBytes>(fill: &mut F, min: Bound<&Self>, max: Bound<&Self>) -> Option<Self>; } pub trait FillBytes { fn mode(&self) -> DriverMode; fn fill_bytes(&mut self, bytes: &mut [u8]) -> Option<()>; } macro_rules! uniform_int { ($ty:ident, $unsigned:ident $(, $smaller:ident)?) => { impl Uniform for $ty { #[inline] fn sample<F: FillBytes>(fill: &mut F, min: Bound<&$ty>, max: Bound<&$ty>) -> Option<$ty> { match (min, max) { (Bound::Unbounded, Bound::Unbounded) | (Bound::Unbounded, Bound::Included(&$ty::MAX)) | (Bound::Included(&$ty::MIN), Bound::Unbounded) | (Bound::Included(&$ty::MIN), Bound::Included(&$ty::MAX)) => { let mut bytes = [0u8; core::mem::size_of::<$ty>()]; fill.fill_bytes(&mut bytes)?; return Some(<$ty>::from_le_bytes(bytes)); } (Bound::Included(&x), Bound::Included(&y)) if x == y => { return Some(x); } (Bound::Included(&x), Bound::Excluded(&y)) if x + 1 == y => { return Some(x); } _ => {} } if fill.mode() == DriverMode::Direct { return Self::sample(fill, Bound::Unbounded, Bound::Unbounded) .filter(|value| (min, max).contains(value)); } let lower = match min { Bound::Included(&v) => v, Bound::Excluded(v) => v.saturating_add(1), Bound::Unbounded => $ty::MIN, }; let upper = match max { Bound::Included(&v) => v, Bound::Excluded(v) => v.saturating_sub(1), Bound::Unbounded => $ty::MAX, }; let (lower, upper) = if upper > lower { (lower, upper) } else { (upper, lower) }; let range = upper.wrapping_sub(lower) as $unsigned; if range == 0 { return Some(lower); } $({ use core::convert::TryInto; if let Ok(range) = range.try_into() { let value: $smaller = Uniform::sample(fill, Bound::Unbounded, Bound::Included(&range))?; let value = value as $ty; let value = lower.wrapping_add(value); if cfg!(test) { assert!((min, max).contains(&value), "{:?} < {} < {:?}", min, value, max); } return Some(value); } })? let value: $unsigned = Uniform::sample(fill, Bound::Unbounded, Bound::Unbounded)?; let value = value % range; let value = value as $ty; let value = lower.wrapping_add(value); if cfg!(test) { assert!((min, max).contains(&value), "{:?} < {} < {:?}", min, value, max); } Some(value) } } }; } uniform_int!(u8, u8); uniform_int!(i8, u8); uniform_int!(u16, u16, u8); uniform_int!(i16, u16, u8); uniform_int!(u32, u32, u16); uniform_int!(i32, u32, u16); uniform_int!(u64, u64, u32); uniform_int!(i64, u64, u32); uniform_int!(u128, u128, u64); uniform_int!(i128, u128, u64); uniform_int!(usize, usize, u64); uniform_int!(isize, usize, u64); impl Uniform for char { #[inline] fn sample<F: FillBytes>(fill: &mut F, min: Bound<&Self>, max: Bound<&Self>) -> Option<Self> {
const START: u32 = 0xD800; const LEN: u32 = 0xE000 - START; fn map_to_u32(c: &char) -> u32 { match *c as u32 { c if c >= START => c - LEN, c => c, } } let lower = BoundExt::map(min, map_to_u32); let upper = match max { Bound::Excluded(v) => Bound::Excluded(map_to_u32(v)), Bound::Included(v) => Bound::Included(map_to_u32(v)), Bound::Unbounded => Bound::Included(map_to_u32(&char::MAX)), }; let mut value = u32::sample(fill, BoundExt::as_ref(&lower), BoundExt::as_ref(&upper))?; if value >= START { value += LEN; } char::from_u32(value) } }
if fill.mode() == DriverMode::Direct { let value = u32::sample(fill, Bound::Unbounded, Bound::Unbounded)?; return char::from_u32(value); }
if_condition
[ { "content": "pub trait BoundedValue<B = Self>: Sized {\n\n fn gen_bounded<D: Driver>(driver: &mut D, min: Bound<&B>, max: Bound<&B>) -> Option<Self>;\n\n\n\n fn mutate_bounded<D: Driver>(\n\n &mut self,\n\n driver: &mut D,\n\n min: Bound<&B>,\n\n max: Bound<&B>,\n\n ) -> Op...
Rust
alacritty/src/main.rs
vitaly-zdanevich/alacritty
6b208a6958a32594cf1248f5336f8a8f79d17fe3
#![warn(rust_2018_idioms, future_incompatible)] #![deny(clippy::all, clippy::if_not_else, clippy::enum_glob_use, clippy::wrong_pub_self_convention)] #![cfg_attr(feature = "cargo-clippy", deny(warnings))] #![cfg_attr(all(test, feature = "bench"), feature(test))] #![windows_subsystem = "windows"] #[cfg(not(any(feature = "x11", feature = "wayland", target_os = "macos", windows)))] compile_error!(r#"at least one of the "x11"/"wayland" features must be enabled"#); #[cfg(target_os = "macos")] use std::env; use std::error::Error; use std::fs; use std::io::{self, Write}; use std::sync::Arc; use glutin::event_loop::EventLoop as GlutinEventLoop; use log::{error, info}; #[cfg(windows)] use winapi::um::wincon::{AttachConsole, FreeConsole, ATTACH_PARENT_PROCESS}; use alacritty_terminal::event_loop::{self, EventLoop, Msg}; use alacritty_terminal::sync::FairMutex; use alacritty_terminal::term::Term; use alacritty_terminal::tty; mod cli; mod clipboard; mod config; mod cursor; mod daemon; mod display; mod event; mod input; mod logging; #[cfg(target_os = "macos")] mod macos; mod message_bar; mod meter; #[cfg(windows)] mod panic; mod renderer; mod scheduler; mod url; mod window; #[cfg(all(feature = "wayland", not(any(target_os = "macos", windows))))] mod wayland_theme; mod gl { #![allow(clippy::all)] include!(concat!(env!("OUT_DIR"), "/gl_bindings.rs")); } use crate::cli::Options; use crate::config::monitor; use crate::config::Config; use crate::display::Display; use crate::event::{Event, EventProxy, Processor}; #[cfg(target_os = "macos")] use crate::macos::locale; use crate::message_bar::MessageBuffer; fn main() { #[cfg(windows)] panic::attach_handler(); #[cfg(windows)] unsafe { AttachConsole(ATTACH_PARENT_PROCESS); } let options = Options::new(); let window_event_loop = GlutinEventLoop::<Event>::with_user_event(); let log_file = logging::initialize(&options, window_event_loop.create_proxy()) .expect("Unable to initialize logger"); let config = config::load(&options); log::set_max_level(config.ui_config.debug.log_level); #[cfg(target_os = "macos")] env::set_current_dir(dirs::home_dir().unwrap()).unwrap(); #[cfg(target_os = "macos")] locale::set_locale_environment(); let persistent_logging = config.ui_config.debug.persistent_logging; if let Err(err) = run(window_event_loop, config, options) { error!("Alacritty encountered an unrecoverable error:\n\n\t{}\n", err); std::process::exit(1); } if let Some(log_file) = log_file { if !persistent_logging && fs::remove_file(&log_file).is_ok() { let _ = writeln!(io::stdout(), "Deleted log file at \"{}\"", log_file.display()); } } } fn run( window_event_loop: GlutinEventLoop<Event>, config: Config, options: Options, ) -> Result<(), Box<dyn Error>> { info!("Welcome to Alacritty"); log_config_path(&config); tty::setup_env(&config); let event_proxy = EventProxy::new(window_event_loop.create_proxy()); let display = Display::new(&config, &window_event_loop)?; info!( "PTY dimensions: {:?} x {:?}", display.size_info.screen_lines(), display.size_info.cols() ); let terminal = Term::new(&config, display.size_info, event_proxy.clone()); let terminal = Arc::new(FairMutex::new(terminal)); let pty = tty::new(&config, &display.size_info, display.window.x11_window_id()); let event_loop = EventLoop::new( Arc::clone(&terminal), event_proxy.clone(), pty, config.hold, config.ui_config.debug.ref_test, ); let loop_tx = event_loop.channel(); if config.ui_config.live_config_reload() { monitor::watch(config.ui_config.config_paths.clone(), event_proxy); } let message_buffer = MessageBuffer::new(); let mut processor = Processor::new( event_loop::Notifier(loop_tx.clone()), message_buffer, config, display, options, ); let io_thread = event_loop.spawn(); info!("Initialisation complete"); processor.run(terminal, window_event_loop); drop(processor); loop_tx.send(Msg::Shutdown).expect("Error sending shutdown to PTY event loop"); io_thread.join().expect("join io thread"); #[cfg(windows)] unsafe { FreeConsole(); } info!("Goodbye"); Ok(()) } fn log_config_path(config: &Config) { let mut msg = String::from("Configuration files loaded from:"); for path in &config.ui_config.config_paths { msg.push_str(&format!("\n {:?}", path.display())); } info!("{}", msg); }
#![warn(rust_2018_idioms, future_incompatible)] #![deny(clippy::all, clippy::if_not_else, clippy::enum_glob_use, clippy::wrong_pub_self_convention)] #![cfg_attr(feature = "cargo-clippy", deny(warnings))] #![cfg_attr(all(test, feature = "bench"), feature(test))] #![windows_subsystem = "windows"] #[cfg(not(any(feature = "x11", feature = "wayland", target_os = "macos", windows)))] compile_error!(r#"at least one of the "x11"/"wayland" features must be enabled"#); #[cfg(target_os = "macos")] use std::env; use std::error::Error; use std::fs; use std::io::{self, Write}; use std::sync::Arc; use glutin::event_loop::EventLoop as GlutinEventLoop; use log::{error, info}; #[cfg(windows)] use winapi::um::wincon::{AttachConsole, FreeConsole, ATTACH_PARENT_PROCESS}; use alacritty_terminal::event_loop::{self, EventLoop, Msg}; use alacritty_terminal::sync::FairMutex; use alacritty_terminal::term::Term; use alacritty_terminal::tty; mod cli; mod clipboard; mod config; mod cursor; mod daemon; mod display; mod event; mod input; mod logging; #[cfg(target_os = "macos")] mod macos; mod message_bar; mod meter; #[cfg(windows)] mod panic; mod renderer; mod scheduler; mod url; mod window; #[cfg(all(feature = "wayland", not(any(target_os = "macos", windows))))] mod wayland_theme; mod gl { #![allow(clippy::all)] include!(concat!(env!("OUT_DIR"), "/gl_bindings.rs")); } use crate::cli::Options; use crate::config::monitor; use crate::config::Config; use crate::display::Display; use crate::event::{Event, EventProxy, Processor}; #[cfg(target_os = "macos")] use crate::macos::locale; use crate::message_bar::MessageBuffer; fn main() { #[cfg(windows)] panic::attach_handler(); #[cfg(windows)] unsafe { AttachConsole(ATTACH_PARENT_PROCESS); } let options = Options::new(); let window_event_loop = GlutinEventLoop::<Event>::with_user_event(); let log_file = logging::initialize(&options, window_event_loop.create_proxy()) .expect("Unable to initialize logger"); let config = config::load(&options); log::set_max_level(config.ui_config.debug.log_level); #[cfg(target_os = "macos")] env::set_current_dir(dirs::home_dir().unwrap()).unwrap(); #[cfg(target_os = "macos")] locale::set_locale_environment(); let persistent_logging = config.ui_config.debug.persistent_logging; if let Err(err) = run(window_event_loop, config, options) { error!("Alacritty encountered an unrecoverable error:\n\n\t{}\n", err); std::process::exit(1); } if let Some(log_file) = log_file { if !persistent_logging && fs::remove_file(&log_file).is_ok() { let _ = writeln!(io::stdout(), "Deleted log file at \"{}\"", log_file.display()); } } } fn run( window_event_loop: GlutinEventLoop<Event>, config: Config, options: Options, ) -> Result<(), Box<dyn Error>> { info!("Welcome to Alacritty"); log_config_path(&config); tty::setup_env(&config); let event_proxy = EventProxy::new(window_event_loop.create_proxy()); let display = Display::new(&config, &window_event_loop)?; info!( "PTY dimensions: {:?} x {:?}", display.size_info.screen_lines(), display.size_info.cols() ); let terminal = Term::new(&config, display.size_info, event_proxy.clone()); let terminal = Arc::new(FairMutex::new(terminal)); let pty = tty::new(&config, &display.size_info, display.window.x11_window_id()); let event_loop = EventLoop::new( Arc::clone(&terminal), event_proxy.clone(), pty, config.hold, config.ui_config.debug.ref_test, ); let loop_tx = event_loop.channel(); if config.ui_config.live_config_reload() { monitor::watch(config.ui_config.config_paths.clone(), event_proxy); } let message_buffer = MessageBuffer::new(); let mut processor = Processor::new( event_loop::Notifier(loop_tx.clone()), message_buffer, config, display, options, ); let io_thread = event_loop.spawn(); info!("Initialisation complete"); processor.run(terminal, window_event_loop); drop(processor); loop_tx.send(Msg::Shutdown).expect("Error sending shutdown to PTY event loop"); io_thread.join().expect("join io thread"); #[cfg(windows)] unsafe { FreeConsole(); } info!("Goodbye"); Ok(()) }
fn log_config_path(config: &Config) { let mut msg = String::from("Configuration files loaded from:"); for path in &config.ui_config.config_paths { msg.push_str(&format!("\n {:?}", path.display())); } info!("{}", msg); }
function_block-full_function
[ { "content": "#[cfg(not(all(feature = \"winpty\", target_env = \"msvc\")))]\n\npub fn new<C>(config: &Config<C>, size: &SizeInfo, window_id: Option<usize>) -> Pty {\n\n conpty::new(config, size, window_id).expect(\"Failed to create ConPTY backend\")\n\n}\n\n\n", "file_path": "alacritty_terminal/src/tty/w...
Rust
src/engine.rs
0ncorhynchus/mictyris
5f8bffe0fb6833048bac9d240050b92f5acd9a0d
mod auxiliary; pub mod procedure; mod storage; use self::auxiliary::*; use self::procedure::*; use self::storage::*; use crate::lexer::Identifier; use crate::parser::{Datum, Formals, ListDatum, Lit}; use crate::pass::*; use std::fmt; use std::rc::Rc; use Value::*; #[derive(Clone, Debug, PartialEq)] pub enum Value { Symbol(Identifier), Character(char), Number(f64), Pair(Location, Location, bool), Vector(Vec<Location>), Str(String), Bool(bool), Null, Unspecified, Undefined, Procedure(Proc), } impl Value { pub fn number(&self) -> Option<f64> { match self { Number(num) => Some(*num), _ => None, } } pub fn pair(&self) -> Option<(Location, Location, bool)> { match self { Pair(car, cdr, mutable) => Some((car.clone(), cdr.clone(), *mutable)), _ => None, } } } #[derive(Clone, Debug, PartialEq)] pub struct EvalError { pub message: String, } impl fmt::Display for EvalError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.message) } } #[derive(Default)] pub struct Engine { env: Env, store: Store, } impl Engine { pub fn new() -> Self { let mut engine = Self::default(); engine.register_proc("list", procedure::list); engine.register_proc("cons", procedure::cons); engine.register_proc("<", procedure::less); engine.register_proc("+", procedure::add); engine.register_proc("car", procedure::car); engine.register_proc("cdr", procedure::cdr); engine.register_proc("set-car!", procedure::setcar); engine.register_proc("eqv?", procedure::eqv); engine.register_proc("apply", procedure::apply); engine.register_proc("call-with-current-continuation", procedure::cwcc); engine.register_proc("call/cc", procedure::cwcc); engine.register_proc("values", procedure::values); engine.register_proc("call-with-values", procedure::cwv); engine } pub fn register(&mut self, variable: &str, value: Value) { let location = self.store.reserve(); self.store.update(&location, value); self.env.borrow_mut().insert(variable, location); } pub fn register_proc<F: 'static>(&mut self, variable: &str, proc: F) where F: Fn(&[Value], ExprCont) -> CommCont, { let location = self.store.reserve(); self.store .update(&location, Procedure(Proc::new(Rc::new(proc)))); self.env.borrow_mut().insert(variable, location); } pub fn eval(&mut self, ast: &AST) -> Answer { let expr_cont: ExprCont = Rc::new(|mut values: Vec<Value>| { let answer = values.pop().unwrap_or(Unspecified); let cont: CommCont = Rc::new(move |_store: &mut Store| Ok(answer.clone())); cont }); let cont = eval(ast, Rc::clone(&self.env), expr_cont); cont(&mut self.store) } pub fn eval_and_print(&mut self, ast: &AST) { let expr_cont: ExprCont = Rc::new(|mut values: Vec<Value>| { if let Some(value) = values.pop() { write(value) } else { Rc::new(|_| Ok(Unspecified)) } }); let cont = eval(ast, Rc::clone(&self.env), expr_cont); match cont(&mut self.store) { Ok(_) => (), Err(err) => eprintln!("Error: {}", err), } } } fn eval(ast: &AST, env: Env, expr_cont: ExprCont) -> CommCont { match ast { AST::Const(lit) => eval_literal(lit, expr_cont), AST::Var(ident) => eval_variable(ident, env, expr_cont), AST::Call(f, args) => eval_proc_call(f, args, env, expr_cont), AST::Lambda(args, commands, expr) => match args { Formals::List(args) => eval_lambda(args, commands, expr, env, expr_cont), Formals::Dot(args, var) => eval_lambda_dot(args, var, commands, expr, env, expr_cont), }, AST::Cond(test, conseq, alter) => match alter { Some(alter) => eval_conditional1(test, conseq, alter, env, expr_cont), None => eval_conditional2(test, conseq, env, expr_cont), }, AST::Assign(ident, expr) => eval_assign(ident, expr, env, expr_cont), } } fn eval_literal(lit: &Lit, expr_cont: ExprCont) -> CommCont { fn literal(store: &mut Store, lit: &Lit) -> Value { match lit { Lit::Bool(b) => Bool(*b), Lit::Number(n) => Number(*n), Lit::Character(c) => Character(*c), Lit::Str(s) => Str(s.clone()), Lit::Quote(d) => eval_datum(store, d), } } fn eval_datum(store: &mut Store, datum: &Datum) -> Value { match datum { Datum::Bool(b) => Bool(*b), Datum::Number(n) => Number(*n), Datum::Character(c) => Character(*c), Datum::Str(s) => Str(s.clone()), Datum::Symbol(ident) => Symbol(ident.clone()), Datum::List(data) => match data { ListDatum::List(data) => data.iter().rev().fold(Null, |acc, x| { let cdr = store.reserve(); store.update(&cdr, acc); let car = store.reserve(); let x = eval_datum(store, x); store.update(&car, x); Pair(car, cdr, true) }), ListDatum::Cons(data, last) => { let last = eval_datum(store, last); data.iter().rev().fold(last, |acc, x| { let cdr = store.reserve(); store.update(&cdr, acc); let car = store.reserve(); let x = eval_datum(store, x); store.update(&car, x); Pair(car, cdr, true) }) } ListDatum::Abbrev(_) => unimplemented!(), }, Datum::Vector(data) => { let mut locations = Vec::with_capacity(data.len()); for elem in data { let elem = eval_datum(store, elem); let loc = store.reserve(); store.update(&loc, elem); locations.push(loc); } Vector(locations) } } } let lit = lit.clone(); Rc::new(move |store| send(literal(store, &lit), &expr_cont)(store)) } fn eval_variable(ident: &str, env: Env, expr_cont: ExprCont) -> CommCont { let location = match env.borrow().lookup(ident) { Some(location) => location, None => { return wrong("undefined variable"); } }; let cont = single(move |value| send(value, &expr_cont)); hold(location, cont) } fn eval_proc_call(f: &AST, args: &[AST], env: Env, cont: ExprCont) -> CommCont { let mut exprs = Vec::with_capacity(args.len() + 1); exprs.push(f.clone()); exprs.extend_from_slice(args); let cont: ExprCont = Rc::new(move |values: Vec<Value>| { let (f, args) = values.split_first().unwrap(); applicate(f, args, Rc::clone(&cont)) }); eval_list(&exprs, env, cont) } fn eval_list(exprs: &[AST], env: Env, cont: ExprCont) -> CommCont { match exprs.split_first() { None => cont(vec![]), Some((head, tail)) => { let tail = tail.to_vec(); let copied_env = Rc::clone(&env); let cont = single(move |value: Value| { let cont = Rc::clone(&cont); let cont: ExprCont = Rc::new(move |mut values| { values.insert(0, value.clone()); cont(values) }); eval_list(&tail, Rc::clone(&copied_env), cont) }); eval(head, env, cont) } } } fn eval_lambda( args: &[String], commands: &[AST], expr: &AST, env: Env, cont: ExprCont, ) -> CommCont { let args = args.to_vec(); let commands = commands.to_vec(); let expr = expr.clone(); Rc::new(move |store: &mut Store| { let args = args.clone(); let commands = commands.clone(); let expr = expr.clone(); let env = Rc::clone(&env); let inner = Rc::new(move |values: &[Value], cont: ExprCont| { let args = args.clone(); let commands = commands.clone(); let expr = expr.clone(); if values.len() == args.len() { let env = Rc::clone(&env); let f = Rc::new(move |locations: &[Location]| { let env = extends(&env, &args, &locations); let cont = eval(&expr, Rc::clone(&env), Rc::clone(&cont)); eval_commands(&commands, env, cont) }); tievals(f, values) } else { wrong("wrong number of arguments") } }); let proc = Procedure(Proc::new(inner)); send(proc, &cont)(store) }) } #[allow(unused_variables)] fn eval_lambda_dot( args: &[String], var: &str, commands: &[AST], expr: &AST, env: Env, cont: ExprCont, ) -> CommCont { let min_args = args.len(); let mut args = args.to_vec(); args.push(var.to_string()); let commands = commands.to_vec(); let expr = expr.clone(); Rc::new(move |store: &mut Store| { let args = args.clone(); let commands = commands.clone(); let expr = expr.clone(); let env = Rc::clone(&env); let location = store.reserve(); let inner = Rc::new(move |values: &[Value], cont: ExprCont| { let args = args.clone(); let commands = commands.clone(); let expr = expr.clone(); if values.len() >= min_args { let env = Rc::clone(&env); let f = Rc::new(move |locations: &[Location]| { let env = extends(&env, &args, &locations); let cont = eval(&expr, Rc::clone(&env), Rc::clone(&cont)); eval_commands(&commands, env, cont) }); tievalsrest(f, values, min_args) } else { wrong("too few arguments") } }); let proc = Procedure(Proc::new(inner)); send(proc, &cont)(store) }) } fn eval_commands(commands: &[AST], env: Env, cont: CommCont) -> CommCont { match commands.split_first() { Some((head, tail)) => { let tail = tail.to_vec(); let copied_env = Rc::clone(&env); let cont = Rc::new(move |_: Vec<Value>| { eval_commands(&tail, Rc::clone(&copied_env), Rc::clone(&cont)) }); eval(head, env, cont) } None => cont, } } fn eval_conditional1(test: &AST, conseq: &AST, alter: &AST, env: Env, cont: ExprCont) -> CommCont { let conseq = conseq.clone(); let alter = alter.clone(); let copied_env = Rc::clone(&env); let cont = single(move |value| { let cont = Rc::clone(&cont); let env = Rc::clone(&copied_env); if truish(value) { eval(&conseq.clone(), env, cont) } else { eval(&alter.clone(), env, cont) } }); eval(test, env, cont) } fn eval_conditional2(test: &AST, conseq: &AST, env: Env, cont: ExprCont) -> CommCont { let conseq = conseq.clone(); let copied_env = Rc::clone(&env); let cont = single(move |value| { if truish(value) { eval(&conseq.clone(), Rc::clone(&copied_env), Rc::clone(&cont)) } else { send(Unspecified, &cont) } }); eval(test, env, cont) } fn eval_assign(ident: &str, expr: &AST, env: Env, cont: ExprCont) -> CommCont { let ident = ident.to_string(); let copied_env = Rc::clone(&env); let cont = single(move |value: Value| { let location = match env.borrow().lookup(&ident) { Some(location) => location, None => { return wrong("undefined variable"); } }; assign(location, value, send(Unspecified, &cont)) }); eval(expr, copied_env, cont) } pub type Answer = Result<Value, EvalError>; #[derive(Clone)] pub struct Proc { inner: Rc<dyn Fn(&[Value], ExprCont) -> CommCont>, } impl Proc { fn new(inner: Rc<dyn Fn(&[Value], ExprCont) -> CommCont>) -> Self { Self { inner } } } impl fmt::Debug for Proc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Proc") } } impl PartialEq for Proc { fn eq(&self, other: &Self) -> bool { Rc::ptr_eq(&self.inner, &other.inner) } } pub type CommCont = Rc<dyn Fn(&mut Store) -> Answer>; pub type ExprCont = Rc<dyn Fn(Vec<Value>) -> CommCont>; pub fn write(value: Value) -> CommCont { fn fmt(store: &Store, value: &Value) -> String { match value { Symbol(ident) => format!("{}", ident), Character(c) => format!("#\\{}", c), Number(n) => format!("{}", n), Pair(loc1, loc2, _) => format!( "({} . {})", fmt(store, &store.get(loc1)), fmt(store, &store.get(loc2)), ), Vector(locations) => { let mut strings = Vec::with_capacity(locations.len()); for loc in locations { strings.push(fmt(store, &store.get(loc))); } format!("#({})", strings.join(" ")) } Str(s) => s.clone(), Bool(b) => format!("{}", b), Null => "()".to_string(), Unspecified => "<unspecified>".to_string(), Undefined => "<undefined>".to_string(), Procedure(_) => "<procedure>".to_string(), } } Rc::new(move |store: &mut Store| { println!("{}", fmt(store, &value)); Ok(Unspecified) }) }
mod auxiliary; pub mod procedure; mod storage; use self::auxiliary::*; use self::procedure::*; use self::storage::*; use crate::lexer::Identifier; use crate::parser::{Datum, Formals, ListDatum, Lit}; use crate::pass::*; use std::fmt; use std::rc::Rc; use Value::*; #[derive(Clone, Debug, PartialEq)] pub enum Value { Symbol(Identifier), Character(char), Number(f64), Pair(Location, Location, bool), Vector(Vec<Location>), Str(String), Bool(bool), Null, Unspecified, Undefined, Procedure(Proc), } impl Value { pub fn number(&self) -> Option<f64> { match self { Number(num) => Some(*num), _ => None, } } pub fn pair(&self) -> Option<(Location, Location, bool)> { match self { Pair(car, cdr, mutable) => Some((car.clone(), cdr.clone(), *mutable)), _ => None, } } } #[derive(Clone, Debug, PartialEq)] pub struct EvalError { pub message: String, } impl fmt::Display for EvalError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.message) } } #[derive(Default)] pub struct Engine { env: Env, store: Store, } impl Engine { pub fn new() -> Self { let mut engine = Self::default(); engine.register_proc("list", procedure::list); engine.register_proc("cons", procedure::cons); engine.register_proc("<", procedure::less); engine.register_proc("+", procedure::add); engine.register_proc("car", procedure::car); engine.register_proc("cdr", procedure::cdr); engine.register_proc("set-car!", procedure::setcar); engine.register_proc("eqv?", procedure::eqv); engine.register_proc("apply", procedure::apply); engine.register_proc("call-with-current-continuation", procedure::cwcc); engine.register_proc("call/cc", procedure::cwcc); engine.register_proc("values", procedure::values); engine.register_proc("call-with-values", procedure::cwv); engine } pub fn register(&mut self, variable: &str, value: Value) { let location = self.store.reserve(); self.store.update(&location, value); self.env.borrow_mut().insert(variable, location); } pub fn register_proc<F: 'static>(&mut self, variable: &str, proc: F) where F: Fn(&[Value], ExprCont) -> CommCont, { let location = self.store.reserve(); self.store .update(&location, Procedure(Proc::new(Rc::new(proc)))); self.env.borrow_mut().insert(variable, location); } pub fn eval(&mut self, ast: &AST) -> Answer { let expr_cont: ExprCont = Rc::new(|mut values: Vec<Value>| { let answer = values.pop().unwrap_or(Unspecified); let cont: CommCont = Rc::new(move |_store: &mut Store| Ok(answer.clone())); cont }); let cont = eval(ast, Rc::clone(&self.env), expr_cont); cont(&mut self.store) } pub fn eval_and_print(&mut self, ast: &AST) { let expr_cont: ExprCont = Rc::new(|mut values: Vec<Value>| { if let Some(value) = values.pop() { write(value) } else { Rc::new(|_| Ok(Unspecified)) } }); let cont = eval(ast, Rc::clone(&self.env), expr_cont); match cont(&mut self.store) { Ok(_) => (), Err(err) => eprintln!("Error: {}", err), } } } fn eval(ast: &AST, env: Env, expr_cont: ExprCont) -> CommCont { match ast { AST::Const(lit) => eval_literal(lit, expr_cont), AST::Var(ident) => eval_variable(ident, env, expr_cont), AST::Call(f, args) => eval_proc_call(f, args, env, expr_cont), AST::Lambda(args, commands, expr) => match args { Formals::List(args) => eval_lambda(args, commands, expr, env, expr_cont), Formals::Dot(args, var) => eval_lambda_dot(args, var, commands, expr, env, expr_cont), }, AST::Cond(test, conseq, alter) => match alter { Some(alter) => eval_conditional1(test, conseq, alter, env, expr_cont), None => eval_conditional2(test, conseq, env, expr_cont), }, AST::Assign(ident, expr) => eval_assign(ident, expr, env, expr_cont), } } fn eval_literal(lit: &Lit, expr_cont: ExprCont) -> CommCont { fn literal(store: &mut Store, lit: &Lit) -> Value { match lit { Lit::Bool(b) => Bool(*b), Lit::Number(n) => Number(*n), Lit::Character(c) => Character(*c), Lit::Str(s) => Str(s.clone()), Lit::Quote(d) => eval_datum(store, d), } } fn eval_datum(store: &mut Store, datum: &Datum) -> Value { match datum { Datum::Bool(b) => Bool(*b), Datum::Number(n) => Number(*n), Datum::Character(c) => Character(*c), Datum::Str(s) => Str(s.clone()), Datum::Symbol(ident) => Symbol(ident.clone()), Datum::List(data) => match data { ListDatum::List(data) => data.iter().rev().fold(Null, |acc, x| { let cdr = store.reserve(); store.update(&cdr, acc); let car = store.reserve(); let x = eval_datum(store, x); store.update(&car, x); Pair(car, cdr, true) }), ListDatum::Cons(data, last) => { let last = eval_datum(store, last); data.iter().rev().fold(last, |acc, x| { let cdr = store.reserve(); store.update(&cdr, acc); let car = store.reserve(); let x = eval_datum(store, x); store.update(&car, x); Pair(car, cdr, true) }) } ListDatum::Abbrev(_) => unimplemented!(), }, Datum::Vector(data) => { let mut locations = Vec::with_capacity(data.len()); for elem in data { let elem = eval_datum(store, elem); let loc = store.reserve(); store.update(&loc, elem); locations.push(loc); } Vector(locations) } } } let lit = lit.clone(); Rc::new(move |store| send(literal(store, &lit), &expr_cont)(store)) } fn eval_variable(ident: &str, env: Env, expr_cont: ExprCont) -> CommCont { let location = match env.borrow().lookup(ident) { Some(location) => location, None => { return wrong("undefined variable"); } }; let cont = single(move |value| send(value, &expr_cont)); hold(location, cont) } fn eval_proc_call(f: &AST, args: &[AST], env: Env, cont: ExprCont) -> CommCont { let mut exprs = Vec::with_capacity(args.len() + 1); exprs.push(f.clone()); exprs.extend_from_slice(args); let cont: ExprCont = Rc::new(move |values: Vec<Value>| { let (f, args) = values.split_first().unwrap(); applicate(f, args, Rc::clone(&cont)) }); eval_list(&exprs, env, cont) } fn eval_list(exprs: &[AST], env: Env, cont: ExprCont) -> CommCont { match exprs.split_first() { None => cont(vec![]), Some((head, tail)) => { let tail = tail.to_vec(); let copied_env = Rc::clone(&env); let cont = single(move |value: Value| { let cont = Rc::clone(&cont); let cont: ExprCont = Rc::new(move |mut values| { values.insert(0, value.clone()); cont(values) }); eval_list(&tail, Rc::clone(&copied_env), cont) }); eval(head, env, cont) } } } fn eval_lambda( args: &[String], commands: &[AST], expr: &AST, env: Env, cont: ExprCont, ) -> CommCont { let args = args.to_vec(); let commands = commands.to_vec(); let expr = expr.clone(); Rc::new(move |store: &mut Store| { let args = args.clone(); let commands = commands.clone(); let expr = expr.clone(); let env = Rc::clone(&env); let inner = Rc::new(move |values: &[Value], cont: ExprCont| { let args = args.clone(); let commands = commands.clone(); let expr = expr.clone(); if values.len() == args.len() { let env = Rc::clone(&env); let f = Rc::new(move |locations: &[Location]| { let env = extends(&env, &args, &locations); let cont = eval(&expr, Rc::clone(&env), Rc::clone(&cont)); eval_commands(&commands, env, cont) }); tievals(f, values) } else { wrong("wrong number of arguments") } }); let proc = Procedure(Proc::new(inner)); send(proc, &cont)(store) }) } #[allow(unused_variables)] fn eval_lambda_dot( args: &[String], var: &str, commands: &[AST], expr: &AST, env: Env, cont: ExprCont, ) -> CommCont { let min_args = args.len(); let mut args = args.to_vec(); args.push(var.to_string()); let commands = commands.to_vec(); let expr = expr.clone(); Rc::new(move |store: &mut Store| { let args = args.clone(); let commands = commands.clone(); let expr = expr.clone(); let env = Rc::clone(&env); let location = store.reserve(); let inner = Rc::new(move |values: &[Value], cont: ExprCont| { let args = args.clone(); let commands = commands.clone(); let expr = expr.clone(); if values.len() >= min_args { let env = Rc::clone(&env); let f = Rc::new(move |locations: &[Location]| { let env = extends(&env, &args, &locations); let cont = eval(&expr, Rc::clone(&env), Rc::clone(&cont)); eval_commands(&commands, env, cont) }); tievalsrest(f, values, min_args) } else { wrong("too few arguments") } }); let proc = Procedure(Proc::new(inner)); send(proc, &cont)(store) }) } fn eval_commands(commands: &[AST], env: Env, cont: CommCont) -> CommCont { match commands.split_first() { Some((head, tail)) => { let tail = tail.to_vec(); let copied_env = Rc::clone(&env); let cont = Rc::new(move |_: Vec<Value>| { eval_commands(&tail, Rc::clone(&copied_env), Rc::clone(&cont)) }); eval(head, env, cont) } None => cont, } } fn eval_conditional1(test: &AST, conseq: &AST, alter: &AST, env: Env, cont: ExprCont) -> CommCont { let conseq = conseq.clone(); let alter = alter.clone(); let copied_env = Rc::clone(&env); let cont = single(move |value| { let cont = Rc::clone(&cont); let env = Rc::clone(&copied_env); if truish(value) { eval(&conseq.clone(), env, cont) } else { eval(&alter.clone(), env, cont) } }); eval(test, env, cont) } fn eval_conditional2(test: &AST, conseq: &AST, env: Env, cont: ExprCont) -> CommCont { let conseq = conseq.clone(); let copied_env = Rc::clone(&env); let cont = single(move |value| { if truish(value) { eval(&conseq.clone(), Rc::clone(&copied_env), Rc::clone(&cont)) } else { send(Unspecified, &cont) } }); eval(test, env, cont) } fn eval_assign(ident: &str, expr: &AST, env: Env, cont: ExprCont) -> CommCont { let ident = ident.to_string(); let copied_env = Rc::clone(&env); let cont = single(move |value: Value| { let location = match env.borrow().lookup(&ident) { Some(location) => location, None => { return wrong("undefined variable"); } }; assign(location, value, send(Unspecified, &cont)) }); eval(expr, copied_env, cont) } pub type Answer = Result<Value, EvalError>; #[derive(Clone)] pub struct Proc { inner: Rc<dyn Fn(&[Value], ExprCont) -> CommCont>, } impl Proc { fn new(inner: Rc<dyn Fn(&[Value], ExprCont) -> CommCont>) -> Self { Self { inner } } } impl fmt::Debug for Proc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Proc") } } impl PartialEq for Proc { fn eq(&self, other: &Self) -> bool { Rc::ptr_eq(&self.inner, &other.inner) } } pub type CommCont = Rc<dyn Fn(&mut Store) -> Answer>; pub type ExprCont = Rc<dyn Fn(Vec<Value>) -> CommCont>;
pub fn write(value: Value) -> CommCont { fn fmt(store: &Store, value: &Value) -> String { match value { Symbol(ident) => format!("{}", ident), Character(c) => format!("#\\{}", c), Number(n) => format!("{}", n), Pair(loc1, loc2, _) => format!( "({} . {})", fmt(store, &store.get(loc1)), fmt(store, &store.get(loc2)), ), Vector(locations) => { let mut strings = Vec::with_capacity(locations.len()); for loc in locations { strings.push(fmt(store, &store.get(loc))); } format!("#({})", strings.join(" ")) } Str(s) => s.clone(), Bool(b) => format!("{}", b), Null => "()".to_string(), Unspecified => "<unspecified>".to_string(), Undefined => "<undefined>".to_string(), Procedure(_) => "<procedure>".to_string(), } } Rc::new(move |store: &mut Store| { println!("{}", fmt(store, &value)); Ok(Unspecified) }) }
function_block-full_function
[ { "content": "pub fn cdr(values: &[Value], cont: ExprCont) -> CommCont {\n\n onearg(\n\n |arg, cont| match arg.pair() {\n\n Some((_, cdr, _)) => hold(cdr, cont),\n\n None => wrong(\"non-pair argument\"),\n\n },\n\n values,\n\n cont,\n\n )\n\n}\n\n\n", ...
Rust
src/network.rs
Aloxaf/mcfly
0f50f2deeed7c8ec75d41711369c2fc927006a4e
#![allow(clippy::unreadable_literal)] use crate::node::Node; use crate::training_sample_generator::TrainingSampleGenerator; use crate::history::Features; use rand::Rng; #[derive(Debug, Copy, Clone)] pub struct Network { pub final_bias: f64, pub final_weights: [f64; 3], pub final_sum: f64, pub final_output: f64, pub hidden_nodes: [Node; 3], pub hidden_node_sums: [f64; 3], pub hidden_node_outputs: [f64; 3], } impl Default for Network { fn default() -> Network { Network { final_bias: -0.3829333755179377, final_weights: [ 0.44656858145177714, -1.9550439349609872, -2.963322601316632 ], final_sum: 0.0, final_output: 0.0, hidden_nodes: [ Node { offset: -0.878184962836099, age: -0.9045522440219468, length: 0.5406937685800283, exit: -0.3472765681766297, recent_failure: -0.05291342121445077, selected_dir: -0.35027519196134, dir: -0.2466069217936986, overlap: 0.4791784213482642, immediate_overlap: 0.5565797758340211, selected_occurrences: -0.3600203296209723, occurrences: 0.15694312742881805 }, Node { offset: -0.04362945902379799, age: -0.25381913331319716, length: 0.4238780143901607, exit: 0.21906785628210726, recent_failure: -0.9510136025685453, selected_dir: -0.04654084670567356, dir: -2.2858050301068693, overlap: -0.562274365705918, immediate_overlap: -0.47252489212451904, selected_occurrences: 0.2446391951417497, occurrences: -1.4846489581676605 }, Node { offset: -0.11992725490486622, age: 0.3759013420273308, length: 1.674601413922965, exit: -0.15529596916772864, recent_failure: -0.7819181782432957, selected_dir: -1.1890532332896768, dir: 0.34723729558743677, overlap: 0.09372412920642742, immediate_overlap: 0.393989158881144, selected_occurrences: -0.2383372126951215, occurrences: -2.196219880265691 } ], hidden_node_sums: [ 0.0, 0.0, 0.0 ], hidden_node_outputs: [ 0.0, 0.0, 0.0 ] } } } impl Network { pub fn random() -> Network { let mut rng = rand::thread_rng(); Network { final_bias: rng.gen_range(-1.0, 1.0), final_weights: [rng.gen_range(-1.0, 1.0), rng.gen_range(-1.0, 1.0), rng.gen_range(-1.0, 1.0)], hidden_nodes: [Node::random(), Node::random(), Node::random()], hidden_node_sums: [0.0, 0.0, 0.0], hidden_node_outputs: [0.0, 0.0, 0.0], final_sum: 0.0, final_output: 0.0, } } pub fn compute(&mut self, features: &Features) { self.final_sum = self.final_bias; for i in 0..self.hidden_nodes.len() { self.hidden_node_sums[i] = self.hidden_nodes[i].dot(features); self.hidden_node_outputs[i] = self.hidden_node_sums[i].tanh(); self.final_sum += self.hidden_node_outputs[i] * self.final_weights[i]; } self.final_output = self.final_sum.tanh(); } pub fn dot(&self, features: &Features) -> f64 { let mut network_output = self.final_bias; for (node, output_weight) in self.hidden_nodes.iter().zip(self.final_weights.iter()) { let node_output = node.output(features); network_output += node_output * output_weight; } network_output } pub fn output(&self, features: &Features) -> f64 { self.dot(features).tanh() } pub fn average_error(&self, generator: &TrainingSampleGenerator, records: usize) -> f64 { let mut error = 0.0; let mut samples = 0.0; generator.generate(Some(records), |features: &Features, correct: bool| { let target = if correct { 1.0 } else { -1.0 }; let output = self.output(features); error += 0.5 * (target - output).powi(2); samples += 1.0; }); error / samples } }
#![allow(clippy::unreadable_literal)] use crate::node::Node; use crate::training_sample_generator::TrainingSampleGenerator; use crate::history::Features; use rand::Rng; #[derive(Debug, Copy, Clone)] pub struct Network { pub final_bias: f64, pub final_weights: [f64; 3], pub final_sum: f64, pub final_output: f64, pub hidden_nodes: [Node; 3], pub hidden_node_sums: [f64; 3], pub hidden_node_outputs: [f64; 3], } impl Default for Network { fn default() -> Network { Network { final_bias: -0.3829333755179377, final_weights: [ 0.44656858145177714, -1.9550439349609872, -2.963322601316632 ], final_sum: 0.0, final_output: 0.0, hidden_nodes: [ Node { offset: -0.878184962836099, age: -0.9045522440219468, length: 0.5406937685800283, exit: -0.3472765681766297, recent_failure: -0.05291342121445077, selected_dir: -0.35027519196134, dir: -0.2466069217936986, overlap: 0.4791784213482642, immediate_overlap: 0.5565797758340211, selected_occurrences: -0.3600203296209723, occurrences: 0.15694312742881805 }, Node { offset: -0.04362945902379799, age: -0.25381913331319716, length: 0.4238780143901607, exit: 0.21906785628210726, recent_failure: -0.9510136025685453, selected_dir: -0.04654084670567356, dir: -2.2858050301068693, overlap: -0.562274365705918, immediate_overlap: -0.47252489212451904, selected_occurrences: 0.2446391951417497, occurrences: -1.4846489581676605 }, Node { offset: -0.11992725490486622, age: 0.3759013420273308, length: 1.674601413922965, exit: -0.15529596916772864, recent_failure: -0.7819181782432957, selected_dir: -1.1890532332896768, dir: 0.34723729558743677, overlap: 0.09372412920642742, immediate_overlap: 0.393989158881144, selected_occurrences: -0.2383372126951215, occurrences: -2.196219880265691 } ], hidden_node_sums: [ 0.0, 0.0, 0.0 ], hidden_node_outputs: [ 0.0, 0.0, 0.0 ] } } } impl Network { pub fn random() -> Network { let mut rng = rand::thread_rng(); Network { final_bias: rng.gen_range(-1.0, 1.0), final_weights: [rng.gen_range(-1.0, 1.0), rng.gen_range(-1.0, 1.0), rng.gen_range(-1.0, 1.0)], hidden_nodes: [Node::random(), Node::random(), Node::random()], hidden_node_sums: [0.0, 0.0, 0.0], hidden_node_outputs: [0.0, 0.0, 0.0], final_sum: 0.0, final_output: 0.0, } } pub fn compute(&mut self, features: &Features) { self.final_sum = self.final_bias; for i in 0..self.hidden_nodes.len() { self.hidden_node_sums[i] = self.hidden_nodes[i].dot(features); self.hidden_node_outputs[i] = self.hidden_node_sums[i].tanh(); sel
pub fn dot(&self, features: &Features) -> f64 { let mut network_output = self.final_bias; for (node, output_weight) in self.hidden_nodes.iter().zip(self.final_weights.iter()) { let node_output = node.output(features); network_output += node_output * output_weight; } network_output } pub fn output(&self, features: &Features) -> f64 { self.dot(features).tanh() } pub fn average_error(&self, generator: &TrainingSampleGenerator, records: usize) -> f64 { let mut error = 0.0; let mut samples = 0.0; generator.generate(Some(records), |features: &Features, correct: bool| { let target = if correct { 1.0 } else { -1.0 }; let output = self.output(features); error += 0.5 * (target - output).powi(2); samples += 1.0; }); error / samples } }
f.final_sum += self.hidden_node_outputs[i] * self.final_weights[i]; } self.final_output = self.final_sum.tanh(); }
function_block-function_prefixed
[ { "content": "pub fn use_tiocsti(string: &str) {\n\n for byte in string.as_bytes() {\n\n let a: *const u8 = byte;\n\n if unsafe { ioctl(0, libc::TIOCSTI as u32, a) } < 0 {\n\n panic!(\"Error encountered when calling ioctl\");\n\n }\n\n }\n\n}\n", "file_path": "src/fake_...
Rust
src/node_state/leader/follower.rs
yuezato/raftlog
12315643c559118dbe9c20625ff9e3c415bf9bb3
use futures::{Async, Future}; use std::collections::BTreeMap; use std::mem; use trackable::error::ErrorKindExt; use super::super::Common; use crate::cluster::ClusterConfig; use crate::log::{Log, LogIndex}; use crate::message::{AppendEntriesReply, SequenceNumber}; use crate::node::NodeId; use crate::{ErrorKind, Io, Result}; pub struct FollowersManager<IO: Io> { followers: BTreeMap<NodeId, Follower>, config: ClusterConfig, latest_hearbeat_ack: SequenceNumber, last_broadcast_seq_no: SequenceNumber, tasks: BTreeMap<NodeId, IO::LoadLog>, } impl<IO: Io> FollowersManager<IO> { pub fn new(config: ClusterConfig) -> Self { let followers = config .members() .map(|n| (n.clone(), Follower::new())) .collect(); FollowersManager { followers, config, tasks: BTreeMap::new(), latest_hearbeat_ack: SequenceNumber::new(0), last_broadcast_seq_no: SequenceNumber::new(0), } } pub fn run_once(&mut self, common: &mut Common<IO>) -> Result<()> { let mut dones = Vec::new(); for (follower, task) in &mut self.tasks { if let Async::Ready(log) = track!(task.poll())? { dones.push((follower.clone(), log)); } } for (follower, log) in dones { let rpc = common.rpc_caller(); match log { Log::Prefix(snapshot) => rpc.send_install_snapshot(&follower, snapshot), Log::Suffix(slice) => rpc.send_append_entries(&follower, slice), } self.tasks.remove(&follower); } Ok(()) } pub fn latest_hearbeat_ack(&self) -> SequenceNumber { self.latest_hearbeat_ack } pub fn committed_log_tail(&self) -> LogIndex { self.config.consensus_value(|node_id| { let f = &self.followers[node_id]; if f.synced { f.log_tail } else { LogIndex::new(0) } }) } pub fn joint_committed_log_tail(&self) -> LogIndex { self.config.full_consensus_value(|node_id| { let f = &self.followers[node_id]; if f.synced { f.log_tail } else { LogIndex::new(0) } }) } pub fn handle_append_entries_reply( &mut self, common: &Common<IO>, reply: &AppendEntriesReply, ) -> bool { let updated = self.update_follower_state(common, reply); if self.latest_hearbeat_ack < reply.header.seq_no { self.latest_hearbeat_ack = self .config .consensus_value(|node_id| self.followers[node_id].last_seq_no); } updated } pub fn set_last_broadcast_seq_no(&mut self, seq_no: SequenceNumber) { self.last_broadcast_seq_no = seq_no; } pub fn log_sync(&mut self, common: &mut Common<IO>, reply: &AppendEntriesReply) -> Result<()> { if reply.busy || self.tasks.contains_key(&reply.header.sender) { return Ok(()); } let follower = track!(self .followers .get_mut(&reply.header.sender) .ok_or_else(|| ErrorKind::InconsistentState.error()))?; if reply.header.seq_no <= follower.obsolete_seq_no { return Ok(()); } follower.obsolete_seq_no = self.last_broadcast_seq_no; if common.log().tail().index <= follower.log_tail { return Ok(()); } let end = if follower.synced { common.log().tail().index } else { follower.log_tail }; let future = common.load_log(follower.log_tail, Some(end)); self.tasks.insert(reply.header.sender.clone(), future); Ok(()) } pub fn handle_config_updated(&mut self, config: &ClusterConfig) { for id in config.members() { if !self.followers.contains_key(id) { self.followers.insert(id.clone(), Follower::new()); } } self.followers = mem::take(&mut self.followers) .into_iter() .filter(|&(ref id, _)| config.is_known_node(id)) .collect(); self.config = config.clone(); } fn update_follower_state(&mut self, common: &Common<IO>, reply: &AppendEntriesReply) -> bool { let follower = &mut self .followers .get_mut(&reply.header.sender) .expect("Never fails"); if follower.last_seq_no < reply.header.seq_no { follower.last_seq_no = reply.header.seq_no; } match *reply { AppendEntriesReply { busy: true, .. } => false, AppendEntriesReply { log_tail, .. } if follower.synced => { let updated = follower.log_tail < log_tail.index; if updated { follower.log_tail = log_tail.index; } else if log_tail.index.as_u64() == 0 && follower.log_tail.as_u64() != 0 { follower.synced = false; } updated } AppendEntriesReply { log_tail, .. } => { let leader_term = common .log() .get_record(log_tail.index) .map(|r| r.head.prev_term); follower.synced = leader_term == Some(log_tail.prev_term); if follower.synced { follower.log_tail = log_tail.index; } else { follower.log_tail = log_tail.index.as_u64().saturating_sub(1).into(); } follower.synced } } } } #[derive(Debug)] struct Follower { pub obsolete_seq_no: SequenceNumber, pub log_tail: LogIndex, pub last_seq_no: SequenceNumber, pub synced: bool, } impl Follower { pub fn new() -> Self { Follower { obsolete_seq_no: SequenceNumber::new(0), log_tail: LogIndex::new(0), last_seq_no: SequenceNumber::new(0), synced: false, } } }
use futures::{Async, Future}; use std::collections::BTreeMap; use std::mem; use trackable::error::ErrorKindExt; use super::super::Common; use crate::cluster::ClusterConfig; use crate::log::{Log, LogIndex}; use crate::message::{AppendEntriesReply, SequenceNumber}; use crate::node::NodeId; use crate::{ErrorKind, Io, Result}; pub struct FollowersManager<IO: Io> { followers: BTreeMap<NodeId, Follower>, config: ClusterConfig, latest_hearbeat_ack: SequenceNumber, last_broadcast_seq_no: SequenceNumber, tasks: BTreeMap<NodeId, IO::LoadLog>, } impl<IO: Io> FollowersManager<IO> { pub fn new(config: ClusterConfig) -> Self { let followers = config .members() .map(|n| (n.clone(), Follower::new())) .collect(); FollowersManager { followers, config, tasks: BTreeMap::new(), latest_hearbeat_ack: SequenceNumber::new(0), last_broadcast_seq_no: SequenceNumber::new(0), } } pub fn run_once(&mut self, common: &mut Common<IO>) -> Result<()> { let mut dones = Vec::new(); for (follower, task) in &mut self.tasks { if let Async::Ready(log) = track!(task.poll())? { dones.push((follower.clone(), log)); } } for (follower, log) in dones { let rpc = common.rpc_caller(); match log { Log::Prefix(snapshot) => rpc.send_install_snapshot(&follower, snapshot), Log::Suffix(slice) => rpc.send_append_entries(&follower, slice), } self.tasks.remove(&follower); } Ok(()) } pub fn latest_hearbeat_ack(&self) -> SequenceNumber { self.latest_hearbeat_ack } pub fn committed_log_tail(&self) -> LogIndex { self.config.consensus_value(|node_id| { let f = &self.followers[node_id]; if f.synced { f.log_tail } else { LogIndex::new(0) } }) } pub fn joint_committed_log_tail(&self) -> LogIndex { self.config.full_consensus_value(|node_id| { let f = &self.followers[node_id]; if f.synced { f.log_tail } else { LogIndex::new(0) } }) } pub fn handle_append_entries_reply( &mut self, common: &Common<IO>, reply: &AppendEntriesReply, ) -> bool { let updated = self.update_follower_state(common, reply); if self.latest_hearbeat_ack < reply.header.seq_no { self.latest_hearbeat_ack = self .config .consensus_value(|node_id| self.followers[node_id].last_seq_no); } updated } pub fn set_last_broadcast_seq_no(&mut self, seq_no: SequenceNumber) { self.last_broadcast_seq_no = seq_no; } pub fn log_sync(&mut self, common: &mut Common<IO>, reply: &AppendEntriesReply) -> Result<()> { if reply.busy || self.tasks.contains_key(&reply.header.sender) { return Ok(()); }
if reply.header.seq_no <= follower.obsolete_seq_no { return Ok(()); } follower.obsolete_seq_no = self.last_broadcast_seq_no; if common.log().tail().index <= follower.log_tail { return Ok(()); } let end = if follower.synced { common.log().tail().index } else { follower.log_tail }; let future = common.load_log(follower.log_tail, Some(end)); self.tasks.insert(reply.header.sender.clone(), future); Ok(()) } pub fn handle_config_updated(&mut self, config: &ClusterConfig) { for id in config.members() { if !self.followers.contains_key(id) { self.followers.insert(id.clone(), Follower::new()); } } self.followers = mem::take(&mut self.followers) .into_iter() .filter(|&(ref id, _)| config.is_known_node(id)) .collect(); self.config = config.clone(); } fn update_follower_state(&mut self, common: &Common<IO>, reply: &AppendEntriesReply) -> bool { let follower = &mut self .followers .get_mut(&reply.header.sender) .expect("Never fails"); if follower.last_seq_no < reply.header.seq_no { follower.last_seq_no = reply.header.seq_no; } match *reply { AppendEntriesReply { busy: true, .. } => false, AppendEntriesReply { log_tail, .. } if follower.synced => { let updated = follower.log_tail < log_tail.index; if updated { follower.log_tail = log_tail.index; } else if log_tail.index.as_u64() == 0 && follower.log_tail.as_u64() != 0 { follower.synced = false; } updated } AppendEntriesReply { log_tail, .. } => { let leader_term = common .log() .get_record(log_tail.index) .map(|r| r.head.prev_term); follower.synced = leader_term == Some(log_tail.prev_term); if follower.synced { follower.log_tail = log_tail.index; } else { follower.log_tail = log_tail.index.as_u64().saturating_sub(1).into(); } follower.synced } } } } #[derive(Debug)] struct Follower { pub obsolete_seq_no: SequenceNumber, pub log_tail: LogIndex, pub last_seq_no: SequenceNumber, pub synced: bool, } impl Follower { pub fn new() -> Self { Follower { obsolete_seq_no: SequenceNumber::new(0), log_tail: LogIndex::new(0), last_seq_no: SequenceNumber::new(0), synced: false, } } }
let follower = track!(self .followers .get_mut(&reply.header.sender) .ok_or_else(|| ErrorKind::InconsistentState.error()))?;
assignment_statement
[ { "content": "struct InstallSnapshot<IO: Io> {\n\n future: IO::SaveLog,\n\n summary: SnapshotSummary,\n\n}\n\nimpl<IO: Io> InstallSnapshot<IO> {\n\n pub fn new(common: &mut Common<IO>, prefix: LogPrefix) -> Self {\n\n let summary = SnapshotSummary {\n\n tail: prefix.tail,\n\n ...
Rust
state/api/src/chain_state.rs
xielong/starcoin
14faf39ea7231d6a24780a87f847584824e7ff18
use anyhow::{ensure, format_err, Result}; use merkle_tree::{blob::Blob, proof::SparseMerkleProof, RawKey}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use starcoin_crypto::HashValue; use starcoin_types::state_set::AccountStateSet; use starcoin_types::write_set::WriteSet; use starcoin_types::{ access_path::AccessPath, account_address::AccountAddress, account_config::{AccountResource, BalanceResource}, account_state::AccountState, language_storage::TypeTag, state_set::ChainStateSet, }; use starcoin_vm_types::account_config::{genesis_address, STC_TOKEN_CODE}; use starcoin_vm_types::genesis_config::ChainId; use starcoin_vm_types::language_storage::ModuleId; use starcoin_vm_types::on_chain_resource::{Epoch, EpochData, EpochInfo, GlobalTimeOnChain}; use starcoin_vm_types::sips::SIP; use starcoin_vm_types::token::token_code::TokenCode; use starcoin_vm_types::{ move_resource::MoveResource, on_chain_config::OnChainConfig, state_view::StateView, }; use std::convert::TryFrom; use std::sync::Arc; #[derive(Debug, Default, Eq, PartialEq, Clone, Serialize, Deserialize)] pub struct StateProof { pub account_state: Option<Blob>, pub account_proof: SparseMerkleProof, pub account_state_proof: SparseMerkleProof, } impl StateProof { pub fn new( account_state: Option<Vec<u8>>, account_proof: SparseMerkleProof, account_state_proof: SparseMerkleProof, ) -> Self { Self { account_state: account_state.map(Blob::from), account_proof, account_state_proof, } } pub fn verify( &self, expected_root_hash: HashValue, access_path: AccessPath, access_resource_blob: Option<&[u8]>, ) -> Result<()> { let (account_address, data_path) = access_path.into_inner(); match self.account_state.as_ref() { None => { ensure!( access_resource_blob.is_none(), "accessed resource should not exists" ); } Some(s) => { let account_state = AccountState::try_from(s.as_ref())?; match account_state.storage_roots()[data_path.data_type().storage_index()] { None => { ensure!( access_resource_blob.is_none(), "accessed resource should not exists" ); } Some(expected_hash) => { let blob = access_resource_blob.map(|data| Blob::from(data.to_vec())); self.account_state_proof.verify( expected_hash, data_path.key_hash(), blob.as_ref(), )?; } } } } self.account_proof.verify( expected_root_hash, account_address.key_hash(), self.account_state.as_ref(), ) } } #[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)] pub struct StateWithProof { pub state: Option<Vec<u8>>, pub proof: StateProof, } impl StateWithProof { pub fn new(state: Option<Vec<u8>>, proof: StateProof) -> Self { Self { state, proof } } pub fn get_state(&self) -> &Option<Vec<u8>> { &self.state } } pub trait ChainStateReader: StateView { fn get_with_proof(&self, access_path: &AccessPath) -> Result<StateWithProof>; fn get_account_state(&self, address: &AccountAddress) -> Result<Option<AccountState>>; fn get_account_state_set(&self, address: &AccountAddress) -> Result<Option<AccountStateSet>>; fn exist_account(&self, address: &AccountAddress) -> Result<bool> { self.get_account_state(address).map(|state| state.is_some()) } fn state_root(&self) -> HashValue; fn dump(&self) -> Result<ChainStateSet>; } pub trait ChainStateWriter { fn set(&self, access_path: &AccessPath, value: Vec<u8>) -> Result<()>; fn remove(&self, access_path: &AccessPath) -> Result<()>; fn apply(&self, state_set: ChainStateSet) -> Result<()>; fn apply_write_set(&self, write_set: WriteSet) -> Result<()>; fn commit(&self) -> Result<HashValue>; fn flush(&self) -> Result<()>; } pub trait IntoSuper<Super: ?Sized> { fn as_super(&self) -> &Super; fn as_super_mut(&mut self) -> &mut Super; fn into_super(self: Box<Self>) -> Box<Super>; fn into_super_arc(self: Arc<Self>) -> Arc<Super>; } pub trait ChainState: ChainStateReader + ChainStateWriter + StateView + IntoSuper<dyn StateView> + IntoSuper<dyn ChainStateReader> + IntoSuper<dyn ChainStateWriter> { } impl<'a, T: 'a + ChainStateReader> IntoSuper<dyn ChainStateReader + 'a> for T { fn as_super(&self) -> &(dyn ChainStateReader + 'a) { self } fn as_super_mut(&mut self) -> &mut (dyn ChainStateReader + 'a) { self } fn into_super(self: Box<Self>) -> Box<dyn ChainStateReader + 'a> { self } fn into_super_arc(self: Arc<Self>) -> Arc<dyn ChainStateReader + 'a> { self } } impl<'a, T: 'a + ChainStateWriter> IntoSuper<dyn ChainStateWriter + 'a> for T { fn as_super(&self) -> &(dyn ChainStateWriter + 'a) { self } fn as_super_mut(&mut self) -> &mut (dyn ChainStateWriter + 'a) { self } fn into_super(self: Box<Self>) -> Box<dyn ChainStateWriter + 'a> { self } fn into_super_arc(self: Arc<Self>) -> Arc<dyn ChainStateWriter + 'a> { self } } impl<'a, T: 'a + StateView> IntoSuper<dyn StateView + 'a> for T { fn as_super(&self) -> &(dyn StateView + 'a) { self } fn as_super_mut(&mut self) -> &mut (dyn StateView + 'a) { self } fn into_super(self: Box<Self>) -> Box<dyn StateView + 'a> { self } fn into_super_arc(self: Arc<Self>) -> Arc<dyn StateView + 'a> { self } } impl<T: ?Sized> StateReaderExt for T where T: ChainStateReader {} pub trait StateReaderExt: ChainStateReader { fn get_account_resource(&self, address: AccountAddress) -> Result<Option<AccountResource>> { self.get_resource::<AccountResource>(address) } fn get_resource<R>(&self, address: AccountAddress) -> Result<Option<R>> where R: MoveResource + DeserializeOwned, { let access_path = AccessPath::new(address, R::resource_path()); let r = self.get(&access_path).and_then(|state| match state { Some(state) => Ok(Some(bcs_ext::from_bytes::<R>(state.as_slice())?)), None => Ok(None), })?; Ok(r) } fn get_sequence_number(&self, address: AccountAddress) -> Result<u64> { self.get_account_resource(address)? .map(|resource| resource.sequence_number()) .ok_or_else(|| format_err!("Can not find account by address:{}", address)) } fn get_on_chain_config<C>(&self) -> Result<Option<C>> where C: OnChainConfig, Self: Sized, { C::fetch_config(self) } fn get_balance(&self, address: AccountAddress) -> Result<Option<u128>> { self.get_balance_by_token_code(address, STC_TOKEN_CODE.clone()) } fn get_balance_by_type( &self, address: AccountAddress, type_tag: TypeTag, ) -> Result<Option<u128>> { Ok(self .get(&AccessPath::new( address, BalanceResource::access_path_for(type_tag), )) .and_then(|bytes| match bytes { Some(bytes) => Ok(Some(bcs_ext::from_bytes::<BalanceResource>( bytes.as_slice(), )?)), None => Ok(None), })? .map(|resource| resource.token())) } fn get_balance_by_token_code( &self, address: AccountAddress, token_code: TokenCode, ) -> Result<Option<u128>> { self.get_balance_by_type(address, token_code.into()) } fn get_epoch(&self) -> Result<Epoch> { self.get_resource::<Epoch>(genesis_address())? .ok_or_else(|| format_err!("Epoch is none.")) } fn get_epoch_info(&self) -> Result<EpochInfo> { let epoch = self .get_resource::<Epoch>(genesis_address())? .ok_or_else(|| format_err!("Epoch is none."))?; let epoch_data = self .get_resource::<EpochData>(genesis_address())? .ok_or_else(|| format_err!("Epoch is none."))?; Ok(EpochInfo::new(epoch, epoch_data)) } fn get_timestamp(&self) -> Result<GlobalTimeOnChain> { self.get_resource(genesis_address())? .ok_or_else(|| format_err!("Timestamp resource should exist.")) } fn get_chain_id(&self) -> Result<ChainId> { self.get_resource::<ChainId>(genesis_address())? .ok_or_else(|| format_err!("ChainId resource should exist at genesis address. ")) } fn get_code(&self, module_id: ModuleId) -> Result<Option<Vec<u8>>> { self.get(&AccessPath::from(&module_id)) } fn is_activated(&self, sip: SIP) -> Result<bool> { self.get_code(sip.module_id()).map(|code| code.is_some()) } } pub struct AccountStateReader<'a, Reader> { reader: &'a Reader, } impl<'a, Reader> AccountStateReader<'a, Reader> where Reader: ChainStateReader, { pub fn new(reader: &'a Reader) -> Self { Self { reader } } pub fn get_account_resource( &self, address: &AccountAddress, ) -> Result<Option<AccountResource>> { self.reader.get_account_resource(*address) } pub fn get_resource<R>(&self, address: AccountAddress) -> Result<Option<R>> where R: MoveResource + DeserializeOwned, { self.reader.get_resource(address) } pub fn get_sequence_number(&self, address: AccountAddress) -> Result<u64> { self.reader.get_sequence_number(address) } pub fn get_on_chain_config<C>(&self) -> Result<Option<C>> where C: OnChainConfig, { self.reader.get_on_chain_config() } pub fn get_balance(&self, address: &AccountAddress) -> Result<Option<u128>> { self.reader.get_balance(*address) } pub fn get_balance_by_type( &self, address: &AccountAddress, type_tag: TypeTag, ) -> Result<Option<u128>> { self.reader.get_balance_by_type(*address, type_tag) } pub fn get_balance_by_token_code( &self, address: &AccountAddress, token_code: TokenCode, ) -> Result<Option<u128>> { self.reader.get_balance_by_token_code(*address, token_code) } pub fn get_epoch(&self) -> Result<Epoch> { self.reader.get_epoch() } pub fn get_epoch_info(&self) -> Result<EpochInfo> { self.reader.get_epoch_info() } pub fn get_timestamp(&self) -> Result<GlobalTimeOnChain> { self.reader.get_timestamp() } pub fn get_chain_id(&self) -> Result<ChainId> { self.reader.get_chain_id() } }
use anyhow::{ensure, format_err, Result}; use merkle_tree::{blob::Blob, proof::SparseMerkleProof, RawKey}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use starcoin_crypto::HashValue; use starcoin_types::state_set::AccountStateSet; use starcoin_types::write_set::WriteSet; use starcoin_types::{ access_path::AccessPath, account_address::AccountAddress, account_config::{AccountResource, BalanceResource}, account_state::AccountState, language_storage::TypeTag, state_set::ChainStateSet, }; use starcoin_vm_types::account_config::{genesis_address, STC_TOKEN_CODE}; use starcoin_vm_types::genesis_config::ChainId; use starcoin_vm_types::language_storage::ModuleId; use starcoin_vm_types::on_chain_resource::{Epoch, EpochData, EpochInfo, GlobalTimeOnChain}; use starcoin_vm_types::sips::SIP; use starcoin_vm_types::token::token_code::TokenCode; use starcoin_vm_types::{ move_resource::MoveResource, on_chain_config::OnChainConfig, state_view::StateView, }; use std::convert::TryFrom; use std::sync::Arc; #[derive(Debug, Default, Eq, PartialEq, Clone, Serialize, Deserialize)] pub struct StateProof { pub account_state: Option<Blob>, pub account_proof: SparseMerkleProof, pub account_state_proof: SparseMerkleProof, } impl StateProof { pub fn new( account_state: Option<Vec<u8>>, account_proof: SparseMerkleProof, account_state_proof: SparseMerkleProof, ) -> Self { Self { account_state: account_state.map(Blob::from), account_proof, account_state_proof, } } pub fn verify( &self, expected_root_hash: HashValue, access_path: AccessPath, access_resource_blob: Option<&[u8]>, ) -> Result<()> { let (account_address, data_path) = access_path.into_inner(); match self.account_state.as_ref() { None => { ensure!( access_resource_blob.is_none(), "accessed resource should not exists" ); } Some(s) => { let account_state = AccountState::try_from(s.as_ref())?; match account_state.storage_roots()[data_path.data_type().storage_index()] { None => { ensure!( access_resource_blob.is_none(), "accessed resource should not exists" ); } Some(expected_hash) => { let blob = access_resource_blob.map(|data| Blob::from(data.to_vec())); self.account_state_proof.verify( expected_hash, data_path.key_hash(), blob.as_ref(), )?; } } } } self.account_proof.verify( expected_root_hash, account_address.key_hash(), self.account_state.as_ref(), ) } } #[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)] pub struct StateWithProof { pub state: Option<Vec<u8>>, pub proof: StateProof, } impl StateWithProof { pub fn new(state: Option<Vec<u8>>, proof: StateProof) -> Self { Self { state, proof } } pub fn get_state(&self) -> &Option<Vec<u8>> { &self.state } } pub trait ChainStateReader: StateView { fn get_with_proof(&self, access_path: &AccessPath) -> Result<StateWithProof>; fn get_account_state(&self, address: &AccountAddress) -> Result<Option<AccountState>>; fn get_account_state_set(&self, address: &AccountAddress) -> Result<Option<AccountStateSet>>; fn exist_account(&self, address: &AccountAddress) -> Result<bool> { self.get_account_state(address).map(|state| state.is_some()) } fn state_root(&self) -> HashValue; fn dump(&self) -> Result<ChainStateSet>; } pub trait ChainStateWriter { fn set(&self, access_path: &AccessPath, value: Vec<u8>) -> Result<()>; fn remove(&self, access_path: &AccessPath) -> Result<()>; fn apply(&self, state_set: ChainStateSet) -> Result<()>; fn apply_write_set(&self, write_set: WriteSet) -> Result<()>; fn commit(&self) -> Result<HashValue>; fn flush(&self) -> Result<()>; } pub trait IntoSuper<Super: ?Sized> { fn as_super(&self) -> &Super; fn as_super_mut(&mut self) -> &mut Super; fn into_super(self: Box<Self>) -> Box<Super>; fn into_super_arc(self: Arc<Self>) -> Arc<Super>; } pub trait ChainState: ChainStateReader + ChainStateWriter + StateView + IntoSuper<dyn StateView> + IntoSuper<dyn ChainStateReader> + IntoSuper<dyn ChainStateWriter> { } impl<'a, T: 'a + ChainStateReader> IntoSuper<dyn ChainStateReader + 'a> for T { fn as_super(&self) -> &(dyn ChainStateReader + 'a) { self } fn as_super_mut(&mut self) -> &mut (dyn ChainStateReader + 'a) { self } fn into_super(self: Box<Self>) -> Box<dyn ChainStateReader + 'a> { self } fn into_super_arc(self: Arc<Self>) -> Arc<dyn ChainStateReader + 'a> { self } } impl<'a, T: 'a + ChainStateWriter> IntoSuper<dyn ChainStateWriter + 'a> for T { fn as_super(&self) -> &(dyn ChainStateWriter + 'a) { self } fn as_super_mut(&mut self) -> &mut (dyn ChainStateWriter + 'a) { self } fn into_super(self: Box<Self>) -> Box<dyn ChainStateWriter + 'a> { self } fn into_super_arc(self: Arc<Self>) -> Arc<dyn ChainStateWriter + 'a> { self } } impl<'a, T: 'a + StateView> IntoSuper<dyn StateView + 'a> for T { fn as_super(&self) -> &(dyn StateView + 'a) { self } fn as_super_mut(&mut self) -> &mut (dyn StateView + 'a) { self } fn into_super(self: Box<Self>) -> Box<dyn StateView + 'a> { self } fn into_super_arc(self: Arc<Self>) -> Arc<dyn StateView + 'a> { self } } impl<T: ?Sized> StateReaderExt for T where T: ChainStateReader {} pub trait StateReaderExt: ChainStateReader { fn get_account_resource(&self, address: AccountAddress) -> Result<Option<AccountResource>> { self.get_resource::<AccountResource>(address) } fn get_resource<R>(&self, address: AccountAddress) -> Result<Option<R>> where R: MoveResource + DeserializeOwned, { let access_path = AccessPath::new(address, R::resource_path()); let r = self.get(&access_path).and_then(|state| match state { Some(state) => Ok(Some(bcs_ext::from_bytes::<R>(state.as_slice())?)), None => Ok(None), })?; Ok(r) } fn get_sequence_number(&self, address: AccountAddress) -> Result<u64> { self.get_account_resource(address)? .map(|resource| resource.sequence_number()) .ok_or_else(|| format_err!("Can not find account by address:{}", address)) } fn get_on_chain_config<C>(&self) -> Result<Option<C>> where C: OnChainConfig, Self: Sized, { C::fetch_config(self) } fn get_balance(&self, address: AccountAddress) -> Result<Option<u128>> { self.get_balance_by_token_code(address, STC_TOKEN_CODE.clone()) } fn get_balance_by_type( &self, address: AccountAddress, type_tag: TypeTag, ) -> Result<Option<u128>> { Ok(self .get(&AccessPath::new( address, BalanceResource::access_path_for(type_tag), )) .and_then(|bytes| match bytes { Some(bytes) => Ok(Some(bcs_ext::from_bytes::<BalanceResource>( bytes.as_slice(), )?)), None => Ok(None), })? .map(|resource| resource.token())) } fn get_balance_by_token_code( &self, address: AccountAddress, token_code: TokenCode, ) -> Result<Option<u128>> { self.get_balance_by_type(address, token_code.into()) } fn get_epoch(&self) -> Result<Epoch> { self.get_resource::<Epoch>(genesis_address())? .ok_or_else(|| format_err!("Epoch is none.")) } fn get_epoch_info(&self) -> Result<EpochInfo> { let epoch = self .get_resource::<Epoch>(genesis_address())? .ok_or_else(|| format_err!("Epoch is none."))?; let epoch_data = self .get_resource::<EpochData>(genesis_address())? .ok_or_else(|| format_err!("Epoch is none."))?; Ok(EpochInfo::new(epoch, epoch_data)) } fn get_timestamp(&self) -> Result<GlobalTimeOnChain> { self.get_resource(genesis_address())? .ok_or_else(|| format_err!("Timestamp resource should exist.")) } fn get_chain_id(&self) -> Result<ChainId> { self.get_resource::<ChainId>(genesis_address())? .ok_or_else(|| format_err!("ChainId resource should exist at genesis address. ")) } fn get_code(&self, module_id: ModuleId) -> Result<Option<Vec<u8>>> { self.get(&AccessPath::from(&module_id)) } fn is_activated(&self, sip: SIP) -> Result<bool> { self.get_code(sip.module_id()).map(|code| code.is_some()) } } pub struct AccountStateReader<'a, Reader> { reader: &'a Reader, } impl<'a, Reader> AccountStateReader<'a, Reader> where Reader: ChainStateReader, { pub fn new(reader: &'a Reader) -> Self { Self { reader } } pub fn get_account_resource( &self, address: &AccountAddress, ) -> Result<Option<AccountResource>> { self.reader.get_account_resource(*address) } pub fn get_resource<R>(&self, address: AccountAddress) -> Result<Option<R>> where R: MoveResource + DeserializeOwned, { self.reader.get_resource(address) } pub fn get_sequence_number(&self, address: AccountAddress) -> Result<u64> { self.reader.get_sequence_number(address) }
pub fn get_balance(&self, address: &AccountAddress) -> Result<Option<u128>> { self.reader.get_balance(*address) } pub fn get_balance_by_type( &self, address: &AccountAddress, type_tag: TypeTag, ) -> Result<Option<u128>> { self.reader.get_balance_by_type(*address, type_tag) } pub fn get_balance_by_token_code( &self, address: &AccountAddress, token_code: TokenCode, ) -> Result<Option<u128>> { self.reader.get_balance_by_token_code(*address, token_code) } pub fn get_epoch(&self) -> Result<Epoch> { self.reader.get_epoch() } pub fn get_epoch_info(&self) -> Result<EpochInfo> { self.reader.get_epoch_info() } pub fn get_timestamp(&self) -> Result<GlobalTimeOnChain> { self.reader.get_timestamp() } pub fn get_chain_id(&self) -> Result<ChainId> { self.reader.get_chain_id() } }
pub fn get_on_chain_config<C>(&self) -> Result<Option<C>> where C: OnChainConfig, { self.reader.get_on_chain_config() }
function_block-full_function
[ { "content": "pub fn access_path_for_module_upgrade_strategy(address: AccountAddress) -> AccessPath {\n\n AccessPath::resource_access_path(address, ModuleUpgradeStrategy::struct_tag())\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct TwoPhaseUpgradeV2Resource {\n\n config: TwoPhaseUpgrad...
Rust
multi-skill/src/systems/true_skill/normal.rs
kiwec/Elo-MMR
bf64ea75e8c0dbb946d379b9bee1753e604b388a
use super::float::{erfc, Float, MyFloat, PI, TWO, ZERO}; use overload::overload; use std::ops; #[derive(Clone, Debug)] pub struct Gaussian { pub mu: MyFloat, pub sigma: MyFloat, } pub const G_ZERO: Gaussian = Gaussian { mu: ZERO, sigma: ZERO, }; pub const G_ONE: Gaussian = Gaussian { mu: ZERO, sigma: MyFloat::INFINITY, }; overload!((a: ?Gaussian) + (b: ?Gaussian) -> Gaussian { Gaussian { mu: a.mu + b.mu, sigma: a.sigma.hypot(b.sigma), } }); overload!((a: &mut Gaussian) += (b: ?Gaussian) { a.mu += b.mu; a.sigma = a.sigma.hypot(b.sigma); }); overload!((a: ?Gaussian) - (b: ?Gaussian) -> Gaussian { Gaussian { mu: a.mu - b.mu, sigma: a.sigma.hypot(b.sigma), } }); overload!((a: &mut Gaussian) -= (b: ?Gaussian) { a.mu -= b.mu; a.sigma = a.sigma.hypot(b.sigma); }); overload!(-(a: &mut Gaussian) -> Gaussian { Gaussian { mu: -a.mu, sigma: a.sigma, } }); overload!((a: ?Gaussian) * (b: ?MyFloat) -> Gaussian { Gaussian { mu: a.mu * b, sigma: a.sigma * b.abs(), } }); overload!((a: &mut Gaussian) *= (b: ?MyFloat) { a.mu *= b; a.sigma *= b.abs(); }); overload!((a: ?Gaussian) / (b: ?MyFloat) -> Gaussian { Gaussian { mu: a.mu / b, sigma: a.sigma / b.abs(), } }); overload!((a: &mut Gaussian) /= (b: ?MyFloat) { a.mu /= b; a.sigma /= b.abs(); }); overload!((a: ?Gaussian) * (b: ?Gaussian) -> Gaussian { if a.sigma.is_infinite() { return b.clone(); } if b.sigma.is_infinite() { return a.clone(); } let ssigma1 = a.sigma.powi(2); let ssigma2 = b.sigma.powi(2); Gaussian { mu: (a.mu * ssigma2 + b.mu * ssigma1) / (ssigma1 + ssigma2), sigma: a.sigma * b.sigma / (ssigma1 + ssigma2).sqrt(), } }); overload!((a: &mut Gaussian) *= (b: ?Gaussian) { *a = a.clone() * b; }); overload!((a: ?Gaussian) / (b: ?Gaussian) -> Gaussian { if b.sigma.is_infinite() { return a.clone(); } if a.sigma.is_infinite() { return Gaussian { mu: -b.mu, sigma: b.sigma, } } let ssigma1 = a.sigma.powi(2); let ssigma2 = b.sigma.powi(2); Gaussian { mu: (a.mu * ssigma2 - b.mu * ssigma1) / (ssigma2 - ssigma1), sigma: a.sigma * b.sigma / (ssigma2 - ssigma1).abs().sqrt(), } }); overload!((a: &mut Gaussian) /= (b: ?Gaussian) { *a = a.clone() / b; }); fn gauss_exponent(mu: MyFloat, sigma: MyFloat, t: MyFloat) -> MyFloat { (-((t - mu) / sigma).powi(2)).exp() } fn moment0(mu: MyFloat, sigma: MyFloat, t: MyFloat) -> MyFloat { sigma * PI.sqrt() / TWO * erfc((t - mu) / sigma) } fn moment1(mu: MyFloat, sigma: MyFloat, t: MyFloat) -> MyFloat { mu * moment0(ZERO, sigma, t - mu) + sigma.powi(2) / TWO * gauss_exponent(mu, sigma, t) } fn moment2(mu: MyFloat, sigma: MyFloat, t: MyFloat) -> MyFloat { mu.powi(2) * moment0(ZERO, sigma, t - mu) + TWO * mu * moment1(ZERO, sigma, t - mu) + (sigma / TWO).powi(2) * (TWO * gauss_exponent(mu, sigma, t) * (t - mu) + sigma * PI.sqrt() * erfc((t - mu) / sigma)) } impl Gaussian { pub fn leq_eps(&self, eps: MyFloat) -> Gaussian { assert!(eps >= ZERO); assert!(!self.sigma.is_infinite()); let alpha = moment0(self.mu, self.sigma, -eps) - moment0(self.mu, self.sigma, eps); const FLOAT_CMP_EPS: f64 = 1e-8; let (mu, sigma) = if alpha < FLOAT_CMP_EPS.into() { (eps, eps) } else { let mu = (moment1(self.mu, self.sigma, -eps) - moment1(self.mu, self.sigma, eps)) / alpha; let sigma2 = (moment2(self.mu, self.sigma, -eps) - moment2(self.mu, self.sigma, eps)) / alpha - mu.powi(2); (mu, sigma2.max(ZERO).sqrt()) }; assert!( !mu.is_nan() && !sigma.is_nan(), "{:?}\teps {} {} {}", self, eps, mu, sigma ); Gaussian { mu, sigma } / self } pub fn greater_eps(&self, eps: MyFloat) -> Gaussian { assert!(eps >= ZERO); assert!(!self.sigma.is_infinite()); let alpha = moment0(self.mu, self.sigma, eps); const FLOAT_CMP_EPS: f64 = 1e-8; let (mu, sigma) = if alpha < FLOAT_CMP_EPS.into() { (eps, eps) } else { let mu = moment1(self.mu, self.sigma, eps) / alpha; let sigma2 = moment2(self.mu, self.sigma, eps) / alpha - mu.powi(2); (mu, sigma2.max(ZERO).sqrt()) }; assert!(!mu.is_nan() && !sigma.is_nan(), "{:?}\teps {}", self, eps); Gaussian { mu, sigma } / self } }
use super::float::{erfc, Float, MyFloat, PI, TWO, ZERO}; use overload::overload; use std::ops; #[derive(Clone, Debug)] pub struct Gaussian { pub mu: MyFloat, pub sigma: MyFloat, } pub const G_ZERO: Gaussian = Gaussian { mu: ZERO, sigma: ZERO, }; pub const G_ONE: Gaussian = Gaussian { mu: ZERO, sigma: MyFloat::INFINITY, }; overload!((a: ?Gaussian) + (b: ?Gaussian) -> Gaussian { Gaussian { mu: a.mu + b.mu, sigma: a.sigma.hypot(b.sigma), } }); overload!((a: &mut Gaussian) += (b: ?Gaussian) { a.mu += b.mu; a.sigma = a.sigma.hypot(b.sigma); }); overload!((a: ?Gaussian) - (b: ?Gaussian) -> Gaussian { Gaussian { mu: a.mu - b.mu, sigma: a.sigma.hypot(b.sigma), } }); overload!((a: &mut Gaussian) -= (b: ?Gaussian) { a.mu -= b.mu; a.sigma = a.sigma.hypot(b.sigma); }); overload!(-(a: &mut Gaussian) -> Gaussian { Gaussian { mu: -a.mu, sigma: a.sigma, } }); overload!((a: ?Gaussian) * (b: ?MyFloat) -> Gaussian { Gaussian { mu: a.mu * b, sigma: a.sigma * b.abs(), } }); overload!((a: &mut Gaussian) *= (b: ?MyFloat) { a.mu *= b; a.sigma *= b.abs(); }); overload!((a: ?Gaussian) / (b: ?MyFloat) -> Gaussian { Gaussian { mu: a.mu / b, sigma: a.sigma / b.abs(), } }); overload!((a: &mut Gaussian) /= (b: ?MyFloat) { a.mu /= b; a.sigma /= b.abs(); }); overload!((a: ?Gaussian) * (b: ?Gaussian) -> Gaussian { if a.sigma.is_infinite() { return b.clone(); } if b.sigma.is_infinite() { return a.clone(); } let ssigma1 = a.sigma.powi(2); let ssigma2 = b.sigma.powi(2); Gaussian { mu: (a.mu * ssigma2 + b.mu * ssigma1) / (ssigma1 + ssigma2), sigma: a.sigma * b.sigma / (ssigma1 + ssigma2).sqrt(), } }); overload!((a: &mut Gaussian) *= (b: ?Gaussian) { *a = a.clone() * b; }); overload!((a: ?Gaussian) / (b: ?Gaussian) -> Gaussian { if b.sigma.is_infinite() { return a.clone(); } if a.sigma.is_infinite() { return Gaussian { mu: -b.mu, sigma: b.sigma, } } let ssigma1 = a.sigma.powi(2); let ssigma2 = b.sigma.powi(2); Gaussian { mu: (a.mu * ssigma2 - b.mu * ssigma1) / (ssigma2 - ssigma1), sigma: a.sigma * b.sigma / (ssigma2 - ssigma1).abs().sqrt(), } }); overload!((a: &mut Gaussian) /= (b: ?Gaussian) { *a = a.clone() / b; }); fn gauss_exponent(mu: MyFloat, sigma: MyFloat, t: MyFloat) -> MyFloat { (-((t - mu) / sigma).powi(2)).exp() } fn moment0(mu: MyFloat, sigma: MyFloat, t: MyFloat) -> MyFloat { sigma * PI.sqrt() / TWO * erfc((t - mu) / sigma) } fn moment1(mu: MyFloat, sigma: MyFloat, t: MyFloat) -> MyFloat { mu * moment0(ZERO, sigma, t - mu) + sigma.powi(2) / TWO * gauss_exponent(mu, sigma, t) } fn moment2(mu: MyFloat, sigma: MyFloat, t: MyFloat) -> MyFloat {
impl Gaussian { pub fn leq_eps(&self, eps: MyFloat) -> Gaussian { assert!(eps >= ZERO); assert!(!self.sigma.is_infinite()); let alpha = moment0(self.mu, self.sigma, -eps) - moment0(self.mu, self.sigma, eps); const FLOAT_CMP_EPS: f64 = 1e-8; let (mu, sigma) = if alpha < FLOAT_CMP_EPS.into() { (eps, eps) } else { let mu = (moment1(self.mu, self.sigma, -eps) - moment1(self.mu, self.sigma, eps)) / alpha; let sigma2 = (moment2(self.mu, self.sigma, -eps) - moment2(self.mu, self.sigma, eps)) / alpha - mu.powi(2); (mu, sigma2.max(ZERO).sqrt()) }; assert!( !mu.is_nan() && !sigma.is_nan(), "{:?}\teps {} {} {}", self, eps, mu, sigma ); Gaussian { mu, sigma } / self } pub fn greater_eps(&self, eps: MyFloat) -> Gaussian { assert!(eps >= ZERO); assert!(!self.sigma.is_infinite()); let alpha = moment0(self.mu, self.sigma, eps); const FLOAT_CMP_EPS: f64 = 1e-8; let (mu, sigma) = if alpha < FLOAT_CMP_EPS.into() { (eps, eps) } else { let mu = moment1(self.mu, self.sigma, eps) / alpha; let sigma2 = moment2(self.mu, self.sigma, eps) / alpha - mu.powi(2); (mu, sigma2.max(ZERO).sqrt()) }; assert!(!mu.is_nan() && !sigma.is_nan(), "{:?}\teps {}", self, eps); Gaussian { mu, sigma } / self } }
mu.powi(2) * moment0(ZERO, sigma, t - mu) + TWO * mu * moment1(ZERO, sigma, t - mu) + (sigma / TWO).powi(2) * (TWO * gauss_exponent(mu, sigma, t) * (t - mu) + sigma * PI.sqrt() * erfc((t - mu) / sigma)) }
function_block-function_prefix_line
[]
Rust
runtime/src/account_info.rs
luma-team/solana
b02c412d5b5c1902bd5b3616f427ffc0c9925cef
use crate::{ accounts_db::{AppendVecId, CACHE_VIRTUAL_OFFSET}, accounts_index::{IsCached, ZeroLamport}, append_vec::ALIGN_BOUNDARY_OFFSET, }; pub type Offset = usize; pub type StoredSize = u32; #[derive(Debug)] pub enum StorageLocation { AppendVec(AppendVecId, Offset), Cached, } impl StorageLocation { pub fn is_offset_equal(&self, other: &StorageLocation) -> bool { match self { StorageLocation::Cached => { matches!(other, StorageLocation::Cached) } StorageLocation::AppendVec(_, offset) => { match other { StorageLocation::Cached => { false } StorageLocation::AppendVec(_, other_offset) => other_offset == offset, } } } } pub fn is_store_id_equal(&self, other: &StorageLocation) -> bool { match self { StorageLocation::Cached => { matches!(other, StorageLocation::Cached) } StorageLocation::AppendVec(store_id, _) => { match other { StorageLocation::Cached => { false } StorageLocation::AppendVec(other_store_id, _) => other_store_id == store_id, } } } } } pub type OffsetReduced = u32; #[derive(Default, Debug, PartialEq, Eq, Clone, Copy)] pub struct AccountInfo { store_id: AppendVecId, reduced_offset: OffsetReduced, stored_size_mask: StoredSize, } const IS_ZERO_LAMPORT_FLAG: StoredSize = 1 << (StoredSize::BITS - 1); const IS_CACHED_STORE_ID_FLAG: StoredSize = 1 << (StoredSize::BITS - 2); const ALL_FLAGS: StoredSize = IS_ZERO_LAMPORT_FLAG | IS_CACHED_STORE_ID_FLAG; impl ZeroLamport for AccountInfo { fn is_zero_lamport(&self) -> bool { self.stored_size_mask & IS_ZERO_LAMPORT_FLAG == IS_ZERO_LAMPORT_FLAG } } impl IsCached for AccountInfo { fn is_cached(&self) -> bool { self.stored_size_mask & IS_CACHED_STORE_ID_FLAG == IS_CACHED_STORE_ID_FLAG } } impl IsCached for StorageLocation { fn is_cached(&self) -> bool { matches!(self, StorageLocation::Cached) } } const CACHE_VIRTUAL_STORAGE_ID: AppendVecId = AppendVecId::MAX; impl AccountInfo { pub fn new(storage_location: StorageLocation, stored_size: StoredSize, lamports: u64) -> Self { assert_eq!(stored_size & ALL_FLAGS, 0); let mut stored_size_mask = stored_size; let (store_id, raw_offset) = match storage_location { StorageLocation::AppendVec(store_id, offset) => (store_id, offset), StorageLocation::Cached => { stored_size_mask |= IS_CACHED_STORE_ID_FLAG; (CACHE_VIRTUAL_STORAGE_ID, CACHE_VIRTUAL_OFFSET) } }; if lamports == 0 { stored_size_mask |= IS_ZERO_LAMPORT_FLAG; } let reduced_offset: OffsetReduced = (raw_offset / ALIGN_BOUNDARY_OFFSET) as OffsetReduced; let result = Self { store_id, reduced_offset, stored_size_mask, }; assert_eq!(result.offset(), raw_offset, "illegal offset"); result } pub fn store_id(&self) -> AppendVecId { assert!(!self.is_cached()); self.store_id } pub fn offset(&self) -> Offset { (self.reduced_offset as Offset) * ALIGN_BOUNDARY_OFFSET } pub fn stored_size(&self) -> StoredSize { self.stored_size_mask & !ALL_FLAGS } pub fn matches_storage_location(&self, store_id: AppendVecId, offset: Offset) -> bool { self.store_id == store_id && self.offset() == offset && !self.is_cached() } pub fn storage_location(&self) -> StorageLocation { if self.is_cached() { StorageLocation::Cached } else { StorageLocation::AppendVec(self.store_id, self.offset()) } } } #[cfg(test)] mod test { use {super::*, crate::append_vec::MAXIMUM_APPEND_VEC_FILE_SIZE}; #[test] fn test_limits() { for offset in [ MAXIMUM_APPEND_VEC_FILE_SIZE as Offset, 0, ALIGN_BOUNDARY_OFFSET, 4 * ALIGN_BOUNDARY_OFFSET, ] { let info = AccountInfo::new(StorageLocation::AppendVec(0, offset), 0, 0); assert!(info.offset() == offset); } } #[test] #[should_panic(expected = "illegal offset")] fn test_alignment() { let offset = 1; AccountInfo::new(StorageLocation::AppendVec(0, offset), 0, 0); } #[test] fn test_matches_storage_location() { let offset = 0; let id = 0; let info = AccountInfo::new(StorageLocation::AppendVec(id, offset), 0, 0); assert!(info.matches_storage_location(id, offset)); let offset = ALIGN_BOUNDARY_OFFSET; assert!(!info.matches_storage_location(id, offset)); let offset = 0; let id = 1; assert!(!info.matches_storage_location(id, offset)); let id = CACHE_VIRTUAL_STORAGE_ID; let info = AccountInfo::new(StorageLocation::Cached, 0, 0); assert!(!info.matches_storage_location(id, offset)); } }
use crate::{ accounts_db::{AppendVecId, CACHE_VIRTUAL_OFFSET}, accounts_index::{IsCached, ZeroLamport}, append_vec::ALIGN_BOUNDARY_OFFSET, }; pub type Offset = usize; pub type StoredSize = u32; #[derive(Debug)] pub enum StorageLocation { AppendVec(AppendVecId, Offset), Cached, } impl StorageLocation { pub fn is_offset_equal(&self, other: &StorageLocation) -> bool { match self { StorageLocation::Cached => { matches!(other, StorageLocation::Cached) } StorageLocation::AppendVec(_, offset) => { match other { StorageLocation::Cached => { false } StorageLocation::AppendVec(_, other_offset) => other_offset == offset, } } } } pub fn is_store_id_equal(&self, other: &StorageLocation) -> bool { match self { StorageLocation::Cached => { matches!(other, StorageLocation::Cached) } StorageLocation::AppendVec(store_id, _) => { match other { StorageLocation::Cached => { false } StorageLocation::AppendVec(other_store_id, _) => other_store_id == store_id, } } } } } pub type OffsetReduced = u32; #[derive(Default, Debug, PartialEq, Eq, Clone, Copy)] pub struct AccountInfo { store_id: AppendVecId, reduced_offset: OffsetReduced, stored_size_mask: StoredSize, } const IS_ZERO_LAMPORT_FLAG: StoredSize = 1 << (StoredSize::BITS - 1); const IS_CACHED_STORE_ID_FLAG: StoredSize = 1 << (StoredSize::BITS - 2); const ALL_FLAGS: StoredSize = IS_ZERO_LAMPORT_FLAG | IS_CACHED_STORE_ID_FLAG; impl ZeroLamport for AccountInfo { fn is_zero_lamport(&self) -> bool { self.stored_size_mask & IS_ZERO_LAMPORT_FLAG == IS_ZERO_LAMPORT_FLAG } } impl IsCached for AccountInfo { fn is_cached(&self) -> bool { self.stored_size_mask & IS_CACHED_STORE_ID_FLAG == IS_CACHED_STORE_ID_FLAG } } impl IsCached for StorageLocation { fn is_cached(&self) -> bool { matches!(self, StorageLocation::Cached) } } const CACHE_VIRTUAL_STORAGE_ID: AppendVecId = AppendVecId::MAX; impl AccountInfo { pub fn new(storage_location: StorageLocation, stored_size: StoredSize, lamports: u64) -> Self { assert_eq!(stored_size & ALL_FLAGS, 0); let mut stored_size_mask = stored_size; let (store_id, raw_offset) = match storage_location { StorageLocation::AppendVec(store_id, offset) => (store_id, offset), StorageLocation::Cached => { stored_size_mask |= IS_CACHED_STORE_ID_FLAG; (CACHE_VIRTUAL_STORAGE_ID, CACHE_VIRTUAL_OFFSET) } }; if lamports == 0 { stored_size_mask |= IS_ZERO_LAMPORT_FLAG; } let reduced_offset: OffsetReduced = (raw_offset / ALIGN_BOUNDARY_OFFSET) as OffsetReduced; let result = Self { store_id, reduced_offset, stored_size_mask, }; assert_eq!(result.offset(), raw_offset, "illegal offset"); result } pub fn store_id(&self) -> AppendVecId { assert!(!self.is_cached()); self.store_id } pub fn offset(&self) -> Offset { (self.reduced_offset as Offset) * ALIGN_BOUNDARY_OFFSET } pub fn stored_size(&self) -> StoredSize { self.stored_size_mask & !ALL_FLAGS } pub fn matches_storage_location(&self, store_id: AppendVecId, offset: Offset) -> bool { self.store_id == store_id && self.offset() == offset && !self.is_cached() } pub fn storage_location(&self) -> StorageLocation { if self.is_cached() { StorageLocation::Cached } else { StorageLocation::AppendVec(self.store_id, self.offset()) } } } #[cfg(test)] mod test { use {super::*, crate::append_vec::MAXIMUM_APPEND_VEC_FILE_SIZE}; #[test] fn test_limits() { for offset in [ MAXIMUM_APPEND_VEC_FILE_SIZE as Offset, 0, ALIGN_BOUNDARY_OFFSET, 4 * ALIGN_BOUNDARY_OFFSET, ] { let info = AccountInfo::new(StorageLocation::AppendVec(0, offset), 0, 0); assert!(info.offset() == offset); } } #[test] #[should_panic(expected = "illegal offset")] fn test_alignment() { let offset = 1; AccountInfo::new(StorageLocation::AppendVec(0, offset), 0, 0); } #[test] fn test_matches_storage_location() { let offset = 0; let id = 0; let info = AccountInfo::new(StorageLocation::AppendVec(id, offset), 0, 0); assert!(info.matches_storage_location(id, offset)); let offset = ALIGN_BOUNDARY_OFFSET; assert!(!info.matches_storage_location(id, offset)); let offset = 0; let id = 1; assert!(!info.matches_storage_location(id, offset)); let id = CACHE_VI
}
RTUAL_STORAGE_ID; let info = AccountInfo::new(StorageLocation::Cached, 0, 0); assert!(!info.matches_storage_location(id, offset)); }
function_block-function_prefixed
[ { "content": "pub fn is_sysvar_id(id: &Pubkey) -> bool {\n\n ALL_IDS.iter().any(|key| key == id)\n\n}\n\n\n\n/// Declares an ID that implements [`SysvarId`].\n\n#[macro_export]\n\nmacro_rules! declare_sysvar_id(\n\n ($name:expr, $type:ty) => (\n\n $crate::declare_id!($name);\n\n\n\n impl $cr...
Rust
egui/src/grid.rs
katyo/egui
02db9ee5835a522ddf04308f259025388abf0185
use crate::*; #[derive(Clone, Debug, Default, PartialEq)] #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] pub(crate) struct State { col_widths: Vec<f32>, row_heights: Vec<f32>, } impl State { fn set_min_col_width(&mut self, col: usize, width: f32) { self.col_widths .resize(self.col_widths.len().max(col + 1), 0.0); self.col_widths[col] = self.col_widths[col].max(width); } fn set_min_row_height(&mut self, row: usize, height: f32) { self.row_heights .resize(self.row_heights.len().max(row + 1), 0.0); self.row_heights[row] = self.row_heights[row].max(height); } fn col_width(&self, col: usize) -> Option<f32> { self.col_widths.get(col).copied() } fn row_height(&self, row: usize) -> Option<f32> { self.row_heights.get(row).copied() } fn full_width(&self, x_spacing: f32) -> f32 { self.col_widths.iter().sum::<f32>() + (self.col_widths.len().at_least(1) - 1) as f32 * x_spacing } } pub(crate) struct GridLayout { ctx: CtxRef, style: std::sync::Arc<Style>, id: Id, prev_state: State, curr_state: State, spacing: Vec2, striped: bool, initial_x: f32, min_cell_size: Vec2, max_cell_size: Vec2, col: usize, row: usize, } impl GridLayout { pub(crate) fn new(ui: &Ui, id: Id) -> Self { let prev_state = ui.memory().id_data.get_or_default::<State>(id).clone(); let available = ui.placer().max_rect().intersect(ui.cursor()); let initial_x = available.min.x; assert!( initial_x.is_finite(), "Grid not yet available for right-to-left layouts" ); Self { ctx: ui.ctx().clone(), style: ui.style().clone(), id, prev_state, curr_state: State::default(), spacing: ui.spacing().item_spacing, striped: false, initial_x, min_cell_size: ui.spacing().interact_size, max_cell_size: Vec2::INFINITY, col: 0, row: 0, } } } impl GridLayout { fn prev_col_width(&self, col: usize) -> f32 { self.prev_state .col_width(col) .unwrap_or(self.min_cell_size.x) } fn prev_row_height(&self, row: usize) -> f32 { self.prev_state .row_height(row) .unwrap_or(self.min_cell_size.y) } pub(crate) fn wrap_text(&self) -> bool { self.max_cell_size.x.is_finite() } pub(crate) fn available_rect(&self, region: &Region) -> Rect { self.available_rect_finite(region) } pub(crate) fn available_rect_finite(&self, region: &Region) -> Rect { let width = if self.max_cell_size.x.is_finite() { self.max_cell_size.x } else { self.prev_state .col_width(self.col) .or_else(|| self.curr_state.col_width(self.col)) .unwrap_or(self.min_cell_size.x) }; let available = region.max_rect.intersect(region.cursor); let height = region.max_rect_finite().max.y - available.top(); let height = height .at_least(self.min_cell_size.y) .at_most(self.max_cell_size.y); Rect::from_min_size(available.min, vec2(width, height)) } pub(crate) fn next_cell(&self, cursor: Rect, child_size: Vec2) -> Rect { let width = self.prev_state.col_width(self.col).unwrap_or(0.0); let height = self.prev_row_height(self.row); let size = child_size.max(vec2(width, height)); Rect::from_min_size(cursor.min, size) } #[allow(clippy::unused_self)] pub(crate) fn align_size_within_rect(&self, size: Vec2, frame: Rect) -> Rect { Align2::LEFT_CENTER.align_size_within_rect(size, frame) } pub(crate) fn justify_and_align(&self, frame: Rect, size: Vec2) -> Rect { self.align_size_within_rect(size, frame) } pub(crate) fn advance(&mut self, cursor: &mut Rect, frame_rect: Rect, widget_rect: Rect) { let debug_expand_width = self.style.debug.show_expand_width; let debug_expand_height = self.style.debug.show_expand_height; if debug_expand_width || debug_expand_height { let rect = widget_rect; let too_wide = rect.width() > self.prev_col_width(self.col); let too_high = rect.height() > self.prev_row_height(self.row); if (debug_expand_width && too_wide) || (debug_expand_height && too_high) { let painter = self.ctx.debug_painter(); painter.rect_stroke(rect, 0.0, (1.0, Color32::LIGHT_BLUE)); let stroke = Stroke::new(2.5, Color32::from_rgb(200, 0, 0)); let paint_line_seg = |a, b| painter.line_segment([a, b], stroke); if debug_expand_width && too_wide { paint_line_seg(rect.left_top(), rect.left_bottom()); paint_line_seg(rect.left_center(), rect.right_center()); paint_line_seg(rect.right_top(), rect.right_bottom()); } } } self.curr_state .set_min_col_width(self.col, widget_rect.width().at_least(self.min_cell_size.x)); self.curr_state.set_min_row_height( self.row, widget_rect.height().at_least(self.min_cell_size.y), ); self.col += 1; cursor.min.x += frame_rect.width() + self.spacing.x; } pub(crate) fn end_row(&mut self, cursor: &mut Rect, painter: &Painter) { let row_height = self.prev_row_height(self.row); cursor.min.x = self.initial_x; cursor.min.y += row_height + self.spacing.y; self.col = 0; self.row += 1; if self.striped && self.row % 2 == 1 { if let Some(height) = self.prev_state.row_height(self.row) { let size = Vec2::new(self.prev_state.full_width(self.spacing.x), height); let rect = Rect::from_min_size(cursor.min, size); let rect = rect.expand2(0.5 * self.spacing.y * Vec2::Y); let rect = rect.expand2(2.0 * Vec2::X); let color = if self.style.visuals.dark_mode { Rgba::from_white_alpha(0.0075) } else { Rgba::from_black_alpha(0.075) }; painter.rect_filled(rect, 2.0, color); } } } pub(crate) fn save(&self) { if self.curr_state != self.prev_state { self.ctx .memory() .id_data .insert(self.id, self.curr_state.clone()); self.ctx.request_repaint(); } } } #[must_use = "You should call .show()"] pub struct Grid { id_source: Id, striped: bool, min_col_width: Option<f32>, min_row_height: Option<f32>, max_cell_size: Vec2, spacing: Option<Vec2>, start_row: usize, } impl Grid { pub fn new(id_source: impl std::hash::Hash) -> Self { Self { id_source: Id::new(id_source), striped: false, min_col_width: None, min_row_height: None, max_cell_size: Vec2::INFINITY, spacing: None, start_row: 0, } } pub fn striped(mut self, striped: bool) -> Self { self.striped = striped; self } pub fn min_col_width(mut self, min_col_width: f32) -> Self { self.min_col_width = Some(min_col_width); self } pub fn min_row_height(mut self, min_row_height: f32) -> Self { self.min_row_height = Some(min_row_height); self } pub fn max_col_width(mut self, max_col_width: f32) -> Self { self.max_cell_size.x = max_col_width; self } pub fn spacing(mut self, spacing: impl Into<Vec2>) -> Self { self.spacing = Some(spacing.into()); self } pub fn start_row(mut self, start_row: usize) -> Self { self.start_row = start_row; self } } impl Grid { pub fn show<R>(self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> { let Self { id_source, striped, min_col_width, min_row_height, max_cell_size, spacing, start_row, } = self; let min_col_width = min_col_width.unwrap_or_else(|| ui.spacing().interact_size.x); let min_row_height = min_row_height.unwrap_or_else(|| ui.spacing().interact_size.y); let spacing = spacing.unwrap_or_else(|| ui.spacing().item_spacing); ui.horizontal(|ui| { let id = ui.make_persistent_id(id_source); let grid = GridLayout { striped, spacing, min_cell_size: vec2(min_col_width, min_row_height), max_cell_size, row: start_row, ..GridLayout::new(ui, id) }; ui.set_grid(grid); let r = add_contents(ui); ui.save_grid(); r }) } }
use crate::*; #[derive(Clone, Debug, Default, PartialEq)] #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] pub(crate) struct State { col_widths: Vec<f32>, row_heights: Vec<f32>, } impl State { fn set_min_col_width(&mut self, col: usize, width: f32) { self.col_widths .resize(self.col_widths.len().max(col + 1), 0.0); self.col_widths[col] = self.col_widths[col].max(width); } fn set_min_row_height(&mut self, row: usize, height: f32) { self.row_heights .resize(self.row_heights.len().max(row + 1), 0.0); self.row_heights[row] = self.row_heights[row].max(height); } fn col_width(&self, col: usize) -> Option<f32> { self.col_widths.get(col).copied() } fn row_height(&self, row: usize) -> Option<f32> { self.row_heights.get(row).copied() } fn full_width(&self, x_spacing: f32) -> f32 { self.col_widths.iter().sum::<f32>() + (self.col_widths.len().at_least(1) - 1) as f32 * x_spacing } } pub(crate) struct GridLayout { ctx: CtxRef, style: std::sync::Arc<Style>, id: Id, prev_state: State, curr_state: State, spacing: Vec2, striped: bool, initial_x: f32, min_cell_size: Vec2, max_cell_size: Vec2, col: usize, row: usize, } impl GridLayout { pub(crate) fn new(ui: &Ui, id: Id) -> Self { let prev_state = ui.memory().id_data.get_or_default::<State>(id).clone(); let available = ui.placer().max_rect().intersect(ui.cursor()); let initial_x = available.min.x; assert!( initial_x.is_finite(), "Grid not yet available for right-to-left layouts" ); Self { ctx: ui.ctx().clone(), style: ui.style().clone(), id, prev_state, curr_state: State::default(), spacing: ui.spacing().item_spacing, striped: false, initial_x, min_cell_size: ui.spacing().interact_size, max_cell_size: Vec2::INFINITY, col: 0, row: 0, } } } impl GridLayout { fn prev_col_width(&self, col: usize) -> f32 { self.prev_state .col_width(col) .unwrap_or(self.min_cell_size.x) } fn prev_row_height(&self, row: usize) -> f32 { self.prev_state .row_height(row) .unwrap_or(self.min_cell_size.y) } pub(crate) fn wrap_text(&self) -> bool { self.max_cell_size.x.is_finite() } pub(crate) fn available_rect(&self, region: &Region) -> Rect { self.available_rect_finite(region) } pub(crate) fn available_rect_finite(&self, region: &Region) -> Rect { let width = if self.max_cell_size.x.is_finite() { self.max_cell_size.x } else { self.prev_state .col_width(self.col) .or_else(|| self.curr_state.col_width(self.col)) .unwrap_or(self.min_cell_size.x) }; let available = region.max_rect.intersect(region.cursor); let height = region.max_rect_finite().max.y - available.top(); let height = height .at_least(self.min_cell_size.y) .at_most(self.max_cell_size.y); Rect::from_min_size(available.min, vec2(width, height)) } pub(crate) fn next_cell(&self, cursor: Rect, child_size: Vec2) -> Rect { let width = self.prev_state.col_width(self.col).unwrap_or(0.0); let height = self.prev_row_height(self.row); let size = child_size.max(vec2(width, height)); Rect::from_min_size(cursor.min, size) } #[allow(clippy::unused_self)] pub(crate) fn align_size_within_rect(&self, size: Vec2, frame: Rect) -> Rect { Align2::LEFT_CENTER.align_size_within_rect(size, frame) } pub(crate) fn justify_and_align(&self, frame: Rect, size: Vec2) -> Rect { self.align_size_within_rect(size, frame) } pub(crate) fn advance(&mut self, cursor: &mut Rect, frame_rect: Rect, widget_rect: Rect) { let debug_expand_width = self.style.debug.show_expand_width; let debug_expand_height = self.style.debug.show_expand_height; if debug_expand_width || debug_expand_height { let rect = widget_rect; let too_wide = rect.width() > self.prev_col_width(self.col); let too_high = rect.height() > self.prev_row_height(self.row); if (debug_expand_width && too_wide) || (debug_expand_height && too_high) { let painter = self.ctx.debug_painter(); painter.rect_stroke(rect, 0.0, (1.0, Color32::LIGHT_BLUE)); let stroke = Stroke::new(2.5, Color32::from_rgb(200, 0, 0)); let paint_line_seg = |a, b| painter.line_segment([a, b], stroke); if debug_expand_width && too_wide { paint_line_seg(rect.left_top(), rect.left_bottom()); paint_line_seg(rect.left_center(), rect.right_center()); paint_line_seg(rect.right_top(), rect.right_bottom()); } } } self.curr_state .set_min_col_width(self.col, widget_rect.width().at_least(self.min_cell_size.x)); self.curr_state.set_min_row_height( self.row, widget_rect.height().at_least(self.min_cell_size.y), ); self.col += 1; cursor.min.x += frame_rect.width() + self.spacing.x; } pub(crate) fn end_row(&mut self, cursor: &mut Rect, painter: &Painter) { let row_height = self.prev_row_height(self.row); cursor.min.x = self.initial_x; cursor.min.y += row_height + self.spacing.y; self.col = 0; self.row += 1; if self.striped && self.row % 2 == 1 { if let Some(height) = self.prev_state.row_height(self.row) { let size = Vec2::new(self.prev_state.full_width(self.spacing.x), height); let rect = Rect::from_min_size(cursor.min, size); let rect = rect.expand2(0.5 * self.spacing.y * Vec2::Y); let rect = rect.expand2(2.0 * Vec2::X); let color = if self.style.visuals.dark_mode {
pub(crate) fn save(&self) { if self.curr_state != self.prev_state { self.ctx .memory() .id_data .insert(self.id, self.curr_state.clone()); self.ctx.request_repaint(); } } } #[must_use = "You should call .show()"] pub struct Grid { id_source: Id, striped: bool, min_col_width: Option<f32>, min_row_height: Option<f32>, max_cell_size: Vec2, spacing: Option<Vec2>, start_row: usize, } impl Grid { pub fn new(id_source: impl std::hash::Hash) -> Self { Self { id_source: Id::new(id_source), striped: false, min_col_width: None, min_row_height: None, max_cell_size: Vec2::INFINITY, spacing: None, start_row: 0, } } pub fn striped(mut self, striped: bool) -> Self { self.striped = striped; self } pub fn min_col_width(mut self, min_col_width: f32) -> Self { self.min_col_width = Some(min_col_width); self } pub fn min_row_height(mut self, min_row_height: f32) -> Self { self.min_row_height = Some(min_row_height); self } pub fn max_col_width(mut self, max_col_width: f32) -> Self { self.max_cell_size.x = max_col_width; self } pub fn spacing(mut self, spacing: impl Into<Vec2>) -> Self { self.spacing = Some(spacing.into()); self } pub fn start_row(mut self, start_row: usize) -> Self { self.start_row = start_row; self } } impl Grid { pub fn show<R>(self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> { let Self { id_source, striped, min_col_width, min_row_height, max_cell_size, spacing, start_row, } = self; let min_col_width = min_col_width.unwrap_or_else(|| ui.spacing().interact_size.x); let min_row_height = min_row_height.unwrap_or_else(|| ui.spacing().interact_size.y); let spacing = spacing.unwrap_or_else(|| ui.spacing().item_spacing); ui.horizontal(|ui| { let id = ui.make_persistent_id(id_source); let grid = GridLayout { striped, spacing, min_cell_size: vec2(min_col_width, min_row_height), max_cell_size, row: start_row, ..GridLayout::new(ui, id) }; ui.set_grid(grid); let r = add_contents(ui); ui.save_grid(); r }) } }
Rgba::from_white_alpha(0.0075) } else { Rgba::from_black_alpha(0.075) }; painter.rect_filled(rect, 2.0, color); } } }
function_block-function_prefix_line
[ { "content": "pub fn show_tooltip_under(ctx: &CtxRef, id: Id, rect: &Rect, add_contents: impl FnOnce(&mut Ui)) {\n\n show_tooltip_at(\n\n ctx,\n\n id,\n\n Some(rect.left_bottom() + vec2(-2.0, 4.0)),\n\n add_contents,\n\n )\n\n}\n\n\n", "file_path": "egui/src/containers/popu...
Rust
crates/regex/src/re_set.rs
CryZe/libtww
0b8de9f451e7d8afda7a14d618bd3a7784b1d679
macro_rules! define_set { ($name:ident, $exec_build:expr, $text_ty:ty, $as_bytes:expr) => { pub mod $name { use libtww::std::fmt; use libtww::std::iter; use libtww::std::slice; use libtww::std::vec; use error::Error; use exec::{Exec, ExecBuilder}; use re_trait::RegularExpression; #[derive(Clone)] pub struct RegexSet(Exec); impl RegexSet { pub fn new<I, S>(exprs: I) -> Result<RegexSet, Error> where S: AsRef<str>, I: IntoIterator<Item=S> { let exec = try!($exec_build(exprs)); Ok(RegexSet(exec)) } pub fn is_match(&self, text: $text_ty) -> bool { self.0.searcher().is_match_at($as_bytes(text), 0) } pub fn matches(&self, text: $text_ty) -> SetMatches { let mut matches = vec![false; self.0.regex_strings().len()]; let any = self.0.searcher().many_matches_at( &mut matches, $as_bytes(text), 0); SetMatches { matched_any: any, matches: matches, } } pub fn len(&self) -> usize { self.0.regex_strings().len() } } #[derive(Clone, Debug)] pub struct SetMatches { matched_any: bool, matches: Vec<bool>, } impl SetMatches { pub fn matched_any(&self) -> bool { self.matched_any } pub fn matched(&self, regex_index: usize) -> bool { self.matches[regex_index] } pub fn len(&self) -> usize { self.matches.len() } pub fn iter(&self) -> SetMatchesIter { SetMatchesIter((&*self.matches).into_iter().enumerate()) } } impl IntoIterator for SetMatches { type IntoIter = SetMatchesIntoIter; type Item = usize; fn into_iter(self) -> Self::IntoIter { SetMatchesIntoIter(self.matches.into_iter().enumerate()) } } impl<'a> IntoIterator for &'a SetMatches { type IntoIter = SetMatchesIter<'a>; type Item = usize; fn into_iter(self) -> Self::IntoIter { self.iter() } } pub struct SetMatchesIntoIter(iter::Enumerate<vec::IntoIter<bool>>); impl Iterator for SetMatchesIntoIter { type Item = usize; fn next(&mut self) -> Option<usize> { loop { match self.0.next() { None => return None, Some((_, false)) => {} Some((i, true)) => return Some(i), } } } } impl DoubleEndedIterator for SetMatchesIntoIter { fn next_back(&mut self) -> Option<usize> { loop { match self.0.next_back() { None => return None, Some((_, false)) => {} Some((i, true)) => return Some(i), } } } } #[derive(Clone)] pub struct SetMatchesIter<'a>(iter::Enumerate<slice::Iter<'a, bool>>); impl<'a> Iterator for SetMatchesIter<'a> { type Item = usize; fn next(&mut self) -> Option<usize> { loop { match self.0.next() { None => return None, Some((_, &false)) => {} Some((i, &true)) => return Some(i), } } } } impl<'a> DoubleEndedIterator for SetMatchesIter<'a> { fn next_back(&mut self) -> Option<usize> { loop { match self.0.next_back() { None => return None, Some((_, &false)) => {} Some((i, &true)) => return Some(i), } } } } #[doc(hidden)] impl From<Exec> for RegexSet { fn from(exec: Exec) -> Self { RegexSet(exec) } } impl fmt::Debug for RegexSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "RegexSet({:?})", self.0.regex_strings()) } } #[allow(dead_code)] fn as_bytes_str(text: &str) -> &[u8] { text.as_bytes() } #[allow(dead_code)] fn as_bytes_bytes(text: &[u8]) -> &[u8] { text } } } } define_set! { unicode, |exprs| ExecBuilder::new_many(exprs).build(), &str, as_bytes_str } define_set! { bytes, |exprs| ExecBuilder::new_many(exprs).only_utf8(false).build(), &[u8], as_bytes_bytes }
macro_rules! define_set { ($name:ident, $exec_build:expr, $text_ty:ty, $as_bytes:expr) => { pub mod $name { use libtww::std::fmt; use libtww::std::iter; use libtww::std::slice; use libtww::std::vec; use error::Error; use exec::{Exec, ExecBuilder}; use re_trait::RegularExpression; #[derive(Clone)] pub struct RegexSet(Exec); impl RegexSet { pub fn new<I, S>(exprs: I) -> Result<RegexSet, Error> where S: AsRef<str>, I: IntoIterator<Item=S> { let exec = try!($exec_build(exprs)); Ok(RegexSet(exec)) } pub fn is_match(&self, text: $text_ty) -> bool { self.0.searcher().is_match_at($as_bytes(text), 0) } pub fn matches(&self, text: $text_ty) -> SetMatches { let mut matches = vec![false; self.0.regex_strings().len()]; let any = self.0.searcher().many_matches_at( &mut matches, $as_bytes(text), 0); SetMatches { matched_any: any, matches: matches, } } pub fn len(&self) -> usize { self.0.regex_strings().len() } } #[derive(Clone, Debug)] pub struct SetMatches { matched_any: bool, matches: Vec<bool>, } impl SetMatches { pub fn matched_any(&self) -> bool { self.matched_any } pub fn matched(&self, regex_index: usize) -> bool { self.matches[regex_index] } pub fn len(&self) -> usize { self.matches.len() } pub fn iter(&self) -> SetMatchesIter { SetMatchesIter((&*self.matches).into_iter().enumerate()) } } impl IntoIterator for SetMatches { type IntoIter = SetMatchesIntoIter; type Item = usize; fn into_iter(self) -> Self::IntoIter { SetMatchesIntoIter(self.matches.into_iter().enumerate()) } } impl<'a> IntoIterator for &'a SetMatches { type IntoIter = SetMatchesIter<'a>; type Item = usize; fn into_iter(self) -> Self::IntoIter { self.iter() } } pub struct SetMatchesIntoIter(iter::Enumerate<vec::IntoIter<bool>>); impl Iterator for SetMatchesIntoIter { type Item = usize; fn next(&mut self) -> Option
dedIterator for SetMatchesIter<'a> { fn next_back(&mut self) -> Option<usize> { loop { match self.0.next_back() { None => return None, Some((_, &false)) => {} Some((i, &true)) => return Some(i), } } } } #[doc(hidden)] impl From<Exec> for RegexSet { fn from(exec: Exec) -> Self { RegexSet(exec) } } impl fmt::Debug for RegexSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "RegexSet({:?})", self.0.regex_strings()) } } #[allow(dead_code)] fn as_bytes_str(text: &str) -> &[u8] { text.as_bytes() } #[allow(dead_code)] fn as_bytes_bytes(text: &[u8]) -> &[u8] { text } } } } define_set! { unicode, |exprs| ExecBuilder::new_many(exprs).build(), &str, as_bytes_str } define_set! { bytes, |exprs| ExecBuilder::new_many(exprs).only_utf8(false).build(), &[u8], as_bytes_bytes }
<usize> { loop { match self.0.next() { None => return None, Some((_, false)) => {} Some((i, true)) => return Some(i), } } } } impl DoubleEndedIterator for SetMatchesIntoIter { fn next_back(&mut self) -> Option<usize> { loop { match self.0.next_back() { None => return None, Some((_, false)) => {} Some((i, true)) => return Some(i), } } } } #[derive(Clone)] pub struct SetMatchesIter<'a>(iter::Enumerate<slice::Iter<'a, bool>>); impl<'a> Iterator for SetMatchesIter<'a> { type Item = usize; fn next(&mut self) -> Option<usize> { loop { match self.0.next() { None => return None, Some((_, &false)) => {} Some((i, &true)) => return Some(i), } } } } impl<'a> DoubleEn
random
[ { "content": "/// Tests if the given regular expression matches somewhere in the text given.\n\n///\n\n/// If there was a problem compiling the regular expression, an error is\n\n/// returned.\n\n///\n\n/// To find submatches, split or replace text, you'll need to compile an\n\n/// expression first.\n\npub fn i...
Rust
src/passes/mod.rs
Kixiron/cranial-coitus
2f0b158709b23f23a4d84045846829b250779f31
mod add_sub_loop; mod associative_ops; mod canonicalize; mod const_folding; mod copy_cell; mod dataflow; mod dce; mod eliminate_const_gamma; mod equality; mod expr_dedup; mod fold_arithmetic; mod fuse_io; mod licm; mod mem2reg; mod move_cell; mod scan_loops; mod square_cell; mod symbolic_eval; mod unobserved_store; mod utils; mod zero_loop; pub use add_sub_loop::AddSubLoop; pub use associative_ops::AssociativeOps; pub use canonicalize::Canonicalize; pub use const_folding::ConstFolding; pub use copy_cell::CopyCell; pub use dataflow::{Dataflow, DataflowSettings}; pub use dce::Dce; pub use eliminate_const_gamma::ElimConstGamma; pub use equality::Equality; pub use expr_dedup::ExprDedup; pub use fold_arithmetic::FoldArithmetic; pub use fuse_io::FuseIO; pub use licm::Licm; pub use mem2reg::Mem2Reg; pub use move_cell::MoveCell; pub use scan_loops::ScanLoops; pub use square_cell::SquareCell; pub use symbolic_eval::SymbolicEval; pub use unobserved_store::UnobservedStore; pub use zero_loop::ZeroLoop; use crate::{ graph::{ Add, Bool, Byte, End, Eq, Gamma, Input, InputParam, Int, Load, Mul, Neg, Neq, Node, NodeExt, NodeId, Not, Output, OutputParam, Rvsdg, Scan, Start, Store, Sub, Theta, }, passes::utils::ChangeReport, utils::HashSet, values::{Cell, Ptr}, }; use std::{cell::RefCell, collections::VecDeque}; #[derive(Debug, Clone)] pub struct PassConfig { tape_len: u16, tape_operations_wrap: bool, cell_operations_wrap: bool, } impl PassConfig { pub fn new(tape_len: u16, tape_operations_wrap: bool, cell_operations_wrap: bool) -> Self { Self { tape_len, tape_operations_wrap, cell_operations_wrap, } } } pub fn default_passes(config: &PassConfig) -> Vec<Box<dyn Pass>> { let tape_len = config.tape_len; bvec![ UnobservedStore::new(tape_len), ConstFolding::new(tape_len), FoldArithmetic::new(tape_len), AssociativeOps::new(tape_len), ZeroLoop::new(tape_len), Mem2Reg::new(tape_len), AddSubLoop::new(tape_len), FuseIO::new(), MoveCell::new(tape_len), ScanLoops::new(tape_len), Dce::new(), ElimConstGamma::new(tape_len), ConstFolding::new(tape_len), SymbolicEval::new(tape_len), Licm::new(), CopyCell::new(tape_len), Equality::new(), ExprDedup::new(tape_len), Canonicalize::new(), Dce::new(), ] } thread_local! { #[allow(clippy::declare_interior_mutable_const)] #[allow(clippy::type_complexity)] static VISIT_GRAPH_CACHE: RefCell<Vec<(VecDeque<NodeId>, HashSet<NodeId>, Vec<NodeId>)>> = const { RefCell::new(Vec::new()) }; } pub trait Pass { fn pass_name(&self) -> &'static str; fn did_change(&self) -> bool; fn reset(&mut self); fn report(&self) -> ChangeReport { ChangeReport::default() } fn visit_graph(&mut self, graph: &mut Rvsdg) -> bool { let (mut stack, mut visited, mut buffer) = VISIT_GRAPH_CACHE .with(|buffers| buffers.borrow_mut().pop()) .unwrap_or_else(|| { ( VecDeque::with_capacity(graph.node_len() / 2), HashSet::with_capacity_and_hasher(graph.node_len(), Default::default()), Vec::new(), ) }); let result = self.visit_graph_inner(graph, &mut stack, &mut visited, &mut buffer); stack.clear(); visited.clear(); buffer.clear(); VISIT_GRAPH_CACHE.with(|buffers| buffers.borrow_mut().push((stack, visited, buffer))); result } fn visit_graph_inner( &mut self, graph: &mut Rvsdg, stack: &mut VecDeque<NodeId>, visited: &mut HashSet<NodeId>, buffer: &mut Vec<NodeId>, ) -> bool { visited.clear(); buffer.clear(); for node_id in graph.node_ids() { let node = graph.get_node(node_id); if node.is_start() || node.is_input_param() { stack.push_back(node_id); } else if node.is_end() || node.is_output_param() { stack.push_front(node_id); } } while let Some(node_id) = stack.pop_back() { if visited.contains(&node_id) || !graph.contains_node(node_id) { continue; } let mut missing_inputs = false; buffer.extend(graph.try_inputs(node_id).filter_map(|(_, input)| { input.and_then(|(input, ..)| { let input_id = input.node(); if !visited.contains(&input_id) { missing_inputs = true; Some(input_id) } else { None } }) })); if missing_inputs { stack.reserve(buffer.len() + 1); stack.push_back(node_id); stack.extend(buffer.drain(..)); continue; } self.visit(graph, node_id); self.after_visit(graph, node_id); let didnt_exist = visited.insert(node_id); debug_assert!(didnt_exist); if graph.contains_node(node_id) { buffer.extend( graph .get_node(node_id) .all_output_ports() .into_iter() .flat_map(|output| graph.get_outputs(output)) .filter_map(|(output_node, ..)| { let output_id = output_node.node(); (!visited.contains(&output_id) && !stack.contains(&output_id)) .then(|| output_id) }), ); stack.extend(buffer.drain(..)); } } self.post_visit_graph(graph, visited); stack.clear(); buffer.clear(); visited.clear(); self.did_change() } fn post_visit_graph(&mut self, _graph: &mut Rvsdg, _visited: &HashSet<NodeId>) {} fn after_visit(&mut self, _graph: &mut Rvsdg, _node_id: NodeId) {} fn visit(&mut self, graph: &mut Rvsdg, node_id: NodeId) { if let Some(node) = graph.try_node(node_id).cloned() { match node { Node::Int(int, value) => self.visit_int(graph, int, value), Node::Byte(byte, value) => self.visit_byte(graph, byte, value), Node::Bool(bool, value) => self.visit_bool(graph, bool, value), Node::Add(add) => self.visit_add(graph, add), Node::Sub(sub) => self.visit_sub(graph, sub), Node::Mul(mul) => self.visit_mul(graph, mul), Node::Load(load) => self.visit_load(graph, load), Node::Store(store) => self.visit_store(graph, store), Node::Scan(scan) => self.visit_scan(graph, scan), Node::Start(start) => self.visit_start(graph, start), Node::End(end) => self.visit_end(graph, end), Node::Input(input) => self.visit_input(graph, input), Node::Output(output) => self.visit_output(graph, output), Node::Theta(theta) => self.visit_theta(graph, *theta), Node::Eq(eq) => self.visit_eq(graph, eq), Node::Neq(neq) => self.visit_neq(graph, neq), Node::Not(not) => self.visit_not(graph, not), Node::Neg(neg) => self.visit_neg(graph, neg), Node::Gamma(gamma) => self.visit_gamma(graph, *gamma), Node::InputParam(input_param) => self.visit_input_param(graph, input_param), Node::OutputParam(output_param) => self.visit_output_param(graph, output_param), } } else { tracing::error!("visited node that doesn't exist: {:?}", node_id); } } fn visit_int(&mut self, _graph: &mut Rvsdg, _int: Int, _value: Ptr) {} fn visit_byte(&mut self, _graph: &mut Rvsdg, _byte: Byte, _value: Cell) {} fn visit_bool(&mut self, _graph: &mut Rvsdg, _bool: Bool, _value: bool) {} fn visit_add(&mut self, _graph: &mut Rvsdg, _add: Add) {} fn visit_sub(&mut self, _graph: &mut Rvsdg, _sub: Sub) {} fn visit_mul(&mut self, _graph: &mut Rvsdg, _mul: Mul) {} fn visit_not(&mut self, _graph: &mut Rvsdg, _not: Not) {} fn visit_neg(&mut self, _graph: &mut Rvsdg, _neg: Neg) {} fn visit_eq(&mut self, _graph: &mut Rvsdg, _eq: Eq) {} fn visit_neq(&mut self, _graph: &mut Rvsdg, _neq: Neq) {} fn visit_load(&mut self, _graph: &mut Rvsdg, _load: Load) {} fn visit_store(&mut self, _graph: &mut Rvsdg, _store: Store) {} fn visit_scan(&mut self, _graph: &mut Rvsdg, _scan: Scan) {} fn visit_input(&mut self, _graph: &mut Rvsdg, _input: Input) {} fn visit_output(&mut self, _graph: &mut Rvsdg, _output: Output) {} fn visit_theta(&mut self, _graph: &mut Rvsdg, _theta: Theta) {} fn visit_gamma(&mut self, _graph: &mut Rvsdg, _gamma: Gamma) {} fn visit_input_param(&mut self, _graph: &mut Rvsdg, _input: InputParam) {} fn visit_output_param(&mut self, _graph: &mut Rvsdg, _output: OutputParam) {} fn visit_start(&mut self, _graph: &mut Rvsdg, _start: Start) {} fn visit_end(&mut self, _graph: &mut Rvsdg, _end: End) {} } test_opts! { memchr_loop, passes = |tape_len| bvec![ZeroLoop::new(tape_len)], output = [0], |graph, mut effect, tape_len| { let mut ptr = graph.int(Ptr::zero(tape_len)).value(); let not_zero = graph.int(Ptr::new(255, tape_len)).value(); let store = graph.store(ptr, not_zero, effect); effect = store.output_effect(); let theta = graph.theta([], [ptr], effect, |graph, mut effect, _invariant, variant| { let ptr = variant[0]; let zero = graph.int(Ptr::zero(tape_len)).value(); let four = graph.int(Ptr::new(4, tape_len)).value(); let add = graph.add(ptr, four); let load = graph.load(add.value(), effect); effect = load.output_effect(); let not_eq_zero = graph.neq(load.output_value(), zero); ThetaData::new([ptr], not_eq_zero.value(), effect) }); ptr = theta.output_ports().next().unwrap(); effect = theta.output_effect().unwrap(); let load = graph.load(ptr, effect); effect = load.output_effect(); let output = graph.output(load.output_value(), effect); output.output_effect() }, }
mod add_sub_loop; mod associative_ops; mod canonicalize; mod const_folding; mod copy_cell; mod dataflow; mod dce; mod eliminate_const_gamma; mod equality; mod expr_dedup; mod fold_arithmetic; mod fuse_io; mod licm; mod mem2reg; mod move_cell; mod scan_loops; mod square_cell; mod symbolic_eval; mod unobserved_store; mod utils; mod zero_loop; pub use add_sub_loop::AddSubLoop; pub use associative_ops::AssociativeOps; pub use canonicalize::Canonicalize; pub use const_folding::ConstFolding; pub use copy_cell::CopyCell; pub use dataflow::{Dataflow, DataflowSettings}; pub use dce::Dce; pub use eliminate_const_gamma::ElimConstGamma; pub use equality::Equality; pub use expr_dedup::ExprDedup; pub use fold_arithmetic::FoldArithmetic; pub use fuse_io::FuseIO; pub use licm::Licm; pub use mem2reg::Mem2Reg; pub use move_cell::MoveCell; pub use scan_loops::ScanLoops; pub use square_cell::SquareCell; pub use symbolic_eval::SymbolicEval; pub use unobserved_store::UnobservedStore; pub use zero_loop::ZeroLoop; use crate::{ graph::{ Add, Bool, Byte, End, Eq, Gamma, Input, InputParam, Int, Load, Mul, Neg, Neq, Node, NodeExt, NodeId, Not, Output, OutputParam, Rvsdg, Scan, Start, Store, Sub, Theta, }, passes::utils::ChangeReport, utils::HashSet, values::{Cell, Ptr}, }; use std::{cell::RefCell, collections::VecDeque}; #[derive(Debug, Clone)] pub struct PassConfig { tape_len: u16, tape_operations_wrap: bool, cell_operations_wrap: bool, } impl PassConfig { pub fn new(tape_len: u16, tape_operations_wrap: bool, cell_operations_wrap: bool) -> Self { Self { tape_len, tape_operations_wrap, cell_operations_wrap, } } } pub fn default_passes(config: &PassConfig) -> Vec<Box<dyn Pass>> { let tape_len = config.tape_len; bvec![ UnobservedStore::new(tape_len), ConstFolding::new(tape_len), FoldArithmetic::new(tape_len), AssociativeOps::new(tape_len), ZeroLoop::new(tape_len), Mem2Reg::new(tape_len), AddSubLoop::new(tape_len), FuseIO::new(), MoveCell::new(tape_len), ScanLoops::new(tape_len), Dce::new(), ElimConstGamma::new(tape_len), ConstFolding::new(tape_len), SymbolicEval::new(tape_len), Licm::new(), CopyCell::new(tape_len), Equality::new(), ExprDedup::new(tape_len), Canonicalize::new(), Dce::new(), ] } thread_local! { #[allow(clippy::declare_interior_mutable_const)] #[allow(clippy::type_complexity)] static VISIT_GRAPH_CACHE: RefCell<Vec<(VecDeque<NodeId>, HashSet<NodeId>, Vec<NodeId>)>> = const { RefCell::new(Vec::new()) }; } pub trait Pass { fn pass_name(&self) -> &'static str; fn did_change(&self) -> bool; fn reset(&mut self); fn report(&self) -> ChangeReport { ChangeReport::default() }
fn visit_graph_inner( &mut self, graph: &mut Rvsdg, stack: &mut VecDeque<NodeId>, visited: &mut HashSet<NodeId>, buffer: &mut Vec<NodeId>, ) -> bool { visited.clear(); buffer.clear(); for node_id in graph.node_ids() { let node = graph.get_node(node_id); if node.is_start() || node.is_input_param() { stack.push_back(node_id); } else if node.is_end() || node.is_output_param() { stack.push_front(node_id); } } while let Some(node_id) = stack.pop_back() { if visited.contains(&node_id) || !graph.contains_node(node_id) { continue; } let mut missing_inputs = false; buffer.extend(graph.try_inputs(node_id).filter_map(|(_, input)| { input.and_then(|(input, ..)| { let input_id = input.node(); if !visited.contains(&input_id) { missing_inputs = true; Some(input_id) } else { None } }) })); if missing_inputs { stack.reserve(buffer.len() + 1); stack.push_back(node_id); stack.extend(buffer.drain(..)); continue; } self.visit(graph, node_id); self.after_visit(graph, node_id); let didnt_exist = visited.insert(node_id); debug_assert!(didnt_exist); if graph.contains_node(node_id) { buffer.extend( graph .get_node(node_id) .all_output_ports() .into_iter() .flat_map(|output| graph.get_outputs(output)) .filter_map(|(output_node, ..)| { let output_id = output_node.node(); (!visited.contains(&output_id) && !stack.contains(&output_id)) .then(|| output_id) }), ); stack.extend(buffer.drain(..)); } } self.post_visit_graph(graph, visited); stack.clear(); buffer.clear(); visited.clear(); self.did_change() } fn post_visit_graph(&mut self, _graph: &mut Rvsdg, _visited: &HashSet<NodeId>) {} fn after_visit(&mut self, _graph: &mut Rvsdg, _node_id: NodeId) {} fn visit(&mut self, graph: &mut Rvsdg, node_id: NodeId) { if let Some(node) = graph.try_node(node_id).cloned() { match node { Node::Int(int, value) => self.visit_int(graph, int, value), Node::Byte(byte, value) => self.visit_byte(graph, byte, value), Node::Bool(bool, value) => self.visit_bool(graph, bool, value), Node::Add(add) => self.visit_add(graph, add), Node::Sub(sub) => self.visit_sub(graph, sub), Node::Mul(mul) => self.visit_mul(graph, mul), Node::Load(load) => self.visit_load(graph, load), Node::Store(store) => self.visit_store(graph, store), Node::Scan(scan) => self.visit_scan(graph, scan), Node::Start(start) => self.visit_start(graph, start), Node::End(end) => self.visit_end(graph, end), Node::Input(input) => self.visit_input(graph, input), Node::Output(output) => self.visit_output(graph, output), Node::Theta(theta) => self.visit_theta(graph, *theta), Node::Eq(eq) => self.visit_eq(graph, eq), Node::Neq(neq) => self.visit_neq(graph, neq), Node::Not(not) => self.visit_not(graph, not), Node::Neg(neg) => self.visit_neg(graph, neg), Node::Gamma(gamma) => self.visit_gamma(graph, *gamma), Node::InputParam(input_param) => self.visit_input_param(graph, input_param), Node::OutputParam(output_param) => self.visit_output_param(graph, output_param), } } else { tracing::error!("visited node that doesn't exist: {:?}", node_id); } } fn visit_int(&mut self, _graph: &mut Rvsdg, _int: Int, _value: Ptr) {} fn visit_byte(&mut self, _graph: &mut Rvsdg, _byte: Byte, _value: Cell) {} fn visit_bool(&mut self, _graph: &mut Rvsdg, _bool: Bool, _value: bool) {} fn visit_add(&mut self, _graph: &mut Rvsdg, _add: Add) {} fn visit_sub(&mut self, _graph: &mut Rvsdg, _sub: Sub) {} fn visit_mul(&mut self, _graph: &mut Rvsdg, _mul: Mul) {} fn visit_not(&mut self, _graph: &mut Rvsdg, _not: Not) {} fn visit_neg(&mut self, _graph: &mut Rvsdg, _neg: Neg) {} fn visit_eq(&mut self, _graph: &mut Rvsdg, _eq: Eq) {} fn visit_neq(&mut self, _graph: &mut Rvsdg, _neq: Neq) {} fn visit_load(&mut self, _graph: &mut Rvsdg, _load: Load) {} fn visit_store(&mut self, _graph: &mut Rvsdg, _store: Store) {} fn visit_scan(&mut self, _graph: &mut Rvsdg, _scan: Scan) {} fn visit_input(&mut self, _graph: &mut Rvsdg, _input: Input) {} fn visit_output(&mut self, _graph: &mut Rvsdg, _output: Output) {} fn visit_theta(&mut self, _graph: &mut Rvsdg, _theta: Theta) {} fn visit_gamma(&mut self, _graph: &mut Rvsdg, _gamma: Gamma) {} fn visit_input_param(&mut self, _graph: &mut Rvsdg, _input: InputParam) {} fn visit_output_param(&mut self, _graph: &mut Rvsdg, _output: OutputParam) {} fn visit_start(&mut self, _graph: &mut Rvsdg, _start: Start) {} fn visit_end(&mut self, _graph: &mut Rvsdg, _end: End) {} } test_opts! { memchr_loop, passes = |tape_len| bvec![ZeroLoop::new(tape_len)], output = [0], |graph, mut effect, tape_len| { let mut ptr = graph.int(Ptr::zero(tape_len)).value(); let not_zero = graph.int(Ptr::new(255, tape_len)).value(); let store = graph.store(ptr, not_zero, effect); effect = store.output_effect(); let theta = graph.theta([], [ptr], effect, |graph, mut effect, _invariant, variant| { let ptr = variant[0]; let zero = graph.int(Ptr::zero(tape_len)).value(); let four = graph.int(Ptr::new(4, tape_len)).value(); let add = graph.add(ptr, four); let load = graph.load(add.value(), effect); effect = load.output_effect(); let not_eq_zero = graph.neq(load.output_value(), zero); ThetaData::new([ptr], not_eq_zero.value(), effect) }); ptr = theta.output_ports().next().unwrap(); effect = theta.output_effect().unwrap(); let load = graph.load(ptr, effect); effect = load.output_effect(); let output = graph.output(load.output_value(), effect); output.output_effect() }, }
fn visit_graph(&mut self, graph: &mut Rvsdg) -> bool { let (mut stack, mut visited, mut buffer) = VISIT_GRAPH_CACHE .with(|buffers| buffers.borrow_mut().pop()) .unwrap_or_else(|| { ( VecDeque::with_capacity(graph.node_len() / 2), HashSet::with_capacity_and_hasher(graph.node_len(), Default::default()), Vec::new(), ) }); let result = self.visit_graph_inner(graph, &mut stack, &mut visited, &mut buffer); stack.clear(); visited.clear(); buffer.clear(); VISIT_GRAPH_CACHE.with(|buffers| buffers.borrow_mut().push((stack, visited, buffer))); result }
function_block-full_function
[ { "content": "pub fn stdout_output() -> impl FnMut(u8) + 'static {\n\n move |byte| {\n\n // FIXME: Lock once, move into closure\n\n let stdout_handle = io::stdout();\n\n let mut stdout = stdout_handle.lock();\n\n\n\n tracing::trace!(\n\n \"wrote output value {byte}, hex...
Rust
garnet/bin/setui/src/tests/media_buttons_agent_tests.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use crate::agent::media_buttons; use crate::agent::Invocation; use crate::agent::Lifespan; use crate::agent::{Context, Payload}; use crate::event::{self, Event}; use crate::input::{MediaButtons, VolumeGain}; use crate::message::base::{Audience, MessengerType}; use crate::message::MessageHubUtil; use crate::service; use crate::service_context::ServiceContext; use crate::tests::fakes::input_device_registry_service::InputDeviceRegistryService; use crate::tests::fakes::service_registry::ServiceRegistry; use fidl_fuchsia_ui_input::MediaButtonsEvent; use futures::lock::Mutex; use media_buttons::MediaButtonsAgent; use std::collections::HashSet; use std::sync::Arc; struct FakeServices { input_device_registry: Arc<Mutex<InputDeviceRegistryService>>, } async fn create_services() -> (Arc<Mutex<ServiceRegistry>>, FakeServices) { let service_registry = ServiceRegistry::create(); let input_device_registry_service_handle = Arc::new(Mutex::new(InputDeviceRegistryService::new())); service_registry.lock().await.register_service(input_device_registry_service_handle.clone()); (service_registry, FakeServices { input_device_registry: input_device_registry_service_handle }) } #[fuchsia_async::run_until_stalled(test)] async fn test_media_buttons_proxied() { let service_hub = service::MessageHub::create_hub(); let agent_receptor = service_hub .create(MessengerType::Unbound) .await .expect("Unable to create agent messenger") .1; let signature = agent_receptor.get_signature(); let (agent_messenger, _) = service_hub.create(MessengerType::Unbound).await.expect("Unable to create agent messenger"); let mut event_receptor = service::build_event_listener(&service_hub).await; let context = Context::new(agent_receptor, service_hub, HashSet::new(), HashSet::new(), None).await; MediaButtonsAgent::create(context).await; let (service_registry, fake_services) = create_services().await; let service_context = Arc::new(ServiceContext::new(Some(ServiceRegistry::serve(service_registry)), None)); let invocation = Invocation { lifespan: Lifespan::Service, service_context }; let mut reply_receptor = agent_messenger .message(Payload::Invocation(invocation).into(), Audience::Messenger(signature)) .send(); let mut completion_result = None; if let Ok((Payload::Complete(result), _)) = reply_receptor.next_of::<Payload>().await { completion_result = Some(result); } assert!( matches!(completion_result, Some(Ok(()))), "Did not receive a completion event from the invocation message" ); fake_services .input_device_registry .lock() .await .send_media_button_event(MediaButtonsEvent { volume: Some(1), mic_mute: Some(true), pause: None, camera_disable: None, ..MediaButtonsEvent::EMPTY }) .await; let mut mic_mute_received = false; let mut volume_received = false; while let Ok((event::Payload::Event(event), _)) = event_receptor.next_of::<event::Payload>().await { if let Event::MediaButtons(event) = event { match event { event::media_buttons::Event::OnButton(MediaButtons { mic_mute: Some(true), .. }) => { mic_mute_received = true; if volume_received { break; } } event::media_buttons::Event::OnVolume(VolumeGain::Up) => { volume_received = true; if mic_mute_received { break; } } _ => {} } } } assert!(mic_mute_received); assert!(volume_received); }
use crate::agent::media_buttons; use crate::agent::Invocation; use crate::agent::Lifespan; use crate::agent::{Context, Payload}; use crate::event::{self, Event}; use crate::input::{MediaButtons, VolumeGain}; use crate::message::base::{Audience, MessengerType}; use crate::message::MessageHubUtil; use crate::service; use crate::service_context::ServiceContext; use crate::tests::fakes::input_device_registry_service::InputDeviceRegistryService; use crate::tests::fakes::service_registry::ServiceRegistry; use fidl_fuchsia_ui_input::MediaButtonsEvent; use futures::lock::Mutex; use media_buttons::MediaButtonsAgent; use std::collections::HashSet; use std::sync::Arc; struct FakeServices { input_device_registry: Arc<Mutex<InputDeviceRegistryService>>, } async fn create_services() -> (Arc<Mutex<ServiceRegistry>>, FakeServices) { let service_registry = ServiceRegistry::create(); let input_device_registry_service_handle = Arc::new(Mutex::new(InputDeviceRegistryService::new())); service_registry.lock().await.register_service(input_device_registry_service_handle.clone()); (service_registry, FakeServices { input_device_registry: input_device_registry_service_handle }) } #[fuchsia_async::run_until_stalled(test)] async fn test_media_buttons_proxied() { let service_hub = service::MessageHub::create_hub(); let agent_receptor = service_hub .create(MessengerType::Unbound) .await .expect("Unable to create agent messenger") .1; let signature = agent_receptor.get_signature(); let (agent_messenger, _) = service_hub.create(MessengerType::Unbound).await.expect("Unable to create agent messenger"); let mut event_receptor = service::build_event_listener(&service_hub).await; let context = Context::new(agent_receptor, service_hub, HashSet::new(), HashSet::new(), None).await; MediaButtonsAgent::create(context).await; let (service_registry, fake_services) = create_services().await; let service_context = Arc::new(ServiceContext::new(Some(ServiceRegistry::serve(service_registry)), None)); let invocation = Invocation { lifespan: Lifespan::Service, service_context }; let mut reply_receptor = agent_messenger .message(Payload::Invocation(invocation).into(), Audience::Messenger(signature)) .send(); let mut completion_result = None;
assert!( matches!(completion_result, Some(Ok(()))), "Did not receive a completion event from the invocation message" ); fake_services .input_device_registry .lock() .await .send_media_button_event(MediaButtonsEvent { volume: Some(1), mic_mute: Some(true), pause: None, camera_disable: None, ..MediaButtonsEvent::EMPTY }) .await; let mut mic_mute_received = false; let mut volume_received = false; while let Ok((event::Payload::Event(event), _)) = event_receptor.next_of::<event::Payload>().await { if let Event::MediaButtons(event) = event { match event { event::media_buttons::Event::OnButton(MediaButtons { mic_mute: Some(true), .. }) => { mic_mute_received = true; if volume_received { break; } } event::media_buttons::Event::OnVolume(VolumeGain::Up) => { volume_received = true; if mic_mute_received { break; } } _ => {} } } } assert!(mic_mute_received); assert!(volume_received); }
if let Ok((Payload::Complete(result), _)) = reply_receptor.next_of::<Payload>().await { completion_result = Some(result); }
if_condition
[]
Rust
src/reconnectable_ws.rs
hermanodecastro/openlimits
af7b4d59c6a874c662bbc5ace9271bcb1956a8c5
use crate::errors::OpenLimitsError; use crate::exchange_ws::{CallbackHandle, ExchangeWs, OpenLimitsWs, Subscriptions}; use crate::model::websocket::{Subscription, WebSocketResponse}; use crate::shared::Result; use futures::stream::BoxStream; use std::sync::Arc; use std::thread::sleep; use tokio::sync::mpsc::{unbounded_channel, UnboundedSender}; use tokio::sync::Mutex; use tokio::time::Duration; pub type SubscriptionCallback<Response> = Arc<dyn Fn(&Result<WebSocketResponse<Response>>) + Sync + Send + 'static>; pub type SubscriptionCallbackRegistry<E> = ( Subscription, SubscriptionCallback<<E as ExchangeWs>::Response>, ); pub struct ReconnectableWebsocket<E: ExchangeWs> { websocket: Arc<Mutex<OpenLimitsWs<E>>>, tx: UnboundedSender<()>, subscriptions: Arc<Mutex<Vec<SubscriptionCallbackRegistry<E>>>>, } impl<E: ExchangeWs + 'static> ReconnectableWebsocket<E> { pub async fn instantiate(params: E::InitParams, reattempt_interval: Duration) -> Result<Self> { let websocket = E::new(params.clone()).await?; let websocket = OpenLimitsWs { websocket }; let websocket = Arc::new(Mutex::new(websocket)); let subscriptions: Arc<Mutex<Vec<SubscriptionCallbackRegistry<E>>>> = Arc::new(Mutex::new(Default::default())); let (tx, mut rx) = unbounded_channel(); { let websocket = Arc::downgrade(&websocket); let subscriptions = Arc::downgrade(&subscriptions); let tx = tx.clone(); tokio::spawn(async move { while rx.recv().await.is_some() { 'reconnection: loop { if let (Some(websocket), Some(subscriptions)) = (websocket.upgrade(), subscriptions.upgrade()) { if let Ok(new_websocket) = E::new(params.clone()).await { let new_websocket = OpenLimitsWs { websocket: new_websocket, }; let mut websocket = websocket.lock().await; *websocket = new_websocket; let subscriptions = { subscriptions.lock().await.clone() }; let subscriptions = subscriptions.iter().map(|(subscription, callback)| { let callback = callback.clone(); let tx = tx.clone(); websocket.subscribe(subscription.clone(), move |message| { if let Err(OpenLimitsError::SocketError()) = message.as_ref() { tx.send(()).ok(); } callback(message) }) }); if futures_util::future::join_all(subscriptions) .await .iter() .all(|subscription| subscription.is_ok()) { break 'reconnection; } } sleep(reattempt_interval); } } } }); } Ok(Self { websocket, tx, subscriptions, }) } pub async fn create_stream_specific( &self, subscriptions: Subscriptions<E::Subscription>, ) -> Result<BoxStream<'static, Result<E::Response>>> { self.websocket .lock() .await .create_stream_specific(subscriptions) .await } pub async fn subscribe< F: Fn(&Result<WebSocketResponse<E::Response>>) + Sync + Send + Clone + 'static, >( &self, subscription: Subscription, callback: F, ) -> Result<CallbackHandle> { let tx = self.tx.clone(); self.subscriptions .lock() .await .push((subscription.clone(), Arc::new(callback.clone()))); self.websocket .lock() .await .subscribe(subscription, move |message| { if let Err(OpenLimitsError::SocketError()) = message.as_ref() { tx.send(()).ok(); } callback(message); }) .await } pub async fn create_stream<S: Into<E::Subscription> + Clone + Send + Sync>( &self, subscriptions: &[S], ) -> Result<BoxStream<'static, Result<WebSocketResponse<E::Response>>>> { self.websocket .lock() .await .create_stream(subscriptions) .await } pub async fn disconnect(&self) { self.websocket.lock().await.disconnect().await; } }
use crate::errors::OpenLimitsError; use crate::exchange_ws::{CallbackHandle, ExchangeWs, OpenLimitsWs, Subscriptions}; use crate::model::websocket::{Subscription, WebSocketResponse}; use crate::shared::Result; use futures::stream::BoxStream; use std::sync::Arc; use std::thread::sleep; use tokio::sync::mpsc::{unbounded_channel, UnboundedSender}; use tokio::sync::Mutex; use tokio::time::Duration; pub type SubscriptionCallback<Response> = Arc<dyn Fn(&Result<WebSocketResponse<Response>>) + Sync + Send + 'static>; pub type SubscriptionCallbackRegistry<E> = ( Subscription, SubscriptionCallback<<E as ExchangeWs>::Response>, ); pub struct ReconnectableWebsocket<E: ExchangeWs> { websocket: Arc<Mutex<OpenLimitsWs<E>>>, tx: UnboundedSender<()>, subscriptions: Arc<Mutex<Vec<SubscriptionCallbackRegistry<E>>>>, } impl<E: ExchangeWs + 'static> ReconnectableWebsocket<E> { pub async fn instantiate(params: E::InitParams, reattempt_interval: Duration) -> Result<Self> { let websocket = E::new(params.clone()).await?; let websocket = OpenLimitsWs { websocket }; let websocket = Arc::new(Mutex::new(websocket)); let subscriptions: Arc<Mutex<Vec<SubscriptionCallbackRegistry<E>>>> = Arc::new(Mutex::new(Default::default())); let (tx, mut rx) = unbounded_channel(); { let websocket = Arc::downgrade(&websocket); let subscriptions = Arc::downgrade(&subscriptions); let tx = tx.clone(); tokio::spawn(async move { while rx.recv().await.is_some() { 'reconnection: loop { if let (Some(websocket), Some(subscriptions)) = (websocket.upgrade(), subscriptions.upgrade()) { if let Ok(new_websocket) = E::new(params.clone()).await { let new_websocket = OpenLimitsWs { websocket: new_websocket, }; let mut websocket = websocket.lock().await; *websocket = new_websocket; let subscriptions = { subscriptions.lock().await.clone() }; let subscriptions = subscriptions.iter().map(|(subscription, callback)| { let callback = callback.clone(); let tx = tx.clone(); websocket.subscribe(subscription.clone(), move |message| { if let Err(OpenLimitsError::SocketError()) = message.as_ref() { tx.send(()).ok(); }
pub async fn create_stream_specific( &self, subscriptions: Subscriptions<E::Subscription>, ) -> Result<BoxStream<'static, Result<E::Response>>> { self.websocket .lock() .await .create_stream_specific(subscriptions) .await } pub async fn subscribe< F: Fn(&Result<WebSocketResponse<E::Response>>) + Sync + Send + Clone + 'static, >( &self, subscription: Subscription, callback: F, ) -> Result<CallbackHandle> { let tx = self.tx.clone(); self.subscriptions .lock() .await .push((subscription.clone(), Arc::new(callback.clone()))); self.websocket .lock() .await .subscribe(subscription, move |message| { if let Err(OpenLimitsError::SocketError()) = message.as_ref() { tx.send(()).ok(); } callback(message); }) .await } pub async fn create_stream<S: Into<E::Subscription> + Clone + Send + Sync>( &self, subscriptions: &[S], ) -> Result<BoxStream<'static, Result<WebSocketResponse<E::Response>>>> { self.websocket .lock() .await .create_stream(subscriptions) .await } pub async fn disconnect(&self) { self.websocket.lock().await.disconnect().await; } }
callback(message) }) }); if futures_util::future::join_all(subscriptions) .await .iter() .all(|subscription| subscription.is_ok()) { break 'reconnection; } } sleep(reattempt_interval); } } } }); } Ok(Self { websocket, tx, subscriptions, }) }
function_block-function_prefix_line
[ { "content": "#[async_trait]\n\npub trait ExchangeWs: Send + Sync + Sized {\n\n type InitParams: Clone + Send + Sync + 'static;\n\n type Subscription: From<Subscription> + Send + Sync + Sized + Clone;\n\n type Response: TryInto<WebSocketResponse<Self::Response>, Error = OpenLimitsError>\n\n + Se...
Rust
src/processes/poisson.rs
rasa200/markovian
8824ae58301e83f2b8f0278b3d321c2a4000331a
use num_traits::Float; use rand_distr::{Exp1, Exp}; use crate::{State, StateIterator}; use core::fmt::Debug; use num_traits::{sign::Unsigned, One, Zero}; use rand::Rng; use rand_distr::Distribution; use crate::errors::InvalidState; use core::mem; #[derive(Debug, Clone)] pub struct Poisson<N, T, R> where N: Float, Exp1: Distribution<N>, T: Debug + PartialEq + Clone + One + Zero + PartialOrd + Unsigned, R: Rng, { state: T, exp: Exp<N>, rng: R, } impl<N, T, R> Poisson<N, T, R> where N: Float, Exp1: Distribution<N>, T: Debug + PartialEq + Clone + One + Zero + PartialOrd + Unsigned, R: Rng, { #[inline] pub fn new(lambda: N, rng: R) -> Result<Self, rand_distr::ExpError> { Ok(Poisson { state: T::zero(), exp: Exp::new(lambda)?, rng, }) } } impl<N, T, R> State for Poisson<N, T, R> where N: Float, Exp1: Distribution<N>, T: Debug + PartialEq + Clone + One + Zero + PartialOrd + Unsigned, R: Rng, { type Item = T; #[inline] fn state(&self) -> Option<&Self::Item> { Some(&self.state) } #[inline] fn state_mut(&mut self) -> Option<&mut Self::Item> { Some(&mut self.state) } #[inline] fn set_state( &mut self, mut new_state: Self::Item, ) -> Result<Option<Self::Item>, InvalidState<Self::Item>> { mem::swap(&mut self.state, &mut new_state); Ok(Some(new_state)) } } impl<N, T, R> Iterator for Poisson<N, T, R> where N: Float, Exp1: Distribution<N>, T: Debug + PartialEq + Clone + One + Zero + PartialOrd + Unsigned, R: Rng, { type Item = (N, T); #[inline] fn next(&mut self) -> Option<Self::Item> { let period = self.exp.sample(&mut self.rng); self.set_state(self.state.clone() + T::one()).unwrap(); self.state().cloned().map(|state| (period, state)) } } impl<N, T, R> StateIterator for Poisson<N, T, R> where N: Float, Exp1: Distribution<N>, T: Debug + PartialEq + Clone + One + Zero + PartialOrd + Unsigned, R: Rng, { #[inline] fn state_as_item(&self) -> Option<<Self as std::iter::Iterator>::Item> { self.state().cloned().map(|state| (N::zero(), state)) } } impl<N, T, R> Distribution<(N, T)> for Poisson<N, T, R> where N: Float, Exp1: Distribution<N>, T: Debug + PartialEq + Clone + One + Zero + PartialOrd + Unsigned, R: Rng, { #[inline] fn sample<R2>(&self, rng: &mut R2) -> (N, T) where R2: Rng + ?Sized, { (self.exp.sample(rng), self.state.clone() + T::one()) } } #[cfg(test)] mod tests { use super::*; #[test] fn value_stability() { let rng = crate::tests::rng(3); let lambda = 1.; let expected = vec![(0.529274135874436, 1), (0.5369108748992898, 2), (0.3618522192460201, 3), (0.5717432176122981, 4)]; let mc = Poisson::new(lambda, rng).unwrap(); let sample: Vec<(f64, u64)> = mc.take(4).collect(); assert_eq!(sample, expected); } }
use num_traits::Float; use rand_distr::{Exp1, Exp}; use crate::{State, StateIterator}; use core::fmt::Debug; use num_traits::{sign::Unsigned, One, Zero}; use rand::Rng; use rand_distr::Distribution; use crate::errors::InvalidState; use core::mem; #[derive(Debug, Clone)] pub struct Poisson<N, T, R> where N: Float, Exp1: Distribution<N>, T: Debug + PartialEq + Clone + One + Zero + PartialOrd + Unsigned, R: Rng, { state: T, exp: Exp<N>, rng: R, } impl<N, T, R> Poisson<N, T, R> where N: Float, Exp1: Distribution<N>, T: Debug + PartialEq + Clone + One + Zero + PartialOrd + Unsigned, R: Rng, { #[inline] pub fn new(lambda: N, rng: R) -> Result<Self, rand_distr::ExpError> { Ok(Poisson { state: T::zero(), exp: Exp::new(lambda)?, rng, }) } } impl<N, T, R> State for Poisson<N, T, R> where N: Float, Exp1: Distribution<N>, T: Debug + PartialEq + Clone + One + Zero + PartialOrd + Unsigned, R: Rng, { type Item = T; #[inline] fn state(&self) -> Option<&Self::Item> { Some(&self.state) } #[inline] fn state_mut(&mut self) -> Option<&mut Self::Item> { Some(&mut self.state) } #[inline]
} impl<N, T, R> Iterator for Poisson<N, T, R> where N: Float, Exp1: Distribution<N>, T: Debug + PartialEq + Clone + One + Zero + PartialOrd + Unsigned, R: Rng, { type Item = (N, T); #[inline] fn next(&mut self) -> Option<Self::Item> { let period = self.exp.sample(&mut self.rng); self.set_state(self.state.clone() + T::one()).unwrap(); self.state().cloned().map(|state| (period, state)) } } impl<N, T, R> StateIterator for Poisson<N, T, R> where N: Float, Exp1: Distribution<N>, T: Debug + PartialEq + Clone + One + Zero + PartialOrd + Unsigned, R: Rng, { #[inline] fn state_as_item(&self) -> Option<<Self as std::iter::Iterator>::Item> { self.state().cloned().map(|state| (N::zero(), state)) } } impl<N, T, R> Distribution<(N, T)> for Poisson<N, T, R> where N: Float, Exp1: Distribution<N>, T: Debug + PartialEq + Clone + One + Zero + PartialOrd + Unsigned, R: Rng, { #[inline] fn sample<R2>(&self, rng: &mut R2) -> (N, T) where R2: Rng + ?Sized, { (self.exp.sample(rng), self.state.clone() + T::one()) } } #[cfg(test)] mod tests { use super::*; #[test] fn value_stability() { let rng = crate::tests::rng(3); let lambda = 1.; let expected = vec![(0.529274135874436, 1), (0.5369108748992898, 2), (0.3618522192460201, 3), (0.5717432176122981, 4)]; let mc = Poisson::new(lambda, rng).unwrap(); let sample: Vec<(f64, u64)> = mc.take(4).collect(); assert_eq!(sample, expected); } }
fn set_state( &mut self, mut new_state: Self::Item, ) -> Result<Option<Self::Item>, InvalidState<Self::Item>> { mem::swap(&mut self.state, &mut new_state); Ok(Some(new_state)) }
function_block-full_function
[ { "content": "pub trait State {\n\n type Item: core::fmt::Debug;\n\n\n\n #[inline]\n\n fn state(&self) -> Option<&Self::Item> {\n\n None\n\n }\n\n\n\n #[inline]\n\n fn state_mut(&mut self) -> Option<&mut Self::Item> {\n\n None\n\n }\n\n\n\n /// Changes the `state` of the st...
Rust
src/libinput.rs
harshadgavali/gnome-x11-gesture-daemon
3c5a56a5ca9cf151bcee05bb8bbc8af3309b5f12
use std::{ fs::{File, OpenOptions}, os::unix::prelude::{AsRawFd, FromRawFd, IntoRawFd, OpenOptionsExt, RawFd}, path::Path, sync::mpsc, }; use input::{ event::{ gesture::{GestureHoldEvent, GesturePinchEvent, GestureSwipeEvent}, Event, GestureEvent, }, ffi::{ libinput_event_gesture_get_angle_delta, libinput_event_gesture_get_cancelled, libinput_event_gesture_get_dx_unaccelerated, libinput_event_gesture_get_dy_unaccelerated, libinput_event_gesture_get_finger_count, libinput_event_gesture_get_scale, libinput_event_gesture_get_time, }, Libinput, LibinputInterface, }; use libc::{poll, pollfd}; use serde::{Deserialize, Serialize}; use zvariant::derive::Type; #[derive(Debug, Deserialize, Serialize, Type)] pub struct CustomSwipeEvent { pub stage: String, pub fingers: i32, pub dx: f64, pub dy: f64, pub time: u32, } #[derive(Debug, Deserialize, Serialize, Type)] pub struct CustomHoldEvent { pub stage: String, pub fingers: i32, pub time: u32, pub is_cancelled: bool, } #[derive(Debug, Deserialize, Serialize, Type)] pub struct CustomPinchEvent { pub stage: String, pub fingers: i32, pub angle_delta: f64, pub scale: f64, pub time: u32, } pub enum CustomGestureEvent { Swipe(CustomSwipeEvent), Hold(CustomHoldEvent), Pinch(CustomPinchEvent), } struct Interface; impl LibinputInterface for Interface { #[allow(clippy::bad_bit_mask)] fn open_restricted(&mut self, path: &Path, flags: i32) -> Result<RawFd, i32> { OpenOptions::new() .custom_flags(flags) .read((flags & libc::O_RDONLY != 0) | (flags & libc::O_RDWR != 0)) .write((flags & libc::O_WRONLY != 0) | (flags & libc::O_RDWR != 0)) .open(path) .map(|file| file.into_raw_fd()) .map_err(|err| err.raw_os_error().unwrap()) } fn close_restricted(&mut self, fd: RawFd) { unsafe { File::from_raw_fd(fd); } } } pub fn handle_swipe(swipe: GestureSwipeEvent, transmitter: &mpsc::Sender<CustomGestureEvent>) { let stage = match &swipe { GestureSwipeEvent::Begin(_) => "Begin", GestureSwipeEvent::Update(_) => "Update", GestureSwipeEvent::End(_) => "End", _ => panic!("Unkown gesture event {:?}", swipe), }; let (fingers, dx, dy, time) = unsafe { let raw_gesture_event = input::AsRaw::as_raw_mut(&swipe); ( libinput_event_gesture_get_finger_count(raw_gesture_event), libinput_event_gesture_get_dx_unaccelerated(raw_gesture_event), libinput_event_gesture_get_dy_unaccelerated(raw_gesture_event), libinput_event_gesture_get_time(raw_gesture_event), ) }; let swipe = CustomSwipeEvent { stage: stage.into(), fingers, dx, dy, time, }; transmitter.send(CustomGestureEvent::Swipe(swipe)).unwrap(); } pub fn handle_hold(hold: GestureHoldEvent, transmitter: &mpsc::Sender<CustomGestureEvent>) { let stage = match &hold { GestureHoldEvent::Begin(_) => "Begin", GestureHoldEvent::End(_) => "End", _ => panic!("Unkown gesture event {:?}", hold), }; let (fingers, time, is_cancelled) = unsafe { let raw_gesture_event = input::AsRaw::as_raw_mut(&hold); ( libinput_event_gesture_get_finger_count(raw_gesture_event), libinput_event_gesture_get_time(raw_gesture_event), matches!(hold, GestureHoldEvent::End(_)) && libinput_event_gesture_get_cancelled(raw_gesture_event) != 0, ) }; if fingers < 3 { return; } let hold = CustomHoldEvent { stage: stage.into(), fingers, time, is_cancelled, }; transmitter.send(CustomGestureEvent::Hold(hold)).unwrap(); } fn handle_pinch(pinch: GesturePinchEvent, transmitter: &mpsc::Sender<CustomGestureEvent>) { let stage = match &pinch { GesturePinchEvent::Begin(_) => "Begin", GesturePinchEvent::Update(_) => "Update", GesturePinchEvent::End(_) => "End", _ => panic!("Unkown gesture event {:?}", pinch), }; let (fingers, angle_delta, scale, time) = unsafe { let raw_gesture_event = input::AsRaw::as_raw_mut(&pinch); ( libinput_event_gesture_get_finger_count(raw_gesture_event), libinput_event_gesture_get_angle_delta(raw_gesture_event), libinput_event_gesture_get_scale(raw_gesture_event), libinput_event_gesture_get_time(raw_gesture_event), ) }; if fingers < 3 { return; } let pinch = CustomPinchEvent { stage: stage.into(), fingers, angle_delta, scale, time, }; transmitter.send(CustomGestureEvent::Pinch(pinch)).unwrap(); } pub fn libinput_listener(transmitter: mpsc::Sender<CustomGestureEvent>) { let mut input = Libinput::new_with_udev(Interface); input.udev_assign_seat("seat0").unwrap(); const POLLIN: i16 = 1; let mut poll_fds = pollfd { fd: input.as_raw_fd(), events: POLLIN, revents: 0, }; loop { unsafe { poll(&mut poll_fds, 1, -1); } input.dispatch().unwrap(); loop { let event = input.next(); if event.is_none() { break; } if let Event::Gesture(gesture_event) = event.unwrap() { match gesture_event { GestureEvent::Hold(hold) => handle_hold(hold, &transmitter), GestureEvent::Swipe(swipe) => handle_swipe(swipe, &transmitter), GestureEvent::Pinch(pinch) => handle_pinch(pinch, &transmitter), _ => {} } } } } }
use std::{ fs::{File, OpenOptions}, os::unix::prelude::{AsRawFd, FromRawFd, IntoRawFd, OpenOptionsExt, RawFd}, path::Path, sync::mpsc, }; use input::{ event::{ gesture::{GestureHoldEvent, GesturePinchEvent, GestureSwipeEvent}, Event, GestureEvent, }, ffi::{ libinput_event_gesture_get_angle_delta, libinput_event_gesture_get_cancelled, libinput_event_gesture_get_dx_unaccelerated, libinput_event_gesture_get_dy_unaccelerated, libinput_event_gesture_get_finger_count, libinput_event_gesture_get_scale, libinput_event_gesture_get_time, }, Libinput, LibinputInterface, }; use libc::{poll, pollfd}; use serde::{Deserialize, Serialize}; use zvariant::derive::Type; #[derive(Debug, Deserialize, Serialize, Type)] pub struct CustomSwipeEvent { pub stage: String, pub fingers: i32, pub dx: f64, pub dy: f64, pub time: u32, } #[derive(Debug, Deserialize, Serialize, Type)] pub struct CustomHoldEvent { pub stage: String, pub fingers: i32, pub time: u32, pub is_cancelled: bool, } #[derive(Debug, Deserialize, Serialize, Type)] pub struct CustomPinchEvent { pub stage: String, pub fingers: i32, pub angle_delta: f64, pub scale: f64, pub time: u32, } pub enum CustomGestureEvent { Swipe(CustomSwipeEvent), Hold(CustomHoldEvent), Pinch(CustomPinchEvent), } struct Interface; impl LibinputInterface for Interface { #[allow(clippy::bad_bit_mask)]
fn close_restricted(&mut self, fd: RawFd) { unsafe { File::from_raw_fd(fd); } } } pub fn handle_swipe(swipe: GestureSwipeEvent, transmitter: &mpsc::Sender<CustomGestureEvent>) { let stage = match &swipe { GestureSwipeEvent::Begin(_) => "Begin", GestureSwipeEvent::Update(_) => "Update", GestureSwipeEvent::End(_) => "End", _ => panic!("Unkown gesture event {:?}", swipe), }; let (fingers, dx, dy, time) = unsafe { let raw_gesture_event = input::AsRaw::as_raw_mut(&swipe); ( libinput_event_gesture_get_finger_count(raw_gesture_event), libinput_event_gesture_get_dx_unaccelerated(raw_gesture_event), libinput_event_gesture_get_dy_unaccelerated(raw_gesture_event), libinput_event_gesture_get_time(raw_gesture_event), ) }; let swipe = CustomSwipeEvent { stage: stage.into(), fingers, dx, dy, time, }; transmitter.send(CustomGestureEvent::Swipe(swipe)).unwrap(); } pub fn handle_hold(hold: GestureHoldEvent, transmitter: &mpsc::Sender<CustomGestureEvent>) { let stage = match &hold { GestureHoldEvent::Begin(_) => "Begin", GestureHoldEvent::End(_) => "End", _ => panic!("Unkown gesture event {:?}", hold), }; let (fingers, time, is_cancelled) = unsafe { let raw_gesture_event = input::AsRaw::as_raw_mut(&hold); ( libinput_event_gesture_get_finger_count(raw_gesture_event), libinput_event_gesture_get_time(raw_gesture_event), matches!(hold, GestureHoldEvent::End(_)) && libinput_event_gesture_get_cancelled(raw_gesture_event) != 0, ) }; if fingers < 3 { return; } let hold = CustomHoldEvent { stage: stage.into(), fingers, time, is_cancelled, }; transmitter.send(CustomGestureEvent::Hold(hold)).unwrap(); } fn handle_pinch(pinch: GesturePinchEvent, transmitter: &mpsc::Sender<CustomGestureEvent>) { let stage = match &pinch { GesturePinchEvent::Begin(_) => "Begin", GesturePinchEvent::Update(_) => "Update", GesturePinchEvent::End(_) => "End", _ => panic!("Unkown gesture event {:?}", pinch), }; let (fingers, angle_delta, scale, time) = unsafe { let raw_gesture_event = input::AsRaw::as_raw_mut(&pinch); ( libinput_event_gesture_get_finger_count(raw_gesture_event), libinput_event_gesture_get_angle_delta(raw_gesture_event), libinput_event_gesture_get_scale(raw_gesture_event), libinput_event_gesture_get_time(raw_gesture_event), ) }; if fingers < 3 { return; } let pinch = CustomPinchEvent { stage: stage.into(), fingers, angle_delta, scale, time, }; transmitter.send(CustomGestureEvent::Pinch(pinch)).unwrap(); } pub fn libinput_listener(transmitter: mpsc::Sender<CustomGestureEvent>) { let mut input = Libinput::new_with_udev(Interface); input.udev_assign_seat("seat0").unwrap(); const POLLIN: i16 = 1; let mut poll_fds = pollfd { fd: input.as_raw_fd(), events: POLLIN, revents: 0, }; loop { unsafe { poll(&mut poll_fds, 1, -1); } input.dispatch().unwrap(); loop { let event = input.next(); if event.is_none() { break; } if let Event::Gesture(gesture_event) = event.unwrap() { match gesture_event { GestureEvent::Hold(hold) => handle_hold(hold, &transmitter), GestureEvent::Swipe(swipe) => handle_swipe(swipe, &transmitter), GestureEvent::Pinch(pinch) => handle_pinch(pinch, &transmitter), _ => {} } } } } }
fn open_restricted(&mut self, path: &Path, flags: i32) -> Result<RawFd, i32> { OpenOptions::new() .custom_flags(flags) .read((flags & libc::O_RDONLY != 0) | (flags & libc::O_RDWR != 0)) .write((flags & libc::O_WRONLY != 0) | (flags & libc::O_RDWR != 0)) .open(path) .map(|file| file.into_raw_fd()) .map_err(|err| err.raw_os_error().unwrap()) }
function_block-full_function
[ { "content": "struct Greeter {}\n\n\n\n#[dbus_interface(name = \"org.gestureImprovements.gestures\")]\n\nimpl Greeter {\n\n #[dbus_interface(signal)]\n\n fn touchpad_swipe(&self, event: &libinput::CustomSwipeEvent) -> zbus::Result<()>;\n\n\n\n #[dbus_interface(signal)]\n\n fn touchpad_hold(&self, ev...
Rust
src/bvh.rs
q4x3/raytracer
7ebb6e1f505dae0985a972fab2d9237cbba3cbc9
use crate::{ aabb::AABB, hittable::{HitRecord, HitTable}, ray::Ray, rtweekend::random_int, vec3::Point3, }; use std::{cmp::Ordering, sync::Arc}; #[derive(Clone)] pub struct BVHNode { left: Arc<dyn HitTable>, right: Arc<dyn HitTable>, bvhbox: AABB, } impl BVHNode { pub fn new( objects: &mut Vec<Arc<dyn HitTable>>, start: usize, end: usize, time0: f64, time1: f64, ) -> Self { let axis = random_int(0, 3); let mut tmp: BVHNode; let comparator = if axis == 0 { box_x_compare } else if axis == 1 { box_y_compare } else { box_z_compare }; let object_span = end - start; if object_span == 1 { tmp = BVHNode { left: objects[start].clone(), right: objects[start].clone(), bvhbox: AABB::new(Point3::zero(), Point3::zero()), }; } else if object_span == 2 { if comparator(&objects[start], &objects[start + 1]) == Ordering::Less { tmp = BVHNode { left: objects[start].clone(), right: objects[start + 1].clone(), bvhbox: AABB::new(Point3::zero(), Point3::zero()), }; } else { tmp = BVHNode { left: objects[start + 1].clone(), right: objects[start].clone(), bvhbox: AABB::new(Point3::zero(), Point3::zero()), }; } } else { objects.as_mut_slice()[start..end].sort_by(comparator); let mid = start + object_span / 2; tmp = BVHNode { left: Arc::new(BVHNode::new(objects, start, mid, time0, time1)), right: Arc::new(BVHNode::new(objects, mid, end, time0, time1)), bvhbox: AABB::new(Point3::zero(), Point3::zero()), }; } let mut box_left = AABB::new(Point3::zero(), Point3::zero()); let mut box_right = AABB::new(Point3::zero(), Point3::zero()); if !tmp.left.bounding_box(time0, time1, &mut box_left) || !tmp.right.bounding_box(time0, time1, &mut box_right) { println!("No bounding box in bvh_node constructor.\n"); } tmp.bvhbox = AABB::surrounding_box(&box_left, &box_right); tmp } } pub fn box_x_compare(a: &Arc<dyn HitTable>, b: &Arc<dyn HitTable>) -> Ordering { let mut box_a = AABB::new(Point3::zero(), Point3::zero()); let mut box_b = AABB::new(Point3::zero(), Point3::zero()); if !a.bounding_box(0.0, 0.0, &mut box_a) || !b.bounding_box(0.0, 0.0, &mut box_b) { println!("No bounding box in bvh_node constructor.\n"); } if box_a._min.x < box_b._min.x { return Ordering::Less; } else if box_a._min.x > box_b._min.x { return Ordering::Greater; } Ordering::Equal } pub fn box_y_compare(a: &Arc<dyn HitTable>, b: &Arc<dyn HitTable>) -> Ordering { let mut box_a = AABB::new(Point3::zero(), Point3::zero()); let mut box_b = AABB::new(Point3::zero(), Point3::zero()); if !a.bounding_box(0.0, 0.0, &mut box_a) || !b.bounding_box(0.0, 0.0, &mut box_b) { println!("No bounding box in bvh_node constructor.\n"); } if box_a._min.y < box_b._min.y { return Ordering::Less; } else if box_a._min.y > box_b._min.y { return Ordering::Greater; } Ordering::Equal } pub fn box_z_compare(a: &Arc<dyn HitTable>, b: &Arc<dyn HitTable>) -> Ordering { let mut box_a = AABB::new(Point3::zero(), Point3::zero()); let mut box_b = AABB::new(Point3::zero(), Point3::zero()); if !a.bounding_box(0.0, 0.0, &mut box_a) || !b.bounding_box(0.0, 0.0, &mut box_b) { println!("No bounding box in bvh_node constructor.\n"); } if box_a._min.z < box_b._min.z { return Ordering::Less; } else if box_a._min.z > box_b._min.z { return Ordering::Greater; } Ordering::Equal } impl HitTable for BVHNode { fn hit(&self, r: &Ray, t_min: f64, t_max: f64, rec: &mut HitRecord) -> bool { if !self.bvhbox.hit(r, t_min, t_max) { return false; } let hit_left = self.left.hit(r, t_min, t_max, rec); let hit_right = self .right .hit(r, t_min, if hit_left { rec.t } else { t_max }, rec); hit_left || hit_right } fn bounding_box(&self, _t0: f64, _t1: f64, output_box: &mut AABB) -> bool { *output_box = self.bvhbox.clone(); true } fn distance(&self, _other_center: &Point3) -> f64 { 0.0 } }
use crate::{ aabb::AABB, hittable::{HitRecord, HitTable}, ray::Ray, rtweekend::random_int, vec3::Point3, }; use std::{cmp::Ordering, sync::Arc}; #[derive(Clone)] pub struct BVHNode { left: Arc<dyn HitTable>, right: Arc<dyn HitTable>, bvhbox: AABB, } impl BVHNode { pub fn new( objects: &mut Vec<Arc<dyn HitTable>>, start: usize, end: usize, time0: f64, time1: f64, ) -> Self { let axis = random_int(0, 3); let mut tmp: BVHNode; let comparator = if axis == 0 { box_x_compare } else if axis == 1 { box_y_compare } else { box_z_compare }; let object_span = end - start; if object_span == 1 {
tor(&objects[start], &objects[start + 1]) == Ordering::Less { tmp = BVHNode { left: objects[start].clone(), right: objects[start + 1].clone(), bvhbox: AABB::new(Point3::zero(), Point3::zero()), }; } else { tmp = BVHNode { left: objects[start + 1].clone(), right: objects[start].clone(), bvhbox: AABB::new(Point3::zero(), Point3::zero()), }; } } else { objects.as_mut_slice()[start..end].sort_by(comparator); let mid = start + object_span / 2; tmp = BVHNode { left: Arc::new(BVHNode::new(objects, start, mid, time0, time1)), right: Arc::new(BVHNode::new(objects, mid, end, time0, time1)), bvhbox: AABB::new(Point3::zero(), Point3::zero()), }; } let mut box_left = AABB::new(Point3::zero(), Point3::zero()); let mut box_right = AABB::new(Point3::zero(), Point3::zero()); if !tmp.left.bounding_box(time0, time1, &mut box_left) || !tmp.right.bounding_box(time0, time1, &mut box_right) { println!("No bounding box in bvh_node constructor.\n"); } tmp.bvhbox = AABB::surrounding_box(&box_left, &box_right); tmp } } pub fn box_x_compare(a: &Arc<dyn HitTable>, b: &Arc<dyn HitTable>) -> Ordering { let mut box_a = AABB::new(Point3::zero(), Point3::zero()); let mut box_b = AABB::new(Point3::zero(), Point3::zero()); if !a.bounding_box(0.0, 0.0, &mut box_a) || !b.bounding_box(0.0, 0.0, &mut box_b) { println!("No bounding box in bvh_node constructor.\n"); } if box_a._min.x < box_b._min.x { return Ordering::Less; } else if box_a._min.x > box_b._min.x { return Ordering::Greater; } Ordering::Equal } pub fn box_y_compare(a: &Arc<dyn HitTable>, b: &Arc<dyn HitTable>) -> Ordering { let mut box_a = AABB::new(Point3::zero(), Point3::zero()); let mut box_b = AABB::new(Point3::zero(), Point3::zero()); if !a.bounding_box(0.0, 0.0, &mut box_a) || !b.bounding_box(0.0, 0.0, &mut box_b) { println!("No bounding box in bvh_node constructor.\n"); } if box_a._min.y < box_b._min.y { return Ordering::Less; } else if box_a._min.y > box_b._min.y { return Ordering::Greater; } Ordering::Equal } pub fn box_z_compare(a: &Arc<dyn HitTable>, b: &Arc<dyn HitTable>) -> Ordering { let mut box_a = AABB::new(Point3::zero(), Point3::zero()); let mut box_b = AABB::new(Point3::zero(), Point3::zero()); if !a.bounding_box(0.0, 0.0, &mut box_a) || !b.bounding_box(0.0, 0.0, &mut box_b) { println!("No bounding box in bvh_node constructor.\n"); } if box_a._min.z < box_b._min.z { return Ordering::Less; } else if box_a._min.z > box_b._min.z { return Ordering::Greater; } Ordering::Equal } impl HitTable for BVHNode { fn hit(&self, r: &Ray, t_min: f64, t_max: f64, rec: &mut HitRecord) -> bool { if !self.bvhbox.hit(r, t_min, t_max) { return false; } let hit_left = self.left.hit(r, t_min, t_max, rec); let hit_right = self .right .hit(r, t_min, if hit_left { rec.t } else { t_max }, rec); hit_left || hit_right } fn bounding_box(&self, _t0: f64, _t1: f64, output_box: &mut AABB) -> bool { *output_box = self.bvhbox.clone(); true } fn distance(&self, _other_center: &Point3) -> f64 { 0.0 } }
tmp = BVHNode { left: objects[start].clone(), right: objects[start].clone(), bvhbox: AABB::new(Point3::zero(), Point3::zero()), }; } else if object_span == 2 { if compara
random
[]
Rust
devices/src/virtio/video/decoder/capability.rs
aosp-riscv/platform_external_crosvm
ff681b6a18eff76336a68058c11afdc287255615
use base::warn; use std::collections::btree_map::Entry; use std::collections::BTreeMap; use crate::virtio::video::control::*; use crate::virtio::video::format::*; fn from_pixel_format( fmt: &libvda::PixelFormat, mask: u64, width_range: FormatRange, height_range: FormatRange, ) -> FormatDesc { let format = match fmt { libvda::PixelFormat::NV12 => Format::NV12, libvda::PixelFormat::YV12 => Format::YUV420, }; let frame_formats = vec![FrameFormat { width: width_range, height: height_range, bitrates: Vec::new(), }]; FormatDesc { mask, format, frame_formats, } } pub struct Capability { pub in_fmts: Vec<FormatDesc>, pub out_fmts: Vec<FormatDesc>, profiles: BTreeMap<Format, Vec<Profile>>, levels: BTreeMap<Format, Vec<Level>>, } impl Capability { pub fn new(caps: &libvda::decode::Capabilities) -> Self { let mask = !(u64::max_value() << caps.output_formats.len()); let mut in_fmts = vec![]; let mut profiles: BTreeMap<Format, Vec<Profile>> = Default::default(); for fmt in caps.input_formats.iter() { match Profile::from_libvda_profile(fmt.profile) { Some(profile) => { let format = profile.to_format(); in_fmts.push(FormatDesc { mask, format, frame_formats: vec![Default::default()], }); match profiles.entry(format) { Entry::Occupied(mut e) => e.get_mut().push(profile), Entry::Vacant(e) => { e.insert(vec![profile]); } } } None => { warn!( "No virtio-video equivalent for libvda profile, skipping: {:?}", fmt.profile ); } } } let levels: BTreeMap<Format, Vec<Level>> = if profiles.contains_key(&Format::H264) { vec![(Format::H264, vec![Level::H264_1_0])] .into_iter() .collect() } else { Default::default() }; let min_width = caps.input_formats.iter().map(|fmt| fmt.min_width).max(); let max_width = caps.input_formats.iter().map(|fmt| fmt.max_width).min(); let min_height = caps.input_formats.iter().map(|fmt| fmt.min_height).max(); let max_height = caps.input_formats.iter().map(|fmt| fmt.max_height).min(); let width_range = FormatRange { min: min_width.unwrap_or(0), max: max_width.unwrap_or(0), step: 1, }; let height_range = FormatRange { min: min_height.unwrap_or(0), max: max_height.unwrap_or(0), step: 1, }; let mask = !(u64::max_value() << caps.input_formats.len()); let out_fmts = caps .output_formats .iter() .map(|fmt| from_pixel_format(fmt, mask, width_range, height_range)) .collect(); Capability { in_fmts, out_fmts, profiles, levels, } } pub fn query_control(&self, t: &QueryCtrlType) -> Option<QueryCtrlResponse> { use QueryCtrlType::*; match *t { Profile(fmt) => { let profiles = self.profiles.get(&fmt)?; Some(QueryCtrlResponse::Profile( profiles.iter().copied().collect(), )) } Level(fmt) => { let levels = self.levels.get(&fmt)?; Some(QueryCtrlResponse::Level(levels.iter().copied().collect())) } } } }
use base::warn; use std::collections::btree_map::Entry; use std::collections::BTreeMap; use crate::virtio::video::control::*; use crate::virtio::video::format::*; fn from_pixel_format( fmt: &libvda::PixelFormat, mask: u64, width_range: FormatRange, height_range: FormatRange, ) -> FormatDesc { let format = match fmt { libvda::PixelFormat::NV12 => Format::NV12, libvda::PixelFormat::YV12 => Format::YUV420, }; let frame_formats = vec![FrameFormat { width: width_range, height: height_range, bitrates: Vec::new(), }]; FormatDesc { mask, format, frame_formats, } } pub struct Capability { pub in_fmts: Vec<FormatDesc>, pub out_fmts: Vec<FormatDesc>, profiles: BTreeMap<Format, Vec<Profile>>, levels: BTreeMap<Format, Vec<Level>>, } impl Capability { pub fn new(caps: &libvda::decode::Capabilities) -> Self { let mask = !(u64::max_value() << caps.output_formats.len()); let mut in_fmts = vec![]; let mut profiles: BTreeMap<Format, Vec<Profile>> = Default::default(); for fmt in caps.input_formats.iter() { match Profile::from_libvda_profile(fmt.profile) { Some(profile) => { let format = profile.to_format(); in_fmts.push(FormatDesc { mask, format, frame_formats: vec![Default::default()], }); match profiles.entry(format) { Entry::Occupied(mut e) => e.get_mut().push(profile), Entry::Vacant(e) => { e.insert(vec![profile]); } } } None => { warn!( "No virtio-video equivalent for libvda profile, skipping: {:?}", fmt.profile ); } }
nge, height_range)) .collect(); Capability { in_fmts, out_fmts, profiles, levels, } } pub fn query_control(&self, t: &QueryCtrlType) -> Option<QueryCtrlResponse> { use QueryCtrlType::*; match *t { Profile(fmt) => { let profiles = self.profiles.get(&fmt)?; Some(QueryCtrlResponse::Profile( profiles.iter().copied().collect(), )) } Level(fmt) => { let levels = self.levels.get(&fmt)?; Some(QueryCtrlResponse::Level(levels.iter().copied().collect())) } } } }
} let levels: BTreeMap<Format, Vec<Level>> = if profiles.contains_key(&Format::H264) { vec![(Format::H264, vec![Level::H264_1_0])] .into_iter() .collect() } else { Default::default() }; let min_width = caps.input_formats.iter().map(|fmt| fmt.min_width).max(); let max_width = caps.input_formats.iter().map(|fmt| fmt.max_width).min(); let min_height = caps.input_formats.iter().map(|fmt| fmt.min_height).max(); let max_height = caps.input_formats.iter().map(|fmt| fmt.max_height).min(); let width_range = FormatRange { min: min_width.unwrap_or(0), max: max_width.unwrap_or(0), step: 1, }; let height_range = FormatRange { min: min_height.unwrap_or(0), max: max_height.unwrap_or(0), step: 1, }; let mask = !(u64::max_value() << caps.input_formats.len()); let out_fmts = caps .output_formats .iter() .map(|fmt| from_pixel_format(fmt, mask, width_ra
random
[ { "content": "/// Returns a Vec of the valid memory addresses.\n\n/// These should be used to configure the GuestMemory structure for the platfrom.\n\npub fn arch_memory_regions(size: u64) -> Vec<(GuestAddress, u64)> {\n\n vec![(GuestAddress(AARCH64_PHYS_MEM_START), size)]\n\n}\n\n\n", "file_path": "aarc...
Rust
src/vec/tests.rs
interlockledger/rust-il2-utils
1c441c609fd71a25fb3a4644b6ed9052180443a6
/* * BSD 3-Clause License * * Copyright (c) 2019-2020, InterlockLedger Network * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * * 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. */ use super::*; #[test] fn test_vecextensions_with_value() { for i in 0..32 { let sample: [u8; 32] = [i as u8; 32]; let v: Vec<u8> = Vec::with_value(&sample); assert_eq!(v.as_slice(), &sample); } } #[test] fn test_vecextensions_set_capacity_to() { let mut v = Vec::<u8>::new(); v.set_capacity_to(10); assert_eq!(v.len(), 0); assert!(v.capacity() >= 10); v.set_capacity_to(100); assert_eq!(v.len(), 0); assert!(v.capacity() >= 100); let sample: [u8; 4] = [1, 2, 3, 4]; let mut v = Vec::<u8>::new(); v.extend_from_slice(&sample); v.set_capacity_to(10); assert_eq!(v.as_slice(), &sample); assert!(v.capacity() >= 10); v.set_capacity_to(100); assert_eq!(v.as_slice(), &sample); assert!(v.capacity() >= 100); } #[test] fn test_vecextensions_set_capacity_to_secure() { let mut v = Vec::<u8>::new(); v.set_capacity_to_secure(10); assert_eq!(v.len(), 0); assert!(v.capacity() >= 10); v.set_capacity_to_secure(100); assert_eq!(v.len(), 0); assert!(v.capacity() >= 100); let sample: [u8; 4] = [1, 2, 3, 4]; let mut v = Vec::<u8>::new(); v.extend_from_slice(&sample); v.set_capacity_to_secure(10); assert_eq!(v.as_slice(), &sample); assert!(v.capacity() >= 10); v.set_capacity_to_secure(100); assert_eq!(v.as_slice(), &sample); assert!(v.capacity() >= 100); } #[test] fn test_vecextensions_set_contents_from_slice() { let sample: [u8; 32] = [0xFA; 32]; let mut v = Vec::<u8>::new(); let old_capacity = v.capacity(); v.set_contents_from_slice(&sample[0..0]); assert!(v.is_empty()); assert_eq!(v.capacity(), old_capacity); let mut v = Vec::<u8>::new(); let old_capacity = v.capacity(); v.set_contents_from_slice(&sample); assert_eq!(v.as_slice(), &sample); assert!(old_capacity < v.capacity()); let old_capacity = v.capacity(); let sample: [u8; 16] = [0xBA; 16]; v.set_contents_from_slice(&sample); assert_eq!(v.as_slice(), &sample); assert_eq!(v.capacity(), old_capacity); } #[test] fn test_vecextensions_set_contents_from_slice_secure() { let sample: [u8; 32] = [0xFA; 32]; let mut v = Vec::<u8>::new(); let old_capacity = v.capacity(); v.set_contents_from_slice_secure(&sample[0..0]); assert!(v.is_empty()); assert_eq!(v.capacity(), old_capacity); let mut v = Vec::<u8>::new(); let old_capacity = v.capacity(); v.set_contents_from_slice_secure(&sample); assert_eq!(v.as_slice(), &sample); assert!(old_capacity < v.capacity()); let old_capacity = v.capacity(); let sample: [u8; 16] = [0xBA; 16]; v.set_contents_from_slice_secure(&sample); assert_eq!(v.as_slice(), &sample); assert_eq!(v.capacity(), old_capacity); } #[test] fn test_vecextensions_shrink_to_fit_secure() { let sample: [u8; 32] = [0xFA; 32]; let mut v = Vec::<u8>::with_capacity(128); let old_capacity = v.capacity(); v.shrink_to_fit_secure(); assert!(v.capacity() < old_capacity); let mut v = Vec::<u8>::with_capacity(128); let old_capacity = v.capacity(); v.set_contents_from_slice(&sample); v.shrink_to_fit_secure(); assert!(v.capacity() < old_capacity); assert_eq!(v.as_slice(), &sample); } #[test] fn test_vecextensions_reserve_secure() { let sample: [u8; 32] = [0xFA; 32]; let mut v = Vec::<u8>::new(); let old_capacity = v.capacity(); v.reserve_secure(10); assert!(v.capacity() > old_capacity); let mut v = Vec::<u8>::new(); v.set_contents_from_slice(&sample); let old_capacity = v.capacity(); v.reserve_secure(128); assert!(v.capacity() > old_capacity); assert_eq!(v.as_slice(), &sample); } #[test] fn test_vecextensions_extend_from_slice_secure() { let mut v = Vec::<u8>::new(); let mut exp = Vec::<u8>::new(); for i in 0..32 { let sample: [u8; 32] = [i as u8; 32]; v.extend_from_slice_secure(&sample); exp.extend_from_slice(&sample); assert_eq!(v.as_slice(), exp.as_slice()); } }
/* * BSD 3-Clause License * * Copyright (c) 2019-2020, InterlockLedger Network * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * * 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. */ use super::*; #[test] fn test_vecextensions_with_value() { for i in 0..32 { let sample: [u8; 32] = [i as u8; 32]; let v: Vec<u8> = Vec::with_value(&sample); assert_eq!(v.as_slice(), &sample); } } #[test] fn test_vecextensions_set_capacity_to() { let mut v = Vec::<u8>::new(); v.set_capacity_to(10); assert_eq!(v.len(), 0); assert!(v.capacity() >= 10); v.set_capacity_to(100); assert_eq!(v.len(), 0); assert!(v.capacity() >= 100); let sample: [u8; 4] = [1, 2, 3, 4]; let mut v = Vec::<u8>::new(); v.extend_from_slice(&sample); v.set_capacity_to(10); assert_eq!(v.as_slice(), &sample); assert!(v.capacity() >= 10); v.set_capacity_to(100); assert_eq!(v.as_slice(), &sample); assert!(v.capacity() >= 100); } #[test]
#[test] fn test_vecextensions_set_contents_from_slice() { let sample: [u8; 32] = [0xFA; 32]; let mut v = Vec::<u8>::new(); let old_capacity = v.capacity(); v.set_contents_from_slice(&sample[0..0]); assert!(v.is_empty()); assert_eq!(v.capacity(), old_capacity); let mut v = Vec::<u8>::new(); let old_capacity = v.capacity(); v.set_contents_from_slice(&sample); assert_eq!(v.as_slice(), &sample); assert!(old_capacity < v.capacity()); let old_capacity = v.capacity(); let sample: [u8; 16] = [0xBA; 16]; v.set_contents_from_slice(&sample); assert_eq!(v.as_slice(), &sample); assert_eq!(v.capacity(), old_capacity); } #[test] fn test_vecextensions_set_contents_from_slice_secure() { let sample: [u8; 32] = [0xFA; 32]; let mut v = Vec::<u8>::new(); let old_capacity = v.capacity(); v.set_contents_from_slice_secure(&sample[0..0]); assert!(v.is_empty()); assert_eq!(v.capacity(), old_capacity); let mut v = Vec::<u8>::new(); let old_capacity = v.capacity(); v.set_contents_from_slice_secure(&sample); assert_eq!(v.as_slice(), &sample); assert!(old_capacity < v.capacity()); let old_capacity = v.capacity(); let sample: [u8; 16] = [0xBA; 16]; v.set_contents_from_slice_secure(&sample); assert_eq!(v.as_slice(), &sample); assert_eq!(v.capacity(), old_capacity); } #[test] fn test_vecextensions_shrink_to_fit_secure() { let sample: [u8; 32] = [0xFA; 32]; let mut v = Vec::<u8>::with_capacity(128); let old_capacity = v.capacity(); v.shrink_to_fit_secure(); assert!(v.capacity() < old_capacity); let mut v = Vec::<u8>::with_capacity(128); let old_capacity = v.capacity(); v.set_contents_from_slice(&sample); v.shrink_to_fit_secure(); assert!(v.capacity() < old_capacity); assert_eq!(v.as_slice(), &sample); } #[test] fn test_vecextensions_reserve_secure() { let sample: [u8; 32] = [0xFA; 32]; let mut v = Vec::<u8>::new(); let old_capacity = v.capacity(); v.reserve_secure(10); assert!(v.capacity() > old_capacity); let mut v = Vec::<u8>::new(); v.set_contents_from_slice(&sample); let old_capacity = v.capacity(); v.reserve_secure(128); assert!(v.capacity() > old_capacity); assert_eq!(v.as_slice(), &sample); } #[test] fn test_vecextensions_extend_from_slice_secure() { let mut v = Vec::<u8>::new(); let mut exp = Vec::<u8>::new(); for i in 0..32 { let sample: [u8; 32] = [i as u8; 32]; v.extend_from_slice_secure(&sample); exp.extend_from_slice(&sample); assert_eq!(v.as_slice(), exp.as_slice()); } }
fn test_vecextensions_set_capacity_to_secure() { let mut v = Vec::<u8>::new(); v.set_capacity_to_secure(10); assert_eq!(v.len(), 0); assert!(v.capacity() >= 10); v.set_capacity_to_secure(100); assert_eq!(v.len(), 0); assert!(v.capacity() >= 100); let sample: [u8; 4] = [1, 2, 3, 4]; let mut v = Vec::<u8>::new(); v.extend_from_slice(&sample); v.set_capacity_to_secure(10); assert_eq!(v.as_slice(), &sample); assert!(v.capacity() >= 10); v.set_capacity_to_secure(100); assert_eq!(v.as_slice(), &sample); assert!(v.capacity() >= 100); }
function_block-full_function
[ { "content": "#[test]\n\nfn test_defaultsharedfilelocknamebuilder_namebuilder_create_lock_file_name() {\n\n let b = DefaultSharedFileLockNameBuilder;\n\n\n\n let name = OsStr::new(\"file\");\n\n assert_eq!(b.create_lock_file_name(name), OsStr::new(\".file.lock~\"));\n\n\n\n let name = OsStr::new(\"z...
Rust
src/lib.rs
arthurhenrique/rusti-cal
5d481a8afb72827f70712caf8f7d88ddad20847a
mod locale; const REFORM_YEAR: u32 = 1099; const MONTHS: usize = 12; const WEEKDAYS: u32 = 7; const COLUMN: usize = 3; const ROWS: usize = 4; const ROW_SIZE: usize = 7; static TOKEN: &str = "\n"; fn is_leap_year(year: u32) -> bool { if year <= REFORM_YEAR { return year % 4 == 0; } (year % 4 == 0) ^ (year % 100 == 0) ^ (year % 400 == 0) } fn days_by_year(mut year: u32) -> u32 { let mut count: u32 = 0; while year > 1 { year -= 1; if is_leap_year(year) { count += 366 } else { count += 365 } } count } fn days_by_month(year: u32) -> Vec<u32> { let mut feb_day: u32 = 28; if is_leap_year(year) { feb_day = 29; } vec![0, 31, feb_day, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] } fn days_by_date( day: u32, month: usize, year: u32, months_memoized: Vec<u32>, year_memoized: u32, ) -> u32 { let mut count = 0; count += day; if month > 1 { count += months_memoized[month - 1] } if year > 1 { count += year_memoized } count } fn get_days_accumulated_by_month(year: u32) -> (Vec<u32>, Vec<u32>) { let mut count = 0; let mut accum = Vec::new(); let days: Vec<u32> = days_by_month(year); (0..MONTHS + 1).for_each(|i| { count += days[i]; accum.push(count); }); (accum, days) } fn first_day_printable(day_year: u32, starting_day: u32) -> String { let mut spaces: String = "".to_string(); let mut printable = format!(""); if (day_year - starting_day) % WEEKDAYS == 0 { printable.push_str(" "); } for i in 2..WEEKDAYS { spaces += &" ".to_string(); if (day_year - starting_day) % WEEKDAYS == i { printable.push_str(spaces.as_str()); break; } } printable } fn remain_day_printable(day: u32, day_year: u32, starting_day: u32) -> String { let base = if ((day_year - starting_day) % WEEKDAYS) == 0 { format!("{:3}{}", day, TOKEN) } else { String::default() }; let complement = (1..WEEKDAYS) .find_map(|i| ((day_year - starting_day) % WEEKDAYS == i).then(|| format!("{:3}", day))) .unwrap_or_default(); format!("{}{}", base, complement) } fn body_printable( year: u32, month: usize, days: u32, months_memoized: Vec<u32>, year_memoized: u32, starting_day: u32, ) -> Vec<String> { let mut result = Vec::<String>::new(); let mut result_days = format!(""); (1..days + 1).for_each(|day| { if day == 1 { let first_day = days_by_date(1, month, year, months_memoized.clone(), year_memoized); result_days.push_str(&first_day_printable(first_day, starting_day)) } let day_year = days_by_date(day, month, year, months_memoized.clone(), year_memoized); result_days.push_str(&remain_day_printable(day, day_year, starting_day)) }); result_days .split(TOKEN) .collect::<Vec<&str>>() .into_iter() .for_each(|i| result.push(i.to_string())); let len = result.len(); if len <= 6 { let spaces = 21 - result[len - 1].len(); if result[len - 1].len() < 20 { for _i in 0..spaces { result[len - 1] += " " } } result.push(" ".to_string()) } result } fn month_printable( year: u32, month: usize, days: u32, months_memoized: Vec<u32>, year_memoized: u32, starting_day: u32, month_names: Vec<String>, week_names: Vec<String>, ) -> Vec<String> { let mut result = Vec::<String>::new(); let body = body_printable( year, month, days, months_memoized, year_memoized, starting_day, ); let month_name = &month_names[month - 1]; result.push(format!(" {:^20}", month_name)); let header = circular_week_name(week_names, starting_day as usize); result.push(header); body.into_iter().for_each(|item| { result.push(item); }); result } fn circular_week_name(week_name: Vec<String>, idx: usize) -> String { let mut s = " ".to_string(); let mut i = idx; while i < ROW_SIZE + idx { if i == (ROW_SIZE - 1) + idx { s.push_str(week_name[i % ROW_SIZE].as_str()); } else { s.push_str(&format!("{} ", week_name[i % ROW_SIZE])); } i += 1 } s.to_string() } pub fn calendar(year: u32, locale_str: &str, starting_day: u32) -> Vec<Vec<Vec<String>>> { let mut rows: Vec<Vec<Vec<String>>> = vec![vec![vec![String::from("")]; COLUMN]; ROWS]; let mut row_counter = 0; let mut column_counter = 0; let (months_memoized, months) = get_days_accumulated_by_month(year); let year_memoized = days_by_year(year); let locale_info = locale::LocaleInfo::new(locale_str); (1..MONTHS + 1).for_each(|month| { rows[row_counter][column_counter] = month_printable( year, month, months[month], months_memoized.clone(), year_memoized, starting_day, locale_info.month_names(), locale_info.week_day_names(), ); column_counter = month % COLUMN; if column_counter == 0 { row_counter += 1; } }); rows } pub fn display(year: u32, locale_str: &str, starting_day: u32) { let rows = calendar(year, locale_str, starting_day); println!(" {:^63}", year); for row in rows { for i in 0..8 { for j in 0..3 { print!("{} ", &row[j][i]); } println!(); } } } #[test] fn test_circular_week_name() { let locale_str = "en_US"; let locale_info = locale::LocaleInfo::new(locale_str); let week_name = locale_info.week_day_names(); assert_eq!(circular_week_name(week_name, 0), " Su Mo Tu We Th Fr Sa"); } #[test] fn test_circular_week_name_pt_br() { let locale_str = "pt_BR"; let locale_info = locale::LocaleInfo::new(locale_str); let week_name = locale_info.week_day_names(); assert_eq!(circular_week_name(week_name, 0), " Do Se Te Qu Qu Se Sá"); }
mod locale; const REFORM_YEAR: u32 = 1099; const MONTHS: usize = 12; const WEEKDAYS: u32 = 7; const COLUMN: usize = 3; const ROWS: usize = 4; const ROW_SIZE: usize = 7; static TOKEN: &str = "\n"; fn is_leap_year(year: u32) -> bool { if year <= REFORM_YEAR { return year % 4 == 0; } (year % 4 == 0) ^ (year % 100 == 0) ^ (year % 400 == 0) } fn days_by_year(mut year: u32) -> u32 { let mut count: u32 = 0; while year > 1 { year -= 1; if is_leap_year(year) { count += 366 } else { count += 365 } } count } fn days_by_month(year: u32) -> Vec<u32> { let mut feb_day: u32 = 28; if is_leap_year(year) { feb_day = 29; } vec![0, 31, feb_day, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] } fn days_by_date( day: u32, month: usize, year: u32, months_memoized: Vec<u32>, year_memoized: u32, ) -> u32 { let mut count = 0; count += day; if month > 1 { count += months_memoized[month - 1] } if year > 1 { count += year_memoized } count } fn get_days_accumulated_by_month(year: u32) -> (Vec<u32>, Vec<u32>) { let mut count = 0; let mut accum = Vec::new(); let days: Vec<u32> = days_by_month(year); (0..MONTHS + 1).for_each(|i| { count += days[i]; accum.push(count); }); (accum, days) } fn first_day_printable(day_year: u32, starting_day: u32) -> String { let mut spaces: String = "".to_string(); let mut printable = format!(""); if (day_year - starting_day) % WEEKDAYS == 0 { printable.push_str(" "); } for i in 2..WEEKDAYS { spaces += &" ".to_string(); if (day_year - starting_day) % WEEKDAYS == i { printable.push_str(spaces.as_str()); break; } } printable } fn remain_day_printable(day: u32, day_year: u32, starting_day: u32) -> String { let base = if ((day_year - starting_day) % WEEKDAYS) == 0 { format!("{:3}{}", day, TOKEN) } else { String::default() }; let complement = (1..WEEKDAYS) .find_map(|i| ((day_year - starting_day) % WEEKDAYS == i).then(|| format!("{:3}", day))) .unwrap_or_default(); format!("{}{}", base, complement) } fn body_printable( year: u32, month: usize, days: u32, months_memoized: Vec<u32>, year_memoized: u32, starting_day: u32, ) -> Vec<String> { let mut result = Vec::<String>::new(); let mut result_days = format!(""); (1..days + 1).for_each(|day| {
let day_year = days_by_date(day, month, year, months_memoized.clone(), year_memoized); result_days.push_str(&remain_day_printable(day, day_year, starting_day)) }); result_days .split(TOKEN) .collect::<Vec<&str>>() .into_iter() .for_each(|i| result.push(i.to_string())); let len = result.len(); if len <= 6 { let spaces = 21 - result[len - 1].len(); if result[len - 1].len() < 20 { for _i in 0..spaces { result[len - 1] += " " } } result.push(" ".to_string()) } result } fn month_printable( year: u32, month: usize, days: u32, months_memoized: Vec<u32>, year_memoized: u32, starting_day: u32, month_names: Vec<String>, week_names: Vec<String>, ) -> Vec<String> { let mut result = Vec::<String>::new(); let body = body_printable( year, month, days, months_memoized, year_memoized, starting_day, ); let month_name = &month_names[month - 1]; result.push(format!(" {:^20}", month_name)); let header = circular_week_name(week_names, starting_day as usize); result.push(header); body.into_iter().for_each(|item| { result.push(item); }); result } fn circular_week_name(week_name: Vec<String>, idx: usize) -> String { let mut s = " ".to_string(); let mut i = idx; while i < ROW_SIZE + idx { if i == (ROW_SIZE - 1) + idx { s.push_str(week_name[i % ROW_SIZE].as_str()); } else { s.push_str(&format!("{} ", week_name[i % ROW_SIZE])); } i += 1 } s.to_string() } pub fn calendar(year: u32, locale_str: &str, starting_day: u32) -> Vec<Vec<Vec<String>>> { let mut rows: Vec<Vec<Vec<String>>> = vec![vec![vec![String::from("")]; COLUMN]; ROWS]; let mut row_counter = 0; let mut column_counter = 0; let (months_memoized, months) = get_days_accumulated_by_month(year); let year_memoized = days_by_year(year); let locale_info = locale::LocaleInfo::new(locale_str); (1..MONTHS + 1).for_each(|month| { rows[row_counter][column_counter] = month_printable( year, month, months[month], months_memoized.clone(), year_memoized, starting_day, locale_info.month_names(), locale_info.week_day_names(), ); column_counter = month % COLUMN; if column_counter == 0 { row_counter += 1; } }); rows } pub fn display(year: u32, locale_str: &str, starting_day: u32) { let rows = calendar(year, locale_str, starting_day); println!(" {:^63}", year); for row in rows { for i in 0..8 { for j in 0..3 { print!("{} ", &row[j][i]); } println!(); } } } #[test] fn test_circular_week_name() { let locale_str = "en_US"; let locale_info = locale::LocaleInfo::new(locale_str); let week_name = locale_info.week_day_names(); assert_eq!(circular_week_name(week_name, 0), " Su Mo Tu We Th Fr Sa"); } #[test] fn test_circular_week_name_pt_br() { let locale_str = "pt_BR"; let locale_info = locale::LocaleInfo::new(locale_str); let week_name = locale_info.week_day_names(); assert_eq!(circular_week_name(week_name, 0), " Do Se Te Qu Qu Se Sá"); }
if day == 1 { let first_day = days_by_date(1, month, year, months_memoized.clone(), year_memoized); result_days.push_str(&first_day_printable(first_day, starting_day)) }
if_condition
[ { "content": "fn to_titlecase(str: &str) -> String {\n\n str.chars()\n\n .enumerate()\n\n .map(|(pos, c)| {\n\n if pos == 0 {\n\n c.to_uppercase().to_string()\n\n } else {\n\n c.to_string()\n\n }\n\n })\n\n .collect()\...
Rust
rust/game/src/schemas.rs
sisso/test-unity3d-rust
883ad1eba80a6fad2b566c170a8597dc2a7600ad
mod packages_generated; mod requests_generated; mod responses_generated; pub use requests_generated::ffi_requests; pub use responses_generated::ffi_responses; use crate::{Error, GameEvent, Request, Result}; use flatbuffers::FlatBufferBuilder; pub type RawMsg = [u8]; pub type RawMsgBuffer = Vec<u8>; pub type PackageKind = u16; pub fn parse_game_requests(kind: PackageKind, requests: &RawMsg) -> Result<Vec<Request>> { if kind != packages_generated::ffi_packages::PackageKind::Request as u16 { eprintln!("receive unknown kind {:?}", kind); return Err(Error::Unknown(format!("Unknown kind {}", kind))); } let root = flatbuffers::get_root::<ffi_requests::Requests>(requests); let total_requests = root.total_messages() as usize; let mut index: Vec<Option<Request>> = Vec::with_capacity(total_requests); for i in 0..total_requests { index.push(None); } for package in root.empty_packages().unwrap_or_default().iter() { match package.kind() { ffi_requests::RequestKind::StartGame => { index[package.ordering() as usize] = Some(Request::StartGame) } ffi_requests::RequestKind::GameStatus => { index[package.ordering() as usize] = Some(Request::GameStatus) } ffi_requests::RequestKind::GetAll => { index[package.ordering() as usize] = Some(Request::GetAll) } other => return Err(Error::Unknown(format!("Invalid kind {:?}", other))), } } let result: Vec<_> = index.into_iter().flatten().collect(); if result.len() != total_requests { Err(format!("invalid result {:?}", result).into()) } else { Ok(result) } } pub fn serialize_game_events( game_responses: Vec<GameEvent>, ) -> Result<(PackageKind, RawMsgBuffer)> { let mut fb = FlatBufferBuilder::new(); macro_rules! create_vector { ($field:expr) => { if $field.is_empty() { None } else { Some(fb.create_vector($field.as_ref())) } }; } let mut total = 0u32; let mut empty_packages = vec![]; let mut create_packages = vec![]; let mut pos_packages = vec![]; let total_game_responses = game_responses.len(); for responses in game_responses { let ordering = total; total += 1; match responses { GameEvent::CreateObj { id, x, y } => { create_packages.push(ffi_responses::CreatePackage::new( ffi_responses::ResponseKind::CreateObj, ordering, id, ffi_responses::PrefabKind::Player, x, y, )); } GameEvent::MoveObj { obj_id, x, y } => { pos_packages.push(ffi_responses::PosPackage::new( ffi_responses::ResponseKind::MoveObj, ordering, obj_id, x, y, )); } GameEvent::GameStarted => empty_packages.push(ffi_responses::EmptyPackage::new( ffi_responses::ResponseKind::GameStarted, ordering, )), GameEvent::GameStatusRunning => empty_packages.push(ffi_responses::EmptyPackage::new( ffi_responses::ResponseKind::GameStatusRunning, ordering, )), GameEvent::GameStatusIdle => empty_packages.push(ffi_responses::EmptyPackage::new( ffi_responses::ResponseKind::GameStatusIdle, ordering, )), GameEvent::FullStateResponse => empty_packages.push(ffi_responses::EmptyPackage::new( ffi_responses::ResponseKind::FullStateResponse, ordering, )), } } if total != total_game_responses as u32 { return Err(format!( "invalid response count {:?}, expected {:?}", total, total_game_responses ) .into()); } let args = ffi_responses::ResponsesArgs { total_messages: total, empty_packages: create_vector!(empty_packages), create_packages: create_vector!(create_packages), pos_packages: create_vector!(pos_packages), string_packages: None, }; let out = ffi_responses::Responses::create(&mut fb, &args); fb.finish_minimal(out); Ok(( packages_generated::ffi_packages::PackageKind::Response as u16, fb.finished_data().to_vec(), )) }
mod packages_generated; mod requests_generated; mod responses_generated; pub use requests_generated::ffi_requests; pub use responses_generated::ffi_responses; use crate::{Error, GameEvent, Request, Result}; use flatbuffers::FlatBufferBuilder; pub type RawMsg = [u8]; pub type RawMsgBuffer = Vec<u8>; pub type PackageKind = u16; pub fn parse_game_requests(kind: PackageKind, requests: &RawMsg) -> Result<Vec<Request>> { if kind != packages_generated::ffi_packages::PackageKind::Request as u16 { eprintln!("receive unknown kind {:?}", kind); return Err(Error::Unknown(format!("Unknown kind {}", kind))); } let root = flatbuffers::get_root::<ffi_requests::Requests>(requests); let total_requests = root.total_messages() as usize; let mut index: Vec<Option<Request>> = Vec::with_capacity(total_requests); for i in 0..total_requests { index.push(None); } for package in root.empty_packages().unwrap_or_default().iter() { match package.kind() { ffi_requests::RequestKind::StartGame => { index[package.ordering() as usize] = Some(Request::StartGame) } ffi_requests::RequestKind::GameStatus => { index[package.ordering() as usize] = Some(Request::GameStatus) } ffi_requests::RequestKind::GetAll => { index[package.ordering() as usize] = Some(Request::GetAll) } other => return Err(Error::Unknown(format!("Invalid kind {:?}", other))), } } let result: Vec<_> = index.into_iter().flatten().collect(); if result.len() != total_requests { Err(format!("invalid result {:?}", result).into()) } else { Ok(result) } } pub fn serialize_game_events( game_responses: Vec<GameEvent>, ) -> Result<(PackageKind, RawMsgBuffer)> { let mut fb = FlatBufferBuilder::new(); macro_rules! create_vector { ($field:expr) => { if $field.is_empty() { None } else { Some(fb.create_vector($field.as_ref())) } }; } let mut total = 0u32; let mut empty_packages = vec![]; let mut create_packages = vec![]; let mut pos_packages = vec![]; let total_game_responses = game_responses.len(); for responses in game_responses { let ordering = total; total += 1; match responses { GameEvent::CreateObj { id, x, y } => { create_packages.push(ffi_responses::CreatePackage::new( ffi_responses::ResponseKind::CreateObj, ordering, id, ffi_responses::PrefabKind::Player, x, y, )); } GameEvent::MoveObj { obj_id, x, y } => { pos_packages.push(ffi_responses::PosPackage::new( ffi_responses::ResponseKind::MoveObj, orderin
g, obj_id, x, y, )); } GameEvent::GameStarted => empty_packages.push(ffi_responses::EmptyPackage::new( ffi_responses::ResponseKind::GameStarted, ordering, )), GameEvent::GameStatusRunning => empty_packages.push(ffi_responses::EmptyPackage::new( ffi_responses::ResponseKind::GameStatusRunning, ordering, )), GameEvent::GameStatusIdle => empty_packages.push(ffi_responses::EmptyPackage::new( ffi_responses::ResponseKind::GameStatusIdle, ordering, )), GameEvent::FullStateResponse => empty_packages.push(ffi_responses::EmptyPackage::new( ffi_responses::ResponseKind::FullStateResponse, ordering, )), } } if total != total_game_responses as u32 { return Err(format!( "invalid response count {:?}, expected {:?}", total, total_game_responses ) .into()); } let args = ffi_responses::ResponsesArgs { total_messages: total, empty_packages: create_vector!(empty_packages), create_packages: create_vector!(create_packages), pos_packages: create_vector!(pos_packages), string_packages: None, }; let out = ffi_responses::Responses::create(&mut fb, &args); fb.finish_minimal(out); Ok(( packages_generated::ffi_packages::PackageKind::Response as u16, fb.finished_data().to_vec(), )) }
function_block-function_prefixed
[ { "content": "pub fn enum_name_package_kind(e: PackageKind) -> &'static str {\n\n let index = e as u16;\n\n ENUM_NAMES_PACKAGE_KIND[index as usize]\n\n}\n\n\n\n} // pub mod FfiPackages\n\n\n", "file_path": "rust/game/src/schemas/packages_generated.rs", "rank": 1, "score": 163941.63861508263 }, ...
Rust
src/handlers/theme.rs
cmarincia/miette
714334098a92c77fb6b962e627defab7e16b540d
use atty::Stream; use owo_colors::Style; /** Theme used by [`GraphicalReportHandler`](crate::GraphicalReportHandler) to render fancy [`Diagnostic`](crate::Diagnostic) reports. A theme consists of two things: the set of characters to be used for drawing, and the [`owo_colors::Style`](https://docs.rs/owo-colors/latest/owo_colors/struct.Style.html)s to be used to paint various items. You can create your own custom graphical theme using this type, or you can use one of the predefined ones using the methods below. */ #[derive(Debug, Clone)] pub struct GraphicalTheme { pub characters: ThemeCharacters, pub styles: ThemeStyles, } impl GraphicalTheme { pub fn ascii() -> Self { Self { characters: ThemeCharacters::ascii(), styles: ThemeStyles::ansi(), } } pub fn unicode() -> Self { Self { characters: ThemeCharacters::unicode(), styles: ThemeStyles::rgb(), } } pub fn unicode_nocolor() -> Self { Self { characters: ThemeCharacters::unicode(), styles: ThemeStyles::none(), } } pub fn none() -> Self { Self { characters: ThemeCharacters::ascii(), styles: ThemeStyles::none(), } } } impl Default for GraphicalTheme { fn default() -> Self { match std::env::var("NO_COLOR") { _ if !atty::is(Stream::Stdout) || !atty::is(Stream::Stderr) => Self::ascii(), Ok(string) if string != "0" => Self::unicode_nocolor(), _ => Self::unicode(), } } } /** Styles for various parts of graphical rendering for the [crate::GraphicalReportHandler]. */ #[derive(Debug, Clone)] pub struct ThemeStyles { pub error: Style, pub warning: Style, pub advice: Style, pub help: Style, pub link: Style, pub linum: Style, pub highlights: Vec<Style>, } fn style() -> Style { Style::new() } impl ThemeStyles { pub fn rgb() -> Self { Self { error: style().fg_rgb::<255, 30, 30>(), warning: style().fg_rgb::<244, 191, 117>(), advice: style().fg_rgb::<106, 159, 181>(), help: style().fg_rgb::<106, 159, 181>(), link: style().fg_rgb::<92, 157, 255>().underline().bold(), linum: style().dimmed(), highlights: vec![ style().fg_rgb::<246, 87, 248>(), style().fg_rgb::<30, 201, 212>(), style().fg_rgb::<145, 246, 111>(), ], } } pub fn ansi() -> Self { Self { error: style().red(), warning: style().yellow(), advice: style().cyan(), help: style().cyan(), link: style().cyan().underline().bold(), linum: style().dimmed(), highlights: vec![ style().red().bold(), style().yellow().bold(), style().cyan().bold(), ], } } pub fn none() -> Self { Self { error: style(), warning: style(), advice: style(), help: style(), link: style(), linum: style(), highlights: vec![style()], } } } #[allow(missing_docs)] #[derive(Debug, Clone, Eq, PartialEq)] pub struct ThemeCharacters { pub hbar: char, pub vbar: char, pub xbar: char, pub vbar_break: char, pub uarrow: char, pub rarrow: char, pub ltop: char, pub mtop: char, pub rtop: char, pub lbot: char, pub rbot: char, pub mbot: char, pub lbox: char, pub rbox: char, pub lcross: char, pub rcross: char, pub underbar: char, pub underline: char, pub error: String, pub warning: String, pub advice: String, } impl ThemeCharacters { pub fn unicode() -> Self { Self { hbar: '─', vbar: '│', xbar: '┼', vbar_break: '·', uarrow: '▲', rarrow: '▶', ltop: '╭', mtop: '┬', rtop: '╮', lbot: '╰', mbot: '┴', rbot: '╯', lbox: '[', rbox: ']', lcross: '├', rcross: '┤', underbar: '┬', underline: '─', error: "×".into(), warning: "⚠".into(), advice: "☞".into(), } } pub fn emoji() -> Self { Self { hbar: '─', vbar: '│', xbar: '┼', vbar_break: '·', uarrow: '▲', rarrow: '▶', ltop: '╭', mtop: '┬', rtop: '╮', lbot: '╰', mbot: '┴', rbot: '╯', lbox: '[', rbox: ']', lcross: '├', rcross: '┤', underbar: '┬', underline: '─', error: "💥".into(), warning: "⚠️".into(), advice: "💡".into(), } } pub fn ascii() -> Self { Self { hbar: '-', vbar: '|', xbar: '+', vbar_break: ':', uarrow: '^', rarrow: '>', ltop: ',', mtop: 'v', rtop: '.', lbot: '`', mbot: '^', rbot: '\'', lbox: '[', rbox: ']', lcross: '|', rcross: '|', underbar: '|', underline: '^', error: "x".into(), warning: "!".into(), advice: ">".into(), } } }
use atty::Stream; use owo_colors::Style; /** Theme used by [`GraphicalReportHandler`](crate::GraphicalReportHandler) to render fancy [`Diagnostic`](crate::Diagnostic) reports. A theme consists of two things: the set of characters to be used for drawing, and the [`owo_colors::Style`](https://docs.rs/owo-colors/latest/owo_colors/struct.Style.html)s to be used to paint various items. You can create your own custom graphical theme using this type, or you can use one of the predefined ones using the methods below. */ #[derive(Debug, Clone)] pub struct GraphicalTheme { pub characters: ThemeCharacters, pub styles: ThemeStyles, } impl GraphicalTheme { pub fn ascii() -> Self { Self { characters: ThemeCharacters::ascii(), styles: ThemeStyles::ansi(), } }
pub fn unicode_nocolor() -> Self { Self { characters: ThemeCharacters::unicode(), styles: ThemeStyles::none(), } } pub fn none() -> Self { Self { characters: ThemeCharacters::ascii(), styles: ThemeStyles::none(), } } } impl Default for GraphicalTheme { fn default() -> Self { match std::env::var("NO_COLOR") { _ if !atty::is(Stream::Stdout) || !atty::is(Stream::Stderr) => Self::ascii(), Ok(string) if string != "0" => Self::unicode_nocolor(), _ => Self::unicode(), } } } /** Styles for various parts of graphical rendering for the [crate::GraphicalReportHandler]. */ #[derive(Debug, Clone)] pub struct ThemeStyles { pub error: Style, pub warning: Style, pub advice: Style, pub help: Style, pub link: Style, pub linum: Style, pub highlights: Vec<Style>, } fn style() -> Style { Style::new() } impl ThemeStyles { pub fn rgb() -> Self { Self { error: style().fg_rgb::<255, 30, 30>(), warning: style().fg_rgb::<244, 191, 117>(), advice: style().fg_rgb::<106, 159, 181>(), help: style().fg_rgb::<106, 159, 181>(), link: style().fg_rgb::<92, 157, 255>().underline().bold(), linum: style().dimmed(), highlights: vec![ style().fg_rgb::<246, 87, 248>(), style().fg_rgb::<30, 201, 212>(), style().fg_rgb::<145, 246, 111>(), ], } } pub fn ansi() -> Self { Self { error: style().red(), warning: style().yellow(), advice: style().cyan(), help: style().cyan(), link: style().cyan().underline().bold(), linum: style().dimmed(), highlights: vec![ style().red().bold(), style().yellow().bold(), style().cyan().bold(), ], } } pub fn none() -> Self { Self { error: style(), warning: style(), advice: style(), help: style(), link: style(), linum: style(), highlights: vec![style()], } } } #[allow(missing_docs)] #[derive(Debug, Clone, Eq, PartialEq)] pub struct ThemeCharacters { pub hbar: char, pub vbar: char, pub xbar: char, pub vbar_break: char, pub uarrow: char, pub rarrow: char, pub ltop: char, pub mtop: char, pub rtop: char, pub lbot: char, pub rbot: char, pub mbot: char, pub lbox: char, pub rbox: char, pub lcross: char, pub rcross: char, pub underbar: char, pub underline: char, pub error: String, pub warning: String, pub advice: String, } impl ThemeCharacters { pub fn unicode() -> Self { Self { hbar: '─', vbar: '│', xbar: '┼', vbar_break: '·', uarrow: '▲', rarrow: '▶', ltop: '╭', mtop: '┬', rtop: '╮', lbot: '╰', mbot: '┴', rbot: '╯', lbox: '[', rbox: ']', lcross: '├', rcross: '┤', underbar: '┬', underline: '─', error: "×".into(), warning: "⚠".into(), advice: "☞".into(), } } pub fn emoji() -> Self { Self { hbar: '─', vbar: '│', xbar: '┼', vbar_break: '·', uarrow: '▲', rarrow: '▶', ltop: '╭', mtop: '┬', rtop: '╮', lbot: '╰', mbot: '┴', rbot: '╯', lbox: '[', rbox: ']', lcross: '├', rcross: '┤', underbar: '┬', underline: '─', error: "💥".into(), warning: "⚠️".into(), advice: "💡".into(), } } pub fn ascii() -> Self { Self { hbar: '-', vbar: '|', xbar: '+', vbar_break: ':', uarrow: '^', rarrow: '>', ltop: ',', mtop: 'v', rtop: '.', lbot: '`', mbot: '^', rbot: '\'', lbox: '[', rbox: ']', lcross: '|', rcross: '|', underbar: '|', underline: '^', error: "x".into(), warning: "!".into(), advice: ">".into(), } } }
pub fn unicode() -> Self { Self { characters: ThemeCharacters::unicode(), styles: ThemeStyles::rgb(), } }
function_block-full_function
[]
Rust
cranelift-codegen/src/topo_order.rs
jgouly/cranelift-1
470372f0b55cd51199466669cb87d9e038a3f459
use crate::dominator_tree::DominatorTree; use crate::entity::EntitySet; use crate::ir::{Block, Layout}; use alloc::vec::Vec; pub struct TopoOrder { preferred: Vec<Block>, next: usize, visited: EntitySet<Block>, stack: Vec<Block>, } impl TopoOrder { pub fn new() -> Self { Self { preferred: Vec::new(), next: 0, visited: EntitySet::new(), stack: Vec::new(), } } pub fn clear(&mut self) { self.preferred.clear(); self.next = 0; self.visited.clear(); self.stack.clear(); } pub fn reset<Blocks>(&mut self, preferred: Blocks) where Blocks: IntoIterator<Item = Block>, { self.preferred.clear(); self.preferred.extend(preferred); self.next = 0; self.visited.clear(); self.stack.clear(); } pub fn next(&mut self, layout: &Layout, domtree: &DominatorTree) -> Option<Block> { self.visited.resize(layout.block_capacity()); while self.stack.is_empty() { match self.preferred.get(self.next).cloned() { None => return None, Some(mut block) => { self.next += 1; while self.visited.insert(block) { self.stack.push(block); match domtree.idom(block) { Some(idom) => { block = layout.inst_block(idom).expect("idom not in layout") } None => break, } } } } } self.stack.pop() } } #[cfg(test)] mod tests { use super::*; use crate::cursor::{Cursor, FuncCursor}; use crate::dominator_tree::DominatorTree; use crate::flowgraph::ControlFlowGraph; use crate::ir::{Function, InstBuilder}; use core::iter; #[test] fn empty() { let func = Function::new(); let cfg = ControlFlowGraph::with_function(&func); let domtree = DominatorTree::with_function(&func, &cfg); let mut topo = TopoOrder::new(); assert_eq!(topo.next(&func.layout, &domtree), None); topo.reset(func.layout.blocks()); assert_eq!(topo.next(&func.layout, &domtree), None); } #[test] fn simple() { let mut func = Function::new(); let block0 = func.dfg.make_block(); let block1 = func.dfg.make_block(); { let mut cur = FuncCursor::new(&mut func); cur.insert_block(block0); cur.ins().jump(block1, &[]); cur.insert_block(block1); cur.ins().jump(block1, &[]); } let cfg = ControlFlowGraph::with_function(&func); let domtree = DominatorTree::with_function(&func, &cfg); let mut topo = TopoOrder::new(); topo.reset(iter::once(block1)); assert_eq!(topo.next(&func.layout, &domtree), Some(block0)); assert_eq!(topo.next(&func.layout, &domtree), Some(block1)); assert_eq!(topo.next(&func.layout, &domtree), None); } }
use crate::dominator_tree::DominatorTree; use crate::entity::EntitySet; use crate::ir::{Block, Layout}; use alloc::vec::Vec; pub struct TopoOrder { preferred: Vec<Block>, next: usize, visited: EntitySet<Block>, stack: Vec<Block>, } impl TopoOrder { pub fn new() -> Self { Self { preferred: Vec::new(), next: 0, visited: EntitySet::new(), stack: Vec::new(), } } pub fn clear(&mut self) { self.preferred.clear(); self.next = 0; self.visited.clear(); self.stack.clear(); } pub fn reset<Blocks>(&mut self, preferred: Blocks) where Blocks: IntoIterator<Item = Block>, { self.preferred.clear(); self.preferred.extend(preferred); self.next = 0; self.visited.clear(); self.stack.clear(); } pub fn next(&mut self, layout: &Layout, domtree: &DominatorTree) -> Option<Block> { self.visited.resize(layout.block_capacity()); while self.stack.is_empty() { match self.preferred.ge
} } } self.stack.pop() } } #[cfg(test)] mod tests { use super::*; use crate::cursor::{Cursor, FuncCursor}; use crate::dominator_tree::DominatorTree; use crate::flowgraph::ControlFlowGraph; use crate::ir::{Function, InstBuilder}; use core::iter; #[test] fn empty() { let func = Function::new(); let cfg = ControlFlowGraph::with_function(&func); let domtree = DominatorTree::with_function(&func, &cfg); let mut topo = TopoOrder::new(); assert_eq!(topo.next(&func.layout, &domtree), None); topo.reset(func.layout.blocks()); assert_eq!(topo.next(&func.layout, &domtree), None); } #[test] fn simple() { let mut func = Function::new(); let block0 = func.dfg.make_block(); let block1 = func.dfg.make_block(); { let mut cur = FuncCursor::new(&mut func); cur.insert_block(block0); cur.ins().jump(block1, &[]); cur.insert_block(block1); cur.ins().jump(block1, &[]); } let cfg = ControlFlowGraph::with_function(&func); let domtree = DominatorTree::with_function(&func, &cfg); let mut topo = TopoOrder::new(); topo.reset(iter::once(block1)); assert_eq!(topo.next(&func.layout, &domtree), Some(block0)); assert_eq!(topo.next(&func.layout, &domtree), Some(block1)); assert_eq!(topo.next(&func.layout, &domtree), None); } }
t(self.next).cloned() { None => return None, Some(mut block) => { self.next += 1; while self.visited.insert(block) { self.stack.push(block); match domtree.idom(block) { Some(idom) => { block = layout.inst_block(idom).expect("idom not in layout") } None => break, } }
function_block-random_span
[ { "content": "/// Compute the stack frame layout.\n\n///\n\n/// Determine the total size of this stack frame and assign offsets to all `Spill` and `Explicit`\n\n/// stack slots.\n\n///\n\n/// The total frame size will be a multiple of `alignment` which must be a power of two, unless the\n\n/// function doesn't ...