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
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/. */ //! Servo's compiler plugin/macro crate //! //! Attributes this crate provides: //! //! - `#[derive(DenyPublicFields)]` : Forces all fields in a struct/enum to be private //! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate //! - `#[must_root]` : Prevents data of the marked type from being used on the stack. //! See the lints module for more details //! - `#[dom_struct]` : Implies #[derive(JSTraceable, DenyPublicFields)]`, and `#[must_root]`. //! Use this for structs that correspond to a DOM type #![deny(unsafe_code)] #![feature(plugin)] #![feature(plugin_registrar)] #![feature(rustc_private)] #[macro_use] extern crate rustc; extern crate rustc_plugin;
mod unrooted_must_root; /// Utilities for writing plugins mod utils; #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_late_lint_pass(Box::new(unrooted_must_root::UnrootedPass::new())); reg.register_attribute("allow_unrooted_interior".to_string(), Whitelisted); reg.register_attribute("must_root".to_string(), Whitelisted); }
extern crate syntax; use rustc_plugin::Registry; use syntax::feature_gate::AttributeType::Whitelisted;
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/. */ //! Servo's compiler plugin/macro crate //! //! Attributes this crate provides: //! //! - `#[derive(DenyPublicFields)]` : Forces all fields in a struct/enum to be private //! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate //! - `#[must_root]` : Prevents data of the marked type from being used on the stack. //! See the lints module for more details //! - `#[dom_struct]` : Implies #[derive(JSTraceable, DenyPublicFields)]`, and `#[must_root]`. //! Use this for structs that correspond to a DOM type #![deny(unsafe_code)] #![feature(plugin)] #![feature(plugin_registrar)] #![feature(rustc_private)] #[macro_use] extern crate rustc; extern crate rustc_plugin; extern crate syntax; use rustc_plugin::Registry; use syntax::feature_gate::AttributeType::Whitelisted; mod unrooted_must_root; /// Utilities for writing plugins mod utils; #[plugin_registrar] pub fn
(reg: &mut Registry) { reg.register_late_lint_pass(Box::new(unrooted_must_root::UnrootedPass::new())); reg.register_attribute("allow_unrooted_interior".to_string(), Whitelisted); reg.register_attribute("must_root".to_string(), Whitelisted); }
plugin_registrar
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 super::Constraint; use middle::infer::SubregionOrigin; use middle::infer::region_inference::RegionVarBindings; use util::nodemap::{FnvHashMap, FnvHashSet}; use util::ppaux::Repr; use std::collections::hash_map::Entry::Vacant; use std::io::{self, File}; use std::os; 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> = os::getenv("RUST_REGION_GRAPH_NODE").and_then(|s| s.parse()); if requested_node.is_some() && requested_node!= Some(subject_node) { return; } let requested_output = os::getenv("RUST_REGION_GRAPH"); debug!("requested_output: {:?} requested_node: {:?}", requested_output, requested_node); let output_path = { let output_template = match requested_output { Some(ref s) if s.as_slice() == "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().as_slice()); } 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.as_slice()) { Ok(()) => {} Err(e) => { let msg = format!("io error dumping region constraints: {}", e); region_vars.tcx.sess.err(msg.as_slice()) } } } 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, Show)] enum Node { RegionVid(ty::RegionVid), Region(ty::Region), } type Edge = Constraint; 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::new(); { let mut add_node = |&mut : 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); } } 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.as_slice()).unwrap() } fn node_id(&self, n: &Node) -> dot::Id { dot::Id::new(format!("node_{}", self.node_ids.get(n).unwrap())).unwrap() } 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 { dot::LabelText::label(format!("{}", self.map.get(e).unwrap().repr(self.tcx))) } } 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)), } } impl<'a, 'tcx> dot::GraphWalk<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { fn nodes(&self) -> dot::Nodes<Node> { let mut set = FnvHashSet::new(); for constraint in self.map.keys() { let (n1, n2) = constraint_to_nodes(constraint); set.insert(n1); set.insert(n2); } debug!("constraint graph has {} nodes", set.len()); set.into_iter().collect() } fn
(&self) -> dot::Edges<Edge> { debug!("constraint graph has {} edges", self.map.len()); self.map.keys().map(|e|*e).collect() } fn source(&self, edge: &Edge) -> Node { let (n1, _) = constraint_to_nodes(edge); debug!("edge {:?} has source {:?}", edge, n1); n1 } fn target(&self, edge: &Edge) -> Node { let (_, n2) = constraint_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) -> 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) }
edges
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 super::Constraint; use middle::infer::SubregionOrigin; use middle::infer::region_inference::RegionVarBindings; use util::nodemap::{FnvHashMap, FnvHashSet}; use util::ppaux::Repr; use std::collections::hash_map::Entry::Vacant; use std::io::{self, File}; use std::os; 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> = os::getenv("RUST_REGION_GRAPH_NODE").and_then(|s| s.parse()); if requested_node.is_some() && requested_node!= Some(subject_node) { return; } let requested_output = os::getenv("RUST_REGION_GRAPH"); debug!("requested_output: {:?} requested_node: {:?}", requested_output, requested_node); let output_path = { let output_template = match requested_output { Some(ref s) if s.as_slice() == "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().as_slice()); } 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.as_slice()) { Ok(()) =>
Err(e) => { let msg = format!("io error dumping region constraints: {}", e); region_vars.tcx.sess.err(msg.as_slice()) } } } 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, Show)] enum Node { RegionVid(ty::RegionVid), Region(ty::Region), } type Edge = Constraint; 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::new(); { let mut add_node = |&mut : 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); } } 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.as_slice()).unwrap() } fn node_id(&self, n: &Node) -> dot::Id { dot::Id::new(format!("node_{}", self.node_ids.get(n).unwrap())).unwrap() } 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 { dot::LabelText::label(format!("{}", self.map.get(e).unwrap().repr(self.tcx))) } } 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)), } } impl<'a, 'tcx> dot::GraphWalk<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { fn nodes(&self) -> dot::Nodes<Node> { let mut set = FnvHashSet::new(); for constraint in self.map.keys() { let (n1, n2) = constraint_to_nodes(constraint); set.insert(n1); set.insert(n2); } 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()); self.map.keys().map(|e|*e).collect() } fn source(&self, edge: &Edge) -> Node { let (n1, _) = constraint_to_nodes(edge); debug!("edge {:?} has source {:?}", edge, n1); n1 } fn target(&self, edge: &Edge) -> Node { let (_, n2) = constraint_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) -> 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) }
{}
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 super::Constraint; use middle::infer::SubregionOrigin; use middle::infer::region_inference::RegionVarBindings; use util::nodemap::{FnvHashMap, FnvHashSet}; use util::ppaux::Repr; use std::collections::hash_map::Entry::Vacant; use std::io::{self, File}; use std::os; 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> = os::getenv("RUST_REGION_GRAPH_NODE").and_then(|s| s.parse()); if requested_node.is_some() && requested_node!= Some(subject_node) { return; } let requested_output = os::getenv("RUST_REGION_GRAPH"); debug!("requested_output: {:?} requested_node: {:?}", requested_output, requested_node); let output_path = { let output_template = match requested_output { Some(ref s) if s.as_slice() == "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().as_slice()); } 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.as_slice()) { Ok(()) => {} Err(e) => { let msg = format!("io error dumping region constraints: {}", e); region_vars.tcx.sess.err(msg.as_slice()) } } } 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, Show)] enum Node { RegionVid(ty::RegionVid), Region(ty::Region), } type Edge = Constraint; 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::new(); { let mut add_node = |&mut : 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); } } 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.as_slice()).unwrap() } fn node_id(&self, n: &Node) -> dot::Id { dot::Id::new(format!("node_{}", self.node_ids.get(n).unwrap())).unwrap() } 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 { dot::LabelText::label(format!("{}", self.map.get(e).unwrap().repr(self.tcx))) } } 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)), } } impl<'a, 'tcx> dot::GraphWalk<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { fn nodes(&self) -> dot::Nodes<Node> { let mut set = FnvHashSet::new(); for constraint in self.map.keys() { let (n1, n2) = constraint_to_nodes(constraint); set.insert(n1); set.insert(n2); } 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()); self.map.keys().map(|e|*e).collect() } fn source(&self, edge: &Edge) -> Node { let (n1, _) = constraint_to_nodes(edge); debug!("edge {:?} has source {:?}", edge, n1); n1 } fn target(&self, edge: &Edge) -> Node { let (_, n2) = constraint_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) -> 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) }
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 super::Constraint; use middle::infer::SubregionOrigin; use middle::infer::region_inference::RegionVarBindings; use util::nodemap::{FnvHashMap, FnvHashSet}; use util::ppaux::Repr; use std::collections::hash_map::Entry::Vacant; use std::io::{self, File}; use std::os; 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> = os::getenv("RUST_REGION_GRAPH_NODE").and_then(|s| s.parse()); if requested_node.is_some() && requested_node!= Some(subject_node) { return; } let requested_output = os::getenv("RUST_REGION_GRAPH"); debug!("requested_output: {:?} requested_node: {:?}", requested_output, requested_node); let output_path = { let output_template = match requested_output { Some(ref s) if s.as_slice() == "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().as_slice()); } 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.as_slice()) { Ok(()) => {} Err(e) => { let msg = format!("io error dumping region constraints: {}", e); region_vars.tcx.sess.err(msg.as_slice()) } } } 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, Show)] enum Node { RegionVid(ty::RegionVid), Region(ty::Region), } type Edge = Constraint; 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::new(); { let mut add_node = |&mut : 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); } } 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.as_slice()).unwrap() } fn node_id(&self, n: &Node) -> dot::Id { dot::Id::new(format!("node_{}", self.node_ids.get(n).unwrap())).unwrap() } 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 { dot::LabelText::label(format!("{}", self.map.get(e).unwrap().repr(self.tcx))) } } 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)), } } impl<'a, 'tcx> dot::GraphWalk<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { fn nodes(&self) -> dot::Nodes<Node> { let mut set = FnvHashSet::new(); for constraint in self.map.keys() { let (n1, n2) = constraint_to_nodes(constraint); set.insert(n1); set.insert(n2); } 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()); self.map.keys().map(|e|*e).collect() } fn source(&self, edge: &Edge) -> Node { let (n1, _) = constraint_to_nodes(edge); debug!("edge {:?} has source {:?}", edge, n1); n1 } fn target(&self, edge: &Edge) -> Node
} 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) -> 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) }
{ let (_, n2) = constraint_to_nodes(edge); debug!("edge {:?} has target {:?}", edge, n2); n2 }
identifier_body
color.rs
// SPDX-License-Identifier: MIT use core::fmt; /// A color #[derive(Copy, Clone)] #[repr(transparent)] pub struct Color { pub data: u32, } impl Color { /// Create a new color from RGB pub const fn rgb(r: u8, g: u8, b: u8) -> Self { Color { #[cfg(not(target_arch = "wasm32"))] data: 0xFF000000 | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32), #[cfg(target_arch = "wasm32")] data: 0xFF000000 | ((b as u32) << 16) | ((g as u32) << 8) | (r as u32), } } /// Set the alpha pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self { Color { #[cfg(not(target_arch = "wasm32"))] data: ((a as u32) << 24) | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32), #[cfg(target_arch = "wasm32")] data: ((a as u32) << 24) | ((b as u32) << 16) | ((g as u32) << 8) | (r as u32), } } /// Get the r value #[cfg(not(target_arch = "wasm32"))] pub fn r(&self) -> u8 { ((self.data & 0x00FF0000) >> 16) as u8 } /// Get the r value #[cfg(target_arch = "wasm32")] pub fn r(&self) -> u8 { (self.data & 0x000000FF) as u8 } /// Get the g value pub fn g(&self) -> u8 { ((self.data & 0x0000FF00) >> 8) as u8 } /// Get the b value #[cfg(not(target_arch = "wasm32"))] pub fn b(&self) -> u8 { (self.data & 0x000000FF) as u8 } #[cfg(target_arch = "wasm32")] pub fn b(&self) -> u8 { ((self.data & 0x00FF0000) >> 16) as u8 } /// Get the alpha value pub fn a(&self) -> u8 { ((self.data & 0xFF000000) >> 24) as u8 } /// Interpolate between two colors pub fn
(start_color: Color, end_color: Color, scale: f64) -> Color { let r = Color::interp(start_color.r(), end_color.r(), scale); let g = Color::interp(start_color.g(), end_color.g(), scale); let b = Color::interp(start_color.b(), end_color.b(), scale); let a = Color::interp(start_color.a(), end_color.a(), scale); Color::rgba(r, g, b, a) } fn interp(start_color: u8, end_color: u8, scale: f64) -> u8 { ((end_color as f64 - start_color as f64) * scale + start_color as f64) as u8 } } /// Compare two colors (Do not take care of alpha) impl PartialEq for Color { fn eq(&self, other: &Color) -> bool { self.r() == other.r() && self.g() == other.g() && self.b() == other.b() } } impl fmt::Debug for Color { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{:#010X}", { self.data }) } } #[cfg(test)] mod tests { use super::*; #[test] fn partial_eq() { assert_eq!(Color::rgb(1, 2, 3), Color::rgba(1, 2, 3, 200)); assert_ne!(Color::rgb(1, 2, 3), Color::rgba(11, 2, 3, 200)); assert_eq!(Color::rgba(1, 2, 3, 200), Color::rgba(1, 2, 3, 200)); } #[test] fn alignment() { assert_eq!(4, core::mem::size_of::<Color>()); assert_eq!(8, core::mem::size_of::<[Color; 2]>()); assert_eq!(12, core::mem::size_of::<[Color; 3]>()); assert_eq!(16, core::mem::size_of::<[Color; 4]>()); assert_eq!(20, core::mem::size_of::<[Color; 5]>()); } }
interpolate
identifier_name
color.rs
// SPDX-License-Identifier: MIT use core::fmt; /// A color #[derive(Copy, Clone)] #[repr(transparent)] pub struct Color { pub data: u32, } impl Color { /// Create a new color from RGB pub const fn rgb(r: u8, g: u8, b: u8) -> Self { Color { #[cfg(not(target_arch = "wasm32"))] data: 0xFF000000 | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32), #[cfg(target_arch = "wasm32")] data: 0xFF000000 | ((b as u32) << 16) | ((g as u32) << 8) | (r as u32), } } /// Set the alpha pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self { Color { #[cfg(not(target_arch = "wasm32"))] data: ((a as u32) << 24) | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32), #[cfg(target_arch = "wasm32")] data: ((a as u32) << 24) | ((b as u32) << 16) | ((g as u32) << 8) | (r as u32), } } /// Get the r value #[cfg(not(target_arch = "wasm32"))] pub fn r(&self) -> u8 { ((self.data & 0x00FF0000) >> 16) as u8 } /// Get the r value #[cfg(target_arch = "wasm32")] pub fn r(&self) -> u8 { (self.data & 0x000000FF) as u8 } /// Get the g value pub fn g(&self) -> u8 { ((self.data & 0x0000FF00) >> 8) as u8 } /// Get the b value #[cfg(not(target_arch = "wasm32"))] pub fn b(&self) -> u8 { (self.data & 0x000000FF) as u8 } #[cfg(target_arch = "wasm32")] pub fn b(&self) -> u8 { ((self.data & 0x00FF0000) >> 16) as u8 } /// Get the alpha value pub fn a(&self) -> u8 { ((self.data & 0xFF000000) >> 24) as u8 } /// Interpolate between two colors pub fn interpolate(start_color: Color, end_color: Color, scale: f64) -> Color { let r = Color::interp(start_color.r(), end_color.r(), scale); let g = Color::interp(start_color.g(), end_color.g(), scale); let b = Color::interp(start_color.b(), end_color.b(), scale); let a = Color::interp(start_color.a(), end_color.a(), scale); Color::rgba(r, g, b, a) } fn interp(start_color: u8, end_color: u8, scale: f64) -> u8 { ((end_color as f64 - start_color as f64) * scale + start_color as f64) as u8 } } /// Compare two colors (Do not take care of alpha) impl PartialEq for Color { fn eq(&self, other: &Color) -> bool { self.r() == other.r() && self.g() == other.g() && self.b() == other.b() } } impl fmt::Debug for Color { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{:#010X}", { self.data }) } } #[cfg(test)] mod tests { use super::*; #[test] fn partial_eq()
#[test] fn alignment() { assert_eq!(4, core::mem::size_of::<Color>()); assert_eq!(8, core::mem::size_of::<[Color; 2]>()); assert_eq!(12, core::mem::size_of::<[Color; 3]>()); assert_eq!(16, core::mem::size_of::<[Color; 4]>()); assert_eq!(20, core::mem::size_of::<[Color; 5]>()); } }
{ assert_eq!(Color::rgb(1, 2, 3), Color::rgba(1, 2, 3, 200)); assert_ne!(Color::rgb(1, 2, 3), Color::rgba(11, 2, 3, 200)); assert_eq!(Color::rgba(1, 2, 3, 200), Color::rgba(1, 2, 3, 200)); }
identifier_body
color.rs
// SPDX-License-Identifier: MIT use core::fmt; /// A color #[derive(Copy, Clone)] #[repr(transparent)] pub struct Color { pub data: u32, } impl Color { /// Create a new color from RGB pub const fn rgb(r: u8, g: u8, b: u8) -> Self { Color { #[cfg(not(target_arch = "wasm32"))] data: 0xFF000000 | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32), #[cfg(target_arch = "wasm32")] data: 0xFF000000 | ((b as u32) << 16) | ((g as u32) << 8) | (r as u32), } } /// Set the alpha pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self { Color { #[cfg(not(target_arch = "wasm32"))] data: ((a as u32) << 24) | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32), #[cfg(target_arch = "wasm32")] data: ((a as u32) << 24) | ((b as u32) << 16) | ((g as u32) << 8) | (r as u32), } } /// Get the r value #[cfg(not(target_arch = "wasm32"))] pub fn r(&self) -> u8 { ((self.data & 0x00FF0000) >> 16) as u8 } /// Get the r value #[cfg(target_arch = "wasm32")] pub fn r(&self) -> u8 { (self.data & 0x000000FF) as u8 } /// Get the g value pub fn g(&self) -> u8 { ((self.data & 0x0000FF00) >> 8) as u8 } /// Get the b value #[cfg(not(target_arch = "wasm32"))] pub fn b(&self) -> u8 { (self.data & 0x000000FF) as u8 } #[cfg(target_arch = "wasm32")] pub fn b(&self) -> u8 { ((self.data & 0x00FF0000) >> 16) as u8 } /// Get the alpha value pub fn a(&self) -> u8 { ((self.data & 0xFF000000) >> 24) as u8 } /// Interpolate between two colors pub fn interpolate(start_color: Color, end_color: Color, scale: f64) -> Color { let r = Color::interp(start_color.r(), end_color.r(), scale);
} fn interp(start_color: u8, end_color: u8, scale: f64) -> u8 { ((end_color as f64 - start_color as f64) * scale + start_color as f64) as u8 } } /// Compare two colors (Do not take care of alpha) impl PartialEq for Color { fn eq(&self, other: &Color) -> bool { self.r() == other.r() && self.g() == other.g() && self.b() == other.b() } } impl fmt::Debug for Color { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{:#010X}", { self.data }) } } #[cfg(test)] mod tests { use super::*; #[test] fn partial_eq() { assert_eq!(Color::rgb(1, 2, 3), Color::rgba(1, 2, 3, 200)); assert_ne!(Color::rgb(1, 2, 3), Color::rgba(11, 2, 3, 200)); assert_eq!(Color::rgba(1, 2, 3, 200), Color::rgba(1, 2, 3, 200)); } #[test] fn alignment() { assert_eq!(4, core::mem::size_of::<Color>()); assert_eq!(8, core::mem::size_of::<[Color; 2]>()); assert_eq!(12, core::mem::size_of::<[Color; 3]>()); assert_eq!(16, core::mem::size_of::<[Color; 4]>()); assert_eq!(20, core::mem::size_of::<[Color; 5]>()); } }
let g = Color::interp(start_color.g(), end_color.g(), scale); let b = Color::interp(start_color.b(), end_color.b(), scale); let a = Color::interp(start_color.a(), end_color.a(), scale); Color::rgba(r, g, b, a)
random_line_split
build.rs
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. fn main() { #[cfg(feature = "powerd")] { extern crate protoc_rust; use std::env; use std::fmt::Write as FmtWrite; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; fn paths_to_strs<P: AsRef<Path>>(paths: &[P]) -> Vec<&str>
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); let proto_root = match env::var("SYSROOT") { Ok(dir) => PathBuf::from(dir).join("usr/include/chromeos"), // Make this work when typing "cargo build" in platform/crosvm/power_monitor Err(_) => PathBuf::from("../../../platform2/system_api"), }; let power_manager_dir = proto_root.join("dbus/power_manager"); let input_files = [power_manager_dir.join("power_supply_properties.proto")]; let include_dirs = [power_manager_dir]; protoc_rust::Codegen::new() .inputs(&paths_to_strs(&input_files)) .includes(&paths_to_strs(&include_dirs)) .out_dir(out_dir.as_os_str().to_str().unwrap()) .run() .expect("protoc"); let mut path_include_mods = String::new(); for input_file in input_files.iter() { let stem = input_file.file_stem().unwrap().to_str().unwrap(); let mod_path = out_dir.join(format!("{}.rs", stem)); writeln!( &mut path_include_mods, "#[path = \"{}\"]", mod_path.display() ) .unwrap(); writeln!(&mut path_include_mods, "pub mod {};", stem).unwrap(); } let mut mod_out = fs::File::create(out_dir.join("powerd_proto.rs")).unwrap(); writeln!(mod_out, "pub mod system_api {{\n{}}}", path_include_mods).unwrap(); } }
{ paths .iter() .map(|p| p.as_ref().as_os_str().to_str().unwrap()) .collect() }
identifier_body
build.rs
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. fn main() { #[cfg(feature = "powerd")] { extern crate protoc_rust; use std::env; use std::fmt::Write as FmtWrite; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; fn
<P: AsRef<Path>>(paths: &[P]) -> Vec<&str> { paths .iter() .map(|p| p.as_ref().as_os_str().to_str().unwrap()) .collect() } let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); let proto_root = match env::var("SYSROOT") { Ok(dir) => PathBuf::from(dir).join("usr/include/chromeos"), // Make this work when typing "cargo build" in platform/crosvm/power_monitor Err(_) => PathBuf::from("../../../platform2/system_api"), }; let power_manager_dir = proto_root.join("dbus/power_manager"); let input_files = [power_manager_dir.join("power_supply_properties.proto")]; let include_dirs = [power_manager_dir]; protoc_rust::Codegen::new() .inputs(&paths_to_strs(&input_files)) .includes(&paths_to_strs(&include_dirs)) .out_dir(out_dir.as_os_str().to_str().unwrap()) .run() .expect("protoc"); let mut path_include_mods = String::new(); for input_file in input_files.iter() { let stem = input_file.file_stem().unwrap().to_str().unwrap(); let mod_path = out_dir.join(format!("{}.rs", stem)); writeln!( &mut path_include_mods, "#[path = \"{}\"]", mod_path.display() ) .unwrap(); writeln!(&mut path_include_mods, "pub mod {};", stem).unwrap(); } let mut mod_out = fs::File::create(out_dir.join("powerd_proto.rs")).unwrap(); writeln!(mod_out, "pub mod system_api {{\n{}}}", path_include_mods).unwrap(); } }
paths_to_strs
identifier_name
build.rs
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file.
{ extern crate protoc_rust; use std::env; use std::fmt::Write as FmtWrite; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; fn paths_to_strs<P: AsRef<Path>>(paths: &[P]) -> Vec<&str> { paths .iter() .map(|p| p.as_ref().as_os_str().to_str().unwrap()) .collect() } let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); let proto_root = match env::var("SYSROOT") { Ok(dir) => PathBuf::from(dir).join("usr/include/chromeos"), // Make this work when typing "cargo build" in platform/crosvm/power_monitor Err(_) => PathBuf::from("../../../platform2/system_api"), }; let power_manager_dir = proto_root.join("dbus/power_manager"); let input_files = [power_manager_dir.join("power_supply_properties.proto")]; let include_dirs = [power_manager_dir]; protoc_rust::Codegen::new() .inputs(&paths_to_strs(&input_files)) .includes(&paths_to_strs(&include_dirs)) .out_dir(out_dir.as_os_str().to_str().unwrap()) .run() .expect("protoc"); let mut path_include_mods = String::new(); for input_file in input_files.iter() { let stem = input_file.file_stem().unwrap().to_str().unwrap(); let mod_path = out_dir.join(format!("{}.rs", stem)); writeln!( &mut path_include_mods, "#[path = \"{}\"]", mod_path.display() ) .unwrap(); writeln!(&mut path_include_mods, "pub mod {};", stem).unwrap(); } let mut mod_out = fs::File::create(out_dir.join("powerd_proto.rs")).unwrap(); writeln!(mod_out, "pub mod system_api {{\n{}}}", path_include_mods).unwrap(); } }
fn main() { #[cfg(feature = "powerd")]
random_line_split
method.rs
struct Circle { x: f64, y: f64, radius: f64, } impl Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } fn reference(&self) { println!("taking self by reference!"); } fn mutable_reference(&mut self) { println!("taking self by mutable reference!"); } fn takes_ownership(self) { println!("taking ownership of self!"); } fn grow(&self, increment: f64) -> Circle { Circle { x: self.x, y: self.y, radius: self.radius + increment } } // Ассоциированная функция. Не имеет параметра self, // вызывается через :: // В других языках это "статичная" функция fn new(x: f64, y: f64, radius: f64) -> Circle { Circle { x: x, y: y, radius: radius, } } } fn main() { let c = Circle { x: 0.0, y: 0.0, radius: 2.0 }; println!("{}", c.area()); let d = c.grow(2.0).area(); println!("{}", d);
let c = Circle::new(0.0, 0.0, 2.0); }
random_line_split
method.rs
struct Circle { x: f64, y: f64, radius: f64, } impl Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } fn reference(&self) { println!("taking self by reference!"); } fn mutable_reference(&mut self) { println!("taking self by mutable reference!"); } fn takes_ownership(self) { println!("taking ownership of self!"); } fn grow(&self, increment: f64) -> Circle
// Ассоциированная функция. Не имеет параметра self, // вызывается через :: // В других языках это "статичная" функция fn new(x: f64, y: f64, radius: f64) -> Circle { Circle { x: x, y: y, radius: radius, } } } fn main() { let c = Circle { x: 0.0, y: 0.0, radius: 2.0 }; println!("{}", c.area()); let d = c.grow(2.0).area(); println!("{}", d); let c = Circle::new(0.0, 0.0, 2.0); }
{ Circle { x: self.x, y: self.y, radius: self.radius + increment } }
identifier_body
method.rs
struct Circle { x: f64, y: f64, radius: f64, } impl Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } fn reference(&self) { println!("taking self by reference!"); } fn mutable_reference(&mut self) { println!("taking self by mutable reference!"); } fn takes_ownership(self) { println!("taking ownership of self!"); } fn grow(&self, increment: f64) -> Circle { Circle { x: self.x, y: self.y, radius: self.radius + increment } } // Ассоциированная функция. Не имеет параметра self, // вызывается через :: // В других языках это "статичная" функция fn new(x: f64, y: f64, radius: f64) -> Circle { Circle { x: x, y: y, radius: radius, } } } fn main() { let c = Circle { x: 0.0, y: 0.0, radius: 2.0 }; println!("{}", c.a
)); let d = c.grow(2.0).area(); println!("{}", d); let c = Circle::new(0.0, 0.0, 2.0); }
rea(
identifier_name
lib.rs
extern crate cgmath; #[macro_use] extern crate puck_core; extern crate alto; extern crate lewton; extern crate time; extern crate notify; extern crate rand; extern crate image; #[macro_use] extern crate gfx; extern crate gfx_device_gl; extern crate gfx_window_glutin; extern crate glutin; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate multimap; pub mod audio; pub mod render; pub mod app; pub mod input; pub mod dimensions; pub mod camera; pub mod resources; pub use input::*; pub use camera::*; pub use dimensions::*; pub use resources::*; use std::io; use std::path::PathBuf; pub type PuckResult<T> = Result<T, PuckError>; #[derive(Debug)] pub enum PuckError { IO(io::Error), FileDoesntExist(PathBuf), PipelineError(gfx::PipelineStateError<String>), CombinedGFXError(gfx::CombinedError), ContextError(glutin::ContextError), NoTexture(), NoPipeline(), BufferCreationError(gfx::buffer::CreationError), TextureCreationError(gfx::texture::CreationError), ResourceViewError(gfx::ResourceViewError), // FontLoadError(FontLoadError), ImageError(image::ImageError), MustLoadTextureBeforeFont, NoFiles, MismatchingDimensions, // path buf, expectation RenderingPipelineIncomplete, } impl From<image::ImageError> for PuckError { fn from(err: image::ImageError) -> Self { PuckError::ImageError(err) }
fn from(val: io::Error) -> PuckError { PuckError::IO(val) } } #[derive(Copy, Clone)] pub struct RenderTick { pub n: u64, pub accu_alpha: f64, // percentage of a frame that has accumulated pub tick_rate: u64, // per second }
} impl From<io::Error> for PuckError {
random_line_split
lib.rs
extern crate cgmath; #[macro_use] extern crate puck_core; extern crate alto; extern crate lewton; extern crate time; extern crate notify; extern crate rand; extern crate image; #[macro_use] extern crate gfx; extern crate gfx_device_gl; extern crate gfx_window_glutin; extern crate glutin; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate multimap; pub mod audio; pub mod render; pub mod app; pub mod input; pub mod dimensions; pub mod camera; pub mod resources; pub use input::*; pub use camera::*; pub use dimensions::*; pub use resources::*; use std::io; use std::path::PathBuf; pub type PuckResult<T> = Result<T, PuckError>; #[derive(Debug)] pub enum PuckError { IO(io::Error), FileDoesntExist(PathBuf), PipelineError(gfx::PipelineStateError<String>), CombinedGFXError(gfx::CombinedError), ContextError(glutin::ContextError), NoTexture(), NoPipeline(), BufferCreationError(gfx::buffer::CreationError), TextureCreationError(gfx::texture::CreationError), ResourceViewError(gfx::ResourceViewError), // FontLoadError(FontLoadError), ImageError(image::ImageError), MustLoadTextureBeforeFont, NoFiles, MismatchingDimensions, // path buf, expectation RenderingPipelineIncomplete, } impl From<image::ImageError> for PuckError { fn from(err: image::ImageError) -> Self { PuckError::ImageError(err) } } impl From<io::Error> for PuckError { fn from(val: io::Error) -> PuckError { PuckError::IO(val) } } #[derive(Copy, Clone)] pub struct
{ pub n: u64, pub accu_alpha: f64, // percentage of a frame that has accumulated pub tick_rate: u64, // per second }
RenderTick
identifier_name
tac.rs
#![crate_name = "uu_tac"] /* * This file is part of the uutils coreutils package. * * (c) Alex Lyon <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uucore; use std::fs::File; use std::io::{stdin, stdout, BufReader, Read, Stdout, Write}; static NAME: &'static str = "tac"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag( "b", "before", "attach the separator before instead of after", ); opts.optflag( "r", "regex", "interpret the sequence as a regular expression (NOT IMPLEMENTED)", ); opts.optopt( "s", "separator", "use STRING as the separator instead of newline", "STRING",
Ok(m) => m, Err(f) => crash!(1, "{}", f), }; if matches.opt_present("help") { let msg = format!( "{0} {1} Usage: {0} [OPTION]... [FILE]... Write each file to standard output, last line first.", NAME, VERSION ); print!("{}", opts.usage(&msg)); } else if matches.opt_present("version") { println!("{} {}", NAME, VERSION); } else { let before = matches.opt_present("b"); let regex = matches.opt_present("r"); let separator = match matches.opt_str("s") { Some(m) => { if m.is_empty() { crash!(1, "separator cannot be empty") } else { m } } None => "\n".to_owned(), }; let files = if matches.free.is_empty() { vec!["-".to_owned()] } else { matches.free }; tac(files, before, regex, &separator[..]); } 0 } fn tac(filenames: Vec<String>, before: bool, _: bool, separator: &str) { let mut out = stdout(); let sbytes = separator.as_bytes(); let slen = sbytes.len(); for filename in &filenames { let mut file = BufReader::new(if filename == "-" { Box::new(stdin()) as Box<Read> } else { match File::open(filename) { Ok(f) => Box::new(f) as Box<Read>, Err(e) => { show_warning!("failed to open '{}' for reading: {}", filename, e); continue; } } }); let mut data = Vec::new(); match file.read_to_end(&mut data) { Err(e) => { show_warning!("failed to read '{}': {}", filename, e); continue; } Ok(_) => (), }; // find offsets in string of all separators let mut offsets = Vec::new(); let mut i = 0; loop { if i + slen > data.len() { break; } if &data[i..i + slen] == sbytes { offsets.push(i); i += slen; } else { i += 1; } } drop(i); // if there isn't a separator at the end of the file, fake it if offsets.is_empty() || *offsets.last().unwrap() < data.len() - slen { offsets.push(data.len()); } let mut prev = *offsets.last().unwrap(); let mut start = true; for off in offsets.iter().rev().skip(1) { // correctly handle case of no final separator in file if start && prev == data.len() { show_line(&mut out, &[], &data[*off + slen..prev], before); start = false; } else { show_line(&mut out, sbytes, &data[*off + slen..prev], before); } prev = *off; } show_line(&mut out, sbytes, &data[0..prev], before); } } fn show_line(out: &mut Stdout, sep: &[u8], dat: &[u8], before: bool) { if before { out.write_all(sep) .unwrap_or_else(|e| crash!(1, "failed to write to stdout: {}", e)); } out.write_all(dat) .unwrap_or_else(|e| crash!(1, "failed to write to stdout: {}", e)); if!before { out.write_all(sep) .unwrap_or_else(|e| crash!(1, "failed to write to stdout: {}", e)); } }
); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) {
random_line_split
tac.rs
#![crate_name = "uu_tac"] /* * This file is part of the uutils coreutils package. * * (c) Alex Lyon <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uucore; use std::fs::File; use std::io::{stdin, stdout, BufReader, Read, Stdout, Write}; static NAME: &'static str = "tac"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn
(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag( "b", "before", "attach the separator before instead of after", ); opts.optflag( "r", "regex", "interpret the sequence as a regular expression (NOT IMPLEMENTED)", ); opts.optopt( "s", "separator", "use STRING as the separator instead of newline", "STRING", ); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => crash!(1, "{}", f), }; if matches.opt_present("help") { let msg = format!( "{0} {1} Usage: {0} [OPTION]... [FILE]... Write each file to standard output, last line first.", NAME, VERSION ); print!("{}", opts.usage(&msg)); } else if matches.opt_present("version") { println!("{} {}", NAME, VERSION); } else { let before = matches.opt_present("b"); let regex = matches.opt_present("r"); let separator = match matches.opt_str("s") { Some(m) => { if m.is_empty() { crash!(1, "separator cannot be empty") } else { m } } None => "\n".to_owned(), }; let files = if matches.free.is_empty() { vec!["-".to_owned()] } else { matches.free }; tac(files, before, regex, &separator[..]); } 0 } fn tac(filenames: Vec<String>, before: bool, _: bool, separator: &str) { let mut out = stdout(); let sbytes = separator.as_bytes(); let slen = sbytes.len(); for filename in &filenames { let mut file = BufReader::new(if filename == "-" { Box::new(stdin()) as Box<Read> } else { match File::open(filename) { Ok(f) => Box::new(f) as Box<Read>, Err(e) => { show_warning!("failed to open '{}' for reading: {}", filename, e); continue; } } }); let mut data = Vec::new(); match file.read_to_end(&mut data) { Err(e) => { show_warning!("failed to read '{}': {}", filename, e); continue; } Ok(_) => (), }; // find offsets in string of all separators let mut offsets = Vec::new(); let mut i = 0; loop { if i + slen > data.len() { break; } if &data[i..i + slen] == sbytes { offsets.push(i); i += slen; } else { i += 1; } } drop(i); // if there isn't a separator at the end of the file, fake it if offsets.is_empty() || *offsets.last().unwrap() < data.len() - slen { offsets.push(data.len()); } let mut prev = *offsets.last().unwrap(); let mut start = true; for off in offsets.iter().rev().skip(1) { // correctly handle case of no final separator in file if start && prev == data.len() { show_line(&mut out, &[], &data[*off + slen..prev], before); start = false; } else { show_line(&mut out, sbytes, &data[*off + slen..prev], before); } prev = *off; } show_line(&mut out, sbytes, &data[0..prev], before); } } fn show_line(out: &mut Stdout, sep: &[u8], dat: &[u8], before: bool) { if before { out.write_all(sep) .unwrap_or_else(|e| crash!(1, "failed to write to stdout: {}", e)); } out.write_all(dat) .unwrap_or_else(|e| crash!(1, "failed to write to stdout: {}", e)); if!before { out.write_all(sep) .unwrap_or_else(|e| crash!(1, "failed to write to stdout: {}", e)); } }
uumain
identifier_name
tac.rs
#![crate_name = "uu_tac"] /* * This file is part of the uutils coreutils package. * * (c) Alex Lyon <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uucore; use std::fs::File; use std::io::{stdin, stdout, BufReader, Read, Stdout, Write}; static NAME: &'static str = "tac"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32
opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => crash!(1, "{}", f), }; if matches.opt_present("help") { let msg = format!( "{0} {1} Usage: {0} [OPTION]... [FILE]... Write each file to standard output, last line first.", NAME, VERSION ); print!("{}", opts.usage(&msg)); } else if matches.opt_present("version") { println!("{} {}", NAME, VERSION); } else { let before = matches.opt_present("b"); let regex = matches.opt_present("r"); let separator = match matches.opt_str("s") { Some(m) => { if m.is_empty() { crash!(1, "separator cannot be empty") } else { m } } None => "\n".to_owned(), }; let files = if matches.free.is_empty() { vec!["-".to_owned()] } else { matches.free }; tac(files, before, regex, &separator[..]); } 0 } fn tac(filenames: Vec<String>, before: bool, _: bool, separator: &str) { let mut out = stdout(); let sbytes = separator.as_bytes(); let slen = sbytes.len(); for filename in &filenames { let mut file = BufReader::new(if filename == "-" { Box::new(stdin()) as Box<Read> } else { match File::open(filename) { Ok(f) => Box::new(f) as Box<Read>, Err(e) => { show_warning!("failed to open '{}' for reading: {}", filename, e); continue; } } }); let mut data = Vec::new(); match file.read_to_end(&mut data) { Err(e) => { show_warning!("failed to read '{}': {}", filename, e); continue; } Ok(_) => (), }; // find offsets in string of all separators let mut offsets = Vec::new(); let mut i = 0; loop { if i + slen > data.len() { break; } if &data[i..i + slen] == sbytes { offsets.push(i); i += slen; } else { i += 1; } } drop(i); // if there isn't a separator at the end of the file, fake it if offsets.is_empty() || *offsets.last().unwrap() < data.len() - slen { offsets.push(data.len()); } let mut prev = *offsets.last().unwrap(); let mut start = true; for off in offsets.iter().rev().skip(1) { // correctly handle case of no final separator in file if start && prev == data.len() { show_line(&mut out, &[], &data[*off + slen..prev], before); start = false; } else { show_line(&mut out, sbytes, &data[*off + slen..prev], before); } prev = *off; } show_line(&mut out, sbytes, &data[0..prev], before); } } fn show_line(out: &mut Stdout, sep: &[u8], dat: &[u8], before: bool) { if before { out.write_all(sep) .unwrap_or_else(|e| crash!(1, "failed to write to stdout: {}", e)); } out.write_all(dat) .unwrap_or_else(|e| crash!(1, "failed to write to stdout: {}", e)); if!before { out.write_all(sep) .unwrap_or_else(|e| crash!(1, "failed to write to stdout: {}", e)); } }
{ let mut opts = getopts::Options::new(); opts.optflag( "b", "before", "attach the separator before instead of after", ); opts.optflag( "r", "regex", "interpret the sequence as a regular expression (NOT IMPLEMENTED)", ); opts.optopt( "s", "separator", "use STRING as the separator instead of newline", "STRING", ); opts.optflag("h", "help", "display this help and exit");
identifier_body
euler.rs
use super::matrix4::Matrix4; use super::vector3::Vector3; use super::quaternion::Quaternion; use super::math_static::clamp; use std::mem; #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum RotationOrders { XYZ, YZX, ZXY, XZY, YXZ, ZYX, } impl From<u8> for RotationOrders { fn from(t:u8) -> RotationOrders { assert!(RotationOrders::XYZ as u8 <= t && t <= RotationOrders::ZYX as u8); unsafe { mem::transmute(t) } } } pub static mut DEFAULT_ORDER: RotationOrders = RotationOrders::XYZ; #[derive(Debug, Clone, Copy)] pub struct Euler { pub x: f32, pub y: f32, pub z: f32, pub order: RotationOrders, } impl Euler { pub fn new() -> Euler { Euler { x: 0.0f32, y: 0.0f32, z: 0.0f32, order: unsafe {DEFAULT_ORDER}, } } pub fn get_x(&self) -> f32 { self.x } pub fn set_x(&mut self, x: f32) { self.x = x; } pub fn get_y(&self) -> f32 { self.y } pub fn set_y(&mut self, y: f32) { self.y = y; } pub fn get_z(&self) -> f32 { self.z } pub fn set_order(&mut self, order: RotationOrders) { self.order = order; } pub fn get_order(&self) -> RotationOrders { self.order } pub fn set(&mut self, x: f32, y: f32, z: f32, order: RotationOrders) { self.x = x;
} pub fn copy(&mut self, euler: &Euler) { self.x = euler.x; self.y = euler.y; self.z = euler.z; self.order = euler.order; } pub fn set_from_rotation_matrix(&mut self, m: &Matrix4, order: Option<RotationOrders>) { let te = m.get_elements(); let m11 = te[ 0 ]; let m12 = te[ 4 ]; let m13 = te[ 8 ]; let m21 = te[ 1 ]; let m22 = te[ 5 ]; let m23 = te[ 9 ]; let m31 = te[ 2 ]; let m32 = te[ 6 ]; let m33 = te[ 10 ]; let order = match order { Some(ord) => ord, None => self.order, }; match order { RotationOrders::XYZ => { self.y = clamp(m13, -1.0, 1.0).asin(); if m13.abs() < 0.99999f32 { self.x = (-m23).atan2(m33); self.z = (-m12).atan2(m11); } else { self.x = m32.atan2(m22); self.z = 0.0f32; } }, RotationOrders::YXZ => { self.x = (-clamp(m23, -1.0, 1.0)).asin(); if m23.abs() < 0.99999f32 { self.y = m13.atan2(m33); self.z = m21.atan2(m22); } else { self.y = (-m31).atan2(m11); self.z = 0.0f32; } }, RotationOrders::ZXY => { self.x = clamp(m32, -1.0, 1.0).asin(); if m32.abs() < 0.99999f32 { self.y = (-m31).atan2(m33); self.z = (-m12).atan2(m22); } else { self.y = 0.0f32; self.z = m21.atan2(m11); } }, RotationOrders::ZYX => { self.y = (-clamp(m31, -1.0, 1.0)).asin(); if m31.abs() < 0.99999f32 { self.x = m32.atan2(m33); self.z = m21.atan2(m11); } else { self.x = 0.0f32; self.z = (-m12).atan2(m22); } }, RotationOrders::YZX => { self.z = clamp(m21, -1.0, 1.0).asin(); if m21.abs() < 0.99999f32 { self.x = (-m23).atan2(m22); self.y = (-m31).atan2(m11); } else { self.x = 0.0f32; self.y = m13.atan2(m33); } }, RotationOrders::XZY => { self.z = (-clamp(m21, -1.0, 1.0)).asin(); if m12.abs() < 0.99999f32 { self.x = m32.atan2(m22); self.y = m13.atan2(m11); } else { self.x = (-m23).atan2(m33); self.y = 0.0f32; } }, } self.order = order; } pub fn set_from_quaternion(&mut self, q: &Quaternion, order: Option<RotationOrders>) { let mut matrix = Matrix4::new(); matrix.make_rotation_from_quaternion(q); self.set_from_rotation_matrix(&matrix, order); } pub fn set_from_vector3(&mut self, v: &Vector3, order: Option<RotationOrders>) { let order = match order { Some(ord) => ord, None => self.order, }; self.set(v.get_x(), v.get_y(), v.get_z(), order); } pub fn reorder(&mut self, new_order: RotationOrders) { let mut q = Quaternion::new(); q.set_from_euler(self); self.set_from_quaternion(&q, Some(new_order)); } pub fn equals(&mut self, euler: &Euler) -> bool { ( euler.x == self.x ) && ( euler.y == self.y ) && ( euler.z == self.z ) && ( euler.order == self.order ) } pub fn copy_from_array(&mut self, array: &[f32]) { self.x = array[0]; self.y = array[1]; self.z = array[2]; // I know this is bad, but its necessary to get api compatibility if array.len() >= 4 { self.order = RotationOrders::from(array[3] as u8); } } pub fn copy_to_array(&self, array: &mut [f32], offset: Option<usize>) { let offset = match offset { Some(off) => off, None => 0usize, }; array[ offset ] = self.x; array[ offset + 1 ] = self.y; array[ offset + 2 ] = self.z; // I know this is bad, but its necessary to get api compatibility array[ offset + 3 ] = (self.order as u8) as f32; } pub fn to_vector3(&self, vector: &mut Vector3) { vector.set(self.x, self.y, self.z); } }
self.y = y; self.z = z; self.order = order;
random_line_split
euler.rs
use super::matrix4::Matrix4; use super::vector3::Vector3; use super::quaternion::Quaternion; use super::math_static::clamp; use std::mem; #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum RotationOrders { XYZ, YZX, ZXY, XZY, YXZ, ZYX, } impl From<u8> for RotationOrders { fn from(t:u8) -> RotationOrders { assert!(RotationOrders::XYZ as u8 <= t && t <= RotationOrders::ZYX as u8); unsafe { mem::transmute(t) } } } pub static mut DEFAULT_ORDER: RotationOrders = RotationOrders::XYZ; #[derive(Debug, Clone, Copy)] pub struct Euler { pub x: f32, pub y: f32, pub z: f32, pub order: RotationOrders, } impl Euler { pub fn new() -> Euler { Euler { x: 0.0f32, y: 0.0f32, z: 0.0f32, order: unsafe {DEFAULT_ORDER}, } } pub fn get_x(&self) -> f32 { self.x } pub fn set_x(&mut self, x: f32) { self.x = x; } pub fn get_y(&self) -> f32 { self.y } pub fn set_y(&mut self, y: f32) { self.y = y; } pub fn get_z(&self) -> f32 { self.z } pub fn set_order(&mut self, order: RotationOrders) { self.order = order; } pub fn get_order(&self) -> RotationOrders { self.order } pub fn set(&mut self, x: f32, y: f32, z: f32, order: RotationOrders) { self.x = x; self.y = y; self.z = z; self.order = order; } pub fn copy(&mut self, euler: &Euler) { self.x = euler.x; self.y = euler.y; self.z = euler.z; self.order = euler.order; } pub fn set_from_rotation_matrix(&mut self, m: &Matrix4, order: Option<RotationOrders>) { let te = m.get_elements(); let m11 = te[ 0 ]; let m12 = te[ 4 ]; let m13 = te[ 8 ]; let m21 = te[ 1 ]; let m22 = te[ 5 ]; let m23 = te[ 9 ]; let m31 = te[ 2 ]; let m32 = te[ 6 ]; let m33 = te[ 10 ]; let order = match order { Some(ord) => ord, None => self.order, }; match order { RotationOrders::XYZ => { self.y = clamp(m13, -1.0, 1.0).asin(); if m13.abs() < 0.99999f32 { self.x = (-m23).atan2(m33); self.z = (-m12).atan2(m11); } else { self.x = m32.atan2(m22); self.z = 0.0f32; } }, RotationOrders::YXZ => { self.x = (-clamp(m23, -1.0, 1.0)).asin(); if m23.abs() < 0.99999f32 { self.y = m13.atan2(m33); self.z = m21.atan2(m22); } else { self.y = (-m31).atan2(m11); self.z = 0.0f32; } }, RotationOrders::ZXY => { self.x = clamp(m32, -1.0, 1.0).asin(); if m32.abs() < 0.99999f32 { self.y = (-m31).atan2(m33); self.z = (-m12).atan2(m22); } else { self.y = 0.0f32; self.z = m21.atan2(m11); } }, RotationOrders::ZYX => { self.y = (-clamp(m31, -1.0, 1.0)).asin(); if m31.abs() < 0.99999f32 { self.x = m32.atan2(m33); self.z = m21.atan2(m11); } else { self.x = 0.0f32; self.z = (-m12).atan2(m22); } }, RotationOrders::YZX => { self.z = clamp(m21, -1.0, 1.0).asin(); if m21.abs() < 0.99999f32 { self.x = (-m23).atan2(m22); self.y = (-m31).atan2(m11); } else { self.x = 0.0f32; self.y = m13.atan2(m33); } }, RotationOrders::XZY => { self.z = (-clamp(m21, -1.0, 1.0)).asin(); if m12.abs() < 0.99999f32 { self.x = m32.atan2(m22); self.y = m13.atan2(m11); } else { self.x = (-m23).atan2(m33); self.y = 0.0f32; } }, } self.order = order; } pub fn set_from_quaternion(&mut self, q: &Quaternion, order: Option<RotationOrders>) { let mut matrix = Matrix4::new(); matrix.make_rotation_from_quaternion(q); self.set_from_rotation_matrix(&matrix, order); } pub fn set_from_vector3(&mut self, v: &Vector3, order: Option<RotationOrders>) { let order = match order { Some(ord) => ord, None => self.order, }; self.set(v.get_x(), v.get_y(), v.get_z(), order); } pub fn reorder(&mut self, new_order: RotationOrders) { let mut q = Quaternion::new(); q.set_from_euler(self); self.set_from_quaternion(&q, Some(new_order)); } pub fn equals(&mut self, euler: &Euler) -> bool { ( euler.x == self.x ) && ( euler.y == self.y ) && ( euler.z == self.z ) && ( euler.order == self.order ) } pub fn copy_from_array(&mut self, array: &[f32]) { self.x = array[0]; self.y = array[1]; self.z = array[2]; // I know this is bad, but its necessary to get api compatibility if array.len() >= 4
} pub fn copy_to_array(&self, array: &mut [f32], offset: Option<usize>) { let offset = match offset { Some(off) => off, None => 0usize, }; array[ offset ] = self.x; array[ offset + 1 ] = self.y; array[ offset + 2 ] = self.z; // I know this is bad, but its necessary to get api compatibility array[ offset + 3 ] = (self.order as u8) as f32; } pub fn to_vector3(&self, vector: &mut Vector3) { vector.set(self.x, self.y, self.z); } }
{ self.order = RotationOrders::from(array[3] as u8); }
conditional_block
euler.rs
use super::matrix4::Matrix4; use super::vector3::Vector3; use super::quaternion::Quaternion; use super::math_static::clamp; use std::mem; #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum RotationOrders { XYZ, YZX, ZXY, XZY, YXZ, ZYX, } impl From<u8> for RotationOrders { fn from(t:u8) -> RotationOrders { assert!(RotationOrders::XYZ as u8 <= t && t <= RotationOrders::ZYX as u8); unsafe { mem::transmute(t) } } } pub static mut DEFAULT_ORDER: RotationOrders = RotationOrders::XYZ; #[derive(Debug, Clone, Copy)] pub struct Euler { pub x: f32, pub y: f32, pub z: f32, pub order: RotationOrders, } impl Euler { pub fn new() -> Euler { Euler { x: 0.0f32, y: 0.0f32, z: 0.0f32, order: unsafe {DEFAULT_ORDER}, } } pub fn get_x(&self) -> f32 { self.x } pub fn set_x(&mut self, x: f32) { self.x = x; } pub fn get_y(&self) -> f32 { self.y } pub fn set_y(&mut self, y: f32) { self.y = y; } pub fn get_z(&self) -> f32 { self.z } pub fn set_order(&mut self, order: RotationOrders) { self.order = order; } pub fn get_order(&self) -> RotationOrders { self.order } pub fn set(&mut self, x: f32, y: f32, z: f32, order: RotationOrders) { self.x = x; self.y = y; self.z = z; self.order = order; } pub fn copy(&mut self, euler: &Euler) { self.x = euler.x; self.y = euler.y; self.z = euler.z; self.order = euler.order; } pub fn set_from_rotation_matrix(&mut self, m: &Matrix4, order: Option<RotationOrders>) { let te = m.get_elements(); let m11 = te[ 0 ]; let m12 = te[ 4 ]; let m13 = te[ 8 ]; let m21 = te[ 1 ]; let m22 = te[ 5 ]; let m23 = te[ 9 ]; let m31 = te[ 2 ]; let m32 = te[ 6 ]; let m33 = te[ 10 ]; let order = match order { Some(ord) => ord, None => self.order, }; match order { RotationOrders::XYZ => { self.y = clamp(m13, -1.0, 1.0).asin(); if m13.abs() < 0.99999f32 { self.x = (-m23).atan2(m33); self.z = (-m12).atan2(m11); } else { self.x = m32.atan2(m22); self.z = 0.0f32; } }, RotationOrders::YXZ => { self.x = (-clamp(m23, -1.0, 1.0)).asin(); if m23.abs() < 0.99999f32 { self.y = m13.atan2(m33); self.z = m21.atan2(m22); } else { self.y = (-m31).atan2(m11); self.z = 0.0f32; } }, RotationOrders::ZXY => { self.x = clamp(m32, -1.0, 1.0).asin(); if m32.abs() < 0.99999f32 { self.y = (-m31).atan2(m33); self.z = (-m12).atan2(m22); } else { self.y = 0.0f32; self.z = m21.atan2(m11); } }, RotationOrders::ZYX => { self.y = (-clamp(m31, -1.0, 1.0)).asin(); if m31.abs() < 0.99999f32 { self.x = m32.atan2(m33); self.z = m21.atan2(m11); } else { self.x = 0.0f32; self.z = (-m12).atan2(m22); } }, RotationOrders::YZX => { self.z = clamp(m21, -1.0, 1.0).asin(); if m21.abs() < 0.99999f32 { self.x = (-m23).atan2(m22); self.y = (-m31).atan2(m11); } else { self.x = 0.0f32; self.y = m13.atan2(m33); } }, RotationOrders::XZY => { self.z = (-clamp(m21, -1.0, 1.0)).asin(); if m12.abs() < 0.99999f32 { self.x = m32.atan2(m22); self.y = m13.atan2(m11); } else { self.x = (-m23).atan2(m33); self.y = 0.0f32; } }, } self.order = order; } pub fn
(&mut self, q: &Quaternion, order: Option<RotationOrders>) { let mut matrix = Matrix4::new(); matrix.make_rotation_from_quaternion(q); self.set_from_rotation_matrix(&matrix, order); } pub fn set_from_vector3(&mut self, v: &Vector3, order: Option<RotationOrders>) { let order = match order { Some(ord) => ord, None => self.order, }; self.set(v.get_x(), v.get_y(), v.get_z(), order); } pub fn reorder(&mut self, new_order: RotationOrders) { let mut q = Quaternion::new(); q.set_from_euler(self); self.set_from_quaternion(&q, Some(new_order)); } pub fn equals(&mut self, euler: &Euler) -> bool { ( euler.x == self.x ) && ( euler.y == self.y ) && ( euler.z == self.z ) && ( euler.order == self.order ) } pub fn copy_from_array(&mut self, array: &[f32]) { self.x = array[0]; self.y = array[1]; self.z = array[2]; // I know this is bad, but its necessary to get api compatibility if array.len() >= 4 { self.order = RotationOrders::from(array[3] as u8); } } pub fn copy_to_array(&self, array: &mut [f32], offset: Option<usize>) { let offset = match offset { Some(off) => off, None => 0usize, }; array[ offset ] = self.x; array[ offset + 1 ] = self.y; array[ offset + 2 ] = self.z; // I know this is bad, but its necessary to get api compatibility array[ offset + 3 ] = (self.order as u8) as f32; } pub fn to_vector3(&self, vector: &mut Vector3) { vector.set(self.x, self.y, self.z); } }
set_from_quaternion
identifier_name
euler.rs
use super::matrix4::Matrix4; use super::vector3::Vector3; use super::quaternion::Quaternion; use super::math_static::clamp; use std::mem; #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum RotationOrders { XYZ, YZX, ZXY, XZY, YXZ, ZYX, } impl From<u8> for RotationOrders { fn from(t:u8) -> RotationOrders { assert!(RotationOrders::XYZ as u8 <= t && t <= RotationOrders::ZYX as u8); unsafe { mem::transmute(t) } } } pub static mut DEFAULT_ORDER: RotationOrders = RotationOrders::XYZ; #[derive(Debug, Clone, Copy)] pub struct Euler { pub x: f32, pub y: f32, pub z: f32, pub order: RotationOrders, } impl Euler { pub fn new() -> Euler { Euler { x: 0.0f32, y: 0.0f32, z: 0.0f32, order: unsafe {DEFAULT_ORDER}, } } pub fn get_x(&self) -> f32 { self.x } pub fn set_x(&mut self, x: f32) { self.x = x; } pub fn get_y(&self) -> f32 { self.y } pub fn set_y(&mut self, y: f32) { self.y = y; } pub fn get_z(&self) -> f32 { self.z } pub fn set_order(&mut self, order: RotationOrders) { self.order = order; } pub fn get_order(&self) -> RotationOrders { self.order } pub fn set(&mut self, x: f32, y: f32, z: f32, order: RotationOrders) { self.x = x; self.y = y; self.z = z; self.order = order; } pub fn copy(&mut self, euler: &Euler) { self.x = euler.x; self.y = euler.y; self.z = euler.z; self.order = euler.order; } pub fn set_from_rotation_matrix(&mut self, m: &Matrix4, order: Option<RotationOrders>)
if m13.abs() < 0.99999f32 { self.x = (-m23).atan2(m33); self.z = (-m12).atan2(m11); } else { self.x = m32.atan2(m22); self.z = 0.0f32; } }, RotationOrders::YXZ => { self.x = (-clamp(m23, -1.0, 1.0)).asin(); if m23.abs() < 0.99999f32 { self.y = m13.atan2(m33); self.z = m21.atan2(m22); } else { self.y = (-m31).atan2(m11); self.z = 0.0f32; } }, RotationOrders::ZXY => { self.x = clamp(m32, -1.0, 1.0).asin(); if m32.abs() < 0.99999f32 { self.y = (-m31).atan2(m33); self.z = (-m12).atan2(m22); } else { self.y = 0.0f32; self.z = m21.atan2(m11); } }, RotationOrders::ZYX => { self.y = (-clamp(m31, -1.0, 1.0)).asin(); if m31.abs() < 0.99999f32 { self.x = m32.atan2(m33); self.z = m21.atan2(m11); } else { self.x = 0.0f32; self.z = (-m12).atan2(m22); } }, RotationOrders::YZX => { self.z = clamp(m21, -1.0, 1.0).asin(); if m21.abs() < 0.99999f32 { self.x = (-m23).atan2(m22); self.y = (-m31).atan2(m11); } else { self.x = 0.0f32; self.y = m13.atan2(m33); } }, RotationOrders::XZY => { self.z = (-clamp(m21, -1.0, 1.0)).asin(); if m12.abs() < 0.99999f32 { self.x = m32.atan2(m22); self.y = m13.atan2(m11); } else { self.x = (-m23).atan2(m33); self.y = 0.0f32; } }, } self.order = order; } pub fn set_from_quaternion(&mut self, q: &Quaternion, order: Option<RotationOrders>) { let mut matrix = Matrix4::new(); matrix.make_rotation_from_quaternion(q); self.set_from_rotation_matrix(&matrix, order); } pub fn set_from_vector3(&mut self, v: &Vector3, order: Option<RotationOrders>) { let order = match order { Some(ord) => ord, None => self.order, }; self.set(v.get_x(), v.get_y(), v.get_z(), order); } pub fn reorder(&mut self, new_order: RotationOrders) { let mut q = Quaternion::new(); q.set_from_euler(self); self.set_from_quaternion(&q, Some(new_order)); } pub fn equals(&mut self, euler: &Euler) -> bool { ( euler.x == self.x ) && ( euler.y == self.y ) && ( euler.z == self.z ) && ( euler.order == self.order ) } pub fn copy_from_array(&mut self, array: &[f32]) { self.x = array[0]; self.y = array[1]; self.z = array[2]; // I know this is bad, but its necessary to get api compatibility if array.len() >= 4 { self.order = RotationOrders::from(array[3] as u8); } } pub fn copy_to_array(&self, array: &mut [f32], offset: Option<usize>) { let offset = match offset { Some(off) => off, None => 0usize, }; array[ offset ] = self.x; array[ offset + 1 ] = self.y; array[ offset + 2 ] = self.z; // I know this is bad, but its necessary to get api compatibility array[ offset + 3 ] = (self.order as u8) as f32; } pub fn to_vector3(&self, vector: &mut Vector3) { vector.set(self.x, self.y, self.z); } }
{ let te = m.get_elements(); let m11 = te[ 0 ]; let m12 = te[ 4 ]; let m13 = te[ 8 ]; let m21 = te[ 1 ]; let m22 = te[ 5 ]; let m23 = te[ 9 ]; let m31 = te[ 2 ]; let m32 = te[ 6 ]; let m33 = te[ 10 ]; let order = match order { Some(ord) => ord, None => self.order, }; match order { RotationOrders::XYZ => { self.y = clamp(m13, -1.0, 1.0).asin();
identifier_body
helpers.rs
// Copyright 2015-2017 Parity Technologies (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/>. //! Snapshot test helpers. These are used to build blockchains and state tries //! which can be queried before and after a full snapshot/restore cycle. use basic_account::BasicAccount; use account_db::AccountDBMut; use rand::Rng; use util::DBValue; use util::hash::{FixedHash, H256}; use util::hashdb::HashDB; use util::trie::{Alphabet, StandardMap, SecTrieDBMut, TrieMut, ValueMode}; use util::trie::{TrieDB, TrieDBMut, Trie}; use util::sha3::SHA3_NULL_RLP; // the proportion of accounts we will alter each tick. const ACCOUNT_CHURN: f32 = 0.01; /// This structure will incrementally alter a state given an rng. pub struct StateProducer { state_root: H256, storage_seed: H256, } impl StateProducer { /// Create a new `StateProducer`. pub fn new() -> Self { StateProducer { state_root: SHA3_NULL_RLP, storage_seed: H256::zero(), } } #[cfg_attr(feature="dev", allow(let_and_return))] /// Tick the state producer. This alters the state, writing new data into /// the database. pub fn tick<R: Rng>(&mut self, rng: &mut R, db: &mut HashDB) { // modify existing accounts. let mut accounts_to_modify: Vec<_> = { let trie = TrieDB::new(&*db, &self.state_root).unwrap(); let temp = trie.iter().unwrap() // binding required due to complicated lifetime stuff .filter(|_| rng.gen::<f32>() < ACCOUNT_CHURN) .map(Result::unwrap) .map(|(k, v)| (H256::from_slice(&k), v.to_owned())) .collect(); temp }; // sweep once to alter storage tries. for &mut (ref mut address_hash, ref mut account_data) in &mut accounts_to_modify { let mut account: BasicAccount = ::rlp::decode(&*account_data); let acct_db = AccountDBMut::from_hash(db, *address_hash); fill_storage(acct_db, &mut account.storage_root, &mut self.storage_seed); *account_data = DBValue::from_vec(::rlp::encode(&account).to_vec()); } // sweep again to alter account trie. let mut trie = TrieDBMut::from_existing(db, &mut self.state_root).unwrap(); for (address_hash, account_data) in accounts_to_modify { trie.insert(&address_hash[..], &account_data).unwrap(); } // add between 0 and 5 new accounts each tick. let new_accs = rng.gen::<u32>() % 5; for _ in 0..new_accs { let address_hash = H256(rng.gen()); let balance: usize = rng.gen(); let nonce: usize = rng.gen(); let acc = ::state::Account::new_basic(balance.into(), nonce.into()).rlp(); trie.insert(&address_hash[..], &acc).unwrap(); } } /// Get the current state root. pub fn state_root(&self) -> H256 { self.state_root } } /// Fill the storage of an account. pub fn fill_storage(mut db: AccountDBMut, root: &mut H256, seed: &mut H256) { let map = StandardMap { alphabet: Alphabet::All, min_key: 6, journal_key: 6, value_mode: ValueMode::Random, count: 100, }; { let mut trie = if *root == SHA3_NULL_RLP { SecTrieDBMut::new(&mut db, root) } else { SecTrieDBMut::from_existing(&mut db, root).unwrap() }; for (k, v) in map.make_with(seed) { trie.insert(&k, &v).unwrap(); } } } /// Compare two state dbs. pub fn compare_dbs(one: &HashDB, two: &HashDB)
{ let keys = one.keys(); for key in keys.keys() { assert_eq!(one.get(&key).unwrap(), two.get(&key).unwrap()); } }
identifier_body
helpers.rs
// Copyright 2015-2017 Parity Technologies (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/>. //! Snapshot test helpers. These are used to build blockchains and state tries //! which can be queried before and after a full snapshot/restore cycle. use basic_account::BasicAccount; use account_db::AccountDBMut; use rand::Rng; use util::DBValue; use util::hash::{FixedHash, H256}; use util::hashdb::HashDB; use util::trie::{Alphabet, StandardMap, SecTrieDBMut, TrieMut, ValueMode}; use util::trie::{TrieDB, TrieDBMut, Trie}; use util::sha3::SHA3_NULL_RLP; // the proportion of accounts we will alter each tick. const ACCOUNT_CHURN: f32 = 0.01; /// This structure will incrementally alter a state given an rng. pub struct StateProducer { state_root: H256, storage_seed: H256, } impl StateProducer { /// Create a new `StateProducer`. pub fn new() -> Self { StateProducer { state_root: SHA3_NULL_RLP, storage_seed: H256::zero(), } } #[cfg_attr(feature="dev", allow(let_and_return))] /// Tick the state producer. This alters the state, writing new data into /// the database. pub fn tick<R: Rng>(&mut self, rng: &mut R, db: &mut HashDB) { // modify existing accounts. let mut accounts_to_modify: Vec<_> = { let trie = TrieDB::new(&*db, &self.state_root).unwrap(); let temp = trie.iter().unwrap() // binding required due to complicated lifetime stuff .filter(|_| rng.gen::<f32>() < ACCOUNT_CHURN) .map(Result::unwrap) .map(|(k, v)| (H256::from_slice(&k), v.to_owned())) .collect(); temp }; // sweep once to alter storage tries. for &mut (ref mut address_hash, ref mut account_data) in &mut accounts_to_modify { let mut account: BasicAccount = ::rlp::decode(&*account_data); let acct_db = AccountDBMut::from_hash(db, *address_hash); fill_storage(acct_db, &mut account.storage_root, &mut self.storage_seed); *account_data = DBValue::from_vec(::rlp::encode(&account).to_vec()); } // sweep again to alter account trie. let mut trie = TrieDBMut::from_existing(db, &mut self.state_root).unwrap(); for (address_hash, account_data) in accounts_to_modify { trie.insert(&address_hash[..], &account_data).unwrap(); } // add between 0 and 5 new accounts each tick. let new_accs = rng.gen::<u32>() % 5; for _ in 0..new_accs { let address_hash = H256(rng.gen()); let balance: usize = rng.gen(); let nonce: usize = rng.gen(); let acc = ::state::Account::new_basic(balance.into(), nonce.into()).rlp(); trie.insert(&address_hash[..], &acc).unwrap(); } } /// Get the current state root. pub fn state_root(&self) -> H256 { self.state_root } } /// Fill the storage of an account. pub fn fill_storage(mut db: AccountDBMut, root: &mut H256, seed: &mut H256) { let map = StandardMap { alphabet: Alphabet::All, min_key: 6, journal_key: 6, value_mode: ValueMode::Random, count: 100, }; { let mut trie = if *root == SHA3_NULL_RLP { SecTrieDBMut::new(&mut db, root) } else
; for (k, v) in map.make_with(seed) { trie.insert(&k, &v).unwrap(); } } } /// Compare two state dbs. pub fn compare_dbs(one: &HashDB, two: &HashDB) { let keys = one.keys(); for key in keys.keys() { assert_eq!(one.get(&key).unwrap(), two.get(&key).unwrap()); } }
{ SecTrieDBMut::from_existing(&mut db, root).unwrap() }
conditional_block
helpers.rs
// Copyright 2015-2017 Parity Technologies (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/>. //! Snapshot test helpers. These are used to build blockchains and state tries
use rand::Rng; use util::DBValue; use util::hash::{FixedHash, H256}; use util::hashdb::HashDB; use util::trie::{Alphabet, StandardMap, SecTrieDBMut, TrieMut, ValueMode}; use util::trie::{TrieDB, TrieDBMut, Trie}; use util::sha3::SHA3_NULL_RLP; // the proportion of accounts we will alter each tick. const ACCOUNT_CHURN: f32 = 0.01; /// This structure will incrementally alter a state given an rng. pub struct StateProducer { state_root: H256, storage_seed: H256, } impl StateProducer { /// Create a new `StateProducer`. pub fn new() -> Self { StateProducer { state_root: SHA3_NULL_RLP, storage_seed: H256::zero(), } } #[cfg_attr(feature="dev", allow(let_and_return))] /// Tick the state producer. This alters the state, writing new data into /// the database. pub fn tick<R: Rng>(&mut self, rng: &mut R, db: &mut HashDB) { // modify existing accounts. let mut accounts_to_modify: Vec<_> = { let trie = TrieDB::new(&*db, &self.state_root).unwrap(); let temp = trie.iter().unwrap() // binding required due to complicated lifetime stuff .filter(|_| rng.gen::<f32>() < ACCOUNT_CHURN) .map(Result::unwrap) .map(|(k, v)| (H256::from_slice(&k), v.to_owned())) .collect(); temp }; // sweep once to alter storage tries. for &mut (ref mut address_hash, ref mut account_data) in &mut accounts_to_modify { let mut account: BasicAccount = ::rlp::decode(&*account_data); let acct_db = AccountDBMut::from_hash(db, *address_hash); fill_storage(acct_db, &mut account.storage_root, &mut self.storage_seed); *account_data = DBValue::from_vec(::rlp::encode(&account).to_vec()); } // sweep again to alter account trie. let mut trie = TrieDBMut::from_existing(db, &mut self.state_root).unwrap(); for (address_hash, account_data) in accounts_to_modify { trie.insert(&address_hash[..], &account_data).unwrap(); } // add between 0 and 5 new accounts each tick. let new_accs = rng.gen::<u32>() % 5; for _ in 0..new_accs { let address_hash = H256(rng.gen()); let balance: usize = rng.gen(); let nonce: usize = rng.gen(); let acc = ::state::Account::new_basic(balance.into(), nonce.into()).rlp(); trie.insert(&address_hash[..], &acc).unwrap(); } } /// Get the current state root. pub fn state_root(&self) -> H256 { self.state_root } } /// Fill the storage of an account. pub fn fill_storage(mut db: AccountDBMut, root: &mut H256, seed: &mut H256) { let map = StandardMap { alphabet: Alphabet::All, min_key: 6, journal_key: 6, value_mode: ValueMode::Random, count: 100, }; { let mut trie = if *root == SHA3_NULL_RLP { SecTrieDBMut::new(&mut db, root) } else { SecTrieDBMut::from_existing(&mut db, root).unwrap() }; for (k, v) in map.make_with(seed) { trie.insert(&k, &v).unwrap(); } } } /// Compare two state dbs. pub fn compare_dbs(one: &HashDB, two: &HashDB) { let keys = one.keys(); for key in keys.keys() { assert_eq!(one.get(&key).unwrap(), two.get(&key).unwrap()); } }
//! which can be queried before and after a full snapshot/restore cycle. use basic_account::BasicAccount; use account_db::AccountDBMut;
random_line_split
helpers.rs
// Copyright 2015-2017 Parity Technologies (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/>. //! Snapshot test helpers. These are used to build blockchains and state tries //! which can be queried before and after a full snapshot/restore cycle. use basic_account::BasicAccount; use account_db::AccountDBMut; use rand::Rng; use util::DBValue; use util::hash::{FixedHash, H256}; use util::hashdb::HashDB; use util::trie::{Alphabet, StandardMap, SecTrieDBMut, TrieMut, ValueMode}; use util::trie::{TrieDB, TrieDBMut, Trie}; use util::sha3::SHA3_NULL_RLP; // the proportion of accounts we will alter each tick. const ACCOUNT_CHURN: f32 = 0.01; /// This structure will incrementally alter a state given an rng. pub struct StateProducer { state_root: H256, storage_seed: H256, } impl StateProducer { /// Create a new `StateProducer`. pub fn new() -> Self { StateProducer { state_root: SHA3_NULL_RLP, storage_seed: H256::zero(), } } #[cfg_attr(feature="dev", allow(let_and_return))] /// Tick the state producer. This alters the state, writing new data into /// the database. pub fn tick<R: Rng>(&mut self, rng: &mut R, db: &mut HashDB) { // modify existing accounts. let mut accounts_to_modify: Vec<_> = { let trie = TrieDB::new(&*db, &self.state_root).unwrap(); let temp = trie.iter().unwrap() // binding required due to complicated lifetime stuff .filter(|_| rng.gen::<f32>() < ACCOUNT_CHURN) .map(Result::unwrap) .map(|(k, v)| (H256::from_slice(&k), v.to_owned())) .collect(); temp }; // sweep once to alter storage tries. for &mut (ref mut address_hash, ref mut account_data) in &mut accounts_to_modify { let mut account: BasicAccount = ::rlp::decode(&*account_data); let acct_db = AccountDBMut::from_hash(db, *address_hash); fill_storage(acct_db, &mut account.storage_root, &mut self.storage_seed); *account_data = DBValue::from_vec(::rlp::encode(&account).to_vec()); } // sweep again to alter account trie. let mut trie = TrieDBMut::from_existing(db, &mut self.state_root).unwrap(); for (address_hash, account_data) in accounts_to_modify { trie.insert(&address_hash[..], &account_data).unwrap(); } // add between 0 and 5 new accounts each tick. let new_accs = rng.gen::<u32>() % 5; for _ in 0..new_accs { let address_hash = H256(rng.gen()); let balance: usize = rng.gen(); let nonce: usize = rng.gen(); let acc = ::state::Account::new_basic(balance.into(), nonce.into()).rlp(); trie.insert(&address_hash[..], &acc).unwrap(); } } /// Get the current state root. pub fn
(&self) -> H256 { self.state_root } } /// Fill the storage of an account. pub fn fill_storage(mut db: AccountDBMut, root: &mut H256, seed: &mut H256) { let map = StandardMap { alphabet: Alphabet::All, min_key: 6, journal_key: 6, value_mode: ValueMode::Random, count: 100, }; { let mut trie = if *root == SHA3_NULL_RLP { SecTrieDBMut::new(&mut db, root) } else { SecTrieDBMut::from_existing(&mut db, root).unwrap() }; for (k, v) in map.make_with(seed) { trie.insert(&k, &v).unwrap(); } } } /// Compare two state dbs. pub fn compare_dbs(one: &HashDB, two: &HashDB) { let keys = one.keys(); for key in keys.keys() { assert_eq!(one.get(&key).unwrap(), two.get(&key).unwrap()); } }
state_root
identifier_name
main.rs
extern crate xmz_mod_touch_test_tool; use xmz_mod_touch_test_tool::errors::*; fn run() -> Result<()>
fn main() { println!("{} Version: {}\n", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); if let Err(ref e) = run() { use ::std::io::Write; let stderr = &mut ::std::io::stderr(); let errmsg = "Error writing to stderr"; writeln!(stderr, "error: {}", e).expect(errmsg); for e in e.iter().skip(1) { writeln!(stderr, "caused by: {}", e).expect(errmsg); } // The backtrace is not always generated. Try to run this example // with `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() { writeln!(stderr, "backtrace: {:?}", backtrace).expect(errmsg); } ::std::process::exit(1); } }
{ xmz_mod_touch_test_tool::gui::gtk3::launch(); Ok(()) }
identifier_body
main.rs
extern crate xmz_mod_touch_test_tool; use xmz_mod_touch_test_tool::errors::*; fn
() -> Result<()> { xmz_mod_touch_test_tool::gui::gtk3::launch(); Ok(()) } fn main() { println!("{} Version: {}\n", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); if let Err(ref e) = run() { use ::std::io::Write; let stderr = &mut ::std::io::stderr(); let errmsg = "Error writing to stderr"; writeln!(stderr, "error: {}", e).expect(errmsg); for e in e.iter().skip(1) { writeln!(stderr, "caused by: {}", e).expect(errmsg); } // The backtrace is not always generated. Try to run this example // with `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() { writeln!(stderr, "backtrace: {:?}", backtrace).expect(errmsg); } ::std::process::exit(1); } }
run
identifier_name
main.rs
extern crate xmz_mod_touch_test_tool; use xmz_mod_touch_test_tool::errors::*; fn run() -> Result<()> { xmz_mod_touch_test_tool::gui::gtk3::launch(); Ok(()) } fn main() { println!("{} Version: {}\n", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); if let Err(ref e) = run() { use ::std::io::Write; let stderr = &mut ::std::io::stderr(); let errmsg = "Error writing to stderr"; writeln!(stderr, "error: {}", e).expect(errmsg); for e in e.iter().skip(1) { writeln!(stderr, "caused by: {}", e).expect(errmsg); } // The backtrace is not always generated. Try to run this example // with `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace()
::std::process::exit(1); } }
{ writeln!(stderr, "backtrace: {:?}", backtrace).expect(errmsg); }
conditional_block
main.rs
extern crate xmz_mod_touch_test_tool; use xmz_mod_touch_test_tool::errors::*; fn run() -> Result<()> { xmz_mod_touch_test_tool::gui::gtk3::launch(); Ok(())
env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); if let Err(ref e) = run() { use ::std::io::Write; let stderr = &mut ::std::io::stderr(); let errmsg = "Error writing to stderr"; writeln!(stderr, "error: {}", e).expect(errmsg); for e in e.iter().skip(1) { writeln!(stderr, "caused by: {}", e).expect(errmsg); } // The backtrace is not always generated. Try to run this example // with `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() { writeln!(stderr, "backtrace: {:?}", backtrace).expect(errmsg); } ::std::process::exit(1); } }
} fn main() { println!("{} Version: {}\n",
random_line_split
cstore_impl.rs
cdata.get_generics(def_id.index, tcx.sess) } explicit_predicates_of => { cdata.get_explicit_predicates(def_id.index, tcx) } inferred_outlives_of => { cdata.get_inferred_outlives(def_id.index, tcx) } super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) } explicit_item_bounds => { cdata.get_explicit_item_bounds(def_id.index, tcx) } trait_def => { cdata.get_trait_def(def_id.index, tcx.sess) } adt_def => { cdata.get_adt_def(def_id.index, tcx) } adt_destructor => { let _ = cdata; tcx.calculate_dtor(def_id, |_,_| Ok(())) } variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) } associated_item_def_ids => { let mut result = SmallVec::<[_; 8]>::new(); cdata.each_child_of_item(def_id.index, |child| result.push(child.res.def_id()), tcx.sess); tcx.arena.alloc_slice(&result) } associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) } impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) } impl_polarity => { cdata.get_impl_polarity(def_id.index) } coerce_unsized_info => { cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| { bug!("coerce_unsized_info: `{:?}` is missing its info", def_id); }) } optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) } mir_for_ctfe => { tcx.arena.alloc(cdata.get_mir_for_ctfe(tcx, def_id.index)) } promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) } mir_abstract_const => { cdata.get_mir_abstract_const(tcx, def_id.index) } unused_generic_params => { cdata.get_unused_generic_params(def_id.index) } const_param_default => { tcx.mk_const(cdata.get_const_param_default(tcx, def_id.index)) } mir_const_qualif => { cdata.mir_const_qualif(def_id.index) } fn_sig => { cdata.fn_sig(def_id.index, tcx) } inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) } is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) } asyncness => { cdata.asyncness(def_id.index) } is_foreign_item => { cdata.is_foreign_item(def_id.index) } static_mutability => { cdata.static_mutability(def_id.index) } generator_kind => { cdata.generator_kind(def_id.index) } opt_def_kind => { Some(cdata.def_kind(def_id.index)) } def_span => { cdata.get_span(def_id.index, &tcx.sess) } def_ident_span => { cdata.try_item_ident(def_id.index, &tcx.sess).ok().map(|ident| ident.span) } lookup_stability => { cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s)) } lookup_const_stability => { cdata.get_const_stability(def_id.index).map(|s| tcx.intern_const_stability(s)) } lookup_deprecation_entry => { cdata.get_deprecation(def_id.index).map(DeprecationEntry::external) } item_attrs => { tcx.arena.alloc_from_iter( cdata.get_item_attrs(def_id.index, tcx.sess) ) } fn_arg_names => { cdata.get_fn_param_names(tcx, def_id.index) } rendered_const => { cdata.get_rendered_const(def_id.index) } impl_parent => { cdata.get_parent_impl(def_id.index) } trait_of_item => { cdata.get_trait_of_item(def_id.index) } is_mir_available => { cdata.is_item_mir_available(def_id.index) } is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) } dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) } is_private_dep => { cdata.private_dep } is_panic_runtime => { cdata.root.panic_runtime } is_compiler_builtins => { cdata.root.compiler_builtins } has_global_allocator => { cdata.root.has_global_allocator } has_panic_handler => { cdata.root.has_panic_handler } is_profiler_runtime => { cdata.root.profiler_runtime } panic_strategy => { cdata.root.panic_strategy } extern_crate => { let r = *cdata.extern_crate.lock(); r.map(|c| &*tcx.arena.alloc(c)) } is_no_builtins => { cdata.root.no_builtins } symbol_mangling_version => { cdata.root.symbol_mangling_version } impl_defaultness => { cdata.get_impl_defaultness(def_id.index) } impl_constness => { cdata.get_impl_constness(def_id.index) } reachable_non_generics => { let reachable_non_generics = tcx .exported_symbols(cdata.cnum) .iter() .filter_map(|&(exported_symbol, export_level)| { if let ExportedSymbol::NonGeneric(def_id) = exported_symbol { Some((def_id, export_level)) } else { None } }) .collect(); reachable_non_generics } native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) } foreign_modules => { cdata.get_foreign_modules(tcx) } crate_hash => { cdata.root.hash } crate_host_hash => { cdata.host_hash } crate_name => { cdata.root.name } extra_filename => { cdata.root.extra_filename.clone() } implementations_of_trait => { cdata.get_implementations_for_trait(tcx, Some(other)) } all_trait_implementations => { cdata.get_implementations_for_trait(tcx, None) } visibility => { cdata.get_visibility(def_id.index) } dep_kind => { let r = *cdata.dep_kind.lock(); r } item_children => { let mut result = SmallVec::<[_; 8]>::new(); cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess); tcx.arena.alloc_slice(&result) } defined_lib_features => { cdata.get_lib_features(tcx) } defined_lang_items => { cdata.get_lang_items(tcx) } diagnostic_items => { cdata.get_diagnostic_items() } missing_lang_items => { cdata.get_missing_lang_items(tcx) } missing_extern_crate_item => { let r = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if!extern_crate.is_direct()); r } used_crate_source => { Lrc::new(cdata.source.clone()) } exported_symbols => { let syms = cdata.exported_symbols(tcx); // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want // to block export of generics from dylibs, but we must fix // rust-lang/rust#65890 before we can do that robustly. syms } crate_extern_paths => { cdata.source().paths().cloned().collect() } expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) } } pub fn provide(providers: &mut Providers) { // FIXME(#44234) - almost all of these queries have no sub-queries and // therefore no actual inputs, they're just reading tables calculated in // resolve! Does this work? Unsure! That's what the issue is about *providers = Providers { allocator_kind: |tcx, ()| CStore::from_tcx(tcx).allocator_kind(), is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) { Some( NativeLibKind::Dylib {.. } | NativeLibKind::RawDylib | NativeLibKind::Unspecified, ) => true, _ => false, }, is_statically_included_foreign_item: |tcx, id| { matches!(tcx.native_library_kind(id), Some(NativeLibKind::Static {.. })) }, is_private_dep: |_tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); false }, native_library_kind: |tcx, id| { tcx.native_libraries(id.krate) .iter() .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib)) .find(|lib| { let fm_id = match lib.foreign_module { Some(id) => id, None => return false, }; let map = tcx.foreign_modules(id.krate); map.get(&fm_id) .expect("failed to find foreign module") .foreign_items .contains(&id) }) .map(|l| l.kind) }, native_libraries: |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); Lrc::new(native_libs::collect(tcx)) }, foreign_modules: |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); let modules: FxHashMap<DefId, ForeignModule> = foreign_modules::collect(tcx).into_iter().map(|m| (m.def_id, m)).collect(); Lrc::new(modules) }, // Returns a map from a sufficiently visible external item (i.e., an // external item that is visible from at least one local module) to a // sufficiently visible parent (considering modules that re-export the // external item to be parents). visible_parent_map: |tcx, ()| { use std::collections::hash_map::Entry; use std::collections::vec_deque::VecDeque; let mut visible_parent_map: DefIdMap<DefId> = Default::default(); // Issue 46112: We want the map to prefer the shortest // paths when reporting the path to an item. Therefore we // build up the map via a breadth-first search (BFS), // which naturally yields minimal-length paths. // // Note that it needs to be a BFS over the whole forest of // crates, not just each individual crate; otherwise you // only get paths that are locally minimal with respect to // whatever crate we happened to encounter first in this // traversal, but not globally minimal across all crates. let bfs_queue = &mut VecDeque::new(); // Preferring shortest paths alone does not guarantee a // deterministic result; so sort by crate num to avoid // hashtable iteration non-determinism. This only makes // things as deterministic as crate-nums assignment is, // which is to say, its not deterministic in general. But // we believe that libstd is consistently assigned crate // num 1, so it should be enough to resolve #46112. let mut crates: Vec<CrateNum> = (*tcx.crates(())).to_owned(); crates.sort(); for &cnum in crates.iter() { // Ignore crates without a corresponding local `extern crate` item. if tcx.missing_extern_crate_item(cnum) { continue; } bfs_queue.push_back(DefId { krate: cnum, index: CRATE_DEF_INDEX }); } // (restrict scope of mutable-borrow of `visible_parent_map`) { let visible_parent_map = &mut visible_parent_map; let mut add_child = |bfs_queue: &mut VecDeque<_>, child: &Export<hir::HirId>, parent: DefId| { if child.vis!= ty::Visibility::Public { return; } if let Some(child) = child.res.opt_def_id() { match visible_parent_map.entry(child) { Entry::Occupied(mut entry) => { // If `child` is defined in crate `cnum`, ensure // that it is mapped to a parent in `cnum`. if child.is_local() && entry.get().is_local() { entry.insert(parent); } } Entry::Vacant(entry) => { entry.insert(parent); bfs_queue.push_back(child); } } } }; while let Some(def) = bfs_queue.pop_front() { for child in tcx.item_children(def).iter() { add_child(bfs_queue, child, def); } } } visible_parent_map }, dependency_formats: |tcx, ()| Lrc::new(crate::dependency_format::calculate(tcx)), has_global_allocator: |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); CStore::from_tcx(tcx).has_global_allocator() }, postorder_cnums: |tcx, ()| { tcx.arena .alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(LOCAL_CRATE)) }, crates: |tcx, ()| tcx.arena.alloc_slice(&CStore::from_tcx(tcx).crates_untracked()), ..*providers }; } impl CStore { pub fn struct_field_names_untracked(&self, def: DefId, sess: &Session) -> Vec<Spanned<Symbol>> { self.get_crate_data(def.krate).get_struct_field_names(def.index, sess) } pub fn struct_field_visibilities_untracked(&self, def: DefId) -> Vec<Visibility> { self.get_crate_data(def.krate).get_struct_field_visibilities(def.index) } pub fn ctor_def_id_and_kind_untracked(&self, def: DefId) -> Option<(DefId, CtorKind)> { self.get_crate_data(def.krate).get_ctor_def_id(def.index).map(|ctor_def_id| { (ctor_def_id, self.get_crate_data(def.krate).get_ctor_kind(def.index)) }) } pub fn visibility_untracked(&self, def: DefId) -> Visibility { self.get_crate_data(def.krate).get_visibility(def.index) } pub fn item_children_untracked( &self, def_id: DefId, sess: &Session, ) -> Vec<Export<hir::HirId>> { let mut result = vec![]; self.get_crate_data(def_id.krate).each_child_of_item( def_id.index, |child| result.push(child), sess, ); result } pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro { let _prof_timer = sess.prof.generic_activity("metadata_load_macro"); let data = self.get_crate_data(id.krate); if data.root.is_proc_macro_crate() { return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess)); } let span = data.get_span(id.index, sess); let attrs = data.get_item_attrs(id.index, sess).collect(); let ident = data.item_ident(id.index, sess); LoadedMacro::MacroDef( ast::Item { ident, id: ast::DUMMY_NODE_ID, span, attrs, kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)), vis: ast::Visibility { span: span.shrink_to_lo(), kind: ast::VisibilityKind::Inherited, tokens: None, }, tokens: None, }, data.root.edition, ) } pub fn associated_item_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::AssocItem { self.get_crate_data(def.krate).get_associated_item(def.index, sess) } pub fn crate_source_untracked(&self, cnum: CrateNum) -> CrateSource { self.get_crate_data(cnum).source.clone() } pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span { self.get_crate_data(def_id.krate).get_span(def_id.index, sess) } pub fn def_kind(&self, def: DefId) -> DefKind { self.get_crate_data(def.krate).def_kind(def.index) } pub fn crates_untracked(&self) -> Vec<CrateNum> { let mut result = vec![]; self.iter_crate_data(|cnum, _| result.push(cnum)); result } pub fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize { self.get_crate_data(def_id.krate).get_generics(def_id.index, sess).own_counts().lifetimes } pub fn module_expansion_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId { self.get_crate_data(def_id.krate).module_expansion(def_id.index, sess) } /// Only public-facing way to traverse all the definitions in a non-local crate. /// Critically useful for this third-party project: <https://github.com/hacspec/hacspec>. /// See <https://github.com/rust-lang/rust/pull/85889> for context. pub fn num_def_ids_untracked(&self, cnum: CrateNum) -> usize { self.get_crate_data(cnum).num_def_ids() } pub fn item_attrs(&self, def_id: DefId, sess: &Session) -> Vec<ast::Attribute> { self.get_crate_data(def_id.krate).get_item_attrs(def_id.index, sess).collect() } pub fn get_proc_macro_quoted_span_untracked( &self, cnum: CrateNum, id: usize, sess: &Session, ) -> Span { self.get_crate_data(cnum).get_proc_macro_quoted_span(id, sess) } } impl CrateStore for CStore { fn as_any(&self) -> &dyn Any { self } fn crate_name(&self, cnum: CrateNum) -> Symbol { self.get_crate_data(cnum).root.name } fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId { self.get_crate_data(cnum).root.stable_crate_id } /// Returns the `DefKey` for a given `DefId`. This indicates the /// parent `DefId` as well as some idea of what kind of data the /// `DefId` refers to. fn def_key(&self, def: DefId) -> DefKey { self.get_crate_data(def.krate).def_key(def.index) } fn def_path(&self, def: DefId) -> DefPath
{ self.get_crate_data(def.krate).def_path(def.index) }
identifier_body
cstore_impl.rs
::query::query_values::$name<$lt> { let _prof_timer = $tcx.prof.generic_activity(concat!("metadata_decode_entry_", stringify!($name))); #[allow(unused_variables)] let ($def_id, $other) = def_id_arg.into_args(); assert!(!$def_id.is_local()); // External query providers call `crate_hash` in order to register a dependency // on the crate metadata. The exception is `crate_hash` itself, which obviously // doesn't need to do this (and can't, as it would cause a query cycle). use rustc_middle::dep_graph::DepKind; if DepKind::$name!= DepKind::crate_hash && $tcx.dep_graph.is_fully_enabled() { $tcx.ensure().crate_hash($def_id.krate); } let $cdata = CStore::from_tcx($tcx).get_crate_data($def_id.krate); $compute })* *providers = Providers { $($name,)* ..*providers }; } } } // small trait to work around different signature queries all being defined via // the macro above. trait IntoArgs { fn into_args(self) -> (DefId, DefId); } impl IntoArgs for DefId { fn into_args(self) -> (DefId, DefId) { (self, self) } } impl IntoArgs for CrateNum { fn into_args(self) -> (DefId, DefId) { (self.as_def_id(), self.as_def_id()) } } impl IntoArgs for (CrateNum, DefId) { fn into_args(self) -> (DefId, DefId) { (self.0.as_def_id(), self.1) } } provide! { <'tcx> tcx, def_id, other, cdata, type_of => { cdata.get_type(def_id.index, tcx) } generics_of => { cdata.get_generics(def_id.index, tcx.sess) } explicit_predicates_of => { cdata.get_explicit_predicates(def_id.index, tcx) } inferred_outlives_of => { cdata.get_inferred_outlives(def_id.index, tcx) } super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) } explicit_item_bounds => { cdata.get_explicit_item_bounds(def_id.index, tcx) } trait_def => { cdata.get_trait_def(def_id.index, tcx.sess) } adt_def => { cdata.get_adt_def(def_id.index, tcx) } adt_destructor => { let _ = cdata; tcx.calculate_dtor(def_id, |_,_| Ok(())) } variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) } associated_item_def_ids => { let mut result = SmallVec::<[_; 8]>::new(); cdata.each_child_of_item(def_id.index, |child| result.push(child.res.def_id()), tcx.sess); tcx.arena.alloc_slice(&result) } associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) } impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) } impl_polarity => { cdata.get_impl_polarity(def_id.index) } coerce_unsized_info => { cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| { bug!("coerce_unsized_info: `{:?}` is missing its info", def_id); }) } optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) } mir_for_ctfe => { tcx.arena.alloc(cdata.get_mir_for_ctfe(tcx, def_id.index)) } promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) } mir_abstract_const => { cdata.get_mir_abstract_const(tcx, def_id.index) } unused_generic_params => { cdata.get_unused_generic_params(def_id.index) } const_param_default => { tcx.mk_const(cdata.get_const_param_default(tcx, def_id.index)) } mir_const_qualif => { cdata.mir_const_qualif(def_id.index) } fn_sig => { cdata.fn_sig(def_id.index, tcx) } inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) } is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) } asyncness => { cdata.asyncness(def_id.index) } is_foreign_item => { cdata.is_foreign_item(def_id.index) } static_mutability => { cdata.static_mutability(def_id.index) } generator_kind => { cdata.generator_kind(def_id.index) } opt_def_kind => { Some(cdata.def_kind(def_id.index)) } def_span => { cdata.get_span(def_id.index, &tcx.sess) } def_ident_span => { cdata.try_item_ident(def_id.index, &tcx.sess).ok().map(|ident| ident.span) } lookup_stability => { cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s)) } lookup_const_stability => { cdata.get_const_stability(def_id.index).map(|s| tcx.intern_const_stability(s)) } lookup_deprecation_entry => { cdata.get_deprecation(def_id.index).map(DeprecationEntry::external) } item_attrs => { tcx.arena.alloc_from_iter( cdata.get_item_attrs(def_id.index, tcx.sess) ) } fn_arg_names => { cdata.get_fn_param_names(tcx, def_id.index) } rendered_const => { cdata.get_rendered_const(def_id.index) } impl_parent => { cdata.get_parent_impl(def_id.index) } trait_of_item => { cdata.get_trait_of_item(def_id.index) } is_mir_available => { cdata.is_item_mir_available(def_id.index) } is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) } dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) } is_private_dep => { cdata.private_dep } is_panic_runtime => { cdata.root.panic_runtime } is_compiler_builtins => { cdata.root.compiler_builtins } has_global_allocator => { cdata.root.has_global_allocator } has_panic_handler => { cdata.root.has_panic_handler } is_profiler_runtime => { cdata.root.profiler_runtime } panic_strategy => { cdata.root.panic_strategy } extern_crate => { let r = *cdata.extern_crate.lock(); r.map(|c| &*tcx.arena.alloc(c)) } is_no_builtins => { cdata.root.no_builtins } symbol_mangling_version => { cdata.root.symbol_mangling_version } impl_defaultness => { cdata.get_impl_defaultness(def_id.index) } impl_constness => { cdata.get_impl_constness(def_id.index) } reachable_non_generics => { let reachable_non_generics = tcx .exported_symbols(cdata.cnum) .iter() .filter_map(|&(exported_symbol, export_level)| { if let ExportedSymbol::NonGeneric(def_id) = exported_symbol { Some((def_id, export_level)) } else { None } }) .collect(); reachable_non_generics } native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) } foreign_modules => { cdata.get_foreign_modules(tcx) } crate_hash => { cdata.root.hash } crate_host_hash => { cdata.host_hash } crate_name => { cdata.root.name } extra_filename => { cdata.root.extra_filename.clone() } implementations_of_trait => { cdata.get_implementations_for_trait(tcx, Some(other)) } all_trait_implementations => { cdata.get_implementations_for_trait(tcx, None) } visibility => { cdata.get_visibility(def_id.index) } dep_kind => { let r = *cdata.dep_kind.lock(); r } item_children => { let mut result = SmallVec::<[_; 8]>::new(); cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess); tcx.arena.alloc_slice(&result) } defined_lib_features => { cdata.get_lib_features(tcx) } defined_lang_items => { cdata.get_lang_items(tcx) } diagnostic_items => { cdata.get_diagnostic_items() } missing_lang_items => { cdata.get_missing_lang_items(tcx) } missing_extern_crate_item => { let r = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if!extern_crate.is_direct()); r } used_crate_source => { Lrc::new(cdata.source.clone()) } exported_symbols => { let syms = cdata.exported_symbols(tcx); // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want // to block export of generics from dylibs, but we must fix // rust-lang/rust#65890 before we can do that robustly. syms } crate_extern_paths => { cdata.source().paths().cloned().collect() } expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) } } pub fn provide(providers: &mut Providers) { // FIXME(#44234) - almost all of these queries have no sub-queries and // therefore no actual inputs, they're just reading tables calculated in // resolve! Does this work? Unsure! That's what the issue is about *providers = Providers { allocator_kind: |tcx, ()| CStore::from_tcx(tcx).allocator_kind(), is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) { Some( NativeLibKind::Dylib {.. } | NativeLibKind::RawDylib | NativeLibKind::Unspecified, ) => true, _ => false, }, is_statically_included_foreign_item: |tcx, id| { matches!(tcx.native_library_kind(id), Some(NativeLibKind::Static {.. })) }, is_private_dep: |_tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); false }, native_library_kind: |tcx, id| { tcx.native_libraries(id.krate) .iter() .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib)) .find(|lib| { let fm_id = match lib.foreign_module { Some(id) => id, None => return false, }; let map = tcx.foreign_modules(id.krate); map.get(&fm_id) .expect("failed to find foreign module") .foreign_items .contains(&id) }) .map(|l| l.kind) }, native_libraries: |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); Lrc::new(native_libs::collect(tcx)) }, foreign_modules: |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); let modules: FxHashMap<DefId, ForeignModule> = foreign_modules::collect(tcx).into_iter().map(|m| (m.def_id, m)).collect(); Lrc::new(modules) }, // Returns a map from a sufficiently visible external item (i.e., an // external item that is visible from at least one local module) to a // sufficiently visible parent (considering modules that re-export the // external item to be parents). visible_parent_map: |tcx, ()| { use std::collections::hash_map::Entry; use std::collections::vec_deque::VecDeque; let mut visible_parent_map: DefIdMap<DefId> = Default::default(); // Issue 46112: We want the map to prefer the shortest // paths when reporting the path to an item. Therefore we // build up the map via a breadth-first search (BFS), // which naturally yields minimal-length paths. // // Note that it needs to be a BFS over the whole forest of // crates, not just each individual crate; otherwise you // only get paths that are locally minimal with respect to // whatever crate we happened to encounter first in this // traversal, but not globally minimal across all crates. let bfs_queue = &mut VecDeque::new(); // Preferring shortest paths alone does not guarantee a // deterministic result; so sort by crate num to avoid // hashtable iteration non-determinism. This only makes // things as deterministic as crate-nums assignment is, // which is to say, its not deterministic in general. But // we believe that libstd is consistently assigned crate // num 1, so it should be enough to resolve #46112. let mut crates: Vec<CrateNum> = (*tcx.crates(())).to_owned(); crates.sort(); for &cnum in crates.iter() { // Ignore crates without a corresponding local `extern crate` item. if tcx.missing_extern_crate_item(cnum) { continue; } bfs_queue.push_back(DefId { krate: cnum, index: CRATE_DEF_INDEX }); } // (restrict scope of mutable-borrow of `visible_parent_map`) { let visible_parent_map = &mut visible_parent_map; let mut add_child = |bfs_queue: &mut VecDeque<_>, child: &Export<hir::HirId>, parent: DefId| { if child.vis!= ty::Visibility::Public { return; } if let Some(child) = child.res.opt_def_id() { match visible_parent_map.entry(child) { Entry::Occupied(mut entry) => { // If `child` is defined in crate `cnum`, ensure // that it is mapped to a parent in `cnum`. if child.is_local() && entry.get().is_local() { entry.insert(parent); } } Entry::Vacant(entry) => { entry.insert(parent); bfs_queue.push_back(child); } } } }; while let Some(def) = bfs_queue.pop_front() { for child in tcx.item_children(def).iter() { add_child(bfs_queue, child, def); } } } visible_parent_map }, dependency_formats: |tcx, ()| Lrc::new(crate::dependency_format::calculate(tcx)), has_global_allocator: |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); CStore::from_tcx(tcx).has_global_allocator() }, postorder_cnums: |tcx, ()| { tcx.arena .alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(LOCAL_CRATE)) }, crates: |tcx, ()| tcx.arena.alloc_slice(&CStore::from_tcx(tcx).crates_untracked()), ..*providers }; } impl CStore { pub fn struct_field_names_untracked(&self, def: DefId, sess: &Session) -> Vec<Spanned<Symbol>> { self.get_crate_data(def.krate).get_struct_field_names(def.index, sess) } pub fn struct_field_visibilities_untracked(&self, def: DefId) -> Vec<Visibility> { self.get_crate_data(def.krate).get_struct_field_visibilities(def.index) } pub fn ctor_def_id_and_kind_untracked(&self, def: DefId) -> Option<(DefId, CtorKind)> { self.get_crate_data(def.krate).get_ctor_def_id(def.index).map(|ctor_def_id| { (ctor_def_id, self.get_crate_data(def.krate).get_ctor_kind(def.index))
}) } pub fn visibility_untracked(&self, def: DefId) -> Visibility { self.get_crate_data(def.krate).get_visibility(def.index) } pub fn item_children_untracked( &self, def_id: DefId, sess: &Session, ) -> Vec<Export<hir::HirId>> { let mut result = vec![]; self.get_crate_data(def_id.krate).each_child_of_item( def_id.index, |child| result.push(child), sess, ); result } pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro { let _prof_timer = sess.prof.generic_activity("metadata_load_macro"); let data = self.get_crate_data(id.krate); if data.root.is_proc_macro_crate() { return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess)); } let span = data.get_span(id.index, sess); let attrs = data.get_item_attrs(id.index, sess).collect(); let ident = data.item_ident(id.index, sess); LoadedMacro::MacroDef( ast::Item { ident, id: ast::DUMMY_NODE_ID, span, attrs, kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)), vis: ast::Visibility { span: span.shrink_to_lo(), kind: ast::VisibilityKind::Inherited, tokens: None, }, tokens: None, }, data.root.edition, ) } pub fn associated_item_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::AssocItem { self.get_crate_data(def.krate).get_associated_item(def.index, sess) } pub fn crate_source_untracked(&self, cnum: CrateNum) -> CrateSource { self.get_crate_data(cnum).source.clone() } pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span { self.get_crate_data(def_id.krate).get_span(def_id.index, sess) } pub fn def_kind(&self, def: DefId) -> DefKind { self.get_crate_data(def.krate).def_kind(def.index) } pub fn crates_untracked(&self) -> Vec<CrateNum> { let mut result = vec![];
random_line_split
cstore_impl.rs
id.index, tcx) } explicit_item_bounds => { cdata.get_explicit_item_bounds(def_id.index, tcx) } trait_def => { cdata.get_trait_def(def_id.index, tcx.sess) } adt_def => { cdata.get_adt_def(def_id.index, tcx) } adt_destructor => { let _ = cdata; tcx.calculate_dtor(def_id, |_,_| Ok(())) } variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) } associated_item_def_ids => { let mut result = SmallVec::<[_; 8]>::new(); cdata.each_child_of_item(def_id.index, |child| result.push(child.res.def_id()), tcx.sess); tcx.arena.alloc_slice(&result) } associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) } impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) } impl_polarity => { cdata.get_impl_polarity(def_id.index) } coerce_unsized_info => { cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| { bug!("coerce_unsized_info: `{:?}` is missing its info", def_id); }) } optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) } mir_for_ctfe => { tcx.arena.alloc(cdata.get_mir_for_ctfe(tcx, def_id.index)) } promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) } mir_abstract_const => { cdata.get_mir_abstract_const(tcx, def_id.index) } unused_generic_params => { cdata.get_unused_generic_params(def_id.index) } const_param_default => { tcx.mk_const(cdata.get_const_param_default(tcx, def_id.index)) } mir_const_qualif => { cdata.mir_const_qualif(def_id.index) } fn_sig => { cdata.fn_sig(def_id.index, tcx) } inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) } is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) } asyncness => { cdata.asyncness(def_id.index) } is_foreign_item => { cdata.is_foreign_item(def_id.index) } static_mutability => { cdata.static_mutability(def_id.index) } generator_kind => { cdata.generator_kind(def_id.index) } opt_def_kind => { Some(cdata.def_kind(def_id.index)) } def_span => { cdata.get_span(def_id.index, &tcx.sess) } def_ident_span => { cdata.try_item_ident(def_id.index, &tcx.sess).ok().map(|ident| ident.span) } lookup_stability => { cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s)) } lookup_const_stability => { cdata.get_const_stability(def_id.index).map(|s| tcx.intern_const_stability(s)) } lookup_deprecation_entry => { cdata.get_deprecation(def_id.index).map(DeprecationEntry::external) } item_attrs => { tcx.arena.alloc_from_iter( cdata.get_item_attrs(def_id.index, tcx.sess) ) } fn_arg_names => { cdata.get_fn_param_names(tcx, def_id.index) } rendered_const => { cdata.get_rendered_const(def_id.index) } impl_parent => { cdata.get_parent_impl(def_id.index) } trait_of_item => { cdata.get_trait_of_item(def_id.index) } is_mir_available => { cdata.is_item_mir_available(def_id.index) } is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) } dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) } is_private_dep => { cdata.private_dep } is_panic_runtime => { cdata.root.panic_runtime } is_compiler_builtins => { cdata.root.compiler_builtins } has_global_allocator => { cdata.root.has_global_allocator } has_panic_handler => { cdata.root.has_panic_handler } is_profiler_runtime => { cdata.root.profiler_runtime } panic_strategy => { cdata.root.panic_strategy } extern_crate => { let r = *cdata.extern_crate.lock(); r.map(|c| &*tcx.arena.alloc(c)) } is_no_builtins => { cdata.root.no_builtins } symbol_mangling_version => { cdata.root.symbol_mangling_version } impl_defaultness => { cdata.get_impl_defaultness(def_id.index) } impl_constness => { cdata.get_impl_constness(def_id.index) } reachable_non_generics => { let reachable_non_generics = tcx .exported_symbols(cdata.cnum) .iter() .filter_map(|&(exported_symbol, export_level)| { if let ExportedSymbol::NonGeneric(def_id) = exported_symbol { Some((def_id, export_level)) } else { None } }) .collect(); reachable_non_generics } native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) } foreign_modules => { cdata.get_foreign_modules(tcx) } crate_hash => { cdata.root.hash } crate_host_hash => { cdata.host_hash } crate_name => { cdata.root.name } extra_filename => { cdata.root.extra_filename.clone() } implementations_of_trait => { cdata.get_implementations_for_trait(tcx, Some(other)) } all_trait_implementations => { cdata.get_implementations_for_trait(tcx, None) } visibility => { cdata.get_visibility(def_id.index) } dep_kind => { let r = *cdata.dep_kind.lock(); r } item_children => { let mut result = SmallVec::<[_; 8]>::new(); cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess); tcx.arena.alloc_slice(&result) } defined_lib_features => { cdata.get_lib_features(tcx) } defined_lang_items => { cdata.get_lang_items(tcx) } diagnostic_items => { cdata.get_diagnostic_items() } missing_lang_items => { cdata.get_missing_lang_items(tcx) } missing_extern_crate_item => { let r = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if!extern_crate.is_direct()); r } used_crate_source => { Lrc::new(cdata.source.clone()) } exported_symbols => { let syms = cdata.exported_symbols(tcx); // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want // to block export of generics from dylibs, but we must fix // rust-lang/rust#65890 before we can do that robustly. syms } crate_extern_paths => { cdata.source().paths().cloned().collect() } expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) } } pub fn provide(providers: &mut Providers) { // FIXME(#44234) - almost all of these queries have no sub-queries and // therefore no actual inputs, they're just reading tables calculated in // resolve! Does this work? Unsure! That's what the issue is about *providers = Providers { allocator_kind: |tcx, ()| CStore::from_tcx(tcx).allocator_kind(), is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) { Some( NativeLibKind::Dylib {.. } | NativeLibKind::RawDylib | NativeLibKind::Unspecified, ) => true, _ => false, }, is_statically_included_foreign_item: |tcx, id| { matches!(tcx.native_library_kind(id), Some(NativeLibKind::Static {.. })) }, is_private_dep: |_tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); false }, native_library_kind: |tcx, id| { tcx.native_libraries(id.krate) .iter() .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib)) .find(|lib| { let fm_id = match lib.foreign_module { Some(id) => id, None => return false, }; let map = tcx.foreign_modules(id.krate); map.get(&fm_id) .expect("failed to find foreign module") .foreign_items .contains(&id) }) .map(|l| l.kind) }, native_libraries: |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); Lrc::new(native_libs::collect(tcx)) }, foreign_modules: |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); let modules: FxHashMap<DefId, ForeignModule> = foreign_modules::collect(tcx).into_iter().map(|m| (m.def_id, m)).collect(); Lrc::new(modules) }, // Returns a map from a sufficiently visible external item (i.e., an // external item that is visible from at least one local module) to a // sufficiently visible parent (considering modules that re-export the // external item to be parents). visible_parent_map: |tcx, ()| { use std::collections::hash_map::Entry; use std::collections::vec_deque::VecDeque; let mut visible_parent_map: DefIdMap<DefId> = Default::default(); // Issue 46112: We want the map to prefer the shortest // paths when reporting the path to an item. Therefore we // build up the map via a breadth-first search (BFS), // which naturally yields minimal-length paths. // // Note that it needs to be a BFS over the whole forest of // crates, not just each individual crate; otherwise you // only get paths that are locally minimal with respect to // whatever crate we happened to encounter first in this // traversal, but not globally minimal across all crates. let bfs_queue = &mut VecDeque::new(); // Preferring shortest paths alone does not guarantee a // deterministic result; so sort by crate num to avoid // hashtable iteration non-determinism. This only makes // things as deterministic as crate-nums assignment is, // which is to say, its not deterministic in general. But // we believe that libstd is consistently assigned crate // num 1, so it should be enough to resolve #46112. let mut crates: Vec<CrateNum> = (*tcx.crates(())).to_owned(); crates.sort(); for &cnum in crates.iter() { // Ignore crates without a corresponding local `extern crate` item. if tcx.missing_extern_crate_item(cnum) { continue; } bfs_queue.push_back(DefId { krate: cnum, index: CRATE_DEF_INDEX }); } // (restrict scope of mutable-borrow of `visible_parent_map`) { let visible_parent_map = &mut visible_parent_map; let mut add_child = |bfs_queue: &mut VecDeque<_>, child: &Export<hir::HirId>, parent: DefId| { if child.vis!= ty::Visibility::Public { return; } if let Some(child) = child.res.opt_def_id() { match visible_parent_map.entry(child) { Entry::Occupied(mut entry) => { // If `child` is defined in crate `cnum`, ensure // that it is mapped to a parent in `cnum`. if child.is_local() && entry.get().is_local() { entry.insert(parent); } } Entry::Vacant(entry) => { entry.insert(parent); bfs_queue.push_back(child); } } } }; while let Some(def) = bfs_queue.pop_front() { for child in tcx.item_children(def).iter() { add_child(bfs_queue, child, def); } } } visible_parent_map }, dependency_formats: |tcx, ()| Lrc::new(crate::dependency_format::calculate(tcx)), has_global_allocator: |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); CStore::from_tcx(tcx).has_global_allocator() }, postorder_cnums: |tcx, ()| { tcx.arena .alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(LOCAL_CRATE)) }, crates: |tcx, ()| tcx.arena.alloc_slice(&CStore::from_tcx(tcx).crates_untracked()), ..*providers }; } impl CStore { pub fn struct_field_names_untracked(&self, def: DefId, sess: &Session) -> Vec<Spanned<Symbol>> { self.get_crate_data(def.krate).get_struct_field_names(def.index, sess) } pub fn struct_field_visibilities_untracked(&self, def: DefId) -> Vec<Visibility> { self.get_crate_data(def.krate).get_struct_field_visibilities(def.index) } pub fn ctor_def_id_and_kind_untracked(&self, def: DefId) -> Option<(DefId, CtorKind)> { self.get_crate_data(def.krate).get_ctor_def_id(def.index).map(|ctor_def_id| { (ctor_def_id, self.get_crate_data(def.krate).get_ctor_kind(def.index)) }) } pub fn visibility_untracked(&self, def: DefId) -> Visibility { self.get_crate_data(def.krate).get_visibility(def.index) } pub fn item_children_untracked( &self, def_id: DefId, sess: &Session, ) -> Vec<Export<hir::HirId>> { let mut result = vec![]; self.get_crate_data(def_id.krate).each_child_of_item( def_id.index, |child| result.push(child), sess, ); result } pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro { let _prof_timer = sess.prof.generic_activity("metadata_load_macro"); let data = self.get_crate_data(id.krate); if data.root.is_proc_macro_crate() { return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess)); } let span = data.get_span(id.index, sess); let attrs = data.get_item_attrs(id.index, sess).collect(); let ident = data.item_ident(id.index, sess); LoadedMacro::MacroDef( ast::Item { ident, id: ast::DUMMY_NODE_ID, span, attrs, kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)), vis: ast::Visibility { span: span.shrink_to_lo(), kind: ast::VisibilityKind::Inherited, tokens: None, }, tokens: None, }, data.root.edition, ) } pub fn associated_item_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::AssocItem { self.get_crate_data(def.krate).get_associated_item(def.index, sess) } pub fn crate_source_untracked(&self, cnum: CrateNum) -> CrateSource { self.get_crate_data(cnum).source.clone() } pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span { self.get_crate_data(def_id.krate).get_span(def_id.index, sess) } pub fn def_kind(&self, def: DefId) -> DefKind { self.get_crate_data(def.krate).def_kind(def.index) } pub fn crates_untracked(&self) -> Vec<CrateNum> { let mut result = vec![]; self.iter_crate_data(|cnum, _| result.push(cnum)); result } pub fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize { self.get_crate_data(def_id.krate).get_generics(def_id.index, sess).own_counts().lifetimes } pub fn module_expansion_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId { self.get_crate_data(def_id.krate).module_expansion(def_id.index, sess) } /// Only public-facing way to traverse all the definitions in a non-local crate. /// Critically useful for this third-party project: <https://github.com/hacspec/hacspec>. /// See <https://github.com/rust-lang/rust/pull/85889> for context. pub fn num_def_ids_untracked(&self, cnum: CrateNum) -> usize { self.get_crate_data(cnum).num_def_ids() } pub fn item_attrs(&self, def_id: DefId, sess: &Session) -> Vec<ast::Attribute> { self.get_crate_data(def_id.krate).get_item_attrs(def_id.index, sess).collect() } pub fn get_proc_macro_quoted_span_untracked( &self, cnum: CrateNum, id: usize, sess: &Session, ) -> Span { self.get_crate_data(cnum).get_proc_macro_quoted_span(id, sess) } } impl CrateStore for CStore { fn as_any(&self) -> &dyn Any { self } fn crate_name(&self, cnum: CrateNum) -> Symbol { self.get_crate_data(cnum).root.name } fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId { self.get_crate_data(cnum).root.stable_crate_id } /// Returns the `DefKey` for a given `DefId`. This indicates the /// parent `DefId` as well as some idea of what kind of data the /// `DefId` refers to. fn def_key(&self, def: DefId) -> DefKey { self.get_crate_data(def.krate).def_key(def.index) } fn def_path(&self, def: DefId) -> DefPath { self.get_crate_data(def.krate).def_path(def.index) } fn def_path_hash(&self, def: DefId) -> DefPathHash { self.get_crate_data(def.krate).def_path_hash(def.index) } // See `CrateMetadataRef::def_path_hash_to_def_id` for more details fn
def_path_hash_to_def_id
identifier_name
issue-9957.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. pub extern crate std; //~ ERROR: `pub` visibility is not allowed priv extern crate std; //~ ERROR: unnecessary visibility qualifier extern crate std; pub use std::bool; priv use std::bool; //~ ERROR: unnecessary visibility qualifier use std::bool; fn main()
{ pub use std::bool; //~ ERROR: imports in functions are never reachable priv use std::bool; //~ ERROR: unnecessary visibility qualifier use std::bool; }
identifier_body
issue-9957.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. pub extern crate std; //~ ERROR: `pub` visibility is not allowed priv extern crate std; //~ ERROR: unnecessary visibility qualifier extern crate std; pub use std::bool; priv use std::bool; //~ ERROR: unnecessary visibility qualifier use std::bool; fn
() { pub use std::bool; //~ ERROR: imports in functions are never reachable priv use std::bool; //~ ERROR: unnecessary visibility qualifier use std::bool; }
main
identifier_name
issue-9957.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
// except according to those terms. pub extern crate std; //~ ERROR: `pub` visibility is not allowed priv extern crate std; //~ ERROR: unnecessary visibility qualifier extern crate std; pub use std::bool; priv use std::bool; //~ ERROR: unnecessary visibility qualifier use std::bool; fn main() { pub use std::bool; //~ ERROR: imports in functions are never reachable priv use std::bool; //~ ERROR: unnecessary visibility qualifier use std::bool; }
// option. This file may not be copied, modified, or distributed
random_line_split
assign-to-static-within-other-static.rs
// Copyright 2018 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. // New test for #53818: modifying static memory at compile-time is not allowed. // The test should never compile successfully #![feature(const_raw_ptr_deref)] #![feature(const_let)] use std::cell::UnsafeCell; static mut FOO: u32 = 42; static BOO: () = unsafe { FOO = 5; //~ ERROR cannot mutate statics in the initializer of another static }; fn
() {}
main
identifier_name
assign-to-static-within-other-static.rs
// Copyright 2018 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. // New test for #53818: modifying static memory at compile-time is not allowed. // The test should never compile successfully #![feature(const_raw_ptr_deref)] #![feature(const_let)] use std::cell::UnsafeCell; static mut FOO: u32 = 42; static BOO: () = unsafe { FOO = 5; //~ ERROR cannot mutate statics in the initializer of another static }; fn main()
{}
identifier_body
assign-to-static-within-other-static.rs
// Copyright 2018 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. // New test for #53818: modifying static memory at compile-time is not allowed. // The test should never compile successfully
static mut FOO: u32 = 42; static BOO: () = unsafe { FOO = 5; //~ ERROR cannot mutate statics in the initializer of another static }; fn main() {}
#![feature(const_raw_ptr_deref)] #![feature(const_let)] use std::cell::UnsafeCell;
random_line_split
simple.rs
extern crate escposify; extern crate tempfile; use std::io; use escposify::device::File; use escposify::printer::Printer; use tempfile::NamedTempFileOptions; fn main() -> io::Result<()>
{ let tempf = NamedTempFileOptions::new().create().unwrap(); let file = File::from(tempf); let mut printer = Printer::new(file, None, None); printer .chain_font("C")? .chain_align("lt")? .chain_style("bu")? .chain_size(0, 0)? .chain_text("The quick brown fox jumps over the lazy dog")? .chain_text("敏捷的棕色狐狸跳过懒狗")? .chain_barcode("12345678", "EAN8", "", "", 0, 0)? .chain_feed(1)? .chain_cut(false)? .flush() }
identifier_body
simple.rs
extern crate escposify; extern crate tempfile; use std::io; use escposify::device::File; use escposify::printer::Printer;
let tempf = NamedTempFileOptions::new().create().unwrap(); let file = File::from(tempf); let mut printer = Printer::new(file, None, None); printer .chain_font("C")? .chain_align("lt")? .chain_style("bu")? .chain_size(0, 0)? .chain_text("The quick brown fox jumps over the lazy dog")? .chain_text("敏捷的棕色狐狸跳过懒狗")? .chain_barcode("12345678", "EAN8", "", "", 0, 0)? .chain_feed(1)? .chain_cut(false)? .flush() }
use tempfile::NamedTempFileOptions; fn main() -> io::Result<()> {
random_line_split
simple.rs
extern crate escposify; extern crate tempfile; use std::io; use escposify::device::File; use escposify::printer::Printer; use tempfile::NamedTempFileOptions; fn
() -> io::Result<()> { let tempf = NamedTempFileOptions::new().create().unwrap(); let file = File::from(tempf); let mut printer = Printer::new(file, None, None); printer .chain_font("C")? .chain_align("lt")? .chain_style("bu")? .chain_size(0, 0)? .chain_text("The quick brown fox jumps over the lazy dog")? .chain_text("敏捷的棕色狐狸跳过懒狗")? .chain_barcode("12345678", "EAN8", "", "", 0, 0)? .chain_feed(1)? .chain_cut(false)? .flush() }
main
identifier_name
sepcomp-lib-lto.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. // run-pass // Check that we can use `-C lto` when linking against libraries that were // separately compiled. // aux-build:sepcomp_lib.rs // compile-flags: -C lto -g // no-prefer-dynamic extern crate sepcomp_lib; use sepcomp_lib::a::one; use sepcomp_lib::b::two; use sepcomp_lib::c::three; fn main()
{ assert_eq!(one(), 1); assert_eq!(two(), 2); assert_eq!(three(), 3); }
identifier_body
sepcomp-lib-lto.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. // run-pass // Check that we can use `-C lto` when linking against libraries that were // separately compiled. // aux-build:sepcomp_lib.rs // compile-flags: -C lto -g // no-prefer-dynamic extern crate sepcomp_lib; use sepcomp_lib::a::one; use sepcomp_lib::b::two; use sepcomp_lib::c::three; fn main() { assert_eq!(one(), 1); assert_eq!(two(), 2); assert_eq!(three(), 3); }
//
random_line_split
sepcomp-lib-lto.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. // run-pass // Check that we can use `-C lto` when linking against libraries that were // separately compiled. // aux-build:sepcomp_lib.rs // compile-flags: -C lto -g // no-prefer-dynamic extern crate sepcomp_lib; use sepcomp_lib::a::one; use sepcomp_lib::b::two; use sepcomp_lib::c::three; fn
() { assert_eq!(one(), 1); assert_eq!(two(), 2); assert_eq!(three(), 3); }
main
identifier_name
self-without-lifetime-constraint.rs
use std::error::Error; use std::fmt; #[derive(Copy, Clone, Debug, PartialEq)] pub enum ValueRef<'a> { Null, Integer(i64), Real(f64), Text(&'a [u8]), Blob(&'a [u8]), } impl<'a> ValueRef<'a> { pub fn as_str(&self) -> FromSqlResult<&'a str, &'a &'a str> { match *self { ValueRef::Text(t) => { std::str::from_utf8(t).map_err(|_| FromSqlError::InvalidType).map(|x| (x, &x)) } _ => Err(FromSqlError::InvalidType), } } } #[derive(Debug)] #[non_exhaustive] pub enum FromSqlError { InvalidType } impl fmt::Display for FromSqlError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "InvalidType") } } impl Error for FromSqlError {} pub type FromSqlResult<T, K> = Result<(T, K), FromSqlError>; pub trait FromSql: Sized { fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self, &Self>; } impl FromSql for &str { fn
(value: ValueRef<'_>) -> FromSqlResult<&str, &&str> { //~^ ERROR `impl` item signature doesn't match `trait` item signature value.as_str() } } pub fn main() { println!("{}", "Hello World"); }
column_result
identifier_name
self-without-lifetime-constraint.rs
use std::error::Error; use std::fmt; #[derive(Copy, Clone, Debug, PartialEq)] pub enum ValueRef<'a> { Null, Integer(i64), Real(f64), Text(&'a [u8]), Blob(&'a [u8]), } impl<'a> ValueRef<'a> { pub fn as_str(&self) -> FromSqlResult<&'a str, &'a &'a str>
} #[derive(Debug)] #[non_exhaustive] pub enum FromSqlError { InvalidType } impl fmt::Display for FromSqlError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "InvalidType") } } impl Error for FromSqlError {} pub type FromSqlResult<T, K> = Result<(T, K), FromSqlError>; pub trait FromSql: Sized { fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self, &Self>; } impl FromSql for &str { fn column_result(value: ValueRef<'_>) -> FromSqlResult<&str, &&str> { //~^ ERROR `impl` item signature doesn't match `trait` item signature value.as_str() } } pub fn main() { println!("{}", "Hello World"); }
{ match *self { ValueRef::Text(t) => { std::str::from_utf8(t).map_err(|_| FromSqlError::InvalidType).map(|x| (x, &x)) } _ => Err(FromSqlError::InvalidType), } }
identifier_body
self-without-lifetime-constraint.rs
use std::error::Error; use std::fmt; #[derive(Copy, Clone, Debug, PartialEq)] pub enum ValueRef<'a> { Null, Integer(i64), Real(f64), Text(&'a [u8]), Blob(&'a [u8]), } impl<'a> ValueRef<'a> { pub fn as_str(&self) -> FromSqlResult<&'a str, &'a &'a str> { match *self { ValueRef::Text(t) => { std::str::from_utf8(t).map_err(|_| FromSqlError::InvalidType).map(|x| (x, &x)) } _ => Err(FromSqlError::InvalidType), } } } #[derive(Debug)] #[non_exhaustive] pub enum FromSqlError { InvalidType } impl fmt::Display for FromSqlError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "InvalidType") } } impl Error for FromSqlError {} pub type FromSqlResult<T, K> = Result<(T, K), FromSqlError>; pub trait FromSql: Sized { fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self, &Self>; } impl FromSql for &str { fn column_result(value: ValueRef<'_>) -> FromSqlResult<&str, &&str> { //~^ ERROR `impl` item signature doesn't match `trait` item signature value.as_str() }
} pub fn main() { println!("{}", "Hello World"); }
random_line_split
mod.rs
// The MIT License (MIT) // // Copyright (c) 2016-2022 Ivan Dejanovic // // 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. pub struct Instructions { pub halt: &'static str, pub in_n: &'static str, pub out_n: &'static str, pub in_s: &'static str, pub out_s: &'static str, pub add: &'static str, pub sub: &'static str, pub mul: &'static str, pub div: &'static str,
pub ld: &'static str, pub st: &'static str, pub jmp: &'static str, pub jgr: &'static str, pub jge: &'static str, pub jeq: &'static str, pub jne: &'static str, pub jle: &'static str, pub jls: &'static str, } pub const INSTRUCTIONS: Instructions = Instructions { halt: "HALT", in_n: "IN_N", out_n: "OUT_N", in_s: "IN_S", out_s: "OUT_S", add: "ADD", sub: "SUB", mul: "MUL", div: "DIV", con: "CON", push: "PUSH", pop: "POP", ld: "LD", st: "ST", jmp: "JMP", jgr: "JGR", jge: "JGE", jeq: "JEQ", jne: "JNE", jle: "JLE", jls: "JLS", };
pub con: &'static str, pub push: &'static str, pub pop: &'static str,
random_line_split
mod.rs
// The MIT License (MIT) // // Copyright (c) 2016-2022 Ivan Dejanovic // // 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. pub struct
{ pub halt: &'static str, pub in_n: &'static str, pub out_n: &'static str, pub in_s: &'static str, pub out_s: &'static str, pub add: &'static str, pub sub: &'static str, pub mul: &'static str, pub div: &'static str, pub con: &'static str, pub push: &'static str, pub pop: &'static str, pub ld: &'static str, pub st: &'static str, pub jmp: &'static str, pub jgr: &'static str, pub jge: &'static str, pub jeq: &'static str, pub jne: &'static str, pub jle: &'static str, pub jls: &'static str, } pub const INSTRUCTIONS: Instructions = Instructions { halt: "HALT", in_n: "IN_N", out_n: "OUT_N", in_s: "IN_S", out_s: "OUT_S", add: "ADD", sub: "SUB", mul: "MUL", div: "DIV", con: "CON", push: "PUSH", pop: "POP", ld: "LD", st: "ST", jmp: "JMP", jgr: "JGR", jge: "JGE", jeq: "JEQ", jne: "JNE", jle: "JLE", jls: "JLS", };
Instructions
identifier_name
particle.rs
use geometry::{Advance, Position, Vector}; use geometry_derive::{Advance, Position}; /// A model representing a particle /// /// Particles are visible objects that have a time to live and move around /// in a given direction until their time is up. They are spawned when the /// player or an enemy is killed #[derive(Advance, Position)] pub struct Particle { pub vector: Vector, pub ttl: f32, } impl Particle { /// Create a particle with the given vector and time to live in seconds pub fn new(vector: Vector, ttl: f32) -> Particle { Particle { vector: vector, ttl: ttl, } } /// Update the particle pub fn
(&mut self, elapsed_time: f32) { self.ttl -= elapsed_time; let speed = 500.0 * self.ttl * self.ttl; self.advance(elapsed_time * speed); } }
update
identifier_name
particle.rs
use geometry::{Advance, Position, Vector}; use geometry_derive::{Advance, Position}; /// A model representing a particle /// /// Particles are visible objects that have a time to live and move around /// in a given direction until their time is up. They are spawned when the /// player or an enemy is killed #[derive(Advance, Position)] pub struct Particle {
impl Particle { /// Create a particle with the given vector and time to live in seconds pub fn new(vector: Vector, ttl: f32) -> Particle { Particle { vector: vector, ttl: ttl, } } /// Update the particle pub fn update(&mut self, elapsed_time: f32) { self.ttl -= elapsed_time; let speed = 500.0 * self.ttl * self.ttl; self.advance(elapsed_time * speed); } }
pub vector: Vector, pub ttl: f32, }
random_line_split
particle.rs
use geometry::{Advance, Position, Vector}; use geometry_derive::{Advance, Position}; /// A model representing a particle /// /// Particles are visible objects that have a time to live and move around /// in a given direction until their time is up. They are spawned when the /// player or an enemy is killed #[derive(Advance, Position)] pub struct Particle { pub vector: Vector, pub ttl: f32, } impl Particle { /// Create a particle with the given vector and time to live in seconds pub fn new(vector: Vector, ttl: f32) -> Particle { Particle { vector: vector, ttl: ttl, } } /// Update the particle pub fn update(&mut self, elapsed_time: f32)
}
{ self.ttl -= elapsed_time; let speed = 500.0 * self.ttl * self.ttl; self.advance(elapsed_time * speed); }
identifier_body
main.rs
/* Este programa genera soluciones al azar para el problema de las reinas */ extern crate rand; use rand::Rng; use rand::distributions::{IndependentSample, Range}; use std::io; use std::io::prelude::*; fn pause() { let mut stdin = io::stdin(); let mut stdout = io::stdout(); // We want the cursor to stay at the end of the line, so we print without a newline and flush manually. write!(stdout, "Press any key to continue...").unwrap(); stdout.flush().unwrap(); // Read a single byte and discard let _ = stdin.read(&mut [0u8]).unwrap(); } fn main() { let rep = 10000; let mut vector_of_queens = Vec::<(isize,isize)>::with_capacity(8); let step = Range::new(1, 9); let mut rng = rand::thread_rng(); get_random_vector(& mut vector_of_queens, & step, & mut rng); let mut collisions = get_collisions( & vector_of_queens ); let mut mincollisions = collisions; for _ in 0..rep { collisions = get_collisions(& vector_of_queens); if collisions < mincollisions { mincollisions = collisions; println!("{} con {:?}", mincollisions, vector_of_queens); } get_random_vector(& mut vector_of_queens, & step, & mut rng); } println!("TERMINADO"); pause(); } fn get_collisions (vec : & Vec<(isize,isize)> ) -> isize { let mut collisions = 0; for a in 0..8 { for b in a+1.. 8 { if vec[a].0 == vec[b].0 { collisions += 1; } if vec[a].1 == vec[b].1 { collisions += 1; } if ( vec[a].0 - vec[b].1 ).abs() == ( vec[a].1 - vec[b].0 ).abs() { collisions += 1; } } } collisions } fn get_random_vector(vec: & mut Vec<(isize,isize)>, step: & Range<isize>, mut rng: & mut Rng )
{ vec.clear(); for _ in 0..8 { vec.push((step.ind_sample(&mut rng),step.ind_sample(&mut rng))); } }
identifier_body
main.rs
/* Este programa genera soluciones al azar para el problema de las reinas */ extern crate rand; use rand::Rng; use rand::distributions::{IndependentSample, Range}; use std::io; use std::io::prelude::*; fn pause() { let mut stdin = io::stdin(); let mut stdout = io::stdout(); // We want the cursor to stay at the end of the line, so we print without a newline and flush manually. write!(stdout, "Press any key to continue...").unwrap(); stdout.flush().unwrap(); // Read a single byte and discard let _ = stdin.read(&mut [0u8]).unwrap(); } fn main() { let rep = 10000; let mut vector_of_queens = Vec::<(isize,isize)>::with_capacity(8); let step = Range::new(1, 9); let mut rng = rand::thread_rng(); get_random_vector(& mut vector_of_queens, & step, & mut rng); let mut collisions = get_collisions( & vector_of_queens ); let mut mincollisions = collisions; for _ in 0..rep { collisions = get_collisions(& vector_of_queens); if collisions < mincollisions { mincollisions = collisions; println!("{} con {:?}", mincollisions, vector_of_queens); } get_random_vector(& mut vector_of_queens, & step, & mut rng); } println!("TERMINADO"); pause(); } fn
(vec : & Vec<(isize,isize)> ) -> isize { let mut collisions = 0; for a in 0..8 { for b in a+1.. 8 { if vec[a].0 == vec[b].0 { collisions += 1; } if vec[a].1 == vec[b].1 { collisions += 1; } if ( vec[a].0 - vec[b].1 ).abs() == ( vec[a].1 - vec[b].0 ).abs() { collisions += 1; } } } collisions } fn get_random_vector(vec: & mut Vec<(isize,isize)>, step: & Range<isize>, mut rng: & mut Rng ) { vec.clear(); for _ in 0..8 { vec.push((step.ind_sample(&mut rng),step.ind_sample(&mut rng))); } }
get_collisions
identifier_name
main.rs
/* Este programa genera soluciones al azar para el problema de las reinas */ extern crate rand; use rand::Rng; use rand::distributions::{IndependentSample, Range}; use std::io; use std::io::prelude::*; fn pause() { let mut stdin = io::stdin(); let mut stdout = io::stdout(); // We want the cursor to stay at the end of the line, so we print without a newline and flush manually. write!(stdout, "Press any key to continue...").unwrap(); stdout.flush().unwrap(); // Read a single byte and discard let _ = stdin.read(&mut [0u8]).unwrap(); } fn main() { let rep = 10000; let mut vector_of_queens = Vec::<(isize,isize)>::with_capacity(8); let step = Range::new(1, 9); let mut rng = rand::thread_rng(); get_random_vector(& mut vector_of_queens, & step, & mut rng); let mut collisions = get_collisions( & vector_of_queens ); let mut mincollisions = collisions; for _ in 0..rep { collisions = get_collisions(& vector_of_queens); if collisions < mincollisions { mincollisions = collisions; println!("{} con {:?}", mincollisions, vector_of_queens); } get_random_vector(& mut vector_of_queens, & step, & mut rng); } println!("TERMINADO"); pause(); } fn get_collisions (vec : & Vec<(isize,isize)> ) -> isize { let mut collisions = 0; for a in 0..8 { for b in a+1.. 8 { if vec[a].0 == vec[b].0 { collisions += 1; } if vec[a].1 == vec[b].1
if ( vec[a].0 - vec[b].1 ).abs() == ( vec[a].1 - vec[b].0 ).abs() { collisions += 1; } } } collisions } fn get_random_vector(vec: & mut Vec<(isize,isize)>, step: & Range<isize>, mut rng: & mut Rng ) { vec.clear(); for _ in 0..8 { vec.push((step.ind_sample(&mut rng),step.ind_sample(&mut rng))); } }
{ collisions += 1; }
conditional_block
main.rs
/* Este programa genera soluciones al azar para el problema de las reinas */ extern crate rand; use rand::Rng; use rand::distributions::{IndependentSample, Range}; use std::io; use std::io::prelude::*; fn pause() { let mut stdin = io::stdin(); let mut stdout = io::stdout(); // We want the cursor to stay at the end of the line, so we print without a newline and flush manually. write!(stdout, "Press any key to continue...").unwrap(); stdout.flush().unwrap();
fn main() { let rep = 10000; let mut vector_of_queens = Vec::<(isize,isize)>::with_capacity(8); let step = Range::new(1, 9); let mut rng = rand::thread_rng(); get_random_vector(& mut vector_of_queens, & step, & mut rng); let mut collisions = get_collisions( & vector_of_queens ); let mut mincollisions = collisions; for _ in 0..rep { collisions = get_collisions(& vector_of_queens); if collisions < mincollisions { mincollisions = collisions; println!("{} con {:?}", mincollisions, vector_of_queens); } get_random_vector(& mut vector_of_queens, & step, & mut rng); } println!("TERMINADO"); pause(); } fn get_collisions (vec : & Vec<(isize,isize)> ) -> isize { let mut collisions = 0; for a in 0..8 { for b in a+1.. 8 { if vec[a].0 == vec[b].0 { collisions += 1; } if vec[a].1 == vec[b].1 { collisions += 1; } if ( vec[a].0 - vec[b].1 ).abs() == ( vec[a].1 - vec[b].0 ).abs() { collisions += 1; } } } collisions } fn get_random_vector(vec: & mut Vec<(isize,isize)>, step: & Range<isize>, mut rng: & mut Rng ) { vec.clear(); for _ in 0..8 { vec.push((step.ind_sample(&mut rng),step.ind_sample(&mut rng))); } }
// Read a single byte and discard let _ = stdin.read(&mut [0u8]).unwrap(); }
random_line_split
build.rs
/*! The build script has two primary jobs: 1. Do code generation. Currently, this consists of turning `data/winver.json` into an appropriate `enum`. 2. Tell Cargo to link against Clang. */ extern crate itertools; extern crate serde; use std::env; use std::fs; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; use itertools::Itertools; /// `pj` as in "path join". macro_rules! pj { ($p0:expr, $($ps:expr),*) => { { let mut pb = PathBuf::from($p0); $(pb.push($ps);)* pb } } } fn main() { let self_path = pj!(get_manifest_dir(), "build.rs"); let gen_path = make_gen_dir(); let data_path = get_data_dir(); { let winver_rs = pj!(&gen_path, "winver.rs"); let winver_json = pj!(&data_path, "winver.json"); if is_target_stale(&winver_rs, &[&self_path, &winver_json]) { let mut f = fs::File::create(winver_rs).ok().expect("create winver.rs"); gen_winver_enum(&mut f, &read_file_str(winver_json)); f.flush().unwrap(); } } link_clang(); } fn make_gen_dir() -> PathBuf { let gen_path = pj!(get_out_dir(), "src"); let _ = fs::create_dir(&gen_path).ok(); gen_path } fn get_data_dir() -> PathBuf { pj!(get_manifest_dir(), "data") } #[cfg(windows)] fn is_target_stale<P0, P1>(target: P0, dep_paths: &[P1]) -> bool where P0: AsRef<Path>, P1: AsRef<Path> { use std::os::windows::fs::MetadataExt; let target_ts = fs::metadata(&target).map(|md| md.last_write_time()).unwrap_or(0); dep_paths.iter().any(|dp| fs::metadata(dp).map(|md| md.last_write_time()).unwrap_or(1) > target_ts) } fn gen_winver_enum<W>(out: &mut W, json_str: &str) where W: io::Write { use std::collections::HashMap; use serde::json; println!("# gen_winver_enum(..)"); let root: HashMap<String, String> = json::from_str(json_str).unwrap(); // First, parse those version numbers! let root: HashMap<_, u32> = root.into_iter() .map(|(k, v)| (k, parse_int(&v))) .collect(); // Make the map of "primary" names. let primary: HashMap<&str, u32> = root.iter() .filter(|&(ref k, _)|!k.starts_with("*")) .map(|(k, v)| (&**k, *v)) .collect(); // Make the reverse lookup map. let reverse: HashMap<u32, &str> = primary.iter().map(|(k, v)| (*v, *k)).collect(); assert_eq!(primary.len(), reverse.len()); // Make the map of non-primary aliases. let mut aliases: Vec<(&str, u32)> = root.iter().filter(|&(k, _)| k.starts_with("*")) .map(|(k, v)| (&k[1..], *v)).collect(); aliases.sort(); // Get a sorted list of versions. let mut vers: Vec<u32> = primary.values().cloned().collect(); vers.sort(); // Use that to get a "next" version map. let next_ver_iter = vers.iter().cloned().skip(1).chain(Some(vers.last().unwrap() + 1).into_iter()); let next_ver: HashMap<u32, u32> = vers.iter().cloned().zip(next_ver_iter).collect(); // Generate the enum. write!(out, r#" #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] #[repr(u32)] pub enum WinVersion {{ {primary_variants} }} impl WinVersion {{ {alias_consts} pub const AFTER_LAST: u32 = 0x{guard_const:08x}; pub fn from_name(name: &str) -> Option<WinVersion> {{ match name {{ {from_names} _ => None }} }} pub fn next_version(self) -> Option<WinVersion> {{ match self {{ {next_versions} _ => None }} }} pub fn from_u32_round_up(v: u32) -> Option<WinVersion> {{ {from_u32_round_ups} None }} }} "#, primary_variants = vers.iter().cloned() .map(|v| format!(" {:<8} = 0x{:08x},", reverse[&v], v)) .join("\n"), alias_consts = aliases.iter() .map(|&(k, v)| format!(" pub const {:<7}: WinVersion = WinVersion::{};", k, reverse[&v])) .join("\n"), guard_const = next_ver[vers.last().unwrap()], from_names = primary.iter().map(|(&k, &v)| (k, v)).chain(aliases.iter().map(|&(k, v)| (k, v))) .map(|(k, v)| format!(" \"{}\" => Some(WinVersion::{}),", k, reverse[&v])) .join("\n"), next_versions = vers.iter().cloned() .filter(|&k| reverse.contains_key(&next_ver[&k])) .map(|k| format!(" WinVersion::{:<8} => Some(WinVersion::{}),", reverse[&k], reverse[&next_ver[&k]])) .join("\n"), from_u32_round_ups = vers.iter().cloned() .map(|k| format!(" if v <= 0x{:08x} {{ return Some(WinVersion::{}); }}", k, reverse[&k])) .join("\n"), ).unwrap(); } fn link_clang() { let manifest_path = get_manifest_dir(); let bin_dir = pj!(manifest_path, "bin", get_target()); println!("cargo:rustc-link-lib=clang"); println!("cargo:rustc-link-search={}", bin_dir.to_str().unwrap()); } fn
(s: &str) -> u32 { if s.starts_with("0x") || s.starts_with("0X") { u32::from_str_radix(&s[2..], 16).unwrap() } else { s.parse().unwrap() } } fn read_file_str<P>(path: P) -> String where P: AsRef<Path> + ::std::fmt::Debug { let mut s = String::new(); let _ = fs::File::open(&path).ok().expect(&format!("open {:?}", path)) .read_to_string(&mut s).ok().expect(&format!("read from {:?}", path)); s } fn get_manifest_dir() -> PathBuf { env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".into()).into() } fn get_out_dir() -> PathBuf { env::var("OUT_DIR").ok().expect("OUT_DIR *must* be set").into() } fn get_target() -> PathBuf { env::var("TARGET").unwrap_or_else(|_| "i686-pc-windows-gnu".into()).into() }
parse_int
identifier_name
build.rs
/*! The build script has two primary jobs: 1. Do code generation. Currently, this consists of turning `data/winver.json` into an appropriate `enum`. 2. Tell Cargo to link against Clang. */ extern crate itertools; extern crate serde; use std::env; use std::fs; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; use itertools::Itertools; /// `pj` as in "path join". macro_rules! pj { ($p0:expr, $($ps:expr),*) => { { let mut pb = PathBuf::from($p0); $(pb.push($ps);)* pb } } } fn main() { let self_path = pj!(get_manifest_dir(), "build.rs"); let gen_path = make_gen_dir(); let data_path = get_data_dir(); { let winver_rs = pj!(&gen_path, "winver.rs"); let winver_json = pj!(&data_path, "winver.json"); if is_target_stale(&winver_rs, &[&self_path, &winver_json]) { let mut f = fs::File::create(winver_rs).ok().expect("create winver.rs"); gen_winver_enum(&mut f, &read_file_str(winver_json)); f.flush().unwrap(); } } link_clang(); } fn make_gen_dir() -> PathBuf { let gen_path = pj!(get_out_dir(), "src"); let _ = fs::create_dir(&gen_path).ok(); gen_path } fn get_data_dir() -> PathBuf { pj!(get_manifest_dir(), "data") } #[cfg(windows)] fn is_target_stale<P0, P1>(target: P0, dep_paths: &[P1]) -> bool where P0: AsRef<Path>, P1: AsRef<Path> { use std::os::windows::fs::MetadataExt; let target_ts = fs::metadata(&target).map(|md| md.last_write_time()).unwrap_or(0); dep_paths.iter().any(|dp| fs::metadata(dp).map(|md| md.last_write_time()).unwrap_or(1) > target_ts) } fn gen_winver_enum<W>(out: &mut W, json_str: &str) where W: io::Write
let reverse: HashMap<u32, &str> = primary.iter().map(|(k, v)| (*v, *k)).collect(); assert_eq!(primary.len(), reverse.len()); // Make the map of non-primary aliases. let mut aliases: Vec<(&str, u32)> = root.iter().filter(|&(k, _)| k.starts_with("*")) .map(|(k, v)| (&k[1..], *v)).collect(); aliases.sort(); // Get a sorted list of versions. let mut vers: Vec<u32> = primary.values().cloned().collect(); vers.sort(); // Use that to get a "next" version map. let next_ver_iter = vers.iter().cloned().skip(1).chain(Some(vers.last().unwrap() + 1).into_iter()); let next_ver: HashMap<u32, u32> = vers.iter().cloned().zip(next_ver_iter).collect(); // Generate the enum. write!(out, r#" #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] #[repr(u32)] pub enum WinVersion {{ {primary_variants} }} impl WinVersion {{ {alias_consts} pub const AFTER_LAST: u32 = 0x{guard_const:08x}; pub fn from_name(name: &str) -> Option<WinVersion> {{ match name {{ {from_names} _ => None }} }} pub fn next_version(self) -> Option<WinVersion> {{ match self {{ {next_versions} _ => None }} }} pub fn from_u32_round_up(v: u32) -> Option<WinVersion> {{ {from_u32_round_ups} None }} }} "#, primary_variants = vers.iter().cloned() .map(|v| format!(" {:<8} = 0x{:08x},", reverse[&v], v)) .join("\n"), alias_consts = aliases.iter() .map(|&(k, v)| format!(" pub const {:<7}: WinVersion = WinVersion::{};", k, reverse[&v])) .join("\n"), guard_const = next_ver[vers.last().unwrap()], from_names = primary.iter().map(|(&k, &v)| (k, v)).chain(aliases.iter().map(|&(k, v)| (k, v))) .map(|(k, v)| format!(" \"{}\" => Some(WinVersion::{}),", k, reverse[&v])) .join("\n"), next_versions = vers.iter().cloned() .filter(|&k| reverse.contains_key(&next_ver[&k])) .map(|k| format!(" WinVersion::{:<8} => Some(WinVersion::{}),", reverse[&k], reverse[&next_ver[&k]])) .join("\n"), from_u32_round_ups = vers.iter().cloned() .map(|k| format!(" if v <= 0x{:08x} {{ return Some(WinVersion::{}); }}", k, reverse[&k])) .join("\n"), ).unwrap(); } fn link_clang() { let manifest_path = get_manifest_dir(); let bin_dir = pj!(manifest_path, "bin", get_target()); println!("cargo:rustc-link-lib=clang"); println!("cargo:rustc-link-search={}", bin_dir.to_str().unwrap()); } fn parse_int(s: &str) -> u32 { if s.starts_with("0x") || s.starts_with("0X") { u32::from_str_radix(&s[2..], 16).unwrap() } else { s.parse().unwrap() } } fn read_file_str<P>(path: P) -> String where P: AsRef<Path> + ::std::fmt::Debug { let mut s = String::new(); let _ = fs::File::open(&path).ok().expect(&format!("open {:?}", path)) .read_to_string(&mut s).ok().expect(&format!("read from {:?}", path)); s } fn get_manifest_dir() -> PathBuf { env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".into()).into() } fn get_out_dir() -> PathBuf { env::var("OUT_DIR").ok().expect("OUT_DIR *must* be set").into() } fn get_target() -> PathBuf { env::var("TARGET").unwrap_or_else(|_| "i686-pc-windows-gnu".into()).into() }
{ use std::collections::HashMap; use serde::json; println!("# gen_winver_enum(..)"); let root: HashMap<String, String> = json::from_str(json_str).unwrap(); // First, parse those version numbers! let root: HashMap<_, u32> = root.into_iter() .map(|(k, v)| (k, parse_int(&v))) .collect(); // Make the map of "primary" names. let primary: HashMap<&str, u32> = root.iter() .filter(|&(ref k, _)| !k.starts_with("*")) .map(|(k, v)| (&**k, *v)) .collect(); // Make the reverse lookup map.
identifier_body
build.rs
/*! The build script has two primary jobs: 1. Do code generation. Currently, this consists of turning `data/winver.json` into an appropriate `enum`. 2. Tell Cargo to link against Clang. */ extern crate itertools; extern crate serde; use std::env; use std::fs; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; use itertools::Itertools; /// `pj` as in "path join". macro_rules! pj { ($p0:expr, $($ps:expr),*) => { { let mut pb = PathBuf::from($p0); $(pb.push($ps);)* pb } } } fn main() { let self_path = pj!(get_manifest_dir(), "build.rs"); let gen_path = make_gen_dir(); let data_path = get_data_dir(); { let winver_rs = pj!(&gen_path, "winver.rs"); let winver_json = pj!(&data_path, "winver.json"); if is_target_stale(&winver_rs, &[&self_path, &winver_json]) { let mut f = fs::File::create(winver_rs).ok().expect("create winver.rs"); gen_winver_enum(&mut f, &read_file_str(winver_json)); f.flush().unwrap(); } } link_clang(); } fn make_gen_dir() -> PathBuf { let gen_path = pj!(get_out_dir(), "src"); let _ = fs::create_dir(&gen_path).ok(); gen_path } fn get_data_dir() -> PathBuf { pj!(get_manifest_dir(), "data") } #[cfg(windows)] fn is_target_stale<P0, P1>(target: P0, dep_paths: &[P1]) -> bool where P0: AsRef<Path>, P1: AsRef<Path> { use std::os::windows::fs::MetadataExt; let target_ts = fs::metadata(&target).map(|md| md.last_write_time()).unwrap_or(0); dep_paths.iter().any(|dp| fs::metadata(dp).map(|md| md.last_write_time()).unwrap_or(1) > target_ts) } fn gen_winver_enum<W>(out: &mut W, json_str: &str) where W: io::Write { use std::collections::HashMap; use serde::json; println!("# gen_winver_enum(..)"); let root: HashMap<String, String> = json::from_str(json_str).unwrap(); // First, parse those version numbers! let root: HashMap<_, u32> = root.into_iter() .map(|(k, v)| (k, parse_int(&v))) .collect(); // Make the map of "primary" names. let primary: HashMap<&str, u32> = root.iter() .filter(|&(ref k, _)|!k.starts_with("*")) .map(|(k, v)| (&**k, *v)) .collect(); // Make the reverse lookup map. let reverse: HashMap<u32, &str> = primary.iter().map(|(k, v)| (*v, *k)).collect(); assert_eq!(primary.len(), reverse.len()); // Make the map of non-primary aliases. let mut aliases: Vec<(&str, u32)> = root.iter().filter(|&(k, _)| k.starts_with("*")) .map(|(k, v)| (&k[1..], *v)).collect(); aliases.sort(); // Get a sorted list of versions. let mut vers: Vec<u32> = primary.values().cloned().collect(); vers.sort(); // Use that to get a "next" version map. let next_ver_iter = vers.iter().cloned().skip(1).chain(Some(vers.last().unwrap() + 1).into_iter()); let next_ver: HashMap<u32, u32> = vers.iter().cloned().zip(next_ver_iter).collect(); // Generate the enum. write!(out, r#" #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] #[repr(u32)] pub enum WinVersion {{ {primary_variants} }} impl WinVersion {{ {alias_consts} pub const AFTER_LAST: u32 = 0x{guard_const:08x}; pub fn from_name(name: &str) -> Option<WinVersion> {{ match name {{ {from_names} _ => None }} }} pub fn next_version(self) -> Option<WinVersion> {{ match self {{ {next_versions} _ => None }} }} pub fn from_u32_round_up(v: u32) -> Option<WinVersion> {{ {from_u32_round_ups} None }} }} "#, primary_variants = vers.iter().cloned() .map(|v| format!(" {:<8} = 0x{:08x},", reverse[&v], v)) .join("\n"), alias_consts = aliases.iter() .map(|&(k, v)| format!(" pub const {:<7}: WinVersion = WinVersion::{};", k, reverse[&v])) .join("\n"), guard_const = next_ver[vers.last().unwrap()], from_names = primary.iter().map(|(&k, &v)| (k, v)).chain(aliases.iter().map(|&(k, v)| (k, v))) .map(|(k, v)| format!(" \"{}\" => Some(WinVersion::{}),", k, reverse[&v])) .join("\n"), next_versions = vers.iter().cloned() .filter(|&k| reverse.contains_key(&next_ver[&k])) .map(|k| format!(" WinVersion::{:<8} => Some(WinVersion::{}),", reverse[&k], reverse[&next_ver[&k]])) .join("\n"), from_u32_round_ups = vers.iter().cloned() .map(|k| format!(" if v <= 0x{:08x} {{ return Some(WinVersion::{}); }}", k, reverse[&k])) .join("\n"), ).unwrap(); } fn link_clang() { let manifest_path = get_manifest_dir(); let bin_dir = pj!(manifest_path, "bin", get_target()); println!("cargo:rustc-link-lib=clang"); println!("cargo:rustc-link-search={}", bin_dir.to_str().unwrap()); } fn parse_int(s: &str) -> u32 { if s.starts_with("0x") || s.starts_with("0X")
else { s.parse().unwrap() } } fn read_file_str<P>(path: P) -> String where P: AsRef<Path> + ::std::fmt::Debug { let mut s = String::new(); let _ = fs::File::open(&path).ok().expect(&format!("open {:?}", path)) .read_to_string(&mut s).ok().expect(&format!("read from {:?}", path)); s } fn get_manifest_dir() -> PathBuf { env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".into()).into() } fn get_out_dir() -> PathBuf { env::var("OUT_DIR").ok().expect("OUT_DIR *must* be set").into() } fn get_target() -> PathBuf { env::var("TARGET").unwrap_or_else(|_| "i686-pc-windows-gnu".into()).into() }
{ u32::from_str_radix(&s[2..], 16).unwrap() }
conditional_block
build.rs
1. Do code generation. Currently, this consists of turning `data/winver.json` into an appropriate `enum`. 2. Tell Cargo to link against Clang. */ extern crate itertools; extern crate serde; use std::env; use std::fs; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; use itertools::Itertools; /// `pj` as in "path join". macro_rules! pj { ($p0:expr, $($ps:expr),*) => { { let mut pb = PathBuf::from($p0); $(pb.push($ps);)* pb } } } fn main() { let self_path = pj!(get_manifest_dir(), "build.rs"); let gen_path = make_gen_dir(); let data_path = get_data_dir(); { let winver_rs = pj!(&gen_path, "winver.rs"); let winver_json = pj!(&data_path, "winver.json"); if is_target_stale(&winver_rs, &[&self_path, &winver_json]) { let mut f = fs::File::create(winver_rs).ok().expect("create winver.rs"); gen_winver_enum(&mut f, &read_file_str(winver_json)); f.flush().unwrap(); } } link_clang(); } fn make_gen_dir() -> PathBuf { let gen_path = pj!(get_out_dir(), "src"); let _ = fs::create_dir(&gen_path).ok(); gen_path } fn get_data_dir() -> PathBuf { pj!(get_manifest_dir(), "data") } #[cfg(windows)] fn is_target_stale<P0, P1>(target: P0, dep_paths: &[P1]) -> bool where P0: AsRef<Path>, P1: AsRef<Path> { use std::os::windows::fs::MetadataExt; let target_ts = fs::metadata(&target).map(|md| md.last_write_time()).unwrap_or(0); dep_paths.iter().any(|dp| fs::metadata(dp).map(|md| md.last_write_time()).unwrap_or(1) > target_ts) } fn gen_winver_enum<W>(out: &mut W, json_str: &str) where W: io::Write { use std::collections::HashMap; use serde::json; println!("# gen_winver_enum(..)"); let root: HashMap<String, String> = json::from_str(json_str).unwrap(); // First, parse those version numbers! let root: HashMap<_, u32> = root.into_iter() .map(|(k, v)| (k, parse_int(&v))) .collect(); // Make the map of "primary" names. let primary: HashMap<&str, u32> = root.iter() .filter(|&(ref k, _)|!k.starts_with("*")) .map(|(k, v)| (&**k, *v)) .collect(); // Make the reverse lookup map. let reverse: HashMap<u32, &str> = primary.iter().map(|(k, v)| (*v, *k)).collect(); assert_eq!(primary.len(), reverse.len()); // Make the map of non-primary aliases. let mut aliases: Vec<(&str, u32)> = root.iter().filter(|&(k, _)| k.starts_with("*")) .map(|(k, v)| (&k[1..], *v)).collect(); aliases.sort(); // Get a sorted list of versions. let mut vers: Vec<u32> = primary.values().cloned().collect(); vers.sort(); // Use that to get a "next" version map. let next_ver_iter = vers.iter().cloned().skip(1).chain(Some(vers.last().unwrap() + 1).into_iter()); let next_ver: HashMap<u32, u32> = vers.iter().cloned().zip(next_ver_iter).collect(); // Generate the enum. write!(out, r#" #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] #[repr(u32)] pub enum WinVersion {{ {primary_variants} }} impl WinVersion {{ {alias_consts} pub const AFTER_LAST: u32 = 0x{guard_const:08x}; pub fn from_name(name: &str) -> Option<WinVersion> {{ match name {{ {from_names} _ => None }} }} pub fn next_version(self) -> Option<WinVersion> {{ match self {{ {next_versions} _ => None }} }} pub fn from_u32_round_up(v: u32) -> Option<WinVersion> {{ {from_u32_round_ups} None }} }} "#, primary_variants = vers.iter().cloned() .map(|v| format!(" {:<8} = 0x{:08x},", reverse[&v], v)) .join("\n"), alias_consts = aliases.iter() .map(|&(k, v)| format!(" pub const {:<7}: WinVersion = WinVersion::{};", k, reverse[&v])) .join("\n"), guard_const = next_ver[vers.last().unwrap()], from_names = primary.iter().map(|(&k, &v)| (k, v)).chain(aliases.iter().map(|&(k, v)| (k, v))) .map(|(k, v)| format!(" \"{}\" => Some(WinVersion::{}),", k, reverse[&v])) .join("\n"), next_versions = vers.iter().cloned() .filter(|&k| reverse.contains_key(&next_ver[&k])) .map(|k| format!(" WinVersion::{:<8} => Some(WinVersion::{}),", reverse[&k], reverse[&next_ver[&k]])) .join("\n"), from_u32_round_ups = vers.iter().cloned() .map(|k| format!(" if v <= 0x{:08x} {{ return Some(WinVersion::{}); }}", k, reverse[&k])) .join("\n"), ).unwrap(); } fn link_clang() { let manifest_path = get_manifest_dir(); let bin_dir = pj!(manifest_path, "bin", get_target()); println!("cargo:rustc-link-lib=clang"); println!("cargo:rustc-link-search={}", bin_dir.to_str().unwrap()); } fn parse_int(s: &str) -> u32 { if s.starts_with("0x") || s.starts_with("0X") { u32::from_str_radix(&s[2..], 16).unwrap() } else { s.parse().unwrap() } } fn read_file_str<P>(path: P) -> String where P: AsRef<Path> + ::std::fmt::Debug { let mut s = String::new(); let _ = fs::File::open(&path).ok().expect(&format!("open {:?}", path)) .read_to_string(&mut s).ok().expect(&format!("read from {:?}", path)); s } fn get_manifest_dir() -> PathBuf { env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".into()).into() } fn get_out_dir() -> PathBuf { env::var("OUT_DIR").ok().expect("OUT_DIR *must* be set").into() } fn get_target() -> PathBuf { env::var("TARGET").unwrap_or_else(|_| "i686-pc-windows-gnu".into()).into() }
/*! The build script has two primary jobs:
random_line_split
main.rs
fn main() { println!("-459.67 F == {}", fht_to_celsius(-459.67)); let mut input = String::new(); let n = { println!("Print fib(n) for n: (choose 1-90, I'm not using bigints)"); std::io::stdin().read_line(&mut input) .expect("Readline failed"); match input.trim().parse() { Ok(num) => num, Err(_) => 0, } }; if n < 20 { println!("fib({}) = {}", n, fib(n)); } else if n <= 90 { println!("fib({}) = {}", n, fib_no_brute(n)); } } fn fht_to_celsius(fahrenheit: f32) -> f32 { (fahrenheit - 32.0) * 5.0 / 9.0 } fn fib(n: u32) -> u32 {
fn fib_no_brute(n: u32) -> u64 { if n == 0 || n == 1 { return n as u64; } let mut tmp0 = 0; let mut tmp1 = 1; let mut result = 0; for _ in 2..n { result = tmp0 + tmp1; tmp0 = tmp1; tmp1 = result; } return result; }
if n == 0 || n == 1 { return n; } fib(n-1) + fib(n-2) }
random_line_split
main.rs
fn main() { println!("-459.67 F == {}", fht_to_celsius(-459.67)); let mut input = String::new(); let n = { println!("Print fib(n) for n: (choose 1-90, I'm not using bigints)"); std::io::stdin().read_line(&mut input) .expect("Readline failed"); match input.trim().parse() { Ok(num) => num, Err(_) => 0, } }; if n < 20 { println!("fib({}) = {}", n, fib(n)); } else if n <= 90 { println!("fib({}) = {}", n, fib_no_brute(n)); } } fn fht_to_celsius(fahrenheit: f32) -> f32
fn fib(n: u32) -> u32 { if n == 0 || n == 1 { return n; } fib(n-1) + fib(n-2) } fn fib_no_brute(n: u32) -> u64 { if n == 0 || n == 1 { return n as u64; } let mut tmp0 = 0; let mut tmp1 = 1; let mut result = 0; for _ in 2..n { result = tmp0 + tmp1; tmp0 = tmp1; tmp1 = result; } return result; }
{ (fahrenheit - 32.0) * 5.0 / 9.0 }
identifier_body
main.rs
fn main() { println!("-459.67 F == {}", fht_to_celsius(-459.67)); let mut input = String::new(); let n = { println!("Print fib(n) for n: (choose 1-90, I'm not using bigints)"); std::io::stdin().read_line(&mut input) .expect("Readline failed"); match input.trim().parse() { Ok(num) => num, Err(_) => 0, } }; if n < 20 { println!("fib({}) = {}", n, fib(n)); } else if n <= 90 { println!("fib({}) = {}", n, fib_no_brute(n)); } } fn fht_to_celsius(fahrenheit: f32) -> f32 { (fahrenheit - 32.0) * 5.0 / 9.0 } fn fib(n: u32) -> u32 { if n == 0 || n == 1 { return n; } fib(n-1) + fib(n-2) } fn fib_no_brute(n: u32) -> u64 { if n == 0 || n == 1
let mut tmp0 = 0; let mut tmp1 = 1; let mut result = 0; for _ in 2..n { result = tmp0 + tmp1; tmp0 = tmp1; tmp1 = result; } return result; }
{ return n as u64; }
conditional_block
main.rs
fn main() { println!("-459.67 F == {}", fht_to_celsius(-459.67)); let mut input = String::new(); let n = { println!("Print fib(n) for n: (choose 1-90, I'm not using bigints)"); std::io::stdin().read_line(&mut input) .expect("Readline failed"); match input.trim().parse() { Ok(num) => num, Err(_) => 0, } }; if n < 20 { println!("fib({}) = {}", n, fib(n)); } else if n <= 90 { println!("fib({}) = {}", n, fib_no_brute(n)); } } fn fht_to_celsius(fahrenheit: f32) -> f32 { (fahrenheit - 32.0) * 5.0 / 9.0 } fn fib(n: u32) -> u32 { if n == 0 || n == 1 { return n; } fib(n-1) + fib(n-2) } fn
(n: u32) -> u64 { if n == 0 || n == 1 { return n as u64; } let mut tmp0 = 0; let mut tmp1 = 1; let mut result = 0; for _ in 2..n { result = tmp0 + tmp1; tmp0 = tmp1; tmp1 = result; } return result; }
fib_no_brute
identifier_name
x86.rs
pub type sig_atomic_t = ::int_t; pub type sigset_t = [u32; 32]; #[repr(C)] #[derive(Copy)] pub struct siginfo_t { pub si_signo: ::int_t, pub si_errno: ::int_t, pub si_code: ::int_t, _sifields: [u32; 29], } new!(siginfo_t); #[repr(C)] #[derive(Copy)] pub struct sigval { _data: [u32; 1usize], } new!(sigval); impl sigval { pub fn sival_int(&self) -> &::int_t { unsafe { ::std::mem::transmute(self) } } pub fn sival_ptr(&self) -> &*mut ::void_t { unsafe { ::std::mem::transmute(self) } } pub fn
(&mut self) -> &mut ::int_t { unsafe { ::std::mem::transmute(self) } } pub fn sival_ptr_mut(&mut self) -> &mut *mut ::void_t { unsafe { ::std::mem::transmute(self) } } } #[repr(C)] #[derive(Copy)] pub struct sigevent { pub sigev_value: sigval, pub sigev_signo: ::int_t, pub sigev_notify: ::int_t, pub sigev_notify_function: ::std::option::Option<extern fn(arg1: sigval)>, pub sigev_notify_attribute: *mut ::sys::types::pthread_attr_t, _pad: [u32; 11], } new!(sigevent); #[repr(C)] #[derive(Copy)] pub struct sigaction { __sigaction_handler: [u32; 1], pub sa_mask: sigset_t, pub sa_flags: ::int_t, pub sa_restorer: fn(), } new!(sigaction); #[repr(C)] #[derive(Copy)] pub struct stack_t { pub ss_sp: *mut ::void_t, pub ss_flags: ::int_t, pub ss_size: ::size_t, } new!(stack_t); #[repr(C)] #[derive(Copy)] pub struct mcontext_t { pub gregs: [::int_t; 19], pub fpregs: [u32; 28], pub oldmask: ::ulong_t, pub cr2: ::ulong_t, } new!(mcontext_t); #[repr(C)] #[derive(Copy)] pub struct ucontext { pub uc_flags: ::ulong_t, pub uc_link: *mut ucontext, pub uc_stack: stack_t, pub uc_mcontext: mcontext_t, pub uc_sigmask: sigset_t, __fpregs_mem: [u32; 28], } new!(ucontext); pub fn SIG_DFL() -> extern fn(::int_t) { unsafe { ::std::mem::transmute::<uint,_>(0) } } pub fn SIG_ERR() -> extern fn(::int_t) { unsafe { ::std::mem::transmute::<uint,_>(-1) } } pub fn SIG_IGN() -> extern fn(::int_t) { unsafe { ::std::mem::transmute::<uint,_>(1) } } pub const SIGEV_NONE: ::int_t = 1; pub const SIGEV_SIGNAL: ::int_t = 0; pub const SIGEV_THREAD: ::int_t = 2; pub const SIGABRT: ::int_t = 6; pub const SIGALRM: ::int_t = 14; pub const SIGBUS: ::int_t = 7; pub const SIGCHLD: ::int_t = 17; pub const SIGCONT: ::int_t = 18; pub const SIGFPE: ::int_t = 8; pub const SIGHUP: ::int_t = 1; pub const SIGILL: ::int_t = 4; pub const SIGINT: ::int_t = 2; pub const SIGKILL: ::int_t = 9; pub const SIGPIPE: ::int_t = 13; pub const SIGQUIT: ::int_t = 3; pub const SIGSEGV: ::int_t = 11; pub const SIGSTOP: ::int_t = 19; pub const SIGTERM: ::int_t = 15; pub const SIGTSTP: ::int_t = 20; pub const SIGTTIN: ::int_t = 21; pub const SIGTTOU: ::int_t = 22; pub const SIGUSR1: ::int_t = 10; pub const SIGUSR2: ::int_t = 12; pub const SIGPOLL: ::int_t = 29; pub const SIGPROF: ::int_t = 27; pub const SIGSYS: ::int_t = 31; pub const SIGTRAP: ::int_t = 5; pub const SIGURG: ::int_t = 23; pub const SIGVTALRM: ::int_t = 26; pub const SIGXCPU: ::int_t = 24; pub const SIGXFSZ: ::int_t = 25; pub const SIG_BLOCK: ::int_t = 0; pub const SIG_UNBLOCK: ::int_t = 1; pub const SIG_SETMASK: ::int_t = 2; pub const SA_NOCLDSTOP: ::int_t = 1; pub const SA_ONSTACK: ::int_t = 0x08000000; pub const SA_RESETHAND: ::int_t = -2147483648; pub const SA_RESTART: ::int_t = 0x10000000; pub const SA_SIGINFO: ::int_t = 4; pub const SA_NOCLDWAIT: ::int_t = 2; pub const SA_NODEFER: ::int_t = 0x40000000; pub const SS_ONSTACK: ::int_t = 1; pub const SS_DISABLE: ::int_t = 2; pub const MINSIGSTKSZ: ::int_t = 2048; pub const SIGSTKSZ: ::int_t = 8192; pub const ILL_ILLOPC: ::int_t = 1; pub const ILL_ILLOPN: ::int_t = 2; pub const ILL_ILLADR: ::int_t = 3; pub const ILL_ILLTRP: ::int_t = 4; pub const ILL_PRVOPC: ::int_t = 5; pub const ILL_PRVREG: ::int_t = 6; pub const ILL_COPROC: ::int_t = 7; pub const ILL_BADSTK: ::int_t = 8; pub const FPE_INTDIV: ::int_t = 1; pub const FPE_INTOVF: ::int_t = 2; pub const FPE_FLTDIV: ::int_t = 3; pub const FPE_FLTOVF: ::int_t = 4; pub const FPE_FLTUND: ::int_t = 5; pub const FPE_FLTRES: ::int_t = 6; pub const FPE_FLTINV: ::int_t = 7; pub const FPE_FLTSUB: ::int_t = 8; pub const SEGV_MAPERR: ::int_t = 1; pub const SEGV_ACCERR: ::int_t = 2; pub const BUS_ADRALN: ::int_t = 1; pub const BUS_ADRERR: ::int_t = 2; pub const BUS_OBJERR: ::int_t = 3; pub const TRAP_BRKPT: ::int_t = 1; pub const TRAP_TRACE: ::int_t = 2; pub const CLD_EXITED: ::int_t = 1; pub const CLD_KILLED: ::int_t = 2; pub const CLD_DUMPED: ::int_t = 3; pub const CLD_TRAPPED: ::int_t = 4; pub const CLD_STOPPED: ::int_t = 5; pub const CLD_CONTINUED: ::int_t = 6; pub const POLL_IN: ::int_t = 1; pub const POLL_OUT: ::int_t = 2; pub const POLL_MSG: ::int_t = 3; pub const POLL_ERR: ::int_t = 4; pub const POLL_PRI: ::int_t = 5; pub const POLL_HUP: ::int_t = 6; pub const SI_USER: ::int_t = 0; pub const SI_QUEUE: ::int_t = -1; pub const SI_TIMER: ::int_t = -2; pub const SI_ASYNCIO: ::int_t = -4; pub const SI_MESGQ: ::int_t = -3;
sival_int_mut
identifier_name
x86.rs
pub type sig_atomic_t = ::int_t; pub type sigset_t = [u32; 32]; #[repr(C)] #[derive(Copy)] pub struct siginfo_t { pub si_signo: ::int_t, pub si_errno: ::int_t, pub si_code: ::int_t, _sifields: [u32; 29], } new!(siginfo_t); #[repr(C)] #[derive(Copy)] pub struct sigval { _data: [u32; 1usize], } new!(sigval); impl sigval { pub fn sival_int(&self) -> &::int_t { unsafe { ::std::mem::transmute(self) } } pub fn sival_ptr(&self) -> &*mut ::void_t
pub fn sival_int_mut(&mut self) -> &mut ::int_t { unsafe { ::std::mem::transmute(self) } } pub fn sival_ptr_mut(&mut self) -> &mut *mut ::void_t { unsafe { ::std::mem::transmute(self) } } } #[repr(C)] #[derive(Copy)] pub struct sigevent { pub sigev_value: sigval, pub sigev_signo: ::int_t, pub sigev_notify: ::int_t, pub sigev_notify_function: ::std::option::Option<extern fn(arg1: sigval)>, pub sigev_notify_attribute: *mut ::sys::types::pthread_attr_t, _pad: [u32; 11], } new!(sigevent); #[repr(C)] #[derive(Copy)] pub struct sigaction { __sigaction_handler: [u32; 1], pub sa_mask: sigset_t, pub sa_flags: ::int_t, pub sa_restorer: fn(), } new!(sigaction); #[repr(C)] #[derive(Copy)] pub struct stack_t { pub ss_sp: *mut ::void_t, pub ss_flags: ::int_t, pub ss_size: ::size_t, } new!(stack_t); #[repr(C)] #[derive(Copy)] pub struct mcontext_t { pub gregs: [::int_t; 19], pub fpregs: [u32; 28], pub oldmask: ::ulong_t, pub cr2: ::ulong_t, } new!(mcontext_t); #[repr(C)] #[derive(Copy)] pub struct ucontext { pub uc_flags: ::ulong_t, pub uc_link: *mut ucontext, pub uc_stack: stack_t, pub uc_mcontext: mcontext_t, pub uc_sigmask: sigset_t, __fpregs_mem: [u32; 28], } new!(ucontext); pub fn SIG_DFL() -> extern fn(::int_t) { unsafe { ::std::mem::transmute::<uint,_>(0) } } pub fn SIG_ERR() -> extern fn(::int_t) { unsafe { ::std::mem::transmute::<uint,_>(-1) } } pub fn SIG_IGN() -> extern fn(::int_t) { unsafe { ::std::mem::transmute::<uint,_>(1) } } pub const SIGEV_NONE: ::int_t = 1; pub const SIGEV_SIGNAL: ::int_t = 0; pub const SIGEV_THREAD: ::int_t = 2; pub const SIGABRT: ::int_t = 6; pub const SIGALRM: ::int_t = 14; pub const SIGBUS: ::int_t = 7; pub const SIGCHLD: ::int_t = 17; pub const SIGCONT: ::int_t = 18; pub const SIGFPE: ::int_t = 8; pub const SIGHUP: ::int_t = 1; pub const SIGILL: ::int_t = 4; pub const SIGINT: ::int_t = 2; pub const SIGKILL: ::int_t = 9; pub const SIGPIPE: ::int_t = 13; pub const SIGQUIT: ::int_t = 3; pub const SIGSEGV: ::int_t = 11; pub const SIGSTOP: ::int_t = 19; pub const SIGTERM: ::int_t = 15; pub const SIGTSTP: ::int_t = 20; pub const SIGTTIN: ::int_t = 21; pub const SIGTTOU: ::int_t = 22; pub const SIGUSR1: ::int_t = 10; pub const SIGUSR2: ::int_t = 12; pub const SIGPOLL: ::int_t = 29; pub const SIGPROF: ::int_t = 27; pub const SIGSYS: ::int_t = 31; pub const SIGTRAP: ::int_t = 5; pub const SIGURG: ::int_t = 23; pub const SIGVTALRM: ::int_t = 26; pub const SIGXCPU: ::int_t = 24; pub const SIGXFSZ: ::int_t = 25; pub const SIG_BLOCK: ::int_t = 0; pub const SIG_UNBLOCK: ::int_t = 1; pub const SIG_SETMASK: ::int_t = 2; pub const SA_NOCLDSTOP: ::int_t = 1; pub const SA_ONSTACK: ::int_t = 0x08000000; pub const SA_RESETHAND: ::int_t = -2147483648; pub const SA_RESTART: ::int_t = 0x10000000; pub const SA_SIGINFO: ::int_t = 4; pub const SA_NOCLDWAIT: ::int_t = 2; pub const SA_NODEFER: ::int_t = 0x40000000; pub const SS_ONSTACK: ::int_t = 1; pub const SS_DISABLE: ::int_t = 2; pub const MINSIGSTKSZ: ::int_t = 2048; pub const SIGSTKSZ: ::int_t = 8192; pub const ILL_ILLOPC: ::int_t = 1; pub const ILL_ILLOPN: ::int_t = 2; pub const ILL_ILLADR: ::int_t = 3; pub const ILL_ILLTRP: ::int_t = 4; pub const ILL_PRVOPC: ::int_t = 5; pub const ILL_PRVREG: ::int_t = 6; pub const ILL_COPROC: ::int_t = 7; pub const ILL_BADSTK: ::int_t = 8; pub const FPE_INTDIV: ::int_t = 1; pub const FPE_INTOVF: ::int_t = 2; pub const FPE_FLTDIV: ::int_t = 3; pub const FPE_FLTOVF: ::int_t = 4; pub const FPE_FLTUND: ::int_t = 5; pub const FPE_FLTRES: ::int_t = 6; pub const FPE_FLTINV: ::int_t = 7; pub const FPE_FLTSUB: ::int_t = 8; pub const SEGV_MAPERR: ::int_t = 1; pub const SEGV_ACCERR: ::int_t = 2; pub const BUS_ADRALN: ::int_t = 1; pub const BUS_ADRERR: ::int_t = 2; pub const BUS_OBJERR: ::int_t = 3; pub const TRAP_BRKPT: ::int_t = 1; pub const TRAP_TRACE: ::int_t = 2; pub const CLD_EXITED: ::int_t = 1; pub const CLD_KILLED: ::int_t = 2; pub const CLD_DUMPED: ::int_t = 3; pub const CLD_TRAPPED: ::int_t = 4; pub const CLD_STOPPED: ::int_t = 5; pub const CLD_CONTINUED: ::int_t = 6; pub const POLL_IN: ::int_t = 1; pub const POLL_OUT: ::int_t = 2; pub const POLL_MSG: ::int_t = 3; pub const POLL_ERR: ::int_t = 4; pub const POLL_PRI: ::int_t = 5; pub const POLL_HUP: ::int_t = 6; pub const SI_USER: ::int_t = 0; pub const SI_QUEUE: ::int_t = -1; pub const SI_TIMER: ::int_t = -2; pub const SI_ASYNCIO: ::int_t = -4; pub const SI_MESGQ: ::int_t = -3;
{ unsafe { ::std::mem::transmute(self) } }
identifier_body
x86.rs
pub type sig_atomic_t = ::int_t; pub type sigset_t = [u32; 32]; #[repr(C)] #[derive(Copy)] pub struct siginfo_t { pub si_signo: ::int_t, pub si_errno: ::int_t, pub si_code: ::int_t, _sifields: [u32; 29], } new!(siginfo_t); #[repr(C)] #[derive(Copy)] pub struct sigval { _data: [u32; 1usize], } new!(sigval); impl sigval { pub fn sival_int(&self) -> &::int_t { unsafe { ::std::mem::transmute(self) } } pub fn sival_ptr(&self) -> &*mut ::void_t { unsafe { ::std::mem::transmute(self) } } pub fn sival_int_mut(&mut self) -> &mut ::int_t { unsafe { ::std::mem::transmute(self) } } pub fn sival_ptr_mut(&mut self) -> &mut *mut ::void_t { unsafe { ::std::mem::transmute(self) } } } #[repr(C)] #[derive(Copy)] pub struct sigevent { pub sigev_value: sigval, pub sigev_signo: ::int_t, pub sigev_notify: ::int_t, pub sigev_notify_function: ::std::option::Option<extern fn(arg1: sigval)>, pub sigev_notify_attribute: *mut ::sys::types::pthread_attr_t, _pad: [u32; 11], } new!(sigevent); #[repr(C)] #[derive(Copy)] pub struct sigaction { __sigaction_handler: [u32; 1], pub sa_mask: sigset_t, pub sa_flags: ::int_t, pub sa_restorer: fn(), } new!(sigaction); #[repr(C)] #[derive(Copy)] pub struct stack_t { pub ss_sp: *mut ::void_t, pub ss_flags: ::int_t, pub ss_size: ::size_t, } new!(stack_t);
pub struct mcontext_t { pub gregs: [::int_t; 19], pub fpregs: [u32; 28], pub oldmask: ::ulong_t, pub cr2: ::ulong_t, } new!(mcontext_t); #[repr(C)] #[derive(Copy)] pub struct ucontext { pub uc_flags: ::ulong_t, pub uc_link: *mut ucontext, pub uc_stack: stack_t, pub uc_mcontext: mcontext_t, pub uc_sigmask: sigset_t, __fpregs_mem: [u32; 28], } new!(ucontext); pub fn SIG_DFL() -> extern fn(::int_t) { unsafe { ::std::mem::transmute::<uint,_>(0) } } pub fn SIG_ERR() -> extern fn(::int_t) { unsafe { ::std::mem::transmute::<uint,_>(-1) } } pub fn SIG_IGN() -> extern fn(::int_t) { unsafe { ::std::mem::transmute::<uint,_>(1) } } pub const SIGEV_NONE: ::int_t = 1; pub const SIGEV_SIGNAL: ::int_t = 0; pub const SIGEV_THREAD: ::int_t = 2; pub const SIGABRT: ::int_t = 6; pub const SIGALRM: ::int_t = 14; pub const SIGBUS: ::int_t = 7; pub const SIGCHLD: ::int_t = 17; pub const SIGCONT: ::int_t = 18; pub const SIGFPE: ::int_t = 8; pub const SIGHUP: ::int_t = 1; pub const SIGILL: ::int_t = 4; pub const SIGINT: ::int_t = 2; pub const SIGKILL: ::int_t = 9; pub const SIGPIPE: ::int_t = 13; pub const SIGQUIT: ::int_t = 3; pub const SIGSEGV: ::int_t = 11; pub const SIGSTOP: ::int_t = 19; pub const SIGTERM: ::int_t = 15; pub const SIGTSTP: ::int_t = 20; pub const SIGTTIN: ::int_t = 21; pub const SIGTTOU: ::int_t = 22; pub const SIGUSR1: ::int_t = 10; pub const SIGUSR2: ::int_t = 12; pub const SIGPOLL: ::int_t = 29; pub const SIGPROF: ::int_t = 27; pub const SIGSYS: ::int_t = 31; pub const SIGTRAP: ::int_t = 5; pub const SIGURG: ::int_t = 23; pub const SIGVTALRM: ::int_t = 26; pub const SIGXCPU: ::int_t = 24; pub const SIGXFSZ: ::int_t = 25; pub const SIG_BLOCK: ::int_t = 0; pub const SIG_UNBLOCK: ::int_t = 1; pub const SIG_SETMASK: ::int_t = 2; pub const SA_NOCLDSTOP: ::int_t = 1; pub const SA_ONSTACK: ::int_t = 0x08000000; pub const SA_RESETHAND: ::int_t = -2147483648; pub const SA_RESTART: ::int_t = 0x10000000; pub const SA_SIGINFO: ::int_t = 4; pub const SA_NOCLDWAIT: ::int_t = 2; pub const SA_NODEFER: ::int_t = 0x40000000; pub const SS_ONSTACK: ::int_t = 1; pub const SS_DISABLE: ::int_t = 2; pub const MINSIGSTKSZ: ::int_t = 2048; pub const SIGSTKSZ: ::int_t = 8192; pub const ILL_ILLOPC: ::int_t = 1; pub const ILL_ILLOPN: ::int_t = 2; pub const ILL_ILLADR: ::int_t = 3; pub const ILL_ILLTRP: ::int_t = 4; pub const ILL_PRVOPC: ::int_t = 5; pub const ILL_PRVREG: ::int_t = 6; pub const ILL_COPROC: ::int_t = 7; pub const ILL_BADSTK: ::int_t = 8; pub const FPE_INTDIV: ::int_t = 1; pub const FPE_INTOVF: ::int_t = 2; pub const FPE_FLTDIV: ::int_t = 3; pub const FPE_FLTOVF: ::int_t = 4; pub const FPE_FLTUND: ::int_t = 5; pub const FPE_FLTRES: ::int_t = 6; pub const FPE_FLTINV: ::int_t = 7; pub const FPE_FLTSUB: ::int_t = 8; pub const SEGV_MAPERR: ::int_t = 1; pub const SEGV_ACCERR: ::int_t = 2; pub const BUS_ADRALN: ::int_t = 1; pub const BUS_ADRERR: ::int_t = 2; pub const BUS_OBJERR: ::int_t = 3; pub const TRAP_BRKPT: ::int_t = 1; pub const TRAP_TRACE: ::int_t = 2; pub const CLD_EXITED: ::int_t = 1; pub const CLD_KILLED: ::int_t = 2; pub const CLD_DUMPED: ::int_t = 3; pub const CLD_TRAPPED: ::int_t = 4; pub const CLD_STOPPED: ::int_t = 5; pub const CLD_CONTINUED: ::int_t = 6; pub const POLL_IN: ::int_t = 1; pub const POLL_OUT: ::int_t = 2; pub const POLL_MSG: ::int_t = 3; pub const POLL_ERR: ::int_t = 4; pub const POLL_PRI: ::int_t = 5; pub const POLL_HUP: ::int_t = 6; pub const SI_USER: ::int_t = 0; pub const SI_QUEUE: ::int_t = -1; pub const SI_TIMER: ::int_t = -2; pub const SI_ASYNCIO: ::int_t = -4; pub const SI_MESGQ: ::int_t = -3;
#[repr(C)] #[derive(Copy)]
random_line_split
lib.rs
/* * Copyright (C) 2015 Benjamin Fry <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #![warn( missing_docs, clippy::dbg_macro, clippy::print_stdout, clippy::unimplemented )] //! TLS protocol related components for DNS over TLS extern crate futures; extern crate openssl; extern crate tokio;
mod tls_client_stream; pub mod tls_server; mod tls_stream; pub use self::tls_client_stream::{TlsClientStream, TlsClientStreamBuilder}; pub use self::tls_stream::{tls_stream_from_existing_tls_stream, TlsStream, TlsStreamBuilder};
extern crate tokio_openssl; extern crate trust_dns_proto;
random_line_split
lcg128xsl64.rs
use rand_core::{RngCore, SeedableRng}; use rand_pcg::{Lcg128Xsl64, Pcg64}; #[test] fn test_lcg128xsl64_advancing() { for seed in 0..20 { let mut rng1 = Lcg128Xsl64::seed_from_u64(seed); let mut rng2 = rng1.clone(); for _ in 0..20 { rng1.next_u64(); } rng2.advance(20); assert_eq!(rng1, rng2); } } #[test] fn test_lcg128xsl64_construction() { // Test that various construction techniques produce a working RNG. #[rustfmt::skip] let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32]; let mut rng1 = Lcg128Xsl64::from_seed(seed); assert_eq!(rng1.next_u64(), 8740028313290271629); let mut rng2 = Lcg128Xsl64::from_rng(&mut rng1).unwrap(); assert_eq!(rng2.next_u64(), 1922280315005786345); let mut rng3 = Lcg128Xsl64::seed_from_u64(0); assert_eq!(rng3.next_u64(), 2354861276966075475); // This is the same as Lcg128Xsl64, so we only have a single test: let mut rng4 = Pcg64::seed_from_u64(0); assert_eq!(rng4.next_u64(), 2354861276966075475); } #[test] fn test_lcg128xsl64_true_values() { // Numbers copied from official test suite (C version). let mut rng = Lcg128Xsl64::new(42, 54); let mut results = [0u64; 6]; for i in results.iter_mut() { *i = rng.next_u64(); } let expected: [u64; 6] = [ 0x86b1da1d72062b68, 0x1304aa46c9853d39, 0xa3670e9e0dd50358, 0xf9090e529a7dae00, 0xc85b9fd837996f2c, 0x606121f8e3919196, ]; assert_eq!(results, expected); } #[cfg(feature = "serde1")] #[test] fn
() { use bincode; use std::io::{BufReader, BufWriter}; let mut rng = Lcg128Xsl64::seed_from_u64(0); let buf: Vec<u8> = Vec::new(); let mut buf = BufWriter::new(buf); bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); let buf = buf.into_inner().unwrap(); let mut read = BufReader::new(&buf[..]); let mut deserialized: Lcg128Xsl64 = bincode::deserialize_from(&mut read).expect("Could not deserialize"); for _ in 0..16 { assert_eq!(rng.next_u64(), deserialized.next_u64()); } }
test_lcg128xsl64_serde
identifier_name
lcg128xsl64.rs
use rand_core::{RngCore, SeedableRng}; use rand_pcg::{Lcg128Xsl64, Pcg64}; #[test] fn test_lcg128xsl64_advancing() { for seed in 0..20 { let mut rng1 = Lcg128Xsl64::seed_from_u64(seed); let mut rng2 = rng1.clone(); for _ in 0..20 { rng1.next_u64(); } rng2.advance(20); assert_eq!(rng1, rng2); } } #[test] fn test_lcg128xsl64_construction() { // Test that various construction techniques produce a working RNG. #[rustfmt::skip] let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32]; let mut rng1 = Lcg128Xsl64::from_seed(seed); assert_eq!(rng1.next_u64(), 8740028313290271629); let mut rng2 = Lcg128Xsl64::from_rng(&mut rng1).unwrap(); assert_eq!(rng2.next_u64(), 1922280315005786345); let mut rng3 = Lcg128Xsl64::seed_from_u64(0); assert_eq!(rng3.next_u64(), 2354861276966075475); // This is the same as Lcg128Xsl64, so we only have a single test: let mut rng4 = Pcg64::seed_from_u64(0); assert_eq!(rng4.next_u64(), 2354861276966075475); } #[test] fn test_lcg128xsl64_true_values() { // Numbers copied from official test suite (C version). let mut rng = Lcg128Xsl64::new(42, 54); let mut results = [0u64; 6]; for i in results.iter_mut() { *i = rng.next_u64(); } let expected: [u64; 6] = [ 0x86b1da1d72062b68, 0x1304aa46c9853d39, 0xa3670e9e0dd50358, 0xf9090e529a7dae00, 0xc85b9fd837996f2c, 0x606121f8e3919196, ]; assert_eq!(results, expected); } #[cfg(feature = "serde1")] #[test] fn test_lcg128xsl64_serde() { use bincode; use std::io::{BufReader, BufWriter}; let mut rng = Lcg128Xsl64::seed_from_u64(0); let buf: Vec<u8> = Vec::new(); let mut buf = BufWriter::new(buf); bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); let buf = buf.into_inner().unwrap(); let mut read = BufReader::new(&buf[..]); let mut deserialized: Lcg128Xsl64 = bincode::deserialize_from(&mut read).expect("Could not deserialize"); for _ in 0..16 { assert_eq!(rng.next_u64(), deserialized.next_u64()); }
}
random_line_split
lcg128xsl64.rs
use rand_core::{RngCore, SeedableRng}; use rand_pcg::{Lcg128Xsl64, Pcg64}; #[test] fn test_lcg128xsl64_advancing() { for seed in 0..20 { let mut rng1 = Lcg128Xsl64::seed_from_u64(seed); let mut rng2 = rng1.clone(); for _ in 0..20 { rng1.next_u64(); } rng2.advance(20); assert_eq!(rng1, rng2); } } #[test] fn test_lcg128xsl64_construction()
#[test] fn test_lcg128xsl64_true_values() { // Numbers copied from official test suite (C version). let mut rng = Lcg128Xsl64::new(42, 54); let mut results = [0u64; 6]; for i in results.iter_mut() { *i = rng.next_u64(); } let expected: [u64; 6] = [ 0x86b1da1d72062b68, 0x1304aa46c9853d39, 0xa3670e9e0dd50358, 0xf9090e529a7dae00, 0xc85b9fd837996f2c, 0x606121f8e3919196, ]; assert_eq!(results, expected); } #[cfg(feature = "serde1")] #[test] fn test_lcg128xsl64_serde() { use bincode; use std::io::{BufReader, BufWriter}; let mut rng = Lcg128Xsl64::seed_from_u64(0); let buf: Vec<u8> = Vec::new(); let mut buf = BufWriter::new(buf); bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); let buf = buf.into_inner().unwrap(); let mut read = BufReader::new(&buf[..]); let mut deserialized: Lcg128Xsl64 = bincode::deserialize_from(&mut read).expect("Could not deserialize"); for _ in 0..16 { assert_eq!(rng.next_u64(), deserialized.next_u64()); } }
{ // Test that various construction techniques produce a working RNG. #[rustfmt::skip] let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32]; let mut rng1 = Lcg128Xsl64::from_seed(seed); assert_eq!(rng1.next_u64(), 8740028313290271629); let mut rng2 = Lcg128Xsl64::from_rng(&mut rng1).unwrap(); assert_eq!(rng2.next_u64(), 1922280315005786345); let mut rng3 = Lcg128Xsl64::seed_from_u64(0); assert_eq!(rng3.next_u64(), 2354861276966075475); // This is the same as Lcg128Xsl64, so we only have a single test: let mut rng4 = Pcg64::seed_from_u64(0); assert_eq!(rng4.next_u64(), 2354861276966075475); }
identifier_body
radionodelist.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 dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods; use dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods; use dom::bindings::codegen::Bindings::RadioNodeListBinding; use dom::bindings::codegen::Bindings::RadioNodeListBinding::RadioNodeListMethods; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::{Dom, DomRoot}; use dom::bindings::str::DOMString; use dom::htmlinputelement::{HTMLInputElement, InputType}; use dom::node::Node; use dom::nodelist::{NodeList, NodeListType}; use dom::window::Window; use dom_struct::dom_struct; #[dom_struct] pub struct RadioNodeList { node_list: NodeList, } impl RadioNodeList { #[allow(unrooted_must_root)] fn new_inherited(list_type: NodeListType) -> RadioNodeList { RadioNodeList { node_list: NodeList::new_inherited(list_type) } } #[allow(unrooted_must_root)] pub fn new(window: &Window, list_type: NodeListType) -> DomRoot<RadioNodeList> { reflect_dom_object(Box::new(RadioNodeList::new_inherited(list_type)), window, RadioNodeListBinding::Wrap) } pub fn new_simple_list<T>(window: &Window, iter: T) -> DomRoot<RadioNodeList> where T: Iterator<Item=DomRoot<Node>> { RadioNodeList::new(window, NodeListType::Simple(iter.map(|r| Dom::from_ref(&*r)).collect())) } // FIXME: This shouldn't need to be implemented here since NodeList (the parent of // RadioNodeList) implements Length // https://github.com/servo/servo/issues/5875 pub fn Length(&self) -> u32 { self.node_list.Length() } } impl RadioNodeListMethods for RadioNodeList { // https://html.spec.whatwg.org/multipage/#dom-radionodelist-value fn Value(&self) -> DOMString { self.upcast::<NodeList>().as_simple_list().iter().filter_map(|node| { // Step 1 node.downcast::<HTMLInputElement>().and_then(|input| { if input.input_type() == InputType::Radio && input.Checked() { // Step 3-4 let value = input.Value(); Some(if value.is_empty() { DOMString::from("on") } else { value }) } else { None } }) }).next() // Step 2 .unwrap_or(DOMString::from("")) } // https://html.spec.whatwg.org/multipage/#dom-radionodelist-value fn SetValue(&self, value: DOMString) { for node in self.upcast::<NodeList>().as_simple_list().iter() { // Step 1 if let Some(input) = node.downcast::<HTMLInputElement>() { match input.input_type() { InputType::Radio if value == DOMString::from("on") => { // Step 2 let val = input.Value(); if val.is_empty() || val == value { input.SetChecked(true); return; } } InputType::Radio =>
_ => {} } } } } // FIXME: This shouldn't need to be implemented here since NodeList (the parent of // RadioNodeList) implements IndexedGetter. // https://github.com/servo/servo/issues/5875 // // https://dom.spec.whatwg.org/#dom-nodelist-item fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Node>> { self.node_list.IndexedGetter(index) } }
{ // Step 2 if input.Value() == value { input.SetChecked(true); return; } }
conditional_block
radionodelist.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 dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods; use dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods; use dom::bindings::codegen::Bindings::RadioNodeListBinding; use dom::bindings::codegen::Bindings::RadioNodeListBinding::RadioNodeListMethods; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::{Dom, DomRoot}; use dom::bindings::str::DOMString; use dom::htmlinputelement::{HTMLInputElement, InputType}; use dom::node::Node; use dom::nodelist::{NodeList, NodeListType}; use dom::window::Window; use dom_struct::dom_struct; #[dom_struct] pub struct RadioNodeList { node_list: NodeList, } impl RadioNodeList { #[allow(unrooted_must_root)] fn new_inherited(list_type: NodeListType) -> RadioNodeList { RadioNodeList { node_list: NodeList::new_inherited(list_type) } } #[allow(unrooted_must_root)] pub fn new(window: &Window, list_type: NodeListType) -> DomRoot<RadioNodeList>
pub fn new_simple_list<T>(window: &Window, iter: T) -> DomRoot<RadioNodeList> where T: Iterator<Item=DomRoot<Node>> { RadioNodeList::new(window, NodeListType::Simple(iter.map(|r| Dom::from_ref(&*r)).collect())) } // FIXME: This shouldn't need to be implemented here since NodeList (the parent of // RadioNodeList) implements Length // https://github.com/servo/servo/issues/5875 pub fn Length(&self) -> u32 { self.node_list.Length() } } impl RadioNodeListMethods for RadioNodeList { // https://html.spec.whatwg.org/multipage/#dom-radionodelist-value fn Value(&self) -> DOMString { self.upcast::<NodeList>().as_simple_list().iter().filter_map(|node| { // Step 1 node.downcast::<HTMLInputElement>().and_then(|input| { if input.input_type() == InputType::Radio && input.Checked() { // Step 3-4 let value = input.Value(); Some(if value.is_empty() { DOMString::from("on") } else { value }) } else { None } }) }).next() // Step 2 .unwrap_or(DOMString::from("")) } // https://html.spec.whatwg.org/multipage/#dom-radionodelist-value fn SetValue(&self, value: DOMString) { for node in self.upcast::<NodeList>().as_simple_list().iter() { // Step 1 if let Some(input) = node.downcast::<HTMLInputElement>() { match input.input_type() { InputType::Radio if value == DOMString::from("on") => { // Step 2 let val = input.Value(); if val.is_empty() || val == value { input.SetChecked(true); return; } } InputType::Radio => { // Step 2 if input.Value() == value { input.SetChecked(true); return; } } _ => {} } } } } // FIXME: This shouldn't need to be implemented here since NodeList (the parent of // RadioNodeList) implements IndexedGetter. // https://github.com/servo/servo/issues/5875 // // https://dom.spec.whatwg.org/#dom-nodelist-item fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Node>> { self.node_list.IndexedGetter(index) } }
{ reflect_dom_object(Box::new(RadioNodeList::new_inherited(list_type)), window, RadioNodeListBinding::Wrap) }
identifier_body
radionodelist.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 dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods; use dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods; use dom::bindings::codegen::Bindings::RadioNodeListBinding; use dom::bindings::codegen::Bindings::RadioNodeListBinding::RadioNodeListMethods; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::{Dom, DomRoot}; use dom::bindings::str::DOMString; use dom::htmlinputelement::{HTMLInputElement, InputType}; use dom::node::Node; use dom::nodelist::{NodeList, NodeListType}; use dom::window::Window; use dom_struct::dom_struct; #[dom_struct] pub struct RadioNodeList { node_list: NodeList, }
node_list: NodeList::new_inherited(list_type) } } #[allow(unrooted_must_root)] pub fn new(window: &Window, list_type: NodeListType) -> DomRoot<RadioNodeList> { reflect_dom_object(Box::new(RadioNodeList::new_inherited(list_type)), window, RadioNodeListBinding::Wrap) } pub fn new_simple_list<T>(window: &Window, iter: T) -> DomRoot<RadioNodeList> where T: Iterator<Item=DomRoot<Node>> { RadioNodeList::new(window, NodeListType::Simple(iter.map(|r| Dom::from_ref(&*r)).collect())) } // FIXME: This shouldn't need to be implemented here since NodeList (the parent of // RadioNodeList) implements Length // https://github.com/servo/servo/issues/5875 pub fn Length(&self) -> u32 { self.node_list.Length() } } impl RadioNodeListMethods for RadioNodeList { // https://html.spec.whatwg.org/multipage/#dom-radionodelist-value fn Value(&self) -> DOMString { self.upcast::<NodeList>().as_simple_list().iter().filter_map(|node| { // Step 1 node.downcast::<HTMLInputElement>().and_then(|input| { if input.input_type() == InputType::Radio && input.Checked() { // Step 3-4 let value = input.Value(); Some(if value.is_empty() { DOMString::from("on") } else { value }) } else { None } }) }).next() // Step 2 .unwrap_or(DOMString::from("")) } // https://html.spec.whatwg.org/multipage/#dom-radionodelist-value fn SetValue(&self, value: DOMString) { for node in self.upcast::<NodeList>().as_simple_list().iter() { // Step 1 if let Some(input) = node.downcast::<HTMLInputElement>() { match input.input_type() { InputType::Radio if value == DOMString::from("on") => { // Step 2 let val = input.Value(); if val.is_empty() || val == value { input.SetChecked(true); return; } } InputType::Radio => { // Step 2 if input.Value() == value { input.SetChecked(true); return; } } _ => {} } } } } // FIXME: This shouldn't need to be implemented here since NodeList (the parent of // RadioNodeList) implements IndexedGetter. // https://github.com/servo/servo/issues/5875 // // https://dom.spec.whatwg.org/#dom-nodelist-item fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Node>> { self.node_list.IndexedGetter(index) } }
impl RadioNodeList { #[allow(unrooted_must_root)] fn new_inherited(list_type: NodeListType) -> RadioNodeList { RadioNodeList {
random_line_split
radionodelist.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 dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods; use dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods; use dom::bindings::codegen::Bindings::RadioNodeListBinding; use dom::bindings::codegen::Bindings::RadioNodeListBinding::RadioNodeListMethods; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::{Dom, DomRoot}; use dom::bindings::str::DOMString; use dom::htmlinputelement::{HTMLInputElement, InputType}; use dom::node::Node; use dom::nodelist::{NodeList, NodeListType}; use dom::window::Window; use dom_struct::dom_struct; #[dom_struct] pub struct RadioNodeList { node_list: NodeList, } impl RadioNodeList { #[allow(unrooted_must_root)] fn new_inherited(list_type: NodeListType) -> RadioNodeList { RadioNodeList { node_list: NodeList::new_inherited(list_type) } } #[allow(unrooted_must_root)] pub fn new(window: &Window, list_type: NodeListType) -> DomRoot<RadioNodeList> { reflect_dom_object(Box::new(RadioNodeList::new_inherited(list_type)), window, RadioNodeListBinding::Wrap) } pub fn new_simple_list<T>(window: &Window, iter: T) -> DomRoot<RadioNodeList> where T: Iterator<Item=DomRoot<Node>> { RadioNodeList::new(window, NodeListType::Simple(iter.map(|r| Dom::from_ref(&*r)).collect())) } // FIXME: This shouldn't need to be implemented here since NodeList (the parent of // RadioNodeList) implements Length // https://github.com/servo/servo/issues/5875 pub fn Length(&self) -> u32 { self.node_list.Length() } } impl RadioNodeListMethods for RadioNodeList { // https://html.spec.whatwg.org/multipage/#dom-radionodelist-value fn
(&self) -> DOMString { self.upcast::<NodeList>().as_simple_list().iter().filter_map(|node| { // Step 1 node.downcast::<HTMLInputElement>().and_then(|input| { if input.input_type() == InputType::Radio && input.Checked() { // Step 3-4 let value = input.Value(); Some(if value.is_empty() { DOMString::from("on") } else { value }) } else { None } }) }).next() // Step 2 .unwrap_or(DOMString::from("")) } // https://html.spec.whatwg.org/multipage/#dom-radionodelist-value fn SetValue(&self, value: DOMString) { for node in self.upcast::<NodeList>().as_simple_list().iter() { // Step 1 if let Some(input) = node.downcast::<HTMLInputElement>() { match input.input_type() { InputType::Radio if value == DOMString::from("on") => { // Step 2 let val = input.Value(); if val.is_empty() || val == value { input.SetChecked(true); return; } } InputType::Radio => { // Step 2 if input.Value() == value { input.SetChecked(true); return; } } _ => {} } } } } // FIXME: This shouldn't need to be implemented here since NodeList (the parent of // RadioNodeList) implements IndexedGetter. // https://github.com/servo/servo/issues/5875 // // https://dom.spec.whatwg.org/#dom-nodelist-item fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Node>> { self.node_list.IndexedGetter(index) } }
Value
identifier_name
MZ.rs
// fn main() { // let nums = vec![0,1,0,3,12]; // let mut result:Vec<i32> = Vec::new(); // let mut zeros = 0; // for i in &nums { // if *i!= 0 { // result.push(*i); // }else { // zeros += 1; // } // } // for _ in 0..zeros { // result.push(0) // } // println!("{:?}", nums); // println!("{:?}", result); // } pub fn move_zeroes(nums: &mut Vec<i32>) { let mut result: Vec<i32> = Vec::new(); let mut zeros = 0; for i in nums.clone() { if i!= 0 { result.push(i); } else { zeros += 1; } } for _ in 0..zeros { result.push(0) } *nums = result; } pub fn move_zeroes_new(nums: &mut Vec<i32>) { let mut result: Vec<i32> = Vec::new(); let mut zeros = 0;
let len = nums.len().clone(); for i in 0..len { if nums[i]!= 0 { result.push(nums[i].clone()); } else { zeros += 1; } } for _ in 0..zeros { result.push(0) } *nums = result; } fn main() { let mut testcase = vec![0, 1, 0, 3, 12]; move_zeroes(&mut testcase); println!("{:?}", testcase); }
random_line_split
MZ.rs
// fn main() { // let nums = vec![0,1,0,3,12]; // let mut result:Vec<i32> = Vec::new(); // let mut zeros = 0; // for i in &nums { // if *i!= 0 { // result.push(*i); // }else { // zeros += 1; // } // } // for _ in 0..zeros { // result.push(0) // } // println!("{:?}", nums); // println!("{:?}", result); // } pub fn move_zeroes(nums: &mut Vec<i32>) { let mut result: Vec<i32> = Vec::new(); let mut zeros = 0; for i in nums.clone() { if i!= 0 { result.push(i); } else { zeros += 1; } } for _ in 0..zeros { result.push(0) } *nums = result; } pub fn move_zeroes_new(nums: &mut Vec<i32>)
fn main() { let mut testcase = vec![0, 1, 0, 3, 12]; move_zeroes(&mut testcase); println!("{:?}", testcase); }
{ let mut result: Vec<i32> = Vec::new(); let mut zeros = 0; let len = nums.len().clone(); for i in 0..len { if nums[i] != 0 { result.push(nums[i].clone()); } else { zeros += 1; } } for _ in 0..zeros { result.push(0) } *nums = result; }
identifier_body
MZ.rs
// fn main() { // let nums = vec![0,1,0,3,12]; // let mut result:Vec<i32> = Vec::new(); // let mut zeros = 0; // for i in &nums { // if *i!= 0 { // result.push(*i); // }else { // zeros += 1; // } // } // for _ in 0..zeros { // result.push(0) // } // println!("{:?}", nums); // println!("{:?}", result); // } pub fn
(nums: &mut Vec<i32>) { let mut result: Vec<i32> = Vec::new(); let mut zeros = 0; for i in nums.clone() { if i!= 0 { result.push(i); } else { zeros += 1; } } for _ in 0..zeros { result.push(0) } *nums = result; } pub fn move_zeroes_new(nums: &mut Vec<i32>) { let mut result: Vec<i32> = Vec::new(); let mut zeros = 0; let len = nums.len().clone(); for i in 0..len { if nums[i]!= 0 { result.push(nums[i].clone()); } else { zeros += 1; } } for _ in 0..zeros { result.push(0) } *nums = result; } fn main() { let mut testcase = vec![0, 1, 0, 3, 12]; move_zeroes(&mut testcase); println!("{:?}", testcase); }
move_zeroes
identifier_name
MZ.rs
// fn main() { // let nums = vec![0,1,0,3,12]; // let mut result:Vec<i32> = Vec::new(); // let mut zeros = 0; // for i in &nums { // if *i!= 0 { // result.push(*i); // }else { // zeros += 1; // } // } // for _ in 0..zeros { // result.push(0) // } // println!("{:?}", nums); // println!("{:?}", result); // } pub fn move_zeroes(nums: &mut Vec<i32>) { let mut result: Vec<i32> = Vec::new(); let mut zeros = 0; for i in nums.clone() { if i!= 0 { result.push(i); } else
} for _ in 0..zeros { result.push(0) } *nums = result; } pub fn move_zeroes_new(nums: &mut Vec<i32>) { let mut result: Vec<i32> = Vec::new(); let mut zeros = 0; let len = nums.len().clone(); for i in 0..len { if nums[i]!= 0 { result.push(nums[i].clone()); } else { zeros += 1; } } for _ in 0..zeros { result.push(0) } *nums = result; } fn main() { let mut testcase = vec![0, 1, 0, 3, 12]; move_zeroes(&mut testcase); println!("{:?}", testcase); }
{ zeros += 1; }
conditional_block
error.rs
// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. use std::result; use crate::grpc; use tokio_timer::TimerError; #[derive(Debug)] pub enum Error { Grpc(grpc::Error), Timer(TimerError), } impl From<grpc::Error> for Error { fn
(e: grpc::Error) -> Error { Error::Grpc(e) } } impl From<TimerError> for Error { fn from(e: TimerError) -> Error { Error::Timer(e) } } pub type Result<T> = result::Result<T, Error>;
from
identifier_name
error.rs
// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. use std::result; use crate::grpc; use tokio_timer::TimerError; #[derive(Debug)] pub enum Error { Grpc(grpc::Error), Timer(TimerError), } impl From<grpc::Error> for Error { fn from(e: grpc::Error) -> Error
} impl From<TimerError> for Error { fn from(e: TimerError) -> Error { Error::Timer(e) } } pub type Result<T> = result::Result<T, Error>;
{ Error::Grpc(e) }
identifier_body
error.rs
// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. use std::result; use crate::grpc; use tokio_timer::TimerError; #[derive(Debug)] pub enum Error { Grpc(grpc::Error), Timer(TimerError), } impl From<grpc::Error> for Error { fn from(e: grpc::Error) -> Error { Error::Grpc(e) } } impl From<TimerError> for Error { fn from(e: TimerError) -> Error { Error::Timer(e) }
} pub type Result<T> = result::Result<T, Error>;
random_line_split
lib.rs
//! Farbfeld is a simple image encoding format from suckless. //! # Related Links //! * http://git.suckless.org/farbfeld/tree/FORMAT. #![deny(unsafe_code)] #![deny(trivial_casts, trivial_numeric_casts)] #![deny(missing_docs, missing_debug_implementations, missing_copy_implementations)] #![deny(unused_extern_crates, unused_import_braces, unused_qualifications)] extern crate byteorder; use std::error; use std::fmt; use std::io; mod decoder; mod encoder; #[cfg(test)] mod tests; pub use decoder::Decoder; pub use encoder::Encoder; const HEADER_LEN: u64 = 8+4+4; /// Result of an image decoding/encoding process pub type Result<T> = ::std::result::Result<T, Error>; /// An enumeration of decoding/encoding Errors #[derive(Debug)] pub enum Error { /// The Image is not formatted properly FormatError(String), /// Not enough data was provided to the Decoder /// to decode the image NotEnoughData, /// An I/O Error occurred while decoding the image IoError(io::Error), /// The end of the image has been reached ImageEnd } impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { &Error::FormatError(ref e) => write!(fmt, "Format error: {}", e), &Error::NotEnoughData => write!(fmt, "Not enough data was provided to the \ Decoder to decode the image"), &Error::IoError(ref e) => e.fmt(fmt), &Error::ImageEnd => write!(fmt, "The end of the image has been reached") } } } impl error::Error for Error { fn description (&self) -> &str { match *self { Error::FormatError(..) => &"Format error", Error::NotEnoughData => &"Not enough data", Error::IoError(..) => &"IO error", Error::ImageEnd => &"Image end" } } fn
(&self) -> Option<&error::Error> { match *self { Error::IoError(ref e) => Some(e), _ => None } } } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::IoError(err) } }
cause
identifier_name
lib.rs
//! Farbfeld is a simple image encoding format from suckless. //! # Related Links //! * http://git.suckless.org/farbfeld/tree/FORMAT. #![deny(unsafe_code)] #![deny(trivial_casts, trivial_numeric_casts)] #![deny(missing_docs, missing_debug_implementations, missing_copy_implementations)] #![deny(unused_extern_crates, unused_import_braces, unused_qualifications)] extern crate byteorder; use std::error; use std::fmt; use std::io; mod decoder; mod encoder; #[cfg(test)] mod tests; pub use decoder::Decoder; pub use encoder::Encoder; const HEADER_LEN: u64 = 8+4+4; /// Result of an image decoding/encoding process pub type Result<T> = ::std::result::Result<T, Error>; /// An enumeration of decoding/encoding Errors #[derive(Debug)] pub enum Error { /// The Image is not formatted properly FormatError(String), /// Not enough data was provided to the Decoder /// to decode the image NotEnoughData, /// An I/O Error occurred while decoding the image IoError(io::Error), /// The end of the image has been reached ImageEnd } impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { &Error::FormatError(ref e) => write!(fmt, "Format error: {}", e), &Error::NotEnoughData => write!(fmt, "Not enough data was provided to the \ Decoder to decode the image"), &Error::IoError(ref e) => e.fmt(fmt), &Error::ImageEnd => write!(fmt, "The end of the image has been reached") } } } impl error::Error for Error { fn description (&self) -> &str { match *self { Error::FormatError(..) => &"Format error", Error::NotEnoughData => &"Not enough data", Error::IoError(..) => &"IO error", Error::ImageEnd => &"Image end" } } fn cause (&self) -> Option<&error::Error> { match *self { Error::IoError(ref e) => Some(e), _ => None } } }
Error::IoError(err) } }
impl From<io::Error> for Error { fn from(err: io::Error) -> Error {
random_line_split
lib.rs
//! Farbfeld is a simple image encoding format from suckless. //! # Related Links //! * http://git.suckless.org/farbfeld/tree/FORMAT. #![deny(unsafe_code)] #![deny(trivial_casts, trivial_numeric_casts)] #![deny(missing_docs, missing_debug_implementations, missing_copy_implementations)] #![deny(unused_extern_crates, unused_import_braces, unused_qualifications)] extern crate byteorder; use std::error; use std::fmt; use std::io; mod decoder; mod encoder; #[cfg(test)] mod tests; pub use decoder::Decoder; pub use encoder::Encoder; const HEADER_LEN: u64 = 8+4+4; /// Result of an image decoding/encoding process pub type Result<T> = ::std::result::Result<T, Error>; /// An enumeration of decoding/encoding Errors #[derive(Debug)] pub enum Error { /// The Image is not formatted properly FormatError(String), /// Not enough data was provided to the Decoder /// to decode the image NotEnoughData, /// An I/O Error occurred while decoding the image IoError(io::Error), /// The end of the image has been reached ImageEnd } impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { &Error::FormatError(ref e) => write!(fmt, "Format error: {}", e), &Error::NotEnoughData => write!(fmt, "Not enough data was provided to the \ Decoder to decode the image"), &Error::IoError(ref e) => e.fmt(fmt), &Error::ImageEnd => write!(fmt, "The end of the image has been reached") } } } impl error::Error for Error { fn description (&self) -> &str { match *self { Error::FormatError(..) => &"Format error", Error::NotEnoughData => &"Not enough data", Error::IoError(..) => &"IO error", Error::ImageEnd => &"Image end" } } fn cause (&self) -> Option<&error::Error> { match *self { Error::IoError(ref e) => Some(e), _ => None } } } impl From<io::Error> for Error { fn from(err: io::Error) -> Error
}
{ Error::IoError(err) }
identifier_body
depth.rs
//! Compute the depth of coverage in a BAM file for a list of reference sequences and positions. //! //! ## Input: //! A BAM file and a positions file. //! The positions file contains the name of one reference sequence and one position per line (tab separated). //! Example: //! ``` //! 16 1 //! 17 1 //! 17 2 //! 17 38 //! 17 39 //! ``` //! //! Positions are read from stdin, the BAM file is the first argument. //! //! ## Output: //! Depth are written to stdout as tab-separated lines, similar to the positions input. //! Example: //! ``` //! 16 1 0 //! 17 1 5 //! 17 2 5 //! 17 38 14 //! 17 39 13 //! ``` //! //! ## Usage: //! //! ```bash //! $ rbt bam-depth tests/test.bam < tests/pos.txt > tests/depth.txt //! ``` //! Where `pos.txt` is a positions file, as described above. //! //! use anyhow::Result; use log::info; use std::cmp; use std::io; use serde::Deserialize; use rust_htslib::bam; use rust_htslib::bam::{FetchDefinition, Read}; use std::path::Path; #[derive(Deserialize, Debug)] struct
{ chrom: String, pos: u32, } pub fn depth<P: AsRef<Path>>( bam_path: P, max_read_length: u32, include_flags: u16, exclude_flags: u16, min_mapq: u8, ) -> Result<()> { let mut bam_reader = bam::IndexedReader::from_path(&bam_path)?; let bam_header = bam_reader.header().clone(); let mut pos_reader = csv::ReaderBuilder::new() .has_headers(false) .delimiter(b'\t') .from_reader(io::stdin()); let mut csv_writer = csv::WriterBuilder::new() .delimiter(b'\t') .from_writer(io::BufWriter::new(io::stdout())); for (i, record) in pos_reader.deserialize().enumerate() { let record: PosRecord = record?; // jump to correct position let tid = bam_header.tid(record.chrom.as_bytes()).unwrap() as i32; let start = cmp::max(record.pos as i64 - max_read_length as i64 - 1, 0); bam_reader.fetch(FetchDefinition::Region( tid, start as i64, start as i64 + (max_read_length * 2) as i64, ))?; // iterate over pileups let mut covered = false; for pileup in bam_reader.pileup() { let pileup = pileup?; covered = pileup.pos() == record.pos - 1; if covered { let depth = pileup .alignments() .filter(|alignment| { let record = alignment.record(); let flags = record.flags(); (!flags) & include_flags == 0 && flags & exclude_flags == 0 && record.mapq() >= min_mapq }) .count(); csv_writer.serialize((&record.chrom, record.pos, depth))?; break; } else if pileup.pos() > record.pos { break; } } if!covered { csv_writer.serialize((&record.chrom, record.pos, 0))?; } if (i + 1) % 100 == 0 { info!("{} records written.", i + 1); } } Ok(()) }
PosRecord
identifier_name
depth.rs
//! Compute the depth of coverage in a BAM file for a list of reference sequences and positions. //! //! ## Input: //! A BAM file and a positions file. //! The positions file contains the name of one reference sequence and one position per line (tab separated). //! Example: //! ``` //! 16 1 //! 17 1 //! 17 2 //! 17 38 //! 17 39 //! ``` //! //! Positions are read from stdin, the BAM file is the first argument. //! //! ## Output: //! Depth are written to stdout as tab-separated lines, similar to the positions input. //! Example: //! ``` //! 16 1 0 //! 17 1 5 //! 17 2 5 //! 17 38 14 //! 17 39 13 //! ``` //! //! ## Usage: //! //! ```bash //! $ rbt bam-depth tests/test.bam < tests/pos.txt > tests/depth.txt //! ``` //! Where `pos.txt` is a positions file, as described above. //! //! use anyhow::Result; use log::info; use std::cmp; use std::io; use serde::Deserialize; use rust_htslib::bam; use rust_htslib::bam::{FetchDefinition, Read}; use std::path::Path; #[derive(Deserialize, Debug)] struct PosRecord { chrom: String, pos: u32,
} pub fn depth<P: AsRef<Path>>( bam_path: P, max_read_length: u32, include_flags: u16, exclude_flags: u16, min_mapq: u8, ) -> Result<()> { let mut bam_reader = bam::IndexedReader::from_path(&bam_path)?; let bam_header = bam_reader.header().clone(); let mut pos_reader = csv::ReaderBuilder::new() .has_headers(false) .delimiter(b'\t') .from_reader(io::stdin()); let mut csv_writer = csv::WriterBuilder::new() .delimiter(b'\t') .from_writer(io::BufWriter::new(io::stdout())); for (i, record) in pos_reader.deserialize().enumerate() { let record: PosRecord = record?; // jump to correct position let tid = bam_header.tid(record.chrom.as_bytes()).unwrap() as i32; let start = cmp::max(record.pos as i64 - max_read_length as i64 - 1, 0); bam_reader.fetch(FetchDefinition::Region( tid, start as i64, start as i64 + (max_read_length * 2) as i64, ))?; // iterate over pileups let mut covered = false; for pileup in bam_reader.pileup() { let pileup = pileup?; covered = pileup.pos() == record.pos - 1; if covered { let depth = pileup .alignments() .filter(|alignment| { let record = alignment.record(); let flags = record.flags(); (!flags) & include_flags == 0 && flags & exclude_flags == 0 && record.mapq() >= min_mapq }) .count(); csv_writer.serialize((&record.chrom, record.pos, depth))?; break; } else if pileup.pos() > record.pos { break; } } if!covered { csv_writer.serialize((&record.chrom, record.pos, 0))?; } if (i + 1) % 100 == 0 { info!("{} records written.", i + 1); } } Ok(()) }
random_line_split
depth.rs
//! Compute the depth of coverage in a BAM file for a list of reference sequences and positions. //! //! ## Input: //! A BAM file and a positions file. //! The positions file contains the name of one reference sequence and one position per line (tab separated). //! Example: //! ``` //! 16 1 //! 17 1 //! 17 2 //! 17 38 //! 17 39 //! ``` //! //! Positions are read from stdin, the BAM file is the first argument. //! //! ## Output: //! Depth are written to stdout as tab-separated lines, similar to the positions input. //! Example: //! ``` //! 16 1 0 //! 17 1 5 //! 17 2 5 //! 17 38 14 //! 17 39 13 //! ``` //! //! ## Usage: //! //! ```bash //! $ rbt bam-depth tests/test.bam < tests/pos.txt > tests/depth.txt //! ``` //! Where `pos.txt` is a positions file, as described above. //! //! use anyhow::Result; use log::info; use std::cmp; use std::io; use serde::Deserialize; use rust_htslib::bam; use rust_htslib::bam::{FetchDefinition, Read}; use std::path::Path; #[derive(Deserialize, Debug)] struct PosRecord { chrom: String, pos: u32, } pub fn depth<P: AsRef<Path>>( bam_path: P, max_read_length: u32, include_flags: u16, exclude_flags: u16, min_mapq: u8, ) -> Result<()>
start as i64 + (max_read_length * 2) as i64, ))?; // iterate over pileups let mut covered = false; for pileup in bam_reader.pileup() { let pileup = pileup?; covered = pileup.pos() == record.pos - 1; if covered { let depth = pileup .alignments() .filter(|alignment| { let record = alignment.record(); let flags = record.flags(); (!flags) & include_flags == 0 && flags & exclude_flags == 0 && record.mapq() >= min_mapq }) .count(); csv_writer.serialize((&record.chrom, record.pos, depth))?; break; } else if pileup.pos() > record.pos { break; } } if!covered { csv_writer.serialize((&record.chrom, record.pos, 0))?; } if (i + 1) % 100 == 0 { info!("{} records written.", i + 1); } } Ok(()) }
{ let mut bam_reader = bam::IndexedReader::from_path(&bam_path)?; let bam_header = bam_reader.header().clone(); let mut pos_reader = csv::ReaderBuilder::new() .has_headers(false) .delimiter(b'\t') .from_reader(io::stdin()); let mut csv_writer = csv::WriterBuilder::new() .delimiter(b'\t') .from_writer(io::BufWriter::new(io::stdout())); for (i, record) in pos_reader.deserialize().enumerate() { let record: PosRecord = record?; // jump to correct position let tid = bam_header.tid(record.chrom.as_bytes()).unwrap() as i32; let start = cmp::max(record.pos as i64 - max_read_length as i64 - 1, 0); bam_reader.fetch(FetchDefinition::Region( tid, start as i64,
identifier_body
depth.rs
//! Compute the depth of coverage in a BAM file for a list of reference sequences and positions. //! //! ## Input: //! A BAM file and a positions file. //! The positions file contains the name of one reference sequence and one position per line (tab separated). //! Example: //! ``` //! 16 1 //! 17 1 //! 17 2 //! 17 38 //! 17 39 //! ``` //! //! Positions are read from stdin, the BAM file is the first argument. //! //! ## Output: //! Depth are written to stdout as tab-separated lines, similar to the positions input. //! Example: //! ``` //! 16 1 0 //! 17 1 5 //! 17 2 5 //! 17 38 14 //! 17 39 13 //! ``` //! //! ## Usage: //! //! ```bash //! $ rbt bam-depth tests/test.bam < tests/pos.txt > tests/depth.txt //! ``` //! Where `pos.txt` is a positions file, as described above. //! //! use anyhow::Result; use log::info; use std::cmp; use std::io; use serde::Deserialize; use rust_htslib::bam; use rust_htslib::bam::{FetchDefinition, Read}; use std::path::Path; #[derive(Deserialize, Debug)] struct PosRecord { chrom: String, pos: u32, } pub fn depth<P: AsRef<Path>>( bam_path: P, max_read_length: u32, include_flags: u16, exclude_flags: u16, min_mapq: u8, ) -> Result<()> { let mut bam_reader = bam::IndexedReader::from_path(&bam_path)?; let bam_header = bam_reader.header().clone(); let mut pos_reader = csv::ReaderBuilder::new() .has_headers(false) .delimiter(b'\t') .from_reader(io::stdin()); let mut csv_writer = csv::WriterBuilder::new() .delimiter(b'\t') .from_writer(io::BufWriter::new(io::stdout())); for (i, record) in pos_reader.deserialize().enumerate() { let record: PosRecord = record?; // jump to correct position let tid = bam_header.tid(record.chrom.as_bytes()).unwrap() as i32; let start = cmp::max(record.pos as i64 - max_read_length as i64 - 1, 0); bam_reader.fetch(FetchDefinition::Region( tid, start as i64, start as i64 + (max_read_length * 2) as i64, ))?; // iterate over pileups let mut covered = false; for pileup in bam_reader.pileup() { let pileup = pileup?; covered = pileup.pos() == record.pos - 1; if covered { let depth = pileup .alignments() .filter(|alignment| { let record = alignment.record(); let flags = record.flags(); (!flags) & include_flags == 0 && flags & exclude_flags == 0 && record.mapq() >= min_mapq }) .count(); csv_writer.serialize((&record.chrom, record.pos, depth))?; break; } else if pileup.pos() > record.pos { break; } } if!covered { csv_writer.serialize((&record.chrom, record.pos, 0))?; } if (i + 1) % 100 == 0
} Ok(()) }
{ info!("{} records written.", i + 1); }
conditional_block
async-fn.rs
// Copyright 2018 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
// edition:2018 // compile-flags:-Z unstable-options // FIXME: once `--edition` is stable in rustdoc, remove that `compile-flags` directive #![feature(async_await, futures_api)] // @has async_fn/struct.S.html // @has - '//code' 'pub async fn f()' pub struct S; impl S { pub async fn f() {} }
// <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.
random_line_split
async-fn.rs
// Copyright 2018 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. // edition:2018 // compile-flags:-Z unstable-options // FIXME: once `--edition` is stable in rustdoc, remove that `compile-flags` directive #![feature(async_await, futures_api)] // @has async_fn/struct.S.html // @has - '//code' 'pub async fn f()' pub struct S; impl S { pub async fn
() {} }
f
identifier_name
sodium_type.rs
// This macro allows to wrap Sodimoxide type to libindy type keeping the same behaviour macro_rules! sodium_type (($newtype:ident, $sodiumtype:path, $len:ident) => ( pub struct $newtype(pub(super) $sodiumtype); impl $newtype { #[allow(dead_code)] pub fn new(bytes: [u8; $len]) -> $newtype { $newtype($sodiumtype(bytes)) } #[allow(dead_code)] pub fn from_slice(bs: &[u8]) -> Result<$newtype, ::errors::IndyError> { let inner = <$sodiumtype>::from_slice(bs) .ok_or(::errors::err_msg(::errors::IndyErrorKind::InvalidStructure, format!("Invalid bytes for {:?}", stringify!($newtype))))?; Ok($newtype(inner)) } } impl Clone for $newtype { fn clone(&self) -> $newtype { $newtype(self.0.clone()) } } impl ::std::fmt::Debug for $newtype { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { self.0.fmt(f) } } impl ::std::cmp::PartialEq for $newtype { fn eq(&self, other: &$newtype) -> bool {
impl ::std::cmp::Eq for $newtype {} impl ::serde::Serialize for $newtype { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ::serde::Serializer { serializer.serialize_bytes(&self.0[..]) } } impl<'de> ::serde::Deserialize<'de> for $newtype { fn deserialize<D>(deserializer: D) -> Result<$newtype, D::Error> where D: ::serde::Deserializer<'de> { <$sodiumtype>::deserialize(deserializer).map($newtype) } } impl ::std::ops::Index<::std::ops::Range<usize>> for $newtype { type Output = [u8]; fn index(&self, _index: ::std::ops::Range<usize>) -> &[u8] { self.0.index(_index) } } impl ::std::ops::Index<::std::ops::RangeTo<usize>> for $newtype { type Output = [u8]; fn index(&self, _index: ::std::ops::RangeTo<usize>) -> &[u8] { self.0.index(_index) } } impl ::std::ops::Index<::std::ops::RangeFrom<usize>> for $newtype { type Output = [u8]; fn index(&self, _index: ::std::ops::RangeFrom<usize>) -> &[u8] { self.0.index(_index) } } impl ::std::ops::Index<::std::ops::RangeFull> for $newtype { type Output = [u8]; fn index(&self, _index: ::std::ops::RangeFull) -> &[u8] { self.0.index(_index) } } impl AsRef<[u8]> for $newtype { #[inline] fn as_ref(&self) -> &[u8] { &self[..] } } ));
self.0.eq(&other.0) } }
random_line_split
test.rs
// use msg_parse::{ParsingResult, Parsing, add_char}; // use test_diff; // pub const MSG_TEST_WIKIPEDIA1: &'static str = "8=FIX.4.2|9=178|35=8|49=PHLX|56=PERS|52=20071123-05:\ // 30:00.000|11=ATOMNOCCC9990900|20=3|150=E|39=E|55=MSFT|167=CS|54=1|38=15|40=2|44=15|58=PHLX \ // EQUITY TESTING|59=0|47=C|32=0|31=0|151=15|14=0|6=0|10=128|"; // fn add_char_incomplete(mut parser: Parsing, ch: char) -> Parsing { // match add_char(parser, ch) { // ParsingResult::Parsing(parsing) => parser = parsing, // ParsingResult::ParsedOK(_) => panic!("ParsedOK in icomplete message"), // ParsingResult::ParsedErrors { parsed: _, errors: _ } => { // panic!("ParsedErrors in icomplete message") // } // } // parser // } // #[test]
// let mut parser = Parsing::new(); // parser = add_char_incomplete(parser, '1'); // ass_eqdf!{ // parser.parsed.orig_msg => "1".to_string(), // parser.parsed.msg_length => 1, // parser.reading_tag => 1 // }; // }
// fn init_add_char() {
random_line_split
cssrulelist.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 dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CSSRuleListBinding; use dom::bindings::codegen::Bindings::CSSRuleListBinding::CSSRuleListMethods; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::js::{JS, MutNullableJS, Root}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::csskeyframerule::CSSKeyframeRule; use dom::cssrule::CSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use parking_lot::RwLock; use std::sync::Arc; use style::stylesheets::{CssRules, KeyframesRule, RulesMutateError}; #[allow(unsafe_code)] unsafe_no_jsmanaged_fields!(RulesSource); unsafe_no_jsmanaged_fields!(CssRules); impl From<RulesMutateError> for Error { fn from(other: RulesMutateError) -> Self { match other { RulesMutateError::Syntax => Error::Syntax, RulesMutateError::IndexSize => Error::IndexSize, RulesMutateError::HierarchyRequest => Error::HierarchyRequest, RulesMutateError::InvalidState => Error::InvalidState, } } } #[dom_struct] pub struct CSSRuleList { reflector_: Reflector, parent_stylesheet: JS<CSSStyleSheet>, #[ignore_heap_size_of = "Arc"] rules: RulesSource, dom_rules: DOMRefCell<Vec<MutNullableJS<CSSRule>>> } pub enum RulesSource { Rules(Arc<RwLock<CssRules>>), Keyframes(Arc<RwLock<KeyframesRule>>), } impl CSSRuleList { #[allow(unrooted_must_root)] pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, rules: RulesSource) -> CSSRuleList { let dom_rules = match rules { RulesSource::Rules(ref rules) => { rules.read().0.iter().map(|_| MutNullableJS::new(None)).collect() } RulesSource::Keyframes(ref rules) => { rules.read().keyframes.iter().map(|_| MutNullableJS::new(None)).collect() } }; CSSRuleList { reflector_: Reflector::new(), parent_stylesheet: JS::from_ref(parent_stylesheet), rules: rules, dom_rules: DOMRefCell::new(dom_rules), } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, rules: RulesSource) -> Root<CSSRuleList> { reflect_dom_object(box CSSRuleList::new_inherited(parent_stylesheet, rules), window, CSSRuleListBinding::Wrap) } /// Should only be called for CssRules-backed rules. Use append_lazy_rule /// for keyframes-backed rules. pub fn insert_rule(&self, rule: &str, idx: u32, nested: bool) -> Fallible<u32> { let css_rules = if let RulesSource::Rules(ref rules) = self.rules { rules } else { panic!("Called insert_rule on non-CssRule-backed CSSRuleList"); }; let global = self.global(); let window = global.as_window(); let index = idx as usize; let parent_stylesheet = self.parent_stylesheet.style_stylesheet(); let new_rule = css_rules.write().insert_rule(rule, parent_stylesheet, index, nested)?; let parent_stylesheet = &*self.parent_stylesheet; let dom_rule = CSSRule::new_specific(&window, parent_stylesheet, new_rule); self.dom_rules.borrow_mut().insert(index, MutNullableJS::new(Some(&*dom_rule))); Ok((idx)) } // In case of a keyframe rule, index must be valid. pub fn
(&self, index: u32) -> ErrorResult { let index = index as usize; match self.rules { RulesSource::Rules(ref css_rules) => { css_rules.write().remove_rule(index)?; let mut dom_rules = self.dom_rules.borrow_mut(); dom_rules[index].get().map(|r| r.detach()); dom_rules.remove(index); Ok(()) } RulesSource::Keyframes(ref kf) => { // https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-deleterule let mut dom_rules = self.dom_rules.borrow_mut(); dom_rules[index].get().map(|r| r.detach()); dom_rules.remove(index); kf.write().keyframes.remove(index); Ok(()) } } } // Remove parent stylesheets from all children pub fn deparent_all(&self) { for rule in self.dom_rules.borrow().iter() { rule.get().map(|r| Root::upcast(r).deparent()); } } pub fn item(&self, idx: u32) -> Option<Root<CSSRule>> { self.dom_rules.borrow().get(idx as usize).map(|rule| { rule.or_init(|| { let parent_stylesheet = &self.parent_stylesheet; match self.rules { RulesSource::Rules(ref rules) => { CSSRule::new_specific(self.global().as_window(), parent_stylesheet, rules.read().0[idx as usize].clone()) } RulesSource::Keyframes(ref rules) => { Root::upcast(CSSKeyframeRule::new(self.global().as_window(), parent_stylesheet, rules.read() .keyframes[idx as usize] .clone())) } } }) }) } /// Add a rule to the list of DOM rules. This list is lazy, /// so we just append a placeholder. /// /// Should only be called for keyframes-backed rules, use insert_rule /// for CssRules-backed rules pub fn append_lazy_dom_rule(&self) { if let RulesSource::Rules(..) = self.rules { panic!("Can only call append_lazy_rule with keyframes-backed CSSRules"); } self.dom_rules.borrow_mut().push(MutNullableJS::new(None)); } } impl CSSRuleListMethods for CSSRuleList { // https://drafts.csswg.org/cssom/#ref-for-dom-cssrulelist-item-1 fn Item(&self, idx: u32) -> Option<Root<CSSRule>> { self.item(idx) } // https://drafts.csswg.org/cssom/#dom-cssrulelist-length fn Length(&self) -> u32 { self.dom_rules.borrow().len() as u32 } // check-tidy: no specs after this line fn IndexedGetter(&self, index: u32) -> Option<Root<CSSRule>> { self.Item(index) } }
remove_rule
identifier_name
cssrulelist.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 dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CSSRuleListBinding; use dom::bindings::codegen::Bindings::CSSRuleListBinding::CSSRuleListMethods; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::js::{JS, MutNullableJS, Root}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::csskeyframerule::CSSKeyframeRule; use dom::cssrule::CSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use parking_lot::RwLock; use std::sync::Arc; use style::stylesheets::{CssRules, KeyframesRule, RulesMutateError}; #[allow(unsafe_code)] unsafe_no_jsmanaged_fields!(RulesSource); unsafe_no_jsmanaged_fields!(CssRules); impl From<RulesMutateError> for Error { fn from(other: RulesMutateError) -> Self { match other { RulesMutateError::Syntax => Error::Syntax, RulesMutateError::IndexSize => Error::IndexSize, RulesMutateError::HierarchyRequest => Error::HierarchyRequest, RulesMutateError::InvalidState => Error::InvalidState, } } } #[dom_struct] pub struct CSSRuleList { reflector_: Reflector, parent_stylesheet: JS<CSSStyleSheet>, #[ignore_heap_size_of = "Arc"] rules: RulesSource, dom_rules: DOMRefCell<Vec<MutNullableJS<CSSRule>>> } pub enum RulesSource { Rules(Arc<RwLock<CssRules>>), Keyframes(Arc<RwLock<KeyframesRule>>), } impl CSSRuleList { #[allow(unrooted_must_root)] pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, rules: RulesSource) -> CSSRuleList { let dom_rules = match rules { RulesSource::Rules(ref rules) => { rules.read().0.iter().map(|_| MutNullableJS::new(None)).collect() } RulesSource::Keyframes(ref rules) => { rules.read().keyframes.iter().map(|_| MutNullableJS::new(None)).collect() } }; CSSRuleList { reflector_: Reflector::new(), parent_stylesheet: JS::from_ref(parent_stylesheet), rules: rules, dom_rules: DOMRefCell::new(dom_rules), } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, rules: RulesSource) -> Root<CSSRuleList> { reflect_dom_object(box CSSRuleList::new_inherited(parent_stylesheet, rules), window, CSSRuleListBinding::Wrap) } /// Should only be called for CssRules-backed rules. Use append_lazy_rule /// for keyframes-backed rules. pub fn insert_rule(&self, rule: &str, idx: u32, nested: bool) -> Fallible<u32> { let css_rules = if let RulesSource::Rules(ref rules) = self.rules { rules } else { panic!("Called insert_rule on non-CssRule-backed CSSRuleList"); }; let global = self.global(); let window = global.as_window(); let index = idx as usize; let parent_stylesheet = self.parent_stylesheet.style_stylesheet(); let new_rule = css_rules.write().insert_rule(rule, parent_stylesheet, index, nested)?; let parent_stylesheet = &*self.parent_stylesheet; let dom_rule = CSSRule::new_specific(&window, parent_stylesheet, new_rule); self.dom_rules.borrow_mut().insert(index, MutNullableJS::new(Some(&*dom_rule))); Ok((idx)) } // In case of a keyframe rule, index must be valid. pub fn remove_rule(&self, index: u32) -> ErrorResult { let index = index as usize;
match self.rules { RulesSource::Rules(ref css_rules) => { css_rules.write().remove_rule(index)?; let mut dom_rules = self.dom_rules.borrow_mut(); dom_rules[index].get().map(|r| r.detach()); dom_rules.remove(index); Ok(()) } RulesSource::Keyframes(ref kf) => { // https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-deleterule let mut dom_rules = self.dom_rules.borrow_mut(); dom_rules[index].get().map(|r| r.detach()); dom_rules.remove(index); kf.write().keyframes.remove(index); Ok(()) } } } // Remove parent stylesheets from all children pub fn deparent_all(&self) { for rule in self.dom_rules.borrow().iter() { rule.get().map(|r| Root::upcast(r).deparent()); } } pub fn item(&self, idx: u32) -> Option<Root<CSSRule>> { self.dom_rules.borrow().get(idx as usize).map(|rule| { rule.or_init(|| { let parent_stylesheet = &self.parent_stylesheet; match self.rules { RulesSource::Rules(ref rules) => { CSSRule::new_specific(self.global().as_window(), parent_stylesheet, rules.read().0[idx as usize].clone()) } RulesSource::Keyframes(ref rules) => { Root::upcast(CSSKeyframeRule::new(self.global().as_window(), parent_stylesheet, rules.read() .keyframes[idx as usize] .clone())) } } }) }) } /// Add a rule to the list of DOM rules. This list is lazy, /// so we just append a placeholder. /// /// Should only be called for keyframes-backed rules, use insert_rule /// for CssRules-backed rules pub fn append_lazy_dom_rule(&self) { if let RulesSource::Rules(..) = self.rules { panic!("Can only call append_lazy_rule with keyframes-backed CSSRules"); } self.dom_rules.borrow_mut().push(MutNullableJS::new(None)); } } impl CSSRuleListMethods for CSSRuleList { // https://drafts.csswg.org/cssom/#ref-for-dom-cssrulelist-item-1 fn Item(&self, idx: u32) -> Option<Root<CSSRule>> { self.item(idx) } // https://drafts.csswg.org/cssom/#dom-cssrulelist-length fn Length(&self) -> u32 { self.dom_rules.borrow().len() as u32 } // check-tidy: no specs after this line fn IndexedGetter(&self, index: u32) -> Option<Root<CSSRule>> { self.Item(index) } }
random_line_split
cssrulelist.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 dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CSSRuleListBinding; use dom::bindings::codegen::Bindings::CSSRuleListBinding::CSSRuleListMethods; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::js::{JS, MutNullableJS, Root}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::csskeyframerule::CSSKeyframeRule; use dom::cssrule::CSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use parking_lot::RwLock; use std::sync::Arc; use style::stylesheets::{CssRules, KeyframesRule, RulesMutateError}; #[allow(unsafe_code)] unsafe_no_jsmanaged_fields!(RulesSource); unsafe_no_jsmanaged_fields!(CssRules); impl From<RulesMutateError> for Error { fn from(other: RulesMutateError) -> Self { match other { RulesMutateError::Syntax => Error::Syntax, RulesMutateError::IndexSize => Error::IndexSize, RulesMutateError::HierarchyRequest => Error::HierarchyRequest, RulesMutateError::InvalidState => Error::InvalidState, } } } #[dom_struct] pub struct CSSRuleList { reflector_: Reflector, parent_stylesheet: JS<CSSStyleSheet>, #[ignore_heap_size_of = "Arc"] rules: RulesSource, dom_rules: DOMRefCell<Vec<MutNullableJS<CSSRule>>> } pub enum RulesSource { Rules(Arc<RwLock<CssRules>>), Keyframes(Arc<RwLock<KeyframesRule>>), } impl CSSRuleList { #[allow(unrooted_must_root)] pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, rules: RulesSource) -> CSSRuleList { let dom_rules = match rules { RulesSource::Rules(ref rules) => { rules.read().0.iter().map(|_| MutNullableJS::new(None)).collect() } RulesSource::Keyframes(ref rules) => { rules.read().keyframes.iter().map(|_| MutNullableJS::new(None)).collect() } }; CSSRuleList { reflector_: Reflector::new(), parent_stylesheet: JS::from_ref(parent_stylesheet), rules: rules, dom_rules: DOMRefCell::new(dom_rules), } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, rules: RulesSource) -> Root<CSSRuleList> { reflect_dom_object(box CSSRuleList::new_inherited(parent_stylesheet, rules), window, CSSRuleListBinding::Wrap) } /// Should only be called for CssRules-backed rules. Use append_lazy_rule /// for keyframes-backed rules. pub fn insert_rule(&self, rule: &str, idx: u32, nested: bool) -> Fallible<u32> { let css_rules = if let RulesSource::Rules(ref rules) = self.rules { rules } else { panic!("Called insert_rule on non-CssRule-backed CSSRuleList"); }; let global = self.global(); let window = global.as_window(); let index = idx as usize; let parent_stylesheet = self.parent_stylesheet.style_stylesheet(); let new_rule = css_rules.write().insert_rule(rule, parent_stylesheet, index, nested)?; let parent_stylesheet = &*self.parent_stylesheet; let dom_rule = CSSRule::new_specific(&window, parent_stylesheet, new_rule); self.dom_rules.borrow_mut().insert(index, MutNullableJS::new(Some(&*dom_rule))); Ok((idx)) } // In case of a keyframe rule, index must be valid. pub fn remove_rule(&self, index: u32) -> ErrorResult { let index = index as usize; match self.rules { RulesSource::Rules(ref css_rules) => { css_rules.write().remove_rule(index)?; let mut dom_rules = self.dom_rules.borrow_mut(); dom_rules[index].get().map(|r| r.detach()); dom_rules.remove(index); Ok(()) } RulesSource::Keyframes(ref kf) => { // https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-deleterule let mut dom_rules = self.dom_rules.borrow_mut(); dom_rules[index].get().map(|r| r.detach()); dom_rules.remove(index); kf.write().keyframes.remove(index); Ok(()) } } } // Remove parent stylesheets from all children pub fn deparent_all(&self) { for rule in self.dom_rules.borrow().iter() { rule.get().map(|r| Root::upcast(r).deparent()); } } pub fn item(&self, idx: u32) -> Option<Root<CSSRule>> { self.dom_rules.borrow().get(idx as usize).map(|rule| { rule.or_init(|| { let parent_stylesheet = &self.parent_stylesheet; match self.rules { RulesSource::Rules(ref rules) => { CSSRule::new_specific(self.global().as_window(), parent_stylesheet, rules.read().0[idx as usize].clone()) } RulesSource::Keyframes(ref rules) =>
} }) }) } /// Add a rule to the list of DOM rules. This list is lazy, /// so we just append a placeholder. /// /// Should only be called for keyframes-backed rules, use insert_rule /// for CssRules-backed rules pub fn append_lazy_dom_rule(&self) { if let RulesSource::Rules(..) = self.rules { panic!("Can only call append_lazy_rule with keyframes-backed CSSRules"); } self.dom_rules.borrow_mut().push(MutNullableJS::new(None)); } } impl CSSRuleListMethods for CSSRuleList { // https://drafts.csswg.org/cssom/#ref-for-dom-cssrulelist-item-1 fn Item(&self, idx: u32) -> Option<Root<CSSRule>> { self.item(idx) } // https://drafts.csswg.org/cssom/#dom-cssrulelist-length fn Length(&self) -> u32 { self.dom_rules.borrow().len() as u32 } // check-tidy: no specs after this line fn IndexedGetter(&self, index: u32) -> Option<Root<CSSRule>> { self.Item(index) } }
{ Root::upcast(CSSKeyframeRule::new(self.global().as_window(), parent_stylesheet, rules.read() .keyframes[idx as usize] .clone())) }
conditional_block
cssrulelist.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 dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CSSRuleListBinding; use dom::bindings::codegen::Bindings::CSSRuleListBinding::CSSRuleListMethods; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::js::{JS, MutNullableJS, Root}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::csskeyframerule::CSSKeyframeRule; use dom::cssrule::CSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use parking_lot::RwLock; use std::sync::Arc; use style::stylesheets::{CssRules, KeyframesRule, RulesMutateError}; #[allow(unsafe_code)] unsafe_no_jsmanaged_fields!(RulesSource); unsafe_no_jsmanaged_fields!(CssRules); impl From<RulesMutateError> for Error { fn from(other: RulesMutateError) -> Self { match other { RulesMutateError::Syntax => Error::Syntax, RulesMutateError::IndexSize => Error::IndexSize, RulesMutateError::HierarchyRequest => Error::HierarchyRequest, RulesMutateError::InvalidState => Error::InvalidState, } } } #[dom_struct] pub struct CSSRuleList { reflector_: Reflector, parent_stylesheet: JS<CSSStyleSheet>, #[ignore_heap_size_of = "Arc"] rules: RulesSource, dom_rules: DOMRefCell<Vec<MutNullableJS<CSSRule>>> } pub enum RulesSource { Rules(Arc<RwLock<CssRules>>), Keyframes(Arc<RwLock<KeyframesRule>>), } impl CSSRuleList { #[allow(unrooted_must_root)] pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, rules: RulesSource) -> CSSRuleList { let dom_rules = match rules { RulesSource::Rules(ref rules) => { rules.read().0.iter().map(|_| MutNullableJS::new(None)).collect() } RulesSource::Keyframes(ref rules) => { rules.read().keyframes.iter().map(|_| MutNullableJS::new(None)).collect() } }; CSSRuleList { reflector_: Reflector::new(), parent_stylesheet: JS::from_ref(parent_stylesheet), rules: rules, dom_rules: DOMRefCell::new(dom_rules), } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, rules: RulesSource) -> Root<CSSRuleList> { reflect_dom_object(box CSSRuleList::new_inherited(parent_stylesheet, rules), window, CSSRuleListBinding::Wrap) } /// Should only be called for CssRules-backed rules. Use append_lazy_rule /// for keyframes-backed rules. pub fn insert_rule(&self, rule: &str, idx: u32, nested: bool) -> Fallible<u32> { let css_rules = if let RulesSource::Rules(ref rules) = self.rules { rules } else { panic!("Called insert_rule on non-CssRule-backed CSSRuleList"); }; let global = self.global(); let window = global.as_window(); let index = idx as usize; let parent_stylesheet = self.parent_stylesheet.style_stylesheet(); let new_rule = css_rules.write().insert_rule(rule, parent_stylesheet, index, nested)?; let parent_stylesheet = &*self.parent_stylesheet; let dom_rule = CSSRule::new_specific(&window, parent_stylesheet, new_rule); self.dom_rules.borrow_mut().insert(index, MutNullableJS::new(Some(&*dom_rule))); Ok((idx)) } // In case of a keyframe rule, index must be valid. pub fn remove_rule(&self, index: u32) -> ErrorResult { let index = index as usize; match self.rules { RulesSource::Rules(ref css_rules) => { css_rules.write().remove_rule(index)?; let mut dom_rules = self.dom_rules.borrow_mut(); dom_rules[index].get().map(|r| r.detach()); dom_rules.remove(index); Ok(()) } RulesSource::Keyframes(ref kf) => { // https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-deleterule let mut dom_rules = self.dom_rules.borrow_mut(); dom_rules[index].get().map(|r| r.detach()); dom_rules.remove(index); kf.write().keyframes.remove(index); Ok(()) } } } // Remove parent stylesheets from all children pub fn deparent_all(&self) { for rule in self.dom_rules.borrow().iter() { rule.get().map(|r| Root::upcast(r).deparent()); } } pub fn item(&self, idx: u32) -> Option<Root<CSSRule>> { self.dom_rules.borrow().get(idx as usize).map(|rule| { rule.or_init(|| { let parent_stylesheet = &self.parent_stylesheet; match self.rules { RulesSource::Rules(ref rules) => { CSSRule::new_specific(self.global().as_window(), parent_stylesheet, rules.read().0[idx as usize].clone()) } RulesSource::Keyframes(ref rules) => { Root::upcast(CSSKeyframeRule::new(self.global().as_window(), parent_stylesheet, rules.read() .keyframes[idx as usize] .clone())) } } }) }) } /// Add a rule to the list of DOM rules. This list is lazy, /// so we just append a placeholder. /// /// Should only be called for keyframes-backed rules, use insert_rule /// for CssRules-backed rules pub fn append_lazy_dom_rule(&self) { if let RulesSource::Rules(..) = self.rules { panic!("Can only call append_lazy_rule with keyframes-backed CSSRules"); } self.dom_rules.borrow_mut().push(MutNullableJS::new(None)); } } impl CSSRuleListMethods for CSSRuleList { // https://drafts.csswg.org/cssom/#ref-for-dom-cssrulelist-item-1 fn Item(&self, idx: u32) -> Option<Root<CSSRule>>
// https://drafts.csswg.org/cssom/#dom-cssrulelist-length fn Length(&self) -> u32 { self.dom_rules.borrow().len() as u32 } // check-tidy: no specs after this line fn IndexedGetter(&self, index: u32) -> Option<Root<CSSRule>> { self.Item(index) } }
{ self.item(idx) }
identifier_body