file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
root.rs
/* The library provides a simple datastructure to access geolocated labels with an additional elimination time t and a label size factor. The library provides method to query a set of such labels with a bounding box and a minimum elimination time. Copyright (C) {2017} {Filip Krumpe <[email protected]} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ use std::f64; use std::cmp::Ordering; use primitives::label::Label; use primitives::bbox::BBox; /// /// Represent the possible split dimensions. /// #[derive(PartialEq)] enum SplitDimension { X, Y, UNDEF, } /// /// The struct defines a tree node. /// /// The tree nodes members are the labels t value, the label itself, the split type (X, Y or UNDEF /// in case the node is a leaf node). /// /// The split value indicates the maximum value of the left children in the corresponding /// dimension. The split value is guaranteed to be less than the corresponding coordinate of the /// right children. /// /// Left and right child are some indices, if there is a left or right subtree and none otherwise. pub struct Root { m_t: f64, m_data: Label, m_type: SplitDimension, m_split: f64, m_left_child: Option<usize>, m_right_child: Option<usize>, } impl Root { /// /// Construct a new root from the given label /// /// Note: The function only contains the given label. No subtrees of connenctions to other /// tree nodes are constructed. /// /// To construct a single tree from a forest of root nodes use the Root::init_pst3d(...) /// function. /// pub fn new(l: Label) -> Root { Root { m_t: l.get_t(), m_data: l, m_type: SplitDimension::UNDEF, m_split: f64::NAN, m_left_child: None, m_right_child: None, } } /// /// Initialize a single 3D PST out of a forest of root nodes and return the root node index. /// /// The function will mutate the given root nodes and set the corresponding split type, split /// value and left and right subtree indices. /// /// The function returns the index of the root node in the data array. /// pub fn init_pst3d(mut data: &mut Vec<Root>) -> Option<usize> { let mut refs: Vec<RootRef> = Vec::with_capacity(data.len()); data.sort_by(|first, second| if first.m_t < second.m_t { Ordering::Less } else if first.m_t > second.m_t { Ordering::Greater } else { Ordering::Equal }); data.reverse(); for (idx, d) in data.iter().enumerate() { refs.push(RootRef::new(d, idx)); } let initial_dimension = SplitDimension::X; create_root(refs, &mut data, &initial_dimension) } /// /// Get a vector of references to the elements in the 3d PST with t >= min_t and that are /// contained in bbox. /// pub fn get<'a>(&'a self, bbox: &BBox, min_t: f64, data: &'a Vec<Root>) -> Vec<&'a Label> { let mut r: Vec<&Label> = Vec::new(); if self.m_t <= min_t { return r; } if bbox.is_contained(&self.m_data) { r.push(&self.m_data); } // append the left child if it exists and is cut by the bounding box if let Some(idx) = self.m_left_child { let append = match self.m_type { SplitDimension::X => bbox.get_min_x() <= self.m_split, SplitDimension::Y => bbox.get_min_y() <= self.m_split, SplitDimension::UNDEF => false, }; if append { assert!(idx < data.len()); let mut res = data[idx].get(&bbox, min_t, &data); r.append(&mut res); } } // append the right child if it exists and is cut by the bounding box if let Some(idx) = self.m_right_child { let append = match self.m_type { SplitDimension::X => bbox.get_max_x() > self.m_split, SplitDimension::Y => bbox.get_max_y() > self.m_split, SplitDimension::UNDEF => false, }; if append { assert!(idx < data.len()); let mut res = data[idx].get(&bbox, min_t, &data); r.append(&mut res); } } r } /// /// Get a human readable string representation of the tree rooted at self. /// /// A such string will look like: /// /// ```text /// x-node (split: 4.5): Label [#1]: 'T1' at (1, 2) with prio 1,elim-t: 9 and label factor: \ /// 1.5 /// l y-node (split: 4.5): Label [#2]: 'T2' at (2, 3) with prio 1, elim-t: 8 and label \ /// factor: 1.5 /// l x-node (split: NaN): Label [#3]: 'T3' at (3, 4) with prio 1, elim-t: 7 and \ /// label factor: 1.5 /// ``` /// pub fn to_string(&self, level: i32, data: &Vec<Root>) -> String { // prefix is level x p let p = " "; let mut prefix = String::new(); for _ in 0..level { prefix = format!("{}{}", prefix, p); } let mut result = match self.m_type { SplitDimension::X => { format!("{}x-node (split: {}): {}", prefix, self.m_split, self.m_data.to_string()) } SplitDimension::Y => { format!("{}y-node (split: {}): {}", prefix, self.m_split, self.m_data.to_string()) } SplitDimension::UNDEF => { format!("{}leaf-node (split: {}): {}", prefix, self.m_split, self.m_data.to_string()) } }; // append the left subtree if let Some(idx) = self.m_left_child { assert!(idx < data.len()); result = format!("{}\nl{}", result, data[idx].to_string(level + 1, &data)); } // append the right subtree if let Some(idx) = self.m_right_child { assert!(idx < data.len()); result = format!("{}\nr{}", result, data[idx].to_string(level + 1, &data)); } result } } /// /// The struct represents a reference to a root node and contains all the information required to /// construct the 3D PST. /// #[derive(Debug)] struct RootRef { m_x: f64, m_y: f64, m_t: f64, m_idx: usize, } impl RootRef { /// /// Initialize a new root ref /// fn new(r: &Root, idx: usize) -> RootRef { RootRef { m_t: r.m_data.get_t(), m_x: r.m_data.get_x(), m_y: r.m_data.get_y(), m_idx: idx, } } /// /// Compare two Root refs with respect to the t value. /// fn order_by_t(first: &Self, second: &Self) -> Ordering { if first.m_t < second.m_t { Ordering::Less } else if first.m_t > second.m_t { Ordering::Greater } else { Ordering::Equal } } /// /// Compare two Root refs with respect to the x value. /// fn order_by_x(first: &Self, second: &Self) -> Ordering
/// /// Compare two Root refs with respect to the y value. /// fn order_by_y(first: &Self, second: &Self) -> Ordering { if first.m_y < second.m_y { Ordering::Less } else if first.m_y > second.m_y { Ordering::Greater } else { Ordering::Equal } } } /// /// In the RootRef vector find the index of the root with the maximum t value. /// fn find_root_idx(refs: &mut Vec<RootRef>) -> usize { let mut max_t = 0.; let mut max_idx = 0; for (idx, e) in refs.iter().enumerate() { if e.m_t > max_t { max_t = e.m_t; max_idx = idx; } } let r = refs.swap_remove(max_idx); assert!(r.m_t == max_t); r.m_idx } /// /// From the given RootRef vector construct the subtree and update the corresponding root nodes in /// the data vector. /// /// The element with the maximum t value will be set as root with the corresponding split /// dimension. The remaining elements will sorted by the split dimension. The split value is the /// corresponding coordinate of item floor(|root_refs| / 2) and the elements are splitted into <= /// and >. /// /// From the <= elements the left subtree is constructed recursively with swapped split dimension. /// Same for the > elements as the right subtree. /// /// For the nodes in data that are referenced by RootRefs in root_refs the corresponding Roots are /// updated accordingly. /// fn create_root(mut root_refs: Vec<RootRef>, mut data: &mut Vec<Root>, dim: &SplitDimension) -> Option<usize> { if root_refs.is_empty() { return None; } let size1 = root_refs.len(); assert!(*dim!= SplitDimension::UNDEF); let is_x = *dim == SplitDimension::X; // find the element with the maximum t value, remove the corresonding RootRef let root_idx = find_root_idx(&mut root_refs); // the sub dimension flips from X to Y or from Y to X let sub_dim = if is_x { SplitDimension::Y } else { SplitDimension::X }; let mut split_value = f64::NAN; let mut left_child_idx: Option<usize> = None; let mut right_child_idx: Option<usize> = None; let order_asc = if is_x { RootRef::order_by_x } else { RootRef::order_by_y }; if root_refs.len() == 1 { split_value = if is_x { root_refs[0].m_x } else { root_refs[0].m_y }; left_child_idx = create_root(root_refs, &mut data, &sub_dim); } else if root_refs.len() > 1 { root_refs.sort_by(order_asc); // take the x value of the median element as the new split value let mut median_idx = root_refs.len() / 2 - 1; split_value = if is_x { root_refs[median_idx].m_x } else { root_refs[median_idx].m_y }; // ensure that the right children realy have a value > m_split if is_x { while median_idx < root_refs.len() && root_refs[median_idx].m_x == split_value { median_idx = median_idx + 1; } } else { while median_idx < root_refs.len() && root_refs[median_idx].m_y == split_value { median_idx = median_idx + 1; } } let size2 = root_refs.len(); assert!(size1 == size2 + 1); // split the data at the median point: let last = root_refs.split_off(median_idx); assert!(size2 == root_refs.len() + last.len()); left_child_idx = create_root(root_refs, &mut data, &sub_dim); right_child_idx = create_root(last, &mut data, &sub_dim); } let r = data.get_mut(root_idx) .expect("Trying to access element at not existing vector position"); r.m_type = if is_x { SplitDimension::X } else { SplitDimension::Y }; r.m_split = split_value; r.m_left_child = left_child_idx; r.m_right_child = right_child_idx; Some(root_idx) } #[test] fn test_root_new() { let r = Root::new(Label::new(1., 2., 9., 1, 1, 1.5, "A".to_string())); assert!(r.m_t == 9.); assert!(*r.m_data.get_label() == "A".to_string()); assert!(r.m_type == SplitDimension::UNDEF); } #[test] fn test_pst_init() { let mut f: Vec<Root> = Vec::new(); f.push(Root::new(Label::new(1., 2., 9., 1, 1, 1.5, "A".to_string()))); f.push(Root::new(Label::new(2., 3., 8., 2, 1, 1.5, "B".to_string()))); f.push(Root::new(Label::new(3., 4., 7., 3, 1, 1.5, "C".to_string()))); let root = Root::init_pst3d(&mut f); let root_idx = root.unwrap(); println!("{}", f[root_idx].to_string(0, &f)); assert!(root_idx == 0); assert!(f[root_idx].m_type == SplitDimension::X); assert!(f[root_idx].m_left_child.is_some()); assert!(f[root_idx].m_right_child.is_some()); assert!(f[root_idx].m_left_child.unwrap() == 1); assert!(f[root_idx].m_right_child.unwrap() == 2); }
{ if first.m_x < second.m_x { Ordering::Less } else if first.m_x > second.m_x { Ordering::Greater } else { Ordering::Equal } }
identifier_body
uninhabited_enum_branching.rs
//! A pass that eliminates branches on uninhabited enum variants. use crate::MirPass; use rustc_data_structures::stable_set::FxHashSet; use rustc_middle::mir::{ BasicBlock, BasicBlockData, Body, Local, Operand, Rvalue, StatementKind, SwitchTargets, TerminatorKind, }; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{Ty, TyCtxt}; use rustc_target::abi::{Abi, Variants}; pub struct UninhabitedEnumBranching; fn get_discriminant_local(terminator: &TerminatorKind<'_>) -> Option<Local> { if let TerminatorKind::SwitchInt { discr: Operand::Move(p),.. } = terminator { p.as_local() } else { None } } /// If the basic block terminates by switching on a discriminant, this returns the `Ty` the /// discriminant is read from. Otherwise, returns None. fn get_switched_on_type<'tcx>( block_data: &BasicBlockData<'tcx>, tcx: TyCtxt<'tcx>, body: &Body<'tcx>, ) -> Option<Ty<'tcx>>
} fn variant_discriminants<'tcx>( layout: &TyAndLayout<'tcx>, ty: Ty<'tcx>, tcx: TyCtxt<'tcx>, ) -> FxHashSet<u128> { match &layout.variants { Variants::Single { index } => { let mut res = FxHashSet::default(); res.insert(index.as_u32() as u128); res } Variants::Multiple { variants,.. } => variants .iter_enumerated() .filter_map(|(idx, layout)| { (layout.abi!= Abi::Uninhabited) .then(|| ty.discriminant_for_variant(tcx, idx).unwrap().val) }) .collect(), } } impl<'tcx> MirPass<'tcx> for UninhabitedEnumBranching { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { if body.source.promoted.is_some() { return; } trace!("UninhabitedEnumBranching starting for {:?}", body.source); let basic_block_count = body.basic_blocks().len(); for bb in 0..basic_block_count { let bb = BasicBlock::from_usize(bb); trace!("processing block {:?}", bb); let Some(discriminant_ty) = get_switched_on_type(&body.basic_blocks()[bb], tcx, body) else { continue; }; let layout = tcx.layout_of(tcx.param_env(body.source.def_id()).and(discriminant_ty)); let allowed_variants = if let Ok(layout) = layout { variant_discriminants(&layout, discriminant_ty, tcx) } else { continue; }; trace!("allowed_variants = {:?}", allowed_variants); if let TerminatorKind::SwitchInt { targets,.. } = &mut body.basic_blocks_mut()[bb].terminator_mut().kind { let new_targets = SwitchTargets::new( targets.iter().filter(|(val, _)| allowed_variants.contains(val)), targets.otherwise(), ); *targets = new_targets; } else { unreachable!() } } } }
{ let terminator = block_data.terminator(); // Only bother checking blocks which terminate by switching on a local. if let Some(local) = get_discriminant_local(&terminator.kind) { let stmt_before_term = (!block_data.statements.is_empty()) .then(|| &block_data.statements[block_data.statements.len() - 1].kind); if let Some(StatementKind::Assign(box (l, Rvalue::Discriminant(place)))) = stmt_before_term { if l.as_local() == Some(local) { let ty = place.ty(body, tcx).ty; if ty.is_enum() { return Some(ty); } } } } None
identifier_body
uninhabited_enum_branching.rs
//! A pass that eliminates branches on uninhabited enum variants. use crate::MirPass; use rustc_data_structures::stable_set::FxHashSet; use rustc_middle::mir::{ BasicBlock, BasicBlockData, Body, Local, Operand, Rvalue, StatementKind, SwitchTargets, TerminatorKind, }; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{Ty, TyCtxt}; use rustc_target::abi::{Abi, Variants}; pub struct UninhabitedEnumBranching; fn get_discriminant_local(terminator: &TerminatorKind<'_>) -> Option<Local> { if let TerminatorKind::SwitchInt { discr: Operand::Move(p),.. } = terminator { p.as_local() } else {
/// If the basic block terminates by switching on a discriminant, this returns the `Ty` the /// discriminant is read from. Otherwise, returns None. fn get_switched_on_type<'tcx>( block_data: &BasicBlockData<'tcx>, tcx: TyCtxt<'tcx>, body: &Body<'tcx>, ) -> Option<Ty<'tcx>> { let terminator = block_data.terminator(); // Only bother checking blocks which terminate by switching on a local. if let Some(local) = get_discriminant_local(&terminator.kind) { let stmt_before_term = (!block_data.statements.is_empty()) .then(|| &block_data.statements[block_data.statements.len() - 1].kind); if let Some(StatementKind::Assign(box (l, Rvalue::Discriminant(place)))) = stmt_before_term { if l.as_local() == Some(local) { let ty = place.ty(body, tcx).ty; if ty.is_enum() { return Some(ty); } } } } None } fn variant_discriminants<'tcx>( layout: &TyAndLayout<'tcx>, ty: Ty<'tcx>, tcx: TyCtxt<'tcx>, ) -> FxHashSet<u128> { match &layout.variants { Variants::Single { index } => { let mut res = FxHashSet::default(); res.insert(index.as_u32() as u128); res } Variants::Multiple { variants,.. } => variants .iter_enumerated() .filter_map(|(idx, layout)| { (layout.abi!= Abi::Uninhabited) .then(|| ty.discriminant_for_variant(tcx, idx).unwrap().val) }) .collect(), } } impl<'tcx> MirPass<'tcx> for UninhabitedEnumBranching { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { if body.source.promoted.is_some() { return; } trace!("UninhabitedEnumBranching starting for {:?}", body.source); let basic_block_count = body.basic_blocks().len(); for bb in 0..basic_block_count { let bb = BasicBlock::from_usize(bb); trace!("processing block {:?}", bb); let Some(discriminant_ty) = get_switched_on_type(&body.basic_blocks()[bb], tcx, body) else { continue; }; let layout = tcx.layout_of(tcx.param_env(body.source.def_id()).and(discriminant_ty)); let allowed_variants = if let Ok(layout) = layout { variant_discriminants(&layout, discriminant_ty, tcx) } else { continue; }; trace!("allowed_variants = {:?}", allowed_variants); if let TerminatorKind::SwitchInt { targets,.. } = &mut body.basic_blocks_mut()[bb].terminator_mut().kind { let new_targets = SwitchTargets::new( targets.iter().filter(|(val, _)| allowed_variants.contains(val)), targets.otherwise(), ); *targets = new_targets; } else { unreachable!() } } } }
None } }
random_line_split
uninhabited_enum_branching.rs
//! A pass that eliminates branches on uninhabited enum variants. use crate::MirPass; use rustc_data_structures::stable_set::FxHashSet; use rustc_middle::mir::{ BasicBlock, BasicBlockData, Body, Local, Operand, Rvalue, StatementKind, SwitchTargets, TerminatorKind, }; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{Ty, TyCtxt}; use rustc_target::abi::{Abi, Variants}; pub struct UninhabitedEnumBranching; fn get_discriminant_local(terminator: &TerminatorKind<'_>) -> Option<Local> { if let TerminatorKind::SwitchInt { discr: Operand::Move(p),.. } = terminator { p.as_local() } else { None } } /// If the basic block terminates by switching on a discriminant, this returns the `Ty` the /// discriminant is read from. Otherwise, returns None. fn get_switched_on_type<'tcx>( block_data: &BasicBlockData<'tcx>, tcx: TyCtxt<'tcx>, body: &Body<'tcx>, ) -> Option<Ty<'tcx>> { let terminator = block_data.terminator(); // Only bother checking blocks which terminate by switching on a local. if let Some(local) = get_discriminant_local(&terminator.kind) { let stmt_before_term = (!block_data.statements.is_empty()) .then(|| &block_data.statements[block_data.statements.len() - 1].kind); if let Some(StatementKind::Assign(box (l, Rvalue::Discriminant(place)))) = stmt_before_term { if l.as_local() == Some(local) { let ty = place.ty(body, tcx).ty; if ty.is_enum() { return Some(ty); } } } } None } fn variant_discriminants<'tcx>( layout: &TyAndLayout<'tcx>, ty: Ty<'tcx>, tcx: TyCtxt<'tcx>, ) -> FxHashSet<u128> { match &layout.variants { Variants::Single { index } =>
Variants::Multiple { variants,.. } => variants .iter_enumerated() .filter_map(|(idx, layout)| { (layout.abi!= Abi::Uninhabited) .then(|| ty.discriminant_for_variant(tcx, idx).unwrap().val) }) .collect(), } } impl<'tcx> MirPass<'tcx> for UninhabitedEnumBranching { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { if body.source.promoted.is_some() { return; } trace!("UninhabitedEnumBranching starting for {:?}", body.source); let basic_block_count = body.basic_blocks().len(); for bb in 0..basic_block_count { let bb = BasicBlock::from_usize(bb); trace!("processing block {:?}", bb); let Some(discriminant_ty) = get_switched_on_type(&body.basic_blocks()[bb], tcx, body) else { continue; }; let layout = tcx.layout_of(tcx.param_env(body.source.def_id()).and(discriminant_ty)); let allowed_variants = if let Ok(layout) = layout { variant_discriminants(&layout, discriminant_ty, tcx) } else { continue; }; trace!("allowed_variants = {:?}", allowed_variants); if let TerminatorKind::SwitchInt { targets,.. } = &mut body.basic_blocks_mut()[bb].terminator_mut().kind { let new_targets = SwitchTargets::new( targets.iter().filter(|(val, _)| allowed_variants.contains(val)), targets.otherwise(), ); *targets = new_targets; } else { unreachable!() } } } }
{ let mut res = FxHashSet::default(); res.insert(index.as_u32() as u128); res }
conditional_block
uninhabited_enum_branching.rs
//! A pass that eliminates branches on uninhabited enum variants. use crate::MirPass; use rustc_data_structures::stable_set::FxHashSet; use rustc_middle::mir::{ BasicBlock, BasicBlockData, Body, Local, Operand, Rvalue, StatementKind, SwitchTargets, TerminatorKind, }; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{Ty, TyCtxt}; use rustc_target::abi::{Abi, Variants}; pub struct UninhabitedEnumBranching; fn get_discriminant_local(terminator: &TerminatorKind<'_>) -> Option<Local> { if let TerminatorKind::SwitchInt { discr: Operand::Move(p),.. } = terminator { p.as_local() } else { None } } /// If the basic block terminates by switching on a discriminant, this returns the `Ty` the /// discriminant is read from. Otherwise, returns None. fn get_switched_on_type<'tcx>( block_data: &BasicBlockData<'tcx>, tcx: TyCtxt<'tcx>, body: &Body<'tcx>, ) -> Option<Ty<'tcx>> { let terminator = block_data.terminator(); // Only bother checking blocks which terminate by switching on a local. if let Some(local) = get_discriminant_local(&terminator.kind) { let stmt_before_term = (!block_data.statements.is_empty()) .then(|| &block_data.statements[block_data.statements.len() - 1].kind); if let Some(StatementKind::Assign(box (l, Rvalue::Discriminant(place)))) = stmt_before_term { if l.as_local() == Some(local) { let ty = place.ty(body, tcx).ty; if ty.is_enum() { return Some(ty); } } } } None } fn
<'tcx>( layout: &TyAndLayout<'tcx>, ty: Ty<'tcx>, tcx: TyCtxt<'tcx>, ) -> FxHashSet<u128> { match &layout.variants { Variants::Single { index } => { let mut res = FxHashSet::default(); res.insert(index.as_u32() as u128); res } Variants::Multiple { variants,.. } => variants .iter_enumerated() .filter_map(|(idx, layout)| { (layout.abi!= Abi::Uninhabited) .then(|| ty.discriminant_for_variant(tcx, idx).unwrap().val) }) .collect(), } } impl<'tcx> MirPass<'tcx> for UninhabitedEnumBranching { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { if body.source.promoted.is_some() { return; } trace!("UninhabitedEnumBranching starting for {:?}", body.source); let basic_block_count = body.basic_blocks().len(); for bb in 0..basic_block_count { let bb = BasicBlock::from_usize(bb); trace!("processing block {:?}", bb); let Some(discriminant_ty) = get_switched_on_type(&body.basic_blocks()[bb], tcx, body) else { continue; }; let layout = tcx.layout_of(tcx.param_env(body.source.def_id()).and(discriminant_ty)); let allowed_variants = if let Ok(layout) = layout { variant_discriminants(&layout, discriminant_ty, tcx) } else { continue; }; trace!("allowed_variants = {:?}", allowed_variants); if let TerminatorKind::SwitchInt { targets,.. } = &mut body.basic_blocks_mut()[bb].terminator_mut().kind { let new_targets = SwitchTargets::new( targets.iter().filter(|(val, _)| allowed_variants.contains(val)), targets.otherwise(), ); *targets = new_targets; } else { unreachable!() } } } }
variant_discriminants
identifier_name
practicalengine.rs
#![allow(unstable)] extern crate time; extern crate water; use water::Net; use water::Endpoint; use water::Message; use water::ID; use water::Duration; use time::Timespec; use std::thread::JoinGuard; use std::thread::Thread; use std::vec::Vec; use std::collections::HashMap; use std::sync::Arc; use std::sync::Mutex; /* This tests and demonstrates: * segmented networks * selecting on multiple endpoints * splitting work onto multiple * dynamically * using sync messages We accept a `Request` packet which is accepted by one manager. We can have one or more managers and do not need to implement logic to select between them. The first avalible one will receive the message and only one. It will then produce work depending on the number of threads. If a thread becomes stuck it will cause the request/job to become stuck but some redundancy is provided using sync messages in that the other threads could continue to function. As each thread/worker finishes the result is sent back to the manager who has been tracking the jobs. When all results arrived a final packet is completed and this is sent to the requestor. The important parts are the potential scalability and the simplicity of implementation. We did not have to implement logic to handle multiple channels, ensure only one worker or manager received a packet, or serialize any of our data. */ struct Request { id: u64, data: Vec<u8>, } struct Work { id: u64, data: Arc<Vec<u8>>, offset: usize, length: usize, tail: u64, } struct WorkReply { id: u64, data: Vec<u8>, offset: usize, length: usize, } struct WorkPending { id: u64, epid: ID, epsid: ID, need: usize, totalsize: usize, work: Vec<WorkReply>, } struct Reply { id: u64, data: Vec<u8>, } struct Terminate; impl Clone for Terminate { fn clone(&self) -> Terminate { Terminate } } const WORKERGRPID: ID = 0x3000; const MANAGEREID: ID = 0x1000; /// Accepts work packets. Processes the packet. Sends back reply. fn thread_pipelineworker(ep: Endpoint) { loop { println!("[worker] waiting for messages"); let result = ep.recvorblockforever(); if result.is_err() { return; } let msg = result.unwrap(); if msg.is_type::<Terminate>() { return; } // Figure out the type of message. if msg.is_type::<Work>() { let work: Work = msg.get_sync().get_payload(); println!("[worker] working on id {:x} and tail {:x} with data of length {:x}/{:x}", work.id, work.tail, work.length, work.data.len()); // Do the work. let mut out: Vec<u8> = Vec::with_capacity(work.length); for i in range(0us, work.length) { out.push(((work.data[i + work.offset] * 2) >> 1 + 5) * 2); } let mut wreply = Message::new_sync(WorkReply { id: work.id, data: out, offset: work.offset, length: work.length, }); wreply.dsteid = MANAGEREID; wreply.dstsid = 1; // The `srceid` and `srcsid` will be filled in automatically. ep.send(wreply); } } } /// Accepts requests. Splits the data. Sends it out to processors. It also /// forwards the data for the second processing pass to the processors. /// fn
(mep: Endpoint, corecnt: usize) { let mut endpoints: Vec<Endpoint> = Vec::new(); let mut workerthreads: Vec<JoinGuard<()>> = Vec::new(); let mut pending: HashMap<u64, WorkPending> = HashMap::new(); // Create net for this pipeline. let net = Net::new(400); let ep = net.new_endpoint_withid(MANAGEREID); endpoints.push(mep.clone()); endpoints.push(ep.clone()); println!("[man] creating worker threads"); // Spawn worker threads for the number of specified cores. for _ in range(0us, corecnt) { let wep = net.new_endpoint(); wep.setgid(WORKERGRPID); workerthreads.push(Thread::scoped(move || thread_pipelineworker(wep))); } // Create processor threads for this pipeline. loop { // Check for requests and results from data processors. println!("[man] waiting for messages"); let result = water::recvorblock(&endpoints, Duration::seconds(10)); if result.is_err() { continue; } let msg = result.unwrap(); if msg.is_type::<Terminate>() { // Tell all workers to terminate. ep.sendclonetype(Terminate); return; } // Figure out the type of message. if msg.is_type::<Request>() { println!("[man] got request"); let msg_srcsid = msg.srcsid; let msg_srceid = msg.srceid; let request: Request = msg.get_sync().get_payload(); // Break into DataChunk(s) and hand out to the processor threads. let data = request.data.clone(); let chklen = data.len() / corecnt; let slack = data.len() % corecnt; let datalen = data.len(); let adata = Arc::new(data); pending.insert(request.id, WorkPending { epsid: msg_srcsid, epid: msg_srceid, id: request.id, need: corecnt, work: Vec::new(), totalsize: datalen, }); for chkndx in range(0us, (corecnt - 1) as usize) { let work = Work { id: request.id, data: adata.clone(), offset: chkndx * chklen, length: chklen, tail: 0x1234, }; println!("[man] sent work packet of length {:x}", work.data.len()); // Only the first worker to receive this gets it. This is // because we are sending it as sync instead of clone. ep.sendsynctype(work); } // Throw slack onto last chunk. let work = Work { id: request.id, data: adata, offset: (corecnt - 1) * chklen, length: chklen + slack, tail: 0x1234, }; println!("[man] sent slack work packet {:x}", work.data.len()); // Only the first worker to receive this gets it. This is // because we are sending it as sync instead of clone. ep.sendsynctype(work); continue; } if msg.is_type::<WorkReply>() { // Combine all results. let reply: WorkReply = msg.get_sync().get_payload(); println!("[man] got work reply with id:{:x}", reply.id); let result = pending.get_mut(&reply.id); if result.is_some() { println!("[man] looking at work reply"); let pending = result.unwrap(); // Place into pending. pending.work.push(reply); // Are we done? if pending.work.len() >= pending.need { println!("[man] processing all work replies for job"); // Combine output and send to original requestor. let mut f: Vec<u8> = Vec::with_capacity(pending.totalsize); // Only *safe* way to initialize at the moment. for i in range(0us, pending.totalsize) { f.push(0u8); } for reply in pending.work.iter() { let mut i = 0us; for value in reply.data.iter() { f[reply.offset + i] = *value; i += 1; } } // let reply = Reply { id: pending.id, data: f, }; println!("[man] sending work finished message"); let mut msg = Message::new_sync(reply); msg.dsteid = pending.epid; msg.dstsid = pending.epsid; mep.send(msg); } } } } } /// Perform a benchmark/test run. fn go(reqcnt: usize, mancnt: usize, coreperman: usize, datcnt: usize) { let net = Net::new(100); let mut threads: Vec<JoinGuard<()>> = Vec::new(); for manid in range(0us, mancnt) { let manep = net.new_endpoint_withid((1000 + manid) as ID); let t = Thread::scoped(move || thread_pipelinemanager(manep, coreperman)); threads.push(t); } while net.getepcount() < mancnt { Thread::yield_now(); } let ep = net.new_endpoint(); for _ in range(0us, reqcnt) { let mut data: Vec<u8> = Vec::new(); for _ in range(0us, datcnt) { data.push(1u8); } ep.sendsynctype(Request { id: 0x100u64, data: data, }); } for _ in range(0us, reqcnt) { let msg = ep.recvorblockforever().unwrap(); println!("[main] got result"); } println!("[main] telling manager to terminate"); ep.sendclonetype(Terminate); } #[test] fn practicalengine() { // Create a thread so we can debug using stdout under `cargo test`. std::thread::Thread::scoped(move || { go(10, 2, 2, 1024); }); }
thread_pipelinemanager
identifier_name
practicalengine.rs
#![allow(unstable)] extern crate time; extern crate water; use water::Net; use water::Endpoint; use water::Message; use water::ID; use water::Duration; use time::Timespec; use std::thread::JoinGuard; use std::thread::Thread; use std::vec::Vec; use std::collections::HashMap; use std::sync::Arc; use std::sync::Mutex; /* This tests and demonstrates: * segmented networks * selecting on multiple endpoints * splitting work onto multiple * dynamically * using sync messages We accept a `Request` packet which is accepted by one manager. We can have one or more managers and do not need to implement logic to select between them. The first avalible one will receive the message and only one. It will then produce work depending on the number of threads. If a thread becomes stuck it will cause the request/job to become stuck but some redundancy is provided using sync messages in that the other threads could continue to function. As each thread/worker finishes the result is sent back to the manager who has been tracking the jobs. When all results arrived a final packet is completed and this is sent to the requestor. The important parts are the potential scalability and the simplicity of implementation. We did not have to implement logic to handle multiple channels, ensure only one worker or manager received a packet, or serialize any of our data. */ struct Request { id: u64, data: Vec<u8>, } struct Work { id: u64, data: Arc<Vec<u8>>, offset: usize, length: usize, tail: u64, } struct WorkReply { id: u64, data: Vec<u8>, offset: usize, length: usize, } struct WorkPending { id: u64, epid: ID, epsid: ID, need: usize, totalsize: usize, work: Vec<WorkReply>, } struct Reply { id: u64, data: Vec<u8>, } struct Terminate; impl Clone for Terminate { fn clone(&self) -> Terminate { Terminate } } const WORKERGRPID: ID = 0x3000; const MANAGEREID: ID = 0x1000; /// Accepts work packets. Processes the packet. Sends back reply. fn thread_pipelineworker(ep: Endpoint) { loop { println!("[worker] waiting for messages"); let result = ep.recvorblockforever(); if result.is_err() { return; } let msg = result.unwrap(); if msg.is_type::<Terminate>() { return; } // Figure out the type of message. if msg.is_type::<Work>() { let work: Work = msg.get_sync().get_payload(); println!("[worker] working on id {:x} and tail {:x} with data of length {:x}/{:x}", work.id, work.tail, work.length, work.data.len()); // Do the work. let mut out: Vec<u8> = Vec::with_capacity(work.length); for i in range(0us, work.length) { out.push(((work.data[i + work.offset] * 2) >> 1 + 5) * 2); } let mut wreply = Message::new_sync(WorkReply { id: work.id, data: out, offset: work.offset, length: work.length, }); wreply.dsteid = MANAGEREID; wreply.dstsid = 1; // The `srceid` and `srcsid` will be filled in automatically. ep.send(wreply); } } } /// Accepts requests. Splits the data. Sends it out to processors. It also /// forwards the data for the second processing pass to the processors. /// fn thread_pipelinemanager(mep: Endpoint, corecnt: usize) { let mut endpoints: Vec<Endpoint> = Vec::new(); let mut workerthreads: Vec<JoinGuard<()>> = Vec::new(); let mut pending: HashMap<u64, WorkPending> = HashMap::new(); // Create net for this pipeline. let net = Net::new(400); let ep = net.new_endpoint_withid(MANAGEREID); endpoints.push(mep.clone()); endpoints.push(ep.clone()); println!("[man] creating worker threads"); // Spawn worker threads for the number of specified cores. for _ in range(0us, corecnt) { let wep = net.new_endpoint(); wep.setgid(WORKERGRPID); workerthreads.push(Thread::scoped(move || thread_pipelineworker(wep))); } // Create processor threads for this pipeline. loop { // Check for requests and results from data processors. println!("[man] waiting for messages"); let result = water::recvorblock(&endpoints, Duration::seconds(10)); if result.is_err() { continue; } let msg = result.unwrap(); if msg.is_type::<Terminate>() { // Tell all workers to terminate. ep.sendclonetype(Terminate); return; } // Figure out the type of message. if msg.is_type::<Request>() { println!("[man] got request"); let msg_srcsid = msg.srcsid; let msg_srceid = msg.srceid; let request: Request = msg.get_sync().get_payload(); // Break into DataChunk(s) and hand out to the processor threads. let data = request.data.clone(); let chklen = data.len() / corecnt; let slack = data.len() % corecnt; let datalen = data.len(); let adata = Arc::new(data); pending.insert(request.id, WorkPending {
epid: msg_srceid, id: request.id, need: corecnt, work: Vec::new(), totalsize: datalen, }); for chkndx in range(0us, (corecnt - 1) as usize) { let work = Work { id: request.id, data: adata.clone(), offset: chkndx * chklen, length: chklen, tail: 0x1234, }; println!("[man] sent work packet of length {:x}", work.data.len()); // Only the first worker to receive this gets it. This is // because we are sending it as sync instead of clone. ep.sendsynctype(work); } // Throw slack onto last chunk. let work = Work { id: request.id, data: adata, offset: (corecnt - 1) * chklen, length: chklen + slack, tail: 0x1234, }; println!("[man] sent slack work packet {:x}", work.data.len()); // Only the first worker to receive this gets it. This is // because we are sending it as sync instead of clone. ep.sendsynctype(work); continue; } if msg.is_type::<WorkReply>() { // Combine all results. let reply: WorkReply = msg.get_sync().get_payload(); println!("[man] got work reply with id:{:x}", reply.id); let result = pending.get_mut(&reply.id); if result.is_some() { println!("[man] looking at work reply"); let pending = result.unwrap(); // Place into pending. pending.work.push(reply); // Are we done? if pending.work.len() >= pending.need { println!("[man] processing all work replies for job"); // Combine output and send to original requestor. let mut f: Vec<u8> = Vec::with_capacity(pending.totalsize); // Only *safe* way to initialize at the moment. for i in range(0us, pending.totalsize) { f.push(0u8); } for reply in pending.work.iter() { let mut i = 0us; for value in reply.data.iter() { f[reply.offset + i] = *value; i += 1; } } // let reply = Reply { id: pending.id, data: f, }; println!("[man] sending work finished message"); let mut msg = Message::new_sync(reply); msg.dsteid = pending.epid; msg.dstsid = pending.epsid; mep.send(msg); } } } } } /// Perform a benchmark/test run. fn go(reqcnt: usize, mancnt: usize, coreperman: usize, datcnt: usize) { let net = Net::new(100); let mut threads: Vec<JoinGuard<()>> = Vec::new(); for manid in range(0us, mancnt) { let manep = net.new_endpoint_withid((1000 + manid) as ID); let t = Thread::scoped(move || thread_pipelinemanager(manep, coreperman)); threads.push(t); } while net.getepcount() < mancnt { Thread::yield_now(); } let ep = net.new_endpoint(); for _ in range(0us, reqcnt) { let mut data: Vec<u8> = Vec::new(); for _ in range(0us, datcnt) { data.push(1u8); } ep.sendsynctype(Request { id: 0x100u64, data: data, }); } for _ in range(0us, reqcnt) { let msg = ep.recvorblockforever().unwrap(); println!("[main] got result"); } println!("[main] telling manager to terminate"); ep.sendclonetype(Terminate); } #[test] fn practicalengine() { // Create a thread so we can debug using stdout under `cargo test`. std::thread::Thread::scoped(move || { go(10, 2, 2, 1024); }); }
epsid: msg_srcsid,
random_line_split
practicalengine.rs
#![allow(unstable)] extern crate time; extern crate water; use water::Net; use water::Endpoint; use water::Message; use water::ID; use water::Duration; use time::Timespec; use std::thread::JoinGuard; use std::thread::Thread; use std::vec::Vec; use std::collections::HashMap; use std::sync::Arc; use std::sync::Mutex; /* This tests and demonstrates: * segmented networks * selecting on multiple endpoints * splitting work onto multiple * dynamically * using sync messages We accept a `Request` packet which is accepted by one manager. We can have one or more managers and do not need to implement logic to select between them. The first avalible one will receive the message and only one. It will then produce work depending on the number of threads. If a thread becomes stuck it will cause the request/job to become stuck but some redundancy is provided using sync messages in that the other threads could continue to function. As each thread/worker finishes the result is sent back to the manager who has been tracking the jobs. When all results arrived a final packet is completed and this is sent to the requestor. The important parts are the potential scalability and the simplicity of implementation. We did not have to implement logic to handle multiple channels, ensure only one worker or manager received a packet, or serialize any of our data. */ struct Request { id: u64, data: Vec<u8>, } struct Work { id: u64, data: Arc<Vec<u8>>, offset: usize, length: usize, tail: u64, } struct WorkReply { id: u64, data: Vec<u8>, offset: usize, length: usize, } struct WorkPending { id: u64, epid: ID, epsid: ID, need: usize, totalsize: usize, work: Vec<WorkReply>, } struct Reply { id: u64, data: Vec<u8>, } struct Terminate; impl Clone for Terminate { fn clone(&self) -> Terminate { Terminate } } const WORKERGRPID: ID = 0x3000; const MANAGEREID: ID = 0x1000; /// Accepts work packets. Processes the packet. Sends back reply. fn thread_pipelineworker(ep: Endpoint) { loop { println!("[worker] waiting for messages"); let result = ep.recvorblockforever(); if result.is_err()
let msg = result.unwrap(); if msg.is_type::<Terminate>() { return; } // Figure out the type of message. if msg.is_type::<Work>() { let work: Work = msg.get_sync().get_payload(); println!("[worker] working on id {:x} and tail {:x} with data of length {:x}/{:x}", work.id, work.tail, work.length, work.data.len()); // Do the work. let mut out: Vec<u8> = Vec::with_capacity(work.length); for i in range(0us, work.length) { out.push(((work.data[i + work.offset] * 2) >> 1 + 5) * 2); } let mut wreply = Message::new_sync(WorkReply { id: work.id, data: out, offset: work.offset, length: work.length, }); wreply.dsteid = MANAGEREID; wreply.dstsid = 1; // The `srceid` and `srcsid` will be filled in automatically. ep.send(wreply); } } } /// Accepts requests. Splits the data. Sends it out to processors. It also /// forwards the data for the second processing pass to the processors. /// fn thread_pipelinemanager(mep: Endpoint, corecnt: usize) { let mut endpoints: Vec<Endpoint> = Vec::new(); let mut workerthreads: Vec<JoinGuard<()>> = Vec::new(); let mut pending: HashMap<u64, WorkPending> = HashMap::new(); // Create net for this pipeline. let net = Net::new(400); let ep = net.new_endpoint_withid(MANAGEREID); endpoints.push(mep.clone()); endpoints.push(ep.clone()); println!("[man] creating worker threads"); // Spawn worker threads for the number of specified cores. for _ in range(0us, corecnt) { let wep = net.new_endpoint(); wep.setgid(WORKERGRPID); workerthreads.push(Thread::scoped(move || thread_pipelineworker(wep))); } // Create processor threads for this pipeline. loop { // Check for requests and results from data processors. println!("[man] waiting for messages"); let result = water::recvorblock(&endpoints, Duration::seconds(10)); if result.is_err() { continue; } let msg = result.unwrap(); if msg.is_type::<Terminate>() { // Tell all workers to terminate. ep.sendclonetype(Terminate); return; } // Figure out the type of message. if msg.is_type::<Request>() { println!("[man] got request"); let msg_srcsid = msg.srcsid; let msg_srceid = msg.srceid; let request: Request = msg.get_sync().get_payload(); // Break into DataChunk(s) and hand out to the processor threads. let data = request.data.clone(); let chklen = data.len() / corecnt; let slack = data.len() % corecnt; let datalen = data.len(); let adata = Arc::new(data); pending.insert(request.id, WorkPending { epsid: msg_srcsid, epid: msg_srceid, id: request.id, need: corecnt, work: Vec::new(), totalsize: datalen, }); for chkndx in range(0us, (corecnt - 1) as usize) { let work = Work { id: request.id, data: adata.clone(), offset: chkndx * chklen, length: chklen, tail: 0x1234, }; println!("[man] sent work packet of length {:x}", work.data.len()); // Only the first worker to receive this gets it. This is // because we are sending it as sync instead of clone. ep.sendsynctype(work); } // Throw slack onto last chunk. let work = Work { id: request.id, data: adata, offset: (corecnt - 1) * chklen, length: chklen + slack, tail: 0x1234, }; println!("[man] sent slack work packet {:x}", work.data.len()); // Only the first worker to receive this gets it. This is // because we are sending it as sync instead of clone. ep.sendsynctype(work); continue; } if msg.is_type::<WorkReply>() { // Combine all results. let reply: WorkReply = msg.get_sync().get_payload(); println!("[man] got work reply with id:{:x}", reply.id); let result = pending.get_mut(&reply.id); if result.is_some() { println!("[man] looking at work reply"); let pending = result.unwrap(); // Place into pending. pending.work.push(reply); // Are we done? if pending.work.len() >= pending.need { println!("[man] processing all work replies for job"); // Combine output and send to original requestor. let mut f: Vec<u8> = Vec::with_capacity(pending.totalsize); // Only *safe* way to initialize at the moment. for i in range(0us, pending.totalsize) { f.push(0u8); } for reply in pending.work.iter() { let mut i = 0us; for value in reply.data.iter() { f[reply.offset + i] = *value; i += 1; } } // let reply = Reply { id: pending.id, data: f, }; println!("[man] sending work finished message"); let mut msg = Message::new_sync(reply); msg.dsteid = pending.epid; msg.dstsid = pending.epsid; mep.send(msg); } } } } } /// Perform a benchmark/test run. fn go(reqcnt: usize, mancnt: usize, coreperman: usize, datcnt: usize) { let net = Net::new(100); let mut threads: Vec<JoinGuard<()>> = Vec::new(); for manid in range(0us, mancnt) { let manep = net.new_endpoint_withid((1000 + manid) as ID); let t = Thread::scoped(move || thread_pipelinemanager(manep, coreperman)); threads.push(t); } while net.getepcount() < mancnt { Thread::yield_now(); } let ep = net.new_endpoint(); for _ in range(0us, reqcnt) { let mut data: Vec<u8> = Vec::new(); for _ in range(0us, datcnt) { data.push(1u8); } ep.sendsynctype(Request { id: 0x100u64, data: data, }); } for _ in range(0us, reqcnt) { let msg = ep.recvorblockforever().unwrap(); println!("[main] got result"); } println!("[main] telling manager to terminate"); ep.sendclonetype(Terminate); } #[test] fn practicalengine() { // Create a thread so we can debug using stdout under `cargo test`. std::thread::Thread::scoped(move || { go(10, 2, 2, 1024); }); }
{ return; }
conditional_block
service.rs
use futures::{Future, IntoFuture}; use std::io; use std::marker::PhantomData; use std::sync::{Arc, Mutex}; /// An asynchronous function from `Request` to a `Response`. /// /// The `Service` trait is a simplified interface making it easy to write /// network applications in a modular and reusable way, decoupled from the /// underlying protocol. It is one of Tokio's fundamental abstractions. /// /// # Functional /// /// A `Service` is a function from a `Request`. It immediately returns a /// `Future` representing the the eventual completion of processing the /// request. The actual request processing may happen at any time in the /// future, on any thread or executor. The processing may depend on calling /// other services. At some point in the future, the processing will complete, /// and the `Future` will resolve to a response or error. /// /// At a high level, the `Service::call` represents an RPC request. The /// `Service` value can be a server or a client. /// /// # Server /// /// An RPC server *implements* the `Service` trait. Requests received by the /// server over the network are deserialized then passed as an argument to the /// server value. The returned response is sent back over the network. /// /// As an example, here is how an HTTP request is processed by a server: /// /// ```rust,ignore /// impl Service for HelloWorld { /// type Req = http::Request; /// type Resp = http::Response; /// type Error = http::Error; /// type Fut = Box<Future<Item = Self::Resp, Error = http::Error>>; /// /// fn call(&self, req: http::Request) -> Self::Fut { /// // Create the HTTP response /// let resp = http::Response::ok() /// .with_body(b"hello world\n"); /// /// // Return the response as an immediate future /// futures::finished(resp).boxed() /// } /// } /// ``` /// /// # Client /// /// A client consumes a service by using a `Service` value. The client may /// issue requests by invoking `call` and passing the request as an argument. /// It then waits receives the response by waiting for the returned future. /// /// As an example, here is how a Redis request would be issued: /// /// ```rust,ignore /// let client = redis::Client::new() /// .connect("127.0.0.1:6379".parse().unwrap()) /// .unwrap(); /// /// let resp = client.call(Cmd::set("foo", "this is the value of foo")); /// /// // Wait for the future to resolve /// println!("Redis response: {:?}", await(resp)); /// ``` /// /// # Middleware /// /// More often than not, all the pieces needed for writing robust, scalable /// network applications are the same no matter the underlying protocol. By /// unifying the API for both clients and servers in a protocol agnostic way, /// it is possible to write middlware that provide these pieces in in a /// reusable way. /// /// For example, take timeouts as an example: /// /// ```rust,ignore /// use tokio::Service; /// use futures::Future; /// use std::time::Duration; /// /// // Not yet implemented, but soon :) /// use tokio::timer::{Timer, Expired}; /// /// pub struct Timeout<T> { /// upstream: T, /// delay: Duration, /// timer: Timer, /// } /// /// impl<T> Timeout<T> { /// pub fn new(upstream: T, delay: Duration) -> Timeout<T> { /// Timeout { /// upstream: upstream, /// delay: delay, /// timer: Timer::default(), /// } /// } /// } /// /// impl<T> Service for Timeout<T> /// where T: Service, /// T::Error: From<Expired>, /// { /// type Req = T::Req; /// type Resp = T::Resp; /// type Error = T::Error; /// type Fut = Box<Future<Item = Self::Resp, Error = Self::Error>>; /// /// fn call(&self, req: Self::Req) -> Self::Fut { /// let timeout = self.timer.timeout(self.delay) /// .and_then(|timeout| Err(Self::Error::from(timeout))); /// /// self.upstream.call(req) /// .select(timeout) /// .map(|(v, _)| v) /// .map_err(|(e, _)| e) /// .boxed() /// } /// } /// /// ``` /// /// The above timeout implementation is decoupled from the underlying protocol /// and is also decoupled from client or server concerns. In other words, the /// same timeout middleware could be used in either a client or a server. pub trait Service: Send +'static { /// Requests handled by the service. type Req: Send +'static; /// Responses given by the service. type Resp: Send +'static; /// Errors produced by the service. type Error: Send +'static; /// The future response value. type Fut: Future<Item = Self::Resp, Error = Self::Error>; /// Process the request and return the response asynchronously. fn call(&self, req: Self::Req) -> Self::Fut; } /// Creates new `Service` values. pub trait NewService { /// Requests handled by the service type Req: Send +'static; /// Responses given by the service type Resp: Send +'static; /// Errors produced by the service type Error: Send +'static; /// The `Service` value created by this factory type Item: Service<Req = Self::Req, Resp = Self::Resp, Error = Self::Error>; /// Create and return a new service value. fn new_service(&self) -> io::Result<Self::Item>; } /// A service implemented by a closure. pub struct SimpleService<F, R> { f: Arc<F>, _ty: PhantomData<Mutex<R>>, // use Mutex to avoid imposing Sync on Req } /// Returns a `Service` backed by the given closure. pub fn simple_service<F, R>(f: F) -> SimpleService<F, R> { SimpleService::new(f) } impl<F, R> SimpleService<F, R> { /// Create and return a new `SimpleService` backed by the given function. pub fn new(f: F) -> SimpleService<F, R> { SimpleService { f: Arc::new(f), _ty: PhantomData, } } } impl<F, R, S> Service for SimpleService<F, R> where F: Fn(R) -> S + Sync + Send +'static, R: Send +'static, S: IntoFuture, { type Req = R; type Resp = S::Item; type Error = S::Error; type Fut = S::Future; fn call(&self, req: R) -> Self::Fut { (self.f)(req).into_future() } } impl<F, R> Clone for SimpleService<F, R> { fn
(&self) -> SimpleService<F, R> { SimpleService { f: self.f.clone(), _ty: PhantomData, } } } impl<T> NewService for T where T: Service + Clone, { type Item = T; type Req = T::Req; type Resp = T::Resp; type Error = T::Error; fn new_service(&self) -> io::Result<T> { Ok(self.clone()) } }
clone
identifier_name
service.rs
use futures::{Future, IntoFuture}; use std::io; use std::marker::PhantomData; use std::sync::{Arc, Mutex}; /// An asynchronous function from `Request` to a `Response`. /// /// The `Service` trait is a simplified interface making it easy to write /// network applications in a modular and reusable way, decoupled from the /// underlying protocol. It is one of Tokio's fundamental abstractions. /// /// # Functional /// /// A `Service` is a function from a `Request`. It immediately returns a /// `Future` representing the the eventual completion of processing the /// request. The actual request processing may happen at any time in the /// future, on any thread or executor. The processing may depend on calling /// other services. At some point in the future, the processing will complete, /// and the `Future` will resolve to a response or error. /// /// At a high level, the `Service::call` represents an RPC request. The /// `Service` value can be a server or a client. /// /// # Server /// /// An RPC server *implements* the `Service` trait. Requests received by the /// server over the network are deserialized then passed as an argument to the /// server value. The returned response is sent back over the network. /// /// As an example, here is how an HTTP request is processed by a server: /// /// ```rust,ignore /// impl Service for HelloWorld { /// type Req = http::Request; /// type Resp = http::Response; /// type Error = http::Error; /// type Fut = Box<Future<Item = Self::Resp, Error = http::Error>>; /// /// fn call(&self, req: http::Request) -> Self::Fut { /// // Create the HTTP response /// let resp = http::Response::ok() /// .with_body(b"hello world\n"); /// /// // Return the response as an immediate future /// futures::finished(resp).boxed() /// } /// } /// ``` /// /// # Client /// /// A client consumes a service by using a `Service` value. The client may /// issue requests by invoking `call` and passing the request as an argument. /// It then waits receives the response by waiting for the returned future. /// /// As an example, here is how a Redis request would be issued: /// /// ```rust,ignore /// let client = redis::Client::new() /// .connect("127.0.0.1:6379".parse().unwrap()) /// .unwrap(); /// /// let resp = client.call(Cmd::set("foo", "this is the value of foo")); /// /// // Wait for the future to resolve /// println!("Redis response: {:?}", await(resp)); /// ``` /// /// # Middleware /// /// More often than not, all the pieces needed for writing robust, scalable /// network applications are the same no matter the underlying protocol. By /// unifying the API for both clients and servers in a protocol agnostic way, /// it is possible to write middlware that provide these pieces in in a /// reusable way. /// /// For example, take timeouts as an example: /// /// ```rust,ignore /// use tokio::Service; /// use futures::Future; /// use std::time::Duration; /// /// // Not yet implemented, but soon :) /// use tokio::timer::{Timer, Expired}; /// /// pub struct Timeout<T> { /// upstream: T, /// delay: Duration, /// timer: Timer, /// } /// /// impl<T> Timeout<T> { /// pub fn new(upstream: T, delay: Duration) -> Timeout<T> { /// Timeout { /// upstream: upstream, /// delay: delay, /// timer: Timer::default(), /// } /// }
/// impl<T> Service for Timeout<T> /// where T: Service, /// T::Error: From<Expired>, /// { /// type Req = T::Req; /// type Resp = T::Resp; /// type Error = T::Error; /// type Fut = Box<Future<Item = Self::Resp, Error = Self::Error>>; /// /// fn call(&self, req: Self::Req) -> Self::Fut { /// let timeout = self.timer.timeout(self.delay) /// .and_then(|timeout| Err(Self::Error::from(timeout))); /// /// self.upstream.call(req) /// .select(timeout) /// .map(|(v, _)| v) /// .map_err(|(e, _)| e) /// .boxed() /// } /// } /// /// ``` /// /// The above timeout implementation is decoupled from the underlying protocol /// and is also decoupled from client or server concerns. In other words, the /// same timeout middleware could be used in either a client or a server. pub trait Service: Send +'static { /// Requests handled by the service. type Req: Send +'static; /// Responses given by the service. type Resp: Send +'static; /// Errors produced by the service. type Error: Send +'static; /// The future response value. type Fut: Future<Item = Self::Resp, Error = Self::Error>; /// Process the request and return the response asynchronously. fn call(&self, req: Self::Req) -> Self::Fut; } /// Creates new `Service` values. pub trait NewService { /// Requests handled by the service type Req: Send +'static; /// Responses given by the service type Resp: Send +'static; /// Errors produced by the service type Error: Send +'static; /// The `Service` value created by this factory type Item: Service<Req = Self::Req, Resp = Self::Resp, Error = Self::Error>; /// Create and return a new service value. fn new_service(&self) -> io::Result<Self::Item>; } /// A service implemented by a closure. pub struct SimpleService<F, R> { f: Arc<F>, _ty: PhantomData<Mutex<R>>, // use Mutex to avoid imposing Sync on Req } /// Returns a `Service` backed by the given closure. pub fn simple_service<F, R>(f: F) -> SimpleService<F, R> { SimpleService::new(f) } impl<F, R> SimpleService<F, R> { /// Create and return a new `SimpleService` backed by the given function. pub fn new(f: F) -> SimpleService<F, R> { SimpleService { f: Arc::new(f), _ty: PhantomData, } } } impl<F, R, S> Service for SimpleService<F, R> where F: Fn(R) -> S + Sync + Send +'static, R: Send +'static, S: IntoFuture, { type Req = R; type Resp = S::Item; type Error = S::Error; type Fut = S::Future; fn call(&self, req: R) -> Self::Fut { (self.f)(req).into_future() } } impl<F, R> Clone for SimpleService<F, R> { fn clone(&self) -> SimpleService<F, R> { SimpleService { f: self.f.clone(), _ty: PhantomData, } } } impl<T> NewService for T where T: Service + Clone, { type Item = T; type Req = T::Req; type Resp = T::Resp; type Error = T::Error; fn new_service(&self) -> io::Result<T> { Ok(self.clone()) } }
/// } ///
random_line_split
service.rs
use futures::{Future, IntoFuture}; use std::io; use std::marker::PhantomData; use std::sync::{Arc, Mutex}; /// An asynchronous function from `Request` to a `Response`. /// /// The `Service` trait is a simplified interface making it easy to write /// network applications in a modular and reusable way, decoupled from the /// underlying protocol. It is one of Tokio's fundamental abstractions. /// /// # Functional /// /// A `Service` is a function from a `Request`. It immediately returns a /// `Future` representing the the eventual completion of processing the /// request. The actual request processing may happen at any time in the /// future, on any thread or executor. The processing may depend on calling /// other services. At some point in the future, the processing will complete, /// and the `Future` will resolve to a response or error. /// /// At a high level, the `Service::call` represents an RPC request. The /// `Service` value can be a server or a client. /// /// # Server /// /// An RPC server *implements* the `Service` trait. Requests received by the /// server over the network are deserialized then passed as an argument to the /// server value. The returned response is sent back over the network. /// /// As an example, here is how an HTTP request is processed by a server: /// /// ```rust,ignore /// impl Service for HelloWorld { /// type Req = http::Request; /// type Resp = http::Response; /// type Error = http::Error; /// type Fut = Box<Future<Item = Self::Resp, Error = http::Error>>; /// /// fn call(&self, req: http::Request) -> Self::Fut { /// // Create the HTTP response /// let resp = http::Response::ok() /// .with_body(b"hello world\n"); /// /// // Return the response as an immediate future /// futures::finished(resp).boxed() /// } /// } /// ``` /// /// # Client /// /// A client consumes a service by using a `Service` value. The client may /// issue requests by invoking `call` and passing the request as an argument. /// It then waits receives the response by waiting for the returned future. /// /// As an example, here is how a Redis request would be issued: /// /// ```rust,ignore /// let client = redis::Client::new() /// .connect("127.0.0.1:6379".parse().unwrap()) /// .unwrap(); /// /// let resp = client.call(Cmd::set("foo", "this is the value of foo")); /// /// // Wait for the future to resolve /// println!("Redis response: {:?}", await(resp)); /// ``` /// /// # Middleware /// /// More often than not, all the pieces needed for writing robust, scalable /// network applications are the same no matter the underlying protocol. By /// unifying the API for both clients and servers in a protocol agnostic way, /// it is possible to write middlware that provide these pieces in in a /// reusable way. /// /// For example, take timeouts as an example: /// /// ```rust,ignore /// use tokio::Service; /// use futures::Future; /// use std::time::Duration; /// /// // Not yet implemented, but soon :) /// use tokio::timer::{Timer, Expired}; /// /// pub struct Timeout<T> { /// upstream: T, /// delay: Duration, /// timer: Timer, /// } /// /// impl<T> Timeout<T> { /// pub fn new(upstream: T, delay: Duration) -> Timeout<T> { /// Timeout { /// upstream: upstream, /// delay: delay, /// timer: Timer::default(), /// } /// } /// } /// /// impl<T> Service for Timeout<T> /// where T: Service, /// T::Error: From<Expired>, /// { /// type Req = T::Req; /// type Resp = T::Resp; /// type Error = T::Error; /// type Fut = Box<Future<Item = Self::Resp, Error = Self::Error>>; /// /// fn call(&self, req: Self::Req) -> Self::Fut { /// let timeout = self.timer.timeout(self.delay) /// .and_then(|timeout| Err(Self::Error::from(timeout))); /// /// self.upstream.call(req) /// .select(timeout) /// .map(|(v, _)| v) /// .map_err(|(e, _)| e) /// .boxed() /// } /// } /// /// ``` /// /// The above timeout implementation is decoupled from the underlying protocol /// and is also decoupled from client or server concerns. In other words, the /// same timeout middleware could be used in either a client or a server. pub trait Service: Send +'static { /// Requests handled by the service. type Req: Send +'static; /// Responses given by the service. type Resp: Send +'static; /// Errors produced by the service. type Error: Send +'static; /// The future response value. type Fut: Future<Item = Self::Resp, Error = Self::Error>; /// Process the request and return the response asynchronously. fn call(&self, req: Self::Req) -> Self::Fut; } /// Creates new `Service` values. pub trait NewService { /// Requests handled by the service type Req: Send +'static; /// Responses given by the service type Resp: Send +'static; /// Errors produced by the service type Error: Send +'static; /// The `Service` value created by this factory type Item: Service<Req = Self::Req, Resp = Self::Resp, Error = Self::Error>; /// Create and return a new service value. fn new_service(&self) -> io::Result<Self::Item>; } /// A service implemented by a closure. pub struct SimpleService<F, R> { f: Arc<F>, _ty: PhantomData<Mutex<R>>, // use Mutex to avoid imposing Sync on Req } /// Returns a `Service` backed by the given closure. pub fn simple_service<F, R>(f: F) -> SimpleService<F, R> { SimpleService::new(f) } impl<F, R> SimpleService<F, R> { /// Create and return a new `SimpleService` backed by the given function. pub fn new(f: F) -> SimpleService<F, R> { SimpleService { f: Arc::new(f), _ty: PhantomData, } } } impl<F, R, S> Service for SimpleService<F, R> where F: Fn(R) -> S + Sync + Send +'static, R: Send +'static, S: IntoFuture, { type Req = R; type Resp = S::Item; type Error = S::Error; type Fut = S::Future; fn call(&self, req: R) -> Self::Fut { (self.f)(req).into_future() } } impl<F, R> Clone for SimpleService<F, R> { fn clone(&self) -> SimpleService<F, R>
} impl<T> NewService for T where T: Service + Clone, { type Item = T; type Req = T::Req; type Resp = T::Resp; type Error = T::Error; fn new_service(&self) -> io::Result<T> { Ok(self.clone()) } }
{ SimpleService { f: self.f.clone(), _ty: PhantomData, } }
identifier_body
char.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 pub fn main() { let c: char = 'x'; let d: char = 'x'; assert_eq!(c, 'x'); assert_eq!('x', c); assert_eq!(c, c);
assert_eq!(c, d); assert_eq!(d, c); assert_eq!(d, 'x'); assert_eq!('x', d); }
random_line_split
char.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 pub fn main()
{ let c: char = 'x'; let d: char = 'x'; assert_eq!(c, 'x'); assert_eq!('x', c); assert_eq!(c, c); assert_eq!(c, d); assert_eq!(d, c); assert_eq!(d, 'x'); assert_eq!('x', d); }
identifier_body
char.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 pub fn
() { let c: char = 'x'; let d: char = 'x'; assert_eq!(c, 'x'); assert_eq!('x', c); assert_eq!(c, c); assert_eq!(c, d); assert_eq!(d, c); assert_eq!(d, 'x'); assert_eq!('x', d); }
main
identifier_name
binary_tree.rs
pub struct Node<T: Clone> { elem: T, left: Box<Tree<T>>, right: Box<Tree<T>>, } /* impl<T: Clone> Drop for Node<T> { fn drop(self) { println!("> Dropping {}", self.name); } } */ impl<T: Clone> Node<T> { /// Allocates a new binary tree node to contain the given element. pub fn new(elem: T) -> Node<T> { Node { elem: elem, left: box Tree::Nil, right: box Tree::Nil } } } pub enum Tree<T: Clone> { Nil, Node(Node<T>) } impl<T: Clone> Tree<T> { /// Creates a new tree which is empty. pub fn new() -> Tree<T>
pub fn is_nil(&self) -> bool { match *self { Tree::Nil => true, _ => false } } /// Returns a clone of the element stored in the root node. /// /// Panics if there is no root node. pub fn peek(&self) -> T { match *self { Tree::Nil => panic!(), Tree::Node(ref n) => (*n).elem.clone() } } /* /// The given element is cloned, and this clone is stored at the root of /// the tree. /// /// If the tree is `Nil`, then a node is made in-place to hold the element. pub fn set(&mut self, &elem: T) { match *self { Tree::Nil => Node::new(elem), Tree::Node(ref mut n) => *n.elem = *elem.clone() }; } */ /// The given `elem` is stored as the `elem` of the tree's root node. The /// tree takes ownership of the given node. /// /// If the tree is `Nil`, then a node is made in-place to hold the `elem`. pub fn give(&mut self, elem: T) { match *self { Tree::Nil => *self = Tree::Node(Node::new(elem)), Tree::Node(ref mut n) => (*n).elem = elem }; } /* /// Saves the given element in the data field of a leaf node. This node is /// then saved as the tree's left subtree. This calls `panic!()` if `self` /// is `Nil`. pub fn make_left(& mut self, elem: T) { } */ /// Applies the given function to each element of the tree and saves the /// results in-place. pub fn apply<F: Fn(T) -> T>(&mut self, f: F) { match *self { Tree::Nil => (), Tree::Node(ref mut node) => (*node).elem = f((*node).elem.clone()) } } }
{ Tree::Nil }
identifier_body
binary_tree.rs
pub struct Node<T: Clone> { elem: T, left: Box<Tree<T>>, right: Box<Tree<T>>, } /* impl<T: Clone> Drop for Node<T> { fn drop(self) { println!("> Dropping {}", self.name); } } */ impl<T: Clone> Node<T> { /// Allocates a new binary tree node to contain the given element. pub fn new(elem: T) -> Node<T> { Node { elem: elem, left: box Tree::Nil, right: box Tree::Nil } } } pub enum Tree<T: Clone> { Nil, Node(Node<T>) } impl<T: Clone> Tree<T> { /// Creates a new tree which is empty. pub fn new() -> Tree<T> { Tree::Nil } pub fn is_nil(&self) -> bool { match *self { Tree::Nil => true, _ => false } } /// Returns a clone of the element stored in the root node. /// /// Panics if there is no root node. pub fn
(&self) -> T { match *self { Tree::Nil => panic!(), Tree::Node(ref n) => (*n).elem.clone() } } /* /// The given element is cloned, and this clone is stored at the root of /// the tree. /// /// If the tree is `Nil`, then a node is made in-place to hold the element. pub fn set(&mut self, &elem: T) { match *self { Tree::Nil => Node::new(elem), Tree::Node(ref mut n) => *n.elem = *elem.clone() }; } */ /// The given `elem` is stored as the `elem` of the tree's root node. The /// tree takes ownership of the given node. /// /// If the tree is `Nil`, then a node is made in-place to hold the `elem`. pub fn give(&mut self, elem: T) { match *self { Tree::Nil => *self = Tree::Node(Node::new(elem)), Tree::Node(ref mut n) => (*n).elem = elem }; } /* /// Saves the given element in the data field of a leaf node. This node is /// then saved as the tree's left subtree. This calls `panic!()` if `self` /// is `Nil`. pub fn make_left(& mut self, elem: T) { } */ /// Applies the given function to each element of the tree and saves the /// results in-place. pub fn apply<F: Fn(T) -> T>(&mut self, f: F) { match *self { Tree::Nil => (), Tree::Node(ref mut node) => (*node).elem = f((*node).elem.clone()) } } }
peek
identifier_name
binary_tree.rs
pub struct Node<T: Clone> {
} /* impl<T: Clone> Drop for Node<T> { fn drop(self) { println!("> Dropping {}", self.name); } } */ impl<T: Clone> Node<T> { /// Allocates a new binary tree node to contain the given element. pub fn new(elem: T) -> Node<T> { Node { elem: elem, left: box Tree::Nil, right: box Tree::Nil } } } pub enum Tree<T: Clone> { Nil, Node(Node<T>) } impl<T: Clone> Tree<T> { /// Creates a new tree which is empty. pub fn new() -> Tree<T> { Tree::Nil } pub fn is_nil(&self) -> bool { match *self { Tree::Nil => true, _ => false } } /// Returns a clone of the element stored in the root node. /// /// Panics if there is no root node. pub fn peek(&self) -> T { match *self { Tree::Nil => panic!(), Tree::Node(ref n) => (*n).elem.clone() } } /* /// The given element is cloned, and this clone is stored at the root of /// the tree. /// /// If the tree is `Nil`, then a node is made in-place to hold the element. pub fn set(&mut self, &elem: T) { match *self { Tree::Nil => Node::new(elem), Tree::Node(ref mut n) => *n.elem = *elem.clone() }; } */ /// The given `elem` is stored as the `elem` of the tree's root node. The /// tree takes ownership of the given node. /// /// If the tree is `Nil`, then a node is made in-place to hold the `elem`. pub fn give(&mut self, elem: T) { match *self { Tree::Nil => *self = Tree::Node(Node::new(elem)), Tree::Node(ref mut n) => (*n).elem = elem }; } /* /// Saves the given element in the data field of a leaf node. This node is /// then saved as the tree's left subtree. This calls `panic!()` if `self` /// is `Nil`. pub fn make_left(& mut self, elem: T) { } */ /// Applies the given function to each element of the tree and saves the /// results in-place. pub fn apply<F: Fn(T) -> T>(&mut self, f: F) { match *self { Tree::Nil => (), Tree::Node(ref mut node) => (*node).elem = f((*node).elem.clone()) } } }
elem: T, left: Box<Tree<T>>, right: Box<Tree<T>>,
random_line_split
graphviz.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module provides linkage between libgraphviz traits and //! `rustc::middle::typeck::infer::region_inference`, generating a //! rendering of the graph represented by the list of `Constraint` //! instances (which make up the edges of the graph), as well as the //! origin for each constraint (which are attached to the labels on //! each edge). /// For clarity, rename the graphviz crate locally to dot. use graphviz as dot; use middle::ty; use middle::region::CodeExtent; use super::Constraint; use middle::infer::SubregionOrigin; use middle::infer::region_inference::RegionVarBindings; use util::nodemap::{FnvHashMap, FnvHashSet}; use util::ppaux::Repr; use std::borrow::Cow; use std::collections::hash_map::Entry::Vacant; use std::old_io::{self, File}; use std::env; use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; use syntax::ast; fn print_help_message() { println!("\ -Z print-region-graph by default prints a region constraint graph for every \n\ function body, to the path `/tmp/constraints.nodeXXX.dot`, where the XXX is \n\ replaced with the node id of the function under analysis. \n\ \n\ To select one particular function body, set `RUST_REGION_GRAPH_NODE=XXX`, \n\ where XXX is the node id desired. \n\ \n\ To generate output to some path other than the default \n\ `/tmp/constraints.nodeXXX.dot`, set `RUST_REGION_GRAPH=/path/desired.dot`; \n\ occurrences of the character `%` in the requested path will be replaced with\n\ the node id of the function under analysis. \n\ \n\ (Since you requested help via RUST_REGION_GRAPH=help, no region constraint \n\ graphs will be printed. \n\ "); } pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a, 'tcx>, subject_node: ast::NodeId) { let tcx = region_vars.tcx; if!region_vars.tcx.sess.opts.debugging_opts.print_region_graph { return; } let requested_node : Option<ast::NodeId> = env::var("RUST_REGION_GRAPH_NODE").ok().and_then(|s| s.parse().ok()); if requested_node.is_some() && requested_node!= Some(subject_node) { return; } let requested_output = env::var("RUST_REGION_GRAPH").ok(); debug!("requested_output: {:?} requested_node: {:?}", requested_output, requested_node); let output_path = { let output_template = match requested_output { Some(ref s) if &**s == "help" => { static PRINTED_YET: AtomicBool = ATOMIC_BOOL_INIT; if!PRINTED_YET.load(Ordering::SeqCst) { print_help_message(); PRINTED_YET.store(true, Ordering::SeqCst); } return; } Some(other_path) => other_path, None => "/tmp/constraints.node%.dot".to_string(), }; if output_template.len() == 0 { tcx.sess.bug("empty string provided as RUST_REGION_GRAPH"); } if output_template.contains_char('%') { let mut new_str = String::new(); for c in output_template.chars() { if c == '%' { new_str.push_str(&subject_node.to_string()); } else { new_str.push(c); } } new_str } else { output_template } }; let constraints = &*region_vars.constraints.borrow(); match dump_region_constraints_to(tcx, constraints, &output_path) { Ok(()) => {} Err(e) => { let msg = format!("io error dumping region constraints: {}", e); region_vars.tcx.sess.err(&msg) } } } struct ConstraintGraph<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx>, graph_name: String, map: &'a FnvHashMap<Constraint, SubregionOrigin<'tcx>>, node_ids: FnvHashMap<Node, uint>, } #[derive(Clone, Hash, PartialEq, Eq, Debug, Copy)] enum Node { RegionVid(ty::RegionVid), Region(ty::Region), } // type Edge = Constraint; #[derive(Clone, PartialEq, Eq, Debug, Copy)] enum Edge { Constraint(Constraint), EnclScope(CodeExtent, CodeExtent), } impl<'a, 'tcx> ConstraintGraph<'a, 'tcx> { fn new(tcx: &'a ty::ctxt<'tcx>, name: String, map: &'a ConstraintMap<'tcx>) -> ConstraintGraph<'a, 'tcx> { let mut i = 0; let mut node_ids = FnvHashMap(); { let mut add_node = |node| { if let Vacant(e) = node_ids.entry(node) { e.insert(i); i += 1; } }; for (n1, n2) in map.keys().map(|c|constraint_to_nodes(c)) { add_node(n1); add_node(n2); } tcx.region_maps.each_encl_scope(|sub, sup| { add_node(Node::Region(ty::ReScope(*sub))); add_node(Node::Region(ty::ReScope(*sup))); }); } ConstraintGraph { tcx: tcx, graph_name: name, map: map, node_ids: node_ids } } } impl<'a, 'tcx> dot::Labeller<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { fn graph_id(&self) -> dot::Id { dot::Id::new(&*self.graph_name).ok().unwrap() } fn node_id(&self, n: &Node) -> dot::Id { let node_id = match self.node_ids.get(n) { Some(node_id) => node_id, None => panic!("no node_id found for node: {:?}", n), }; let name = || format!("node_{}", node_id); match dot::Id::new(name()) { Ok(id) => id, Err(_) => { panic!("failed to create graphviz node identified by {}", name()); } } } fn node_label(&self, n: &Node) -> dot::LabelText { match *n { Node::RegionVid(n_vid) => dot::LabelText::label(format!("{:?}", n_vid)), Node::Region(n_rgn) => dot::LabelText::label(format!("{}", n_rgn.repr(self.tcx))), } } fn edge_label(&self, e: &Edge) -> dot::LabelText { match *e { Edge::Constraint(ref c) => dot::LabelText::label(format!("{}", self.map.get(c).unwrap().repr(self.tcx))), Edge::EnclScope(..) => dot::LabelText::label(format!("(enclosed)")), } } } fn constraint_to_nodes(c: &Constraint) -> (Node, Node) { match *c { Constraint::ConstrainVarSubVar(rv_1, rv_2) => (Node::RegionVid(rv_1), Node::RegionVid(rv_2)), Constraint::ConstrainRegSubVar(r_1, rv_2) => (Node::Region(r_1), Node::RegionVid(rv_2)), Constraint::ConstrainVarSubReg(rv_1, r_2) => (Node::RegionVid(rv_1), Node::Region(r_2)), } } fn edge_to_nodes(e: &Edge) -> (Node, Node) { match *e { Edge::Constraint(ref c) => constraint_to_nodes(c), Edge::EnclScope(sub, sup) =>
} } impl<'a, 'tcx> dot::GraphWalk<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { fn nodes(&self) -> dot::Nodes<Node> { let mut set = FnvHashSet(); for node in self.node_ids.keys() { set.insert(*node); } debug!("constraint graph has {} nodes", set.len()); set.into_iter().collect() } fn edges(&self) -> dot::Edges<Edge> { debug!("constraint graph has {} edges", self.map.len()); let mut v : Vec<_> = self.map.keys().map(|e| Edge::Constraint(*e)).collect(); self.tcx.region_maps.each_encl_scope(|sub, sup| { v.push(Edge::EnclScope(*sub, *sup)) }); debug!("region graph has {} edges", v.len()); Cow::Owned(v) } fn source(&self, edge: &Edge) -> Node { let (n1, _) = edge_to_nodes(edge); debug!("edge {:?} has source {:?}", edge, n1); n1 } fn target(&self, edge: &Edge) -> Node { let (_, n2) = edge_to_nodes(edge); debug!("edge {:?} has target {:?}", edge, n2); n2 } } pub type ConstraintMap<'tcx> = FnvHashMap<Constraint, SubregionOrigin<'tcx>>; fn dump_region_constraints_to<'a, 'tcx:'a >(tcx: &'a ty::ctxt<'tcx>, map: &ConstraintMap<'tcx>, path: &str) -> old_io::IoResult<()> { debug!("dump_region_constraints map (len: {}) path: {}", map.len(), path); let g = ConstraintGraph::new(tcx, format!("region_constraints"), map); let mut f = File::create(&Path::new(path)); debug!("dump_region_constraints calling render"); dot::render(&g, &mut f) }
{ (Node::Region(ty::ReScope(sub)), Node::Region(ty::ReScope(sup))) }
conditional_block
graphviz.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module provides linkage between libgraphviz traits and //! `rustc::middle::typeck::infer::region_inference`, generating a //! rendering of the graph represented by the list of `Constraint` //! instances (which make up the edges of the graph), as well as the //! origin for each constraint (which are attached to the labels on //! each edge). /// For clarity, rename the graphviz crate locally to dot. use graphviz as dot; use middle::ty; use middle::region::CodeExtent; use super::Constraint; use middle::infer::SubregionOrigin; use middle::infer::region_inference::RegionVarBindings; use util::nodemap::{FnvHashMap, FnvHashSet}; use util::ppaux::Repr; use std::borrow::Cow; use std::collections::hash_map::Entry::Vacant; use std::old_io::{self, File}; use std::env; use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; use syntax::ast; fn print_help_message() { println!("\ -Z print-region-graph by default prints a region constraint graph for every \n\ function body, to the path `/tmp/constraints.nodeXXX.dot`, where the XXX is \n\ replaced with the node id of the function under analysis. \n\ \n\ To select one particular function body, set `RUST_REGION_GRAPH_NODE=XXX`, \n\ where XXX is the node id desired. \n\ \n\ To generate output to some path other than the default \n\ `/tmp/constraints.nodeXXX.dot`, set `RUST_REGION_GRAPH=/path/desired.dot`; \n\ occurrences of the character `%` in the requested path will be replaced with\n\ the node id of the function under analysis. \n\ \n\ (Since you requested help via RUST_REGION_GRAPH=help, no region constraint \n\ graphs will be printed. \n\ "); } pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a, 'tcx>, subject_node: ast::NodeId) { let tcx = region_vars.tcx; if!region_vars.tcx.sess.opts.debugging_opts.print_region_graph { return; } let requested_node : Option<ast::NodeId> = env::var("RUST_REGION_GRAPH_NODE").ok().and_then(|s| s.parse().ok()); if requested_node.is_some() && requested_node!= Some(subject_node) { return; } let requested_output = env::var("RUST_REGION_GRAPH").ok(); debug!("requested_output: {:?} requested_node: {:?}", requested_output, requested_node); let output_path = { let output_template = match requested_output { Some(ref s) if &**s == "help" => { static PRINTED_YET: AtomicBool = ATOMIC_BOOL_INIT; if!PRINTED_YET.load(Ordering::SeqCst) { print_help_message(); PRINTED_YET.store(true, Ordering::SeqCst); } return; } Some(other_path) => other_path, None => "/tmp/constraints.node%.dot".to_string(), }; if output_template.len() == 0 { tcx.sess.bug("empty string provided as RUST_REGION_GRAPH"); } if output_template.contains_char('%') { let mut new_str = String::new(); for c in output_template.chars() { if c == '%' { new_str.push_str(&subject_node.to_string()); } else { new_str.push(c); } } new_str } else { output_template } }; let constraints = &*region_vars.constraints.borrow(); match dump_region_constraints_to(tcx, constraints, &output_path) { Ok(()) => {} Err(e) => { let msg = format!("io error dumping region constraints: {}", e); region_vars.tcx.sess.err(&msg) } } } struct ConstraintGraph<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx>, graph_name: String, map: &'a FnvHashMap<Constraint, SubregionOrigin<'tcx>>, node_ids: FnvHashMap<Node, uint>, } #[derive(Clone, Hash, PartialEq, Eq, Debug, Copy)] enum Node { RegionVid(ty::RegionVid), Region(ty::Region), } // type Edge = Constraint; #[derive(Clone, PartialEq, Eq, Debug, Copy)] enum Edge { Constraint(Constraint), EnclScope(CodeExtent, CodeExtent), } impl<'a, 'tcx> ConstraintGraph<'a, 'tcx> { fn new(tcx: &'a ty::ctxt<'tcx>, name: String, map: &'a ConstraintMap<'tcx>) -> ConstraintGraph<'a, 'tcx> { let mut i = 0; let mut node_ids = FnvHashMap(); { let mut add_node = |node| { if let Vacant(e) = node_ids.entry(node) { e.insert(i); i += 1; } }; for (n1, n2) in map.keys().map(|c|constraint_to_nodes(c)) { add_node(n1); add_node(n2); } tcx.region_maps.each_encl_scope(|sub, sup| { add_node(Node::Region(ty::ReScope(*sub))); add_node(Node::Region(ty::ReScope(*sup))); }); } ConstraintGraph { tcx: tcx, graph_name: name, map: map, node_ids: node_ids } } } impl<'a, 'tcx> dot::Labeller<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { fn graph_id(&self) -> dot::Id { dot::Id::new(&*self.graph_name).ok().unwrap() } fn node_id(&self, n: &Node) -> dot::Id { let node_id = match self.node_ids.get(n) { Some(node_id) => node_id, None => panic!("no node_id found for node: {:?}", n), }; let name = || format!("node_{}", node_id); match dot::Id::new(name()) { Ok(id) => id, Err(_) => { panic!("failed to create graphviz node identified by {}", name()); } } } fn
(&self, n: &Node) -> dot::LabelText { match *n { Node::RegionVid(n_vid) => dot::LabelText::label(format!("{:?}", n_vid)), Node::Region(n_rgn) => dot::LabelText::label(format!("{}", n_rgn.repr(self.tcx))), } } fn edge_label(&self, e: &Edge) -> dot::LabelText { match *e { Edge::Constraint(ref c) => dot::LabelText::label(format!("{}", self.map.get(c).unwrap().repr(self.tcx))), Edge::EnclScope(..) => dot::LabelText::label(format!("(enclosed)")), } } } fn constraint_to_nodes(c: &Constraint) -> (Node, Node) { match *c { Constraint::ConstrainVarSubVar(rv_1, rv_2) => (Node::RegionVid(rv_1), Node::RegionVid(rv_2)), Constraint::ConstrainRegSubVar(r_1, rv_2) => (Node::Region(r_1), Node::RegionVid(rv_2)), Constraint::ConstrainVarSubReg(rv_1, r_2) => (Node::RegionVid(rv_1), Node::Region(r_2)), } } fn edge_to_nodes(e: &Edge) -> (Node, Node) { match *e { Edge::Constraint(ref c) => constraint_to_nodes(c), Edge::EnclScope(sub, sup) => { (Node::Region(ty::ReScope(sub)), Node::Region(ty::ReScope(sup))) } } } impl<'a, 'tcx> dot::GraphWalk<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { fn nodes(&self) -> dot::Nodes<Node> { let mut set = FnvHashSet(); for node in self.node_ids.keys() { set.insert(*node); } debug!("constraint graph has {} nodes", set.len()); set.into_iter().collect() } fn edges(&self) -> dot::Edges<Edge> { debug!("constraint graph has {} edges", self.map.len()); let mut v : Vec<_> = self.map.keys().map(|e| Edge::Constraint(*e)).collect(); self.tcx.region_maps.each_encl_scope(|sub, sup| { v.push(Edge::EnclScope(*sub, *sup)) }); debug!("region graph has {} edges", v.len()); Cow::Owned(v) } fn source(&self, edge: &Edge) -> Node { let (n1, _) = edge_to_nodes(edge); debug!("edge {:?} has source {:?}", edge, n1); n1 } fn target(&self, edge: &Edge) -> Node { let (_, n2) = edge_to_nodes(edge); debug!("edge {:?} has target {:?}", edge, n2); n2 } } pub type ConstraintMap<'tcx> = FnvHashMap<Constraint, SubregionOrigin<'tcx>>; fn dump_region_constraints_to<'a, 'tcx:'a >(tcx: &'a ty::ctxt<'tcx>, map: &ConstraintMap<'tcx>, path: &str) -> old_io::IoResult<()> { debug!("dump_region_constraints map (len: {}) path: {}", map.len(), path); let g = ConstraintGraph::new(tcx, format!("region_constraints"), map); let mut f = File::create(&Path::new(path)); debug!("dump_region_constraints calling render"); dot::render(&g, &mut f) }
node_label
identifier_name
graphviz.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module provides linkage between libgraphviz traits and //! `rustc::middle::typeck::infer::region_inference`, generating a //! rendering of the graph represented by the list of `Constraint` //! instances (which make up the edges of the graph), as well as the //! origin for each constraint (which are attached to the labels on //! each edge). /// For clarity, rename the graphviz crate locally to dot. use graphviz as dot; use middle::ty; use middle::region::CodeExtent; use super::Constraint; use middle::infer::SubregionOrigin; use middle::infer::region_inference::RegionVarBindings; use util::nodemap::{FnvHashMap, FnvHashSet}; use util::ppaux::Repr; use std::borrow::Cow; use std::collections::hash_map::Entry::Vacant; use std::old_io::{self, File}; use std::env; use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; use syntax::ast; fn print_help_message() { println!("\ -Z print-region-graph by default prints a region constraint graph for every \n\ function body, to the path `/tmp/constraints.nodeXXX.dot`, where the XXX is \n\ replaced with the node id of the function under analysis. \n\ \n\ To select one particular function body, set `RUST_REGION_GRAPH_NODE=XXX`, \n\ where XXX is the node id desired. \n\ \n\ To generate output to some path other than the default \n\ `/tmp/constraints.nodeXXX.dot`, set `RUST_REGION_GRAPH=/path/desired.dot`; \n\ occurrences of the character `%` in the requested path will be replaced with\n\ the node id of the function under analysis. \n\ \n\ (Since you requested help via RUST_REGION_GRAPH=help, no region constraint \n\ graphs will be printed. \n\ "); } pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a, 'tcx>, subject_node: ast::NodeId) { let tcx = region_vars.tcx; if!region_vars.tcx.sess.opts.debugging_opts.print_region_graph { return; } let requested_node : Option<ast::NodeId> = env::var("RUST_REGION_GRAPH_NODE").ok().and_then(|s| s.parse().ok()); if requested_node.is_some() && requested_node!= Some(subject_node) { return; } let requested_output = env::var("RUST_REGION_GRAPH").ok(); debug!("requested_output: {:?} requested_node: {:?}", requested_output, requested_node); let output_path = { let output_template = match requested_output { Some(ref s) if &**s == "help" => { static PRINTED_YET: AtomicBool = ATOMIC_BOOL_INIT; if!PRINTED_YET.load(Ordering::SeqCst) { print_help_message(); PRINTED_YET.store(true, Ordering::SeqCst); } return; } Some(other_path) => other_path, None => "/tmp/constraints.node%.dot".to_string(), }; if output_template.len() == 0 { tcx.sess.bug("empty string provided as RUST_REGION_GRAPH"); } if output_template.contains_char('%') { let mut new_str = String::new(); for c in output_template.chars() { if c == '%' { new_str.push_str(&subject_node.to_string()); } else { new_str.push(c); } } new_str } else { output_template } }; let constraints = &*region_vars.constraints.borrow(); match dump_region_constraints_to(tcx, constraints, &output_path) { Ok(()) => {} Err(e) => { let msg = format!("io error dumping region constraints: {}", e); region_vars.tcx.sess.err(&msg) } } } struct ConstraintGraph<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx>, graph_name: String, map: &'a FnvHashMap<Constraint, SubregionOrigin<'tcx>>, node_ids: FnvHashMap<Node, uint>, } #[derive(Clone, Hash, PartialEq, Eq, Debug, Copy)] enum Node { RegionVid(ty::RegionVid), Region(ty::Region), } // type Edge = Constraint; #[derive(Clone, PartialEq, Eq, Debug, Copy)] enum Edge { Constraint(Constraint), EnclScope(CodeExtent, CodeExtent), } impl<'a, 'tcx> ConstraintGraph<'a, 'tcx> { fn new(tcx: &'a ty::ctxt<'tcx>, name: String, map: &'a ConstraintMap<'tcx>) -> ConstraintGraph<'a, 'tcx> { let mut i = 0; let mut node_ids = FnvHashMap(); { let mut add_node = |node| { if let Vacant(e) = node_ids.entry(node) { e.insert(i); i += 1; } }; for (n1, n2) in map.keys().map(|c|constraint_to_nodes(c)) { add_node(n1); add_node(n2); } tcx.region_maps.each_encl_scope(|sub, sup| { add_node(Node::Region(ty::ReScope(*sub))); add_node(Node::Region(ty::ReScope(*sup))); }); } ConstraintGraph { tcx: tcx, graph_name: name, map: map, node_ids: node_ids } } } impl<'a, 'tcx> dot::Labeller<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { fn graph_id(&self) -> dot::Id { dot::Id::new(&*self.graph_name).ok().unwrap() } fn node_id(&self, n: &Node) -> dot::Id { let node_id = match self.node_ids.get(n) { Some(node_id) => node_id, None => panic!("no node_id found for node: {:?}", n), }; let name = || format!("node_{}", node_id); match dot::Id::new(name()) { Ok(id) => id, Err(_) => { panic!("failed to create graphviz node identified by {}", name()); } } } fn node_label(&self, n: &Node) -> dot::LabelText { match *n { Node::RegionVid(n_vid) => dot::LabelText::label(format!("{:?}", n_vid)), Node::Region(n_rgn) => dot::LabelText::label(format!("{}", n_rgn.repr(self.tcx))), } } fn edge_label(&self, e: &Edge) -> dot::LabelText { match *e { Edge::Constraint(ref c) => dot::LabelText::label(format!("{}", self.map.get(c).unwrap().repr(self.tcx))), Edge::EnclScope(..) => dot::LabelText::label(format!("(enclosed)")), } } } fn constraint_to_nodes(c: &Constraint) -> (Node, Node) { match *c { Constraint::ConstrainVarSubVar(rv_1, rv_2) => (Node::RegionVid(rv_1), Node::RegionVid(rv_2)), Constraint::ConstrainRegSubVar(r_1, rv_2) => (Node::Region(r_1), Node::RegionVid(rv_2)), Constraint::ConstrainVarSubReg(rv_1, r_2) => (Node::RegionVid(rv_1), Node::Region(r_2)), } } fn edge_to_nodes(e: &Edge) -> (Node, Node) { match *e { Edge::Constraint(ref c) => constraint_to_nodes(c), Edge::EnclScope(sub, sup) => { (Node::Region(ty::ReScope(sub)), Node::Region(ty::ReScope(sup))) } } } impl<'a, 'tcx> dot::GraphWalk<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { fn nodes(&self) -> dot::Nodes<Node> { let mut set = FnvHashSet(); for node in self.node_ids.keys() { set.insert(*node); } debug!("constraint graph has {} nodes", set.len()); set.into_iter().collect() } fn edges(&self) -> dot::Edges<Edge> { debug!("constraint graph has {} edges", self.map.len()); let mut v : Vec<_> = self.map.keys().map(|e| Edge::Constraint(*e)).collect(); self.tcx.region_maps.each_encl_scope(|sub, sup| { v.push(Edge::EnclScope(*sub, *sup)) }); debug!("region graph has {} edges", v.len()); Cow::Owned(v) } fn source(&self, edge: &Edge) -> Node { let (n1, _) = edge_to_nodes(edge);
fn target(&self, edge: &Edge) -> Node { let (_, n2) = edge_to_nodes(edge); debug!("edge {:?} has target {:?}", edge, n2); n2 } } pub type ConstraintMap<'tcx> = FnvHashMap<Constraint, SubregionOrigin<'tcx>>; fn dump_region_constraints_to<'a, 'tcx:'a >(tcx: &'a ty::ctxt<'tcx>, map: &ConstraintMap<'tcx>, path: &str) -> old_io::IoResult<()> { debug!("dump_region_constraints map (len: {}) path: {}", map.len(), path); let g = ConstraintGraph::new(tcx, format!("region_constraints"), map); let mut f = File::create(&Path::new(path)); debug!("dump_region_constraints calling render"); dot::render(&g, &mut f) }
debug!("edge {:?} has source {:?}", edge, n1); n1 }
random_line_split
graphviz.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module provides linkage between libgraphviz traits and //! `rustc::middle::typeck::infer::region_inference`, generating a //! rendering of the graph represented by the list of `Constraint` //! instances (which make up the edges of the graph), as well as the //! origin for each constraint (which are attached to the labels on //! each edge). /// For clarity, rename the graphviz crate locally to dot. use graphviz as dot; use middle::ty; use middle::region::CodeExtent; use super::Constraint; use middle::infer::SubregionOrigin; use middle::infer::region_inference::RegionVarBindings; use util::nodemap::{FnvHashMap, FnvHashSet}; use util::ppaux::Repr; use std::borrow::Cow; use std::collections::hash_map::Entry::Vacant; use std::old_io::{self, File}; use std::env; use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; use syntax::ast; fn print_help_message() { println!("\ -Z print-region-graph by default prints a region constraint graph for every \n\ function body, to the path `/tmp/constraints.nodeXXX.dot`, where the XXX is \n\ replaced with the node id of the function under analysis. \n\ \n\ To select one particular function body, set `RUST_REGION_GRAPH_NODE=XXX`, \n\ where XXX is the node id desired. \n\ \n\ To generate output to some path other than the default \n\ `/tmp/constraints.nodeXXX.dot`, set `RUST_REGION_GRAPH=/path/desired.dot`; \n\ occurrences of the character `%` in the requested path will be replaced with\n\ the node id of the function under analysis. \n\ \n\ (Since you requested help via RUST_REGION_GRAPH=help, no region constraint \n\ graphs will be printed. \n\ "); } pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a, 'tcx>, subject_node: ast::NodeId) { let tcx = region_vars.tcx; if!region_vars.tcx.sess.opts.debugging_opts.print_region_graph { return; } let requested_node : Option<ast::NodeId> = env::var("RUST_REGION_GRAPH_NODE").ok().and_then(|s| s.parse().ok()); if requested_node.is_some() && requested_node!= Some(subject_node) { return; } let requested_output = env::var("RUST_REGION_GRAPH").ok(); debug!("requested_output: {:?} requested_node: {:?}", requested_output, requested_node); let output_path = { let output_template = match requested_output { Some(ref s) if &**s == "help" => { static PRINTED_YET: AtomicBool = ATOMIC_BOOL_INIT; if!PRINTED_YET.load(Ordering::SeqCst) { print_help_message(); PRINTED_YET.store(true, Ordering::SeqCst); } return; } Some(other_path) => other_path, None => "/tmp/constraints.node%.dot".to_string(), }; if output_template.len() == 0 { tcx.sess.bug("empty string provided as RUST_REGION_GRAPH"); } if output_template.contains_char('%') { let mut new_str = String::new(); for c in output_template.chars() { if c == '%' { new_str.push_str(&subject_node.to_string()); } else { new_str.push(c); } } new_str } else { output_template } }; let constraints = &*region_vars.constraints.borrow(); match dump_region_constraints_to(tcx, constraints, &output_path) { Ok(()) => {} Err(e) => { let msg = format!("io error dumping region constraints: {}", e); region_vars.tcx.sess.err(&msg) } } } struct ConstraintGraph<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx>, graph_name: String, map: &'a FnvHashMap<Constraint, SubregionOrigin<'tcx>>, node_ids: FnvHashMap<Node, uint>, } #[derive(Clone, Hash, PartialEq, Eq, Debug, Copy)] enum Node { RegionVid(ty::RegionVid), Region(ty::Region), } // type Edge = Constraint; #[derive(Clone, PartialEq, Eq, Debug, Copy)] enum Edge { Constraint(Constraint), EnclScope(CodeExtent, CodeExtent), } impl<'a, 'tcx> ConstraintGraph<'a, 'tcx> { fn new(tcx: &'a ty::ctxt<'tcx>, name: String, map: &'a ConstraintMap<'tcx>) -> ConstraintGraph<'a, 'tcx> { let mut i = 0; let mut node_ids = FnvHashMap(); { let mut add_node = |node| { if let Vacant(e) = node_ids.entry(node) { e.insert(i); i += 1; } }; for (n1, n2) in map.keys().map(|c|constraint_to_nodes(c)) { add_node(n1); add_node(n2); } tcx.region_maps.each_encl_scope(|sub, sup| { add_node(Node::Region(ty::ReScope(*sub))); add_node(Node::Region(ty::ReScope(*sup))); }); } ConstraintGraph { tcx: tcx, graph_name: name, map: map, node_ids: node_ids } } } impl<'a, 'tcx> dot::Labeller<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { fn graph_id(&self) -> dot::Id { dot::Id::new(&*self.graph_name).ok().unwrap() } fn node_id(&self, n: &Node) -> dot::Id { let node_id = match self.node_ids.get(n) { Some(node_id) => node_id, None => panic!("no node_id found for node: {:?}", n), }; let name = || format!("node_{}", node_id); match dot::Id::new(name()) { Ok(id) => id, Err(_) => { panic!("failed to create graphviz node identified by {}", name()); } } } fn node_label(&self, n: &Node) -> dot::LabelText
fn edge_label(&self, e: &Edge) -> dot::LabelText { match *e { Edge::Constraint(ref c) => dot::LabelText::label(format!("{}", self.map.get(c).unwrap().repr(self.tcx))), Edge::EnclScope(..) => dot::LabelText::label(format!("(enclosed)")), } } } fn constraint_to_nodes(c: &Constraint) -> (Node, Node) { match *c { Constraint::ConstrainVarSubVar(rv_1, rv_2) => (Node::RegionVid(rv_1), Node::RegionVid(rv_2)), Constraint::ConstrainRegSubVar(r_1, rv_2) => (Node::Region(r_1), Node::RegionVid(rv_2)), Constraint::ConstrainVarSubReg(rv_1, r_2) => (Node::RegionVid(rv_1), Node::Region(r_2)), } } fn edge_to_nodes(e: &Edge) -> (Node, Node) { match *e { Edge::Constraint(ref c) => constraint_to_nodes(c), Edge::EnclScope(sub, sup) => { (Node::Region(ty::ReScope(sub)), Node::Region(ty::ReScope(sup))) } } } impl<'a, 'tcx> dot::GraphWalk<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { fn nodes(&self) -> dot::Nodes<Node> { let mut set = FnvHashSet(); for node in self.node_ids.keys() { set.insert(*node); } debug!("constraint graph has {} nodes", set.len()); set.into_iter().collect() } fn edges(&self) -> dot::Edges<Edge> { debug!("constraint graph has {} edges", self.map.len()); let mut v : Vec<_> = self.map.keys().map(|e| Edge::Constraint(*e)).collect(); self.tcx.region_maps.each_encl_scope(|sub, sup| { v.push(Edge::EnclScope(*sub, *sup)) }); debug!("region graph has {} edges", v.len()); Cow::Owned(v) } fn source(&self, edge: &Edge) -> Node { let (n1, _) = edge_to_nodes(edge); debug!("edge {:?} has source {:?}", edge, n1); n1 } fn target(&self, edge: &Edge) -> Node { let (_, n2) = edge_to_nodes(edge); debug!("edge {:?} has target {:?}", edge, n2); n2 } } pub type ConstraintMap<'tcx> = FnvHashMap<Constraint, SubregionOrigin<'tcx>>; fn dump_region_constraints_to<'a, 'tcx:'a >(tcx: &'a ty::ctxt<'tcx>, map: &ConstraintMap<'tcx>, path: &str) -> old_io::IoResult<()> { debug!("dump_region_constraints map (len: {}) path: {}", map.len(), path); let g = ConstraintGraph::new(tcx, format!("region_constraints"), map); let mut f = File::create(&Path::new(path)); debug!("dump_region_constraints calling render"); dot::render(&g, &mut f) }
{ match *n { Node::RegionVid(n_vid) => dot::LabelText::label(format!("{:?}", n_vid)), Node::Region(n_rgn) => dot::LabelText::label(format!("{}", n_rgn.repr(self.tcx))), } }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(ascii)] #![feature(as_unsafe_cell)] #![feature(borrow_state)] #![feature(box_syntax)] #![feature(const_fn)] #![feature(core_intrinsics)] #![feature(custom_attribute)] #![feature(custom_derive)] #![feature(fnbox)] #![feature(mpsc_select)] #![feature(nonzero)] #![feature(on_unimplemented)] #![feature(peekable_is_empty)] #![feature(plugin)] #![feature(slice_patterns)] #![deny(unsafe_code)] #![allow(non_snake_case)] #![doc = "The script crate contains all matters DOM."] #![plugin(heapsize_plugin)] #![plugin(phf_macros)] #![plugin(plugins)] extern crate angle; extern crate app_units; #[macro_use] extern crate bitflags; extern crate canvas; extern crate canvas_traits; extern crate caseless; extern crate core; extern crate cssparser; extern crate devtools_traits; extern crate encoding; extern crate euclid; extern crate fnv; extern crate gfx_traits; extern crate heapsize; extern crate html5ever; extern crate hyper; extern crate image; extern crate ipc_channel; extern crate js; extern crate libc; #[macro_use] extern crate log; extern crate msg; extern crate net_traits; extern crate num; extern crate offscreen_gl_context; extern crate phf; #[macro_use] extern crate profile_traits; extern crate rand; extern crate ref_filter_map; extern crate ref_slice; extern crate regex; extern crate rustc_serialize; extern crate script_traits; extern crate selectors; extern crate serde; extern crate smallvec; #[macro_use(atom, ns)] extern crate string_cache; #[macro_use] extern crate style; extern crate time; extern crate unicase; extern crate url; #[macro_use] extern crate util; extern crate uuid; extern crate websocket; extern crate xml5ever; pub mod clipboard_provider; pub mod cors; mod devtools; pub mod document_loader; #[macro_use] pub mod dom; pub mod layout_interface; mod mem; mod network_listener; pub mod page; pub mod parse; pub mod reporter; #[allow(unsafe_code)] pub mod script_thread; mod task_source; pub mod textinput; mod timers; mod unpremultiplytable; mod webdriver_handlers; use dom::bindings::codegen::RegisterBindings; use js::jsapi::SetDOMProxyInformation; use std::ptr; #[cfg(target_os = "linux")] #[allow(unsafe_code)] fn perform_platform_specific_initialization() { use std::mem; // 4096 is default max on many linux systems const MAX_FILE_LIMIT: libc::rlim_t = 4096; // Bump up our number of file descriptors to save us from impending doom caused by an onslaught // of iframes. unsafe { let mut rlim: libc::rlimit = mem::uninitialized(); match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) { 0 => { if rlim.rlim_cur >= MAX_FILE_LIMIT { // we have more than enough return; } rlim.rlim_cur = match rlim.rlim_max { libc::RLIM_INFINITY => MAX_FILE_LIMIT, _ => { if rlim.rlim_max < MAX_FILE_LIMIT { rlim.rlim_max } else { MAX_FILE_LIMIT } } }; match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) { 0 => (), _ => warn!("Failed to set file count limit"), }; }, _ => warn!("Failed to get file count limit"), }; } } #[cfg(not(target_os = "linux"))] fn perform_platform_specific_initialization() {}
assert_eq!(js::jsapi::JS_Init(), true); SetDOMProxyInformation(ptr::null(), 0, Some(script_thread::shadow_check_callback)); } // Create the global vtables used by the (generated) DOM // bindings to implement JS proxies. RegisterBindings::RegisterProxyHandlers(); perform_platform_specific_initialization(); }
#[allow(unsafe_code)] pub fn init() { unsafe {
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(ascii)] #![feature(as_unsafe_cell)] #![feature(borrow_state)] #![feature(box_syntax)] #![feature(const_fn)] #![feature(core_intrinsics)] #![feature(custom_attribute)] #![feature(custom_derive)] #![feature(fnbox)] #![feature(mpsc_select)] #![feature(nonzero)] #![feature(on_unimplemented)] #![feature(peekable_is_empty)] #![feature(plugin)] #![feature(slice_patterns)] #![deny(unsafe_code)] #![allow(non_snake_case)] #![doc = "The script crate contains all matters DOM."] #![plugin(heapsize_plugin)] #![plugin(phf_macros)] #![plugin(plugins)] extern crate angle; extern crate app_units; #[macro_use] extern crate bitflags; extern crate canvas; extern crate canvas_traits; extern crate caseless; extern crate core; extern crate cssparser; extern crate devtools_traits; extern crate encoding; extern crate euclid; extern crate fnv; extern crate gfx_traits; extern crate heapsize; extern crate html5ever; extern crate hyper; extern crate image; extern crate ipc_channel; extern crate js; extern crate libc; #[macro_use] extern crate log; extern crate msg; extern crate net_traits; extern crate num; extern crate offscreen_gl_context; extern crate phf; #[macro_use] extern crate profile_traits; extern crate rand; extern crate ref_filter_map; extern crate ref_slice; extern crate regex; extern crate rustc_serialize; extern crate script_traits; extern crate selectors; extern crate serde; extern crate smallvec; #[macro_use(atom, ns)] extern crate string_cache; #[macro_use] extern crate style; extern crate time; extern crate unicase; extern crate url; #[macro_use] extern crate util; extern crate uuid; extern crate websocket; extern crate xml5ever; pub mod clipboard_provider; pub mod cors; mod devtools; pub mod document_loader; #[macro_use] pub mod dom; pub mod layout_interface; mod mem; mod network_listener; pub mod page; pub mod parse; pub mod reporter; #[allow(unsafe_code)] pub mod script_thread; mod task_source; pub mod textinput; mod timers; mod unpremultiplytable; mod webdriver_handlers; use dom::bindings::codegen::RegisterBindings; use js::jsapi::SetDOMProxyInformation; use std::ptr; #[cfg(target_os = "linux")] #[allow(unsafe_code)] fn perform_platform_specific_initialization() { use std::mem; // 4096 is default max on many linux systems const MAX_FILE_LIMIT: libc::rlim_t = 4096; // Bump up our number of file descriptors to save us from impending doom caused by an onslaught // of iframes. unsafe { let mut rlim: libc::rlimit = mem::uninitialized(); match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) { 0 => { if rlim.rlim_cur >= MAX_FILE_LIMIT { // we have more than enough return; } rlim.rlim_cur = match rlim.rlim_max { libc::RLIM_INFINITY => MAX_FILE_LIMIT, _ => { if rlim.rlim_max < MAX_FILE_LIMIT { rlim.rlim_max } else { MAX_FILE_LIMIT } } }; match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) { 0 => (), _ => warn!("Failed to set file count limit"), }; }, _ => warn!("Failed to get file count limit"), }; } } #[cfg(not(target_os = "linux"))] fn perform_platform_specific_initialization() {} #[allow(unsafe_code)] pub fn init()
{ unsafe { assert_eq!(js::jsapi::JS_Init(), true); SetDOMProxyInformation(ptr::null(), 0, Some(script_thread::shadow_check_callback)); } // Create the global vtables used by the (generated) DOM // bindings to implement JS proxies. RegisterBindings::RegisterProxyHandlers(); perform_platform_specific_initialization(); }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(ascii)] #![feature(as_unsafe_cell)] #![feature(borrow_state)] #![feature(box_syntax)] #![feature(const_fn)] #![feature(core_intrinsics)] #![feature(custom_attribute)] #![feature(custom_derive)] #![feature(fnbox)] #![feature(mpsc_select)] #![feature(nonzero)] #![feature(on_unimplemented)] #![feature(peekable_is_empty)] #![feature(plugin)] #![feature(slice_patterns)] #![deny(unsafe_code)] #![allow(non_snake_case)] #![doc = "The script crate contains all matters DOM."] #![plugin(heapsize_plugin)] #![plugin(phf_macros)] #![plugin(plugins)] extern crate angle; extern crate app_units; #[macro_use] extern crate bitflags; extern crate canvas; extern crate canvas_traits; extern crate caseless; extern crate core; extern crate cssparser; extern crate devtools_traits; extern crate encoding; extern crate euclid; extern crate fnv; extern crate gfx_traits; extern crate heapsize; extern crate html5ever; extern crate hyper; extern crate image; extern crate ipc_channel; extern crate js; extern crate libc; #[macro_use] extern crate log; extern crate msg; extern crate net_traits; extern crate num; extern crate offscreen_gl_context; extern crate phf; #[macro_use] extern crate profile_traits; extern crate rand; extern crate ref_filter_map; extern crate ref_slice; extern crate regex; extern crate rustc_serialize; extern crate script_traits; extern crate selectors; extern crate serde; extern crate smallvec; #[macro_use(atom, ns)] extern crate string_cache; #[macro_use] extern crate style; extern crate time; extern crate unicase; extern crate url; #[macro_use] extern crate util; extern crate uuid; extern crate websocket; extern crate xml5ever; pub mod clipboard_provider; pub mod cors; mod devtools; pub mod document_loader; #[macro_use] pub mod dom; pub mod layout_interface; mod mem; mod network_listener; pub mod page; pub mod parse; pub mod reporter; #[allow(unsafe_code)] pub mod script_thread; mod task_source; pub mod textinput; mod timers; mod unpremultiplytable; mod webdriver_handlers; use dom::bindings::codegen::RegisterBindings; use js::jsapi::SetDOMProxyInformation; use std::ptr; #[cfg(target_os = "linux")] #[allow(unsafe_code)] fn
() { use std::mem; // 4096 is default max on many linux systems const MAX_FILE_LIMIT: libc::rlim_t = 4096; // Bump up our number of file descriptors to save us from impending doom caused by an onslaught // of iframes. unsafe { let mut rlim: libc::rlimit = mem::uninitialized(); match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) { 0 => { if rlim.rlim_cur >= MAX_FILE_LIMIT { // we have more than enough return; } rlim.rlim_cur = match rlim.rlim_max { libc::RLIM_INFINITY => MAX_FILE_LIMIT, _ => { if rlim.rlim_max < MAX_FILE_LIMIT { rlim.rlim_max } else { MAX_FILE_LIMIT } } }; match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) { 0 => (), _ => warn!("Failed to set file count limit"), }; }, _ => warn!("Failed to get file count limit"), }; } } #[cfg(not(target_os = "linux"))] fn perform_platform_specific_initialization() {} #[allow(unsafe_code)] pub fn init() { unsafe { assert_eq!(js::jsapi::JS_Init(), true); SetDOMProxyInformation(ptr::null(), 0, Some(script_thread::shadow_check_callback)); } // Create the global vtables used by the (generated) DOM // bindings to implement JS proxies. RegisterBindings::RegisterProxyHandlers(); perform_platform_specific_initialization(); }
perform_platform_specific_initialization
identifier_name
cg_clif.rs
#![feature(rustc_private, once_cell)] extern crate rustc_data_structures; extern crate rustc_driver; extern crate rustc_interface; extern crate rustc_session; extern crate rustc_target; use std::lazy::SyncLazy; use std::panic; use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry}; use rustc_interface::interface; use rustc_session::config::ErrorOutputType; use rustc_session::early_error; use rustc_target::spec::PanicStrategy; const BUG_REPORT_URL: &str = "https://github.com/bjorn3/rustc_codegen_cranelift/issues/new"; static DEFAULT_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send +'static>> = SyncLazy::new(|| { let hook = panic::take_hook(); panic::set_hook(Box::new(|info| { // Invoke the default handler, which prints the actual panic message and optionally a backtrace (*DEFAULT_HOOK)(info); // Separate the output with an empty line eprintln!(); // Print the ICE message rustc_driver::report_ice(info, BUG_REPORT_URL); })); hook }); #[derive(Default)] pub struct CraneliftPassesCallbacks { time_passes: bool, } impl rustc_driver::Callbacks for CraneliftPassesCallbacks { fn config(&mut self, config: &mut interface::Config) { // If a --prints=... option has been given, we don't print the "total" // time because it will mess up the --prints output. See #64339. self.time_passes = config.opts.prints.is_empty() && (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time); config.opts.cg.panic = Some(PanicStrategy::Abort); config.opts.debugging_opts.panic_abort_tests = true; config.opts.maybe_sysroot = Some(config.opts.maybe_sysroot.clone().unwrap_or_else(|| { std::env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_owned() })); } } fn main() { let start_time = std::time::Instant::now(); let start_rss = get_resident_set_size(); rustc_driver::init_rustc_env_logger(); let mut callbacks = CraneliftPassesCallbacks::default(); SyncLazy::force(&DEFAULT_HOOK); // Install ice hook let exit_code = rustc_driver::catch_with_exit_code(|| { let args = std::env::args_os() .enumerate() .map(|(i, arg)| { arg.into_string().unwrap_or_else(|arg| { early_error( ErrorOutputType::default(), &format!("Argument {} is not valid Unicode: {:?}", i, arg), ) }) }) .collect::<Vec<_>>(); let mut run_compiler = rustc_driver::RunCompiler::new(&args, &mut callbacks); run_compiler.set_make_codegen_backend(Some(Box::new(move |_| { Box::new(rustc_codegen_cranelift::CraneliftCodegenBackend { config: None }) }))); run_compiler.run() }); if callbacks.time_passes { let end_rss = get_resident_set_size(); print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss);
}
} std::process::exit(exit_code)
random_line_split
cg_clif.rs
#![feature(rustc_private, once_cell)] extern crate rustc_data_structures; extern crate rustc_driver; extern crate rustc_interface; extern crate rustc_session; extern crate rustc_target; use std::lazy::SyncLazy; use std::panic; use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry}; use rustc_interface::interface; use rustc_session::config::ErrorOutputType; use rustc_session::early_error; use rustc_target::spec::PanicStrategy; const BUG_REPORT_URL: &str = "https://github.com/bjorn3/rustc_codegen_cranelift/issues/new"; static DEFAULT_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send +'static>> = SyncLazy::new(|| { let hook = panic::take_hook(); panic::set_hook(Box::new(|info| { // Invoke the default handler, which prints the actual panic message and optionally a backtrace (*DEFAULT_HOOK)(info); // Separate the output with an empty line eprintln!(); // Print the ICE message rustc_driver::report_ice(info, BUG_REPORT_URL); })); hook }); #[derive(Default)] pub struct
{ time_passes: bool, } impl rustc_driver::Callbacks for CraneliftPassesCallbacks { fn config(&mut self, config: &mut interface::Config) { // If a --prints=... option has been given, we don't print the "total" // time because it will mess up the --prints output. See #64339. self.time_passes = config.opts.prints.is_empty() && (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time); config.opts.cg.panic = Some(PanicStrategy::Abort); config.opts.debugging_opts.panic_abort_tests = true; config.opts.maybe_sysroot = Some(config.opts.maybe_sysroot.clone().unwrap_or_else(|| { std::env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_owned() })); } } fn main() { let start_time = std::time::Instant::now(); let start_rss = get_resident_set_size(); rustc_driver::init_rustc_env_logger(); let mut callbacks = CraneliftPassesCallbacks::default(); SyncLazy::force(&DEFAULT_HOOK); // Install ice hook let exit_code = rustc_driver::catch_with_exit_code(|| { let args = std::env::args_os() .enumerate() .map(|(i, arg)| { arg.into_string().unwrap_or_else(|arg| { early_error( ErrorOutputType::default(), &format!("Argument {} is not valid Unicode: {:?}", i, arg), ) }) }) .collect::<Vec<_>>(); let mut run_compiler = rustc_driver::RunCompiler::new(&args, &mut callbacks); run_compiler.set_make_codegen_backend(Some(Box::new(move |_| { Box::new(rustc_codegen_cranelift::CraneliftCodegenBackend { config: None }) }))); run_compiler.run() }); if callbacks.time_passes { let end_rss = get_resident_set_size(); print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss); } std::process::exit(exit_code) }
CraneliftPassesCallbacks
identifier_name
cg_clif.rs
#![feature(rustc_private, once_cell)] extern crate rustc_data_structures; extern crate rustc_driver; extern crate rustc_interface; extern crate rustc_session; extern crate rustc_target; use std::lazy::SyncLazy; use std::panic; use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry}; use rustc_interface::interface; use rustc_session::config::ErrorOutputType; use rustc_session::early_error; use rustc_target::spec::PanicStrategy; const BUG_REPORT_URL: &str = "https://github.com/bjorn3/rustc_codegen_cranelift/issues/new"; static DEFAULT_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send +'static>> = SyncLazy::new(|| { let hook = panic::take_hook(); panic::set_hook(Box::new(|info| { // Invoke the default handler, which prints the actual panic message and optionally a backtrace (*DEFAULT_HOOK)(info); // Separate the output with an empty line eprintln!(); // Print the ICE message rustc_driver::report_ice(info, BUG_REPORT_URL); })); hook }); #[derive(Default)] pub struct CraneliftPassesCallbacks { time_passes: bool, } impl rustc_driver::Callbacks for CraneliftPassesCallbacks { fn config(&mut self, config: &mut interface::Config) { // If a --prints=... option has been given, we don't print the "total" // time because it will mess up the --prints output. See #64339. self.time_passes = config.opts.prints.is_empty() && (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time); config.opts.cg.panic = Some(PanicStrategy::Abort); config.opts.debugging_opts.panic_abort_tests = true; config.opts.maybe_sysroot = Some(config.opts.maybe_sysroot.clone().unwrap_or_else(|| { std::env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_owned() })); } } fn main()
Box::new(rustc_codegen_cranelift::CraneliftCodegenBackend { config: None }) }))); run_compiler.run() }); if callbacks.time_passes { let end_rss = get_resident_set_size(); print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss); } std::process::exit(exit_code) }
{ let start_time = std::time::Instant::now(); let start_rss = get_resident_set_size(); rustc_driver::init_rustc_env_logger(); let mut callbacks = CraneliftPassesCallbacks::default(); SyncLazy::force(&DEFAULT_HOOK); // Install ice hook let exit_code = rustc_driver::catch_with_exit_code(|| { let args = std::env::args_os() .enumerate() .map(|(i, arg)| { arg.into_string().unwrap_or_else(|arg| { early_error( ErrorOutputType::default(), &format!("Argument {} is not valid Unicode: {:?}", i, arg), ) }) }) .collect::<Vec<_>>(); let mut run_compiler = rustc_driver::RunCompiler::new(&args, &mut callbacks); run_compiler.set_make_codegen_backend(Some(Box::new(move |_| {
identifier_body
cg_clif.rs
#![feature(rustc_private, once_cell)] extern crate rustc_data_structures; extern crate rustc_driver; extern crate rustc_interface; extern crate rustc_session; extern crate rustc_target; use std::lazy::SyncLazy; use std::panic; use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry}; use rustc_interface::interface; use rustc_session::config::ErrorOutputType; use rustc_session::early_error; use rustc_target::spec::PanicStrategy; const BUG_REPORT_URL: &str = "https://github.com/bjorn3/rustc_codegen_cranelift/issues/new"; static DEFAULT_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send +'static>> = SyncLazy::new(|| { let hook = panic::take_hook(); panic::set_hook(Box::new(|info| { // Invoke the default handler, which prints the actual panic message and optionally a backtrace (*DEFAULT_HOOK)(info); // Separate the output with an empty line eprintln!(); // Print the ICE message rustc_driver::report_ice(info, BUG_REPORT_URL); })); hook }); #[derive(Default)] pub struct CraneliftPassesCallbacks { time_passes: bool, } impl rustc_driver::Callbacks for CraneliftPassesCallbacks { fn config(&mut self, config: &mut interface::Config) { // If a --prints=... option has been given, we don't print the "total" // time because it will mess up the --prints output. See #64339. self.time_passes = config.opts.prints.is_empty() && (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time); config.opts.cg.panic = Some(PanicStrategy::Abort); config.opts.debugging_opts.panic_abort_tests = true; config.opts.maybe_sysroot = Some(config.opts.maybe_sysroot.clone().unwrap_or_else(|| { std::env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_owned() })); } } fn main() { let start_time = std::time::Instant::now(); let start_rss = get_resident_set_size(); rustc_driver::init_rustc_env_logger(); let mut callbacks = CraneliftPassesCallbacks::default(); SyncLazy::force(&DEFAULT_HOOK); // Install ice hook let exit_code = rustc_driver::catch_with_exit_code(|| { let args = std::env::args_os() .enumerate() .map(|(i, arg)| { arg.into_string().unwrap_or_else(|arg| { early_error( ErrorOutputType::default(), &format!("Argument {} is not valid Unicode: {:?}", i, arg), ) }) }) .collect::<Vec<_>>(); let mut run_compiler = rustc_driver::RunCompiler::new(&args, &mut callbacks); run_compiler.set_make_codegen_backend(Some(Box::new(move |_| { Box::new(rustc_codegen_cranelift::CraneliftCodegenBackend { config: None }) }))); run_compiler.run() }); if callbacks.time_passes
std::process::exit(exit_code) }
{ let end_rss = get_resident_set_size(); print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss); }
conditional_block
sysex.rs
// This file is part of a6-tools. // Copyright (C) 2017 Jeffrey Sharp // // a6-tools is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // a6-tools is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See // the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with a6-tools. If not, see <http://www.gnu.org/licenses/>. use std::cmp; use std::io; use std::io::prelude::*; use io::*; use self::SysExReadError::*; // MIDI byte ranges const DATA_MIN: u8 = 0x00; // \_ Data bytes const DATA_MAX: u8 = 0x7F; // / const STATUS_MIN: u8 = 0x80; // \_ Status bytes const STATUS_MAX: u8 = 0xEF; // / const SYSEX_START: u8 = 0xF0; // \_ System exlusive messages const SYSEX_END: u8 = 0xF7; // / const SYSCOM_MIN: u8 = 0xF1; // \_ System common messages const SYSCOM_MAX: u8 = 0xF6; // / const SYSRT_MIN: u8 = 0xF8; // \_ System real-time messages const SYSRT_MAX: u8 = 0xFF; // / // Masks const ALL_BITS: u8 = 0xFF; const STATUS_BIT: u8 = 0x80; /// Consumes the given `input` stream and detects MIDI System Exclusive messages /// of length `cap` or less. Invokes the handler `on_msg` for each detected /// message and the handler `on_err` for each error condition. pub fn read_sysex<R, M, E>( input: &mut R, cap: usize, on_msg: M, on_err: E, ) -> io::Result<bool> where R: BufRead, M: Fn(usize, &[u8]) -> bool, E: Fn(usize, usize, SysExReadError) -> bool, { let mut start = 0; // Start position of message or skipped chunk let mut next = 0; // Position of next unread byte let mut len = 0; // Length of message data (no start/end bytes) or skipped chunk (all bytes) // Message data, without SysEx start/end bytes let mut buf = vec![0u8; cap].into_boxed_slice(); // Helper for invoking the on_msg/on_err handlers macro_rules! fire { ($fn:ident, $($arg:expr),+) => { if!$fn($($arg),+) { return Ok(false) } } } loop { // State A: Not In SysEx Message { let (read, found) = input.skip_until_bits(SYSEX_START, ALL_BITS)?; next += read; let end = match found { Some(_) => next - 1, None => next, }; let len = end - start; if len!= 0 { fire!(on_err, start, len, NotSysEx); } match found { Some(_) => start = end, None => return Ok(true), } } // State B: In SysEx Message len = 0; loop { let idx = cmp::min(len, cap); let (read, found) = input.read_until_bits(STATUS_BIT, STATUS_BIT, &mut buf[idx..])?; next += read; match found { Some(SYSRT_MIN...SYSRT_MAX) => { len += read - 1; // remain in state B }, Some(SYSEX_START) => { let end = next - 1; fire!(on_err, start, end - start, UnexpectedByte); start = end; len = 0; // restart state B }, Some(SYSEX_END) => { len += read - 1; if len > cap { fire!(on_err, start, next - start, Overflow) } else { fire!(on_msg, start, &buf[..len]) } start = next; break // to state A }, Some(_) => { let end = next - 1; fire!(on_err, start, end - start, UnexpectedByte); start = end; break // to State A }, None => { fire!(on_err, start, next - start, UnexpectedEof); return Ok(true) } } } } Ok(true) } /// Possible error conditions encountered by `read_sysex`. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum SysExReadError { /// The bytes did not contain a System Exclusive message. NotSysEx, /// A System Exclusive message exceeded the maximum allowed length. Overflow, /// A System Exclusive message was interrupted by an unexpected byte. UnexpectedByte, /// A System Exclusive message was interrupted by end-of-file. UnexpectedEof, } /// Encodes a sequence of bytes into a sequence of 7-bit values. pub fn encode_7bit(src: &[u8], dst: &mut Vec<u8>) { // Iteration // | Leftover bits // | | 7-bit output // | | | // 0:........ 00000000 -> yield 7 bits // 1:.......1 11111110 -> yield 7 bits // 2:......22 22222211 -> yield 7 bits // 3:.....333 33333222 -> yield 7 bits // 4:....4444 44443333 -> yield 7 bits // 5:...55555 55544444 -> yield 7 bits // 6:..666666 66555555 -> yield 7 bits, then // .........6666666 -> yield 7 bits again // 7: (repeats) let mut data = 0u16; // a shift register where bytes become bits let mut bits = 0; // how many leftover bits from previous iteration
for v in src { // Add 8 input bits. data |= (*v as u16) << bits; // Yield 7 bits. Accrue 1 leftover bit for next iteration. dst.push((data & 0x7F) as u8); data >>= 7; bits += 1; // Every 7 iterations, 7 leftover bits have accrued. // Consume them to yield another 7-bit output. if bits == 7 { dst.push((data & 0x7F) as u8); data = 0; bits = 0; } } // Yield final leftover bits, if any. if bits > 0 { dst.push((data & 0x7F) as u8); } } /// Decodes a sequence of 7-bit values into a sequence of bytes. pub fn decode_7bit(src: &[u8], dst: &mut Vec<u8>) { // Iteration // | Leftover bits // | | Byte output // | | | // 0:.........0000000 (not enough bits for a byte) // 1:..111111 10000000 -> yield byte // 2:...22222 22111111 -> yield byte // 3:....3333 33322222 -> yield byte // 4:.....444 44443333 -> yield byte // 5:......55 55555444 -> yield byte // 6:.......6 66666655 -> yield byte // 7:........ 77777776 -> yield byte // 8: (repeats) let mut data = 0u16; // a shift register where bits become bytes let mut bits = 0; // how many leftover bits from previous iteration for v in src { // Isolate 7 input bits. let v = (*v & 0x7F) as u16; if bits == 0 { // Initially, and after every 8 iterations, there are no leftover // bits from the previous iteration. With only 7 new bits, there // aren't enough to make a byte. Just let those bits become the // leftovers for the next iteration. data = v; bits = 7; } else { // For other iterations, there are leftover bits from the previous // iteration. Consider those as least significant, and the 7 new // bits as most significant, and yield a byte. Any unused bits // become leftovers for the next iteration to use. data |= v << bits; dst.push((data & 0xFF) as u8); data >>= 8; bits -= 1; } } } #[cfg(test)] mod tests { use super::*; use self::ReadEvent::*; #[derive(Clone, PartialEq, Eq, Debug)] enum ReadEvent { Message { pos: usize, msg: Vec<u8> }, Error { pos: usize, len: usize, err: SysExReadError }, } fn run_read(mut bytes: &[u8], cap: usize) -> Vec<ReadEvent> { use std::cell::RefCell; let events = RefCell::new(vec![]); let result = read_sysex( &mut bytes, cap, |pos, msg| { events.borrow_mut().push(Message { pos, msg: msg.to_vec() }); true }, |pos, len, err| { events.borrow_mut().push(Error { pos, len, err }); true }, ); assert!(result.unwrap()); events.into_inner() } #[test] fn test_read_sysex_empty() { let events = run_read(b"", 10); assert_eq!(events.len(), 0); } #[test] fn test_read_sysex_junk() { let events = run_read(b"any", 10); assert_eq!(events.len(), 1); assert_eq!(events[0], Error { pos: 0, len: 3, err: NotSysEx }); } #[test] fn test_read_sysex_sysex() { let events = run_read(b"\xF0msg\xF7", 10); assert_eq!(events.len(), 1); assert_eq!(events[0], Message { pos: 0, msg: b"msg".to_vec() }); } #[test] fn test_read_sysex_with_junk() { let events = run_read(b"abc\xF0def\xF7ghi\xF0jkl\xF7mno", 10); assert_eq!(events.len(), 5); assert_eq!(events[0], Error { pos: 0, len: 3, err: NotSysEx }); assert_eq!(events[1], Message { pos: 3, msg: b"def".to_vec() }); assert_eq!(events[2], Error { pos: 8, len: 3, err: NotSysEx }); assert_eq!(events[3], Message { pos: 11, msg: b"jkl".to_vec() }); assert_eq!(events[4], Error { pos: 16, len: 3, err: NotSysEx }); } #[test] fn test_read_sysex_with_sysrt() { let events = run_read(b"\xF0abc\xF8def\xF7", 10); assert_eq!(events.len(), 1); assert_eq!(events[0], Message { pos: 0, msg: b"abcdef".to_vec() }); } #[test] fn test_read_sysex_interrupted_by_sysex() { let events = run_read(b"\xF0abc\xF0def\xF7", 10); assert_eq!(events.len(), 2); assert_eq!(events[0], Error { pos: 0, len: 4, err: UnexpectedByte }); assert_eq!(events[1], Message { pos: 4, msg: b"def".to_vec() }); } #[test] fn test_read_sysex_interrupted_by_status() { let events = run_read(b"\xF0abc\xA5def\xF7", 10); assert_eq!(events.len(), 2); assert_eq!(events[0], Error { pos: 0, len: 4, err: UnexpectedByte }); assert_eq!(events[1], Error { pos: 4, len: 5, err: NotSysEx }); } #[test] fn test_read_sysex_interrupted_by_eof() { let events = run_read(b"\xF0abc", 10); assert_eq!(events.len(), 1); assert_eq!(events[0], Error { pos: 0, len: 4, err: UnexpectedEof }); } #[test] fn test_read_sysex_overflow() { let events = run_read(b"\xF0abc\xF7", 2); assert_eq!(events.len(), 1); assert_eq!(events[0], Error { pos: 0, len: 5, err: Overflow }); } #[test] fn test_read_sysex_overflow_2() { let events = run_read(b"\xF0abc\xF8def\xF7", 2); assert_eq!(events.len(), 1); assert_eq!(events[0], Error { pos: 0, len: 9, err: Overflow }); } #[test] fn test_encode_7bit() { let data8 = [ 0xF1, 0xE2, 0xD3, 0xC4, 0xB5, 0xA6, 0x97, 0x88, 0x79, 0x6A, ]; let mut data7 = vec![]; encode_7bit(&data8, &mut data7); assert_eq!(data7.len(), 12); // always 0 // | new bits // | | leftover bits // | | | // 0b_x_xxxx_xxx assert_eq!(data7[ 0], 0b_0_1110001_); assert_eq!(data7[ 1], 0b_0_100010_1); assert_eq!(data7[ 2], 0b_0_10011_11); assert_eq!(data7[ 3], 0b_0_0100_110); assert_eq!(data7[ 4], 0b_0_101_1100); assert_eq!(data7[ 5], 0b_0_10_10110); assert_eq!(data7[ 6], 0b_0_1_101001); assert_eq!(data7[ 7], 0b_0__1001011); assert_eq!(data7[ 8], 0b_0_0001000_); assert_eq!(data7[ 9], 0b_0_111001_1); assert_eq!(data7[10], 0b_0_01010_01); assert_eq!(data7[11], 0b_0_0000_011); // | | // | final leftover bits // 0-padding } #[test] fn test_decode_7bit() { let data7 = [ // don't care // | leftover bits // | | new bits // | | | // 0b_x_xxxx_xxx 0b_1_1110001_, 0b_0_100010_1, 0b_1_10011_11, 0b_0_0100_110, 0b_1_101_1100, 0b_0_10_10110, 0b_1_1_101001, 0b_0__1001011, 0b_1_0001000_, 0b_0_111001_1, 0b_1_01010_01, 0b_0_1111_011, ]; let mut data8 = vec![]; decode_7bit(&data7, &mut data8); assert_eq!(data8.len(), 10); assert_eq!(data8[0], 0xF1); assert_eq!(data8[1], 0xE2); assert_eq!(data8[2], 0xD3); assert_eq!(data8[3], 0xC4); assert_eq!(data8[4], 0xB5); assert_eq!(data8[5], 0xA6); assert_eq!(data8[6], 0x97); assert_eq!(data8[7], 0x88); assert_eq!(data8[8], 0x79); assert_eq!(data8[9], 0x6A); // Final leftover 4 bits go unused. } }
random_line_split
sysex.rs
// This file is part of a6-tools. // Copyright (C) 2017 Jeffrey Sharp // // a6-tools is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // a6-tools is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See // the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with a6-tools. If not, see <http://www.gnu.org/licenses/>. use std::cmp; use std::io; use std::io::prelude::*; use io::*; use self::SysExReadError::*; // MIDI byte ranges const DATA_MIN: u8 = 0x00; // \_ Data bytes const DATA_MAX: u8 = 0x7F; // / const STATUS_MIN: u8 = 0x80; // \_ Status bytes const STATUS_MAX: u8 = 0xEF; // / const SYSEX_START: u8 = 0xF0; // \_ System exlusive messages const SYSEX_END: u8 = 0xF7; // / const SYSCOM_MIN: u8 = 0xF1; // \_ System common messages const SYSCOM_MAX: u8 = 0xF6; // / const SYSRT_MIN: u8 = 0xF8; // \_ System real-time messages const SYSRT_MAX: u8 = 0xFF; // / // Masks const ALL_BITS: u8 = 0xFF; const STATUS_BIT: u8 = 0x80; /// Consumes the given `input` stream and detects MIDI System Exclusive messages /// of length `cap` or less. Invokes the handler `on_msg` for each detected /// message and the handler `on_err` for each error condition. pub fn read_sysex<R, M, E>( input: &mut R, cap: usize, on_msg: M, on_err: E, ) -> io::Result<bool> where R: BufRead, M: Fn(usize, &[u8]) -> bool, E: Fn(usize, usize, SysExReadError) -> bool, { let mut start = 0; // Start position of message or skipped chunk let mut next = 0; // Position of next unread byte let mut len = 0; // Length of message data (no start/end bytes) or skipped chunk (all bytes) // Message data, without SysEx start/end bytes let mut buf = vec![0u8; cap].into_boxed_slice(); // Helper for invoking the on_msg/on_err handlers macro_rules! fire { ($fn:ident, $($arg:expr),+) => { if!$fn($($arg),+) { return Ok(false) } } } loop { // State A: Not In SysEx Message { let (read, found) = input.skip_until_bits(SYSEX_START, ALL_BITS)?; next += read; let end = match found { Some(_) => next - 1, None => next, }; let len = end - start; if len!= 0 { fire!(on_err, start, len, NotSysEx); } match found { Some(_) => start = end, None => return Ok(true), } } // State B: In SysEx Message len = 0; loop { let idx = cmp::min(len, cap); let (read, found) = input.read_until_bits(STATUS_BIT, STATUS_BIT, &mut buf[idx..])?; next += read; match found { Some(SYSRT_MIN...SYSRT_MAX) => { len += read - 1; // remain in state B }, Some(SYSEX_START) => { let end = next - 1; fire!(on_err, start, end - start, UnexpectedByte); start = end; len = 0; // restart state B }, Some(SYSEX_END) => { len += read - 1; if len > cap
else { fire!(on_msg, start, &buf[..len]) } start = next; break // to state A }, Some(_) => { let end = next - 1; fire!(on_err, start, end - start, UnexpectedByte); start = end; break // to State A }, None => { fire!(on_err, start, next - start, UnexpectedEof); return Ok(true) } } } } Ok(true) } /// Possible error conditions encountered by `read_sysex`. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum SysExReadError { /// The bytes did not contain a System Exclusive message. NotSysEx, /// A System Exclusive message exceeded the maximum allowed length. Overflow, /// A System Exclusive message was interrupted by an unexpected byte. UnexpectedByte, /// A System Exclusive message was interrupted by end-of-file. UnexpectedEof, } /// Encodes a sequence of bytes into a sequence of 7-bit values. pub fn encode_7bit(src: &[u8], dst: &mut Vec<u8>) { // Iteration // | Leftover bits // | | 7-bit output // | | | // 0:........ 00000000 -> yield 7 bits // 1:.......1 11111110 -> yield 7 bits // 2:......22 22222211 -> yield 7 bits // 3:.....333 33333222 -> yield 7 bits // 4:....4444 44443333 -> yield 7 bits // 5:...55555 55544444 -> yield 7 bits // 6:..666666 66555555 -> yield 7 bits, then // .........6666666 -> yield 7 bits again // 7: (repeats) let mut data = 0u16; // a shift register where bytes become bits let mut bits = 0; // how many leftover bits from previous iteration for v in src { // Add 8 input bits. data |= (*v as u16) << bits; // Yield 7 bits. Accrue 1 leftover bit for next iteration. dst.push((data & 0x7F) as u8); data >>= 7; bits += 1; // Every 7 iterations, 7 leftover bits have accrued. // Consume them to yield another 7-bit output. if bits == 7 { dst.push((data & 0x7F) as u8); data = 0; bits = 0; } } // Yield final leftover bits, if any. if bits > 0 { dst.push((data & 0x7F) as u8); } } /// Decodes a sequence of 7-bit values into a sequence of bytes. pub fn decode_7bit(src: &[u8], dst: &mut Vec<u8>) { // Iteration // | Leftover bits // | | Byte output // | | | // 0:.........0000000 (not enough bits for a byte) // 1:..111111 10000000 -> yield byte // 2:...22222 22111111 -> yield byte // 3:....3333 33322222 -> yield byte // 4:.....444 44443333 -> yield byte // 5:......55 55555444 -> yield byte // 6:.......6 66666655 -> yield byte // 7:........ 77777776 -> yield byte // 8: (repeats) let mut data = 0u16; // a shift register where bits become bytes let mut bits = 0; // how many leftover bits from previous iteration for v in src { // Isolate 7 input bits. let v = (*v & 0x7F) as u16; if bits == 0 { // Initially, and after every 8 iterations, there are no leftover // bits from the previous iteration. With only 7 new bits, there // aren't enough to make a byte. Just let those bits become the // leftovers for the next iteration. data = v; bits = 7; } else { // For other iterations, there are leftover bits from the previous // iteration. Consider those as least significant, and the 7 new // bits as most significant, and yield a byte. Any unused bits // become leftovers for the next iteration to use. data |= v << bits; dst.push((data & 0xFF) as u8); data >>= 8; bits -= 1; } } } #[cfg(test)] mod tests { use super::*; use self::ReadEvent::*; #[derive(Clone, PartialEq, Eq, Debug)] enum ReadEvent { Message { pos: usize, msg: Vec<u8> }, Error { pos: usize, len: usize, err: SysExReadError }, } fn run_read(mut bytes: &[u8], cap: usize) -> Vec<ReadEvent> { use std::cell::RefCell; let events = RefCell::new(vec![]); let result = read_sysex( &mut bytes, cap, |pos, msg| { events.borrow_mut().push(Message { pos, msg: msg.to_vec() }); true }, |pos, len, err| { events.borrow_mut().push(Error { pos, len, err }); true }, ); assert!(result.unwrap()); events.into_inner() } #[test] fn test_read_sysex_empty() { let events = run_read(b"", 10); assert_eq!(events.len(), 0); } #[test] fn test_read_sysex_junk() { let events = run_read(b"any", 10); assert_eq!(events.len(), 1); assert_eq!(events[0], Error { pos: 0, len: 3, err: NotSysEx }); } #[test] fn test_read_sysex_sysex() { let events = run_read(b"\xF0msg\xF7", 10); assert_eq!(events.len(), 1); assert_eq!(events[0], Message { pos: 0, msg: b"msg".to_vec() }); } #[test] fn test_read_sysex_with_junk() { let events = run_read(b"abc\xF0def\xF7ghi\xF0jkl\xF7mno", 10); assert_eq!(events.len(), 5); assert_eq!(events[0], Error { pos: 0, len: 3, err: NotSysEx }); assert_eq!(events[1], Message { pos: 3, msg: b"def".to_vec() }); assert_eq!(events[2], Error { pos: 8, len: 3, err: NotSysEx }); assert_eq!(events[3], Message { pos: 11, msg: b"jkl".to_vec() }); assert_eq!(events[4], Error { pos: 16, len: 3, err: NotSysEx }); } #[test] fn test_read_sysex_with_sysrt() { let events = run_read(b"\xF0abc\xF8def\xF7", 10); assert_eq!(events.len(), 1); assert_eq!(events[0], Message { pos: 0, msg: b"abcdef".to_vec() }); } #[test] fn test_read_sysex_interrupted_by_sysex() { let events = run_read(b"\xF0abc\xF0def\xF7", 10); assert_eq!(events.len(), 2); assert_eq!(events[0], Error { pos: 0, len: 4, err: UnexpectedByte }); assert_eq!(events[1], Message { pos: 4, msg: b"def".to_vec() }); } #[test] fn test_read_sysex_interrupted_by_status() { let events = run_read(b"\xF0abc\xA5def\xF7", 10); assert_eq!(events.len(), 2); assert_eq!(events[0], Error { pos: 0, len: 4, err: UnexpectedByte }); assert_eq!(events[1], Error { pos: 4, len: 5, err: NotSysEx }); } #[test] fn test_read_sysex_interrupted_by_eof() { let events = run_read(b"\xF0abc", 10); assert_eq!(events.len(), 1); assert_eq!(events[0], Error { pos: 0, len: 4, err: UnexpectedEof }); } #[test] fn test_read_sysex_overflow() { let events = run_read(b"\xF0abc\xF7", 2); assert_eq!(events.len(), 1); assert_eq!(events[0], Error { pos: 0, len: 5, err: Overflow }); } #[test] fn test_read_sysex_overflow_2() { let events = run_read(b"\xF0abc\xF8def\xF7", 2); assert_eq!(events.len(), 1); assert_eq!(events[0], Error { pos: 0, len: 9, err: Overflow }); } #[test] fn test_encode_7bit() { let data8 = [ 0xF1, 0xE2, 0xD3, 0xC4, 0xB5, 0xA6, 0x97, 0x88, 0x79, 0x6A, ]; let mut data7 = vec![]; encode_7bit(&data8, &mut data7); assert_eq!(data7.len(), 12); // always 0 // | new bits // | | leftover bits // | | | // 0b_x_xxxx_xxx assert_eq!(data7[ 0], 0b_0_1110001_); assert_eq!(data7[ 1], 0b_0_100010_1); assert_eq!(data7[ 2], 0b_0_10011_11); assert_eq!(data7[ 3], 0b_0_0100_110); assert_eq!(data7[ 4], 0b_0_101_1100); assert_eq!(data7[ 5], 0b_0_10_10110); assert_eq!(data7[ 6], 0b_0_1_101001); assert_eq!(data7[ 7], 0b_0__1001011); assert_eq!(data7[ 8], 0b_0_0001000_); assert_eq!(data7[ 9], 0b_0_111001_1); assert_eq!(data7[10], 0b_0_01010_01); assert_eq!(data7[11], 0b_0_0000_011); // | | // | final leftover bits // 0-padding } #[test] fn test_decode_7bit() { let data7 = [ // don't care // | leftover bits // | | new bits // | | | // 0b_x_xxxx_xxx 0b_1_1110001_, 0b_0_100010_1, 0b_1_10011_11, 0b_0_0100_110, 0b_1_101_1100, 0b_0_10_10110, 0b_1_1_101001, 0b_0__1001011, 0b_1_0001000_, 0b_0_111001_1, 0b_1_01010_01, 0b_0_1111_011, ]; let mut data8 = vec![]; decode_7bit(&data7, &mut data8); assert_eq!(data8.len(), 10); assert_eq!(data8[0], 0xF1); assert_eq!(data8[1], 0xE2); assert_eq!(data8[2], 0xD3); assert_eq!(data8[3], 0xC4); assert_eq!(data8[4], 0xB5); assert_eq!(data8[5], 0xA6); assert_eq!(data8[6], 0x97); assert_eq!(data8[7], 0x88); assert_eq!(data8[8], 0x79); assert_eq!(data8[9], 0x6A); // Final leftover 4 bits go unused. } }
{ fire!(on_err, start, next - start, Overflow) }
conditional_block
sysex.rs
// This file is part of a6-tools. // Copyright (C) 2017 Jeffrey Sharp // // a6-tools is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // a6-tools is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See // the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with a6-tools. If not, see <http://www.gnu.org/licenses/>. use std::cmp; use std::io; use std::io::prelude::*; use io::*; use self::SysExReadError::*; // MIDI byte ranges const DATA_MIN: u8 = 0x00; // \_ Data bytes const DATA_MAX: u8 = 0x7F; // / const STATUS_MIN: u8 = 0x80; // \_ Status bytes const STATUS_MAX: u8 = 0xEF; // / const SYSEX_START: u8 = 0xF0; // \_ System exlusive messages const SYSEX_END: u8 = 0xF7; // / const SYSCOM_MIN: u8 = 0xF1; // \_ System common messages const SYSCOM_MAX: u8 = 0xF6; // / const SYSRT_MIN: u8 = 0xF8; // \_ System real-time messages const SYSRT_MAX: u8 = 0xFF; // / // Masks const ALL_BITS: u8 = 0xFF; const STATUS_BIT: u8 = 0x80; /// Consumes the given `input` stream and detects MIDI System Exclusive messages /// of length `cap` or less. Invokes the handler `on_msg` for each detected /// message and the handler `on_err` for each error condition. pub fn read_sysex<R, M, E>( input: &mut R, cap: usize, on_msg: M, on_err: E, ) -> io::Result<bool> where R: BufRead, M: Fn(usize, &[u8]) -> bool, E: Fn(usize, usize, SysExReadError) -> bool, { let mut start = 0; // Start position of message or skipped chunk let mut next = 0; // Position of next unread byte let mut len = 0; // Length of message data (no start/end bytes) or skipped chunk (all bytes) // Message data, without SysEx start/end bytes let mut buf = vec![0u8; cap].into_boxed_slice(); // Helper for invoking the on_msg/on_err handlers macro_rules! fire { ($fn:ident, $($arg:expr),+) => { if!$fn($($arg),+) { return Ok(false) } } } loop { // State A: Not In SysEx Message { let (read, found) = input.skip_until_bits(SYSEX_START, ALL_BITS)?; next += read; let end = match found { Some(_) => next - 1, None => next, }; let len = end - start; if len!= 0 { fire!(on_err, start, len, NotSysEx); } match found { Some(_) => start = end, None => return Ok(true), } } // State B: In SysEx Message len = 0; loop { let idx = cmp::min(len, cap); let (read, found) = input.read_until_bits(STATUS_BIT, STATUS_BIT, &mut buf[idx..])?; next += read; match found { Some(SYSRT_MIN...SYSRT_MAX) => { len += read - 1; // remain in state B }, Some(SYSEX_START) => { let end = next - 1; fire!(on_err, start, end - start, UnexpectedByte); start = end; len = 0; // restart state B }, Some(SYSEX_END) => { len += read - 1; if len > cap { fire!(on_err, start, next - start, Overflow) } else { fire!(on_msg, start, &buf[..len]) } start = next; break // to state A }, Some(_) => { let end = next - 1; fire!(on_err, start, end - start, UnexpectedByte); start = end; break // to State A }, None => { fire!(on_err, start, next - start, UnexpectedEof); return Ok(true) } } } } Ok(true) } /// Possible error conditions encountered by `read_sysex`. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum SysExReadError { /// The bytes did not contain a System Exclusive message. NotSysEx, /// A System Exclusive message exceeded the maximum allowed length. Overflow, /// A System Exclusive message was interrupted by an unexpected byte. UnexpectedByte, /// A System Exclusive message was interrupted by end-of-file. UnexpectedEof, } /// Encodes a sequence of bytes into a sequence of 7-bit values. pub fn encode_7bit(src: &[u8], dst: &mut Vec<u8>) { // Iteration // | Leftover bits // | | 7-bit output // | | | // 0:........ 00000000 -> yield 7 bits // 1:.......1 11111110 -> yield 7 bits // 2:......22 22222211 -> yield 7 bits // 3:.....333 33333222 -> yield 7 bits // 4:....4444 44443333 -> yield 7 bits // 5:...55555 55544444 -> yield 7 bits // 6:..666666 66555555 -> yield 7 bits, then // .........6666666 -> yield 7 bits again // 7: (repeats) let mut data = 0u16; // a shift register where bytes become bits let mut bits = 0; // how many leftover bits from previous iteration for v in src { // Add 8 input bits. data |= (*v as u16) << bits; // Yield 7 bits. Accrue 1 leftover bit for next iteration. dst.push((data & 0x7F) as u8); data >>= 7; bits += 1; // Every 7 iterations, 7 leftover bits have accrued. // Consume them to yield another 7-bit output. if bits == 7 { dst.push((data & 0x7F) as u8); data = 0; bits = 0; } } // Yield final leftover bits, if any. if bits > 0 { dst.push((data & 0x7F) as u8); } } /// Decodes a sequence of 7-bit values into a sequence of bytes. pub fn decode_7bit(src: &[u8], dst: &mut Vec<u8>) { // Iteration // | Leftover bits // | | Byte output // | | | // 0:.........0000000 (not enough bits for a byte) // 1:..111111 10000000 -> yield byte // 2:...22222 22111111 -> yield byte // 3:....3333 33322222 -> yield byte // 4:.....444 44443333 -> yield byte // 5:......55 55555444 -> yield byte // 6:.......6 66666655 -> yield byte // 7:........ 77777776 -> yield byte // 8: (repeats) let mut data = 0u16; // a shift register where bits become bytes let mut bits = 0; // how many leftover bits from previous iteration for v in src { // Isolate 7 input bits. let v = (*v & 0x7F) as u16; if bits == 0 { // Initially, and after every 8 iterations, there are no leftover // bits from the previous iteration. With only 7 new bits, there // aren't enough to make a byte. Just let those bits become the // leftovers for the next iteration. data = v; bits = 7; } else { // For other iterations, there are leftover bits from the previous // iteration. Consider those as least significant, and the 7 new // bits as most significant, and yield a byte. Any unused bits // become leftovers for the next iteration to use. data |= v << bits; dst.push((data & 0xFF) as u8); data >>= 8; bits -= 1; } } } #[cfg(test)] mod tests { use super::*; use self::ReadEvent::*; #[derive(Clone, PartialEq, Eq, Debug)] enum ReadEvent { Message { pos: usize, msg: Vec<u8> }, Error { pos: usize, len: usize, err: SysExReadError }, } fn run_read(mut bytes: &[u8], cap: usize) -> Vec<ReadEvent> { use std::cell::RefCell; let events = RefCell::new(vec![]); let result = read_sysex( &mut bytes, cap, |pos, msg| { events.borrow_mut().push(Message { pos, msg: msg.to_vec() }); true }, |pos, len, err| { events.borrow_mut().push(Error { pos, len, err }); true }, ); assert!(result.unwrap()); events.into_inner() } #[test] fn test_read_sysex_empty() { let events = run_read(b"", 10); assert_eq!(events.len(), 0); } #[test] fn
() { let events = run_read(b"any", 10); assert_eq!(events.len(), 1); assert_eq!(events[0], Error { pos: 0, len: 3, err: NotSysEx }); } #[test] fn test_read_sysex_sysex() { let events = run_read(b"\xF0msg\xF7", 10); assert_eq!(events.len(), 1); assert_eq!(events[0], Message { pos: 0, msg: b"msg".to_vec() }); } #[test] fn test_read_sysex_with_junk() { let events = run_read(b"abc\xF0def\xF7ghi\xF0jkl\xF7mno", 10); assert_eq!(events.len(), 5); assert_eq!(events[0], Error { pos: 0, len: 3, err: NotSysEx }); assert_eq!(events[1], Message { pos: 3, msg: b"def".to_vec() }); assert_eq!(events[2], Error { pos: 8, len: 3, err: NotSysEx }); assert_eq!(events[3], Message { pos: 11, msg: b"jkl".to_vec() }); assert_eq!(events[4], Error { pos: 16, len: 3, err: NotSysEx }); } #[test] fn test_read_sysex_with_sysrt() { let events = run_read(b"\xF0abc\xF8def\xF7", 10); assert_eq!(events.len(), 1); assert_eq!(events[0], Message { pos: 0, msg: b"abcdef".to_vec() }); } #[test] fn test_read_sysex_interrupted_by_sysex() { let events = run_read(b"\xF0abc\xF0def\xF7", 10); assert_eq!(events.len(), 2); assert_eq!(events[0], Error { pos: 0, len: 4, err: UnexpectedByte }); assert_eq!(events[1], Message { pos: 4, msg: b"def".to_vec() }); } #[test] fn test_read_sysex_interrupted_by_status() { let events = run_read(b"\xF0abc\xA5def\xF7", 10); assert_eq!(events.len(), 2); assert_eq!(events[0], Error { pos: 0, len: 4, err: UnexpectedByte }); assert_eq!(events[1], Error { pos: 4, len: 5, err: NotSysEx }); } #[test] fn test_read_sysex_interrupted_by_eof() { let events = run_read(b"\xF0abc", 10); assert_eq!(events.len(), 1); assert_eq!(events[0], Error { pos: 0, len: 4, err: UnexpectedEof }); } #[test] fn test_read_sysex_overflow() { let events = run_read(b"\xF0abc\xF7", 2); assert_eq!(events.len(), 1); assert_eq!(events[0], Error { pos: 0, len: 5, err: Overflow }); } #[test] fn test_read_sysex_overflow_2() { let events = run_read(b"\xF0abc\xF8def\xF7", 2); assert_eq!(events.len(), 1); assert_eq!(events[0], Error { pos: 0, len: 9, err: Overflow }); } #[test] fn test_encode_7bit() { let data8 = [ 0xF1, 0xE2, 0xD3, 0xC4, 0xB5, 0xA6, 0x97, 0x88, 0x79, 0x6A, ]; let mut data7 = vec![]; encode_7bit(&data8, &mut data7); assert_eq!(data7.len(), 12); // always 0 // | new bits // | | leftover bits // | | | // 0b_x_xxxx_xxx assert_eq!(data7[ 0], 0b_0_1110001_); assert_eq!(data7[ 1], 0b_0_100010_1); assert_eq!(data7[ 2], 0b_0_10011_11); assert_eq!(data7[ 3], 0b_0_0100_110); assert_eq!(data7[ 4], 0b_0_101_1100); assert_eq!(data7[ 5], 0b_0_10_10110); assert_eq!(data7[ 6], 0b_0_1_101001); assert_eq!(data7[ 7], 0b_0__1001011); assert_eq!(data7[ 8], 0b_0_0001000_); assert_eq!(data7[ 9], 0b_0_111001_1); assert_eq!(data7[10], 0b_0_01010_01); assert_eq!(data7[11], 0b_0_0000_011); // | | // | final leftover bits // 0-padding } #[test] fn test_decode_7bit() { let data7 = [ // don't care // | leftover bits // | | new bits // | | | // 0b_x_xxxx_xxx 0b_1_1110001_, 0b_0_100010_1, 0b_1_10011_11, 0b_0_0100_110, 0b_1_101_1100, 0b_0_10_10110, 0b_1_1_101001, 0b_0__1001011, 0b_1_0001000_, 0b_0_111001_1, 0b_1_01010_01, 0b_0_1111_011, ]; let mut data8 = vec![]; decode_7bit(&data7, &mut data8); assert_eq!(data8.len(), 10); assert_eq!(data8[0], 0xF1); assert_eq!(data8[1], 0xE2); assert_eq!(data8[2], 0xD3); assert_eq!(data8[3], 0xC4); assert_eq!(data8[4], 0xB5); assert_eq!(data8[5], 0xA6); assert_eq!(data8[6], 0x97); assert_eq!(data8[7], 0x88); assert_eq!(data8[8], 0x79); assert_eq!(data8[9], 0x6A); // Final leftover 4 bits go unused. } }
test_read_sysex_junk
identifier_name
lib.rs
extern crate ntlm; extern crate rustc_serialize as serialize; use ntlm::messages::{MessageType1, BinaryEncodable}; use serialize::base64::{ToBase64, STANDARD}; #[test] fn new_message_type_1() { let host = String::from("localhost"); let domain = String::from("test"); let m = MessageType1::new(&host.clone().into_bytes(), &domain.clone().into_bytes()); if String::from_utf8(m.host).unwrap() == host && String::from_utf8(m.domain).unwrap() == domain { assert!(true); } else { assert!(false); } } #[test] fn encode_message_type_1()
#[test] fn decode_message_type_1() { }
{ let host = String::from("localhost"); let domain = String::from("test"); let m = MessageType1::new(&host.clone().into_bytes(), &domain.clone().into_bytes()); let enc = m.encode(); assert_eq!(enc.to_base64(STANDARD), "TlRMTVNTUAABAAAAAAAAAAAEAAQAKQAAAAkACQAgAABsb2NhbGhvc3R0ZXN0"); }
identifier_body
lib.rs
extern crate ntlm; extern crate rustc_serialize as serialize; use ntlm::messages::{MessageType1, BinaryEncodable}; use serialize::base64::{ToBase64, STANDARD}; #[test] fn
() { let host = String::from("localhost"); let domain = String::from("test"); let m = MessageType1::new(&host.clone().into_bytes(), &domain.clone().into_bytes()); if String::from_utf8(m.host).unwrap() == host && String::from_utf8(m.domain).unwrap() == domain { assert!(true); } else { assert!(false); } } #[test] fn encode_message_type_1() { let host = String::from("localhost"); let domain = String::from("test"); let m = MessageType1::new(&host.clone().into_bytes(), &domain.clone().into_bytes()); let enc = m.encode(); assert_eq!(enc.to_base64(STANDARD), "TlRMTVNTUAABAAAAAAAAAAAEAAQAKQAAAAkACQAgAABsb2NhbGhvc3R0ZXN0"); } #[test] fn decode_message_type_1() { }
new_message_type_1
identifier_name
lib.rs
extern crate ntlm; extern crate rustc_serialize as serialize; use ntlm::messages::{MessageType1, BinaryEncodable}; use serialize::base64::{ToBase64, STANDARD}; #[test] fn new_message_type_1() { let host = String::from("localhost"); let domain = String::from("test"); let m = MessageType1::new(&host.clone().into_bytes(), &domain.clone().into_bytes()); if String::from_utf8(m.host).unwrap() == host && String::from_utf8(m.domain).unwrap() == domain
else { assert!(false); } } #[test] fn encode_message_type_1() { let host = String::from("localhost"); let domain = String::from("test"); let m = MessageType1::new(&host.clone().into_bytes(), &domain.clone().into_bytes()); let enc = m.encode(); assert_eq!(enc.to_base64(STANDARD), "TlRMTVNTUAABAAAAAAAAAAAEAAQAKQAAAAkACQAgAABsb2NhbGhvc3R0ZXN0"); } #[test] fn decode_message_type_1() { }
{ assert!(true); }
conditional_block
lib.rs
extern crate ntlm; extern crate rustc_serialize as serialize; use ntlm::messages::{MessageType1, BinaryEncodable}; use serialize::base64::{ToBase64, STANDARD}; #[test] fn new_message_type_1() { let host = String::from("localhost"); let domain = String::from("test"); let m = MessageType1::new(&host.clone().into_bytes(), &domain.clone().into_bytes());
} } #[test] fn encode_message_type_1() { let host = String::from("localhost"); let domain = String::from("test"); let m = MessageType1::new(&host.clone().into_bytes(), &domain.clone().into_bytes()); let enc = m.encode(); assert_eq!(enc.to_base64(STANDARD), "TlRMTVNTUAABAAAAAAAAAAAEAAQAKQAAAAkACQAgAABsb2NhbGhvc3R0ZXN0"); } #[test] fn decode_message_type_1() { }
if String::from_utf8(m.host).unwrap() == host && String::from_utf8(m.domain).unwrap() == domain { assert!(true); } else { assert!(false);
random_line_split
utils.rs
use libusb::{ LogLevel, Context, DeviceHandle, AsyncGroup, Result as UsbResult, Error, }; use consts; pub struct UsbWrapper { context: &'static Context, pub handle: &'static DeviceHandle<'static>, has_kernel_driver0: bool, has_kernel_driver1: bool, pub async_group: &'static mut AsyncGroup<'static>, } impl UsbWrapper { pub fn new() -> UsbResult<UsbWrapper> { // We must leak both context and handle and async_group, as rust does not allow sibling structs. // Leaking them gives us a &'static reference, which we can then use without // lifetime bounds, as it outlives everything. // We must make sure though, that the leaked memory is freed afterwards, // which is done in Drop. let context = try!(get_context()); let context_ptr = Box::into_raw(Box::new(context)); let context_ref = unsafe { &*context_ptr as &'static Context }; let (handle, driver0, driver1) = try!(get_handle(context_ref)); let async_group = AsyncGroup::new(context_ref); let handle_ptr = Box::into_raw(Box::new(handle)); let async_ptr = Box::into_raw(Box::new(async_group)); unsafe { Ok(UsbWrapper { context: context_ref, handle: &mut *handle_ptr as &'static mut DeviceHandle<'static>, has_kernel_driver0: driver0, has_kernel_driver1: driver1, async_group: &mut *async_ptr as &'static mut AsyncGroup<'static>, }) } } } macro_rules! unwrap_safe { ($e:expr) => { match $e { Ok(_) => {}, Err(e) => println!("Error while dropping UsbWrapper during another panic: {:?}", e), } } } impl Drop for UsbWrapper { fn drop(&mut self) { // make sure handle_mut is dropped before dropping it's refering content // this assures that there will be no dangling pointers { let handle_mut = unsafe { &mut *(self.handle as *const _ as *mut DeviceHandle<'static>) }; unwrap_safe!(handle_mut.release_interface(1)); unwrap_safe!(handle_mut.release_interface(0)); if self.has_kernel_driver1 { unwrap_safe!(handle_mut.attach_kernel_driver(1)); } if self.has_kernel_driver0 { unwrap_safe!(handle_mut.attach_kernel_driver(0)); } } // first, drop async_group to release all captured references to the DeviceHandle let async_ptr = &mut *self.async_group as *mut AsyncGroup<'static>; drop(unsafe { Box::from_raw(async_ptr) }); // then, drop the DeviceHandle to release Context let handle_ptr = &*self.handle as *const _ as *mut DeviceHandle<'static>; drop(unsafe { Box::from_raw(handle_ptr) }); let context_ptr = self.context as *const _ as *mut Context; drop(unsafe { Box::from_raw(context_ptr) }); } } fn get_context() -> UsbResult<Context> { let mut context = try!(Context::new()); context.set_log_level(LogLevel::Debug); context.set_log_level(LogLevel::Info); context.set_log_level(LogLevel::Warning); context.set_log_level(LogLevel::Error); context.set_log_level(LogLevel::None); Ok(context) } fn get_handle<'a>(context: &'a Context) -> UsbResult<(DeviceHandle<'a>, bool, bool)>
} } Err(Error::NoDevice) } fn detach(handle: &mut DeviceHandle, iface: u8) -> UsbResult<bool> { match handle.kernel_driver_active(iface) { Ok(true) => { try!(handle.detach_kernel_driver(iface)); Ok(true) }, _ => Ok(false) } }
{ let devices = try!(context.devices()); for d in devices.iter() { let dd = match d.device_descriptor() { Ok(dd) => dd, Err(_) => continue }; if dd.vendor_id() == consts::VENDOR_ID && dd.product_id() == consts::PRODUCT_ID { let mut handle = try!(d.open()); // for some reason we cannot claim interface 2 as it doesn't exist // but we will be able to read from it, if we claim interface 1 // detch kernel driver let has_kernel_driver0 = try!(detach(&mut handle, 0)); let has_kernel_driver1 = try!(detach(&mut handle, 1)); // claim interfaces try!(handle.claim_interface(0)); try!(handle.claim_interface(1)); // reset keyboard to get clean status try!(handle.reset()); return Ok((handle, has_kernel_driver0, has_kernel_driver1));
identifier_body
utils.rs
use libusb::{ LogLevel, Context, DeviceHandle, AsyncGroup, Result as UsbResult, Error, }; use consts; pub struct UsbWrapper { context: &'static Context, pub handle: &'static DeviceHandle<'static>, has_kernel_driver0: bool, has_kernel_driver1: bool, pub async_group: &'static mut AsyncGroup<'static>, } impl UsbWrapper { pub fn new() -> UsbResult<UsbWrapper> { // We must leak both context and handle and async_group, as rust does not allow sibling structs. // Leaking them gives us a &'static reference, which we can then use without // lifetime bounds, as it outlives everything. // We must make sure though, that the leaked memory is freed afterwards, // which is done in Drop. let context = try!(get_context()); let context_ptr = Box::into_raw(Box::new(context)); let context_ref = unsafe { &*context_ptr as &'static Context }; let (handle, driver0, driver1) = try!(get_handle(context_ref)); let async_group = AsyncGroup::new(context_ref); let handle_ptr = Box::into_raw(Box::new(handle)); let async_ptr = Box::into_raw(Box::new(async_group)); unsafe { Ok(UsbWrapper { context: context_ref, handle: &mut *handle_ptr as &'static mut DeviceHandle<'static>, has_kernel_driver0: driver0, has_kernel_driver1: driver1, async_group: &mut *async_ptr as &'static mut AsyncGroup<'static>, }) } } } macro_rules! unwrap_safe { ($e:expr) => { match $e { Ok(_) => {}, Err(e) => println!("Error while dropping UsbWrapper during another panic: {:?}", e), } } } impl Drop for UsbWrapper { fn drop(&mut self) { // make sure handle_mut is dropped before dropping it's refering content // this assures that there will be no dangling pointers { let handle_mut = unsafe { &mut *(self.handle as *const _ as *mut DeviceHandle<'static>) }; unwrap_safe!(handle_mut.release_interface(1)); unwrap_safe!(handle_mut.release_interface(0)); if self.has_kernel_driver1 { unwrap_safe!(handle_mut.attach_kernel_driver(1)); } if self.has_kernel_driver0 { unwrap_safe!(handle_mut.attach_kernel_driver(0)); } } // first, drop async_group to release all captured references to the DeviceHandle let async_ptr = &mut *self.async_group as *mut AsyncGroup<'static>; drop(unsafe { Box::from_raw(async_ptr) }); // then, drop the DeviceHandle to release Context let handle_ptr = &*self.handle as *const _ as *mut DeviceHandle<'static>; drop(unsafe { Box::from_raw(handle_ptr) }); let context_ptr = self.context as *const _ as *mut Context; drop(unsafe { Box::from_raw(context_ptr) }); } } fn get_context() -> UsbResult<Context> { let mut context = try!(Context::new()); context.set_log_level(LogLevel::Debug); context.set_log_level(LogLevel::Info); context.set_log_level(LogLevel::Warning); context.set_log_level(LogLevel::Error); context.set_log_level(LogLevel::None); Ok(context) } fn get_handle<'a>(context: &'a Context) -> UsbResult<(DeviceHandle<'a>, bool, bool)> { let devices = try!(context.devices()); for d in devices.iter() { let dd = match d.device_descriptor() { Ok(dd) => dd, Err(_) => continue }; if dd.vendor_id() == consts::VENDOR_ID && dd.product_id() == consts::PRODUCT_ID { let mut handle = try!(d.open()); // for some reason we cannot claim interface 2 as it doesn't exist // but we will be able to read from it, if we claim interface 1 // detch kernel driver let has_kernel_driver0 = try!(detach(&mut handle, 0));
let has_kernel_driver1 = try!(detach(&mut handle, 1)); // claim interfaces try!(handle.claim_interface(0)); try!(handle.claim_interface(1)); // reset keyboard to get clean status try!(handle.reset()); return Ok((handle, has_kernel_driver0, has_kernel_driver1)); } } Err(Error::NoDevice) } fn detach(handle: &mut DeviceHandle, iface: u8) -> UsbResult<bool> { match handle.kernel_driver_active(iface) { Ok(true) => { try!(handle.detach_kernel_driver(iface)); Ok(true) }, _ => Ok(false) } }
random_line_split
utils.rs
use libusb::{ LogLevel, Context, DeviceHandle, AsyncGroup, Result as UsbResult, Error, }; use consts; pub struct UsbWrapper { context: &'static Context, pub handle: &'static DeviceHandle<'static>, has_kernel_driver0: bool, has_kernel_driver1: bool, pub async_group: &'static mut AsyncGroup<'static>, } impl UsbWrapper { pub fn new() -> UsbResult<UsbWrapper> { // We must leak both context and handle and async_group, as rust does not allow sibling structs. // Leaking them gives us a &'static reference, which we can then use without // lifetime bounds, as it outlives everything. // We must make sure though, that the leaked memory is freed afterwards, // which is done in Drop. let context = try!(get_context()); let context_ptr = Box::into_raw(Box::new(context)); let context_ref = unsafe { &*context_ptr as &'static Context }; let (handle, driver0, driver1) = try!(get_handle(context_ref)); let async_group = AsyncGroup::new(context_ref); let handle_ptr = Box::into_raw(Box::new(handle)); let async_ptr = Box::into_raw(Box::new(async_group)); unsafe { Ok(UsbWrapper { context: context_ref, handle: &mut *handle_ptr as &'static mut DeviceHandle<'static>, has_kernel_driver0: driver0, has_kernel_driver1: driver1, async_group: &mut *async_ptr as &'static mut AsyncGroup<'static>, }) } } } macro_rules! unwrap_safe { ($e:expr) => { match $e { Ok(_) => {}, Err(e) => println!("Error while dropping UsbWrapper during another panic: {:?}", e), } } } impl Drop for UsbWrapper { fn drop(&mut self) { // make sure handle_mut is dropped before dropping it's refering content // this assures that there will be no dangling pointers { let handle_mut = unsafe { &mut *(self.handle as *const _ as *mut DeviceHandle<'static>) }; unwrap_safe!(handle_mut.release_interface(1)); unwrap_safe!(handle_mut.release_interface(0)); if self.has_kernel_driver1 { unwrap_safe!(handle_mut.attach_kernel_driver(1)); } if self.has_kernel_driver0 { unwrap_safe!(handle_mut.attach_kernel_driver(0)); } } // first, drop async_group to release all captured references to the DeviceHandle let async_ptr = &mut *self.async_group as *mut AsyncGroup<'static>; drop(unsafe { Box::from_raw(async_ptr) }); // then, drop the DeviceHandle to release Context let handle_ptr = &*self.handle as *const _ as *mut DeviceHandle<'static>; drop(unsafe { Box::from_raw(handle_ptr) }); let context_ptr = self.context as *const _ as *mut Context; drop(unsafe { Box::from_raw(context_ptr) }); } } fn get_context() -> UsbResult<Context> { let mut context = try!(Context::new()); context.set_log_level(LogLevel::Debug); context.set_log_level(LogLevel::Info); context.set_log_level(LogLevel::Warning); context.set_log_level(LogLevel::Error); context.set_log_level(LogLevel::None); Ok(context) } fn get_handle<'a>(context: &'a Context) -> UsbResult<(DeviceHandle<'a>, bool, bool)> { let devices = try!(context.devices()); for d in devices.iter() { let dd = match d.device_descriptor() { Ok(dd) => dd, Err(_) => continue }; if dd.vendor_id() == consts::VENDOR_ID && dd.product_id() == consts::PRODUCT_ID { let mut handle = try!(d.open()); // for some reason we cannot claim interface 2 as it doesn't exist // but we will be able to read from it, if we claim interface 1 // detch kernel driver let has_kernel_driver0 = try!(detach(&mut handle, 0)); let has_kernel_driver1 = try!(detach(&mut handle, 1)); // claim interfaces try!(handle.claim_interface(0)); try!(handle.claim_interface(1)); // reset keyboard to get clean status try!(handle.reset()); return Ok((handle, has_kernel_driver0, has_kernel_driver1)); } } Err(Error::NoDevice) } fn detach(handle: &mut DeviceHandle, iface: u8) -> UsbResult<bool> { match handle.kernel_driver_active(iface) { Ok(true) =>
, _ => Ok(false) } }
{ try!(handle.detach_kernel_driver(iface)); Ok(true) }
conditional_block
utils.rs
use libusb::{ LogLevel, Context, DeviceHandle, AsyncGroup, Result as UsbResult, Error, }; use consts; pub struct
{ context: &'static Context, pub handle: &'static DeviceHandle<'static>, has_kernel_driver0: bool, has_kernel_driver1: bool, pub async_group: &'static mut AsyncGroup<'static>, } impl UsbWrapper { pub fn new() -> UsbResult<UsbWrapper> { // We must leak both context and handle and async_group, as rust does not allow sibling structs. // Leaking them gives us a &'static reference, which we can then use without // lifetime bounds, as it outlives everything. // We must make sure though, that the leaked memory is freed afterwards, // which is done in Drop. let context = try!(get_context()); let context_ptr = Box::into_raw(Box::new(context)); let context_ref = unsafe { &*context_ptr as &'static Context }; let (handle, driver0, driver1) = try!(get_handle(context_ref)); let async_group = AsyncGroup::new(context_ref); let handle_ptr = Box::into_raw(Box::new(handle)); let async_ptr = Box::into_raw(Box::new(async_group)); unsafe { Ok(UsbWrapper { context: context_ref, handle: &mut *handle_ptr as &'static mut DeviceHandle<'static>, has_kernel_driver0: driver0, has_kernel_driver1: driver1, async_group: &mut *async_ptr as &'static mut AsyncGroup<'static>, }) } } } macro_rules! unwrap_safe { ($e:expr) => { match $e { Ok(_) => {}, Err(e) => println!("Error while dropping UsbWrapper during another panic: {:?}", e), } } } impl Drop for UsbWrapper { fn drop(&mut self) { // make sure handle_mut is dropped before dropping it's refering content // this assures that there will be no dangling pointers { let handle_mut = unsafe { &mut *(self.handle as *const _ as *mut DeviceHandle<'static>) }; unwrap_safe!(handle_mut.release_interface(1)); unwrap_safe!(handle_mut.release_interface(0)); if self.has_kernel_driver1 { unwrap_safe!(handle_mut.attach_kernel_driver(1)); } if self.has_kernel_driver0 { unwrap_safe!(handle_mut.attach_kernel_driver(0)); } } // first, drop async_group to release all captured references to the DeviceHandle let async_ptr = &mut *self.async_group as *mut AsyncGroup<'static>; drop(unsafe { Box::from_raw(async_ptr) }); // then, drop the DeviceHandle to release Context let handle_ptr = &*self.handle as *const _ as *mut DeviceHandle<'static>; drop(unsafe { Box::from_raw(handle_ptr) }); let context_ptr = self.context as *const _ as *mut Context; drop(unsafe { Box::from_raw(context_ptr) }); } } fn get_context() -> UsbResult<Context> { let mut context = try!(Context::new()); context.set_log_level(LogLevel::Debug); context.set_log_level(LogLevel::Info); context.set_log_level(LogLevel::Warning); context.set_log_level(LogLevel::Error); context.set_log_level(LogLevel::None); Ok(context) } fn get_handle<'a>(context: &'a Context) -> UsbResult<(DeviceHandle<'a>, bool, bool)> { let devices = try!(context.devices()); for d in devices.iter() { let dd = match d.device_descriptor() { Ok(dd) => dd, Err(_) => continue }; if dd.vendor_id() == consts::VENDOR_ID && dd.product_id() == consts::PRODUCT_ID { let mut handle = try!(d.open()); // for some reason we cannot claim interface 2 as it doesn't exist // but we will be able to read from it, if we claim interface 1 // detch kernel driver let has_kernel_driver0 = try!(detach(&mut handle, 0)); let has_kernel_driver1 = try!(detach(&mut handle, 1)); // claim interfaces try!(handle.claim_interface(0)); try!(handle.claim_interface(1)); // reset keyboard to get clean status try!(handle.reset()); return Ok((handle, has_kernel_driver0, has_kernel_driver1)); } } Err(Error::NoDevice) } fn detach(handle: &mut DeviceHandle, iface: u8) -> UsbResult<bool> { match handle.kernel_driver_active(iface) { Ok(true) => { try!(handle.detach_kernel_driver(iface)); Ok(true) }, _ => Ok(false) } }
UsbWrapper
identifier_name
display_list_builder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Constructs display lists from boxes. use layout::context::LayoutContext; use geom::{Point2D, Rect, Size2D}; use gfx::render_task::RenderLayer; use gfx; use servo_util::geometry::Au; use servo_util::smallvec::SmallVec0; use style; /// Manages the information needed to construct the display list. pub struct
<'a> { ctx: &'a LayoutContext, /// A list of render layers that we've built up, root layer not included. layers: SmallVec0<RenderLayer>, /// The dirty rect. dirty: Rect<Au>, } /// Information needed at each step of the display list building traversal. pub struct DisplayListBuildingInfo { /// The size of the containing block for relatively-positioned descendants. relative_containing_block_size: Size2D<Au>, /// The position and size of the absolute containing block. absolute_containing_block_position: Point2D<Au>, /// Whether the absolute containing block forces positioned descendants to be layerized. layers_needed_for_positioned_flows: bool, } // // Miscellaneous useful routines // /// Allows a CSS color to be converted into a graphics color. pub trait ToGfxColor { /// Converts a CSS color to a graphics color. fn to_gfx_color(&self) -> gfx::color::Color; } impl ToGfxColor for style::computed_values::RGBA { fn to_gfx_color(&self) -> gfx::color::Color { gfx::color::rgba(self.red, self.green, self.blue, self.alpha) } }
DisplayListBuilder
identifier_name
display_list_builder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Constructs display lists from boxes. use layout::context::LayoutContext; use geom::{Point2D, Rect, Size2D}; use gfx::render_task::RenderLayer; use gfx; use servo_util::geometry::Au; use servo_util::smallvec::SmallVec0; use style; /// Manages the information needed to construct the display list. pub struct DisplayListBuilder<'a> { ctx: &'a LayoutContext, /// A list of render layers that we've built up, root layer not included. layers: SmallVec0<RenderLayer>, /// The dirty rect. dirty: Rect<Au>, } /// Information needed at each step of the display list building traversal. pub struct DisplayListBuildingInfo { /// The size of the containing block for relatively-positioned descendants. relative_containing_block_size: Size2D<Au>, /// The position and size of the absolute containing block. absolute_containing_block_position: Point2D<Au>, /// Whether the absolute containing block forces positioned descendants to be layerized. layers_needed_for_positioned_flows: bool, } // // Miscellaneous useful routines // /// Allows a CSS color to be converted into a graphics color. pub trait ToGfxColor { /// Converts a CSS color to a graphics color. fn to_gfx_color(&self) -> gfx::color::Color; } impl ToGfxColor for style::computed_values::RGBA { fn to_gfx_color(&self) -> gfx::color::Color
}
{ gfx::color::rgba(self.red, self.green, self.blue, self.alpha) }
identifier_body
display_list_builder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Constructs display lists from boxes. use layout::context::LayoutContext; use geom::{Point2D, Rect, Size2D}; use gfx::render_task::RenderLayer; use gfx; use servo_util::geometry::Au; use servo_util::smallvec::SmallVec0; use style; /// Manages the information needed to construct the display list. pub struct DisplayListBuilder<'a> { ctx: &'a LayoutContext, /// A list of render layers that we've built up, root layer not included. layers: SmallVec0<RenderLayer>, /// The dirty rect. dirty: Rect<Au>, } /// Information needed at each step of the display list building traversal. pub struct DisplayListBuildingInfo { /// The size of the containing block for relatively-positioned descendants. relative_containing_block_size: Size2D<Au>, /// The position and size of the absolute containing block. absolute_containing_block_position: Point2D<Au>, /// Whether the absolute containing block forces positioned descendants to be layerized. layers_needed_for_positioned_flows: bool, } // // Miscellaneous useful routines // /// Allows a CSS color to be converted into a graphics color. pub trait ToGfxColor { /// Converts a CSS color to a graphics color. fn to_gfx_color(&self) -> gfx::color::Color;
impl ToGfxColor for style::computed_values::RGBA { fn to_gfx_color(&self) -> gfx::color::Color { gfx::color::rgba(self.red, self.green, self.blue, self.alpha) } }
}
random_line_split
builtin.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. use page::handler; use std::sync::Arc; use endpoint::{Endpoint, EndpointInfo, EndpointPath, Handler}; use parity_dapps::{WebApp, File, Info}; pub struct PageEndpoint<T : WebApp +'static> { /// Content of the files pub app: Arc<T>, /// Prefix to strip from the path (when `None` deducted from `app_id`) pub prefix: Option<String>, /// Safe to be loaded in frame by other origin. (use wisely!) safe_to_embed_at_port: Option<u16>, info: EndpointInfo, } impl<T: WebApp +'static> PageEndpoint<T> { /// Creates new `PageEndpoint` for builtin (compile time) Dapp. pub fn new(app: T) -> Self { let info = app.info(); PageEndpoint { app: Arc::new(app), prefix: None, safe_to_embed_at_port: None, info: EndpointInfo::from(info), } } /// Create new `PageEndpoint` and specify prefix that should be removed before looking for a file. /// It's used only for special endpoints (i.e. `/parity-utils/`) /// So `/parity-utils/inject.js` will be resolved to `/inject.js` is prefix is set. pub fn with_prefix(app: T, prefix: String) -> Self { let info = app.info(); PageEndpoint { app: Arc::new(app), prefix: Some(prefix), safe_to_embed_at_port: None, info: EndpointInfo::from(info), } } /// Creates new `PageEndpoint` which can be safely used in iframe /// even from different origin. It might be dangerous (clickjacking). /// Use wisely! pub fn new_safe_to_embed(app: T, port: Option<u16>) -> Self { let info = app.info(); PageEndpoint { app: Arc::new(app), prefix: None, safe_to_embed_at_port: port, info: EndpointInfo::from(info), } } } impl<T: WebApp> Endpoint for PageEndpoint<T> { fn info(&self) -> Option<&EndpointInfo> { Some(&self.info) } fn to_handler(&self, path: EndpointPath) -> Box<Handler> { Box::new(handler::PageHandler { app: BuiltinDapp::new(self.app.clone()), prefix: self.prefix.clone(), path: path, file: handler::ServedFile::new(self.safe_to_embed_at_port.clone()), safe_to_embed_at_port: self.safe_to_embed_at_port.clone(), }) } } impl From<Info> for EndpointInfo { fn from(info: Info) -> Self { EndpointInfo { name: info.name.into(), description: info.description.into(), author: info.author.into(), icon_url: info.icon_url.into(), version: info.version.into(), } } } struct BuiltinDapp<T: WebApp +'static> { app: Arc<T>, } impl<T: WebApp +'static> BuiltinDapp<T> { fn new(app: Arc<T>) -> Self { BuiltinDapp { app: app, } } } impl<T: WebApp +'static> handler::Dapp for BuiltinDapp<T> { type DappFile = BuiltinDappFile<T>; fn file(&self, path: &str) -> Option<Self::DappFile> { self.app.file(path).map(|_| { BuiltinDappFile { app: self.app.clone(), path: path.into(), write_pos: 0, } }) } } struct BuiltinDappFile<T: WebApp +'static> { app: Arc<T>, path: String, write_pos: usize, } impl<T: WebApp +'static> BuiltinDappFile<T> { fn file(&self) -> &File { self.app.file(&self.path).expect("Check is done when structure is created.") } } impl<T: WebApp +'static> handler::DappFile for BuiltinDappFile<T> { fn content_type(&self) -> &str { self.file().content_type } fn is_drained(&self) -> bool { self.write_pos == self.file().content.len() } fn next_chunk(&mut self) -> &[u8] { &self.file().content[self.write_pos..] } fn bytes_written(&mut self, bytes: usize) { self.write_pos += bytes; } }
random_line_split
builtin.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use page::handler; use std::sync::Arc; use endpoint::{Endpoint, EndpointInfo, EndpointPath, Handler}; use parity_dapps::{WebApp, File, Info}; pub struct PageEndpoint<T : WebApp +'static> { /// Content of the files pub app: Arc<T>, /// Prefix to strip from the path (when `None` deducted from `app_id`) pub prefix: Option<String>, /// Safe to be loaded in frame by other origin. (use wisely!) safe_to_embed_at_port: Option<u16>, info: EndpointInfo, } impl<T: WebApp +'static> PageEndpoint<T> { /// Creates new `PageEndpoint` for builtin (compile time) Dapp. pub fn new(app: T) -> Self { let info = app.info(); PageEndpoint { app: Arc::new(app), prefix: None, safe_to_embed_at_port: None, info: EndpointInfo::from(info), } } /// Create new `PageEndpoint` and specify prefix that should be removed before looking for a file. /// It's used only for special endpoints (i.e. `/parity-utils/`) /// So `/parity-utils/inject.js` will be resolved to `/inject.js` is prefix is set. pub fn with_prefix(app: T, prefix: String) -> Self { let info = app.info(); PageEndpoint { app: Arc::new(app), prefix: Some(prefix), safe_to_embed_at_port: None, info: EndpointInfo::from(info), } } /// Creates new `PageEndpoint` which can be safely used in iframe /// even from different origin. It might be dangerous (clickjacking). /// Use wisely! pub fn new_safe_to_embed(app: T, port: Option<u16>) -> Self { let info = app.info(); PageEndpoint { app: Arc::new(app), prefix: None, safe_to_embed_at_port: port, info: EndpointInfo::from(info), } } } impl<T: WebApp> Endpoint for PageEndpoint<T> { fn info(&self) -> Option<&EndpointInfo> { Some(&self.info) } fn to_handler(&self, path: EndpointPath) -> Box<Handler> { Box::new(handler::PageHandler { app: BuiltinDapp::new(self.app.clone()), prefix: self.prefix.clone(), path: path, file: handler::ServedFile::new(self.safe_to_embed_at_port.clone()), safe_to_embed_at_port: self.safe_to_embed_at_port.clone(), }) } } impl From<Info> for EndpointInfo { fn from(info: Info) -> Self { EndpointInfo { name: info.name.into(), description: info.description.into(), author: info.author.into(), icon_url: info.icon_url.into(), version: info.version.into(), } } } struct BuiltinDapp<T: WebApp +'static> { app: Arc<T>, } impl<T: WebApp +'static> BuiltinDapp<T> { fn new(app: Arc<T>) -> Self { BuiltinDapp { app: app, } } } impl<T: WebApp +'static> handler::Dapp for BuiltinDapp<T> { type DappFile = BuiltinDappFile<T>; fn file(&self, path: &str) -> Option<Self::DappFile> { self.app.file(path).map(|_| { BuiltinDappFile { app: self.app.clone(), path: path.into(), write_pos: 0, } }) } } struct BuiltinDappFile<T: WebApp +'static> { app: Arc<T>, path: String, write_pos: usize, } impl<T: WebApp +'static> BuiltinDappFile<T> { fn file(&self) -> &File { self.app.file(&self.path).expect("Check is done when structure is created.") } } impl<T: WebApp +'static> handler::DappFile for BuiltinDappFile<T> { fn
(&self) -> &str { self.file().content_type } fn is_drained(&self) -> bool { self.write_pos == self.file().content.len() } fn next_chunk(&mut self) -> &[u8] { &self.file().content[self.write_pos..] } fn bytes_written(&mut self, bytes: usize) { self.write_pos += bytes; } }
content_type
identifier_name
symbols.rs
use std::str::FromStr; #[derive(Copy, Debug, PartialEq, Clone)] pub enum Symbols { ParenOpen, ParenClose, SBracketOpen, SBracketClose, CBracketOpen, CBracketClose, Period, Comma, Colon, Caret, GreaterThan, LessThan, GreaterThanEqual, LessThanEqual, Plus, Minus, Asterisk, Slash, Percent, Tilde, Equals, PlusEquals, MinusEquals, AsteriskEquals, SlashEquals, PercentEquals, RightThinArrow, } impl FromStr for Symbols { type Err = String; fn
(s: &str) -> Result<Symbols, String> { match s { "(" => Ok(Symbols::ParenOpen), ")" => Ok(Symbols::ParenClose), "[" => Ok(Symbols::SBracketOpen), "]" => Ok(Symbols::SBracketClose), "{" => Ok(Symbols::CBracketOpen), "}" => Ok(Symbols::CBracketClose), "." => Ok(Symbols::Period), "," => Ok(Symbols::Comma), ":" => Ok(Symbols::Colon), "^" => Ok(Symbols::Caret), ">" => Ok(Symbols::GreaterThan), "<" => Ok(Symbols::LessThan), "+" => Ok(Symbols::Plus), "-" => Ok(Symbols::Minus), "*" => Ok(Symbols::Asterisk), "/" => Ok(Symbols::Slash), "%" => Ok(Symbols::Percent), "~" => Ok(Symbols::Tilde), "=" => Ok(Symbols::Equals), ">=" => Ok(Symbols::GreaterThanEqual), "<=" => Ok(Symbols::LessThanEqual), "+=" => Ok(Symbols::PlusEquals), "-=" => Ok(Symbols::MinusEquals), "*=" => Ok(Symbols::AsteriskEquals), "/=" => Ok(Symbols::SlashEquals), "%=" => Ok(Symbols::PercentEquals), "->" => Ok(Symbols::RightThinArrow), s => Err(format!("Invalid Symbol Token match: {}", s)) } } }
from_str
identifier_name
symbols.rs
use std::str::FromStr; #[derive(Copy, Debug, PartialEq, Clone)] pub enum Symbols { ParenOpen, ParenClose, SBracketOpen, SBracketClose, CBracketOpen, CBracketClose, Period, Comma, Colon, Caret, GreaterThan, LessThan, GreaterThanEqual, LessThanEqual, Plus, Minus, Asterisk, Slash, Percent, Tilde, Equals, PlusEquals, MinusEquals, AsteriskEquals, SlashEquals,
impl FromStr for Symbols { type Err = String; fn from_str(s: &str) -> Result<Symbols, String> { match s { "(" => Ok(Symbols::ParenOpen), ")" => Ok(Symbols::ParenClose), "[" => Ok(Symbols::SBracketOpen), "]" => Ok(Symbols::SBracketClose), "{" => Ok(Symbols::CBracketOpen), "}" => Ok(Symbols::CBracketClose), "." => Ok(Symbols::Period), "," => Ok(Symbols::Comma), ":" => Ok(Symbols::Colon), "^" => Ok(Symbols::Caret), ">" => Ok(Symbols::GreaterThan), "<" => Ok(Symbols::LessThan), "+" => Ok(Symbols::Plus), "-" => Ok(Symbols::Minus), "*" => Ok(Symbols::Asterisk), "/" => Ok(Symbols::Slash), "%" => Ok(Symbols::Percent), "~" => Ok(Symbols::Tilde), "=" => Ok(Symbols::Equals), ">=" => Ok(Symbols::GreaterThanEqual), "<=" => Ok(Symbols::LessThanEqual), "+=" => Ok(Symbols::PlusEquals), "-=" => Ok(Symbols::MinusEquals), "*=" => Ok(Symbols::AsteriskEquals), "/=" => Ok(Symbols::SlashEquals), "%=" => Ok(Symbols::PercentEquals), "->" => Ok(Symbols::RightThinArrow), s => Err(format!("Invalid Symbol Token match: {}", s)) } } }
PercentEquals, RightThinArrow, }
random_line_split
parser.rs
use crate::branch::Branch; use crate::dictionary::Dictionary; use crate::state::InterpState; use crate::word::Word; use std::rc::Rc; /// Takes a chars iterator and returns all characters up to the next whitespace, /// excluding the whitespace character. Returns `None` the `chars` iterator is /// exhausted. pub fn next_word<T: Iterator<Item = char>>(chars: &mut T) -> Option<String> { let word = chars .skip_while(|x| x.is_whitespace()) .take_while(|x|!x.is_whitespace()) .collect::<String>(); if word.is_empty() { // No input left None } else { Some(word) } } pub fn parse_word<T: Iterator<Item = char>>( word_str: &str, chars: &mut T, dict: &mut Dictionary, state: &mut InterpState, ) -> Option<Branch> { if let Some(word) = dict.get(word_str) { match word { Word::Custom(x) => Some(Branch::Custom(x)), Word::Builtin(x) => Some(Branch::Builtin(x)), Word::Int(x) => Some(Branch::Int(x)), Word::Float(x) => Some(Branch::Float(x)), Word::Dotquote => { let text = chars.take_while(|x| *x!= '"').collect(); Some(Branch::Dotquote(text)) } Word::Paren => { // Consumes all characters up to next ) chars.take_while(|x| *x!= ')').count(); None } Word::Colon => { let name = next_word(chars).unwrap(); let mut inner_branches: Vec<Branch> = Vec::new(); while let Some(inner_word_str) = next_word(chars) { if dict.get(&inner_word_str) == Some(Word::Semicolon) { break; } if let Some(branch) = parse_word(&inner_word_str, chars, dict, state) { inner_branches.push(branch); } } dict.set(&name, Word::Custom(Rc::new(inner_branches))); None } Word::If => { let mut ifbranches = Vec::new(); let mut elsebranches = Vec::new(); let mut inelse = false; while let Some(inner_word_str) = next_word(chars) { match dict.get(&inner_word_str) { Some(Word::Else) => inelse = true, Some(Word::Then) => break, _ => {} } if let Some(branch) = parse_word(&inner_word_str, chars, dict, state) { if inelse { elsebranches.push(branch); } else { ifbranches.push(branch); } } } Some(Branch::IfElse(ifbranches, elsebranches)) } Word::Variable => { let name = next_word(chars).unwrap(); let addr = state.memory.new(0); dict.set(&name, Word::Int(addr)); None } Word::Create => { let name = next_word(chars).unwrap(); let addr = state.memory.here() + 1; dict.set(&name, Word::Int(addr)); None } Word::Semicolon | Word::Else | Word::Then => { panic!("Invalid here"); } } } else { panic!("Word '{}' not in dictionary.", word_str); } } pub fn parse<T: Iterator<Item = char>>( code: &mut T, dict: &mut Dictionary, state: &mut InterpState, ) -> Vec<Branch>
{ let mut branches: Vec<Branch> = Vec::new(); while let Some(word_str) = next_word(code) { if let Some(branch) = parse_word(&word_str, code, dict, state) { branches.push(branch); } } branches }
identifier_body
parser.rs
use crate::branch::Branch; use crate::dictionary::Dictionary; use crate::state::InterpState; use crate::word::Word; use std::rc::Rc; /// Takes a chars iterator and returns all characters up to the next whitespace, /// excluding the whitespace character. Returns `None` the `chars` iterator is /// exhausted. pub fn next_word<T: Iterator<Item = char>>(chars: &mut T) -> Option<String> { let word = chars .skip_while(|x| x.is_whitespace()) .take_while(|x|!x.is_whitespace()) .collect::<String>(); if word.is_empty() { // No input left None } else { Some(word) } } pub fn parse_word<T: Iterator<Item = char>>( word_str: &str, chars: &mut T, dict: &mut Dictionary, state: &mut InterpState, ) -> Option<Branch> { if let Some(word) = dict.get(word_str) { match word { Word::Custom(x) => Some(Branch::Custom(x)), Word::Builtin(x) => Some(Branch::Builtin(x)), Word::Int(x) => Some(Branch::Int(x)), Word::Float(x) => Some(Branch::Float(x)), Word::Dotquote => { let text = chars.take_while(|x| *x!= '"').collect(); Some(Branch::Dotquote(text)) } Word::Paren => { // Consumes all characters up to next ) chars.take_while(|x| *x!= ')').count(); None } Word::Colon => { let name = next_word(chars).unwrap(); let mut inner_branches: Vec<Branch> = Vec::new(); while let Some(inner_word_str) = next_word(chars) { if dict.get(&inner_word_str) == Some(Word::Semicolon) { break; } if let Some(branch) = parse_word(&inner_word_str, chars, dict, state) { inner_branches.push(branch); } } dict.set(&name, Word::Custom(Rc::new(inner_branches))); None } Word::If => { let mut ifbranches = Vec::new(); let mut elsebranches = Vec::new(); let mut inelse = false; while let Some(inner_word_str) = next_word(chars) { match dict.get(&inner_word_str) { Some(Word::Else) => inelse = true, Some(Word::Then) => break, _ => {} } if let Some(branch) = parse_word(&inner_word_str, chars, dict, state) { if inelse { elsebranches.push(branch); } else { ifbranches.push(branch); } } } Some(Branch::IfElse(ifbranches, elsebranches)) } Word::Variable => { let name = next_word(chars).unwrap(); let addr = state.memory.new(0); dict.set(&name, Word::Int(addr)); None } Word::Create => { let name = next_word(chars).unwrap(); let addr = state.memory.here() + 1; dict.set(&name, Word::Int(addr)); None } Word::Semicolon | Word::Else | Word::Then => { panic!("Invalid here"); } } } else { panic!("Word '{}' not in dictionary.", word_str); } } pub fn
<T: Iterator<Item = char>>( code: &mut T, dict: &mut Dictionary, state: &mut InterpState, ) -> Vec<Branch> { let mut branches: Vec<Branch> = Vec::new(); while let Some(word_str) = next_word(code) { if let Some(branch) = parse_word(&word_str, code, dict, state) { branches.push(branch); } } branches }
parse
identifier_name
parser.rs
use crate::branch::Branch; use crate::dictionary::Dictionary; use crate::state::InterpState; use crate::word::Word; use std::rc::Rc; /// Takes a chars iterator and returns all characters up to the next whitespace, /// excluding the whitespace character. Returns `None` the `chars` iterator is /// exhausted. pub fn next_word<T: Iterator<Item = char>>(chars: &mut T) -> Option<String> { let word = chars .skip_while(|x| x.is_whitespace()) .take_while(|x|!x.is_whitespace()) .collect::<String>(); if word.is_empty() { // No input left None } else { Some(word) } } pub fn parse_word<T: Iterator<Item = char>>( word_str: &str, chars: &mut T, dict: &mut Dictionary, state: &mut InterpState, ) -> Option<Branch> { if let Some(word) = dict.get(word_str) { match word { Word::Custom(x) => Some(Branch::Custom(x)), Word::Builtin(x) => Some(Branch::Builtin(x)), Word::Int(x) => Some(Branch::Int(x)), Word::Float(x) => Some(Branch::Float(x)), Word::Dotquote => { let text = chars.take_while(|x| *x!= '"').collect(); Some(Branch::Dotquote(text)) } Word::Paren => { // Consumes all characters up to next ) chars.take_while(|x| *x!= ')').count(); None } Word::Colon => { let name = next_word(chars).unwrap(); let mut inner_branches: Vec<Branch> = Vec::new(); while let Some(inner_word_str) = next_word(chars) { if dict.get(&inner_word_str) == Some(Word::Semicolon) { break; } if let Some(branch) = parse_word(&inner_word_str, chars, dict, state) { inner_branches.push(branch); } } dict.set(&name, Word::Custom(Rc::new(inner_branches))); None } Word::If => { let mut ifbranches = Vec::new(); let mut elsebranches = Vec::new(); let mut inelse = false;
_ => {} } if let Some(branch) = parse_word(&inner_word_str, chars, dict, state) { if inelse { elsebranches.push(branch); } else { ifbranches.push(branch); } } } Some(Branch::IfElse(ifbranches, elsebranches)) } Word::Variable => { let name = next_word(chars).unwrap(); let addr = state.memory.new(0); dict.set(&name, Word::Int(addr)); None } Word::Create => { let name = next_word(chars).unwrap(); let addr = state.memory.here() + 1; dict.set(&name, Word::Int(addr)); None } Word::Semicolon | Word::Else | Word::Then => { panic!("Invalid here"); } } } else { panic!("Word '{}' not in dictionary.", word_str); } } pub fn parse<T: Iterator<Item = char>>( code: &mut T, dict: &mut Dictionary, state: &mut InterpState, ) -> Vec<Branch> { let mut branches: Vec<Branch> = Vec::new(); while let Some(word_str) = next_word(code) { if let Some(branch) = parse_word(&word_str, code, dict, state) { branches.push(branch); } } branches }
while let Some(inner_word_str) = next_word(chars) { match dict.get(&inner_word_str) { Some(Word::Else) => inelse = true, Some(Word::Then) => break,
random_line_split
hostname.rs
#![crate_name = "uu_hostname"] /* * This file is part of the uutils coreutils package. * * (c) Alan Andrade <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; #[cfg(windows)] extern crate winapi; #[macro_use] extern crate uucore; use std::collections::hash_set::HashSet; use std::iter::repeat; use std::io; use std::str; use std::net::ToSocketAddrs; use getopts::Matches; #[cfg(windows)] use winapi::um::winsock2::{GetHostNameW, WSACleanup, WSAStartup}; #[cfg(windows)] use winapi::um::sysinfoapi::{ComputerNamePhysicalDnsHostname, SetComputerNameExW}; #[cfg(windows)] use winapi::shared::minwindef::MAKEWORD; #[cfg(windows)] use uucore::wide::*; #[cfg(not(windows))] use libc::gethostname; #[cfg(not(windows))] use libc::sethostname; const SYNTAX: &'static str = "[OPTION]... [HOSTNAME]"; const SUMMARY: &'static str = "Print or set the system's host name."; const LONG_HELP: &'static str = ""; pub fn uumain(args: Vec<String>) -> i32 { #[cfg(windows)] unsafe { let mut data = std::mem::uninitialized(); if WSAStartup(MAKEWORD(2, 2), &mut data as *mut _)!= 0 { eprintln!("Failed to start Winsock 2.2"); return 1; } } let result = execute(args); #[cfg(windows)] unsafe { WSACleanup(); } result } fn execute(args: Vec<String>) -> i32 { let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP) .optflag("d", "domain", "Display the name of the DNS domain if possible") .optflag("i", "ip-address", "Display the network address(es) of the host") // TODO: support --long .optflag("f", "fqdn", "Display the FQDN (Fully Qualified Domain Name) (default)") .optflag("s", "short", "Display the short hostname (the portion before the first dot) if \ possible") .parse(args); match matches.free.len() { 0 => display_hostname(matches), 1 => { if let Err(err) = xsethostname(matches.free.last().unwrap()) { show_error!("{}", err); 1 } else { 0 } } _ => { show_error!("{}", msg_wrong_number_of_arguments!(0, 1)); 1 } } } fn display_hostname(matches: Matches) -> i32 { let hostname = return_if_err!(1, xgethostname()); if matches.opt_present("i") { // XXX: to_socket_addrs needs hostname:port so append a dummy port and remove it later. // This was originally supposed to use std::net::lookup_host, but that seems to be // deprecated. Perhaps we should use the dns-lookup crate? let hostname = hostname + ":1"; match hostname.to_socket_addrs() { Ok(addresses) => { let mut hashset = HashSet::new(); let mut output = String::new(); for addr in addresses { // XXX: not sure why this is necessary... if!hashset.contains(&addr) { let mut ip = format!("{}", addr); if ip.ends_with(":1")
output.push_str(&ip); output.push_str(" "); hashset.insert(addr); } } let len = output.len(); if len > 0 { println!("{}", &output[0..len - 1]); } 0 } Err(f) => { show_error!("{}", f); 1 } } } else { if matches.opt_present("s") || matches.opt_present("d") { let mut it = hostname.char_indices().filter(|&ci| ci.1 == '.'); if let Some(ci) = it.next() { if matches.opt_present("s") { println!("{}", &hostname[0..ci.0]); } else { println!("{}", &hostname[ci.0 + 1..]); } return 0; } } println!("{}", hostname); 0 } } #[cfg(not(windows))] fn xgethostname() -> io::Result<String> { use std::ffi::CStr; let namelen = 256; let mut name: Vec<u8> = repeat(0).take(namelen).collect(); let err = unsafe { gethostname( name.as_mut_ptr() as *mut libc::c_char, namelen as libc::size_t, ) }; if err == 0 { let null_pos = name.iter().position(|byte| *byte == 0).unwrap_or(namelen); if null_pos == namelen { name.push(0); } Ok(CStr::from_bytes_with_nul(&name[..null_pos + 1]) .unwrap() .to_string_lossy() .into_owned()) } else { Err(io::Error::last_os_error()) } } #[cfg(windows)] fn xgethostname() -> io::Result<String> { let namelen = 256; let mut name: Vec<u16> = repeat(0).take(namelen).collect(); let err = unsafe { GetHostNameW(name.as_mut_ptr(), namelen as libc::c_int) }; if err == 0 { Ok(String::from_wide_null(&name)) } else { Err(io::Error::last_os_error()) } } #[cfg(not(windows))] fn xsethostname(name: &str) -> io::Result<()> { let vec_name: Vec<libc::c_char> = name.bytes().map(|c| c as libc::c_char).collect(); let err = unsafe { sethostname(vec_name.as_ptr(), vec_name.len() as _) }; if err!= 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } #[cfg(windows)] fn xsethostname(name: &str) -> io::Result<()> { use std::ffi::OsStr; let wide_name = OsStr::new(name).to_wide_null(); let err = unsafe { SetComputerNameExW(ComputerNamePhysicalDnsHostname, wide_name.as_ptr()) }; if err == 0 { // NOTE: the above is correct, failure is when the function returns 0 apparently Err(io::Error::last_os_error()) } else { Ok(()) } }
{ let len = ip.len(); ip.truncate(len - 2); }
conditional_block
hostname.rs
#![crate_name = "uu_hostname"] /* * This file is part of the uutils coreutils package. * * (c) Alan Andrade <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; #[cfg(windows)] extern crate winapi; #[macro_use] extern crate uucore; use std::collections::hash_set::HashSet; use std::iter::repeat; use std::io; use std::str; use std::net::ToSocketAddrs; use getopts::Matches; #[cfg(windows)] use winapi::um::winsock2::{GetHostNameW, WSACleanup, WSAStartup}; #[cfg(windows)] use winapi::um::sysinfoapi::{ComputerNamePhysicalDnsHostname, SetComputerNameExW}; #[cfg(windows)] use winapi::shared::minwindef::MAKEWORD; #[cfg(windows)] use uucore::wide::*; #[cfg(not(windows))] use libc::gethostname; #[cfg(not(windows))] use libc::sethostname; const SYNTAX: &'static str = "[OPTION]... [HOSTNAME]"; const SUMMARY: &'static str = "Print or set the system's host name."; const LONG_HELP: &'static str = ""; pub fn uumain(args: Vec<String>) -> i32 { #[cfg(windows)] unsafe { let mut data = std::mem::uninitialized(); if WSAStartup(MAKEWORD(2, 2), &mut data as *mut _)!= 0 { eprintln!("Failed to start Winsock 2.2"); return 1; } } let result = execute(args); #[cfg(windows)] unsafe { WSACleanup(); } result } fn execute(args: Vec<String>) -> i32 { let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP) .optflag("d", "domain", "Display the name of the DNS domain if possible") .optflag("i", "ip-address", "Display the network address(es) of the host") // TODO: support --long .optflag("f", "fqdn", "Display the FQDN (Fully Qualified Domain Name) (default)") .optflag("s", "short", "Display the short hostname (the portion before the first dot) if \ possible") .parse(args); match matches.free.len() { 0 => display_hostname(matches), 1 => { if let Err(err) = xsethostname(matches.free.last().unwrap()) { show_error!("{}", err); 1 } else { 0 } } _ => { show_error!("{}", msg_wrong_number_of_arguments!(0, 1)); 1 } } } fn display_hostname(matches: Matches) -> i32 { let hostname = return_if_err!(1, xgethostname()); if matches.opt_present("i") { // XXX: to_socket_addrs needs hostname:port so append a dummy port and remove it later. // This was originally supposed to use std::net::lookup_host, but that seems to be // deprecated. Perhaps we should use the dns-lookup crate? let hostname = hostname + ":1"; match hostname.to_socket_addrs() { Ok(addresses) => { let mut hashset = HashSet::new(); let mut output = String::new(); for addr in addresses { // XXX: not sure why this is necessary... if!hashset.contains(&addr) { let mut ip = format!("{}", addr); if ip.ends_with(":1") { let len = ip.len(); ip.truncate(len - 2); } output.push_str(&ip); output.push_str(" "); hashset.insert(addr); } } let len = output.len(); if len > 0 { println!("{}", &output[0..len - 1]); } 0 } Err(f) => { show_error!("{}", f); 1 } } } else { if matches.opt_present("s") || matches.opt_present("d") { let mut it = hostname.char_indices().filter(|&ci| ci.1 == '.'); if let Some(ci) = it.next() { if matches.opt_present("s") { println!("{}", &hostname[0..ci.0]); } else { println!("{}", &hostname[ci.0 + 1..]); } return 0; } } println!("{}", hostname); 0 } } #[cfg(not(windows))] fn xgethostname() -> io::Result<String> { use std::ffi::CStr; let namelen = 256; let mut name: Vec<u8> = repeat(0).take(namelen).collect(); let err = unsafe { gethostname( name.as_mut_ptr() as *mut libc::c_char, namelen as libc::size_t, ) }; if err == 0 { let null_pos = name.iter().position(|byte| *byte == 0).unwrap_or(namelen); if null_pos == namelen { name.push(0); } Ok(CStr::from_bytes_with_nul(&name[..null_pos + 1]) .unwrap() .to_string_lossy() .into_owned()) } else { Err(io::Error::last_os_error()) } } #[cfg(windows)] fn xgethostname() -> io::Result<String> { let namelen = 256; let mut name: Vec<u16> = repeat(0).take(namelen).collect(); let err = unsafe { GetHostNameW(name.as_mut_ptr(), namelen as libc::c_int) }; if err == 0 { Ok(String::from_wide_null(&name)) } else { Err(io::Error::last_os_error()) } } #[cfg(not(windows))] fn xsethostname(name: &str) -> io::Result<()> { let vec_name: Vec<libc::c_char> = name.bytes().map(|c| c as libc::c_char).collect(); let err = unsafe { sethostname(vec_name.as_ptr(), vec_name.len() as _) }; if err!= 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } #[cfg(windows)] fn xsethostname(name: &str) -> io::Result<()>
{ use std::ffi::OsStr; let wide_name = OsStr::new(name).to_wide_null(); let err = unsafe { SetComputerNameExW(ComputerNamePhysicalDnsHostname, wide_name.as_ptr()) }; if err == 0 { // NOTE: the above is correct, failure is when the function returns 0 apparently Err(io::Error::last_os_error()) } else { Ok(()) } }
identifier_body
hostname.rs
#![crate_name = "uu_hostname"]
/* * This file is part of the uutils coreutils package. * * (c) Alan Andrade <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; #[cfg(windows)] extern crate winapi; #[macro_use] extern crate uucore; use std::collections::hash_set::HashSet; use std::iter::repeat; use std::io; use std::str; use std::net::ToSocketAddrs; use getopts::Matches; #[cfg(windows)] use winapi::um::winsock2::{GetHostNameW, WSACleanup, WSAStartup}; #[cfg(windows)] use winapi::um::sysinfoapi::{ComputerNamePhysicalDnsHostname, SetComputerNameExW}; #[cfg(windows)] use winapi::shared::minwindef::MAKEWORD; #[cfg(windows)] use uucore::wide::*; #[cfg(not(windows))] use libc::gethostname; #[cfg(not(windows))] use libc::sethostname; const SYNTAX: &'static str = "[OPTION]... [HOSTNAME]"; const SUMMARY: &'static str = "Print or set the system's host name."; const LONG_HELP: &'static str = ""; pub fn uumain(args: Vec<String>) -> i32 { #[cfg(windows)] unsafe { let mut data = std::mem::uninitialized(); if WSAStartup(MAKEWORD(2, 2), &mut data as *mut _)!= 0 { eprintln!("Failed to start Winsock 2.2"); return 1; } } let result = execute(args); #[cfg(windows)] unsafe { WSACleanup(); } result } fn execute(args: Vec<String>) -> i32 { let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP) .optflag("d", "domain", "Display the name of the DNS domain if possible") .optflag("i", "ip-address", "Display the network address(es) of the host") // TODO: support --long .optflag("f", "fqdn", "Display the FQDN (Fully Qualified Domain Name) (default)") .optflag("s", "short", "Display the short hostname (the portion before the first dot) if \ possible") .parse(args); match matches.free.len() { 0 => display_hostname(matches), 1 => { if let Err(err) = xsethostname(matches.free.last().unwrap()) { show_error!("{}", err); 1 } else { 0 } } _ => { show_error!("{}", msg_wrong_number_of_arguments!(0, 1)); 1 } } } fn display_hostname(matches: Matches) -> i32 { let hostname = return_if_err!(1, xgethostname()); if matches.opt_present("i") { // XXX: to_socket_addrs needs hostname:port so append a dummy port and remove it later. // This was originally supposed to use std::net::lookup_host, but that seems to be // deprecated. Perhaps we should use the dns-lookup crate? let hostname = hostname + ":1"; match hostname.to_socket_addrs() { Ok(addresses) => { let mut hashset = HashSet::new(); let mut output = String::new(); for addr in addresses { // XXX: not sure why this is necessary... if!hashset.contains(&addr) { let mut ip = format!("{}", addr); if ip.ends_with(":1") { let len = ip.len(); ip.truncate(len - 2); } output.push_str(&ip); output.push_str(" "); hashset.insert(addr); } } let len = output.len(); if len > 0 { println!("{}", &output[0..len - 1]); } 0 } Err(f) => { show_error!("{}", f); 1 } } } else { if matches.opt_present("s") || matches.opt_present("d") { let mut it = hostname.char_indices().filter(|&ci| ci.1 == '.'); if let Some(ci) = it.next() { if matches.opt_present("s") { println!("{}", &hostname[0..ci.0]); } else { println!("{}", &hostname[ci.0 + 1..]); } return 0; } } println!("{}", hostname); 0 } } #[cfg(not(windows))] fn xgethostname() -> io::Result<String> { use std::ffi::CStr; let namelen = 256; let mut name: Vec<u8> = repeat(0).take(namelen).collect(); let err = unsafe { gethostname( name.as_mut_ptr() as *mut libc::c_char, namelen as libc::size_t, ) }; if err == 0 { let null_pos = name.iter().position(|byte| *byte == 0).unwrap_or(namelen); if null_pos == namelen { name.push(0); } Ok(CStr::from_bytes_with_nul(&name[..null_pos + 1]) .unwrap() .to_string_lossy() .into_owned()) } else { Err(io::Error::last_os_error()) } } #[cfg(windows)] fn xgethostname() -> io::Result<String> { let namelen = 256; let mut name: Vec<u16> = repeat(0).take(namelen).collect(); let err = unsafe { GetHostNameW(name.as_mut_ptr(), namelen as libc::c_int) }; if err == 0 { Ok(String::from_wide_null(&name)) } else { Err(io::Error::last_os_error()) } } #[cfg(not(windows))] fn xsethostname(name: &str) -> io::Result<()> { let vec_name: Vec<libc::c_char> = name.bytes().map(|c| c as libc::c_char).collect(); let err = unsafe { sethostname(vec_name.as_ptr(), vec_name.len() as _) }; if err!= 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } #[cfg(windows)] fn xsethostname(name: &str) -> io::Result<()> { use std::ffi::OsStr; let wide_name = OsStr::new(name).to_wide_null(); let err = unsafe { SetComputerNameExW(ComputerNamePhysicalDnsHostname, wide_name.as_ptr()) }; if err == 0 { // NOTE: the above is correct, failure is when the function returns 0 apparently Err(io::Error::last_os_error()) } else { Ok(()) } }
random_line_split
hostname.rs
#![crate_name = "uu_hostname"] /* * This file is part of the uutils coreutils package. * * (c) Alan Andrade <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; #[cfg(windows)] extern crate winapi; #[macro_use] extern crate uucore; use std::collections::hash_set::HashSet; use std::iter::repeat; use std::io; use std::str; use std::net::ToSocketAddrs; use getopts::Matches; #[cfg(windows)] use winapi::um::winsock2::{GetHostNameW, WSACleanup, WSAStartup}; #[cfg(windows)] use winapi::um::sysinfoapi::{ComputerNamePhysicalDnsHostname, SetComputerNameExW}; #[cfg(windows)] use winapi::shared::minwindef::MAKEWORD; #[cfg(windows)] use uucore::wide::*; #[cfg(not(windows))] use libc::gethostname; #[cfg(not(windows))] use libc::sethostname; const SYNTAX: &'static str = "[OPTION]... [HOSTNAME]"; const SUMMARY: &'static str = "Print or set the system's host name."; const LONG_HELP: &'static str = ""; pub fn uumain(args: Vec<String>) -> i32 { #[cfg(windows)] unsafe { let mut data = std::mem::uninitialized(); if WSAStartup(MAKEWORD(2, 2), &mut data as *mut _)!= 0 { eprintln!("Failed to start Winsock 2.2"); return 1; } } let result = execute(args); #[cfg(windows)] unsafe { WSACleanup(); } result } fn execute(args: Vec<String>) -> i32 { let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP) .optflag("d", "domain", "Display the name of the DNS domain if possible") .optflag("i", "ip-address", "Display the network address(es) of the host") // TODO: support --long .optflag("f", "fqdn", "Display the FQDN (Fully Qualified Domain Name) (default)") .optflag("s", "short", "Display the short hostname (the portion before the first dot) if \ possible") .parse(args); match matches.free.len() { 0 => display_hostname(matches), 1 => { if let Err(err) = xsethostname(matches.free.last().unwrap()) { show_error!("{}", err); 1 } else { 0 } } _ => { show_error!("{}", msg_wrong_number_of_arguments!(0, 1)); 1 } } } fn display_hostname(matches: Matches) -> i32 { let hostname = return_if_err!(1, xgethostname()); if matches.opt_present("i") { // XXX: to_socket_addrs needs hostname:port so append a dummy port and remove it later. // This was originally supposed to use std::net::lookup_host, but that seems to be // deprecated. Perhaps we should use the dns-lookup crate? let hostname = hostname + ":1"; match hostname.to_socket_addrs() { Ok(addresses) => { let mut hashset = HashSet::new(); let mut output = String::new(); for addr in addresses { // XXX: not sure why this is necessary... if!hashset.contains(&addr) { let mut ip = format!("{}", addr); if ip.ends_with(":1") { let len = ip.len(); ip.truncate(len - 2); } output.push_str(&ip); output.push_str(" "); hashset.insert(addr); } } let len = output.len(); if len > 0 { println!("{}", &output[0..len - 1]); } 0 } Err(f) => { show_error!("{}", f); 1 } } } else { if matches.opt_present("s") || matches.opt_present("d") { let mut it = hostname.char_indices().filter(|&ci| ci.1 == '.'); if let Some(ci) = it.next() { if matches.opt_present("s") { println!("{}", &hostname[0..ci.0]); } else { println!("{}", &hostname[ci.0 + 1..]); } return 0; } } println!("{}", hostname); 0 } } #[cfg(not(windows))] fn
() -> io::Result<String> { use std::ffi::CStr; let namelen = 256; let mut name: Vec<u8> = repeat(0).take(namelen).collect(); let err = unsafe { gethostname( name.as_mut_ptr() as *mut libc::c_char, namelen as libc::size_t, ) }; if err == 0 { let null_pos = name.iter().position(|byte| *byte == 0).unwrap_or(namelen); if null_pos == namelen { name.push(0); } Ok(CStr::from_bytes_with_nul(&name[..null_pos + 1]) .unwrap() .to_string_lossy() .into_owned()) } else { Err(io::Error::last_os_error()) } } #[cfg(windows)] fn xgethostname() -> io::Result<String> { let namelen = 256; let mut name: Vec<u16> = repeat(0).take(namelen).collect(); let err = unsafe { GetHostNameW(name.as_mut_ptr(), namelen as libc::c_int) }; if err == 0 { Ok(String::from_wide_null(&name)) } else { Err(io::Error::last_os_error()) } } #[cfg(not(windows))] fn xsethostname(name: &str) -> io::Result<()> { let vec_name: Vec<libc::c_char> = name.bytes().map(|c| c as libc::c_char).collect(); let err = unsafe { sethostname(vec_name.as_ptr(), vec_name.len() as _) }; if err!= 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } #[cfg(windows)] fn xsethostname(name: &str) -> io::Result<()> { use std::ffi::OsStr; let wide_name = OsStr::new(name).to_wide_null(); let err = unsafe { SetComputerNameExW(ComputerNamePhysicalDnsHostname, wide_name.as_ptr()) }; if err == 0 { // NOTE: the above is correct, failure is when the function returns 0 apparently Err(io::Error::last_os_error()) } else { Ok(()) } }
xgethostname
identifier_name
font.rs
use {JamResult, JamError}; use rusttype::{self, FontCollection}; use {FontLoadError, load_file_contents}; use std::path::Path; use render::read_directory_paths; pub struct OurFont { pub font: rusttype::Font<'static>, } pub fn load_font(full_path: &Path) -> Result<OurFont, FontLoadError> { let bytes = load_file_contents(&full_path).map_err(|io| FontLoadError::CouldntLoadFile(full_path.to_path_buf(), io))?; let collection = FontCollection::from_bytes(bytes.to_vec()); let font = collection.into_font().ok_or(FontLoadError::CouldntReadAsFont(full_path.to_path_buf()))?; Ok(OurFont { font: font, }) } pub fn load_fonts_in_path(full_path: &Path) -> JamResult<Vec<OurFont>> { let mut fonts = Vec::new(); let mut paths = read_directory_paths(full_path)?; paths.sort(); println!("sorted paths for fonts -> {:?}", paths); for path in paths {
} } Ok(fonts) }
if let Some(extension) = path.extension().and_then(|p| p.to_str()).map(|s| s.to_lowercase()) { if extension == "ttf" { let font = load_font(path.as_path()).map_err(JamError::FontLoadError)?; fonts.push(font); }
random_line_split
font.rs
use {JamResult, JamError}; use rusttype::{self, FontCollection}; use {FontLoadError, load_file_contents}; use std::path::Path; use render::read_directory_paths; pub struct OurFont { pub font: rusttype::Font<'static>, } pub fn load_font(full_path: &Path) -> Result<OurFont, FontLoadError> { let bytes = load_file_contents(&full_path).map_err(|io| FontLoadError::CouldntLoadFile(full_path.to_path_buf(), io))?; let collection = FontCollection::from_bytes(bytes.to_vec()); let font = collection.into_font().ok_or(FontLoadError::CouldntReadAsFont(full_path.to_path_buf()))?; Ok(OurFont { font: font, }) } pub fn
(full_path: &Path) -> JamResult<Vec<OurFont>> { let mut fonts = Vec::new(); let mut paths = read_directory_paths(full_path)?; paths.sort(); println!("sorted paths for fonts -> {:?}", paths); for path in paths { if let Some(extension) = path.extension().and_then(|p| p.to_str()).map(|s| s.to_lowercase()) { if extension == "ttf" { let font = load_font(path.as_path()).map_err(JamError::FontLoadError)?; fonts.push(font); } } } Ok(fonts) }
load_fonts_in_path
identifier_name
font.rs
use {JamResult, JamError}; use rusttype::{self, FontCollection}; use {FontLoadError, load_file_contents}; use std::path::Path; use render::read_directory_paths; pub struct OurFont { pub font: rusttype::Font<'static>, } pub fn load_font(full_path: &Path) -> Result<OurFont, FontLoadError> { let bytes = load_file_contents(&full_path).map_err(|io| FontLoadError::CouldntLoadFile(full_path.to_path_buf(), io))?; let collection = FontCollection::from_bytes(bytes.to_vec()); let font = collection.into_font().ok_or(FontLoadError::CouldntReadAsFont(full_path.to_path_buf()))?; Ok(OurFont { font: font, }) } pub fn load_fonts_in_path(full_path: &Path) -> JamResult<Vec<OurFont>> { let mut fonts = Vec::new(); let mut paths = read_directory_paths(full_path)?; paths.sort(); println!("sorted paths for fonts -> {:?}", paths); for path in paths { if let Some(extension) = path.extension().and_then(|p| p.to_str()).map(|s| s.to_lowercase()) { if extension == "ttf"
} } Ok(fonts) }
{ let font = load_font(path.as_path()).map_err(JamError::FontLoadError)?; fonts.push(font); }
conditional_block
font.rs
use {JamResult, JamError}; use rusttype::{self, FontCollection}; use {FontLoadError, load_file_contents}; use std::path::Path; use render::read_directory_paths; pub struct OurFont { pub font: rusttype::Font<'static>, } pub fn load_font(full_path: &Path) -> Result<OurFont, FontLoadError> { let bytes = load_file_contents(&full_path).map_err(|io| FontLoadError::CouldntLoadFile(full_path.to_path_buf(), io))?; let collection = FontCollection::from_bytes(bytes.to_vec()); let font = collection.into_font().ok_or(FontLoadError::CouldntReadAsFont(full_path.to_path_buf()))?; Ok(OurFont { font: font, }) } pub fn load_fonts_in_path(full_path: &Path) -> JamResult<Vec<OurFont>>
{ let mut fonts = Vec::new(); let mut paths = read_directory_paths(full_path)?; paths.sort(); println!("sorted paths for fonts -> {:?}", paths); for path in paths { if let Some(extension) = path.extension().and_then(|p| p.to_str()).map(|s| s.to_lowercase()) { if extension == "ttf" { let font = load_font(path.as_path()).map_err(JamError::FontLoadError)?; fonts.push(font); } } } Ok(fonts) }
identifier_body
mod.rs
mod builder; mod master_key; mod tlv; use bytes; use decompress; use {Error, FileType}; use self::builder::HeaderBuilder; use protected::ProtectedStream; use std::io::Read; #[derive(Debug, PartialEq)] enum CipherType { Aes, } #[derive(Debug, PartialEq)] enum CompressionType { None, Gzip, } #[derive(Debug, PartialEq)] enum
{ None, Rc4, Salsa20, } #[derive(Debug)] pub struct Header { version: u32, cipher: CipherType, compression: CompressionType, master_seed: [u8; 32], transform_seed: [u8; 32], transform_rounds: u64, encryption_iv: [u8; 16], protected_stream_key: [u8; 32], stream_start_bytes: [u8; 32], inner_random_stream: InnerRandomStreamType, } impl Header { pub fn master_key(&self, passphrase: &str) -> Result<[u8; 32], Error> { master_key::key(&self.transform_seed, self.transform_rounds, &self.master_seed, passphrase) } pub fn encryption_iv(&self) -> [u8; 16] { self.encryption_iv } pub fn stream_start_bytes(&self) -> [u8; 32] { self.stream_start_bytes } pub fn decompress(&self, read: Box<Read>) -> Result<Box<Read>, Error> { match self.compression { CompressionType::None => decompress::none(read), CompressionType::Gzip => decompress::gzip(read), } } pub fn protected_stream(&self) -> Box<ProtectedStream> { match self.inner_random_stream { InnerRandomStreamType::None => ProtectedStream::none(), InnerRandomStreamType::Rc4 => ProtectedStream::rc4(&self.protected_stream_key), InnerRandomStreamType::Salsa20 => ProtectedStream::salsa20(&self.protected_stream_key), } } } pub fn read_header(file_type: FileType, reader: &mut Read) -> Result<Header, Error> { try!(check_file_type(file_type)); let version = try!(read_version(reader)); handle_tlvs(reader, version) } fn check_file_type(file_type: FileType) -> Result<(), Error> { match file_type { FileType::KeePass2 => Ok(()), _ => Err(Error::UnsupportedFileType(file_type)), } } fn read_version(reader: &mut Read) -> Result<u32, Error> { bytes::read_u32(reader) } fn handle_tlvs(reader: &mut Read, version: u32) -> Result<Header, Error> { let mut builder = HeaderBuilder::new(version); for tlv in tlv::tlvs(reader) { match tlv { Ok(t) => builder.apply(t), Err(e) => return Err(e), } } builder.build() } #[cfg(test)] mod test { use {Error, FileType}; #[test] pub fn should_return_error_if_wrong_file_type() { let result = super::read_header(FileType::KeePass1, &mut &vec![][..]); match result { Err(Error::UnsupportedFileType(FileType::KeePass1)) => (), _ => panic!("Invalid result: {:#?}", result), } } }
InnerRandomStreamType
identifier_name
mod.rs
mod builder; mod master_key; mod tlv; use bytes; use decompress; use {Error, FileType}; use self::builder::HeaderBuilder; use protected::ProtectedStream; use std::io::Read; #[derive(Debug, PartialEq)] enum CipherType { Aes, } #[derive(Debug, PartialEq)] enum CompressionType { None, Gzip, } #[derive(Debug, PartialEq)] enum InnerRandomStreamType { None, Rc4, Salsa20, } #[derive(Debug)] pub struct Header { version: u32, cipher: CipherType, compression: CompressionType, master_seed: [u8; 32], transform_seed: [u8; 32], transform_rounds: u64, encryption_iv: [u8; 16], protected_stream_key: [u8; 32], stream_start_bytes: [u8; 32], inner_random_stream: InnerRandomStreamType, } impl Header { pub fn master_key(&self, passphrase: &str) -> Result<[u8; 32], Error> { master_key::key(&self.transform_seed, self.transform_rounds, &self.master_seed, passphrase) } pub fn encryption_iv(&self) -> [u8; 16] { self.encryption_iv } pub fn stream_start_bytes(&self) -> [u8; 32] { self.stream_start_bytes } pub fn decompress(&self, read: Box<Read>) -> Result<Box<Read>, Error> { match self.compression { CompressionType::None => decompress::none(read), CompressionType::Gzip => decompress::gzip(read), } } pub fn protected_stream(&self) -> Box<ProtectedStream> { match self.inner_random_stream { InnerRandomStreamType::None => ProtectedStream::none(), InnerRandomStreamType::Rc4 => ProtectedStream::rc4(&self.protected_stream_key), InnerRandomStreamType::Salsa20 => ProtectedStream::salsa20(&self.protected_stream_key), } } } pub fn read_header(file_type: FileType, reader: &mut Read) -> Result<Header, Error> { try!(check_file_type(file_type)); let version = try!(read_version(reader)); handle_tlvs(reader, version) } fn check_file_type(file_type: FileType) -> Result<(), Error> { match file_type { FileType::KeePass2 => Ok(()), _ => Err(Error::UnsupportedFileType(file_type)), } } fn read_version(reader: &mut Read) -> Result<u32, Error> { bytes::read_u32(reader) } fn handle_tlvs(reader: &mut Read, version: u32) -> Result<Header, Error> { let mut builder = HeaderBuilder::new(version); for tlv in tlv::tlvs(reader) { match tlv { Ok(t) => builder.apply(t), Err(e) => return Err(e), } } builder.build() } #[cfg(test)] mod test { use {Error, FileType}; #[test] pub fn should_return_error_if_wrong_file_type() { let result = super::read_header(FileType::KeePass1, &mut &vec![][..]); match result { Err(Error::UnsupportedFileType(FileType::KeePass1)) => (),
} }
_ => panic!("Invalid result: {:#?}", result), }
random_line_split
mod.rs
mod builder; mod master_key; mod tlv; use bytes; use decompress; use {Error, FileType}; use self::builder::HeaderBuilder; use protected::ProtectedStream; use std::io::Read; #[derive(Debug, PartialEq)] enum CipherType { Aes, } #[derive(Debug, PartialEq)] enum CompressionType { None, Gzip, } #[derive(Debug, PartialEq)] enum InnerRandomStreamType { None, Rc4, Salsa20, } #[derive(Debug)] pub struct Header { version: u32, cipher: CipherType, compression: CompressionType, master_seed: [u8; 32], transform_seed: [u8; 32], transform_rounds: u64, encryption_iv: [u8; 16], protected_stream_key: [u8; 32], stream_start_bytes: [u8; 32], inner_random_stream: InnerRandomStreamType, } impl Header { pub fn master_key(&self, passphrase: &str) -> Result<[u8; 32], Error> { master_key::key(&self.transform_seed, self.transform_rounds, &self.master_seed, passphrase) } pub fn encryption_iv(&self) -> [u8; 16] { self.encryption_iv } pub fn stream_start_bytes(&self) -> [u8; 32] { self.stream_start_bytes } pub fn decompress(&self, read: Box<Read>) -> Result<Box<Read>, Error> { match self.compression { CompressionType::None => decompress::none(read), CompressionType::Gzip => decompress::gzip(read), } } pub fn protected_stream(&self) -> Box<ProtectedStream> { match self.inner_random_stream { InnerRandomStreamType::None => ProtectedStream::none(), InnerRandomStreamType::Rc4 => ProtectedStream::rc4(&self.protected_stream_key), InnerRandomStreamType::Salsa20 => ProtectedStream::salsa20(&self.protected_stream_key), } } } pub fn read_header(file_type: FileType, reader: &mut Read) -> Result<Header, Error> { try!(check_file_type(file_type)); let version = try!(read_version(reader)); handle_tlvs(reader, version) } fn check_file_type(file_type: FileType) -> Result<(), Error> { match file_type { FileType::KeePass2 => Ok(()), _ => Err(Error::UnsupportedFileType(file_type)), } } fn read_version(reader: &mut Read) -> Result<u32, Error> { bytes::read_u32(reader) } fn handle_tlvs(reader: &mut Read, version: u32) -> Result<Header, Error>
#[cfg(test)] mod test { use {Error, FileType}; #[test] pub fn should_return_error_if_wrong_file_type() { let result = super::read_header(FileType::KeePass1, &mut &vec![][..]); match result { Err(Error::UnsupportedFileType(FileType::KeePass1)) => (), _ => panic!("Invalid result: {:#?}", result), } } }
{ let mut builder = HeaderBuilder::new(version); for tlv in tlv::tlvs(reader) { match tlv { Ok(t) => builder.apply(t), Err(e) => return Err(e), } } builder.build() }
identifier_body
data.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Data needed to style a Gecko document. use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut}; use context::TraversalStatistics; use dom::TElement; use gecko_bindings::bindings::{self, RawServoStyleSet}; use gecko_bindings::structs::{RawGeckoPresContextOwned, ServoStyleSetSizes, ServoStyleSheet}; use gecko_bindings::structs::{StyleSheetInfo, ServoStyleSheetInner, nsIDocument, self}; use gecko_bindings::sugar::ownership::{HasArcFFI, HasBoxFFI, HasFFI, HasSimpleFFI}; use invalidation::media_queries::{MediaListKey, ToMediaListKey}; use malloc_size_of::MallocSizeOfOps; use media_queries::{Device, MediaList}; use properties::ComputedValues; use selector_parser::SnapshotMap; use servo_arc::Arc; use shared_lock::{Locked, StylesheetGuards, SharedRwLockReadGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use stylesheets::{StylesheetContents, StylesheetInDocument}; use stylist::Stylist; /// Little wrapper to a Gecko style sheet. #[derive(Debug, Eq, PartialEq)] pub struct GeckoStyleSheet(*const ServoStyleSheet); impl ToMediaListKey for ::gecko::data::GeckoStyleSheet { fn to_media_list_key(&self) -> MediaListKey { use std::mem; unsafe { MediaListKey::from_raw(mem::transmute(self.0)) } } } impl GeckoStyleSheet { /// Create a `GeckoStyleSheet` from a raw `ServoStyleSheet` pointer. #[inline] pub unsafe fn new(s: *const ServoStyleSheet) -> Self { debug_assert!(!s.is_null()); bindings::Gecko_StyleSheet_AddRef(s); Self::from_addrefed(s) } /// Create a `GeckoStyleSheet` from a raw `ServoStyleSheet` pointer that /// already holds a strong reference. #[inline] pub unsafe fn from_addrefed(s: *const ServoStyleSheet) -> Self { debug_assert!(!s.is_null()); GeckoStyleSheet(s) } /// Get the raw `ServoStyleSheet` that we're wrapping. pub fn raw(&self) -> &ServoStyleSheet { unsafe { &*self.0 } } fn inner(&self) -> &ServoStyleSheetInner { unsafe { &*(self.raw()._base.mInner as *const StyleSheetInfo as *const ServoStyleSheetInner) } } } impl Drop for GeckoStyleSheet { fn drop(&mut self) { unsafe { bindings::Gecko_StyleSheet_Release(self.0) }; } } impl Clone for GeckoStyleSheet { fn clone(&self) -> Self { unsafe { bindings::Gecko_StyleSheet_AddRef(self.0) }; GeckoStyleSheet(self.0) } } impl StylesheetInDocument for GeckoStyleSheet { fn contents(&self, _: &SharedRwLockReadGuard) -> &StylesheetContents { debug_assert!(!self.inner().mContents.mRawPtr.is_null()); unsafe { let contents = (&**StylesheetContents::as_arc(&&*self.inner().mContents.mRawPtr)) as *const _; &*contents } } fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList> { use gecko_bindings::structs::ServoMediaList; use std::mem; unsafe { let servo_media_list = self.raw()._base.mMedia.mRawPtr as *const ServoMediaList; if servo_media_list.is_null() { return None; } let raw_list = &*(*servo_media_list).mRawList.mRawPtr; let list = Locked::<MediaList>::as_arc(mem::transmute(&raw_list)); Some(list.read_with(guard)) } } // All the stylesheets Servo knows about are enabled, because that state is // handled externally by Gecko. fn enabled(&self) -> bool { true } } #[derive(Default)] /// Helper struct for counting traversals pub struct TraversalCount { /// Total number of events pub total_count: AtomicUsize, /// Number of events which were parallel pub parallel_count: AtomicUsize } impl TraversalCount { fn record(&self, parallel: bool, count: u32) { self.total_count.fetch_add(count as usize, Ordering::Relaxed); if parallel { self.parallel_count.fetch_add(count as usize, Ordering::Relaxed); } } fn get(&self) -> (u32, u32) { (self.total_count.load(Ordering::Relaxed) as u32, self.parallel_count.load(Ordering::Relaxed) as u32) } } /// The container for data that a Servo-backed Gecko document needs to style /// itself. pub struct PerDocumentStyleDataImpl { /// Rule processor. pub stylist: Stylist, /// Counter for traversals that could have been parallel, for telemetry pub traversal_count: TraversalCount, /// Counter for traversals, weighted by elements traversed, pub traversal_count_traversed: TraversalCount, /// Counter for traversals, weighted by elements styled, pub traversal_count_styled: TraversalCount, } /// The data itself is an `AtomicRefCell`, which guarantees the proper semantics /// and unexpected races while trying to mutate it. pub struct
(AtomicRefCell<PerDocumentStyleDataImpl>); impl PerDocumentStyleData { /// Create a dummy `PerDocumentStyleData`. pub fn new(pres_context: RawGeckoPresContextOwned) -> Self { let device = Device::new(pres_context); // FIXME(emilio, tlin): How is this supposed to work with XBL? This is // right now not always honored, see bug 1405543... // // Should we just force XBL Stylists to be NoQuirks? let quirks_mode = unsafe { (*device.pres_context().mDocument.raw::<nsIDocument>()).mCompatMode }; PerDocumentStyleData(AtomicRefCell::new(PerDocumentStyleDataImpl { stylist: Stylist::new(device, quirks_mode.into()), traversal_count: Default::default(), traversal_count_traversed: Default::default(), traversal_count_styled: Default::default(), })) } /// Get an immutable reference to this style data. pub fn borrow(&self) -> AtomicRef<PerDocumentStyleDataImpl> { self.0.borrow() } /// Get an mutable reference to this style data. pub fn borrow_mut(&self) -> AtomicRefMut<PerDocumentStyleDataImpl> { self.0.borrow_mut() } } impl Drop for PerDocumentStyleDataImpl { fn drop(&mut self) { if!structs::GECKO_IS_NIGHTLY { return } let (total, parallel) = self.traversal_count.get(); let (total_t, parallel_t) = self.traversal_count_traversed.get(); let (total_s, parallel_s) = self.traversal_count_styled.get(); unsafe { bindings::Gecko_RecordTraversalStatistics(total, parallel, total_t, parallel_t, total_s, parallel_s) } } } impl PerDocumentStyleDataImpl { /// Recreate the style data if the stylesheets have changed. pub fn flush_stylesheets<E>( &mut self, guard: &SharedRwLockReadGuard, document_element: Option<E>, snapshots: Option<&SnapshotMap>, ) -> bool where E: TElement, { self.stylist.flush( &StylesheetGuards::same(guard), document_element, snapshots, ) } /// Returns whether private browsing is enabled. fn is_private_browsing_enabled(&self) -> bool { let doc = self.stylist.device().pres_context().mDocument.raw::<nsIDocument>(); unsafe { bindings::Gecko_IsPrivateBrowsingEnabled(doc) } } /// Returns whether the document is being used as an image. fn is_being_used_as_an_image(&self) -> bool { let doc = self.stylist.device().pres_context().mDocument.raw::<nsIDocument>(); unsafe { (*doc).mIsBeingUsedAsImage() } } /// Get the default computed values for this document. pub fn default_computed_values(&self) -> &Arc<ComputedValues> { self.stylist.device().default_computed_values_arc() } /// Returns whether visited links are enabled. fn visited_links_enabled(&self) -> bool { unsafe { structs::StylePrefs_sVisitedLinksEnabled } } /// Returns whether visited styles are enabled. pub fn visited_styles_enabled(&self) -> bool { if!self.visited_links_enabled() { return false; } if self.is_private_browsing_enabled() { return false; } if self.is_being_used_as_an_image() { return false; } true } /// Measure heap usage. pub fn add_size_of(&self, ops: &mut MallocSizeOfOps, sizes: &mut ServoStyleSetSizes) { self.stylist.add_size_of(ops, sizes); } /// Record that a traversal happened for later collection as telemetry pub fn record_traversal(&self, was_parallel: bool, stats: Option<TraversalStatistics>) { self.traversal_count.record(was_parallel, 1); if let Some(stats) = stats { self.traversal_count_traversed.record(was_parallel, stats.elements_traversed); self.traversal_count_styled.record(was_parallel, stats.elements_styled); } } } unsafe impl HasFFI for PerDocumentStyleData { type FFIType = RawServoStyleSet; } unsafe impl HasSimpleFFI for PerDocumentStyleData {} unsafe impl HasBoxFFI for PerDocumentStyleData {}
PerDocumentStyleData
identifier_name
data.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Data needed to style a Gecko document. use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut}; use context::TraversalStatistics; use dom::TElement; use gecko_bindings::bindings::{self, RawServoStyleSet}; use gecko_bindings::structs::{RawGeckoPresContextOwned, ServoStyleSetSizes, ServoStyleSheet}; use gecko_bindings::structs::{StyleSheetInfo, ServoStyleSheetInner, nsIDocument, self}; use gecko_bindings::sugar::ownership::{HasArcFFI, HasBoxFFI, HasFFI, HasSimpleFFI}; use invalidation::media_queries::{MediaListKey, ToMediaListKey}; use malloc_size_of::MallocSizeOfOps; use media_queries::{Device, MediaList}; use properties::ComputedValues; use selector_parser::SnapshotMap; use servo_arc::Arc; use shared_lock::{Locked, StylesheetGuards, SharedRwLockReadGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use stylesheets::{StylesheetContents, StylesheetInDocument}; use stylist::Stylist; /// Little wrapper to a Gecko style sheet. #[derive(Debug, Eq, PartialEq)] pub struct GeckoStyleSheet(*const ServoStyleSheet); impl ToMediaListKey for ::gecko::data::GeckoStyleSheet { fn to_media_list_key(&self) -> MediaListKey { use std::mem; unsafe { MediaListKey::from_raw(mem::transmute(self.0)) } } } impl GeckoStyleSheet { /// Create a `GeckoStyleSheet` from a raw `ServoStyleSheet` pointer. #[inline] pub unsafe fn new(s: *const ServoStyleSheet) -> Self { debug_assert!(!s.is_null()); bindings::Gecko_StyleSheet_AddRef(s); Self::from_addrefed(s) } /// Create a `GeckoStyleSheet` from a raw `ServoStyleSheet` pointer that /// already holds a strong reference. #[inline] pub unsafe fn from_addrefed(s: *const ServoStyleSheet) -> Self { debug_assert!(!s.is_null()); GeckoStyleSheet(s) } /// Get the raw `ServoStyleSheet` that we're wrapping. pub fn raw(&self) -> &ServoStyleSheet { unsafe { &*self.0 } } fn inner(&self) -> &ServoStyleSheetInner { unsafe { &*(self.raw()._base.mInner as *const StyleSheetInfo as *const ServoStyleSheetInner) } } } impl Drop for GeckoStyleSheet { fn drop(&mut self) { unsafe { bindings::Gecko_StyleSheet_Release(self.0) }; } } impl Clone for GeckoStyleSheet { fn clone(&self) -> Self { unsafe { bindings::Gecko_StyleSheet_AddRef(self.0) }; GeckoStyleSheet(self.0) } } impl StylesheetInDocument for GeckoStyleSheet { fn contents(&self, _: &SharedRwLockReadGuard) -> &StylesheetContents { debug_assert!(!self.inner().mContents.mRawPtr.is_null()); unsafe { let contents = (&**StylesheetContents::as_arc(&&*self.inner().mContents.mRawPtr)) as *const _; &*contents } } fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList> { use gecko_bindings::structs::ServoMediaList; use std::mem; unsafe { let servo_media_list = self.raw()._base.mMedia.mRawPtr as *const ServoMediaList; if servo_media_list.is_null() { return None; } let raw_list = &*(*servo_media_list).mRawList.mRawPtr; let list = Locked::<MediaList>::as_arc(mem::transmute(&raw_list)); Some(list.read_with(guard)) } } // All the stylesheets Servo knows about are enabled, because that state is // handled externally by Gecko. fn enabled(&self) -> bool { true } } #[derive(Default)] /// Helper struct for counting traversals pub struct TraversalCount { /// Total number of events pub total_count: AtomicUsize, /// Number of events which were parallel pub parallel_count: AtomicUsize } impl TraversalCount { fn record(&self, parallel: bool, count: u32) { self.total_count.fetch_add(count as usize, Ordering::Relaxed); if parallel { self.parallel_count.fetch_add(count as usize, Ordering::Relaxed); } } fn get(&self) -> (u32, u32) { (self.total_count.load(Ordering::Relaxed) as u32, self.parallel_count.load(Ordering::Relaxed) as u32) } } /// The container for data that a Servo-backed Gecko document needs to style /// itself. pub struct PerDocumentStyleDataImpl { /// Rule processor. pub stylist: Stylist, /// Counter for traversals that could have been parallel, for telemetry pub traversal_count: TraversalCount, /// Counter for traversals, weighted by elements traversed, pub traversal_count_traversed: TraversalCount, /// Counter for traversals, weighted by elements styled, pub traversal_count_styled: TraversalCount, } /// The data itself is an `AtomicRefCell`, which guarantees the proper semantics /// and unexpected races while trying to mutate it. pub struct PerDocumentStyleData(AtomicRefCell<PerDocumentStyleDataImpl>); impl PerDocumentStyleData { /// Create a dummy `PerDocumentStyleData`. pub fn new(pres_context: RawGeckoPresContextOwned) -> Self { let device = Device::new(pres_context); // FIXME(emilio, tlin): How is this supposed to work with XBL? This is // right now not always honored, see bug 1405543... // // Should we just force XBL Stylists to be NoQuirks? let quirks_mode = unsafe { (*device.pres_context().mDocument.raw::<nsIDocument>()).mCompatMode }; PerDocumentStyleData(AtomicRefCell::new(PerDocumentStyleDataImpl { stylist: Stylist::new(device, quirks_mode.into()), traversal_count: Default::default(), traversal_count_traversed: Default::default(), traversal_count_styled: Default::default(), })) } /// Get an immutable reference to this style data. pub fn borrow(&self) -> AtomicRef<PerDocumentStyleDataImpl> { self.0.borrow() } /// Get an mutable reference to this style data. pub fn borrow_mut(&self) -> AtomicRefMut<PerDocumentStyleDataImpl> { self.0.borrow_mut() } } impl Drop for PerDocumentStyleDataImpl { fn drop(&mut self) { if!structs::GECKO_IS_NIGHTLY { return } let (total, parallel) = self.traversal_count.get(); let (total_t, parallel_t) = self.traversal_count_traversed.get(); let (total_s, parallel_s) = self.traversal_count_styled.get(); unsafe { bindings::Gecko_RecordTraversalStatistics(total, parallel, total_t, parallel_t, total_s, parallel_s) } } }
impl PerDocumentStyleDataImpl { /// Recreate the style data if the stylesheets have changed. pub fn flush_stylesheets<E>( &mut self, guard: &SharedRwLockReadGuard, document_element: Option<E>, snapshots: Option<&SnapshotMap>, ) -> bool where E: TElement, { self.stylist.flush( &StylesheetGuards::same(guard), document_element, snapshots, ) } /// Returns whether private browsing is enabled. fn is_private_browsing_enabled(&self) -> bool { let doc = self.stylist.device().pres_context().mDocument.raw::<nsIDocument>(); unsafe { bindings::Gecko_IsPrivateBrowsingEnabled(doc) } } /// Returns whether the document is being used as an image. fn is_being_used_as_an_image(&self) -> bool { let doc = self.stylist.device().pres_context().mDocument.raw::<nsIDocument>(); unsafe { (*doc).mIsBeingUsedAsImage() } } /// Get the default computed values for this document. pub fn default_computed_values(&self) -> &Arc<ComputedValues> { self.stylist.device().default_computed_values_arc() } /// Returns whether visited links are enabled. fn visited_links_enabled(&self) -> bool { unsafe { structs::StylePrefs_sVisitedLinksEnabled } } /// Returns whether visited styles are enabled. pub fn visited_styles_enabled(&self) -> bool { if!self.visited_links_enabled() { return false; } if self.is_private_browsing_enabled() { return false; } if self.is_being_used_as_an_image() { return false; } true } /// Measure heap usage. pub fn add_size_of(&self, ops: &mut MallocSizeOfOps, sizes: &mut ServoStyleSetSizes) { self.stylist.add_size_of(ops, sizes); } /// Record that a traversal happened for later collection as telemetry pub fn record_traversal(&self, was_parallel: bool, stats: Option<TraversalStatistics>) { self.traversal_count.record(was_parallel, 1); if let Some(stats) = stats { self.traversal_count_traversed.record(was_parallel, stats.elements_traversed); self.traversal_count_styled.record(was_parallel, stats.elements_styled); } } } unsafe impl HasFFI for PerDocumentStyleData { type FFIType = RawServoStyleSet; } unsafe impl HasSimpleFFI for PerDocumentStyleData {} unsafe impl HasBoxFFI for PerDocumentStyleData {}
random_line_split
data.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Data needed to style a Gecko document. use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut}; use context::TraversalStatistics; use dom::TElement; use gecko_bindings::bindings::{self, RawServoStyleSet}; use gecko_bindings::structs::{RawGeckoPresContextOwned, ServoStyleSetSizes, ServoStyleSheet}; use gecko_bindings::structs::{StyleSheetInfo, ServoStyleSheetInner, nsIDocument, self}; use gecko_bindings::sugar::ownership::{HasArcFFI, HasBoxFFI, HasFFI, HasSimpleFFI}; use invalidation::media_queries::{MediaListKey, ToMediaListKey}; use malloc_size_of::MallocSizeOfOps; use media_queries::{Device, MediaList}; use properties::ComputedValues; use selector_parser::SnapshotMap; use servo_arc::Arc; use shared_lock::{Locked, StylesheetGuards, SharedRwLockReadGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use stylesheets::{StylesheetContents, StylesheetInDocument}; use stylist::Stylist; /// Little wrapper to a Gecko style sheet. #[derive(Debug, Eq, PartialEq)] pub struct GeckoStyleSheet(*const ServoStyleSheet); impl ToMediaListKey for ::gecko::data::GeckoStyleSheet { fn to_media_list_key(&self) -> MediaListKey { use std::mem; unsafe { MediaListKey::from_raw(mem::transmute(self.0)) } } } impl GeckoStyleSheet { /// Create a `GeckoStyleSheet` from a raw `ServoStyleSheet` pointer. #[inline] pub unsafe fn new(s: *const ServoStyleSheet) -> Self { debug_assert!(!s.is_null()); bindings::Gecko_StyleSheet_AddRef(s); Self::from_addrefed(s) } /// Create a `GeckoStyleSheet` from a raw `ServoStyleSheet` pointer that /// already holds a strong reference. #[inline] pub unsafe fn from_addrefed(s: *const ServoStyleSheet) -> Self { debug_assert!(!s.is_null()); GeckoStyleSheet(s) } /// Get the raw `ServoStyleSheet` that we're wrapping. pub fn raw(&self) -> &ServoStyleSheet { unsafe { &*self.0 } } fn inner(&self) -> &ServoStyleSheetInner { unsafe { &*(self.raw()._base.mInner as *const StyleSheetInfo as *const ServoStyleSheetInner) } } } impl Drop for GeckoStyleSheet { fn drop(&mut self) { unsafe { bindings::Gecko_StyleSheet_Release(self.0) }; } } impl Clone for GeckoStyleSheet { fn clone(&self) -> Self { unsafe { bindings::Gecko_StyleSheet_AddRef(self.0) }; GeckoStyleSheet(self.0) } } impl StylesheetInDocument for GeckoStyleSheet { fn contents(&self, _: &SharedRwLockReadGuard) -> &StylesheetContents { debug_assert!(!self.inner().mContents.mRawPtr.is_null()); unsafe { let contents = (&**StylesheetContents::as_arc(&&*self.inner().mContents.mRawPtr)) as *const _; &*contents } } fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList> { use gecko_bindings::structs::ServoMediaList; use std::mem; unsafe { let servo_media_list = self.raw()._base.mMedia.mRawPtr as *const ServoMediaList; if servo_media_list.is_null() { return None; } let raw_list = &*(*servo_media_list).mRawList.mRawPtr; let list = Locked::<MediaList>::as_arc(mem::transmute(&raw_list)); Some(list.read_with(guard)) } } // All the stylesheets Servo knows about are enabled, because that state is // handled externally by Gecko. fn enabled(&self) -> bool { true } } #[derive(Default)] /// Helper struct for counting traversals pub struct TraversalCount { /// Total number of events pub total_count: AtomicUsize, /// Number of events which were parallel pub parallel_count: AtomicUsize } impl TraversalCount { fn record(&self, parallel: bool, count: u32) { self.total_count.fetch_add(count as usize, Ordering::Relaxed); if parallel { self.parallel_count.fetch_add(count as usize, Ordering::Relaxed); } } fn get(&self) -> (u32, u32) { (self.total_count.load(Ordering::Relaxed) as u32, self.parallel_count.load(Ordering::Relaxed) as u32) } } /// The container for data that a Servo-backed Gecko document needs to style /// itself. pub struct PerDocumentStyleDataImpl { /// Rule processor. pub stylist: Stylist, /// Counter for traversals that could have been parallel, for telemetry pub traversal_count: TraversalCount, /// Counter for traversals, weighted by elements traversed, pub traversal_count_traversed: TraversalCount, /// Counter for traversals, weighted by elements styled, pub traversal_count_styled: TraversalCount, } /// The data itself is an `AtomicRefCell`, which guarantees the proper semantics /// and unexpected races while trying to mutate it. pub struct PerDocumentStyleData(AtomicRefCell<PerDocumentStyleDataImpl>); impl PerDocumentStyleData { /// Create a dummy `PerDocumentStyleData`. pub fn new(pres_context: RawGeckoPresContextOwned) -> Self { let device = Device::new(pres_context); // FIXME(emilio, tlin): How is this supposed to work with XBL? This is // right now not always honored, see bug 1405543... // // Should we just force XBL Stylists to be NoQuirks? let quirks_mode = unsafe { (*device.pres_context().mDocument.raw::<nsIDocument>()).mCompatMode }; PerDocumentStyleData(AtomicRefCell::new(PerDocumentStyleDataImpl { stylist: Stylist::new(device, quirks_mode.into()), traversal_count: Default::default(), traversal_count_traversed: Default::default(), traversal_count_styled: Default::default(), })) } /// Get an immutable reference to this style data. pub fn borrow(&self) -> AtomicRef<PerDocumentStyleDataImpl> { self.0.borrow() } /// Get an mutable reference to this style data. pub fn borrow_mut(&self) -> AtomicRefMut<PerDocumentStyleDataImpl> { self.0.borrow_mut() } } impl Drop for PerDocumentStyleDataImpl { fn drop(&mut self) { if!structs::GECKO_IS_NIGHTLY { return } let (total, parallel) = self.traversal_count.get(); let (total_t, parallel_t) = self.traversal_count_traversed.get(); let (total_s, parallel_s) = self.traversal_count_styled.get(); unsafe { bindings::Gecko_RecordTraversalStatistics(total, parallel, total_t, parallel_t, total_s, parallel_s) } } } impl PerDocumentStyleDataImpl { /// Recreate the style data if the stylesheets have changed. pub fn flush_stylesheets<E>( &mut self, guard: &SharedRwLockReadGuard, document_element: Option<E>, snapshots: Option<&SnapshotMap>, ) -> bool where E: TElement, { self.stylist.flush( &StylesheetGuards::same(guard), document_element, snapshots, ) } /// Returns whether private browsing is enabled. fn is_private_browsing_enabled(&self) -> bool { let doc = self.stylist.device().pres_context().mDocument.raw::<nsIDocument>(); unsafe { bindings::Gecko_IsPrivateBrowsingEnabled(doc) } } /// Returns whether the document is being used as an image. fn is_being_used_as_an_image(&self) -> bool { let doc = self.stylist.device().pres_context().mDocument.raw::<nsIDocument>(); unsafe { (*doc).mIsBeingUsedAsImage() } } /// Get the default computed values for this document. pub fn default_computed_values(&self) -> &Arc<ComputedValues> { self.stylist.device().default_computed_values_arc() } /// Returns whether visited links are enabled. fn visited_links_enabled(&self) -> bool { unsafe { structs::StylePrefs_sVisitedLinksEnabled } } /// Returns whether visited styles are enabled. pub fn visited_styles_enabled(&self) -> bool
/// Measure heap usage. pub fn add_size_of(&self, ops: &mut MallocSizeOfOps, sizes: &mut ServoStyleSetSizes) { self.stylist.add_size_of(ops, sizes); } /// Record that a traversal happened for later collection as telemetry pub fn record_traversal(&self, was_parallel: bool, stats: Option<TraversalStatistics>) { self.traversal_count.record(was_parallel, 1); if let Some(stats) = stats { self.traversal_count_traversed.record(was_parallel, stats.elements_traversed); self.traversal_count_styled.record(was_parallel, stats.elements_styled); } } } unsafe impl HasFFI for PerDocumentStyleData { type FFIType = RawServoStyleSet; } unsafe impl HasSimpleFFI for PerDocumentStyleData {} unsafe impl HasBoxFFI for PerDocumentStyleData {}
{ if !self.visited_links_enabled() { return false; } if self.is_private_browsing_enabled() { return false; } if self.is_being_used_as_an_image() { return false; } true }
identifier_body
data.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Data needed to style a Gecko document. use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut}; use context::TraversalStatistics; use dom::TElement; use gecko_bindings::bindings::{self, RawServoStyleSet}; use gecko_bindings::structs::{RawGeckoPresContextOwned, ServoStyleSetSizes, ServoStyleSheet}; use gecko_bindings::structs::{StyleSheetInfo, ServoStyleSheetInner, nsIDocument, self}; use gecko_bindings::sugar::ownership::{HasArcFFI, HasBoxFFI, HasFFI, HasSimpleFFI}; use invalidation::media_queries::{MediaListKey, ToMediaListKey}; use malloc_size_of::MallocSizeOfOps; use media_queries::{Device, MediaList}; use properties::ComputedValues; use selector_parser::SnapshotMap; use servo_arc::Arc; use shared_lock::{Locked, StylesheetGuards, SharedRwLockReadGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use stylesheets::{StylesheetContents, StylesheetInDocument}; use stylist::Stylist; /// Little wrapper to a Gecko style sheet. #[derive(Debug, Eq, PartialEq)] pub struct GeckoStyleSheet(*const ServoStyleSheet); impl ToMediaListKey for ::gecko::data::GeckoStyleSheet { fn to_media_list_key(&self) -> MediaListKey { use std::mem; unsafe { MediaListKey::from_raw(mem::transmute(self.0)) } } } impl GeckoStyleSheet { /// Create a `GeckoStyleSheet` from a raw `ServoStyleSheet` pointer. #[inline] pub unsafe fn new(s: *const ServoStyleSheet) -> Self { debug_assert!(!s.is_null()); bindings::Gecko_StyleSheet_AddRef(s); Self::from_addrefed(s) } /// Create a `GeckoStyleSheet` from a raw `ServoStyleSheet` pointer that /// already holds a strong reference. #[inline] pub unsafe fn from_addrefed(s: *const ServoStyleSheet) -> Self { debug_assert!(!s.is_null()); GeckoStyleSheet(s) } /// Get the raw `ServoStyleSheet` that we're wrapping. pub fn raw(&self) -> &ServoStyleSheet { unsafe { &*self.0 } } fn inner(&self) -> &ServoStyleSheetInner { unsafe { &*(self.raw()._base.mInner as *const StyleSheetInfo as *const ServoStyleSheetInner) } } } impl Drop for GeckoStyleSheet { fn drop(&mut self) { unsafe { bindings::Gecko_StyleSheet_Release(self.0) }; } } impl Clone for GeckoStyleSheet { fn clone(&self) -> Self { unsafe { bindings::Gecko_StyleSheet_AddRef(self.0) }; GeckoStyleSheet(self.0) } } impl StylesheetInDocument for GeckoStyleSheet { fn contents(&self, _: &SharedRwLockReadGuard) -> &StylesheetContents { debug_assert!(!self.inner().mContents.mRawPtr.is_null()); unsafe { let contents = (&**StylesheetContents::as_arc(&&*self.inner().mContents.mRawPtr)) as *const _; &*contents } } fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList> { use gecko_bindings::structs::ServoMediaList; use std::mem; unsafe { let servo_media_list = self.raw()._base.mMedia.mRawPtr as *const ServoMediaList; if servo_media_list.is_null() { return None; } let raw_list = &*(*servo_media_list).mRawList.mRawPtr; let list = Locked::<MediaList>::as_arc(mem::transmute(&raw_list)); Some(list.read_with(guard)) } } // All the stylesheets Servo knows about are enabled, because that state is // handled externally by Gecko. fn enabled(&self) -> bool { true } } #[derive(Default)] /// Helper struct for counting traversals pub struct TraversalCount { /// Total number of events pub total_count: AtomicUsize, /// Number of events which were parallel pub parallel_count: AtomicUsize } impl TraversalCount { fn record(&self, parallel: bool, count: u32) { self.total_count.fetch_add(count as usize, Ordering::Relaxed); if parallel { self.parallel_count.fetch_add(count as usize, Ordering::Relaxed); } } fn get(&self) -> (u32, u32) { (self.total_count.load(Ordering::Relaxed) as u32, self.parallel_count.load(Ordering::Relaxed) as u32) } } /// The container for data that a Servo-backed Gecko document needs to style /// itself. pub struct PerDocumentStyleDataImpl { /// Rule processor. pub stylist: Stylist, /// Counter for traversals that could have been parallel, for telemetry pub traversal_count: TraversalCount, /// Counter for traversals, weighted by elements traversed, pub traversal_count_traversed: TraversalCount, /// Counter for traversals, weighted by elements styled, pub traversal_count_styled: TraversalCount, } /// The data itself is an `AtomicRefCell`, which guarantees the proper semantics /// and unexpected races while trying to mutate it. pub struct PerDocumentStyleData(AtomicRefCell<PerDocumentStyleDataImpl>); impl PerDocumentStyleData { /// Create a dummy `PerDocumentStyleData`. pub fn new(pres_context: RawGeckoPresContextOwned) -> Self { let device = Device::new(pres_context); // FIXME(emilio, tlin): How is this supposed to work with XBL? This is // right now not always honored, see bug 1405543... // // Should we just force XBL Stylists to be NoQuirks? let quirks_mode = unsafe { (*device.pres_context().mDocument.raw::<nsIDocument>()).mCompatMode }; PerDocumentStyleData(AtomicRefCell::new(PerDocumentStyleDataImpl { stylist: Stylist::new(device, quirks_mode.into()), traversal_count: Default::default(), traversal_count_traversed: Default::default(), traversal_count_styled: Default::default(), })) } /// Get an immutable reference to this style data. pub fn borrow(&self) -> AtomicRef<PerDocumentStyleDataImpl> { self.0.borrow() } /// Get an mutable reference to this style data. pub fn borrow_mut(&self) -> AtomicRefMut<PerDocumentStyleDataImpl> { self.0.borrow_mut() } } impl Drop for PerDocumentStyleDataImpl { fn drop(&mut self) { if!structs::GECKO_IS_NIGHTLY { return } let (total, parallel) = self.traversal_count.get(); let (total_t, parallel_t) = self.traversal_count_traversed.get(); let (total_s, parallel_s) = self.traversal_count_styled.get(); unsafe { bindings::Gecko_RecordTraversalStatistics(total, parallel, total_t, parallel_t, total_s, parallel_s) } } } impl PerDocumentStyleDataImpl { /// Recreate the style data if the stylesheets have changed. pub fn flush_stylesheets<E>( &mut self, guard: &SharedRwLockReadGuard, document_element: Option<E>, snapshots: Option<&SnapshotMap>, ) -> bool where E: TElement, { self.stylist.flush( &StylesheetGuards::same(guard), document_element, snapshots, ) } /// Returns whether private browsing is enabled. fn is_private_browsing_enabled(&self) -> bool { let doc = self.stylist.device().pres_context().mDocument.raw::<nsIDocument>(); unsafe { bindings::Gecko_IsPrivateBrowsingEnabled(doc) } } /// Returns whether the document is being used as an image. fn is_being_used_as_an_image(&self) -> bool { let doc = self.stylist.device().pres_context().mDocument.raw::<nsIDocument>(); unsafe { (*doc).mIsBeingUsedAsImage() } } /// Get the default computed values for this document. pub fn default_computed_values(&self) -> &Arc<ComputedValues> { self.stylist.device().default_computed_values_arc() } /// Returns whether visited links are enabled. fn visited_links_enabled(&self) -> bool { unsafe { structs::StylePrefs_sVisitedLinksEnabled } } /// Returns whether visited styles are enabled. pub fn visited_styles_enabled(&self) -> bool { if!self.visited_links_enabled() { return false; } if self.is_private_browsing_enabled() { return false; } if self.is_being_used_as_an_image() { return false; } true } /// Measure heap usage. pub fn add_size_of(&self, ops: &mut MallocSizeOfOps, sizes: &mut ServoStyleSetSizes) { self.stylist.add_size_of(ops, sizes); } /// Record that a traversal happened for later collection as telemetry pub fn record_traversal(&self, was_parallel: bool, stats: Option<TraversalStatistics>) { self.traversal_count.record(was_parallel, 1); if let Some(stats) = stats
} } unsafe impl HasFFI for PerDocumentStyleData { type FFIType = RawServoStyleSet; } unsafe impl HasSimpleFFI for PerDocumentStyleData {} unsafe impl HasBoxFFI for PerDocumentStyleData {}
{ self.traversal_count_traversed.record(was_parallel, stats.elements_traversed); self.traversal_count_styled.record(was_parallel, stats.elements_styled); }
conditional_block
timestamp.rs
pub struct Timestamp(u64); pub trait InTimestampUnits { /// milliseconds fn ms(self) -> Timestamp; /// microseconds fn us(self) -> Timestamp; /// nanoseconds fn ns(self) -> Timestamp; } impl InTimestampUnits for f64 { fn ms(self) -> Timestamp { Timestamp((self * 1_000_000.0) as u64) } fn us(self) -> Timestamp { Timestamp((self * 1_000.0) as u64) } fn ns(self) -> Timestamp { Timestamp(self as u64) } } impl InTimestampUnits for u64 { fn ms(self) -> Timestamp { Timestamp(self * 1_000_000u64) } fn us(self) -> Timestamp { Timestamp(self * 1_000u64) } fn ns(self) -> Timestamp
}
{ Timestamp(self) }
identifier_body
timestamp.rs
pub struct Timestamp(u64); pub trait InTimestampUnits { /// milliseconds fn ms(self) -> Timestamp; /// microseconds fn us(self) -> Timestamp; /// nanoseconds fn ns(self) -> Timestamp; } impl InTimestampUnits for f64 { fn ms(self) -> Timestamp { Timestamp((self * 1_000_000.0) as u64) } fn us(self) -> Timestamp { Timestamp((self * 1_000.0) as u64) } fn ns(self) -> Timestamp { Timestamp(self as u64) } } impl InTimestampUnits for u64 {
fn ms(self) -> Timestamp { Timestamp(self * 1_000_000u64) } fn us(self) -> Timestamp { Timestamp(self * 1_000u64) } fn ns(self) -> Timestamp { Timestamp(self) } }
random_line_split
timestamp.rs
pub struct Timestamp(u64); pub trait InTimestampUnits { /// milliseconds fn ms(self) -> Timestamp; /// microseconds fn us(self) -> Timestamp; /// nanoseconds fn ns(self) -> Timestamp; } impl InTimestampUnits for f64 { fn ms(self) -> Timestamp { Timestamp((self * 1_000_000.0) as u64) } fn
(self) -> Timestamp { Timestamp((self * 1_000.0) as u64) } fn ns(self) -> Timestamp { Timestamp(self as u64) } } impl InTimestampUnits for u64 { fn ms(self) -> Timestamp { Timestamp(self * 1_000_000u64) } fn us(self) -> Timestamp { Timestamp(self * 1_000u64) } fn ns(self) -> Timestamp { Timestamp(self) } }
us
identifier_name
issue-37945.rs
// compile-flags: -O -Zmerge-functions=disabled // ignore-x86 // ignore-arm // ignore-emscripten // ignore-gnux32 // ignore 32-bit platforms (LLVM has a bug with them) // Check that LLVM understands that `Iter` pointer is not null. Issue #37945. #![crate_type = "lib"] use std::slice::Iter; #[no_mangle] pub fn is_empty_1(xs: Iter<f32>) -> bool
#[no_mangle] pub fn is_empty_2(xs: Iter<f32>) -> bool { // CHECK-LABEL: @is_empty_2 // CHECK-NEXT: start: // CHECK-NEXT: [[C:%.*]] = icmp ne i32* %xs.1, null // CHECK-NEXT: tail call void @llvm.assume(i1 [[C]]) // CHECK-NEXT: [[D:%.*]] = icmp eq i32* %xs.0, %xs.1 // CHECK-NEXT: ret i1 [[D:%.*]] xs.map(|&x| x).next().is_none() }
{ // CHECK-LABEL: @is_empty_1( // CHECK-NEXT: start: // CHECK-NEXT: [[A:%.*]] = icmp ne i32* %xs.1, null // CHECK-NEXT: tail call void @llvm.assume(i1 [[A]]) // CHECK-NEXT: [[B:%.*]] = icmp eq i32* %xs.0, %xs.1 // CHECK-NEXT: ret i1 [[B:%.*]] {xs}.next().is_none() }
identifier_body
issue-37945.rs
// compile-flags: -O -Zmerge-functions=disabled // ignore-x86 // ignore-arm // ignore-emscripten // ignore-gnux32 // ignore 32-bit platforms (LLVM has a bug with them) // Check that LLVM understands that `Iter` pointer is not null. Issue #37945. #![crate_type = "lib"]
// CHECK-LABEL: @is_empty_1( // CHECK-NEXT: start: // CHECK-NEXT: [[A:%.*]] = icmp ne i32* %xs.1, null // CHECK-NEXT: tail call void @llvm.assume(i1 [[A]]) // CHECK-NEXT: [[B:%.*]] = icmp eq i32* %xs.0, %xs.1 // CHECK-NEXT: ret i1 [[B:%.*]] {xs}.next().is_none() } #[no_mangle] pub fn is_empty_2(xs: Iter<f32>) -> bool { // CHECK-LABEL: @is_empty_2 // CHECK-NEXT: start: // CHECK-NEXT: [[C:%.*]] = icmp ne i32* %xs.1, null // CHECK-NEXT: tail call void @llvm.assume(i1 [[C]]) // CHECK-NEXT: [[D:%.*]] = icmp eq i32* %xs.0, %xs.1 // CHECK-NEXT: ret i1 [[D:%.*]] xs.map(|&x| x).next().is_none() }
use std::slice::Iter; #[no_mangle] pub fn is_empty_1(xs: Iter<f32>) -> bool {
random_line_split
issue-37945.rs
// compile-flags: -O -Zmerge-functions=disabled // ignore-x86 // ignore-arm // ignore-emscripten // ignore-gnux32 // ignore 32-bit platforms (LLVM has a bug with them) // Check that LLVM understands that `Iter` pointer is not null. Issue #37945. #![crate_type = "lib"] use std::slice::Iter; #[no_mangle] pub fn
(xs: Iter<f32>) -> bool { // CHECK-LABEL: @is_empty_1( // CHECK-NEXT: start: // CHECK-NEXT: [[A:%.*]] = icmp ne i32* %xs.1, null // CHECK-NEXT: tail call void @llvm.assume(i1 [[A]]) // CHECK-NEXT: [[B:%.*]] = icmp eq i32* %xs.0, %xs.1 // CHECK-NEXT: ret i1 [[B:%.*]] {xs}.next().is_none() } #[no_mangle] pub fn is_empty_2(xs: Iter<f32>) -> bool { // CHECK-LABEL: @is_empty_2 // CHECK-NEXT: start: // CHECK-NEXT: [[C:%.*]] = icmp ne i32* %xs.1, null // CHECK-NEXT: tail call void @llvm.assume(i1 [[C]]) // CHECK-NEXT: [[D:%.*]] = icmp eq i32* %xs.0, %xs.1 // CHECK-NEXT: ret i1 [[D:%.*]] xs.map(|&x| x).next().is_none() }
is_empty_1
identifier_name
worker.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg}; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMethods; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{Reflectable, reflect_dom_object}; use dom::bindings::structuredclone::StructuredCloneData; use dom::bindings::trace::JSTraceable; use dom::dedicatedworkerglobalscope::{DedicatedWorkerGlobalScope, WorkerScriptMsg}; use dom::errorevent::ErrorEvent; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventtarget::EventTarget; use dom::messageevent::MessageEvent; use dom::workerglobalscope::WorkerGlobalScopeInit; use ipc_channel::ipc; use js::jsapi::{HandleValue, JSContext, JSRuntime, RootedValue}; use js::jsapi::{JSAutoCompartment, JSAutoRequest, JS_RequestInterruptCallback}; use js::jsval::UndefinedValue; use js::rust::Runtime; use script_runtime::ScriptChan; use script_thread::Runnable; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Sender, channel}; use std::sync::{Arc, Mutex}; use util::str::DOMString; pub type TrustedWorkerAddress = Trusted<Worker>; // https://html.spec.whatwg.org/multipage/#worker #[dom_struct] pub struct Worker { eventtarget: EventTarget, #[ignore_heap_size_of = "Defined in std"] /// Sender to the Receiver associated with the DedicatedWorkerGlobalScope /// this Worker created. sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>, closing: Arc<AtomicBool>, #[ignore_heap_size_of = "Defined in rust-mozjs"] runtime: Arc<Mutex<Option<SharedRt>>> } impl Worker { fn new_inherited(sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>, closing: Arc<AtomicBool>) -> Worker { Worker { eventtarget: EventTarget::new_inherited(), sender: sender, closing: closing, runtime: Arc::new(Mutex::new(None)) } } pub fn new(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>, closing: Arc<AtomicBool>) -> Root<Worker> { reflect_dom_object(box Worker::new_inherited(sender, closing), global, WorkerBinding::Wrap) } // https://html.spec.whatwg.org/multipage/#dom-worker pub fn
(global: GlobalRef, script_url: DOMString) -> Fallible<Root<Worker>> { // Step 2-4. let worker_url = match global.api_base_url().join(&script_url) { Ok(url) => url, Err(_) => return Err(Error::Syntax), }; let resource_thread = global.resource_thread(); let constellation_chan = global.constellation_chan(); let scheduler_chan = global.scheduler_chan(); let (sender, receiver) = channel(); let closing = Arc::new(AtomicBool::new(false)); let worker = Worker::new(global, sender.clone(), closing.clone()); let worker_ref = Trusted::new(worker.r()); let worker_id = global.get_next_worker_id(); let (devtools_sender, devtools_receiver) = ipc::channel().unwrap(); let optional_sender = match global.devtools_chan() { Some(ref chan) => { let pipeline_id = global.pipeline(); let title = format!("Worker for {}", worker_url); let page_info = DevtoolsPageInfo { title: title, url: worker_url.clone(), }; chan.send(ScriptToDevtoolsControlMsg::NewGlobal((pipeline_id, Some(worker_id)), devtools_sender.clone(), page_info)).unwrap(); Some(devtools_sender) }, None => None, }; let init = WorkerGlobalScopeInit { resource_thread: resource_thread, mem_profiler_chan: global.mem_profiler_chan(), to_devtools_sender: global.devtools_chan(), from_devtools_sender: optional_sender, constellation_chan: constellation_chan, scheduler_chan: scheduler_chan, worker_id: worker_id, closing: closing, }; DedicatedWorkerGlobalScope::run_worker_scope( init, worker_url, global.pipeline(), devtools_receiver, worker.runtime.clone(), worker_ref, global.script_chan(), sender, receiver); Ok(worker) } pub fn is_closing(&self) -> bool { self.closing.load(Ordering::SeqCst) } pub fn handle_message(address: TrustedWorkerAddress, data: StructuredCloneData) { let worker = address.root(); if worker.is_closing() { return; } let global = worker.r().global(); let target = worker.upcast(); let _ar = JSAutoRequest::new(global.r().get_cx()); let _ac = JSAutoCompartment::new(global.r().get_cx(), target.reflector().get_jsobject().get()); let mut message = RootedValue::new(global.r().get_cx(), UndefinedValue()); data.read(global.r(), message.handle_mut()); MessageEvent::dispatch_jsval(target, global.r(), message.handle()); } pub fn dispatch_simple_error(address: TrustedWorkerAddress) { let worker = address.root(); worker.upcast().fire_simple_event("error"); } pub fn handle_error_message(address: TrustedWorkerAddress, message: DOMString, filename: DOMString, lineno: u32, colno: u32) { let worker = address.root(); if worker.is_closing() { return; } let global = worker.r().global(); let error = RootedValue::new(global.r().get_cx(), UndefinedValue()); let errorevent = ErrorEvent::new(global.r(), atom!("error"), EventBubbles::Bubbles, EventCancelable::Cancelable, message, filename, lineno, colno, error.handle()); errorevent.upcast::<Event>().fire(worker.upcast()); } } impl WorkerMethods for Worker { // https://html.spec.whatwg.org/multipage/#dom-worker-postmessage fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { let data = try!(StructuredCloneData::write(cx, message)); let address = Trusted::new(self); self.sender.send((address, WorkerScriptMsg::DOMMessage(data))).unwrap(); Ok(()) } // https://html.spec.whatwg.org/multipage/#terminate-a-worker fn Terminate(&self) { // Step 1 if self.closing.swap(true, Ordering::SeqCst) { return; } // Step 4 if let Some(runtime) = *self.runtime.lock().unwrap() { runtime.request_interrupt(); } } // https://html.spec.whatwg.org/multipage/#handler-worker-onmessage event_handler!(message, GetOnmessage, SetOnmessage); // https://html.spec.whatwg.org/multipage/#handler-workerglobalscope-onerror event_handler!(error, GetOnerror, SetOnerror); } pub struct WorkerMessageHandler { addr: TrustedWorkerAddress, data: StructuredCloneData, } impl WorkerMessageHandler { pub fn new(addr: TrustedWorkerAddress, data: StructuredCloneData) -> WorkerMessageHandler { WorkerMessageHandler { addr: addr, data: data, } } } impl Runnable for WorkerMessageHandler { fn handler(self: Box<WorkerMessageHandler>) { let this = *self; Worker::handle_message(this.addr, this.data); } } pub struct SimpleWorkerErrorHandler { addr: TrustedWorkerAddress, } impl SimpleWorkerErrorHandler { pub fn new(addr: TrustedWorkerAddress) -> SimpleWorkerErrorHandler { SimpleWorkerErrorHandler { addr: addr } } } impl Runnable for SimpleWorkerErrorHandler { fn handler(self: Box<SimpleWorkerErrorHandler>) { let this = *self; Worker::dispatch_simple_error(this.addr); } } pub struct WorkerErrorHandler { addr: TrustedWorkerAddress, msg: DOMString, file_name: DOMString, line_num: u32, col_num: u32, } impl WorkerErrorHandler { pub fn new(addr: TrustedWorkerAddress, msg: DOMString, file_name: DOMString, line_num: u32, col_num: u32) -> WorkerErrorHandler { WorkerErrorHandler { addr: addr, msg: msg, file_name: file_name, line_num: line_num, col_num: col_num, } } } impl Runnable for WorkerErrorHandler { fn handler(self: Box<WorkerErrorHandler>) { let this = *self; Worker::handle_error_message(this.addr, this.msg, this.file_name, this.line_num, this.col_num); } } #[derive(Copy, Clone)] pub struct SharedRt { rt: *mut JSRuntime } impl SharedRt { pub fn new(rt: &Runtime) -> SharedRt { SharedRt { rt: rt.rt() } } #[allow(unsafe_code)] pub fn request_interrupt(&self) { unsafe { JS_RequestInterruptCallback(self.rt); } } } #[allow(unsafe_code)] unsafe impl Send for SharedRt {}
Constructor
identifier_name
worker.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg}; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMethods; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{Reflectable, reflect_dom_object}; use dom::bindings::structuredclone::StructuredCloneData; use dom::bindings::trace::JSTraceable; use dom::dedicatedworkerglobalscope::{DedicatedWorkerGlobalScope, WorkerScriptMsg}; use dom::errorevent::ErrorEvent; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventtarget::EventTarget; use dom::messageevent::MessageEvent; use dom::workerglobalscope::WorkerGlobalScopeInit; use ipc_channel::ipc; use js::jsapi::{HandleValue, JSContext, JSRuntime, RootedValue}; use js::jsapi::{JSAutoCompartment, JSAutoRequest, JS_RequestInterruptCallback}; use js::jsval::UndefinedValue; use js::rust::Runtime; use script_runtime::ScriptChan; use script_thread::Runnable; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Sender, channel}; use std::sync::{Arc, Mutex}; use util::str::DOMString; pub type TrustedWorkerAddress = Trusted<Worker>; // https://html.spec.whatwg.org/multipage/#worker #[dom_struct] pub struct Worker { eventtarget: EventTarget, #[ignore_heap_size_of = "Defined in std"] /// Sender to the Receiver associated with the DedicatedWorkerGlobalScope /// this Worker created. sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>, closing: Arc<AtomicBool>, #[ignore_heap_size_of = "Defined in rust-mozjs"] runtime: Arc<Mutex<Option<SharedRt>>> } impl Worker { fn new_inherited(sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>, closing: Arc<AtomicBool>) -> Worker { Worker { eventtarget: EventTarget::new_inherited(), sender: sender, closing: closing, runtime: Arc::new(Mutex::new(None)) } } pub fn new(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>, closing: Arc<AtomicBool>) -> Root<Worker> { reflect_dom_object(box Worker::new_inherited(sender, closing), global, WorkerBinding::Wrap) } // https://html.spec.whatwg.org/multipage/#dom-worker pub fn Constructor(global: GlobalRef, script_url: DOMString) -> Fallible<Root<Worker>> { // Step 2-4. let worker_url = match global.api_base_url().join(&script_url) { Ok(url) => url, Err(_) => return Err(Error::Syntax), }; let resource_thread = global.resource_thread(); let constellation_chan = global.constellation_chan(); let scheduler_chan = global.scheduler_chan(); let (sender, receiver) = channel(); let closing = Arc::new(AtomicBool::new(false)); let worker = Worker::new(global, sender.clone(), closing.clone()); let worker_ref = Trusted::new(worker.r()); let worker_id = global.get_next_worker_id(); let (devtools_sender, devtools_receiver) = ipc::channel().unwrap(); let optional_sender = match global.devtools_chan() { Some(ref chan) => { let pipeline_id = global.pipeline(); let title = format!("Worker for {}", worker_url); let page_info = DevtoolsPageInfo { title: title, url: worker_url.clone(), }; chan.send(ScriptToDevtoolsControlMsg::NewGlobal((pipeline_id, Some(worker_id)), devtools_sender.clone(), page_info)).unwrap(); Some(devtools_sender) }, None => None, }; let init = WorkerGlobalScopeInit { resource_thread: resource_thread, mem_profiler_chan: global.mem_profiler_chan(), to_devtools_sender: global.devtools_chan(), from_devtools_sender: optional_sender, constellation_chan: constellation_chan, scheduler_chan: scheduler_chan, worker_id: worker_id, closing: closing, }; DedicatedWorkerGlobalScope::run_worker_scope( init, worker_url, global.pipeline(), devtools_receiver, worker.runtime.clone(), worker_ref, global.script_chan(), sender, receiver); Ok(worker) } pub fn is_closing(&self) -> bool { self.closing.load(Ordering::SeqCst) } pub fn handle_message(address: TrustedWorkerAddress, data: StructuredCloneData) { let worker = address.root(); if worker.is_closing() { return; } let global = worker.r().global(); let target = worker.upcast(); let _ar = JSAutoRequest::new(global.r().get_cx()); let _ac = JSAutoCompartment::new(global.r().get_cx(), target.reflector().get_jsobject().get()); let mut message = RootedValue::new(global.r().get_cx(), UndefinedValue()); data.read(global.r(), message.handle_mut()); MessageEvent::dispatch_jsval(target, global.r(), message.handle()); } pub fn dispatch_simple_error(address: TrustedWorkerAddress) { let worker = address.root(); worker.upcast().fire_simple_event("error"); } pub fn handle_error_message(address: TrustedWorkerAddress, message: DOMString, filename: DOMString, lineno: u32, colno: u32) { let worker = address.root(); if worker.is_closing() { return; } let global = worker.r().global(); let error = RootedValue::new(global.r().get_cx(), UndefinedValue()); let errorevent = ErrorEvent::new(global.r(), atom!("error"), EventBubbles::Bubbles, EventCancelable::Cancelable, message, filename, lineno, colno, error.handle()); errorevent.upcast::<Event>().fire(worker.upcast()); } } impl WorkerMethods for Worker { // https://html.spec.whatwg.org/multipage/#dom-worker-postmessage fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { let data = try!(StructuredCloneData::write(cx, message));
} // https://html.spec.whatwg.org/multipage/#terminate-a-worker fn Terminate(&self) { // Step 1 if self.closing.swap(true, Ordering::SeqCst) { return; } // Step 4 if let Some(runtime) = *self.runtime.lock().unwrap() { runtime.request_interrupt(); } } // https://html.spec.whatwg.org/multipage/#handler-worker-onmessage event_handler!(message, GetOnmessage, SetOnmessage); // https://html.spec.whatwg.org/multipage/#handler-workerglobalscope-onerror event_handler!(error, GetOnerror, SetOnerror); } pub struct WorkerMessageHandler { addr: TrustedWorkerAddress, data: StructuredCloneData, } impl WorkerMessageHandler { pub fn new(addr: TrustedWorkerAddress, data: StructuredCloneData) -> WorkerMessageHandler { WorkerMessageHandler { addr: addr, data: data, } } } impl Runnable for WorkerMessageHandler { fn handler(self: Box<WorkerMessageHandler>) { let this = *self; Worker::handle_message(this.addr, this.data); } } pub struct SimpleWorkerErrorHandler { addr: TrustedWorkerAddress, } impl SimpleWorkerErrorHandler { pub fn new(addr: TrustedWorkerAddress) -> SimpleWorkerErrorHandler { SimpleWorkerErrorHandler { addr: addr } } } impl Runnable for SimpleWorkerErrorHandler { fn handler(self: Box<SimpleWorkerErrorHandler>) { let this = *self; Worker::dispatch_simple_error(this.addr); } } pub struct WorkerErrorHandler { addr: TrustedWorkerAddress, msg: DOMString, file_name: DOMString, line_num: u32, col_num: u32, } impl WorkerErrorHandler { pub fn new(addr: TrustedWorkerAddress, msg: DOMString, file_name: DOMString, line_num: u32, col_num: u32) -> WorkerErrorHandler { WorkerErrorHandler { addr: addr, msg: msg, file_name: file_name, line_num: line_num, col_num: col_num, } } } impl Runnable for WorkerErrorHandler { fn handler(self: Box<WorkerErrorHandler>) { let this = *self; Worker::handle_error_message(this.addr, this.msg, this.file_name, this.line_num, this.col_num); } } #[derive(Copy, Clone)] pub struct SharedRt { rt: *mut JSRuntime } impl SharedRt { pub fn new(rt: &Runtime) -> SharedRt { SharedRt { rt: rt.rt() } } #[allow(unsafe_code)] pub fn request_interrupt(&self) { unsafe { JS_RequestInterruptCallback(self.rt); } } } #[allow(unsafe_code)] unsafe impl Send for SharedRt {}
let address = Trusted::new(self); self.sender.send((address, WorkerScriptMsg::DOMMessage(data))).unwrap(); Ok(())
random_line_split
relm-root.rs
/* * Copyright (c) 2017-2020 Boucher, Antoni <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use gtk::{ EventBox, Inhibit, Label, Window, WindowType, prelude::ContainerExt, prelude::WidgetExt, }; use gtk::Orientation::Vertical; use relm::{ connect, Component, Container, ContainerComponent, ContainerWidget, Relm, Update, Widget, WidgetTest, create_container, }; use relm_derive::Msg; use self::Msg::*; struct Button { button: gtk::Button, } impl Update for Button { type Model = (); type ModelParam = (); type Msg = (); fn model(_: &Relm<Self>, _: ()) -> () { } fn update(&mut self, _msg: ()) { } } impl Widget for Button { type Root = gtk::Button; fn root(&self) -> gtk::Button { self.button.clone() } fn view(_relm: &Relm<Self>, _model: Self::Model) -> Self { let button = gtk::Button::with_label("+"); button.set_widget_name("button"); Button { button: button, } } } struct VBox { event_box: EventBox, vbox: gtk::Box, } impl Container for VBox { type Container = gtk::Box; type Containers = (); fn container(&self) -> &Self::Container { &self.vbox } fn other_containers(&self) -> () { } } impl Update for VBox { type Model = (); type ModelParam = (); type Msg = (); fn model(_: &Relm<Self>, _: ()) -> () { () } fn update(&mut self, _event: ()) { } } impl Widget for VBox { type Root = EventBox; fn root(&self) -> EventBox { self.event_box.clone() } fn view(_relm: &Relm<Self>, _model: Self::Model) -> Self { let event_box = EventBox::new(); let vbox = gtk::Box::new(Vertical, 0); event_box.add(&vbox); VBox { event_box: event_box, vbox: vbox, } } } struct MyVBox { vbox: ContainerComponent<VBox>, _widget: Component<Button>, } impl Update for MyVBox { type Model = (); type ModelParam = (); type Msg = (); fn model(_: &Relm<Self>, _: ()) -> () { } fn update(&mut self, _event: ()) { } } impl Widget for MyVBox { type Root = <VBox as Widget>::Root; fn root(&self) -> EventBox { self.vbox.widget().clone() } fn view(_relm: &Relm<Self>, _model: Self::Model) -> Self { let vbox = create_container::<VBox>(()); let plus_button = gtk::Button::with_label("+"); plus_button.set_widget_name("inc_button"); vbox.add(&plus_button); let counter_label = Label::new(Some("0")); counter_label.set_widget_name("label"); vbox.add(&counter_label); let widget = vbox.add_widget::<Button>(()); let minus_button = gtk::Button::with_label("-"); minus_button.set_widget_name("dec_button"); vbox.add(&minus_button); MyVBox { vbox: vbox, _widget: widget, } } } #[derive(Msg)] pub enum Msg { Quit, } struct Components { _vbox: Component<MyVBox>, } #[derive(Clone)] struct Widgets { vbox: gtk::EventBox, window: Window, } struct Win { _components: Components, widgets: Widgets, } impl Update for Win { type Model = (); type ModelParam = (); type Msg = Msg; fn model(_: &Relm<Self>, _: ()) -> () { } fn update(&mut self, event: Msg) { match event { Quit => gtk::main_quit(), } } } impl Widget for Win { type Root = Window; fn root(&self) -> Window { self.widgets.window.clone() } fn view(relm: &Relm<Self>, _model: Self::Model) -> Self { let window = Window::new(WindowType::Toplevel); let vbox = window.add_widget::<MyVBox>(()); window.show_all(); connect!(relm, window, connect_delete_event(_, _), return (Some(Msg::Quit), Inhibit(false))); Win { widgets: Widgets { vbox: vbox.widget().clone(), window, }, _components: Components { _vbox: vbox, }, } } } impl WidgetTest for Win { type Streams = (); fn get_streams(&self) -> Self::Streams { }
} } fn main() { Win::run(()).expect("Win::run failed"); } #[cfg(test)] mod tests { use gtk::{Button, Label, prelude::WidgetExt}; use gtk_test::find_child_by_name; use crate::Win; #[test] fn root_widget() { let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed"); let vbox = &widgets.vbox; let inc_button: Button = find_child_by_name(vbox, "inc_button").expect("inc button"); let label: Label = find_child_by_name(vbox, "label").expect("label"); let button: Button = find_child_by_name(vbox, "button").expect("button"); let dec_button: Button = find_child_by_name(vbox, "dec_button").expect("dec button"); let inc_allocation = inc_button.allocation(); let label_allocation = label.allocation(); let button_allocation = button.allocation(); let dec_button_allocation = dec_button.allocation(); assert!(inc_allocation.y() < label_allocation.y()); assert!(label_allocation.y() < button_allocation.y()); assert!(button_allocation.y() < dec_button_allocation.y()); } }
type Widgets = Widgets; fn get_widgets(&self) -> Self::Widgets { self.widgets.clone()
random_line_split
relm-root.rs
/* * Copyright (c) 2017-2020 Boucher, Antoni <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use gtk::{ EventBox, Inhibit, Label, Window, WindowType, prelude::ContainerExt, prelude::WidgetExt, }; use gtk::Orientation::Vertical; use relm::{ connect, Component, Container, ContainerComponent, ContainerWidget, Relm, Update, Widget, WidgetTest, create_container, }; use relm_derive::Msg; use self::Msg::*; struct Button { button: gtk::Button, } impl Update for Button { type Model = (); type ModelParam = (); type Msg = (); fn model(_: &Relm<Self>, _: ()) -> () { } fn update(&mut self, _msg: ()) { } } impl Widget for Button { type Root = gtk::Button; fn root(&self) -> gtk::Button { self.button.clone() } fn view(_relm: &Relm<Self>, _model: Self::Model) -> Self { let button = gtk::Button::with_label("+"); button.set_widget_name("button"); Button { button: button, } } } struct VBox { event_box: EventBox, vbox: gtk::Box, } impl Container for VBox { type Container = gtk::Box; type Containers = (); fn container(&self) -> &Self::Container { &self.vbox } fn other_containers(&self) -> () { } } impl Update for VBox { type Model = (); type ModelParam = (); type Msg = (); fn model(_: &Relm<Self>, _: ()) -> () { () } fn update(&mut self, _event: ()) { } } impl Widget for VBox { type Root = EventBox; fn root(&self) -> EventBox { self.event_box.clone() } fn view(_relm: &Relm<Self>, _model: Self::Model) -> Self { let event_box = EventBox::new(); let vbox = gtk::Box::new(Vertical, 0); event_box.add(&vbox); VBox { event_box: event_box, vbox: vbox, } } } struct MyVBox { vbox: ContainerComponent<VBox>, _widget: Component<Button>, } impl Update for MyVBox { type Model = (); type ModelParam = (); type Msg = (); fn model(_: &Relm<Self>, _: ()) -> () { } fn update(&mut self, _event: ()) { } } impl Widget for MyVBox { type Root = <VBox as Widget>::Root; fn root(&self) -> EventBox { self.vbox.widget().clone() } fn view(_relm: &Relm<Self>, _model: Self::Model) -> Self { let vbox = create_container::<VBox>(()); let plus_button = gtk::Button::with_label("+"); plus_button.set_widget_name("inc_button"); vbox.add(&plus_button); let counter_label = Label::new(Some("0")); counter_label.set_widget_name("label"); vbox.add(&counter_label); let widget = vbox.add_widget::<Button>(()); let minus_button = gtk::Button::with_label("-"); minus_button.set_widget_name("dec_button"); vbox.add(&minus_button); MyVBox { vbox: vbox, _widget: widget, } } } #[derive(Msg)] pub enum Msg { Quit, } struct Components { _vbox: Component<MyVBox>, } #[derive(Clone)] struct Widgets { vbox: gtk::EventBox, window: Window, } struct
{ _components: Components, widgets: Widgets, } impl Update for Win { type Model = (); type ModelParam = (); type Msg = Msg; fn model(_: &Relm<Self>, _: ()) -> () { } fn update(&mut self, event: Msg) { match event { Quit => gtk::main_quit(), } } } impl Widget for Win { type Root = Window; fn root(&self) -> Window { self.widgets.window.clone() } fn view(relm: &Relm<Self>, _model: Self::Model) -> Self { let window = Window::new(WindowType::Toplevel); let vbox = window.add_widget::<MyVBox>(()); window.show_all(); connect!(relm, window, connect_delete_event(_, _), return (Some(Msg::Quit), Inhibit(false))); Win { widgets: Widgets { vbox: vbox.widget().clone(), window, }, _components: Components { _vbox: vbox, }, } } } impl WidgetTest for Win { type Streams = (); fn get_streams(&self) -> Self::Streams { } type Widgets = Widgets; fn get_widgets(&self) -> Self::Widgets { self.widgets.clone() } } fn main() { Win::run(()).expect("Win::run failed"); } #[cfg(test)] mod tests { use gtk::{Button, Label, prelude::WidgetExt}; use gtk_test::find_child_by_name; use crate::Win; #[test] fn root_widget() { let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed"); let vbox = &widgets.vbox; let inc_button: Button = find_child_by_name(vbox, "inc_button").expect("inc button"); let label: Label = find_child_by_name(vbox, "label").expect("label"); let button: Button = find_child_by_name(vbox, "button").expect("button"); let dec_button: Button = find_child_by_name(vbox, "dec_button").expect("dec button"); let inc_allocation = inc_button.allocation(); let label_allocation = label.allocation(); let button_allocation = button.allocation(); let dec_button_allocation = dec_button.allocation(); assert!(inc_allocation.y() < label_allocation.y()); assert!(label_allocation.y() < button_allocation.y()); assert!(button_allocation.y() < dec_button_allocation.y()); } }
Win
identifier_name
relm-root.rs
/* * Copyright (c) 2017-2020 Boucher, Antoni <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use gtk::{ EventBox, Inhibit, Label, Window, WindowType, prelude::ContainerExt, prelude::WidgetExt, }; use gtk::Orientation::Vertical; use relm::{ connect, Component, Container, ContainerComponent, ContainerWidget, Relm, Update, Widget, WidgetTest, create_container, }; use relm_derive::Msg; use self::Msg::*; struct Button { button: gtk::Button, } impl Update for Button { type Model = (); type ModelParam = (); type Msg = (); fn model(_: &Relm<Self>, _: ()) -> () { } fn update(&mut self, _msg: ()) { } } impl Widget for Button { type Root = gtk::Button; fn root(&self) -> gtk::Button { self.button.clone() } fn view(_relm: &Relm<Self>, _model: Self::Model) -> Self { let button = gtk::Button::with_label("+"); button.set_widget_name("button"); Button { button: button, } } } struct VBox { event_box: EventBox, vbox: gtk::Box, } impl Container for VBox { type Container = gtk::Box; type Containers = (); fn container(&self) -> &Self::Container { &self.vbox } fn other_containers(&self) -> () { } } impl Update for VBox { type Model = (); type ModelParam = (); type Msg = (); fn model(_: &Relm<Self>, _: ()) -> () { () } fn update(&mut self, _event: ()) { } } impl Widget for VBox { type Root = EventBox; fn root(&self) -> EventBox { self.event_box.clone() } fn view(_relm: &Relm<Self>, _model: Self::Model) -> Self { let event_box = EventBox::new(); let vbox = gtk::Box::new(Vertical, 0); event_box.add(&vbox); VBox { event_box: event_box, vbox: vbox, } } } struct MyVBox { vbox: ContainerComponent<VBox>, _widget: Component<Button>, } impl Update for MyVBox { type Model = (); type ModelParam = (); type Msg = (); fn model(_: &Relm<Self>, _: ()) -> () { } fn update(&mut self, _event: ()) { } } impl Widget for MyVBox { type Root = <VBox as Widget>::Root; fn root(&self) -> EventBox { self.vbox.widget().clone() } fn view(_relm: &Relm<Self>, _model: Self::Model) -> Self { let vbox = create_container::<VBox>(()); let plus_button = gtk::Button::with_label("+"); plus_button.set_widget_name("inc_button"); vbox.add(&plus_button); let counter_label = Label::new(Some("0")); counter_label.set_widget_name("label"); vbox.add(&counter_label); let widget = vbox.add_widget::<Button>(()); let minus_button = gtk::Button::with_label("-"); minus_button.set_widget_name("dec_button"); vbox.add(&minus_button); MyVBox { vbox: vbox, _widget: widget, } } } #[derive(Msg)] pub enum Msg { Quit, } struct Components { _vbox: Component<MyVBox>, } #[derive(Clone)] struct Widgets { vbox: gtk::EventBox, window: Window, } struct Win { _components: Components, widgets: Widgets, } impl Update for Win { type Model = (); type ModelParam = (); type Msg = Msg; fn model(_: &Relm<Self>, _: ()) -> () { } fn update(&mut self, event: Msg) { match event { Quit => gtk::main_quit(), } } } impl Widget for Win { type Root = Window; fn root(&self) -> Window
fn view(relm: &Relm<Self>, _model: Self::Model) -> Self { let window = Window::new(WindowType::Toplevel); let vbox = window.add_widget::<MyVBox>(()); window.show_all(); connect!(relm, window, connect_delete_event(_, _), return (Some(Msg::Quit), Inhibit(false))); Win { widgets: Widgets { vbox: vbox.widget().clone(), window, }, _components: Components { _vbox: vbox, }, } } } impl WidgetTest for Win { type Streams = (); fn get_streams(&self) -> Self::Streams { } type Widgets = Widgets; fn get_widgets(&self) -> Self::Widgets { self.widgets.clone() } } fn main() { Win::run(()).expect("Win::run failed"); } #[cfg(test)] mod tests { use gtk::{Button, Label, prelude::WidgetExt}; use gtk_test::find_child_by_name; use crate::Win; #[test] fn root_widget() { let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed"); let vbox = &widgets.vbox; let inc_button: Button = find_child_by_name(vbox, "inc_button").expect("inc button"); let label: Label = find_child_by_name(vbox, "label").expect("label"); let button: Button = find_child_by_name(vbox, "button").expect("button"); let dec_button: Button = find_child_by_name(vbox, "dec_button").expect("dec button"); let inc_allocation = inc_button.allocation(); let label_allocation = label.allocation(); let button_allocation = button.allocation(); let dec_button_allocation = dec_button.allocation(); assert!(inc_allocation.y() < label_allocation.y()); assert!(label_allocation.y() < button_allocation.y()); assert!(button_allocation.y() < dec_button_allocation.y()); } }
{ self.widgets.window.clone() }
identifier_body
main.rs
extern crate docopt; extern crate libc; #[cfg(feature = "re-pcre1")] extern crate libpcre_sys; extern crate memmap; #[cfg(feature = "re-onig")] extern crate onig; #[cfg(any(feature = "re-rust", feature = "re-rust-bytes",))] extern crate regex; #[cfg(feature = "re-rust")] extern crate regex_syntax; extern crate serde; #[macro_use] extern crate serde_derive; use std::fs::File; use std::str; use docopt::Docopt; use memmap::Mmap; mod ffi; const USAGE: &'static str = " Count the number of matches of <pattern> in <file>. This compiles the pattern once and counts all successive non-overlapping matches in <file>. <file> is memory mapped. Matching is done as if <file> were a single string (it is not line oriented). Since this tool includes compilation of the <pattern>, sufficiently large haystacks should be used to amortize the cost of compilation. (e.g., >1MB.) Usage: regex-run-one [options] [onig | pcre1 | pcre2 | stdcpp | re2 | rust | rust-bytes | tcl] <file> <pattern> regex-run-one [options] (-h | --help) Options: -h, --help Show this usage message. "; #[derive(Debug, Deserialize)] struct Args { arg_pattern: String, arg_file: String, cmd_onig: bool, cmd_pcre1: bool, cmd_pcre2: bool, cmd_stdcpp: bool, cmd_re2: bool, cmd_rust: bool, cmd_rust_bytes: bool, cmd_tcl: bool, } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.deserialize()) .unwrap_or_else(|e| e.exit()); let mmap = unsafe { Mmap::map(&File::open(&args.arg_file).unwrap()).unwrap() }; let haystack = unsafe { str::from_utf8_unchecked(&mmap) }; println!("{}", args.count(&haystack)); } impl Args { fn count(&self, haystack: &str) -> usize { let pat = &self.arg_pattern; if self.cmd_onig { count_onig(pat, haystack) } else if self.cmd_pcre1 { count_pcre1(pat, haystack) } else if self.cmd_pcre2 { count_pcre2(pat, haystack) } else if self.cmd_stdcpp { count_stdcpp(pat, haystack) } else if self.cmd_re2 { count_re2(pat, haystack) } else if self.cmd_rust { count_rust(pat, haystack) } else if self.cmd_rust_bytes { count_rust_bytes(pat, haystack) } else if self.cmd_tcl { count_tcl(pat, haystack) } else { panic!("unreachable") } } } macro_rules! nada { ($feature:expr, $name:ident) => { #[cfg(not(feature = $feature))] fn $name(_pat: &str, _haystack: &str) -> usize { panic!( "Support not enabled. Re-compile with '--features {}' \ to enable.", $feature ) } }; } nada!("re-onig", count_onig); #[cfg(feature = "re-onig")] fn count_onig(pat: &str, haystack: &str) -> usize { use ffi::onig::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } nada!("re-pcre1", count_pcre1); #[cfg(feature = "re-pcre1")] fn count_pcre1(pat: &str, haystack: &str) -> usize { use ffi::pcre1::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } nada!("re-pcre2", count_pcre2); #[cfg(feature = "re-pcre2")] fn count_pcre2(pat: &str, haystack: &str) -> usize { use ffi::pcre2::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } #[cfg(not(any(feature = "re-stdcpp", feature = "re-boost",)))] nada!("re-stdcpp", count_stdcpp); #[cfg(any(feature = "re-stdcpp", feature = "re-boost",))] fn count_stdcpp(pat: &str, haystack: &str) -> usize { use ffi::stdcpp::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } nada!("re-re2", count_re2); #[cfg(feature = "re-re2")] fn count_re2(pat: &str, haystack: &str) -> usize { use ffi::re2::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } nada!("re-rust", count_rust); #[cfg(feature = "re-rust")] fn
(pat: &str, haystack: &str) -> usize { use regex::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } nada!("re-rust-bytes", count_rust_bytes); #[cfg(feature = "re-rust-bytes")] fn count_rust_bytes(pat: &str, haystack: &str) -> usize { use regex::bytes::Regex; Regex::new(pat).unwrap().find_iter(haystack.as_bytes()).count() } nada!("re-tcl", count_tcl); #[cfg(feature = "re-tcl")] fn count_tcl(pat: &str, haystack: &str) -> usize { use ffi::tcl::{Regex, Text}; Regex::new(pat).unwrap().find_iter(&Text::new(haystack.to_owned())).count() }
count_rust
identifier_name
main.rs
extern crate docopt; extern crate libc; #[cfg(feature = "re-pcre1")] extern crate libpcre_sys; extern crate memmap; #[cfg(feature = "re-onig")] extern crate onig; #[cfg(any(feature = "re-rust", feature = "re-rust-bytes",))] extern crate regex; #[cfg(feature = "re-rust")] extern crate regex_syntax; extern crate serde; #[macro_use] extern crate serde_derive; use std::fs::File; use std::str; use docopt::Docopt; use memmap::Mmap; mod ffi; const USAGE: &'static str = " Count the number of matches of <pattern> in <file>. This compiles the pattern once and counts all successive non-overlapping matches in <file>. <file> is memory mapped. Matching is done as if <file> were a single string (it is not line oriented). Since this tool includes compilation of the <pattern>, sufficiently large haystacks should be used to amortize the cost of compilation. (e.g., >1MB.) Usage: regex-run-one [options] [onig | pcre1 | pcre2 | stdcpp | re2 | rust | rust-bytes | tcl] <file> <pattern> regex-run-one [options] (-h | --help) Options: -h, --help Show this usage message. "; #[derive(Debug, Deserialize)] struct Args { arg_pattern: String, arg_file: String, cmd_onig: bool, cmd_pcre1: bool, cmd_pcre2: bool, cmd_stdcpp: bool, cmd_re2: bool, cmd_rust: bool, cmd_rust_bytes: bool, cmd_tcl: bool, } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.deserialize()) .unwrap_or_else(|e| e.exit()); let mmap = unsafe { Mmap::map(&File::open(&args.arg_file).unwrap()).unwrap() }; let haystack = unsafe { str::from_utf8_unchecked(&mmap) }; println!("{}", args.count(&haystack)); } impl Args { fn count(&self, haystack: &str) -> usize { let pat = &self.arg_pattern; if self.cmd_onig { count_onig(pat, haystack) } else if self.cmd_pcre1 { count_pcre1(pat, haystack) } else if self.cmd_pcre2 { count_pcre2(pat, haystack) } else if self.cmd_stdcpp { count_stdcpp(pat, haystack) } else if self.cmd_re2 { count_re2(pat, haystack) } else if self.cmd_rust { count_rust(pat, haystack) } else if self.cmd_rust_bytes { count_rust_bytes(pat, haystack) } else if self.cmd_tcl { count_tcl(pat, haystack) } else { panic!("unreachable") } } } macro_rules! nada { ($feature:expr, $name:ident) => { #[cfg(not(feature = $feature))] fn $name(_pat: &str, _haystack: &str) -> usize { panic!( "Support not enabled. Re-compile with '--features {}' \ to enable.", $feature ) } }; } nada!("re-onig", count_onig); #[cfg(feature = "re-onig")] fn count_onig(pat: &str, haystack: &str) -> usize { use ffi::onig::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } nada!("re-pcre1", count_pcre1); #[cfg(feature = "re-pcre1")] fn count_pcre1(pat: &str, haystack: &str) -> usize { use ffi::pcre1::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } nada!("re-pcre2", count_pcre2); #[cfg(feature = "re-pcre2")] fn count_pcre2(pat: &str, haystack: &str) -> usize { use ffi::pcre2::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } #[cfg(not(any(feature = "re-stdcpp", feature = "re-boost",)))] nada!("re-stdcpp", count_stdcpp); #[cfg(any(feature = "re-stdcpp", feature = "re-boost",))] fn count_stdcpp(pat: &str, haystack: &str) -> usize { use ffi::stdcpp::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } nada!("re-re2", count_re2); #[cfg(feature = "re-re2")] fn count_re2(pat: &str, haystack: &str) -> usize { use ffi::re2::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } nada!("re-rust", count_rust); #[cfg(feature = "re-rust")] fn count_rust(pat: &str, haystack: &str) -> usize
nada!("re-rust-bytes", count_rust_bytes); #[cfg(feature = "re-rust-bytes")] fn count_rust_bytes(pat: &str, haystack: &str) -> usize { use regex::bytes::Regex; Regex::new(pat).unwrap().find_iter(haystack.as_bytes()).count() } nada!("re-tcl", count_tcl); #[cfg(feature = "re-tcl")] fn count_tcl(pat: &str, haystack: &str) -> usize { use ffi::tcl::{Regex, Text}; Regex::new(pat).unwrap().find_iter(&Text::new(haystack.to_owned())).count() }
{ use regex::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() }
identifier_body
main.rs
extern crate docopt; extern crate libc; #[cfg(feature = "re-pcre1")] extern crate libpcre_sys;
#[cfg(any(feature = "re-rust", feature = "re-rust-bytes",))] extern crate regex; #[cfg(feature = "re-rust")] extern crate regex_syntax; extern crate serde; #[macro_use] extern crate serde_derive; use std::fs::File; use std::str; use docopt::Docopt; use memmap::Mmap; mod ffi; const USAGE: &'static str = " Count the number of matches of <pattern> in <file>. This compiles the pattern once and counts all successive non-overlapping matches in <file>. <file> is memory mapped. Matching is done as if <file> were a single string (it is not line oriented). Since this tool includes compilation of the <pattern>, sufficiently large haystacks should be used to amortize the cost of compilation. (e.g., >1MB.) Usage: regex-run-one [options] [onig | pcre1 | pcre2 | stdcpp | re2 | rust | rust-bytes | tcl] <file> <pattern> regex-run-one [options] (-h | --help) Options: -h, --help Show this usage message. "; #[derive(Debug, Deserialize)] struct Args { arg_pattern: String, arg_file: String, cmd_onig: bool, cmd_pcre1: bool, cmd_pcre2: bool, cmd_stdcpp: bool, cmd_re2: bool, cmd_rust: bool, cmd_rust_bytes: bool, cmd_tcl: bool, } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.deserialize()) .unwrap_or_else(|e| e.exit()); let mmap = unsafe { Mmap::map(&File::open(&args.arg_file).unwrap()).unwrap() }; let haystack = unsafe { str::from_utf8_unchecked(&mmap) }; println!("{}", args.count(&haystack)); } impl Args { fn count(&self, haystack: &str) -> usize { let pat = &self.arg_pattern; if self.cmd_onig { count_onig(pat, haystack) } else if self.cmd_pcre1 { count_pcre1(pat, haystack) } else if self.cmd_pcre2 { count_pcre2(pat, haystack) } else if self.cmd_stdcpp { count_stdcpp(pat, haystack) } else if self.cmd_re2 { count_re2(pat, haystack) } else if self.cmd_rust { count_rust(pat, haystack) } else if self.cmd_rust_bytes { count_rust_bytes(pat, haystack) } else if self.cmd_tcl { count_tcl(pat, haystack) } else { panic!("unreachable") } } } macro_rules! nada { ($feature:expr, $name:ident) => { #[cfg(not(feature = $feature))] fn $name(_pat: &str, _haystack: &str) -> usize { panic!( "Support not enabled. Re-compile with '--features {}' \ to enable.", $feature ) } }; } nada!("re-onig", count_onig); #[cfg(feature = "re-onig")] fn count_onig(pat: &str, haystack: &str) -> usize { use ffi::onig::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } nada!("re-pcre1", count_pcre1); #[cfg(feature = "re-pcre1")] fn count_pcre1(pat: &str, haystack: &str) -> usize { use ffi::pcre1::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } nada!("re-pcre2", count_pcre2); #[cfg(feature = "re-pcre2")] fn count_pcre2(pat: &str, haystack: &str) -> usize { use ffi::pcre2::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } #[cfg(not(any(feature = "re-stdcpp", feature = "re-boost",)))] nada!("re-stdcpp", count_stdcpp); #[cfg(any(feature = "re-stdcpp", feature = "re-boost",))] fn count_stdcpp(pat: &str, haystack: &str) -> usize { use ffi::stdcpp::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } nada!("re-re2", count_re2); #[cfg(feature = "re-re2")] fn count_re2(pat: &str, haystack: &str) -> usize { use ffi::re2::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } nada!("re-rust", count_rust); #[cfg(feature = "re-rust")] fn count_rust(pat: &str, haystack: &str) -> usize { use regex::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } nada!("re-rust-bytes", count_rust_bytes); #[cfg(feature = "re-rust-bytes")] fn count_rust_bytes(pat: &str, haystack: &str) -> usize { use regex::bytes::Regex; Regex::new(pat).unwrap().find_iter(haystack.as_bytes()).count() } nada!("re-tcl", count_tcl); #[cfg(feature = "re-tcl")] fn count_tcl(pat: &str, haystack: &str) -> usize { use ffi::tcl::{Regex, Text}; Regex::new(pat).unwrap().find_iter(&Text::new(haystack.to_owned())).count() }
extern crate memmap; #[cfg(feature = "re-onig")] extern crate onig;
random_line_split
scan.rs
use std::fs; use std::io; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; pub struct Scandir { pub path: PathBuf, pub interval: u64, } impl Scandir { pub fn new(dir: &str, seconds: u64) -> Result<Scandir, io::Error> { let path = try!(fs::canonicalize(dir)); Ok( Scandir { path: path, interval: seconds } ) } pub fn scan(&self) { let files = match fs::read_dir(&self.path) { Err(f) =>
Ok(f) => f }; for f in files { let file = f.unwrap(); let mode = file.metadata().unwrap().permissions().mode(); let mut is_exec: bool = false; if!file.file_type().unwrap().is_dir() { is_exec = mode & 0o111!= 0; } println!("path: {} name: {} mode: {:o} is_exec: {}", file.path().display(), file.file_name().into_string().unwrap(), mode, is_exec); } } }
{ println!("{}", f); return; }
conditional_block
scan.rs
use std::fs; use std::io; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; pub struct Scandir { pub path: PathBuf, pub interval: u64, } impl Scandir { pub fn new(dir: &str, seconds: u64) -> Result<Scandir, io::Error> { let path = try!(fs::canonicalize(dir)); Ok( Scandir { path: path, interval: seconds } ) } pub fn
(&self) { let files = match fs::read_dir(&self.path) { Err(f) => { println!("{}", f); return; } Ok(f) => f }; for f in files { let file = f.unwrap(); let mode = file.metadata().unwrap().permissions().mode(); let mut is_exec: bool = false; if!file.file_type().unwrap().is_dir() { is_exec = mode & 0o111!= 0; } println!("path: {} name: {} mode: {:o} is_exec: {}", file.path().display(), file.file_name().into_string().unwrap(), mode, is_exec); } } }
scan
identifier_name
scan.rs
use std::fs; use std::io; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; pub struct Scandir {
impl Scandir { pub fn new(dir: &str, seconds: u64) -> Result<Scandir, io::Error> { let path = try!(fs::canonicalize(dir)); Ok( Scandir { path: path, interval: seconds } ) } pub fn scan(&self) { let files = match fs::read_dir(&self.path) { Err(f) => { println!("{}", f); return; } Ok(f) => f }; for f in files { let file = f.unwrap(); let mode = file.metadata().unwrap().permissions().mode(); let mut is_exec: bool = false; if!file.file_type().unwrap().is_dir() { is_exec = mode & 0o111!= 0; } println!("path: {} name: {} mode: {:o} is_exec: {}", file.path().display(), file.file_name().into_string().unwrap(), mode, is_exec); } } }
pub path: PathBuf, pub interval: u64, }
random_line_split
issue-17734.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that generating drop glue for Box<str> doesn't ICE #![allow(unknown_features)] #![feature(box_syntax)] fn f(s: Box<str>) -> Box<str> { s
} fn main() { // There is currently no safe way to construct a `Box<str>`, so improvise let box_arr: Box<[u8]> = box ['h' as u8, 'e' as u8, 'l' as u8, 'l' as u8, 'o' as u8]; let box_str: Box<str> = unsafe { std::mem::transmute(box_arr) }; assert_eq!(&*box_str, "hello"); f(box_str); }
random_line_split
issue-17734.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that generating drop glue for Box<str> doesn't ICE #![allow(unknown_features)] #![feature(box_syntax)] fn f(s: Box<str>) -> Box<str> { s } fn main()
{ // There is currently no safe way to construct a `Box<str>`, so improvise let box_arr: Box<[u8]> = box ['h' as u8, 'e' as u8, 'l' as u8, 'l' as u8, 'o' as u8]; let box_str: Box<str> = unsafe { std::mem::transmute(box_arr) }; assert_eq!(&*box_str, "hello"); f(box_str); }
identifier_body
issue-17734.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that generating drop glue for Box<str> doesn't ICE #![allow(unknown_features)] #![feature(box_syntax)] fn f(s: Box<str>) -> Box<str> { s } fn
() { // There is currently no safe way to construct a `Box<str>`, so improvise let box_arr: Box<[u8]> = box ['h' as u8, 'e' as u8, 'l' as u8, 'l' as u8, 'o' as u8]; let box_str: Box<str> = unsafe { std::mem::transmute(box_arr) }; assert_eq!(&*box_str, "hello"); f(box_str); }
main
identifier_name
mod.rs
// Copyright 2015 © Samuel Dolt <[email protected]> // // This file is part of orion_backend. // // Orion_backend is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Orion_backend is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with orion_backend. If not, see <http://www.gnu.org/licenses/>. mod unit; pub use self::unit::Unit; pub use self::unit::ParseUnitError;
pub use self::device::Device; mod measurement; pub use self::measurement::Measurement; pub use self::measurement::ParseMeasurementError; mod measurements_list; pub use self::measurements_list::MeasurementsList; pub use self::measurements_list::ParseMeasurementsListError;
mod device;
random_line_split
ison.rs
use std::fmt; use protocol::command::CMD_ISON; use protocol::message::{IrcMessage, MessageParamIter, RawMessage, ParseMessageError, ParseMessageErrorKind}; #[derive(Debug, Clone, Eq, PartialEq)] pub struct
<'a> { nicknames: &'a str, } impl<'a> IsonCommand<'a> { pub fn new(nicknames: &'a str) -> IsonCommand<'a> { IsonCommand { nicknames: nicknames, } } pub fn nicknames(&self) -> MessageParamIter<'a> { MessageParamIter::wrap(self.nicknames) } } impl<'a> fmt::Display for IsonCommand<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {}", CMD_ISON, self.nicknames) } } impl<'a> IrcMessage<'a> for IsonCommand<'a> { fn from_raw(raw: &RawMessage<'a>) -> Result<IsonCommand<'a>, ParseMessageError> { let nicknames = raw.parameters().get(); if nicknames.is_empty() { return Err(ParseMessageError::new(ParseMessageErrorKind::NeedMoreParams, "ISON requires at least one nickname")); } Ok(IsonCommand::new(nicknames)) } }
IsonCommand
identifier_name
ison.rs
#[derive(Debug, Clone, Eq, PartialEq)] pub struct IsonCommand<'a> { nicknames: &'a str, } impl<'a> IsonCommand<'a> { pub fn new(nicknames: &'a str) -> IsonCommand<'a> { IsonCommand { nicknames: nicknames, } } pub fn nicknames(&self) -> MessageParamIter<'a> { MessageParamIter::wrap(self.nicknames) } } impl<'a> fmt::Display for IsonCommand<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {}", CMD_ISON, self.nicknames) } } impl<'a> IrcMessage<'a> for IsonCommand<'a> { fn from_raw(raw: &RawMessage<'a>) -> Result<IsonCommand<'a>, ParseMessageError> { let nicknames = raw.parameters().get(); if nicknames.is_empty() { return Err(ParseMessageError::new(ParseMessageErrorKind::NeedMoreParams, "ISON requires at least one nickname")); } Ok(IsonCommand::new(nicknames)) } }
use std::fmt; use protocol::command::CMD_ISON; use protocol::message::{IrcMessage, MessageParamIter, RawMessage, ParseMessageError, ParseMessageErrorKind};
random_line_split
ison.rs
use std::fmt; use protocol::command::CMD_ISON; use protocol::message::{IrcMessage, MessageParamIter, RawMessage, ParseMessageError, ParseMessageErrorKind}; #[derive(Debug, Clone, Eq, PartialEq)] pub struct IsonCommand<'a> { nicknames: &'a str, } impl<'a> IsonCommand<'a> { pub fn new(nicknames: &'a str) -> IsonCommand<'a> { IsonCommand { nicknames: nicknames, } } pub fn nicknames(&self) -> MessageParamIter<'a> { MessageParamIter::wrap(self.nicknames) } } impl<'a> fmt::Display for IsonCommand<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {}", CMD_ISON, self.nicknames) } } impl<'a> IrcMessage<'a> for IsonCommand<'a> { fn from_raw(raw: &RawMessage<'a>) -> Result<IsonCommand<'a>, ParseMessageError> { let nicknames = raw.parameters().get(); if nicknames.is_empty()
Ok(IsonCommand::new(nicknames)) } }
{ return Err(ParseMessageError::new(ParseMessageErrorKind::NeedMoreParams, "ISON requires at least one nickname")); }
conditional_block
ison.rs
use std::fmt; use protocol::command::CMD_ISON; use protocol::message::{IrcMessage, MessageParamIter, RawMessage, ParseMessageError, ParseMessageErrorKind}; #[derive(Debug, Clone, Eq, PartialEq)] pub struct IsonCommand<'a> { nicknames: &'a str, } impl<'a> IsonCommand<'a> { pub fn new(nicknames: &'a str) -> IsonCommand<'a> { IsonCommand { nicknames: nicknames, } } pub fn nicknames(&self) -> MessageParamIter<'a> { MessageParamIter::wrap(self.nicknames) } } impl<'a> fmt::Display for IsonCommand<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
} impl<'a> IrcMessage<'a> for IsonCommand<'a> { fn from_raw(raw: &RawMessage<'a>) -> Result<IsonCommand<'a>, ParseMessageError> { let nicknames = raw.parameters().get(); if nicknames.is_empty() { return Err(ParseMessageError::new(ParseMessageErrorKind::NeedMoreParams, "ISON requires at least one nickname")); } Ok(IsonCommand::new(nicknames)) } }
{ write!(f, "{} {}", CMD_ISON, self.nicknames) }
identifier_body
point_segment.rs
use na::Transform; use na; use entities::shape::Segment; use point::PointQuery; use math::{Scalar, Point, Vect}; impl<P, M> PointQuery<P, M> for Segment<P> where P: Point, M: Transform<P> { #[inline] fn project_point(&self, m: &M, pt: &P, _: bool) -> P { let ls_pt = m.inv_transform(pt); let ab = *self.b() - *self.a(); let ap = ls_pt - *self.a(); let ab_ap = na::dot(&ab, &ap); let sqnab = na::sqnorm(&ab); if ab_ap <= na::zero() { // voronoï region of vertex 'a'. m.transform(self.a()) } else if ab_ap >= sqnab { // voronoï region of vertex 'b'. m.transform(self.b()) } else { assert!(sqnab!= na::zero()); // voronoï region of the segment interior. m.transform(&(*self.a() + ab * (ab_ap / sqnab))) } } #[inline] fn dis
elf, m: &M, pt: &P) -> <P::Vect as Vect>::Scalar { na::dist(pt, &self.project_point(m, pt, true)) } #[inline] fn contains_point(&self, m: &M, pt: &P) -> bool { na::approx_eq(&self.distance_to_point(m, pt), &na::zero()) } }
tance_to_point(&s
identifier_name
point_segment.rs
use na::Transform; use na; use entities::shape::Segment; use point::PointQuery; use math::{Scalar, Point, Vect}; impl<P, M> PointQuery<P, M> for Segment<P> where P: Point, M: Transform<P> { #[inline] fn project_point(&self, m: &M, pt: &P, _: bool) -> P { let ls_pt = m.inv_transform(pt); let ab = *self.b() - *self.a(); let ap = ls_pt - *self.a(); let ab_ap = na::dot(&ab, &ap); let sqnab = na::sqnorm(&ab); if ab_ap <= na::zero() { // voronoï region of vertex 'a'. m.transform(self.a()) } else if ab_ap >= sqnab { // voronoï region of vertex 'b'. m.transform(self.b()) } else { assert!(sqnab!= na::zero()); // voronoï region of the segment interior. m.transform(&(*self.a() + ab * (ab_ap / sqnab))) } }
#[inline] fn distance_to_point(&self, m: &M, pt: &P) -> <P::Vect as Vect>::Scalar { na::dist(pt, &self.project_point(m, pt, true)) } #[inline] fn contains_point(&self, m: &M, pt: &P) -> bool { na::approx_eq(&self.distance_to_point(m, pt), &na::zero()) } }
random_line_split
point_segment.rs
use na::Transform; use na; use entities::shape::Segment; use point::PointQuery; use math::{Scalar, Point, Vect}; impl<P, M> PointQuery<P, M> for Segment<P> where P: Point, M: Transform<P> { #[inline] fn project_point(&self, m: &M, pt: &P, _: bool) -> P
} #[inline] fn distance_to_point(&self, m: &M, pt: &P) -> <P::Vect as Vect>::Scalar { na::dist(pt, &self.project_point(m, pt, true)) } #[inline] fn contains_point(&self, m: &M, pt: &P) -> bool { na::approx_eq(&self.distance_to_point(m, pt), &na::zero()) } }
{ let ls_pt = m.inv_transform(pt); let ab = *self.b() - *self.a(); let ap = ls_pt - *self.a(); let ab_ap = na::dot(&ab, &ap); let sqnab = na::sqnorm(&ab); if ab_ap <= na::zero() { // voronoï region of vertex 'a'. m.transform(self.a()) } else if ab_ap >= sqnab { // voronoï region of vertex 'b'. m.transform(self.b()) } else { assert!(sqnab != na::zero()); // voronoï region of the segment interior. m.transform(&(*self.a() + ab * (ab_ap / sqnab))) }
identifier_body
main.rs
#![feature(plugin)] #![feature(test)] #![plugin(peg_syntax_ext)] #[macro_use] extern crate nom; extern crate clap; extern crate termion; extern crate byteorder; extern crate env_logger; extern crate vec_map; extern crate tempdir; #[macro_use] extern crate log; mod db; use db::server::Server; use db::database::{Database, QueryResult}; use clap::{Arg, App, SubCommand}; use std::io::{self, Read}; use std::io::{Write, stdout, stdin}; use std::fs; use termion::input::TermRead; use termion::{color, style}; use std::path::PathBuf; fn main() { println!("Starting the worst database ever created!! (exit to exit)"); let server = Server::new(); let app = App::new("TotalRecallDB") .version("v1.0") .author("Jon Haddad, <[email protected]>") .subcommand(SubCommand::with_name("test")) .get_matches(); if let Some(matches) = app.subcommand_matches("test") { run_test_repl(); } } fn run_test_repl() { let _ = env_logger::init(); println!("Running test repl"); // use local dir "dbs" let dbdir = "trdb"; if let Err(x) = fs::create_dir(dbdir) { warn!("Error creating directory {}", x); } let mut db = Database::new(PathBuf::from(dbdir)); let mut stdin = stdin(); let mut stdout = stdout(); let prompt = "embedded>"; loop { write!(stdout, "{}[?] {}{} ", color::Fg(color::Green), style::Reset, prompt).unwrap(); stdout.lock().flush().unwrap(); match TermRead::read_line(&mut stdin) { Ok(Some(buffer)) => { if buffer == "exit" { write!(stdout, "Exiting\r\n"); stdout.lock().flush().unwrap(); return; } let x= match db.execute(&buffer) { Ok(QueryResult::StreamCreated) => String::from("Stream Created.\n"), Ok(QueryResult::Insert(id)) => format!("Inserted {}", id), _ => String::from("Fail?") }; println!("{}", x); }, Ok(None) =>
, Err(e) => {} } } }
{}
conditional_block
main.rs
#![feature(plugin)] #![feature(test)] #![plugin(peg_syntax_ext)] #[macro_use] extern crate nom; extern crate clap; extern crate termion; extern crate byteorder; extern crate env_logger; extern crate vec_map; extern crate tempdir; #[macro_use] extern crate log; mod db; use db::server::Server; use db::database::{Database, QueryResult}; use clap::{Arg, App, SubCommand}; use std::io::{self, Read}; use std::io::{Write, stdout, stdin}; use std::fs; use termion::input::TermRead; use termion::{color, style}; use std::path::PathBuf; fn main()
fn run_test_repl() { let _ = env_logger::init(); println!("Running test repl"); // use local dir "dbs" let dbdir = "trdb"; if let Err(x) = fs::create_dir(dbdir) { warn!("Error creating directory {}", x); } let mut db = Database::new(PathBuf::from(dbdir)); let mut stdin = stdin(); let mut stdout = stdout(); let prompt = "embedded>"; loop { write!(stdout, "{}[?] {}{} ", color::Fg(color::Green), style::Reset, prompt).unwrap(); stdout.lock().flush().unwrap(); match TermRead::read_line(&mut stdin) { Ok(Some(buffer)) => { if buffer == "exit" { write!(stdout, "Exiting\r\n"); stdout.lock().flush().unwrap(); return; } let x= match db.execute(&buffer) { Ok(QueryResult::StreamCreated) => String::from("Stream Created.\n"), Ok(QueryResult::Insert(id)) => format!("Inserted {}", id), _ => String::from("Fail?") }; println!("{}", x); }, Ok(None) => {}, Err(e) => {} } } }
{ println!("Starting the worst database ever created!! (exit to exit)"); let server = Server::new(); let app = App::new("TotalRecallDB") .version("v1.0") .author("Jon Haddad, <[email protected]>") .subcommand(SubCommand::with_name("test")) .get_matches(); if let Some(matches) = app.subcommand_matches("test") { run_test_repl(); } }
identifier_body
main.rs
#![feature(plugin)] #![feature(test)] #![plugin(peg_syntax_ext)] #[macro_use] extern crate nom; extern crate clap; extern crate termion; extern crate byteorder; extern crate env_logger; extern crate vec_map; extern crate tempdir; #[macro_use] extern crate log; mod db; use db::server::Server; use db::database::{Database, QueryResult}; use clap::{Arg, App, SubCommand}; use std::io::{self, Read}; use std::io::{Write, stdout, stdin}; use std::fs; use termion::input::TermRead; use termion::{color, style}; use std::path::PathBuf; fn main() { println!("Starting the worst database ever created!! (exit to exit)"); let server = Server::new(); let app = App::new("TotalRecallDB") .version("v1.0") .author("Jon Haddad, <[email protected]>") .subcommand(SubCommand::with_name("test")) .get_matches(); if let Some(matches) = app.subcommand_matches("test") { run_test_repl(); } } fn
() { let _ = env_logger::init(); println!("Running test repl"); // use local dir "dbs" let dbdir = "trdb"; if let Err(x) = fs::create_dir(dbdir) { warn!("Error creating directory {}", x); } let mut db = Database::new(PathBuf::from(dbdir)); let mut stdin = stdin(); let mut stdout = stdout(); let prompt = "embedded>"; loop { write!(stdout, "{}[?] {}{} ", color::Fg(color::Green), style::Reset, prompt).unwrap(); stdout.lock().flush().unwrap(); match TermRead::read_line(&mut stdin) { Ok(Some(buffer)) => { if buffer == "exit" { write!(stdout, "Exiting\r\n"); stdout.lock().flush().unwrap(); return; } let x= match db.execute(&buffer) { Ok(QueryResult::StreamCreated) => String::from("Stream Created.\n"), Ok(QueryResult::Insert(id)) => format!("Inserted {}", id), _ => String::from("Fail?") }; println!("{}", x); }, Ok(None) => {}, Err(e) => {} } } }
run_test_repl
identifier_name
main.rs
#![feature(plugin)] #![feature(test)] #![plugin(peg_syntax_ext)] #[macro_use] extern crate nom; extern crate clap; extern crate termion; extern crate byteorder; extern crate env_logger; extern crate vec_map; extern crate tempdir; #[macro_use] extern crate log; mod db; use db::server::Server; use db::database::{Database, QueryResult}; use clap::{Arg, App, SubCommand}; use std::io::{self, Read}; use std::io::{Write, stdout, stdin}; use std::fs; use termion::input::TermRead; use termion::{color, style}; use std::path::PathBuf; fn main() { println!("Starting the worst database ever created!! (exit to exit)"); let server = Server::new(); let app = App::new("TotalRecallDB") .version("v1.0") .author("Jon Haddad, <[email protected]>") .subcommand(SubCommand::with_name("test")) .get_matches(); if let Some(matches) = app.subcommand_matches("test") { run_test_repl(); } } fn run_test_repl() { let _ = env_logger::init(); println!("Running test repl"); // use local dir "dbs" let dbdir = "trdb"; if let Err(x) = fs::create_dir(dbdir) { warn!("Error creating directory {}", x); } let mut db = Database::new(PathBuf::from(dbdir)); let mut stdin = stdin(); let mut stdout = stdout(); let prompt = "embedded>"; loop { write!(stdout, "{}[?] {}{} ", color::Fg(color::Green), style::Reset, prompt).unwrap(); stdout.lock().flush().unwrap(); match TermRead::read_line(&mut stdin) { Ok(Some(buffer)) => { if buffer == "exit" { write!(stdout, "Exiting\r\n"); stdout.lock().flush().unwrap(); return; } let x= match db.execute(&buffer) { Ok(QueryResult::StreamCreated) => String::from("Stream Created.\n"), Ok(QueryResult::Insert(id)) =>
}; println!("{}", x); }, Ok(None) => {}, Err(e) => {} } } }
format!("Inserted {}", id), _ => String::from("Fail?")
random_line_split
raft_engine_switch.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use crossbeam::channel::{unbounded, Receiver}; use engine_rocks::{self, raw::Env, RocksEngine}; use engine_traits::{ CompactExt, DeleteStrategy, Error as EngineError, Iterable, Iterator, MiscExt, RaftEngine, RaftLogBatch, Range, SeekKey, }; use file_system::delete_dir_if_exist; use kvproto::raft_serverpb::RaftLocalState; use protobuf::Message; use raft::eraftpb::Entry; use raft_log_engine::RaftLogEngine; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::{cmp, fs}; use tikv::config::TiKvConfig; const BATCH_THRESHOLD: usize = 32 * 1024; fn get_path_for_remove(path: &str) -> PathBuf { let mut flag_path = PathBuf::from(path); flag_path.set_extension("REMOVE"); flag_path } fn remove_tmp_dir<P: AsRef<Path>>(dir: P) { match delete_dir_if_exist(&dir) { Err(e) => warn!("Cannot remove {:?}: {}", dir.as_ref(), e), Ok(true) => info!("Remove {:?} success", dir.as_ref()), Ok(_) => {} } } fn rename_to_tmp_dir<P1: AsRef<Path>, P2: AsRef<Path>>(src: P1, dst: P2) { fs::rename(&src, &dst).unwrap(); let mut dir = dst.as_ref().to_path_buf(); assert!(dir.pop()); fs::File::open(&dir).and_then(|d| d.sync_all()).unwrap(); info!("Rename {:?} to {:?} correctly", src.as_ref(), dst.as_ref()); } fn clear_raft_engine(engine: &RaftLogEngine) -> Result<(), EngineError> { let mut batch_to_clean = engine.log_batch(0); for id in engine.raft_groups() { let state = engine.get_raft_state(id)?.unwrap(); engine.clean(id, &state, &mut batch_to_clean)?; } engine.consume(&mut batch_to_clean, true).map(|_| ()) } fn clear_raft_db(engine: &RocksEngine) -> Result<(), EngineError> { let start_key = keys::raft_log_key(0, 0); let end_key = keys::raft_log_key(u64::MAX, u64::MAX); engine.compact_range("default", Some(&start_key), Some(&end_key), false, 2)?; let range = Range::new(&start_key, &end_key); engine.delete_ranges_cf("default", DeleteStrategy::DeleteFiles, &[range])?; engine.sync()?; let mut count = 0; engine.scan(&start_key, &end_key, false, |_, _| { count += 1; Ok(true) })?; assert_eq!(count, 0); Ok(()) } /// Check the potential original raftdb directory and try to dump data out. /// /// Procedure: /// 1. Check whether the dump has been completed. If there is a dirty dir, /// delete the original raftdb safely and return. /// 2. Scan and dump raft data into raft engine. /// 3. Rename original raftdb dir to indicate that dump operation is done. /// 4. Delete the original raftdb safely. pub fn check_and_dump_raft_db( config: &TiKvConfig, engine: &RaftLogEngine, env: &Arc<Env>, thread_num: usize, ) { let raftdb_path = &config.raft_store.raftdb_path; let dirty_raftdb_path = get_path_for_remove(raftdb_path); if!RocksEngine::exists(raftdb_path) { remove_tmp_dir(&dirty_raftdb_path); return; } // Clean the target engine if it exists. clear_raft_engine(engine).expect("clear_raft_engine"); let config_raftdb = &config.raftdb; let mut raft_db_opts = config_raftdb.build_opt(); raft_db_opts.set_env(env.clone()); let raft_db_cf_opts = config_raftdb.build_cf_opts(&None); let db = engine_rocks::raw_util::new_engine_opt(&raftdb_path, raft_db_opts, raft_db_cf_opts) .unwrap_or_else(|s| fatal!("failed to create origin raft db: {}", s)); let src_engine = RocksEngine::from_db(Arc::new(db)); let count_size = Arc::new(AtomicUsize::new(0)); let mut count_region = 0; let mut threads = vec![]; let (tx, rx) = unbounded(); for _ in 0..thread_num { let src_engine = src_engine.clone(); let dst_engine = engine.clone(); let count_size = count_size.clone(); let rx = rx.clone(); let t = std::thread::spawn(move || { run_dump_raftdb_worker(&rx, &src_engine, &dst_engine, &count_size); }); threads.push(t); } info!("Start to scan raft log from RocksEngine and dump into RaftLogEngine"); let consumed_time = std::time::Instant::now(); // Seek all region id from raftdb and send them to workers. let mut it = src_engine.iterator().unwrap(); let mut valid = it.seek(SeekKey::Key(keys::REGION_RAFT_MIN_KEY)).unwrap(); while valid { match keys::decode_raft_key(it.key()) { Err(e) => { panic!("Error happened when decoding raft key: {}", e); } Ok((id, _)) => { tx.send(id).unwrap(); count_region += 1; let next_key = keys::raft_log_prefix(id + 1); valid = it.seek(SeekKey::Key(&next_key)).unwrap(); } } } drop(tx); info!("Scanned all region id and waiting for dump"); for t in threads { t.join().unwrap(); } engine.sync().unwrap(); info!( "Finished dump, total regions: {}; Total bytes: {}; Consumed time: {:?}", count_region, count_size.load(Ordering::Relaxed), consumed_time.elapsed(), ); rename_to_tmp_dir(&raftdb_path, &dirty_raftdb_path); remove_tmp_dir(&dirty_raftdb_path); } // Worker receives region id and scan the related range. fn run_dump_raftdb_worker( rx: &Receiver<u64>, old_engine: &RocksEngine, new_engine: &RaftLogEngine, count_size: &Arc<AtomicUsize>, ) { let mut batch = new_engine.log_batch(0); let mut local_size = 0; while let Ok(id) = rx.recv() { let mut entries = vec![]; old_engine .scan( &keys::raft_log_prefix(id), &keys::raft_log_prefix(id + 1), false, |key, value| { let res = keys::decode_raft_key(key); match res { Err(_) => Ok(true), Ok((region_id, suffix)) => { local_size += value.len(); match suffix { keys::RAFT_LOG_SUFFIX => { let mut entry = Entry::default(); entry.merge_from_bytes(&value)?; entries.push(entry); } keys::RAFT_STATE_SUFFIX => { let mut state = RaftLocalState::default(); state.merge_from_bytes(&value)?; batch.put_raft_state(region_id, &state).unwrap(); // Assume that we always scan entry first and raft state at the end. batch .append(region_id, std::mem::take(&mut entries)) .unwrap(); } _ => unreachable!("There is only 2 types of keys in raft"), } // Avoid long log batch. if local_size >= BATCH_THRESHOLD { local_size = 0; batch .append(region_id, std::mem::take(&mut entries)) .unwrap(); let size = new_engine.consume(&mut batch, false).unwrap(); count_size.fetch_add(size, Ordering::Relaxed); } Ok(true) } } }, ) .unwrap(); } let size = new_engine.consume(&mut batch, false).unwrap(); count_size.fetch_add(size, Ordering::Relaxed); } pub fn check_and_dump_raft_engine(config: &TiKvConfig, engine: &RocksEngine, thread_num: usize) { let raft_engine_config = config.raft_engine.config(); let raft_engine_path = &raft_engine_config.dir; let dirty_raft_engine_path = get_path_for_remove(raft_engine_path); if!RaftLogEngine::exists(raft_engine_path) { remove_tmp_dir(&dirty_raft_engine_path); return; } // Clean the target engine if it exists. clear_raft_db(engine).expect("clear_raft_db"); let src_engine = RaftLogEngine::new(raft_engine_config.clone()); let count_size = Arc::new(AtomicUsize::new(0)); let mut count_region = 0; let mut threads = vec![]; let (tx, rx) = unbounded(); for _ in 0..thread_num { let src_engine = src_engine.clone(); let dst_engine = engine.clone(); let count_size = count_size.clone(); let rx = rx.clone(); let t = std::thread::spawn(move || { run_dump_raft_engine_worker(&rx, &src_engine, &dst_engine, &count_size); }); threads.push(t); } info!("Start to scan raft log from RaftLogEngine and dump into RocksEngine"); let consumed_time = std::time::Instant::now(); // Seek all region id from RaftLogEngine and send them to workers. for id in src_engine.raft_groups() { tx.send(id).unwrap(); count_region += 1; }
info!("Scanned all region id and waiting for dump"); for t in threads { t.join().unwrap(); } engine.sync().unwrap(); info!( "Finished dump, total regions: {}; Total bytes: {}; Consumed time: {:?}", count_region, count_size.load(Ordering::Relaxed), consumed_time.elapsed(), ); rename_to_tmp_dir(&raft_engine_path, &dirty_raft_engine_path); remove_tmp_dir(&dirty_raft_engine_path); } fn run_dump_raft_engine_worker( rx: &Receiver<u64>, old_engine: &RaftLogEngine, new_engine: &RocksEngine, count_size: &Arc<AtomicUsize>, ) { while let Ok(id) = rx.recv() { let state = old_engine.get_raft_state(id).unwrap().unwrap(); new_engine.put_raft_state(id, &state).unwrap(); if let Some(last_index) = old_engine.last_index(id) { let mut batch = new_engine.log_batch(0); let mut begin = old_engine.first_index(id).unwrap(); while begin <= last_index { let end = cmp::min(begin + 1024, last_index + 1); let mut entries = Vec::with_capacity((end - begin) as usize); begin += old_engine .fetch_entries_to(id, begin, end, Some(BATCH_THRESHOLD), &mut entries) .unwrap() as u64; batch.append(id, entries).unwrap(); let size = new_engine.consume(&mut batch, false).unwrap(); count_size.fetch_add(size, Ordering::Relaxed); } } } } #[cfg(test)] mod tests { use super::*; use engine_rocks::raw::DBOptions; fn do_test_switch(custom_raft_db_wal: bool, continue_on_aborted: bool) { let data_path = tempfile::Builder::new().tempdir().unwrap().into_path(); let mut raftdb_path = data_path.clone(); let mut raft_engine_path = data_path; let mut raftdb_wal_path = raftdb_path.clone(); raftdb_path.push("raft"); raft_engine_path.push("raft-engine"); if custom_raft_db_wal { raftdb_wal_path.push("test-wal"); } let mut cfg = TiKvConfig::default(); cfg.raft_store.raftdb_path = raftdb_path.to_str().unwrap().to_owned(); cfg.raftdb.wal_dir = raftdb_wal_path.to_str().unwrap().to_owned(); cfg.raft_engine.mut_config().dir = raft_engine_path.to_str().unwrap().to_owned(); // Prepare some data for the RocksEngine. { let db = engine_rocks::raw_util::new_engine_opt( &cfg.raft_store.raftdb_path, cfg.raftdb.build_opt(), cfg.raftdb.build_cf_opts(&None), ) .unwrap(); let engine = RocksEngine::from_db(Arc::new(db)); let mut batch = engine.log_batch(0); set_write_batch(1, &mut batch); engine.consume(&mut batch, false).unwrap(); set_write_batch(5, &mut batch); engine.consume(&mut batch, false).unwrap(); set_write_batch(15, &mut batch); engine.consume(&mut batch, false).unwrap(); engine.sync().unwrap(); } // Dump logs from RocksEngine to RaftLogEngine. let raft_engine = RaftLogEngine::new(cfg.raft_engine.config()); if continue_on_aborted { let mut batch = raft_engine.log_batch(0); set_write_batch(25, &mut batch); raft_engine.consume(&mut batch, false).unwrap(); assert(25, &raft_engine); } check_and_dump_raft_db(&cfg, &raft_engine, &Arc::new(Env::default()), 4); assert(1, &raft_engine); assert(5, &raft_engine); assert(15, &raft_engine); assert_no(25, &raft_engine); drop(raft_engine); // Dump logs from RaftLogEngine to RocksEngine. let rocks_engine = { let db = engine_rocks::raw_util::new_engine_opt( &cfg.raft_store.raftdb_path, DBOptions::new(), vec![], ) .unwrap(); RocksEngine::from_db(Arc::new(db)) }; if continue_on_aborted { let mut batch = rocks_engine.log_batch(0); set_write_batch(25, &mut batch); rocks_engine.consume(&mut batch, false).unwrap(); assert(25, &rocks_engine); } check_and_dump_raft_engine(&cfg, &rocks_engine, 4); assert(1, &rocks_engine); assert(5, &rocks_engine); assert(15, &rocks_engine); assert_no(25, &rocks_engine); } #[test] fn test_switch() { do_test_switch(false, false); } #[test] fn test_switch_with_seperate_wal() { do_test_switch(true, false); } #[test] fn test_switch_continue_on_aborted() { do_test_switch(false, true); } // Insert some data into log batch. fn set_write_batch<T: RaftLogBatch>(num: u64, batch: &mut T) { let mut state = RaftLocalState::default(); state.set_last_index(num); batch.put_raft_state(num, &state).unwrap(); let mut entries = vec![]; for i in 0..num { let mut e = Entry::default(); e.set_index(i); entries.push(e); } batch.append(num, entries).unwrap(); } // Get data from raft engine and assert. fn assert<T: RaftEngine>(num: u64, engine: &T) { let state = engine.get_raft_state(num).unwrap().unwrap(); assert_eq!(state.get_last_index(), num); for i in 0..num { assert!(engine.get_entry(num, i).unwrap().is_some()); } } fn assert_no<T: RaftEngine>(num: u64, engine: &T) { assert!(engine.get_raft_state(num).unwrap().is_none()); for i in 0..num { assert!(engine.get_entry(num, i).unwrap().is_none()); } } }
drop(tx);
random_line_split
raft_engine_switch.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use crossbeam::channel::{unbounded, Receiver}; use engine_rocks::{self, raw::Env, RocksEngine}; use engine_traits::{ CompactExt, DeleteStrategy, Error as EngineError, Iterable, Iterator, MiscExt, RaftEngine, RaftLogBatch, Range, SeekKey, }; use file_system::delete_dir_if_exist; use kvproto::raft_serverpb::RaftLocalState; use protobuf::Message; use raft::eraftpb::Entry; use raft_log_engine::RaftLogEngine; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::{cmp, fs}; use tikv::config::TiKvConfig; const BATCH_THRESHOLD: usize = 32 * 1024; fn
(path: &str) -> PathBuf { let mut flag_path = PathBuf::from(path); flag_path.set_extension("REMOVE"); flag_path } fn remove_tmp_dir<P: AsRef<Path>>(dir: P) { match delete_dir_if_exist(&dir) { Err(e) => warn!("Cannot remove {:?}: {}", dir.as_ref(), e), Ok(true) => info!("Remove {:?} success", dir.as_ref()), Ok(_) => {} } } fn rename_to_tmp_dir<P1: AsRef<Path>, P2: AsRef<Path>>(src: P1, dst: P2) { fs::rename(&src, &dst).unwrap(); let mut dir = dst.as_ref().to_path_buf(); assert!(dir.pop()); fs::File::open(&dir).and_then(|d| d.sync_all()).unwrap(); info!("Rename {:?} to {:?} correctly", src.as_ref(), dst.as_ref()); } fn clear_raft_engine(engine: &RaftLogEngine) -> Result<(), EngineError> { let mut batch_to_clean = engine.log_batch(0); for id in engine.raft_groups() { let state = engine.get_raft_state(id)?.unwrap(); engine.clean(id, &state, &mut batch_to_clean)?; } engine.consume(&mut batch_to_clean, true).map(|_| ()) } fn clear_raft_db(engine: &RocksEngine) -> Result<(), EngineError> { let start_key = keys::raft_log_key(0, 0); let end_key = keys::raft_log_key(u64::MAX, u64::MAX); engine.compact_range("default", Some(&start_key), Some(&end_key), false, 2)?; let range = Range::new(&start_key, &end_key); engine.delete_ranges_cf("default", DeleteStrategy::DeleteFiles, &[range])?; engine.sync()?; let mut count = 0; engine.scan(&start_key, &end_key, false, |_, _| { count += 1; Ok(true) })?; assert_eq!(count, 0); Ok(()) } /// Check the potential original raftdb directory and try to dump data out. /// /// Procedure: /// 1. Check whether the dump has been completed. If there is a dirty dir, /// delete the original raftdb safely and return. /// 2. Scan and dump raft data into raft engine. /// 3. Rename original raftdb dir to indicate that dump operation is done. /// 4. Delete the original raftdb safely. pub fn check_and_dump_raft_db( config: &TiKvConfig, engine: &RaftLogEngine, env: &Arc<Env>, thread_num: usize, ) { let raftdb_path = &config.raft_store.raftdb_path; let dirty_raftdb_path = get_path_for_remove(raftdb_path); if!RocksEngine::exists(raftdb_path) { remove_tmp_dir(&dirty_raftdb_path); return; } // Clean the target engine if it exists. clear_raft_engine(engine).expect("clear_raft_engine"); let config_raftdb = &config.raftdb; let mut raft_db_opts = config_raftdb.build_opt(); raft_db_opts.set_env(env.clone()); let raft_db_cf_opts = config_raftdb.build_cf_opts(&None); let db = engine_rocks::raw_util::new_engine_opt(&raftdb_path, raft_db_opts, raft_db_cf_opts) .unwrap_or_else(|s| fatal!("failed to create origin raft db: {}", s)); let src_engine = RocksEngine::from_db(Arc::new(db)); let count_size = Arc::new(AtomicUsize::new(0)); let mut count_region = 0; let mut threads = vec![]; let (tx, rx) = unbounded(); for _ in 0..thread_num { let src_engine = src_engine.clone(); let dst_engine = engine.clone(); let count_size = count_size.clone(); let rx = rx.clone(); let t = std::thread::spawn(move || { run_dump_raftdb_worker(&rx, &src_engine, &dst_engine, &count_size); }); threads.push(t); } info!("Start to scan raft log from RocksEngine and dump into RaftLogEngine"); let consumed_time = std::time::Instant::now(); // Seek all region id from raftdb and send them to workers. let mut it = src_engine.iterator().unwrap(); let mut valid = it.seek(SeekKey::Key(keys::REGION_RAFT_MIN_KEY)).unwrap(); while valid { match keys::decode_raft_key(it.key()) { Err(e) => { panic!("Error happened when decoding raft key: {}", e); } Ok((id, _)) => { tx.send(id).unwrap(); count_region += 1; let next_key = keys::raft_log_prefix(id + 1); valid = it.seek(SeekKey::Key(&next_key)).unwrap(); } } } drop(tx); info!("Scanned all region id and waiting for dump"); for t in threads { t.join().unwrap(); } engine.sync().unwrap(); info!( "Finished dump, total regions: {}; Total bytes: {}; Consumed time: {:?}", count_region, count_size.load(Ordering::Relaxed), consumed_time.elapsed(), ); rename_to_tmp_dir(&raftdb_path, &dirty_raftdb_path); remove_tmp_dir(&dirty_raftdb_path); } // Worker receives region id and scan the related range. fn run_dump_raftdb_worker( rx: &Receiver<u64>, old_engine: &RocksEngine, new_engine: &RaftLogEngine, count_size: &Arc<AtomicUsize>, ) { let mut batch = new_engine.log_batch(0); let mut local_size = 0; while let Ok(id) = rx.recv() { let mut entries = vec![]; old_engine .scan( &keys::raft_log_prefix(id), &keys::raft_log_prefix(id + 1), false, |key, value| { let res = keys::decode_raft_key(key); match res { Err(_) => Ok(true), Ok((region_id, suffix)) => { local_size += value.len(); match suffix { keys::RAFT_LOG_SUFFIX => { let mut entry = Entry::default(); entry.merge_from_bytes(&value)?; entries.push(entry); } keys::RAFT_STATE_SUFFIX => { let mut state = RaftLocalState::default(); state.merge_from_bytes(&value)?; batch.put_raft_state(region_id, &state).unwrap(); // Assume that we always scan entry first and raft state at the end. batch .append(region_id, std::mem::take(&mut entries)) .unwrap(); } _ => unreachable!("There is only 2 types of keys in raft"), } // Avoid long log batch. if local_size >= BATCH_THRESHOLD { local_size = 0; batch .append(region_id, std::mem::take(&mut entries)) .unwrap(); let size = new_engine.consume(&mut batch, false).unwrap(); count_size.fetch_add(size, Ordering::Relaxed); } Ok(true) } } }, ) .unwrap(); } let size = new_engine.consume(&mut batch, false).unwrap(); count_size.fetch_add(size, Ordering::Relaxed); } pub fn check_and_dump_raft_engine(config: &TiKvConfig, engine: &RocksEngine, thread_num: usize) { let raft_engine_config = config.raft_engine.config(); let raft_engine_path = &raft_engine_config.dir; let dirty_raft_engine_path = get_path_for_remove(raft_engine_path); if!RaftLogEngine::exists(raft_engine_path) { remove_tmp_dir(&dirty_raft_engine_path); return; } // Clean the target engine if it exists. clear_raft_db(engine).expect("clear_raft_db"); let src_engine = RaftLogEngine::new(raft_engine_config.clone()); let count_size = Arc::new(AtomicUsize::new(0)); let mut count_region = 0; let mut threads = vec![]; let (tx, rx) = unbounded(); for _ in 0..thread_num { let src_engine = src_engine.clone(); let dst_engine = engine.clone(); let count_size = count_size.clone(); let rx = rx.clone(); let t = std::thread::spawn(move || { run_dump_raft_engine_worker(&rx, &src_engine, &dst_engine, &count_size); }); threads.push(t); } info!("Start to scan raft log from RaftLogEngine and dump into RocksEngine"); let consumed_time = std::time::Instant::now(); // Seek all region id from RaftLogEngine and send them to workers. for id in src_engine.raft_groups() { tx.send(id).unwrap(); count_region += 1; } drop(tx); info!("Scanned all region id and waiting for dump"); for t in threads { t.join().unwrap(); } engine.sync().unwrap(); info!( "Finished dump, total regions: {}; Total bytes: {}; Consumed time: {:?}", count_region, count_size.load(Ordering::Relaxed), consumed_time.elapsed(), ); rename_to_tmp_dir(&raft_engine_path, &dirty_raft_engine_path); remove_tmp_dir(&dirty_raft_engine_path); } fn run_dump_raft_engine_worker( rx: &Receiver<u64>, old_engine: &RaftLogEngine, new_engine: &RocksEngine, count_size: &Arc<AtomicUsize>, ) { while let Ok(id) = rx.recv() { let state = old_engine.get_raft_state(id).unwrap().unwrap(); new_engine.put_raft_state(id, &state).unwrap(); if let Some(last_index) = old_engine.last_index(id) { let mut batch = new_engine.log_batch(0); let mut begin = old_engine.first_index(id).unwrap(); while begin <= last_index { let end = cmp::min(begin + 1024, last_index + 1); let mut entries = Vec::with_capacity((end - begin) as usize); begin += old_engine .fetch_entries_to(id, begin, end, Some(BATCH_THRESHOLD), &mut entries) .unwrap() as u64; batch.append(id, entries).unwrap(); let size = new_engine.consume(&mut batch, false).unwrap(); count_size.fetch_add(size, Ordering::Relaxed); } } } } #[cfg(test)] mod tests { use super::*; use engine_rocks::raw::DBOptions; fn do_test_switch(custom_raft_db_wal: bool, continue_on_aborted: bool) { let data_path = tempfile::Builder::new().tempdir().unwrap().into_path(); let mut raftdb_path = data_path.clone(); let mut raft_engine_path = data_path; let mut raftdb_wal_path = raftdb_path.clone(); raftdb_path.push("raft"); raft_engine_path.push("raft-engine"); if custom_raft_db_wal { raftdb_wal_path.push("test-wal"); } let mut cfg = TiKvConfig::default(); cfg.raft_store.raftdb_path = raftdb_path.to_str().unwrap().to_owned(); cfg.raftdb.wal_dir = raftdb_wal_path.to_str().unwrap().to_owned(); cfg.raft_engine.mut_config().dir = raft_engine_path.to_str().unwrap().to_owned(); // Prepare some data for the RocksEngine. { let db = engine_rocks::raw_util::new_engine_opt( &cfg.raft_store.raftdb_path, cfg.raftdb.build_opt(), cfg.raftdb.build_cf_opts(&None), ) .unwrap(); let engine = RocksEngine::from_db(Arc::new(db)); let mut batch = engine.log_batch(0); set_write_batch(1, &mut batch); engine.consume(&mut batch, false).unwrap(); set_write_batch(5, &mut batch); engine.consume(&mut batch, false).unwrap(); set_write_batch(15, &mut batch); engine.consume(&mut batch, false).unwrap(); engine.sync().unwrap(); } // Dump logs from RocksEngine to RaftLogEngine. let raft_engine = RaftLogEngine::new(cfg.raft_engine.config()); if continue_on_aborted { let mut batch = raft_engine.log_batch(0); set_write_batch(25, &mut batch); raft_engine.consume(&mut batch, false).unwrap(); assert(25, &raft_engine); } check_and_dump_raft_db(&cfg, &raft_engine, &Arc::new(Env::default()), 4); assert(1, &raft_engine); assert(5, &raft_engine); assert(15, &raft_engine); assert_no(25, &raft_engine); drop(raft_engine); // Dump logs from RaftLogEngine to RocksEngine. let rocks_engine = { let db = engine_rocks::raw_util::new_engine_opt( &cfg.raft_store.raftdb_path, DBOptions::new(), vec![], ) .unwrap(); RocksEngine::from_db(Arc::new(db)) }; if continue_on_aborted { let mut batch = rocks_engine.log_batch(0); set_write_batch(25, &mut batch); rocks_engine.consume(&mut batch, false).unwrap(); assert(25, &rocks_engine); } check_and_dump_raft_engine(&cfg, &rocks_engine, 4); assert(1, &rocks_engine); assert(5, &rocks_engine); assert(15, &rocks_engine); assert_no(25, &rocks_engine); } #[test] fn test_switch() { do_test_switch(false, false); } #[test] fn test_switch_with_seperate_wal() { do_test_switch(true, false); } #[test] fn test_switch_continue_on_aborted() { do_test_switch(false, true); } // Insert some data into log batch. fn set_write_batch<T: RaftLogBatch>(num: u64, batch: &mut T) { let mut state = RaftLocalState::default(); state.set_last_index(num); batch.put_raft_state(num, &state).unwrap(); let mut entries = vec![]; for i in 0..num { let mut e = Entry::default(); e.set_index(i); entries.push(e); } batch.append(num, entries).unwrap(); } // Get data from raft engine and assert. fn assert<T: RaftEngine>(num: u64, engine: &T) { let state = engine.get_raft_state(num).unwrap().unwrap(); assert_eq!(state.get_last_index(), num); for i in 0..num { assert!(engine.get_entry(num, i).unwrap().is_some()); } } fn assert_no<T: RaftEngine>(num: u64, engine: &T) { assert!(engine.get_raft_state(num).unwrap().is_none()); for i in 0..num { assert!(engine.get_entry(num, i).unwrap().is_none()); } } }
get_path_for_remove
identifier_name
raft_engine_switch.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use crossbeam::channel::{unbounded, Receiver}; use engine_rocks::{self, raw::Env, RocksEngine}; use engine_traits::{ CompactExt, DeleteStrategy, Error as EngineError, Iterable, Iterator, MiscExt, RaftEngine, RaftLogBatch, Range, SeekKey, }; use file_system::delete_dir_if_exist; use kvproto::raft_serverpb::RaftLocalState; use protobuf::Message; use raft::eraftpb::Entry; use raft_log_engine::RaftLogEngine; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::{cmp, fs}; use tikv::config::TiKvConfig; const BATCH_THRESHOLD: usize = 32 * 1024; fn get_path_for_remove(path: &str) -> PathBuf { let mut flag_path = PathBuf::from(path); flag_path.set_extension("REMOVE"); flag_path } fn remove_tmp_dir<P: AsRef<Path>>(dir: P) { match delete_dir_if_exist(&dir) { Err(e) => warn!("Cannot remove {:?}: {}", dir.as_ref(), e), Ok(true) => info!("Remove {:?} success", dir.as_ref()), Ok(_) => {} } } fn rename_to_tmp_dir<P1: AsRef<Path>, P2: AsRef<Path>>(src: P1, dst: P2) { fs::rename(&src, &dst).unwrap(); let mut dir = dst.as_ref().to_path_buf(); assert!(dir.pop()); fs::File::open(&dir).and_then(|d| d.sync_all()).unwrap(); info!("Rename {:?} to {:?} correctly", src.as_ref(), dst.as_ref()); } fn clear_raft_engine(engine: &RaftLogEngine) -> Result<(), EngineError> { let mut batch_to_clean = engine.log_batch(0); for id in engine.raft_groups() { let state = engine.get_raft_state(id)?.unwrap(); engine.clean(id, &state, &mut batch_to_clean)?; } engine.consume(&mut batch_to_clean, true).map(|_| ()) } fn clear_raft_db(engine: &RocksEngine) -> Result<(), EngineError> { let start_key = keys::raft_log_key(0, 0); let end_key = keys::raft_log_key(u64::MAX, u64::MAX); engine.compact_range("default", Some(&start_key), Some(&end_key), false, 2)?; let range = Range::new(&start_key, &end_key); engine.delete_ranges_cf("default", DeleteStrategy::DeleteFiles, &[range])?; engine.sync()?; let mut count = 0; engine.scan(&start_key, &end_key, false, |_, _| { count += 1; Ok(true) })?; assert_eq!(count, 0); Ok(()) } /// Check the potential original raftdb directory and try to dump data out. /// /// Procedure: /// 1. Check whether the dump has been completed. If there is a dirty dir, /// delete the original raftdb safely and return. /// 2. Scan and dump raft data into raft engine. /// 3. Rename original raftdb dir to indicate that dump operation is done. /// 4. Delete the original raftdb safely. pub fn check_and_dump_raft_db( config: &TiKvConfig, engine: &RaftLogEngine, env: &Arc<Env>, thread_num: usize, ) { let raftdb_path = &config.raft_store.raftdb_path; let dirty_raftdb_path = get_path_for_remove(raftdb_path); if!RocksEngine::exists(raftdb_path) { remove_tmp_dir(&dirty_raftdb_path); return; } // Clean the target engine if it exists. clear_raft_engine(engine).expect("clear_raft_engine"); let config_raftdb = &config.raftdb; let mut raft_db_opts = config_raftdb.build_opt(); raft_db_opts.set_env(env.clone()); let raft_db_cf_opts = config_raftdb.build_cf_opts(&None); let db = engine_rocks::raw_util::new_engine_opt(&raftdb_path, raft_db_opts, raft_db_cf_opts) .unwrap_or_else(|s| fatal!("failed to create origin raft db: {}", s)); let src_engine = RocksEngine::from_db(Arc::new(db)); let count_size = Arc::new(AtomicUsize::new(0)); let mut count_region = 0; let mut threads = vec![]; let (tx, rx) = unbounded(); for _ in 0..thread_num { let src_engine = src_engine.clone(); let dst_engine = engine.clone(); let count_size = count_size.clone(); let rx = rx.clone(); let t = std::thread::spawn(move || { run_dump_raftdb_worker(&rx, &src_engine, &dst_engine, &count_size); }); threads.push(t); } info!("Start to scan raft log from RocksEngine and dump into RaftLogEngine"); let consumed_time = std::time::Instant::now(); // Seek all region id from raftdb and send them to workers. let mut it = src_engine.iterator().unwrap(); let mut valid = it.seek(SeekKey::Key(keys::REGION_RAFT_MIN_KEY)).unwrap(); while valid { match keys::decode_raft_key(it.key()) { Err(e) => { panic!("Error happened when decoding raft key: {}", e); } Ok((id, _)) => { tx.send(id).unwrap(); count_region += 1; let next_key = keys::raft_log_prefix(id + 1); valid = it.seek(SeekKey::Key(&next_key)).unwrap(); } } } drop(tx); info!("Scanned all region id and waiting for dump"); for t in threads { t.join().unwrap(); } engine.sync().unwrap(); info!( "Finished dump, total regions: {}; Total bytes: {}; Consumed time: {:?}", count_region, count_size.load(Ordering::Relaxed), consumed_time.elapsed(), ); rename_to_tmp_dir(&raftdb_path, &dirty_raftdb_path); remove_tmp_dir(&dirty_raftdb_path); } // Worker receives region id and scan the related range. fn run_dump_raftdb_worker( rx: &Receiver<u64>, old_engine: &RocksEngine, new_engine: &RaftLogEngine, count_size: &Arc<AtomicUsize>, ) { let mut batch = new_engine.log_batch(0); let mut local_size = 0; while let Ok(id) = rx.recv() { let mut entries = vec![]; old_engine .scan( &keys::raft_log_prefix(id), &keys::raft_log_prefix(id + 1), false, |key, value| { let res = keys::decode_raft_key(key); match res { Err(_) => Ok(true), Ok((region_id, suffix)) => { local_size += value.len(); match suffix { keys::RAFT_LOG_SUFFIX => { let mut entry = Entry::default(); entry.merge_from_bytes(&value)?; entries.push(entry); } keys::RAFT_STATE_SUFFIX => { let mut state = RaftLocalState::default(); state.merge_from_bytes(&value)?; batch.put_raft_state(region_id, &state).unwrap(); // Assume that we always scan entry first and raft state at the end. batch .append(region_id, std::mem::take(&mut entries)) .unwrap(); } _ => unreachable!("There is only 2 types of keys in raft"), } // Avoid long log batch. if local_size >= BATCH_THRESHOLD { local_size = 0; batch .append(region_id, std::mem::take(&mut entries)) .unwrap(); let size = new_engine.consume(&mut batch, false).unwrap(); count_size.fetch_add(size, Ordering::Relaxed); } Ok(true) } } }, ) .unwrap(); } let size = new_engine.consume(&mut batch, false).unwrap(); count_size.fetch_add(size, Ordering::Relaxed); } pub fn check_and_dump_raft_engine(config: &TiKvConfig, engine: &RocksEngine, thread_num: usize) { let raft_engine_config = config.raft_engine.config(); let raft_engine_path = &raft_engine_config.dir; let dirty_raft_engine_path = get_path_for_remove(raft_engine_path); if!RaftLogEngine::exists(raft_engine_path) { remove_tmp_dir(&dirty_raft_engine_path); return; } // Clean the target engine if it exists. clear_raft_db(engine).expect("clear_raft_db"); let src_engine = RaftLogEngine::new(raft_engine_config.clone()); let count_size = Arc::new(AtomicUsize::new(0)); let mut count_region = 0; let mut threads = vec![]; let (tx, rx) = unbounded(); for _ in 0..thread_num { let src_engine = src_engine.clone(); let dst_engine = engine.clone(); let count_size = count_size.clone(); let rx = rx.clone(); let t = std::thread::spawn(move || { run_dump_raft_engine_worker(&rx, &src_engine, &dst_engine, &count_size); }); threads.push(t); } info!("Start to scan raft log from RaftLogEngine and dump into RocksEngine"); let consumed_time = std::time::Instant::now(); // Seek all region id from RaftLogEngine and send them to workers. for id in src_engine.raft_groups() { tx.send(id).unwrap(); count_region += 1; } drop(tx); info!("Scanned all region id and waiting for dump"); for t in threads { t.join().unwrap(); } engine.sync().unwrap(); info!( "Finished dump, total regions: {}; Total bytes: {}; Consumed time: {:?}", count_region, count_size.load(Ordering::Relaxed), consumed_time.elapsed(), ); rename_to_tmp_dir(&raft_engine_path, &dirty_raft_engine_path); remove_tmp_dir(&dirty_raft_engine_path); } fn run_dump_raft_engine_worker( rx: &Receiver<u64>, old_engine: &RaftLogEngine, new_engine: &RocksEngine, count_size: &Arc<AtomicUsize>, ) { while let Ok(id) = rx.recv() { let state = old_engine.get_raft_state(id).unwrap().unwrap(); new_engine.put_raft_state(id, &state).unwrap(); if let Some(last_index) = old_engine.last_index(id) { let mut batch = new_engine.log_batch(0); let mut begin = old_engine.first_index(id).unwrap(); while begin <= last_index { let end = cmp::min(begin + 1024, last_index + 1); let mut entries = Vec::with_capacity((end - begin) as usize); begin += old_engine .fetch_entries_to(id, begin, end, Some(BATCH_THRESHOLD), &mut entries) .unwrap() as u64; batch.append(id, entries).unwrap(); let size = new_engine.consume(&mut batch, false).unwrap(); count_size.fetch_add(size, Ordering::Relaxed); } } } } #[cfg(test)] mod tests { use super::*; use engine_rocks::raw::DBOptions; fn do_test_switch(custom_raft_db_wal: bool, continue_on_aborted: bool) { let data_path = tempfile::Builder::new().tempdir().unwrap().into_path(); let mut raftdb_path = data_path.clone(); let mut raft_engine_path = data_path; let mut raftdb_wal_path = raftdb_path.clone(); raftdb_path.push("raft"); raft_engine_path.push("raft-engine"); if custom_raft_db_wal { raftdb_wal_path.push("test-wal"); } let mut cfg = TiKvConfig::default(); cfg.raft_store.raftdb_path = raftdb_path.to_str().unwrap().to_owned(); cfg.raftdb.wal_dir = raftdb_wal_path.to_str().unwrap().to_owned(); cfg.raft_engine.mut_config().dir = raft_engine_path.to_str().unwrap().to_owned(); // Prepare some data for the RocksEngine. { let db = engine_rocks::raw_util::new_engine_opt( &cfg.raft_store.raftdb_path, cfg.raftdb.build_opt(), cfg.raftdb.build_cf_opts(&None), ) .unwrap(); let engine = RocksEngine::from_db(Arc::new(db)); let mut batch = engine.log_batch(0); set_write_batch(1, &mut batch); engine.consume(&mut batch, false).unwrap(); set_write_batch(5, &mut batch); engine.consume(&mut batch, false).unwrap(); set_write_batch(15, &mut batch); engine.consume(&mut batch, false).unwrap(); engine.sync().unwrap(); } // Dump logs from RocksEngine to RaftLogEngine. let raft_engine = RaftLogEngine::new(cfg.raft_engine.config()); if continue_on_aborted { let mut batch = raft_engine.log_batch(0); set_write_batch(25, &mut batch); raft_engine.consume(&mut batch, false).unwrap(); assert(25, &raft_engine); } check_and_dump_raft_db(&cfg, &raft_engine, &Arc::new(Env::default()), 4); assert(1, &raft_engine); assert(5, &raft_engine); assert(15, &raft_engine); assert_no(25, &raft_engine); drop(raft_engine); // Dump logs from RaftLogEngine to RocksEngine. let rocks_engine = { let db = engine_rocks::raw_util::new_engine_opt( &cfg.raft_store.raftdb_path, DBOptions::new(), vec![], ) .unwrap(); RocksEngine::from_db(Arc::new(db)) }; if continue_on_aborted { let mut batch = rocks_engine.log_batch(0); set_write_batch(25, &mut batch); rocks_engine.consume(&mut batch, false).unwrap(); assert(25, &rocks_engine); } check_and_dump_raft_engine(&cfg, &rocks_engine, 4); assert(1, &rocks_engine); assert(5, &rocks_engine); assert(15, &rocks_engine); assert_no(25, &rocks_engine); } #[test] fn test_switch() { do_test_switch(false, false); } #[test] fn test_switch_with_seperate_wal() { do_test_switch(true, false); } #[test] fn test_switch_continue_on_aborted()
// Insert some data into log batch. fn set_write_batch<T: RaftLogBatch>(num: u64, batch: &mut T) { let mut state = RaftLocalState::default(); state.set_last_index(num); batch.put_raft_state(num, &state).unwrap(); let mut entries = vec![]; for i in 0..num { let mut e = Entry::default(); e.set_index(i); entries.push(e); } batch.append(num, entries).unwrap(); } // Get data from raft engine and assert. fn assert<T: RaftEngine>(num: u64, engine: &T) { let state = engine.get_raft_state(num).unwrap().unwrap(); assert_eq!(state.get_last_index(), num); for i in 0..num { assert!(engine.get_entry(num, i).unwrap().is_some()); } } fn assert_no<T: RaftEngine>(num: u64, engine: &T) { assert!(engine.get_raft_state(num).unwrap().is_none()); for i in 0..num { assert!(engine.get_entry(num, i).unwrap().is_none()); } } }
{ do_test_switch(false, true); }
identifier_body
raft_engine_switch.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use crossbeam::channel::{unbounded, Receiver}; use engine_rocks::{self, raw::Env, RocksEngine}; use engine_traits::{ CompactExt, DeleteStrategy, Error as EngineError, Iterable, Iterator, MiscExt, RaftEngine, RaftLogBatch, Range, SeekKey, }; use file_system::delete_dir_if_exist; use kvproto::raft_serverpb::RaftLocalState; use protobuf::Message; use raft::eraftpb::Entry; use raft_log_engine::RaftLogEngine; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::{cmp, fs}; use tikv::config::TiKvConfig; const BATCH_THRESHOLD: usize = 32 * 1024; fn get_path_for_remove(path: &str) -> PathBuf { let mut flag_path = PathBuf::from(path); flag_path.set_extension("REMOVE"); flag_path } fn remove_tmp_dir<P: AsRef<Path>>(dir: P) { match delete_dir_if_exist(&dir) { Err(e) => warn!("Cannot remove {:?}: {}", dir.as_ref(), e), Ok(true) => info!("Remove {:?} success", dir.as_ref()), Ok(_) => {} } } fn rename_to_tmp_dir<P1: AsRef<Path>, P2: AsRef<Path>>(src: P1, dst: P2) { fs::rename(&src, &dst).unwrap(); let mut dir = dst.as_ref().to_path_buf(); assert!(dir.pop()); fs::File::open(&dir).and_then(|d| d.sync_all()).unwrap(); info!("Rename {:?} to {:?} correctly", src.as_ref(), dst.as_ref()); } fn clear_raft_engine(engine: &RaftLogEngine) -> Result<(), EngineError> { let mut batch_to_clean = engine.log_batch(0); for id in engine.raft_groups() { let state = engine.get_raft_state(id)?.unwrap(); engine.clean(id, &state, &mut batch_to_clean)?; } engine.consume(&mut batch_to_clean, true).map(|_| ()) } fn clear_raft_db(engine: &RocksEngine) -> Result<(), EngineError> { let start_key = keys::raft_log_key(0, 0); let end_key = keys::raft_log_key(u64::MAX, u64::MAX); engine.compact_range("default", Some(&start_key), Some(&end_key), false, 2)?; let range = Range::new(&start_key, &end_key); engine.delete_ranges_cf("default", DeleteStrategy::DeleteFiles, &[range])?; engine.sync()?; let mut count = 0; engine.scan(&start_key, &end_key, false, |_, _| { count += 1; Ok(true) })?; assert_eq!(count, 0); Ok(()) } /// Check the potential original raftdb directory and try to dump data out. /// /// Procedure: /// 1. Check whether the dump has been completed. If there is a dirty dir, /// delete the original raftdb safely and return. /// 2. Scan and dump raft data into raft engine. /// 3. Rename original raftdb dir to indicate that dump operation is done. /// 4. Delete the original raftdb safely. pub fn check_and_dump_raft_db( config: &TiKvConfig, engine: &RaftLogEngine, env: &Arc<Env>, thread_num: usize, ) { let raftdb_path = &config.raft_store.raftdb_path; let dirty_raftdb_path = get_path_for_remove(raftdb_path); if!RocksEngine::exists(raftdb_path)
// Clean the target engine if it exists. clear_raft_engine(engine).expect("clear_raft_engine"); let config_raftdb = &config.raftdb; let mut raft_db_opts = config_raftdb.build_opt(); raft_db_opts.set_env(env.clone()); let raft_db_cf_opts = config_raftdb.build_cf_opts(&None); let db = engine_rocks::raw_util::new_engine_opt(&raftdb_path, raft_db_opts, raft_db_cf_opts) .unwrap_or_else(|s| fatal!("failed to create origin raft db: {}", s)); let src_engine = RocksEngine::from_db(Arc::new(db)); let count_size = Arc::new(AtomicUsize::new(0)); let mut count_region = 0; let mut threads = vec![]; let (tx, rx) = unbounded(); for _ in 0..thread_num { let src_engine = src_engine.clone(); let dst_engine = engine.clone(); let count_size = count_size.clone(); let rx = rx.clone(); let t = std::thread::spawn(move || { run_dump_raftdb_worker(&rx, &src_engine, &dst_engine, &count_size); }); threads.push(t); } info!("Start to scan raft log from RocksEngine and dump into RaftLogEngine"); let consumed_time = std::time::Instant::now(); // Seek all region id from raftdb and send them to workers. let mut it = src_engine.iterator().unwrap(); let mut valid = it.seek(SeekKey::Key(keys::REGION_RAFT_MIN_KEY)).unwrap(); while valid { match keys::decode_raft_key(it.key()) { Err(e) => { panic!("Error happened when decoding raft key: {}", e); } Ok((id, _)) => { tx.send(id).unwrap(); count_region += 1; let next_key = keys::raft_log_prefix(id + 1); valid = it.seek(SeekKey::Key(&next_key)).unwrap(); } } } drop(tx); info!("Scanned all region id and waiting for dump"); for t in threads { t.join().unwrap(); } engine.sync().unwrap(); info!( "Finished dump, total regions: {}; Total bytes: {}; Consumed time: {:?}", count_region, count_size.load(Ordering::Relaxed), consumed_time.elapsed(), ); rename_to_tmp_dir(&raftdb_path, &dirty_raftdb_path); remove_tmp_dir(&dirty_raftdb_path); } // Worker receives region id and scan the related range. fn run_dump_raftdb_worker( rx: &Receiver<u64>, old_engine: &RocksEngine, new_engine: &RaftLogEngine, count_size: &Arc<AtomicUsize>, ) { let mut batch = new_engine.log_batch(0); let mut local_size = 0; while let Ok(id) = rx.recv() { let mut entries = vec![]; old_engine .scan( &keys::raft_log_prefix(id), &keys::raft_log_prefix(id + 1), false, |key, value| { let res = keys::decode_raft_key(key); match res { Err(_) => Ok(true), Ok((region_id, suffix)) => { local_size += value.len(); match suffix { keys::RAFT_LOG_SUFFIX => { let mut entry = Entry::default(); entry.merge_from_bytes(&value)?; entries.push(entry); } keys::RAFT_STATE_SUFFIX => { let mut state = RaftLocalState::default(); state.merge_from_bytes(&value)?; batch.put_raft_state(region_id, &state).unwrap(); // Assume that we always scan entry first and raft state at the end. batch .append(region_id, std::mem::take(&mut entries)) .unwrap(); } _ => unreachable!("There is only 2 types of keys in raft"), } // Avoid long log batch. if local_size >= BATCH_THRESHOLD { local_size = 0; batch .append(region_id, std::mem::take(&mut entries)) .unwrap(); let size = new_engine.consume(&mut batch, false).unwrap(); count_size.fetch_add(size, Ordering::Relaxed); } Ok(true) } } }, ) .unwrap(); } let size = new_engine.consume(&mut batch, false).unwrap(); count_size.fetch_add(size, Ordering::Relaxed); } pub fn check_and_dump_raft_engine(config: &TiKvConfig, engine: &RocksEngine, thread_num: usize) { let raft_engine_config = config.raft_engine.config(); let raft_engine_path = &raft_engine_config.dir; let dirty_raft_engine_path = get_path_for_remove(raft_engine_path); if!RaftLogEngine::exists(raft_engine_path) { remove_tmp_dir(&dirty_raft_engine_path); return; } // Clean the target engine if it exists. clear_raft_db(engine).expect("clear_raft_db"); let src_engine = RaftLogEngine::new(raft_engine_config.clone()); let count_size = Arc::new(AtomicUsize::new(0)); let mut count_region = 0; let mut threads = vec![]; let (tx, rx) = unbounded(); for _ in 0..thread_num { let src_engine = src_engine.clone(); let dst_engine = engine.clone(); let count_size = count_size.clone(); let rx = rx.clone(); let t = std::thread::spawn(move || { run_dump_raft_engine_worker(&rx, &src_engine, &dst_engine, &count_size); }); threads.push(t); } info!("Start to scan raft log from RaftLogEngine and dump into RocksEngine"); let consumed_time = std::time::Instant::now(); // Seek all region id from RaftLogEngine and send them to workers. for id in src_engine.raft_groups() { tx.send(id).unwrap(); count_region += 1; } drop(tx); info!("Scanned all region id and waiting for dump"); for t in threads { t.join().unwrap(); } engine.sync().unwrap(); info!( "Finished dump, total regions: {}; Total bytes: {}; Consumed time: {:?}", count_region, count_size.load(Ordering::Relaxed), consumed_time.elapsed(), ); rename_to_tmp_dir(&raft_engine_path, &dirty_raft_engine_path); remove_tmp_dir(&dirty_raft_engine_path); } fn run_dump_raft_engine_worker( rx: &Receiver<u64>, old_engine: &RaftLogEngine, new_engine: &RocksEngine, count_size: &Arc<AtomicUsize>, ) { while let Ok(id) = rx.recv() { let state = old_engine.get_raft_state(id).unwrap().unwrap(); new_engine.put_raft_state(id, &state).unwrap(); if let Some(last_index) = old_engine.last_index(id) { let mut batch = new_engine.log_batch(0); let mut begin = old_engine.first_index(id).unwrap(); while begin <= last_index { let end = cmp::min(begin + 1024, last_index + 1); let mut entries = Vec::with_capacity((end - begin) as usize); begin += old_engine .fetch_entries_to(id, begin, end, Some(BATCH_THRESHOLD), &mut entries) .unwrap() as u64; batch.append(id, entries).unwrap(); let size = new_engine.consume(&mut batch, false).unwrap(); count_size.fetch_add(size, Ordering::Relaxed); } } } } #[cfg(test)] mod tests { use super::*; use engine_rocks::raw::DBOptions; fn do_test_switch(custom_raft_db_wal: bool, continue_on_aborted: bool) { let data_path = tempfile::Builder::new().tempdir().unwrap().into_path(); let mut raftdb_path = data_path.clone(); let mut raft_engine_path = data_path; let mut raftdb_wal_path = raftdb_path.clone(); raftdb_path.push("raft"); raft_engine_path.push("raft-engine"); if custom_raft_db_wal { raftdb_wal_path.push("test-wal"); } let mut cfg = TiKvConfig::default(); cfg.raft_store.raftdb_path = raftdb_path.to_str().unwrap().to_owned(); cfg.raftdb.wal_dir = raftdb_wal_path.to_str().unwrap().to_owned(); cfg.raft_engine.mut_config().dir = raft_engine_path.to_str().unwrap().to_owned(); // Prepare some data for the RocksEngine. { let db = engine_rocks::raw_util::new_engine_opt( &cfg.raft_store.raftdb_path, cfg.raftdb.build_opt(), cfg.raftdb.build_cf_opts(&None), ) .unwrap(); let engine = RocksEngine::from_db(Arc::new(db)); let mut batch = engine.log_batch(0); set_write_batch(1, &mut batch); engine.consume(&mut batch, false).unwrap(); set_write_batch(5, &mut batch); engine.consume(&mut batch, false).unwrap(); set_write_batch(15, &mut batch); engine.consume(&mut batch, false).unwrap(); engine.sync().unwrap(); } // Dump logs from RocksEngine to RaftLogEngine. let raft_engine = RaftLogEngine::new(cfg.raft_engine.config()); if continue_on_aborted { let mut batch = raft_engine.log_batch(0); set_write_batch(25, &mut batch); raft_engine.consume(&mut batch, false).unwrap(); assert(25, &raft_engine); } check_and_dump_raft_db(&cfg, &raft_engine, &Arc::new(Env::default()), 4); assert(1, &raft_engine); assert(5, &raft_engine); assert(15, &raft_engine); assert_no(25, &raft_engine); drop(raft_engine); // Dump logs from RaftLogEngine to RocksEngine. let rocks_engine = { let db = engine_rocks::raw_util::new_engine_opt( &cfg.raft_store.raftdb_path, DBOptions::new(), vec![], ) .unwrap(); RocksEngine::from_db(Arc::new(db)) }; if continue_on_aborted { let mut batch = rocks_engine.log_batch(0); set_write_batch(25, &mut batch); rocks_engine.consume(&mut batch, false).unwrap(); assert(25, &rocks_engine); } check_and_dump_raft_engine(&cfg, &rocks_engine, 4); assert(1, &rocks_engine); assert(5, &rocks_engine); assert(15, &rocks_engine); assert_no(25, &rocks_engine); } #[test] fn test_switch() { do_test_switch(false, false); } #[test] fn test_switch_with_seperate_wal() { do_test_switch(true, false); } #[test] fn test_switch_continue_on_aborted() { do_test_switch(false, true); } // Insert some data into log batch. fn set_write_batch<T: RaftLogBatch>(num: u64, batch: &mut T) { let mut state = RaftLocalState::default(); state.set_last_index(num); batch.put_raft_state(num, &state).unwrap(); let mut entries = vec![]; for i in 0..num { let mut e = Entry::default(); e.set_index(i); entries.push(e); } batch.append(num, entries).unwrap(); } // Get data from raft engine and assert. fn assert<T: RaftEngine>(num: u64, engine: &T) { let state = engine.get_raft_state(num).unwrap().unwrap(); assert_eq!(state.get_last_index(), num); for i in 0..num { assert!(engine.get_entry(num, i).unwrap().is_some()); } } fn assert_no<T: RaftEngine>(num: u64, engine: &T) { assert!(engine.get_raft_state(num).unwrap().is_none()); for i in 0..num { assert!(engine.get_entry(num, i).unwrap().is_none()); } } }
{ remove_tmp_dir(&dirty_raftdb_path); return; }
conditional_block