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
default.rs
// Copyright 2012-2013 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. use ast::{MetaItem, Item, Expr}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token::InternedString; use ptr::P; pub fn expand_deriving_default<F>(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: F) where F: FnOnce(P<Item>), { let inline = cx.meta_word(span, InternedString::new("inline")); let attrs = vec!(cx.attribute(span, inline)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path_std!(cx, core::default::Default), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!( MethodDef { name: "default", generics: LifetimeBounds::empty(), explicit_self: None, args: Vec::new(), ret_ty: Self, attributes: attrs, combine_substructure: combine_substructure(box |a, b, c| { default_substructure(a, b, c) }) } ), associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) } fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> { let default_ident = vec!( cx.ident_of_std("core"), cx.ident_of("default"), cx.ident_of("Default"), cx.ident_of("default") ); let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new()); return match *substr.fields { StaticStruct(_, ref summary) =>
StaticEnum(..) => { cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs"); // let compilation continue cx.expr_usize(trait_span, 0) } _ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`") }; }
{ match *summary { Unnamed(ref fields) => { if fields.is_empty() { cx.expr_ident(trait_span, substr.type_ident) } else { let exprs = fields.iter().map(|sp| default_call(*sp)).collect(); cx.expr_call_ident(trait_span, substr.type_ident, exprs) } } Named(ref fields) => { let default_fields = fields.iter().map(|&(ident, span)| { cx.field_imm(span, ident, default_call(span)) }).collect(); cx.expr_struct_ident(trait_span, substr.type_ident, default_fields) } } }
conditional_block
default.rs
// Copyright 2012-2013 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. use ast::{MetaItem, Item, Expr}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder;
use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token::InternedString; use ptr::P; pub fn expand_deriving_default<F>(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: F) where F: FnOnce(P<Item>), { let inline = cx.meta_word(span, InternedString::new("inline")); let attrs = vec!(cx.attribute(span, inline)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path_std!(cx, core::default::Default), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!( MethodDef { name: "default", generics: LifetimeBounds::empty(), explicit_self: None, args: Vec::new(), ret_ty: Self, attributes: attrs, combine_substructure: combine_substructure(box |a, b, c| { default_substructure(a, b, c) }) } ), associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) } fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> { let default_ident = vec!( cx.ident_of_std("core"), cx.ident_of("default"), cx.ident_of("Default"), cx.ident_of("default") ); let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new()); return match *substr.fields { StaticStruct(_, ref summary) => { match *summary { Unnamed(ref fields) => { if fields.is_empty() { cx.expr_ident(trait_span, substr.type_ident) } else { let exprs = fields.iter().map(|sp| default_call(*sp)).collect(); cx.expr_call_ident(trait_span, substr.type_ident, exprs) } } Named(ref fields) => { let default_fields = fields.iter().map(|&(ident, span)| { cx.field_imm(span, ident, default_call(span)) }).collect(); cx.expr_struct_ident(trait_span, substr.type_ident, default_fields) } } } StaticEnum(..) => { cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs"); // let compilation continue cx.expr_usize(trait_span, 0) } _ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`") }; }
random_line_split
default.rs
// Copyright 2012-2013 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. use ast::{MetaItem, Item, Expr}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token::InternedString; use ptr::P; pub fn
<F>(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: F) where F: FnOnce(P<Item>), { let inline = cx.meta_word(span, InternedString::new("inline")); let attrs = vec!(cx.attribute(span, inline)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path_std!(cx, core::default::Default), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!( MethodDef { name: "default", generics: LifetimeBounds::empty(), explicit_self: None, args: Vec::new(), ret_ty: Self, attributes: attrs, combine_substructure: combine_substructure(box |a, b, c| { default_substructure(a, b, c) }) } ), associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) } fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> { let default_ident = vec!( cx.ident_of_std("core"), cx.ident_of("default"), cx.ident_of("Default"), cx.ident_of("default") ); let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new()); return match *substr.fields { StaticStruct(_, ref summary) => { match *summary { Unnamed(ref fields) => { if fields.is_empty() { cx.expr_ident(trait_span, substr.type_ident) } else { let exprs = fields.iter().map(|sp| default_call(*sp)).collect(); cx.expr_call_ident(trait_span, substr.type_ident, exprs) } } Named(ref fields) => { let default_fields = fields.iter().map(|&(ident, span)| { cx.field_imm(span, ident, default_call(span)) }).collect(); cx.expr_struct_ident(trait_span, substr.type_ident, default_fields) } } } StaticEnum(..) => { cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs"); // let compilation continue cx.expr_usize(trait_span, 0) } _ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`") }; }
expand_deriving_default
identifier_name
cmd.rs
graph::Graph; use crate::progress::Progress; use crate::sim::{Io, GlobalState, RoutingAlgorithm}; use crate::algorithms::vivaldi_routing::VivaldiRouting; use crate::algorithms::random_routing::RandomRouting; use crate::algorithms::spring_routing::SpringRouting; use crate::algorithms::genetic_routing::GeneticRouting; use crate::algorithms::spanning_tree_routing::SpanningTreeRouting; use crate::importer::import_file; use crate::exporter::export_file; use crate::utils::{fmt_duration, DEG2KM, MyError}; use crate::movements::Movements; #[derive(PartialEq)] enum AllowRecursiveCall { No, Yes } // trigger blocking read to exit loop fn send_dummy_to_socket(address: &str) { match TcpStream::connect(address) { Ok(mut stream) => { let _ = stream.set_read_timeout(Some(Duration::from_millis(100))); let _ = stream.write("".as_bytes()); }, Err(e) => { eprintln!("{}", e); } } } fn send_dummy_to_stdin() { let _ = std::io::stdout().write("".as_bytes()); } pub fn ext_loop(sim: Arc<Mutex<GlobalState>>, address: &str) { match TcpListener::bind(address) { Err(err) => { println!("{}", err); }, Ok(listener) => { println!("Listen for commands on {}", address); //let mut input = vec![0u8; 512]; let mut output = String::new(); loop { //input.clear(); output.clear(); if let Ok((mut stream, _addr)) = listener.accept() { let mut buf = [0; 512]; if let Ok(n) = stream.read(&mut buf) { if let (Ok(s), Ok(mut sim)) = (std::str::from_utf8(&buf[0..n]), sim.lock()) { if sim.abort_simulation { // abort loop break; } else if let Err(e) = cmd_handler(&mut output, &mut sim, s, AllowRecursiveCall::Yes) { let _ = stream.write(e.to_string().as_bytes()); } else { let _ = stream.write(&output.as_bytes()); } } } } } } } } pub fn cmd_loop(sim: Arc<Mutex<GlobalState>>, run: &str) { let mut input = run.to_owned(); let mut output = String::new(); loop { if input.len() == 0 { let _ = std::io::stdin().read_line(&mut input); } if let Ok(mut sim) = sim.lock() { output.clear(); if let Err(e) = cmd_handler(&mut output, &mut sim, &input, AllowRecursiveCall::Yes) { let _ = std::io::stderr().write(e.to_string().as_bytes()); } else { let _ = std::io::stdout().write(output.as_bytes()); } if sim.abort_simulation { // abort loop break; } } input.clear(); } } macro_rules! scan { ( $iter:expr, $( $x:ty ),+ ) => {{ ($($iter.next().and_then(|word| word.parse::<$x>().ok()),)*) }} } enum Command { Error(String), Ignore, Help, ClearGraph, GraphInfo, SimInfo, ResetSim, Exit, Progress(Option<bool>), ShowMinimumSpanningTree, CropMinimumSpanningTree, Test(u32), Debug(u32, u32), DebugStep(u32), Get(String), Set(String, String), ConnectInRange(f32), RandomizePositions(f32), RemoveUnconnected, Algorithm(Option<String>), AddLine(u32, bool), AddTree(u32, u32), AddStar(u32), AddLattice4(u32, u32), AddLattice8(u32, u32), Positions(bool), RemoveNodes(Vec<u32>), ConnectNodes(Vec<u32>), DisconnectNodes(Vec<u32>), SimStep(u32), Run(String), Import(String), ExportPath(Option<String>), MoveNode(u32, f32, f32, f32), MoveNodes(f32, f32, f32), MoveTo(f32, f32, f32), } #[derive(Clone, Copy, PartialEq)] enum Cid { Error, Help, ClearGraph, GraphInfo, SimInfo, ResetSim, Exit, Progress, ShowMinimumSpanningTree, CropMinimumSpanningTree, Test, Debug, DebugStep, Get, Set, ConnectInRange, RandomizePositions, RemoveUnconnected, Algorithm, AddLine, AddTree, AddStar, AddLattice4, AddLattice8, Positions, RemoveNodes, ConnectNodes, DisconnectNodes, SimStep, Run, Import, ExportPath, MoveNode, MoveNodes, MoveTo } const COMMANDS: &'static [(&'static str, Cid)] = &[ ("algo [<algorithm>] Get or set given algorithm.", Cid::Algorithm), ("sim_step [<steps>] Run simulation steps. Default is 1.", Cid::SimStep), ("sim_reset Reset simulation.", Cid::ResetSim), ("sim_info Show simulator information.", Cid::SimInfo), ("progress [<true|false>] Show simulation progress.", Cid::Progress), ("test [<samples>] Test routing algorithm with (test packets arrived, path stretch).", Cid::Test), ("debug_init <from> <to> Debug a path step wise.", Cid::Debug), ("debug_step [<steps>] Perform step on path.", Cid::DebugStep), ("", Cid::Error), ("graph_info Show graph information", Cid::GraphInfo), ("get <key> Get node property.", Cid::Get), ("set <key> <value> Set node property.", Cid::Set), ("", Cid::Error), ("graph_clear Clear graph", Cid::ClearGraph), ("line <node_count> [<create_loop>] Add a line of nodes. Connect ends to create a loop.", Cid::AddLine), ("star <edge_count> Add star structure of nodes.", Cid::AddStar), ("tree <node_count> [<inter_count>] Add a tree structure of nodes with interconnections", Cid::AddTree), ("lattice4 <x_xount> <y_count> Create a lattice structure of squares.", Cid::AddLattice4), ("lattice8 <x_xount> <y_count> Create a lattice structure of squares and diagonal connections.", Cid::AddLattice8), ("remove_nodes <node_list> Remove nodes. Node list is a comma separated list of node ids.", Cid::RemoveNodes), ("connect_nodes <node_list> Connect nodes. Node list is a comma separated list of node ids.", Cid::ConnectNodes), ("disconnect_nodes <node_list> Disconnect nodes. Node list is a comma separated list of node ids.", Cid::DisconnectNodes), ("remove_unconnected Remove nodes without any connections.", Cid::RemoveUnconnected), ("", Cid::Error), ("positions <true|false> Enable geo positions.", Cid::Positions), ("move_node <node_id> <x> <y> <z> Move a node by x/y/z (in km).", Cid::MoveNode), ("move_nodes <x> <y> <z> Move all nodes by x/y/z (in km).", Cid::MoveNodes), ("move_to <x> <y> <z> Move all nodes to x/y/z (in degrees).", Cid::MoveTo), ("rnd_pos <range> Randomize node positions in an area with width (in km) around node center.", Cid::RandomizePositions), ("connect_in_range <range> Connect all nodes in range of less then range (in km).", Cid::ConnectInRange), ("", Cid::Error), ("run <file> Run commands from a script.", Cid::Run), ("import <file> Import a graph as JSON file.", Cid::Import), ("export [<file>] Get or set graph export file.", Cid::ExportPath), ("show_mst Mark the minimum spanning tree.", Cid::ShowMinimumSpanningTree), ("crop_mst Only leave the minimum spanning tree.", Cid::CropMinimumSpanningTree), ("exit Exit simulator.", Cid::Exit), ("help Show this help.", Cid::Help), ]; fn parse_command(input: &str) -> Command { let mut tokens = Vec::new(); for tok in input.split_whitespace() { // trim'" characters tokens.push(tok.trim_matches(|c: char| (c == '\'') || (c == '"'))); } let mut iter = tokens.iter().skip(1); let cmd = tokens.get(0).unwrap_or(&""); fn is_first_token(string: &str, tok: &str) -> bool { string.starts_with(tok) && (string.len() > tok.len()) && (string.as_bytes()[tok.len()] =='' as u8) } fn lookup_cmd(cmd: &str) -> Cid { for item in COMMANDS { if is_first_token(item.0, cmd) { return item.1; } } Cid::Error } // parse number separated list of numbers fn parse_list(numbers: Option<&&str>) -> Result<Vec<u32>, ()> { let mut v = Vec::<u32>::new(); for num in numbers.unwrap_or(&"").split(",") { if let Ok(n) = num.parse::<u32>() { v.push(n); } else { return Err(()); } } Ok(v) } let error = Command::Error("Missing Arguments".to_string()); match lookup_cmd(cmd) { Cid::Help => Command::Help, Cid::SimInfo => Command::SimInfo, Cid::GraphInfo => Command::GraphInfo, Cid::ClearGraph => Command::ClearGraph, Cid::ResetSim => Command::ResetSim, Cid::Exit => Command::Exit, Cid::Progress => { if let (Some(progress),) = scan!(iter, bool) { Command::Progress(Some(progress)) } else { Command::Progress(None) } }, Cid::ShowMinimumSpanningTree => Command::ShowMinimumSpanningTree, Cid::CropMinimumSpanningTree => Command::CropMinimumSpanningTree, Cid::Test => { if let (Some(samples),) = scan!(iter, u32) { Command::Test(samples) } else { Command::Test(1000) } }, Cid::Debug => { if let (Some(from), Some(to)) = scan!(iter, u32, u32) { Command::Debug(from, to) } else { error } }, Cid::DebugStep => { if let (Some(steps),) = scan!(iter, u32) { Command::DebugStep(steps) } else { Command::DebugStep(1) } }, Cid::Get => { if let (Some(key),) = scan!(iter, String) { Command::Get(key) } else { error } }, Cid::Set => { if let (Some(key),Some(value)) = scan!(iter, String, String) { Command::Set(key, value) } else { error } }, Cid::SimStep => { Command::SimStep(if let (Some(count),) = scan!(iter, u32) { count } else { 1 }) }, Cid::Run => { if let (Some(path),) = scan!(iter, String) { Command::Run(path) } else { error } }, Cid::Import => { if let (Some(path),) = scan!(iter, String) { Command::Import(path) } else { error } }, Cid::ExportPath => { if let (Some(path),) = scan!(iter, String) { Command::ExportPath(Some(path)) } else { Command::ExportPath(None) } }, Cid::MoveNodes => { if let (Some(x), Some(y), Some(z)) = scan!(iter, f32, f32, f32) { Command::MoveNodes(x, y, z) } else { error } }, Cid::MoveNode => { if let (Some(id), Some(x), Some(y), Some(z)) = scan!(iter, u32, f32, f32, f32) { Command::MoveNode(id, x, y, z) } else { error } }, Cid::AddLine => { let mut iter1 = iter.clone(); let mut iter2 = iter.clone(); if let (Some(count), Some(close)) = scan!(iter1, u32, bool) { Command::AddLine(count, close) } else if let (Some(count),) = scan!(iter2, u32) { Command::AddLine(count, false) } else { error } }, Cid::AddTree => { let mut iter1 = iter.clone(); let mut iter2 = iter.clone(); if let (Some(count), Some(intra)) = scan!(iter1, u32, u32) { Command::AddTree(count, intra) } else if let (Some(count),) = scan!(iter2, u32) { Command::AddTree(count, 0) } else { error } }, Cid::AddStar => { if let (Some(count),) = scan!(iter, u32) { Command::AddStar(count) } else { error } }, Cid::AddLattice4 => { if let (Some(x_count), Some(y_count)) = scan!(iter, u32, u32) { Command::AddLattice4(x_count, y_count) } else { error } }, Cid::AddLattice8 => { if let (Some(x_count), Some(y_count)) = scan!(iter, u32, u32) { Command::AddLattice8(x_count, y_count) } else { error } }, Cid::Positions => { if let (Some(enable),) = scan!(iter, bool) { Command::Positions(enable) } else { error } }, Cid::ConnectInRange => { if let (Some(range),) = scan!(iter, f32) { Command::ConnectInRange(range) } else { error } }, Cid::RandomizePositions => { if let (Some(range),) = scan!(iter, f32) { Command::RandomizePositions(range) } else { error } }, Cid::Algorithm => { if let (Some(algo),) = scan!(iter, String) { Command::Algorithm(Some(algo)) } else { Command::Algorithm(None) } }, Cid::RemoveNodes => { if let Ok(ids) = parse_list(tokens.get(1)) { Command::RemoveNodes(ids) } else { error } }, Cid::ConnectNodes => { if let Ok(ids) = parse_list(tokens.get(1)) { Command::ConnectNodes(ids) } else { error } }, Cid::DisconnectNodes => { if let Ok(ids) = parse_list(tokens.get(1)) { Command::DisconnectNodes(ids) } else { error } }, Cid::RemoveUnconnected => { Command::RemoveUnconnected }, Cid::MoveTo => { if let (Some(x), Some(y), Some(z)) = scan!(iter, f32, f32, f32) { Command::MoveTo(x, y, z) } else { error } }, Cid::Error => { if cmd.is_empty() { Command::Ignore } else if cmd.trim_start().starts_with("#") { Command::Ignore } else { Command::Error(format!("Unknown Command: {}", cmd)) } } } } fn
(out: &mut std::fmt::Write) -> Result<(), MyError> { for item in COMMANDS { if item.1!= Cid::Error { writeln!(out, "{}", item.0)?; } } Ok(()) } fn cmd_handler(out: &mut std::fmt::Write, sim: &mut GlobalState, input: &str, call: AllowRecursiveCall) -> Result<(), MyError> { let mut mark_links : Option<Graph> = None; let mut do_init = false; //println!("command: '{}'", input); let command = parse_command(input); match command { Command::Ignore => { // nothing to do }, Command::Progress(show) => { if let Some(show) = show { sim.show_progress = show; } writeln!(out, "show progress: {}", if sim.show_progress { "enabled" } else { "disabled" })?; }, Command::Exit => { sim.abort_simulation = true; send_dummy_to_socket(&sim.cmd_address); send_dummy_to_stdin(); }, Command::ShowMinimumSpanningTree => { let mst = sim.graph.minimum_spanning_tree(); if mst.node_count() > 0 { mark_links = Some(mst); } }, Command::CropMinimumSpanningTree => { // mst is only a uni-directional graph...!! let mst = sim.graph.minimum_spanning_tree(); if mst.node_count() > 0 { sim.graph = mst; } }, Command::Error(msg) => { //TODO: return Result error writeln!(out, "{}", msg)?; }, Command::Help => { print_help(out)?; }, Command::Get(key) => { let mut buf = String::new(); sim.algorithm.get(&key, &mut buf)?; writeln!(out, "{}", buf)?; }, Command::Set(key, value) => { sim.algorithm.set(&key, &value)?; }, Command::GraphInfo => { let node_count = sim.graph.node_count(); let link_count = sim.graph.link_count(); let avg_node_degree = sim.graph.get_avg_node_degree(); writeln!(out, "nodes: {}, links: {}", node_count, link_count)?; writeln!(out, "locations: {}, metadata: {}", sim.locations.data.len(), sim.meta.data.len())?; writeln!(out, "average node degree: {}", avg_node_degree)?; /* if (verbose) { let mean_clustering_coefficient = state.graph.get_mean_clustering_coefficient(); let mean_link_count = state.graph.get_mean_link_count(); let mean_link_distance = state.get_mean_link_distance(); writeln!(out, "mean clustering coefficient: {}", mean_clustering_coefficient)?; writeln!(out, "mean link count: {} ({} variance)", mean_link_count.0, mean_link_count.1)?; writeln!(out, "mean link distance: {} ({} variance)", mean_link_distance.0, mean_link_distance.1)?; } */ }, Command::SimInfo => { write!(out, " algo: ")?; sim.algorithm.get("name", out)?; writeln!(out, "\n steps: {}", sim.sim_steps)?; }, Command::ClearGraph => { sim.graph.clear(); do_init = true; writeln!(out, "done")?; }, Command::ResetSim => { sim.test.clear(); //state.graph.clear(); sim.sim_steps = 0; do_init = true; writeln!(out, "done")?; }, Command::SimStep(count) => { let mut progress = Progress::new(); let now = Instant::now(); let mut io = Io::new(&sim.graph); for step in 0..count { if sim.abort_simulation { break; } sim.algorithm.step(&mut io); sim.movements.step(&mut sim.locations); sim.sim_steps += 1; if sim.show_progress { progress.update((count + 1) as usize, step as usize); } } let duration = now.elapsed(); writeln!(out, "Run {} simulation steps, duration: {}", count, fmt_duration(duration))?; }, Command::Test(samples) => { fn run_test(out: &mut std::fmt::Write, test: &mut EvalPaths, graph: &Graph, algo: &Box<RoutingAlgorithm>, samples: u32) -> Result<(), std::fmt::Error> { test.clear(); test.run_samples(graph, |p| algo.route(&p), samples as usize); writeln!(out, "samples: {}, arrived: {:.1}, stretch: {}, duration: {}", samples, test.arrived(), test.stretch(), fmt_duration(test.duration()) ) } sim.test.show_progress(sim.show_progress); run_test(out, &mut sim.test, &sim.graph, &sim.algorithm, samples)?; }, Command::Debug(from, to) => { let node_count = sim.graph.node_count() as u32; if (from < node_count) && (from < node_count) { sim.debug_path.init(from, to); writeln!(out, "Init path debugger: {} => {}", from, to)?; } else { writeln!(out, "Invalid path: {} => {}", from, to)?; } }, Command::DebugStep(steps) => { fn run_test(out: &mut std::fmt::Write, debug_path: &mut DebugPath, graph: &Graph, algo: &Box<RoutingAlgorithm>) -> Result<(), MyError> { debug_path.step(out, graph, |p| algo.route(&p)) } for _ in 0..steps { run_test(out, &mut sim.debug_path, &sim.graph, &sim.algorithm)?; } } Command::Import(ref path) => { import_file(&mut sim.graph, Some(&mut sim.locations), Some(&mut sim.meta), path.as_str())?; do_init = true; writeln!(out, "Import done: {}", path)?; }, Command::ExportPath(path) => { if let Some(path) = path { sim.export_path = path; } writeln!(out, "Export done: {}", sim.export_path)?; }, Command::AddLine(count, close) => { sim.add_line(count, close); do_init = true; }, Command::MoveNodes(x, y, z) => { sim.locations.move_nodes([x, y, z]); }, Command::MoveNode(id, x, y, z) => { sim.locations.move_node(id, [x, y, z]); }, Command::AddTree(count, intra) => { sim.add_tree(count, intra); do_init = true; }, Command::AddStar(count) => { sim.add_star(count); do_init = true; }, Command::AddLattice4(x_count, y_count) => { sim.add_lattice4(x_count, y_count); do_init = true; }, Command::AddLattice8(x_count, y_count) => { sim.add_lattice8(x_count, y_count); do_init = true; }, Command::Positions(enable) => { if enable { // add positions to node that have none let node_count = sim.graph.node_count(); sim.locations.init_positions(node_count, [0.0, 0.0, 0.0]); } else { sim.locations.clear(); } writeln!(out, "positions: {}", if enable { "enabled" } else { "disabled" })?; } Command::RandomizePositions(range) => { let center = sim.locations.graph_center(); sim.locations.randomize_positions_2d(center, range); }, Command::ConnectInRange(range) => { sim.connect_in_range(range); }, Command::Algorithm(algo) => { if let Some(algo) = algo { match algo.as_str() { "random" => { sim.algorithm = Box::new(RandomRouting::new()); do_init = true; }, "vivaldi" => { sim.algorithm = Box::new(VivaldiRouting::new()); do_init = true; }, "spring" => { sim.algorithm = Box::new(SpringRouting::new()); do_init = true; }, "genetic" => { sim.algorithm = Box::new(GeneticRouting::new()); do_init = true; }, "tree" => { sim.algorithm = Box::new(SpanningTreeRouting::new()); do_init = true; } _ => { writeln!(out, "Unknown algorithm: {}", algo)?; } } if do_init { writeln!(out, "Done")?; } } else { write!(out, "selected: ")?; sim.algorithm.get("name", out)?; write!(out, "\n")?; write!(out, "available: random, vivaldi, spring, genetic, tree\n")?; } }, Command::Run(path) => { if call == AllowRecursiveCall::Yes { if let Ok(file) = File::open(&path) { for (index, line) in BufReader::new(file).lines().enumerate() { let line = line.unwrap(); if let Err(err) = cmd_handler(out, sim, &line, AllowRecursiveCall::No) { writeln!(out, "Error in {}:{}: {}", path, index, err)?; sim.abort_simulation = true; break; } } } else { writeln!(out, "File not found: {}", &path)?; } } else { writeln!(out, "Recursive call not allowed: {}", &path)?; } }, Command::RemoveUnconnected => { sim.graph.remove_unconnected_nodes(); do_init = true; }, Command::RemoveNodes(ids) => { sim.graph.remove_nodes(&ids); }, Command::ConnectNodes(ids) => {
print_help
identifier_name
cmd.rs
::graph::Graph; use crate::progress::Progress; use crate::sim::{Io, GlobalState, RoutingAlgorithm}; use crate::algorithms::vivaldi_routing::VivaldiRouting; use crate::algorithms::random_routing::RandomRouting; use crate::algorithms::spring_routing::SpringRouting; use crate::algorithms::genetic_routing::GeneticRouting; use crate::algorithms::spanning_tree_routing::SpanningTreeRouting; use crate::importer::import_file; use crate::exporter::export_file; use crate::utils::{fmt_duration, DEG2KM, MyError}; use crate::movements::Movements; #[derive(PartialEq)] enum AllowRecursiveCall { No, Yes } // trigger blocking read to exit loop fn send_dummy_to_socket(address: &str) { match TcpStream::connect(address) { Ok(mut stream) => { let _ = stream.set_read_timeout(Some(Duration::from_millis(100))); let _ = stream.write("".as_bytes()); }, Err(e) => { eprintln!("{}", e); } } } fn send_dummy_to_stdin() { let _ = std::io::stdout().write("".as_bytes()); } pub fn ext_loop(sim: Arc<Mutex<GlobalState>>, address: &str) { match TcpListener::bind(address) { Err(err) => { println!("{}", err); }, Ok(listener) => { println!("Listen for commands on {}", address); //let mut input = vec![0u8; 512]; let mut output = String::new(); loop { //input.clear(); output.clear(); if let Ok((mut stream, _addr)) = listener.accept() { let mut buf = [0; 512]; if let Ok(n) = stream.read(&mut buf) { if let (Ok(s), Ok(mut sim)) = (std::str::from_utf8(&buf[0..n]), sim.lock()) { if sim.abort_simulation { // abort loop break; } else if let Err(e) = cmd_handler(&mut output, &mut sim, s, AllowRecursiveCall::Yes) { let _ = stream.write(e.to_string().as_bytes()); } else { let _ = stream.write(&output.as_bytes()); } } } } } } } } pub fn cmd_loop(sim: Arc<Mutex<GlobalState>>, run: &str) { let mut input = run.to_owned(); let mut output = String::new(); loop { if input.len() == 0 { let _ = std::io::stdin().read_line(&mut input); } if let Ok(mut sim) = sim.lock() { output.clear(); if let Err(e) = cmd_handler(&mut output, &mut sim, &input, AllowRecursiveCall::Yes) { let _ = std::io::stderr().write(e.to_string().as_bytes()); } else { let _ = std::io::stdout().write(output.as_bytes()); } if sim.abort_simulation { // abort loop break; } } input.clear(); } } macro_rules! scan { ( $iter:expr, $( $x:ty ),+ ) => {{ ($($iter.next().and_then(|word| word.parse::<$x>().ok()),)*) }} } enum Command { Error(String), Ignore, Help, ClearGraph, GraphInfo, SimInfo, ResetSim, Exit, Progress(Option<bool>), ShowMinimumSpanningTree, CropMinimumSpanningTree, Test(u32), Debug(u32, u32), DebugStep(u32), Get(String), Set(String, String), ConnectInRange(f32), RandomizePositions(f32), RemoveUnconnected, Algorithm(Option<String>), AddLine(u32, bool), AddTree(u32, u32), AddStar(u32), AddLattice4(u32, u32), AddLattice8(u32, u32), Positions(bool), RemoveNodes(Vec<u32>), ConnectNodes(Vec<u32>), DisconnectNodes(Vec<u32>), SimStep(u32), Run(String), Import(String), ExportPath(Option<String>), MoveNode(u32, f32, f32, f32), MoveNodes(f32, f32, f32), MoveTo(f32, f32, f32), } #[derive(Clone, Copy, PartialEq)] enum Cid { Error, Help, ClearGraph, GraphInfo, SimInfo, ResetSim, Exit, Progress, ShowMinimumSpanningTree, CropMinimumSpanningTree, Test, Debug, DebugStep, Get, Set, ConnectInRange, RandomizePositions, RemoveUnconnected, Algorithm, AddLine, AddTree, AddStar, AddLattice4, AddLattice8, Positions, RemoveNodes, ConnectNodes, DisconnectNodes, SimStep, Run, Import, ExportPath, MoveNode, MoveNodes, MoveTo } const COMMANDS: &'static [(&'static str, Cid)] = &[ ("algo [<algorithm>] Get or set given algorithm.", Cid::Algorithm), ("sim_step [<steps>] Run simulation steps. Default is 1.", Cid::SimStep), ("sim_reset Reset simulation.", Cid::ResetSim), ("sim_info Show simulator information.", Cid::SimInfo), ("progress [<true|false>] Show simulation progress.", Cid::Progress), ("test [<samples>] Test routing algorithm with (test packets arrived, path stretch).", Cid::Test), ("debug_init <from> <to> Debug a path step wise.", Cid::Debug), ("debug_step [<steps>] Perform step on path.", Cid::DebugStep), ("", Cid::Error), ("graph_info Show graph information", Cid::GraphInfo), ("get <key> Get node property.", Cid::Get), ("set <key> <value> Set node property.", Cid::Set), ("", Cid::Error), ("graph_clear Clear graph", Cid::ClearGraph), ("line <node_count> [<create_loop>] Add a line of nodes. Connect ends to create a loop.", Cid::AddLine), ("star <edge_count> Add star structure of nodes.", Cid::AddStar), ("tree <node_count> [<inter_count>] Add a tree structure of nodes with interconnections", Cid::AddTree), ("lattice4 <x_xount> <y_count> Create a lattice structure of squares.", Cid::AddLattice4), ("lattice8 <x_xount> <y_count> Create a lattice structure of squares and diagonal connections.", Cid::AddLattice8), ("remove_nodes <node_list> Remove nodes. Node list is a comma separated list of node ids.", Cid::RemoveNodes), ("connect_nodes <node_list> Connect nodes. Node list is a comma separated list of node ids.", Cid::ConnectNodes), ("disconnect_nodes <node_list> Disconnect nodes. Node list is a comma separated list of node ids.", Cid::DisconnectNodes), ("remove_unconnected Remove nodes without any connections.", Cid::RemoveUnconnected), ("", Cid::Error), ("positions <true|false> Enable geo positions.", Cid::Positions), ("move_node <node_id> <x> <y> <z> Move a node by x/y/z (in km).", Cid::MoveNode), ("move_nodes <x> <y> <z> Move all nodes by x/y/z (in km).", Cid::MoveNodes), ("move_to <x> <y> <z> Move all nodes to x/y/z (in degrees).", Cid::MoveTo), ("rnd_pos <range> Randomize node positions in an area with width (in km) around node center.", Cid::RandomizePositions), ("connect_in_range <range> Connect all nodes in range of less then range (in km).", Cid::ConnectInRange), ("", Cid::Error), ("run <file> Run commands from a script.", Cid::Run), ("import <file> Import a graph as JSON file.", Cid::Import), ("export [<file>] Get or set graph export file.", Cid::ExportPath), ("show_mst Mark the minimum spanning tree.", Cid::ShowMinimumSpanningTree), ("crop_mst Only leave the minimum spanning tree.", Cid::CropMinimumSpanningTree), ("exit Exit simulator.", Cid::Exit), ("help Show this help.", Cid::Help), ]; fn parse_command(input: &str) -> Command { let mut tokens = Vec::new(); for tok in input.split_whitespace() { // trim'" characters tokens.push(tok.trim_matches(|c: char| (c == '\'') || (c == '"'))); } let mut iter = tokens.iter().skip(1); let cmd = tokens.get(0).unwrap_or(&""); fn is_first_token(string: &str, tok: &str) -> bool { string.starts_with(tok) && (string.len() > tok.len()) && (string.as_bytes()[tok.len()] =='' as u8) } fn lookup_cmd(cmd: &str) -> Cid { for item in COMMANDS { if is_first_token(item.0, cmd) { return item.1; } } Cid::Error } // parse number separated list of numbers fn parse_list(numbers: Option<&&str>) -> Result<Vec<u32>, ()> { let mut v = Vec::<u32>::new(); for num in numbers.unwrap_or(&"").split(",") { if let Ok(n) = num.parse::<u32>() { v.push(n); } else { return Err(()); } } Ok(v) } let error = Command::Error("Missing Arguments".to_string()); match lookup_cmd(cmd) { Cid::Help => Command::Help, Cid::SimInfo => Command::SimInfo, Cid::GraphInfo => Command::GraphInfo, Cid::ClearGraph => Command::ClearGraph, Cid::ResetSim => Command::ResetSim, Cid::Exit => Command::Exit, Cid::Progress => { if let (Some(progress),) = scan!(iter, bool) { Command::Progress(Some(progress)) } else { Command::Progress(None) } }, Cid::ShowMinimumSpanningTree => Command::ShowMinimumSpanningTree, Cid::CropMinimumSpanningTree => Command::CropMinimumSpanningTree, Cid::Test => { if let (Some(samples),) = scan!(iter, u32) { Command::Test(samples) } else { Command::Test(1000) } }, Cid::Debug => { if let (Some(from), Some(to)) = scan!(iter, u32, u32) { Command::Debug(from, to) } else { error } }, Cid::DebugStep => { if let (Some(steps),) = scan!(iter, u32) { Command::DebugStep(steps) } else { Command::DebugStep(1) } }, Cid::Get => { if let (Some(key),) = scan!(iter, String) { Command::Get(key) } else { error } }, Cid::Set => { if let (Some(key),Some(value)) = scan!(iter, String, String) { Command::Set(key, value) } else { error } }, Cid::SimStep => { Command::SimStep(if let (Some(count),) = scan!(iter, u32) { count } else { 1 }) }, Cid::Run => { if let (Some(path),) = scan!(iter, String) { Command::Run(path) } else { error } }, Cid::Import => { if let (Some(path),) = scan!(iter, String) { Command::Import(path) } else { error } }, Cid::ExportPath => { if let (Some(path),) = scan!(iter, String) { Command::ExportPath(Some(path)) } else { Command::ExportPath(None) } }, Cid::MoveNodes => { if let (Some(x), Some(y), Some(z)) = scan!(iter, f32, f32, f32) { Command::MoveNodes(x, y, z) } else { error } }, Cid::MoveNode => { if let (Some(id), Some(x), Some(y), Some(z)) = scan!(iter, u32, f32, f32, f32) { Command::MoveNode(id, x, y, z) } else { error } }, Cid::AddLine => { let mut iter1 = iter.clone(); let mut iter2 = iter.clone(); if let (Some(count), Some(close)) = scan!(iter1, u32, bool) { Command::AddLine(count, close) } else if let (Some(count),) = scan!(iter2, u32) { Command::AddLine(count, false) } else { error } }, Cid::AddTree => { let mut iter1 = iter.clone(); let mut iter2 = iter.clone(); if let (Some(count), Some(intra)) = scan!(iter1, u32, u32) { Command::AddTree(count, intra) } else if let (Some(count),) = scan!(iter2, u32) { Command::AddTree(count, 0) } else { error } }, Cid::AddStar => { if let (Some(count),) = scan!(iter, u32) { Command::AddStar(count) } else { error } }, Cid::AddLattice4 => { if let (Some(x_count), Some(y_count)) = scan!(iter, u32, u32) { Command::AddLattice4(x_count, y_count) } else { error } }, Cid::AddLattice8 => { if let (Some(x_count), Some(y_count)) = scan!(iter, u32, u32) { Command::AddLattice8(x_count, y_count) } else { error } }, Cid::Positions => { if let (Some(enable),) = scan!(iter, bool) { Command::Positions(enable) } else { error } }, Cid::ConnectInRange => { if let (Some(range),) = scan!(iter, f32) { Command::ConnectInRange(range) } else { error } }, Cid::RandomizePositions => { if let (Some(range),) = scan!(iter, f32) { Command::RandomizePositions(range) } else { error } }, Cid::Algorithm => { if let (Some(algo),) = scan!(iter, String) { Command::Algorithm(Some(algo)) } else { Command::Algorithm(None) } }, Cid::RemoveNodes => { if let Ok(ids) = parse_list(tokens.get(1)) { Command::RemoveNodes(ids) } else { error } }, Cid::ConnectNodes => { if let Ok(ids) = parse_list(tokens.get(1)) { Command::ConnectNodes(ids) } else { error } }, Cid::DisconnectNodes => { if let Ok(ids) = parse_list(tokens.get(1)) { Command::DisconnectNodes(ids) } else { error } }, Cid::RemoveUnconnected => { Command::RemoveUnconnected }, Cid::MoveTo => { if let (Some(x), Some(y), Some(z)) = scan!(iter, f32, f32, f32) { Command::MoveTo(x, y, z) } else { error } }, Cid::Error => { if cmd.is_empty() { Command::Ignore } else if cmd.trim_start().starts_with("#") { Command::Ignore } else { Command::Error(format!("Unknown Command: {}", cmd)) } } } } fn print_help(out: &mut std::fmt::Write) -> Result<(), MyError> { for item in COMMANDS { if item.1!= Cid::Error { writeln!(out, "{}", item.0)?; } } Ok(()) } fn cmd_handler(out: &mut std::fmt::Write, sim: &mut GlobalState, input: &str, call: AllowRecursiveCall) -> Result<(), MyError> { let mut mark_links : Option<Graph> = None; let mut do_init = false; //println!("command: '{}'", input); let command = parse_command(input); match command { Command::Ignore => { // nothing to do }, Command::Progress(show) => { if let Some(show) = show { sim.show_progress = show; } writeln!(out, "show progress: {}", if sim.show_progress { "enabled" } else { "disabled" })?; }, Command::Exit => { sim.abort_simulation = true; send_dummy_to_socket(&sim.cmd_address); send_dummy_to_stdin(); }, Command::ShowMinimumSpanningTree => { let mst = sim.graph.minimum_spanning_tree(); if mst.node_count() > 0 { mark_links = Some(mst); } }, Command::CropMinimumSpanningTree => { // mst is only a uni-directional graph...!! let mst = sim.graph.minimum_spanning_tree(); if mst.node_count() > 0 { sim.graph = mst; } }, Command::Error(msg) => { //TODO: return Result error writeln!(out, "{}", msg)?; }, Command::Help => { print_help(out)?; }, Command::Get(key) => { let mut buf = String::new(); sim.algorithm.get(&key, &mut buf)?; writeln!(out, "{}", buf)?; }, Command::Set(key, value) => { sim.algorithm.set(&key, &value)?; }, Command::GraphInfo => { let node_count = sim.graph.node_count(); let link_count = sim.graph.link_count(); let avg_node_degree = sim.graph.get_avg_node_degree(); writeln!(out, "nodes: {}, links: {}", node_count, link_count)?; writeln!(out, "locations: {}, metadata: {}", sim.locations.data.len(), sim.meta.data.len())?; writeln!(out, "average node degree: {}", avg_node_degree)?; /* if (verbose) { let mean_clustering_coefficient = state.graph.get_mean_clustering_coefficient(); let mean_link_count = state.graph.get_mean_link_count(); let mean_link_distance = state.get_mean_link_distance(); writeln!(out, "mean clustering coefficient: {}", mean_clustering_coefficient)?; writeln!(out, "mean link count: {} ({} variance)", mean_link_count.0, mean_link_count.1)?; writeln!(out, "mean link distance: {} ({} variance)", mean_link_distance.0, mean_link_distance.1)?; } */ }, Command::SimInfo => { write!(out, " algo: ")?; sim.algorithm.get("name", out)?; writeln!(out, "\n steps: {}", sim.sim_steps)?; }, Command::ClearGraph => { sim.graph.clear(); do_init = true; writeln!(out, "done")?; }, Command::ResetSim => { sim.test.clear(); //state.graph.clear(); sim.sim_steps = 0; do_init = true; writeln!(out, "done")?; }, Command::SimStep(count) => { let mut progress = Progress::new(); let now = Instant::now(); let mut io = Io::new(&sim.graph); for step in 0..count { if sim.abort_simulation { break; } sim.algorithm.step(&mut io); sim.movements.step(&mut sim.locations); sim.sim_steps += 1; if sim.show_progress { progress.update((count + 1) as usize, step as usize); } } let duration = now.elapsed(); writeln!(out, "Run {} simulation steps, duration: {}", count, fmt_duration(duration))?; }, Command::Test(samples) => { fn run_test(out: &mut std::fmt::Write, test: &mut EvalPaths, graph: &Graph, algo: &Box<RoutingAlgorithm>, samples: u32) -> Result<(), std::fmt::Error>
sim.test.show_progress(sim.show_progress); run_test(out, &mut sim.test, &sim.graph, &sim.algorithm, samples)?; }, Command::Debug(from, to) => { let node_count = sim.graph.node_count() as u32; if (from < node_count) && (from < node_count) { sim.debug_path.init(from, to); writeln!(out, "Init path debugger: {} => {}", from, to)?; } else { writeln!(out, "Invalid path: {} => {}", from, to)?; } }, Command::DebugStep(steps) => { fn run_test(out: &mut std::fmt::Write, debug_path: &mut DebugPath, graph: &Graph, algo: &Box<RoutingAlgorithm>) -> Result<(), MyError> { debug_path.step(out, graph, |p| algo.route(&p)) } for _ in 0..steps { run_test(out, &mut sim.debug_path, &sim.graph, &sim.algorithm)?; } } Command::Import(ref path) => { import_file(&mut sim.graph, Some(&mut sim.locations), Some(&mut sim.meta), path.as_str())?; do_init = true; writeln!(out, "Import done: {}", path)?; }, Command::ExportPath(path) => { if let Some(path) = path { sim.export_path = path; } writeln!(out, "Export done: {}", sim.export_path)?; }, Command::AddLine(count, close) => { sim.add_line(count, close); do_init = true; }, Command::MoveNodes(x, y, z) => { sim.locations.move_nodes([x, y, z]); }, Command::MoveNode(id, x, y, z) => { sim.locations.move_node(id, [x, y, z]); }, Command::AddTree(count, intra) => { sim.add_tree(count, intra); do_init = true; }, Command::AddStar(count) => { sim.add_star(count); do_init = true; }, Command::AddLattice4(x_count, y_count) => { sim.add_lattice4(x_count, y_count); do_init = true; }, Command::AddLattice8(x_count, y_count) => { sim.add_lattice8(x_count, y_count); do_init = true; }, Command::Positions(enable) => { if enable { // add positions to node that have none let node_count = sim.graph.node_count(); sim.locations.init_positions(node_count, [0.0, 0.0, 0.0]); } else { sim.locations.clear(); } writeln!(out, "positions: {}", if enable { "enabled" } else { "disabled" })?; } Command::RandomizePositions(range) => { let center = sim.locations.graph_center(); sim.locations.randomize_positions_2d(center, range); }, Command::ConnectInRange(range) => { sim.connect_in_range(range); }, Command::Algorithm(algo) => { if let Some(algo) = algo { match algo.as_str() { "random" => { sim.algorithm = Box::new(RandomRouting::new()); do_init = true; }, "vivaldi" => { sim.algorithm = Box::new(VivaldiRouting::new()); do_init = true; }, "spring" => { sim.algorithm = Box::new(SpringRouting::new()); do_init = true; }, "genetic" => { sim.algorithm = Box::new(GeneticRouting::new()); do_init = true; }, "tree" => { sim.algorithm = Box::new(SpanningTreeRouting::new()); do_init = true; } _ => { writeln!(out, "Unknown algorithm: {}", algo)?; } } if do_init { writeln!(out, "Done")?; } } else { write!(out, "selected: ")?; sim.algorithm.get("name", out)?; write!(out, "\n")?; write!(out, "available: random, vivaldi, spring, genetic, tree\n")?; } }, Command::Run(path) => { if call == AllowRecursiveCall::Yes { if let Ok(file) = File::open(&path) { for (index, line) in BufReader::new(file).lines().enumerate() { let line = line.unwrap(); if let Err(err) = cmd_handler(out, sim, &line, AllowRecursiveCall::No) { writeln!(out, "Error in {}:{}: {}", path, index, err)?; sim.abort_simulation = true; break; } } } else { writeln!(out, "File not found: {}", &path)?; } } else { writeln!(out, "Recursive call not allowed: {}", &path)?; } }, Command::RemoveUnconnected => { sim.graph.remove_unconnected_nodes(); do_init = true; }, Command::RemoveNodes(ids) => { sim.graph.remove_nodes(&ids); }, Command::ConnectNodes(ids) => {
{ test.clear(); test.run_samples(graph, |p| algo.route(&p), samples as usize); writeln!(out, "samples: {}, arrived: {:.1}, stretch: {}, duration: {}", samples, test.arrived(), test.stretch(), fmt_duration(test.duration()) ) }
identifier_body
cmd.rs
::graph::Graph; use crate::progress::Progress; use crate::sim::{Io, GlobalState, RoutingAlgorithm}; use crate::algorithms::vivaldi_routing::VivaldiRouting; use crate::algorithms::random_routing::RandomRouting; use crate::algorithms::spring_routing::SpringRouting; use crate::algorithms::genetic_routing::GeneticRouting; use crate::algorithms::spanning_tree_routing::SpanningTreeRouting; use crate::importer::import_file; use crate::exporter::export_file; use crate::utils::{fmt_duration, DEG2KM, MyError}; use crate::movements::Movements; #[derive(PartialEq)] enum AllowRecursiveCall { No, Yes } // trigger blocking read to exit loop fn send_dummy_to_socket(address: &str) { match TcpStream::connect(address) { Ok(mut stream) => { let _ = stream.set_read_timeout(Some(Duration::from_millis(100))); let _ = stream.write("".as_bytes()); }, Err(e) => { eprintln!("{}", e); } } } fn send_dummy_to_stdin() { let _ = std::io::stdout().write("".as_bytes()); } pub fn ext_loop(sim: Arc<Mutex<GlobalState>>, address: &str) { match TcpListener::bind(address) { Err(err) => { println!("{}", err); }, Ok(listener) => { println!("Listen for commands on {}", address); //let mut input = vec![0u8; 512]; let mut output = String::new(); loop { //input.clear(); output.clear(); if let Ok((mut stream, _addr)) = listener.accept() { let mut buf = [0; 512]; if let Ok(n) = stream.read(&mut buf) { if let (Ok(s), Ok(mut sim)) = (std::str::from_utf8(&buf[0..n]), sim.lock()) { if sim.abort_simulation { // abort loop break; } else if let Err(e) = cmd_handler(&mut output, &mut sim, s, AllowRecursiveCall::Yes) { let _ = stream.write(e.to_string().as_bytes()); } else { let _ = stream.write(&output.as_bytes()); } } } } } } } } pub fn cmd_loop(sim: Arc<Mutex<GlobalState>>, run: &str) { let mut input = run.to_owned(); let mut output = String::new(); loop { if input.len() == 0 { let _ = std::io::stdin().read_line(&mut input); } if let Ok(mut sim) = sim.lock() { output.clear(); if let Err(e) = cmd_handler(&mut output, &mut sim, &input, AllowRecursiveCall::Yes) { let _ = std::io::stderr().write(e.to_string().as_bytes()); } else { let _ = std::io::stdout().write(output.as_bytes()); } if sim.abort_simulation { // abort loop break; } } input.clear(); } } macro_rules! scan { ( $iter:expr, $( $x:ty ),+ ) => {{ ($($iter.next().and_then(|word| word.parse::<$x>().ok()),)*) }} } enum Command { Error(String), Ignore, Help, ClearGraph, GraphInfo, SimInfo, ResetSim, Exit, Progress(Option<bool>), ShowMinimumSpanningTree, CropMinimumSpanningTree, Test(u32), Debug(u32, u32), DebugStep(u32), Get(String), Set(String, String), ConnectInRange(f32), RandomizePositions(f32), RemoveUnconnected, Algorithm(Option<String>), AddLine(u32, bool), AddTree(u32, u32), AddStar(u32), AddLattice4(u32, u32), AddLattice8(u32, u32), Positions(bool), RemoveNodes(Vec<u32>), ConnectNodes(Vec<u32>), DisconnectNodes(Vec<u32>), SimStep(u32), Run(String), Import(String), ExportPath(Option<String>), MoveNode(u32, f32, f32, f32), MoveNodes(f32, f32, f32), MoveTo(f32, f32, f32), } #[derive(Clone, Copy, PartialEq)] enum Cid { Error, Help, ClearGraph, GraphInfo, SimInfo, ResetSim, Exit, Progress, ShowMinimumSpanningTree, CropMinimumSpanningTree, Test, Debug, DebugStep, Get, Set, ConnectInRange, RandomizePositions, RemoveUnconnected, Algorithm, AddLine, AddTree, AddStar, AddLattice4, AddLattice8, Positions, RemoveNodes, ConnectNodes, DisconnectNodes, SimStep, Run, Import, ExportPath, MoveNode, MoveNodes, MoveTo } const COMMANDS: &'static [(&'static str, Cid)] = &[ ("algo [<algorithm>] Get or set given algorithm.", Cid::Algorithm), ("sim_step [<steps>] Run simulation steps. Default is 1.", Cid::SimStep), ("sim_reset Reset simulation.", Cid::ResetSim), ("sim_info Show simulator information.", Cid::SimInfo), ("progress [<true|false>] Show simulation progress.", Cid::Progress), ("test [<samples>] Test routing algorithm with (test packets arrived, path stretch).", Cid::Test), ("debug_init <from> <to> Debug a path step wise.", Cid::Debug), ("debug_step [<steps>] Perform step on path.", Cid::DebugStep), ("", Cid::Error), ("graph_info Show graph information", Cid::GraphInfo), ("get <key> Get node property.", Cid::Get), ("set <key> <value> Set node property.", Cid::Set), ("", Cid::Error), ("graph_clear Clear graph", Cid::ClearGraph),
("tree <node_count> [<inter_count>] Add a tree structure of nodes with interconnections", Cid::AddTree), ("lattice4 <x_xount> <y_count> Create a lattice structure of squares.", Cid::AddLattice4), ("lattice8 <x_xount> <y_count> Create a lattice structure of squares and diagonal connections.", Cid::AddLattice8), ("remove_nodes <node_list> Remove nodes. Node list is a comma separated list of node ids.", Cid::RemoveNodes), ("connect_nodes <node_list> Connect nodes. Node list is a comma separated list of node ids.", Cid::ConnectNodes), ("disconnect_nodes <node_list> Disconnect nodes. Node list is a comma separated list of node ids.", Cid::DisconnectNodes), ("remove_unconnected Remove nodes without any connections.", Cid::RemoveUnconnected), ("", Cid::Error), ("positions <true|false> Enable geo positions.", Cid::Positions), ("move_node <node_id> <x> <y> <z> Move a node by x/y/z (in km).", Cid::MoveNode), ("move_nodes <x> <y> <z> Move all nodes by x/y/z (in km).", Cid::MoveNodes), ("move_to <x> <y> <z> Move all nodes to x/y/z (in degrees).", Cid::MoveTo), ("rnd_pos <range> Randomize node positions in an area with width (in km) around node center.", Cid::RandomizePositions), ("connect_in_range <range> Connect all nodes in range of less then range (in km).", Cid::ConnectInRange), ("", Cid::Error), ("run <file> Run commands from a script.", Cid::Run), ("import <file> Import a graph as JSON file.", Cid::Import), ("export [<file>] Get or set graph export file.", Cid::ExportPath), ("show_mst Mark the minimum spanning tree.", Cid::ShowMinimumSpanningTree), ("crop_mst Only leave the minimum spanning tree.", Cid::CropMinimumSpanningTree), ("exit Exit simulator.", Cid::Exit), ("help Show this help.", Cid::Help), ]; fn parse_command(input: &str) -> Command { let mut tokens = Vec::new(); for tok in input.split_whitespace() { // trim'" characters tokens.push(tok.trim_matches(|c: char| (c == '\'') || (c == '"'))); } let mut iter = tokens.iter().skip(1); let cmd = tokens.get(0).unwrap_or(&""); fn is_first_token(string: &str, tok: &str) -> bool { string.starts_with(tok) && (string.len() > tok.len()) && (string.as_bytes()[tok.len()] =='' as u8) } fn lookup_cmd(cmd: &str) -> Cid { for item in COMMANDS { if is_first_token(item.0, cmd) { return item.1; } } Cid::Error } // parse number separated list of numbers fn parse_list(numbers: Option<&&str>) -> Result<Vec<u32>, ()> { let mut v = Vec::<u32>::new(); for num in numbers.unwrap_or(&"").split(",") { if let Ok(n) = num.parse::<u32>() { v.push(n); } else { return Err(()); } } Ok(v) } let error = Command::Error("Missing Arguments".to_string()); match lookup_cmd(cmd) { Cid::Help => Command::Help, Cid::SimInfo => Command::SimInfo, Cid::GraphInfo => Command::GraphInfo, Cid::ClearGraph => Command::ClearGraph, Cid::ResetSim => Command::ResetSim, Cid::Exit => Command::Exit, Cid::Progress => { if let (Some(progress),) = scan!(iter, bool) { Command::Progress(Some(progress)) } else { Command::Progress(None) } }, Cid::ShowMinimumSpanningTree => Command::ShowMinimumSpanningTree, Cid::CropMinimumSpanningTree => Command::CropMinimumSpanningTree, Cid::Test => { if let (Some(samples),) = scan!(iter, u32) { Command::Test(samples) } else { Command::Test(1000) } }, Cid::Debug => { if let (Some(from), Some(to)) = scan!(iter, u32, u32) { Command::Debug(from, to) } else { error } }, Cid::DebugStep => { if let (Some(steps),) = scan!(iter, u32) { Command::DebugStep(steps) } else { Command::DebugStep(1) } }, Cid::Get => { if let (Some(key),) = scan!(iter, String) { Command::Get(key) } else { error } }, Cid::Set => { if let (Some(key),Some(value)) = scan!(iter, String, String) { Command::Set(key, value) } else { error } }, Cid::SimStep => { Command::SimStep(if let (Some(count),) = scan!(iter, u32) { count } else { 1 }) }, Cid::Run => { if let (Some(path),) = scan!(iter, String) { Command::Run(path) } else { error } }, Cid::Import => { if let (Some(path),) = scan!(iter, String) { Command::Import(path) } else { error } }, Cid::ExportPath => { if let (Some(path),) = scan!(iter, String) { Command::ExportPath(Some(path)) } else { Command::ExportPath(None) } }, Cid::MoveNodes => { if let (Some(x), Some(y), Some(z)) = scan!(iter, f32, f32, f32) { Command::MoveNodes(x, y, z) } else { error } }, Cid::MoveNode => { if let (Some(id), Some(x), Some(y), Some(z)) = scan!(iter, u32, f32, f32, f32) { Command::MoveNode(id, x, y, z) } else { error } }, Cid::AddLine => { let mut iter1 = iter.clone(); let mut iter2 = iter.clone(); if let (Some(count), Some(close)) = scan!(iter1, u32, bool) { Command::AddLine(count, close) } else if let (Some(count),) = scan!(iter2, u32) { Command::AddLine(count, false) } else { error } }, Cid::AddTree => { let mut iter1 = iter.clone(); let mut iter2 = iter.clone(); if let (Some(count), Some(intra)) = scan!(iter1, u32, u32) { Command::AddTree(count, intra) } else if let (Some(count),) = scan!(iter2, u32) { Command::AddTree(count, 0) } else { error } }, Cid::AddStar => { if let (Some(count),) = scan!(iter, u32) { Command::AddStar(count) } else { error } }, Cid::AddLattice4 => { if let (Some(x_count), Some(y_count)) = scan!(iter, u32, u32) { Command::AddLattice4(x_count, y_count) } else { error } }, Cid::AddLattice8 => { if let (Some(x_count), Some(y_count)) = scan!(iter, u32, u32) { Command::AddLattice8(x_count, y_count) } else { error } }, Cid::Positions => { if let (Some(enable),) = scan!(iter, bool) { Command::Positions(enable) } else { error } }, Cid::ConnectInRange => { if let (Some(range),) = scan!(iter, f32) { Command::ConnectInRange(range) } else { error } }, Cid::RandomizePositions => { if let (Some(range),) = scan!(iter, f32) { Command::RandomizePositions(range) } else { error } }, Cid::Algorithm => { if let (Some(algo),) = scan!(iter, String) { Command::Algorithm(Some(algo)) } else { Command::Algorithm(None) } }, Cid::RemoveNodes => { if let Ok(ids) = parse_list(tokens.get(1)) { Command::RemoveNodes(ids) } else { error } }, Cid::ConnectNodes => { if let Ok(ids) = parse_list(tokens.get(1)) { Command::ConnectNodes(ids) } else { error } }, Cid::DisconnectNodes => { if let Ok(ids) = parse_list(tokens.get(1)) { Command::DisconnectNodes(ids) } else { error } }, Cid::RemoveUnconnected => { Command::RemoveUnconnected }, Cid::MoveTo => { if let (Some(x), Some(y), Some(z)) = scan!(iter, f32, f32, f32) { Command::MoveTo(x, y, z) } else { error } }, Cid::Error => { if cmd.is_empty() { Command::Ignore } else if cmd.trim_start().starts_with("#") { Command::Ignore } else { Command::Error(format!("Unknown Command: {}", cmd)) } } } } fn print_help(out: &mut std::fmt::Write) -> Result<(), MyError> { for item in COMMANDS { if item.1!= Cid::Error { writeln!(out, "{}", item.0)?; } } Ok(()) } fn cmd_handler(out: &mut std::fmt::Write, sim: &mut GlobalState, input: &str, call: AllowRecursiveCall) -> Result<(), MyError> { let mut mark_links : Option<Graph> = None; let mut do_init = false; //println!("command: '{}'", input); let command = parse_command(input); match command { Command::Ignore => { // nothing to do }, Command::Progress(show) => { if let Some(show) = show { sim.show_progress = show; } writeln!(out, "show progress: {}", if sim.show_progress { "enabled" } else { "disabled" })?; }, Command::Exit => { sim.abort_simulation = true; send_dummy_to_socket(&sim.cmd_address); send_dummy_to_stdin(); }, Command::ShowMinimumSpanningTree => { let mst = sim.graph.minimum_spanning_tree(); if mst.node_count() > 0 { mark_links = Some(mst); } }, Command::CropMinimumSpanningTree => { // mst is only a uni-directional graph...!! let mst = sim.graph.minimum_spanning_tree(); if mst.node_count() > 0 { sim.graph = mst; } }, Command::Error(msg) => { //TODO: return Result error writeln!(out, "{}", msg)?; }, Command::Help => { print_help(out)?; }, Command::Get(key) => { let mut buf = String::new(); sim.algorithm.get(&key, &mut buf)?; writeln!(out, "{}", buf)?; }, Command::Set(key, value) => { sim.algorithm.set(&key, &value)?; }, Command::GraphInfo => { let node_count = sim.graph.node_count(); let link_count = sim.graph.link_count(); let avg_node_degree = sim.graph.get_avg_node_degree(); writeln!(out, "nodes: {}, links: {}", node_count, link_count)?; writeln!(out, "locations: {}, metadata: {}", sim.locations.data.len(), sim.meta.data.len())?; writeln!(out, "average node degree: {}", avg_node_degree)?; /* if (verbose) { let mean_clustering_coefficient = state.graph.get_mean_clustering_coefficient(); let mean_link_count = state.graph.get_mean_link_count(); let mean_link_distance = state.get_mean_link_distance(); writeln!(out, "mean clustering coefficient: {}", mean_clustering_coefficient)?; writeln!(out, "mean link count: {} ({} variance)", mean_link_count.0, mean_link_count.1)?; writeln!(out, "mean link distance: {} ({} variance)", mean_link_distance.0, mean_link_distance.1)?; } */ }, Command::SimInfo => { write!(out, " algo: ")?; sim.algorithm.get("name", out)?; writeln!(out, "\n steps: {}", sim.sim_steps)?; }, Command::ClearGraph => { sim.graph.clear(); do_init = true; writeln!(out, "done")?; }, Command::ResetSim => { sim.test.clear(); //state.graph.clear(); sim.sim_steps = 0; do_init = true; writeln!(out, "done")?; }, Command::SimStep(count) => { let mut progress = Progress::new(); let now = Instant::now(); let mut io = Io::new(&sim.graph); for step in 0..count { if sim.abort_simulation { break; } sim.algorithm.step(&mut io); sim.movements.step(&mut sim.locations); sim.sim_steps += 1; if sim.show_progress { progress.update((count + 1) as usize, step as usize); } } let duration = now.elapsed(); writeln!(out, "Run {} simulation steps, duration: {}", count, fmt_duration(duration))?; }, Command::Test(samples) => { fn run_test(out: &mut std::fmt::Write, test: &mut EvalPaths, graph: &Graph, algo: &Box<RoutingAlgorithm>, samples: u32) -> Result<(), std::fmt::Error> { test.clear(); test.run_samples(graph, |p| algo.route(&p), samples as usize); writeln!(out, "samples: {}, arrived: {:.1}, stretch: {}, duration: {}", samples, test.arrived(), test.stretch(), fmt_duration(test.duration()) ) } sim.test.show_progress(sim.show_progress); run_test(out, &mut sim.test, &sim.graph, &sim.algorithm, samples)?; }, Command::Debug(from, to) => { let node_count = sim.graph.node_count() as u32; if (from < node_count) && (from < node_count) { sim.debug_path.init(from, to); writeln!(out, "Init path debugger: {} => {}", from, to)?; } else { writeln!(out, "Invalid path: {} => {}", from, to)?; } }, Command::DebugStep(steps) => { fn run_test(out: &mut std::fmt::Write, debug_path: &mut DebugPath, graph: &Graph, algo: &Box<RoutingAlgorithm>) -> Result<(), MyError> { debug_path.step(out, graph, |p| algo.route(&p)) } for _ in 0..steps { run_test(out, &mut sim.debug_path, &sim.graph, &sim.algorithm)?; } } Command::Import(ref path) => { import_file(&mut sim.graph, Some(&mut sim.locations), Some(&mut sim.meta), path.as_str())?; do_init = true; writeln!(out, "Import done: {}", path)?; }, Command::ExportPath(path) => { if let Some(path) = path { sim.export_path = path; } writeln!(out, "Export done: {}", sim.export_path)?; }, Command::AddLine(count, close) => { sim.add_line(count, close); do_init = true; }, Command::MoveNodes(x, y, z) => { sim.locations.move_nodes([x, y, z]); }, Command::MoveNode(id, x, y, z) => { sim.locations.move_node(id, [x, y, z]); }, Command::AddTree(count, intra) => { sim.add_tree(count, intra); do_init = true; }, Command::AddStar(count) => { sim.add_star(count); do_init = true; }, Command::AddLattice4(x_count, y_count) => { sim.add_lattice4(x_count, y_count); do_init = true; }, Command::AddLattice8(x_count, y_count) => { sim.add_lattice8(x_count, y_count); do_init = true; }, Command::Positions(enable) => { if enable { // add positions to node that have none let node_count = sim.graph.node_count(); sim.locations.init_positions(node_count, [0.0, 0.0, 0.0]); } else { sim.locations.clear(); } writeln!(out, "positions: {}", if enable { "enabled" } else { "disabled" })?; } Command::RandomizePositions(range) => { let center = sim.locations.graph_center(); sim.locations.randomize_positions_2d(center, range); }, Command::ConnectInRange(range) => { sim.connect_in_range(range); }, Command::Algorithm(algo) => { if let Some(algo) = algo { match algo.as_str() { "random" => { sim.algorithm = Box::new(RandomRouting::new()); do_init = true; }, "vivaldi" => { sim.algorithm = Box::new(VivaldiRouting::new()); do_init = true; }, "spring" => { sim.algorithm = Box::new(SpringRouting::new()); do_init = true; }, "genetic" => { sim.algorithm = Box::new(GeneticRouting::new()); do_init = true; }, "tree" => { sim.algorithm = Box::new(SpanningTreeRouting::new()); do_init = true; } _ => { writeln!(out, "Unknown algorithm: {}", algo)?; } } if do_init { writeln!(out, "Done")?; } } else { write!(out, "selected: ")?; sim.algorithm.get("name", out)?; write!(out, "\n")?; write!(out, "available: random, vivaldi, spring, genetic, tree\n")?; } }, Command::Run(path) => { if call == AllowRecursiveCall::Yes { if let Ok(file) = File::open(&path) { for (index, line) in BufReader::new(file).lines().enumerate() { let line = line.unwrap(); if let Err(err) = cmd_handler(out, sim, &line, AllowRecursiveCall::No) { writeln!(out, "Error in {}:{}: {}", path, index, err)?; sim.abort_simulation = true; break; } } } else { writeln!(out, "File not found: {}", &path)?; } } else { writeln!(out, "Recursive call not allowed: {}", &path)?; } }, Command::RemoveUnconnected => { sim.graph.remove_unconnected_nodes(); do_init = true; }, Command::RemoveNodes(ids) => { sim.graph.remove_nodes(&ids); }, Command::ConnectNodes(ids) => { sim
("line <node_count> [<create_loop>] Add a line of nodes. Connect ends to create a loop.", Cid::AddLine), ("star <edge_count> Add star structure of nodes.", Cid::AddStar),
random_line_split
config_handler.rs
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. Please review the Licences for the specific language governing // permissions and limitations relating to use of the SAFE Network Software. use crate::CoreError; use directories::ProjectDirs; use quic_p2p::Config as QuicP2pConfig; use serde::{de::DeserializeOwned, Deserialize, Serialize}; #[cfg(test)] use std::fs; use std::{ ffi::OsStr, fs::File, io::{self, BufReader}, path::PathBuf, sync::Mutex, }; const CONFIG_DIR_QUALIFIER: &str = "net"; const CONFIG_DIR_ORGANISATION: &str = "MaidSafe"; const CONFIG_DIR_APPLICATION: &str = "safe_core"; const CONFIG_FILE: &str = "safe_core.config"; const VAULT_CONFIG_DIR_APPLICATION: &str = "safe_vault"; const VAULT_CONNECTION_INFO_FILE: &str = "vault_connection_info.config"; lazy_static! { static ref CONFIG_DIR_PATH: Mutex<Option<PathBuf>> = Mutex::new(None); static ref DEFAULT_SAFE_CORE_PROJECT_DIRS: Option<ProjectDirs> = ProjectDirs::from( CONFIG_DIR_QUALIFIER, CONFIG_DIR_ORGANISATION, CONFIG_DIR_APPLICATION, ); static ref DEFAULT_VAULT_PROJECT_DIRS: Option<ProjectDirs> = ProjectDirs::from( CONFIG_DIR_QUALIFIER, CONFIG_DIR_ORGANISATION, VAULT_CONFIG_DIR_APPLICATION, ); } /// Set a custom path for the config files. // `OsStr` is platform-native. pub fn set_config_dir_path<P: AsRef<OsStr> +?Sized>(path: &P) { *unwrap!(CONFIG_DIR_PATH.lock()) = Some(From::from(path)); } /// Configuration for safe-core. #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)] pub struct Config { /// QuicP2p options. pub quic_p2p: QuicP2pConfig, /// Developer options. pub dev: Option<DevConfig>, } #[cfg(any(target_os = "android", target_os = "androideabi", target_os = "ios"))] fn check_config_path_set() -> Result<(), CoreError> { if unwrap!(CONFIG_DIR_PATH.lock()).is_none() { Err(CoreError::QuicP2p(quic_p2p::Error::Configuration( "Boostrap cache directory not set".to_string(), ))) } else { Ok(()) } } impl Config { /// Returns a new `Config` instance. Tries to read quic-p2p config from file. pub fn new() -> Self { let quic_p2p = Self::read_qp2p_from_file().unwrap_or_default(); Self { quic_p2p, dev: None, } } fn read_qp2p_from_file() -> Result<QuicP2pConfig, CoreError>
} else { None }; // If there is no config file, assume we are a client QuicP2pConfig { our_type: quic_p2p::OurType::Client, bootstrap_cache_dir: custom_dir, ..Default::default() } } result => result?, } }; // Then if there is a locally running Vault we add it to the list of know contacts. if let Ok(node_info) = read_config_file(vault_dirs()?, VAULT_CONNECTION_INFO_FILE) { let _ = config.hard_coded_contacts.insert(node_info); } Ok(config) } } /// Extra configuration options intended for developers. #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)] pub struct DevConfig { /// Switch off mutations limit in mock-vault. pub mock_unlimited_coins: bool, /// Use memory store instead of file store in mock-vault. pub mock_in_memory_storage: bool, /// Set the mock-vault path if using file store (`mock_in_memory_storage` is `false`). pub mock_vault_path: Option<String>, } /// Reads the `safe_core` config file and returns it or a default if this fails. pub fn get_config() -> Config { Config::new() } /// Returns the directory from which the config files are read pub fn config_dir() -> Result<PathBuf, CoreError> { Ok(dirs()?.config_dir().to_path_buf()) } fn dirs() -> Result<ProjectDirs, CoreError> { let project_dirs = if let Some(custom_path) = unwrap!(CONFIG_DIR_PATH.lock()).clone() { ProjectDirs::from_path(custom_path) } else { DEFAULT_SAFE_CORE_PROJECT_DIRS.clone() }; project_dirs.ok_or_else(|| CoreError::from("Cannot determine project directory paths")) } fn vault_dirs() -> Result<ProjectDirs, CoreError> { let project_dirs = if let Some(custom_path) = unwrap!(CONFIG_DIR_PATH.lock()).clone() { ProjectDirs::from_path(custom_path) } else { DEFAULT_VAULT_PROJECT_DIRS.clone() }; project_dirs.ok_or_else(|| CoreError::from("Cannot determine vault directory paths")) } fn read_config_file<T>(dirs: ProjectDirs, file: &str) -> Result<T, CoreError> where T: DeserializeOwned, { let path = dirs.config_dir().join(file); let file = match File::open(&path) { Ok(file) => { trace!("Reading: {}", path.display()); file } Err(error) => { trace!("Not available: {}", path.display()); return Err(error.into()); } }; let reader = BufReader::new(file); serde_json::from_reader(reader).map_err(|err| { info!("Could not parse: {} ({:?})", err, err); err.into() }) } /// Writes a `safe_core` config file **for use by tests and examples**. /// /// N.B. This method should only be used as a utility for test and examples. In normal use cases, /// the config file should be created by the Vault's installer. #[cfg(test)] pub fn write_config_file(config: &Config) -> Result<PathBuf, CoreError> { let dir = config_dir()?; fs::create_dir_all(dir.clone())?; let path = dir.join(CONFIG_FILE); dbg!(&path); let mut file = File::create(&path)?; serde_json::to_writer_pretty(&mut file, config)?; file.sync_all()?; Ok(path) } #[cfg(all(test, feature = "mock-network"))] mod test { use super::*; use std::env::temp_dir; // 1. Write the default config file to temp directory. // 2. Set the temp directory as the custom config directory path. // 3. Assert that `Config::new()` reads the default config written to disk. // 4. Verify that `Config::new()` generates the correct default config. // The default config will have the custom config path in the // `boostrap_cache_dir` field and `our_type` will be set to `Client` #[test] fn custom_config_path() { let path = temp_dir(); let temp_dir_path = path.clone(); set_config_dir_path(&path); // In the default config, `our_type` will be set to Node. let config: Config = Default::default(); unwrap!(write_config_file(&config)); let read_cfg = Config::new(); assert_eq!(config, read_cfg); let mut path = unwrap!(ProjectDirs::from_path(temp_dir_path.clone())) .config_dir() .to_path_buf(); path.push(CONFIG_FILE); unwrap!(std::fs::remove_file(path)); // In the absence of a config file, the config handler // should initialize the `our_type` field to Client. let config = Config::new(); let expected_config = Config { quic_p2p: QuicP2pConfig { our_type: quic_p2p::OurType::Client, bootstrap_cache_dir: Some(unwrap!(temp_dir_path.into_os_string().into_string())), ..Default::default() }, ..Default::default() }; assert_eq!(config, expected_config); } }
{ // First we read the default configuration file, and use a slightly modified default config // if there is none. let mut config: QuicP2pConfig = { match read_config_file(dirs()?, CONFIG_FILE) { Err(CoreError::IoError(ref err)) if err.kind() == io::ErrorKind::NotFound => { // Bootstrap cache dir must be set on mobile platforms // using set_config_dir_path #[cfg(any( target_os = "android", target_os = "androideabi", target_os = "ios" ))] check_config_path_set()?; let custom_dir = if let Some(custom_path) = unwrap!(CONFIG_DIR_PATH.lock()).clone() { Some(custom_path.into_os_string().into_string().map_err(|_| { CoreError::from("Config path is not a valid UTF-8 string") })?)
identifier_body
config_handler.rs
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. Please review the Licences for the specific language governing // permissions and limitations relating to use of the SAFE Network Software. use crate::CoreError; use directories::ProjectDirs; use quic_p2p::Config as QuicP2pConfig; use serde::{de::DeserializeOwned, Deserialize, Serialize}; #[cfg(test)] use std::fs; use std::{ ffi::OsStr, fs::File, io::{self, BufReader}, path::PathBuf, sync::Mutex, }; const CONFIG_DIR_QUALIFIER: &str = "net"; const CONFIG_DIR_ORGANISATION: &str = "MaidSafe"; const CONFIG_DIR_APPLICATION: &str = "safe_core"; const CONFIG_FILE: &str = "safe_core.config"; const VAULT_CONFIG_DIR_APPLICATION: &str = "safe_vault"; const VAULT_CONNECTION_INFO_FILE: &str = "vault_connection_info.config"; lazy_static! { static ref CONFIG_DIR_PATH: Mutex<Option<PathBuf>> = Mutex::new(None); static ref DEFAULT_SAFE_CORE_PROJECT_DIRS: Option<ProjectDirs> = ProjectDirs::from( CONFIG_DIR_QUALIFIER, CONFIG_DIR_ORGANISATION, CONFIG_DIR_APPLICATION, ); static ref DEFAULT_VAULT_PROJECT_DIRS: Option<ProjectDirs> = ProjectDirs::from( CONFIG_DIR_QUALIFIER, CONFIG_DIR_ORGANISATION, VAULT_CONFIG_DIR_APPLICATION, ); } /// Set a custom path for the config files. // `OsStr` is platform-native. pub fn set_config_dir_path<P: AsRef<OsStr> +?Sized>(path: &P) { *unwrap!(CONFIG_DIR_PATH.lock()) = Some(From::from(path)); } /// Configuration for safe-core. #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)] pub struct Config { /// QuicP2p options. pub quic_p2p: QuicP2pConfig, /// Developer options. pub dev: Option<DevConfig>, } #[cfg(any(target_os = "android", target_os = "androideabi", target_os = "ios"))] fn check_config_path_set() -> Result<(), CoreError> { if unwrap!(CONFIG_DIR_PATH.lock()).is_none() { Err(CoreError::QuicP2p(quic_p2p::Error::Configuration( "Boostrap cache directory not set".to_string(), ))) } else { Ok(()) } } impl Config { /// Returns a new `Config` instance. Tries to read quic-p2p config from file. pub fn new() -> Self { let quic_p2p = Self::read_qp2p_from_file().unwrap_or_default(); Self { quic_p2p, dev: None, } } fn read_qp2p_from_file() -> Result<QuicP2pConfig, CoreError> { // First we read the default configuration file, and use a slightly modified default config // if there is none. let mut config: QuicP2pConfig = { match read_config_file(dirs()?, CONFIG_FILE) { Err(CoreError::IoError(ref err)) if err.kind() == io::ErrorKind::NotFound => { // Bootstrap cache dir must be set on mobile platforms // using set_config_dir_path #[cfg(any( target_os = "android", target_os = "androideabi", target_os = "ios" ))] check_config_path_set()?; let custom_dir = if let Some(custom_path) = unwrap!(CONFIG_DIR_PATH.lock()).clone() { Some(custom_path.into_os_string().into_string().map_err(|_| { CoreError::from("Config path is not a valid UTF-8 string") })?) } else { None }; // If there is no config file, assume we are a client QuicP2pConfig { our_type: quic_p2p::OurType::Client, bootstrap_cache_dir: custom_dir, ..Default::default() } } result => result?, } }; // Then if there is a locally running Vault we add it to the list of know contacts. if let Ok(node_info) = read_config_file(vault_dirs()?, VAULT_CONNECTION_INFO_FILE) { let _ = config.hard_coded_contacts.insert(node_info); } Ok(config) } } /// Extra configuration options intended for developers. #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)] pub struct DevConfig { /// Switch off mutations limit in mock-vault. pub mock_unlimited_coins: bool, /// Use memory store instead of file store in mock-vault. pub mock_in_memory_storage: bool, /// Set the mock-vault path if using file store (`mock_in_memory_storage` is `false`). pub mock_vault_path: Option<String>, } /// Reads the `safe_core` config file and returns it or a default if this fails. pub fn get_config() -> Config { Config::new() } /// Returns the directory from which the config files are read pub fn config_dir() -> Result<PathBuf, CoreError> { Ok(dirs()?.config_dir().to_path_buf()) } fn dirs() -> Result<ProjectDirs, CoreError> { let project_dirs = if let Some(custom_path) = unwrap!(CONFIG_DIR_PATH.lock()).clone() { ProjectDirs::from_path(custom_path) } else { DEFAULT_SAFE_CORE_PROJECT_DIRS.clone() }; project_dirs.ok_or_else(|| CoreError::from("Cannot determine project directory paths")) } fn vault_dirs() -> Result<ProjectDirs, CoreError> { let project_dirs = if let Some(custom_path) = unwrap!(CONFIG_DIR_PATH.lock()).clone() { ProjectDirs::from_path(custom_path) } else { DEFAULT_VAULT_PROJECT_DIRS.clone() }; project_dirs.ok_or_else(|| CoreError::from("Cannot determine vault directory paths")) } fn read_config_file<T>(dirs: ProjectDirs, file: &str) -> Result<T, CoreError> where T: DeserializeOwned, { let path = dirs.config_dir().join(file); let file = match File::open(&path) { Ok(file) =>
Err(error) => { trace!("Not available: {}", path.display()); return Err(error.into()); } }; let reader = BufReader::new(file); serde_json::from_reader(reader).map_err(|err| { info!("Could not parse: {} ({:?})", err, err); err.into() }) } /// Writes a `safe_core` config file **for use by tests and examples**. /// /// N.B. This method should only be used as a utility for test and examples. In normal use cases, /// the config file should be created by the Vault's installer. #[cfg(test)] pub fn write_config_file(config: &Config) -> Result<PathBuf, CoreError> { let dir = config_dir()?; fs::create_dir_all(dir.clone())?; let path = dir.join(CONFIG_FILE); dbg!(&path); let mut file = File::create(&path)?; serde_json::to_writer_pretty(&mut file, config)?; file.sync_all()?; Ok(path) } #[cfg(all(test, feature = "mock-network"))] mod test { use super::*; use std::env::temp_dir; // 1. Write the default config file to temp directory. // 2. Set the temp directory as the custom config directory path. // 3. Assert that `Config::new()` reads the default config written to disk. // 4. Verify that `Config::new()` generates the correct default config. // The default config will have the custom config path in the // `boostrap_cache_dir` field and `our_type` will be set to `Client` #[test] fn custom_config_path() { let path = temp_dir(); let temp_dir_path = path.clone(); set_config_dir_path(&path); // In the default config, `our_type` will be set to Node. let config: Config = Default::default(); unwrap!(write_config_file(&config)); let read_cfg = Config::new(); assert_eq!(config, read_cfg); let mut path = unwrap!(ProjectDirs::from_path(temp_dir_path.clone())) .config_dir() .to_path_buf(); path.push(CONFIG_FILE); unwrap!(std::fs::remove_file(path)); // In the absence of a config file, the config handler // should initialize the `our_type` field to Client. let config = Config::new(); let expected_config = Config { quic_p2p: QuicP2pConfig { our_type: quic_p2p::OurType::Client, bootstrap_cache_dir: Some(unwrap!(temp_dir_path.into_os_string().into_string())), ..Default::default() }, ..Default::default() }; assert_eq!(config, expected_config); } }
{ trace!("Reading: {}", path.display()); file }
conditional_block
config_handler.rs
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. Please review the Licences for the specific language governing // permissions and limitations relating to use of the SAFE Network Software. use crate::CoreError; use directories::ProjectDirs; use quic_p2p::Config as QuicP2pConfig; use serde::{de::DeserializeOwned, Deserialize, Serialize}; #[cfg(test)] use std::fs; use std::{ ffi::OsStr, fs::File, io::{self, BufReader}, path::PathBuf, sync::Mutex, }; const CONFIG_DIR_QUALIFIER: &str = "net"; const CONFIG_DIR_ORGANISATION: &str = "MaidSafe"; const CONFIG_DIR_APPLICATION: &str = "safe_core"; const CONFIG_FILE: &str = "safe_core.config"; const VAULT_CONFIG_DIR_APPLICATION: &str = "safe_vault"; const VAULT_CONNECTION_INFO_FILE: &str = "vault_connection_info.config"; lazy_static! { static ref CONFIG_DIR_PATH: Mutex<Option<PathBuf>> = Mutex::new(None); static ref DEFAULT_SAFE_CORE_PROJECT_DIRS: Option<ProjectDirs> = ProjectDirs::from( CONFIG_DIR_QUALIFIER, CONFIG_DIR_ORGANISATION, CONFIG_DIR_APPLICATION, ); static ref DEFAULT_VAULT_PROJECT_DIRS: Option<ProjectDirs> = ProjectDirs::from( CONFIG_DIR_QUALIFIER, CONFIG_DIR_ORGANISATION, VAULT_CONFIG_DIR_APPLICATION, ); } /// Set a custom path for the config files. // `OsStr` is platform-native. pub fn set_config_dir_path<P: AsRef<OsStr> +?Sized>(path: &P) { *unwrap!(CONFIG_DIR_PATH.lock()) = Some(From::from(path)); } /// Configuration for safe-core. #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)] pub struct
{ /// QuicP2p options. pub quic_p2p: QuicP2pConfig, /// Developer options. pub dev: Option<DevConfig>, } #[cfg(any(target_os = "android", target_os = "androideabi", target_os = "ios"))] fn check_config_path_set() -> Result<(), CoreError> { if unwrap!(CONFIG_DIR_PATH.lock()).is_none() { Err(CoreError::QuicP2p(quic_p2p::Error::Configuration( "Boostrap cache directory not set".to_string(), ))) } else { Ok(()) } } impl Config { /// Returns a new `Config` instance. Tries to read quic-p2p config from file. pub fn new() -> Self { let quic_p2p = Self::read_qp2p_from_file().unwrap_or_default(); Self { quic_p2p, dev: None, } } fn read_qp2p_from_file() -> Result<QuicP2pConfig, CoreError> { // First we read the default configuration file, and use a slightly modified default config // if there is none. let mut config: QuicP2pConfig = { match read_config_file(dirs()?, CONFIG_FILE) { Err(CoreError::IoError(ref err)) if err.kind() == io::ErrorKind::NotFound => { // Bootstrap cache dir must be set on mobile platforms // using set_config_dir_path #[cfg(any( target_os = "android", target_os = "androideabi", target_os = "ios" ))] check_config_path_set()?; let custom_dir = if let Some(custom_path) = unwrap!(CONFIG_DIR_PATH.lock()).clone() { Some(custom_path.into_os_string().into_string().map_err(|_| { CoreError::from("Config path is not a valid UTF-8 string") })?) } else { None }; // If there is no config file, assume we are a client QuicP2pConfig { our_type: quic_p2p::OurType::Client, bootstrap_cache_dir: custom_dir, ..Default::default() } } result => result?, } }; // Then if there is a locally running Vault we add it to the list of know contacts. if let Ok(node_info) = read_config_file(vault_dirs()?, VAULT_CONNECTION_INFO_FILE) { let _ = config.hard_coded_contacts.insert(node_info); } Ok(config) } } /// Extra configuration options intended for developers. #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)] pub struct DevConfig { /// Switch off mutations limit in mock-vault. pub mock_unlimited_coins: bool, /// Use memory store instead of file store in mock-vault. pub mock_in_memory_storage: bool, /// Set the mock-vault path if using file store (`mock_in_memory_storage` is `false`). pub mock_vault_path: Option<String>, } /// Reads the `safe_core` config file and returns it or a default if this fails. pub fn get_config() -> Config { Config::new() } /// Returns the directory from which the config files are read pub fn config_dir() -> Result<PathBuf, CoreError> { Ok(dirs()?.config_dir().to_path_buf()) } fn dirs() -> Result<ProjectDirs, CoreError> { let project_dirs = if let Some(custom_path) = unwrap!(CONFIG_DIR_PATH.lock()).clone() { ProjectDirs::from_path(custom_path) } else { DEFAULT_SAFE_CORE_PROJECT_DIRS.clone() }; project_dirs.ok_or_else(|| CoreError::from("Cannot determine project directory paths")) } fn vault_dirs() -> Result<ProjectDirs, CoreError> { let project_dirs = if let Some(custom_path) = unwrap!(CONFIG_DIR_PATH.lock()).clone() { ProjectDirs::from_path(custom_path) } else { DEFAULT_VAULT_PROJECT_DIRS.clone() }; project_dirs.ok_or_else(|| CoreError::from("Cannot determine vault directory paths")) } fn read_config_file<T>(dirs: ProjectDirs, file: &str) -> Result<T, CoreError> where T: DeserializeOwned, { let path = dirs.config_dir().join(file); let file = match File::open(&path) { Ok(file) => { trace!("Reading: {}", path.display()); file } Err(error) => { trace!("Not available: {}", path.display()); return Err(error.into()); } }; let reader = BufReader::new(file); serde_json::from_reader(reader).map_err(|err| { info!("Could not parse: {} ({:?})", err, err); err.into() }) } /// Writes a `safe_core` config file **for use by tests and examples**. /// /// N.B. This method should only be used as a utility for test and examples. In normal use cases, /// the config file should be created by the Vault's installer. #[cfg(test)] pub fn write_config_file(config: &Config) -> Result<PathBuf, CoreError> { let dir = config_dir()?; fs::create_dir_all(dir.clone())?; let path = dir.join(CONFIG_FILE); dbg!(&path); let mut file = File::create(&path)?; serde_json::to_writer_pretty(&mut file, config)?; file.sync_all()?; Ok(path) } #[cfg(all(test, feature = "mock-network"))] mod test { use super::*; use std::env::temp_dir; // 1. Write the default config file to temp directory. // 2. Set the temp directory as the custom config directory path. // 3. Assert that `Config::new()` reads the default config written to disk. // 4. Verify that `Config::new()` generates the correct default config. // The default config will have the custom config path in the // `boostrap_cache_dir` field and `our_type` will be set to `Client` #[test] fn custom_config_path() { let path = temp_dir(); let temp_dir_path = path.clone(); set_config_dir_path(&path); // In the default config, `our_type` will be set to Node. let config: Config = Default::default(); unwrap!(write_config_file(&config)); let read_cfg = Config::new(); assert_eq!(config, read_cfg); let mut path = unwrap!(ProjectDirs::from_path(temp_dir_path.clone())) .config_dir() .to_path_buf(); path.push(CONFIG_FILE); unwrap!(std::fs::remove_file(path)); // In the absence of a config file, the config handler // should initialize the `our_type` field to Client. let config = Config::new(); let expected_config = Config { quic_p2p: QuicP2pConfig { our_type: quic_p2p::OurType::Client, bootstrap_cache_dir: Some(unwrap!(temp_dir_path.into_os_string().into_string())), ..Default::default() }, ..Default::default() }; assert_eq!(config, expected_config); } }
Config
identifier_name
TestFastLength.rs
/* * Copyright (C) 2016 The Android Open Source Project * * 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. */ // Don't edit this file! It is auto-generated by frameworks/rs/api/generate.sh. #pragma version(1) #pragma rs java_package_name(android.renderscript.cts) float __attribute__((kernel)) testFastLengthFloatFloat(float inV) { return fast_length(inV); }
float __attribute__((kernel)) testFastLengthFloat2Float(float2 inV) { return fast_length(inV); } float __attribute__((kernel)) testFastLengthFloat3Float(float3 inV) { return fast_length(inV); } float __attribute__((kernel)) testFastLengthFloat4Float(float4 inV) { return fast_length(inV); }
random_line_split
binary.rs
/* * Copyright (C) 2017 Genymobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::fmt::Write; use byteorder::{BigEndian, ByteOrder}; pub fn to_byte_array(value: u32) -> [u8; 4] { let mut raw = [0u8; 4]; BigEndian::write_u32(&mut raw, value); raw } pub fn
(data: &[u8]) -> String { let mut s = String::new(); for (i, &byte) in data.iter().enumerate() { if i % 16 == 0 { write!(&mut s, "\n").unwrap(); } else if i % 8 == 0 { write!(&mut s, " ").unwrap(); } write!(&mut s, "{:02X} ", byte).unwrap(); } s } // only compare the data part for fat pointers (ignore the vtable part) // for some (buggy) reason, the vtable part may be different even if the data reference the same // object // See <https://github.com/Genymobile/gnirehtet/issues/61#issuecomment-370933770> pub fn ptr_data_eq<T:?Sized>(lhs: *const T, rhs: *const T) -> bool { // cast to thin pointers to ignore the vtable part lhs as *const () == rhs as *const () }
to_string
identifier_name
binary.rs
/* * Copyright (C) 2017 Genymobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::fmt::Write; use byteorder::{BigEndian, ByteOrder}; pub fn to_byte_array(value: u32) -> [u8; 4] { let mut raw = [0u8; 4]; BigEndian::write_u32(&mut raw, value); raw } pub fn to_string(data: &[u8]) -> String { let mut s = String::new(); for (i, &byte) in data.iter().enumerate() { if i % 16 == 0
else if i % 8 == 0 { write!(&mut s, " ").unwrap(); } write!(&mut s, "{:02X} ", byte).unwrap(); } s } // only compare the data part for fat pointers (ignore the vtable part) // for some (buggy) reason, the vtable part may be different even if the data reference the same // object // See <https://github.com/Genymobile/gnirehtet/issues/61#issuecomment-370933770> pub fn ptr_data_eq<T:?Sized>(lhs: *const T, rhs: *const T) -> bool { // cast to thin pointers to ignore the vtable part lhs as *const () == rhs as *const () }
{ write!(&mut s, "\n").unwrap(); }
conditional_block
binary.rs
/* * Copyright (C) 2017 Genymobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::fmt::Write; use byteorder::{BigEndian, ByteOrder}; pub fn to_byte_array(value: u32) -> [u8; 4] { let mut raw = [0u8; 4]; BigEndian::write_u32(&mut raw, value); raw } pub fn to_string(data: &[u8]) -> String { let mut s = String::new(); for (i, &byte) in data.iter().enumerate() { if i % 16 == 0 { write!(&mut s, "\n").unwrap(); } else if i % 8 == 0 { write!(&mut s, " ").unwrap(); }
write!(&mut s, "{:02X} ", byte).unwrap(); } s } // only compare the data part for fat pointers (ignore the vtable part) // for some (buggy) reason, the vtable part may be different even if the data reference the same // object // See <https://github.com/Genymobile/gnirehtet/issues/61#issuecomment-370933770> pub fn ptr_data_eq<T:?Sized>(lhs: *const T, rhs: *const T) -> bool { // cast to thin pointers to ignore the vtable part lhs as *const () == rhs as *const () }
random_line_split
binary.rs
/* * Copyright (C) 2017 Genymobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::fmt::Write; use byteorder::{BigEndian, ByteOrder}; pub fn to_byte_array(value: u32) -> [u8; 4]
pub fn to_string(data: &[u8]) -> String { let mut s = String::new(); for (i, &byte) in data.iter().enumerate() { if i % 16 == 0 { write!(&mut s, "\n").unwrap(); } else if i % 8 == 0 { write!(&mut s, " ").unwrap(); } write!(&mut s, "{:02X} ", byte).unwrap(); } s } // only compare the data part for fat pointers (ignore the vtable part) // for some (buggy) reason, the vtable part may be different even if the data reference the same // object // See <https://github.com/Genymobile/gnirehtet/issues/61#issuecomment-370933770> pub fn ptr_data_eq<T:?Sized>(lhs: *const T, rhs: *const T) -> bool { // cast to thin pointers to ignore the vtable part lhs as *const () == rhs as *const () }
{ let mut raw = [0u8; 4]; BigEndian::write_u32(&mut raw, value); raw }
identifier_body
borrowck-overloaded-index-autoderef.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we still see borrowck errors of various kinds when using // indexing and autoderef in combination. use std::ops::{Index, IndexMut}; struct Foo { x: isize, y: isize, } impl<'a> Index<&'a String> for Foo { type Output = isize; fn index(&self, z: &String) -> &isize { if *z == "x" { &self.x } else { &self.y } } } impl<'a> IndexMut<&'a String> for Foo { fn index_mut(&mut self, z: &String) -> &mut isize { if *z == "x" { &mut self.x } else
} } fn test1(mut f: Box<Foo>, s: String) { let p = &mut f[&s]; let q = &f[&s]; //~ ERROR cannot borrow p.use_mut(); } fn test2(mut f: Box<Foo>, s: String) { let p = &mut f[&s]; let q = &mut f[&s]; //~ ERROR cannot borrow p.use_mut(); } struct Bar { foo: Foo } fn test3(mut f: Box<Bar>, s: String) { let p = &mut f.foo[&s]; let q = &mut f.foo[&s]; //~ ERROR cannot borrow p.use_mut(); } fn test4(mut f: Box<Bar>, s: String) { let p = &f.foo[&s]; let q = &f.foo[&s]; p.use_ref(); } fn test5(mut f: Box<Bar>, s: String) { let p = &f.foo[&s]; let q = &mut f.foo[&s]; //~ ERROR cannot borrow p.use_ref(); } fn test6(mut f: Box<Bar>, g: Foo, s: String) { let p = &f.foo[&s]; f.foo = g; //~ ERROR cannot assign p.use_ref(); } fn test7(mut f: Box<Bar>, g: Bar, s: String) { let p = &f.foo[&s]; *f = g; //~ ERROR cannot assign p.use_ref(); } fn test8(mut f: Box<Bar>, g: Foo, s: String) { let p = &mut f.foo[&s]; f.foo = g; //~ ERROR cannot assign p.use_mut(); } fn test9(mut f: Box<Bar>, g: Bar, s: String) { let p = &mut f.foo[&s]; *f = g; //~ ERROR cannot assign p.use_mut(); } fn main() { } trait Fake { fn use_mut(&mut self) { } fn use_ref(&self) { } } impl<T> Fake for T { }
{ &mut self.y }
conditional_block
borrowck-overloaded-index-autoderef.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we still see borrowck errors of various kinds when using // indexing and autoderef in combination. use std::ops::{Index, IndexMut}; struct Foo { x: isize, y: isize, } impl<'a> Index<&'a String> for Foo { type Output = isize; fn index(&self, z: &String) -> &isize { if *z == "x" { &self.x } else { &self.y } } } impl<'a> IndexMut<&'a String> for Foo { fn index_mut(&mut self, z: &String) -> &mut isize { if *z == "x" { &mut self.x } else { &mut self.y } } } fn test1(mut f: Box<Foo>, s: String) { let p = &mut f[&s]; let q = &f[&s]; //~ ERROR cannot borrow p.use_mut(); } fn test2(mut f: Box<Foo>, s: String) { let p = &mut f[&s]; let q = &mut f[&s]; //~ ERROR cannot borrow p.use_mut(); } struct Bar { foo: Foo } fn
(mut f: Box<Bar>, s: String) { let p = &mut f.foo[&s]; let q = &mut f.foo[&s]; //~ ERROR cannot borrow p.use_mut(); } fn test4(mut f: Box<Bar>, s: String) { let p = &f.foo[&s]; let q = &f.foo[&s]; p.use_ref(); } fn test5(mut f: Box<Bar>, s: String) { let p = &f.foo[&s]; let q = &mut f.foo[&s]; //~ ERROR cannot borrow p.use_ref(); } fn test6(mut f: Box<Bar>, g: Foo, s: String) { let p = &f.foo[&s]; f.foo = g; //~ ERROR cannot assign p.use_ref(); } fn test7(mut f: Box<Bar>, g: Bar, s: String) { let p = &f.foo[&s]; *f = g; //~ ERROR cannot assign p.use_ref(); } fn test8(mut f: Box<Bar>, g: Foo, s: String) { let p = &mut f.foo[&s]; f.foo = g; //~ ERROR cannot assign p.use_mut(); } fn test9(mut f: Box<Bar>, g: Bar, s: String) { let p = &mut f.foo[&s]; *f = g; //~ ERROR cannot assign p.use_mut(); } fn main() { } trait Fake { fn use_mut(&mut self) { } fn use_ref(&self) { } } impl<T> Fake for T { }
test3
identifier_name
borrowck-overloaded-index-autoderef.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we still see borrowck errors of various kinds when using // indexing and autoderef in combination. use std::ops::{Index, IndexMut}; struct Foo { x: isize, y: isize, } impl<'a> Index<&'a String> for Foo { type Output = isize; fn index(&self, z: &String) -> &isize { if *z == "x" { &self.x } else { &self.y } } } impl<'a> IndexMut<&'a String> for Foo {
} else { &mut self.y } } } fn test1(mut f: Box<Foo>, s: String) { let p = &mut f[&s]; let q = &f[&s]; //~ ERROR cannot borrow p.use_mut(); } fn test2(mut f: Box<Foo>, s: String) { let p = &mut f[&s]; let q = &mut f[&s]; //~ ERROR cannot borrow p.use_mut(); } struct Bar { foo: Foo } fn test3(mut f: Box<Bar>, s: String) { let p = &mut f.foo[&s]; let q = &mut f.foo[&s]; //~ ERROR cannot borrow p.use_mut(); } fn test4(mut f: Box<Bar>, s: String) { let p = &f.foo[&s]; let q = &f.foo[&s]; p.use_ref(); } fn test5(mut f: Box<Bar>, s: String) { let p = &f.foo[&s]; let q = &mut f.foo[&s]; //~ ERROR cannot borrow p.use_ref(); } fn test6(mut f: Box<Bar>, g: Foo, s: String) { let p = &f.foo[&s]; f.foo = g; //~ ERROR cannot assign p.use_ref(); } fn test7(mut f: Box<Bar>, g: Bar, s: String) { let p = &f.foo[&s]; *f = g; //~ ERROR cannot assign p.use_ref(); } fn test8(mut f: Box<Bar>, g: Foo, s: String) { let p = &mut f.foo[&s]; f.foo = g; //~ ERROR cannot assign p.use_mut(); } fn test9(mut f: Box<Bar>, g: Bar, s: String) { let p = &mut f.foo[&s]; *f = g; //~ ERROR cannot assign p.use_mut(); } fn main() { } trait Fake { fn use_mut(&mut self) { } fn use_ref(&self) { } } impl<T> Fake for T { }
fn index_mut(&mut self, z: &String) -> &mut isize { if *z == "x" { &mut self.x
random_line_split
generator.rs
// a lot of the source of this file is the same as main.rs // but instead of tweeting, it just prints to stdout extern crate rand; use rand::{thread_rng, ThreadRng}; // these files are paths to plain-text lists of the various word types // these paths assume you're running with *cargo run* from the root of the crate // for production, i replace these with absolute paths const NOUNS_FILENAME: &str = "resources/nouns.txt"; const TEMPLATE_FILENAME: &str = "resources/templates.txt"; const ADJECTIVES_FILENAME: &str = "resources/adjectives.txt"; const ADVERBS_FILENAME: &str = "resources/adverbs.txt"; const ABSTRACTS_FILENAME: &str = "resources/abstracts.txt"; // this module does the heavy lifting of generating the text for tweets // because i'm lazy, we do templating and replacement instead of markov chaining mod template_manager; use template_manager::TemplateManager; fn
() { // TemplateManager::new returns a Result because it will fail if there's a problem loading any of the files match TemplateManager::new( TEMPLATE_FILENAME, NOUNS_FILENAME, ADJECTIVES_FILENAME, ADVERBS_FILENAME, ABSTRACTS_FILENAME ) { Ok(manager) => { // i feel like there's probably a way to have the TemplateManager own ThreadRng // but i'm not sure what it is - mutability in structs is hard let mut rng: ThreadRng = thread_rng(); // TemplateManager.make_formatted_quote returns an Option // because it doesn't work if any of the lists of phrases are empty match manager.make_formatted_quote(&mut rng) { Some(quote) => { println!("{}", quote); }, None => { println!("Couldn't generate a tweet"); }, } }, Err(err) => { println!("Failed to create a TemplateManager with err: {}", err); }, } }
main
identifier_name
generator.rs
// a lot of the source of this file is the same as main.rs // but instead of tweeting, it just prints to stdout extern crate rand; use rand::{thread_rng, ThreadRng}; // these files are paths to plain-text lists of the various word types // these paths assume you're running with *cargo run* from the root of the crate // for production, i replace these with absolute paths const NOUNS_FILENAME: &str = "resources/nouns.txt"; const TEMPLATE_FILENAME: &str = "resources/templates.txt"; const ADJECTIVES_FILENAME: &str = "resources/adjectives.txt"; const ADVERBS_FILENAME: &str = "resources/adverbs.txt"; const ABSTRACTS_FILENAME: &str = "resources/abstracts.txt"; // this module does the heavy lifting of generating the text for tweets // because i'm lazy, we do templating and replacement instead of markov chaining mod template_manager; use template_manager::TemplateManager; fn main() { // TemplateManager::new returns a Result because it will fail if there's a problem loading any of the files match TemplateManager::new( TEMPLATE_FILENAME, NOUNS_FILENAME, ADJECTIVES_FILENAME, ADVERBS_FILENAME, ABSTRACTS_FILENAME ) { Ok(manager) => { // i feel like there's probably a way to have the TemplateManager own ThreadRng // but i'm not sure what it is - mutability in structs is hard let mut rng: ThreadRng = thread_rng(); // TemplateManager.make_formatted_quote returns an Option // because it doesn't work if any of the lists of phrases are empty match manager.make_formatted_quote(&mut rng) { Some(quote) => { println!("{}", quote); }, None =>
, } }, Err(err) => { println!("Failed to create a TemplateManager with err: {}", err); }, } }
{ println!("Couldn't generate a tweet"); }
conditional_block
generator.rs
// a lot of the source of this file is the same as main.rs // but instead of tweeting, it just prints to stdout extern crate rand; use rand::{thread_rng, ThreadRng}; // these files are paths to plain-text lists of the various word types // these paths assume you're running with *cargo run* from the root of the crate // for production, i replace these with absolute paths const NOUNS_FILENAME: &str = "resources/nouns.txt"; const TEMPLATE_FILENAME: &str = "resources/templates.txt"; const ADJECTIVES_FILENAME: &str = "resources/adjectives.txt"; const ADVERBS_FILENAME: &str = "resources/adverbs.txt"; const ABSTRACTS_FILENAME: &str = "resources/abstracts.txt"; // this module does the heavy lifting of generating the text for tweets // because i'm lazy, we do templating and replacement instead of markov chaining mod template_manager; use template_manager::TemplateManager; fn main()
}, None => { println!("Couldn't generate a tweet"); }, } }, Err(err) => { println!("Failed to create a TemplateManager with err: {}", err); }, } }
{ // TemplateManager::new returns a Result because it will fail if there's a problem loading any of the files match TemplateManager::new( TEMPLATE_FILENAME, NOUNS_FILENAME, ADJECTIVES_FILENAME, ADVERBS_FILENAME, ABSTRACTS_FILENAME ) { Ok(manager) => { // i feel like there's probably a way to have the TemplateManager own ThreadRng // but i'm not sure what it is - mutability in structs is hard let mut rng: ThreadRng = thread_rng(); // TemplateManager.make_formatted_quote returns an Option // because it doesn't work if any of the lists of phrases are empty match manager.make_formatted_quote(&mut rng) { Some(quote) => { println!("{}", quote);
identifier_body
generator.rs
// a lot of the source of this file is the same as main.rs // but instead of tweeting, it just prints to stdout extern crate rand; use rand::{thread_rng, ThreadRng}; // these files are paths to plain-text lists of the various word types // these paths assume you're running with *cargo run* from the root of the crate // for production, i replace these with absolute paths const NOUNS_FILENAME: &str = "resources/nouns.txt"; const TEMPLATE_FILENAME: &str = "resources/templates.txt"; const ADJECTIVES_FILENAME: &str = "resources/adjectives.txt"; const ADVERBS_FILENAME: &str = "resources/adverbs.txt"; const ABSTRACTS_FILENAME: &str = "resources/abstracts.txt"; // this module does the heavy lifting of generating the text for tweets // because i'm lazy, we do templating and replacement instead of markov chaining mod template_manager; use template_manager::TemplateManager; fn main() { // TemplateManager::new returns a Result because it will fail if there's a problem loading any of the files match TemplateManager::new( TEMPLATE_FILENAME, NOUNS_FILENAME, ADJECTIVES_FILENAME, ADVERBS_FILENAME, ABSTRACTS_FILENAME ) { Ok(manager) => { // i feel like there's probably a way to have the TemplateManager own ThreadRng // but i'm not sure what it is - mutability in structs is hard let mut rng: ThreadRng = thread_rng(); // TemplateManager.make_formatted_quote returns an Option // because it doesn't work if any of the lists of phrases are empty match manager.make_formatted_quote(&mut rng) { Some(quote) => { println!("{}", quote); }, None => { println!("Couldn't generate a tweet"); }, } }, Err(err) => {
println!("Failed to create a TemplateManager with err: {}", err); }, } }
random_line_split
derive_input_object.rs
use fnv::FnvHashMap; use juniper::{ marker, DefaultScalarValue, FromInputValue, GraphQLInputObject, GraphQLType, GraphQLValue, InputValue, Registry, ToInputValue, }; #[derive(GraphQLInputObject, Debug, PartialEq)] #[graphql( name = "MyInput", description = "input descr", scalar = DefaultScalarValue )] struct Input { regular_field: String, #[graphql(name = "haha", default = "33", description = "haha descr")] c: i32, #[graphql(default)] other: Option<bool>, } #[derive(GraphQLInputObject, Debug, PartialEq)] #[graphql(rename = "none")] struct NoRenameInput { regular_field: String, } /// Object comment. #[derive(GraphQLInputObject, Debug, PartialEq)] struct DocComment { /// Field comment. regular_field: bool, } /// Doc 1.\ /// Doc 2. /// /// Doc 4. #[derive(GraphQLInputObject, Debug, PartialEq)] struct MultiDocComment { /// Field 1. /// Field 2. regular_field: bool, } /// This is not used as the description. #[derive(GraphQLInputObject, Debug, PartialEq)] #[graphql(description = "obj override")] struct OverrideDocComment { /// This is not used as the description. #[graphql(description = "field override")] regular_field: bool, } #[derive(Debug, PartialEq)] struct Fake; impl<'a> marker::IsInputType<DefaultScalarValue> for &'a Fake {} impl<'a> FromInputValue for &'a Fake { fn from_input_value(_v: &InputValue) -> Option<&'a Fake> { None } } impl<'a> ToInputValue for &'a Fake { fn to_input_value(&self) -> InputValue { InputValue::scalar("this is fake") } } impl<'a> GraphQLType<DefaultScalarValue> for &'a Fake { fn name(_: &()) -> Option<&'static str> { None } fn meta<'r>(_: &(), registry: &mut Registry<'r>) -> juniper::meta::MetaType<'r> where DefaultScalarValue: 'r, { let meta = registry.build_enum_type::<&'a Fake>( &(), &[juniper::meta::EnumValue { name: "fake".to_string(), description: None, deprecation_status: juniper::meta::DeprecationStatus::Current, }], ); meta.into_meta() } } impl<'a> GraphQLValue<DefaultScalarValue> for &'a Fake { type Context = (); type TypeInfo = (); fn type_name<'i>(&self, info: &'i Self::TypeInfo) -> Option<&'i str> { <Self as GraphQLType>::name(info) } } #[derive(GraphQLInputObject, Debug, PartialEq)] #[graphql(scalar = DefaultScalarValue)] struct WithLifetime<'a> { regular_field: &'a Fake, } #[test] fn test_derived_input_object() { assert_eq!( <Input as GraphQLType<DefaultScalarValue>>::name(&()), Some("MyInput") ); // Validate meta info. let mut registry: Registry = Registry::new(FnvHashMap::default()); let meta = Input::meta(&(), &mut registry); assert_eq!(meta.name(), Some("MyInput")); assert_eq!(meta.description(), Some(&"input descr".to_string())); // Test default value injection. let input_no_defaults: InputValue = ::serde_json::from_value(serde_json::json!({ "regularField": "a", })) .unwrap(); let output_no_defaults: Input = FromInputValue::from_input_value(&input_no_defaults).unwrap(); assert_eq!( output_no_defaults, Input { regular_field: "a".into(), c: 33, other: None, } ); // Test with all values supplied. let input: InputValue = ::serde_json::from_value(serde_json::json!({ "regularField": "a", "haha": 55, "other": true, })) .unwrap(); let output: Input = FromInputValue::from_input_value(&input).unwrap(); assert_eq!( output, Input { regular_field: "a".into(), c: 55, other: Some(true), } ); // Test disable renaming let input: InputValue = ::serde_json::from_value(serde_json::json!({ "regular_field": "hello", })) .unwrap(); let output: NoRenameInput = FromInputValue::from_input_value(&input).unwrap(); assert_eq!( output, NoRenameInput { regular_field: "hello".into(), } ); } #[test] fn
() { let mut registry: Registry = Registry::new(FnvHashMap::default()); let meta = DocComment::meta(&(), &mut registry); assert_eq!(meta.description(), Some(&"Object comment.".to_string())); } #[test] fn test_multi_doc_comment() { let mut registry: Registry = Registry::new(FnvHashMap::default()); let meta = MultiDocComment::meta(&(), &mut registry); assert_eq!( meta.description(), Some(&"Doc 1. Doc 2.\n\nDoc 4.".to_string()) ); } #[test] fn test_doc_comment_override() { let mut registry: Registry = Registry::new(FnvHashMap::default()); let meta = OverrideDocComment::meta(&(), &mut registry); assert_eq!(meta.description(), Some(&"obj override".to_string())); }
test_doc_comment
identifier_name
derive_input_object.rs
use fnv::FnvHashMap; use juniper::{ marker, DefaultScalarValue, FromInputValue, GraphQLInputObject, GraphQLType, GraphQLValue, InputValue, Registry, ToInputValue, }; #[derive(GraphQLInputObject, Debug, PartialEq)] #[graphql( name = "MyInput", description = "input descr", scalar = DefaultScalarValue )] struct Input { regular_field: String, #[graphql(name = "haha", default = "33", description = "haha descr")] c: i32, #[graphql(default)] other: Option<bool>, } #[derive(GraphQLInputObject, Debug, PartialEq)] #[graphql(rename = "none")] struct NoRenameInput { regular_field: String, } /// Object comment. #[derive(GraphQLInputObject, Debug, PartialEq)] struct DocComment { /// Field comment. regular_field: bool, } /// Doc 1.\ /// Doc 2. /// /// Doc 4. #[derive(GraphQLInputObject, Debug, PartialEq)] struct MultiDocComment { /// Field 1. /// Field 2. regular_field: bool, } /// This is not used as the description. #[derive(GraphQLInputObject, Debug, PartialEq)] #[graphql(description = "obj override")] struct OverrideDocComment { /// This is not used as the description. #[graphql(description = "field override")] regular_field: bool, } #[derive(Debug, PartialEq)] struct Fake; impl<'a> marker::IsInputType<DefaultScalarValue> for &'a Fake {} impl<'a> FromInputValue for &'a Fake { fn from_input_value(_v: &InputValue) -> Option<&'a Fake> { None } } impl<'a> ToInputValue for &'a Fake { fn to_input_value(&self) -> InputValue { InputValue::scalar("this is fake") } } impl<'a> GraphQLType<DefaultScalarValue> for &'a Fake { fn name(_: &()) -> Option<&'static str> { None } fn meta<'r>(_: &(), registry: &mut Registry<'r>) -> juniper::meta::MetaType<'r> where DefaultScalarValue: 'r, { let meta = registry.build_enum_type::<&'a Fake>( &(), &[juniper::meta::EnumValue { name: "fake".to_string(), description: None, deprecation_status: juniper::meta::DeprecationStatus::Current, }], ); meta.into_meta() } } impl<'a> GraphQLValue<DefaultScalarValue> for &'a Fake { type Context = (); type TypeInfo = (); fn type_name<'i>(&self, info: &'i Self::TypeInfo) -> Option<&'i str> { <Self as GraphQLType>::name(info) } } #[derive(GraphQLInputObject, Debug, PartialEq)] #[graphql(scalar = DefaultScalarValue)] struct WithLifetime<'a> { regular_field: &'a Fake, } #[test] fn test_derived_input_object() { assert_eq!( <Input as GraphQLType<DefaultScalarValue>>::name(&()), Some("MyInput") ); // Validate meta info. let mut registry: Registry = Registry::new(FnvHashMap::default()); let meta = Input::meta(&(), &mut registry); assert_eq!(meta.name(), Some("MyInput")); assert_eq!(meta.description(), Some(&"input descr".to_string())); // Test default value injection. let input_no_defaults: InputValue = ::serde_json::from_value(serde_json::json!({ "regularField": "a", })) .unwrap(); let output_no_defaults: Input = FromInputValue::from_input_value(&input_no_defaults).unwrap(); assert_eq!( output_no_defaults, Input { regular_field: "a".into(), c: 33, other: None, } ); // Test with all values supplied. let input: InputValue = ::serde_json::from_value(serde_json::json!({ "regularField": "a", "haha": 55, "other": true, })) .unwrap(); let output: Input = FromInputValue::from_input_value(&input).unwrap(); assert_eq!( output, Input { regular_field: "a".into(), c: 55, other: Some(true), } ); // Test disable renaming let input: InputValue = ::serde_json::from_value(serde_json::json!({ "regular_field": "hello", })) .unwrap(); let output: NoRenameInput = FromInputValue::from_input_value(&input).unwrap(); assert_eq!( output, NoRenameInput { regular_field: "hello".into(), } ); } #[test] fn test_doc_comment() { let mut registry: Registry = Registry::new(FnvHashMap::default()); let meta = DocComment::meta(&(), &mut registry); assert_eq!(meta.description(), Some(&"Object comment.".to_string())); } #[test] fn test_multi_doc_comment() { let mut registry: Registry = Registry::new(FnvHashMap::default()); let meta = MultiDocComment::meta(&(), &mut registry); assert_eq!( meta.description(), Some(&"Doc 1. Doc 2.\n\nDoc 4.".to_string()) ); } #[test] fn test_doc_comment_override() { let mut registry: Registry = Registry::new(FnvHashMap::default()); let meta = OverrideDocComment::meta(&(), &mut registry); assert_eq!(meta.description(), Some(&"obj override".to_string()));
}
random_line_split
builtin-superkinds-self-type.rs
// Copyright 2013 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. // Tests (negatively) the ability for the Self type in default methods // to use capabilities granted by builtin kinds as supertraits. use std::sync::mpsc::{channel, Sender}; trait Foo : Sync+'static { fn foo(self, mut chan: Sender<Self>)
} impl <T: Sync> Foo for T { } //~^ ERROR the parameter type `T` may not live long enough fn main() { let (tx, rx) = channel(); 1193182is.foo(tx); assert!(rx.recv() == 1193182is); }
{ }
identifier_body
builtin-superkinds-self-type.rs
// Copyright 2013 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
// option. This file may not be copied, modified, or distributed // except according to those terms. // Tests (negatively) the ability for the Self type in default methods // to use capabilities granted by builtin kinds as supertraits. use std::sync::mpsc::{channel, Sender}; trait Foo : Sync+'static { fn foo(self, mut chan: Sender<Self>) { } } impl <T: Sync> Foo for T { } //~^ ERROR the parameter type `T` may not live long enough fn main() { let (tx, rx) = channel(); 1193182is.foo(tx); assert!(rx.recv() == 1193182is); }
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
builtin-superkinds-self-type.rs
// Copyright 2013 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. // Tests (negatively) the ability for the Self type in default methods // to use capabilities granted by builtin kinds as supertraits. use std::sync::mpsc::{channel, Sender}; trait Foo : Sync+'static { fn
(self, mut chan: Sender<Self>) { } } impl <T: Sync> Foo for T { } //~^ ERROR the parameter type `T` may not live long enough fn main() { let (tx, rx) = channel(); 1193182is.foo(tx); assert!(rx.recv() == 1193182is); }
foo
identifier_name
euler50.rs
pub fn main() { let primes = || (2..).filter(|&n| (2..(n as f32).sqrt() as u32 + 1).all(|i| n % i!= 0)); let isprime = |n: &u32| (2..(*n as f32).sqrt() as u32 + 1).all(|i| n % i!= 0); let mut sum = 0; let mut primesums = Vec::new(); for p in primes() { sum += p; if sum > 1_000_000 { break; }; primesums.push(sum); } let mut max = 0; for &n in &primesums { for &&p in &primesums.iter().take_while(|&&p| p < n).collect::<Vec<_>>() { let candidate = n - p; if isprime(&candidate) && candidate > max
} } println!("{}", max); }
{ max = candidate; }
conditional_block
euler50.rs
let isprime = |n: &u32| (2..(*n as f32).sqrt() as u32 + 1).all(|i| n % i!= 0); let mut sum = 0; let mut primesums = Vec::new(); for p in primes() { sum += p; if sum > 1_000_000 { break; }; primesums.push(sum); } let mut max = 0; for &n in &primesums { for &&p in &primesums.iter().take_while(|&&p| p < n).collect::<Vec<_>>() { let candidate = n - p; if isprime(&candidate) && candidate > max { max = candidate; } } } println!("{}", max); }
pub fn main() { let primes = || (2..).filter(|&n| (2..(n as f32).sqrt() as u32 + 1).all(|i| n % i != 0));
random_line_split
euler50.rs
pub fn
() { let primes = || (2..).filter(|&n| (2..(n as f32).sqrt() as u32 + 1).all(|i| n % i!= 0)); let isprime = |n: &u32| (2..(*n as f32).sqrt() as u32 + 1).all(|i| n % i!= 0); let mut sum = 0; let mut primesums = Vec::new(); for p in primes() { sum += p; if sum > 1_000_000 { break; }; primesums.push(sum); } let mut max = 0; for &n in &primesums { for &&p in &primesums.iter().take_while(|&&p| p < n).collect::<Vec<_>>() { let candidate = n - p; if isprime(&candidate) && candidate > max { max = candidate; } } } println!("{}", max); }
main
identifier_name
euler50.rs
pub fn main()
} } println!("{}", max); }
{ let primes = || (2..).filter(|&n| (2..(n as f32).sqrt() as u32 + 1).all(|i| n % i != 0)); let isprime = |n: &u32| (2..(*n as f32).sqrt() as u32 + 1).all(|i| n % i != 0); let mut sum = 0; let mut primesums = Vec::new(); for p in primes() { sum += p; if sum > 1_000_000 { break; }; primesums.push(sum); } let mut max = 0; for &n in &primesums { for &&p in &primesums.iter().take_while(|&&p| p < n).collect::<Vec<_>>() { let candidate = n - p; if isprime(&candidate) && candidate > max { max = candidate; }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of in script so that the devtools crate can be //! modified independently of the rest of Servo. #![crate_name = "style_traits"] #![crate_type = "rlib"] #![deny(unsafe_code, missing_docs)] extern crate app_units; #[macro_use] extern crate bitflags; #[macro_use] extern crate cssparser; extern crate euclid; extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; extern crate selectors; #[cfg(feature = "servo")] #[macro_use] extern crate serde; #[cfg(feature = "servo")] extern crate webrender_api; extern crate servo_arc; #[cfg(feature = "servo")] extern crate servo_atoms; #[cfg(feature = "servo")] extern crate servo_url; #[cfg(feature = "servo")] pub use webrender_api::DevicePixel; use cssparser::{CowRcStr, Token}; use selectors::parser::SelectorParseErrorKind; #[cfg(feature = "servo")] use servo_atoms::Atom; /// One hardware pixel. /// /// This unit corresponds to the smallest addressable element of the display hardware. #[cfg(not(feature = "servo"))] #[derive(Clone, Copy, Debug)] pub enum DevicePixel {} /// Represents a mobile style pinch zoom factor. /// TODO(gw): Once WR supports pinch zoom, use a type directly from webrender_api. #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize, MallocSizeOf))] pub struct PinchZoomFactor(f32); impl PinchZoomFactor { /// Construct a new pinch zoom factor. pub fn new(scale: f32) -> PinchZoomFactor { PinchZoomFactor(scale) } /// Get the pinch zoom factor as an untyped float. pub fn get(&self) -> f32 { self.0 } } /// One CSS "px" in the coordinate system of the "initial viewport": /// <http://www.w3.org/TR/css-device-adapt/#initial-viewport> /// /// `CSSPixel` is equal to `DeviceIndependentPixel` times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport /// so it still exactly fits the visible area. /// /// At the default zoom level of 100%, one `CSSPixel` is equal to one `DeviceIndependentPixel`. However, if the /// document is zoomed in or out then this scale may be larger or smaller. #[derive(Clone, Copy, Debug)] pub enum CSSPixel {} // In summary, the hierarchy of pixel units and the factors to convert from one to the next: // // DevicePixel // / hidpi_ratio => DeviceIndependentPixel // / desktop_zoom => CSSPixel pub mod cursor; pub mod specified_value_info; #[macro_use] pub mod values; #[macro_use] pub mod viewport; pub use specified_value_info::{CssType, KeywordsCollectFn, SpecifiedValueInfo}; pub use values::{Comma, CommaWithSpace, CssWriter, OneOrMoreSeparated, Separator, Space, ToCss}; /// The error type for all CSS parsing routines. pub type ParseError<'i> = cssparser::ParseError<'i, StyleParseErrorKind<'i>>; /// Error in property value parsing pub type ValueParseError<'i> = cssparser::ParseError<'i, ValueParseErrorKind<'i>>; #[derive(Clone, Debug, PartialEq)] /// Errors that can be encountered while parsing CSS values. pub enum StyleParseErrorKind<'i> { /// A bad URL token in a DVB. BadUrlInDeclarationValueBlock(CowRcStr<'i>), /// A bad string token in a DVB. BadStringInDeclarationValueBlock(CowRcStr<'i>), /// Unexpected closing parenthesis in a DVB. UnbalancedCloseParenthesisInDeclarationValueBlock, /// Unexpected closing bracket in a DVB. UnbalancedCloseSquareBracketInDeclarationValueBlock, /// Unexpected closing curly bracket in a DVB. UnbalancedCloseCurlyBracketInDeclarationValueBlock, /// A property declaration value had input remaining after successfully parsing. PropertyDeclarationValueNotExhausted, /// An unexpected dimension token was encountered. UnexpectedDimension(CowRcStr<'i>), /// Expected identifier not found. ExpectedIdentifier(Token<'i>), /// Missing or invalid media feature name. MediaQueryExpectedFeatureName(CowRcStr<'i>), /// Missing or invalid media feature value. MediaQueryExpectedFeatureValue, /// min- or max- properties must have a value. RangedExpressionWithNoValue, /// A function was encountered that was not expected. UnexpectedFunction(CowRcStr<'i>), /// @namespace must be before any rule but @charset and @import UnexpectedNamespaceRule, /// @import must be before any rule but @charset UnexpectedImportRule, /// Unexpected @charset rule encountered. UnexpectedCharsetRule, /// Unsupported @ rule UnsupportedAtRule(CowRcStr<'i>), /// A placeholder for many sources of errors that require more specific variants. UnspecifiedError, /// An unexpected token was found within a namespace rule. UnexpectedTokenWithinNamespace(Token<'i>), /// An error was encountered while parsing a property value. ValueError(ValueParseErrorKind<'i>), /// An error was encountered while parsing a selector SelectorError(SelectorParseErrorKind<'i>), /// The property declaration was for an unknown property. UnknownProperty(CowRcStr<'i>), /// An unknown vendor-specific identifier was encountered. UnknownVendorProperty, /// The property declaration was for a disabled experimental property. ExperimentalProperty, /// The property declaration contained an invalid color value. InvalidColor(CowRcStr<'i>, Token<'i>), /// The property declaration contained an invalid filter value. InvalidFilter(CowRcStr<'i>, Token<'i>), /// The property declaration contained an invalid value. OtherInvalidValue(CowRcStr<'i>), /// The declaration contained an animation property, and we were parsing /// this as a keyframe block (so that property should be ignored). /// /// See: https://drafts.csswg.org/css-animations/#keyframes AnimationPropertyInKeyframeBlock, /// The property is not allowed within a page rule. NotAllowedInPageRule, } impl<'i> From<ValueParseErrorKind<'i>> for StyleParseErrorKind<'i> { fn from(this: ValueParseErrorKind<'i>) -> Self { StyleParseErrorKind::ValueError(this) } } impl<'i> From<SelectorParseErrorKind<'i>> for StyleParseErrorKind<'i> { fn from(this: SelectorParseErrorKind<'i>) -> Self { StyleParseErrorKind::SelectorError(this) } } /// Specific errors that can be encountered while parsing property values. #[derive(Clone, Debug, PartialEq)] pub enum ValueParseErrorKind<'i> { /// An invalid token was encountered while parsing a color value. InvalidColor(Token<'i>), /// An invalid filter value was encountered. InvalidFilter(Token<'i>), } impl<'i> StyleParseErrorKind<'i> { /// Create an InvalidValue parse error pub fn new_invalid(name: CowRcStr<'i>, value_error: ParseError<'i>) -> ParseError<'i> { let variant = match value_error.kind { cssparser::ParseErrorKind::Custom(StyleParseErrorKind::ValueError(e)) => { match e { ValueParseErrorKind::InvalidColor(token) =>
ValueParseErrorKind::InvalidFilter(token) => { StyleParseErrorKind::InvalidFilter(name, token) } } } _ => StyleParseErrorKind::OtherInvalidValue(name), }; cssparser::ParseError { kind: cssparser::ParseErrorKind::Custom(variant), location: value_error.location, } } } bitflags! { /// The mode to use when parsing values. pub struct ParsingMode: u8 { /// In CSS; lengths must have units, except for zero values, where the unit can be omitted. /// <https://www.w3.org/TR/css3-values/#lengths> const DEFAULT = 0x00; /// In SVG; a coordinate or length value without a unit identifier (e.g., "25") is assumed /// to be in user units (px). /// <https://www.w3.org/TR/SVG/coords.html#Units> const ALLOW_UNITLESS_LENGTH = 0x01; /// In SVG; out-of-range values are not treated as an error in parsing. /// <https://www.w3.org/TR/SVG/implnote.html#RangeClamping> const ALLOW_ALL_NUMERIC_VALUES = 0x02; } } impl ParsingMode { /// Whether the parsing mode allows unitless lengths for non-zero values to be intpreted as px. #[inline] pub fn allows_unitless_lengths(&self) -> bool { self.intersects(ParsingMode::ALLOW_UNITLESS_LENGTH) } /// Whether the parsing mode allows all numeric values. #[inline] pub fn allows_all_numeric_values(&self) -> bool { self.intersects(ParsingMode::ALLOW_ALL_NUMERIC_VALUES) } } #[cfg(feature = "servo")] /// Speculatively execute paint code in the worklet thread pool. pub trait SpeculativePainter: Send + Sync { /// <https://drafts.css-houdini.org/css-paint-api/#draw-a-paint-image> fn speculatively_draw_a_paint_image(&self, properties: Vec<(Atom, String)>, arguments: Vec<String>); }
{ StyleParseErrorKind::InvalidColor(name, token) }
conditional_block
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/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of in script so that the devtools crate can be //! modified independently of the rest of Servo. #![crate_name = "style_traits"] #![crate_type = "rlib"] #![deny(unsafe_code, missing_docs)] extern crate app_units; #[macro_use] extern crate bitflags; #[macro_use] extern crate cssparser; extern crate euclid; extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; extern crate selectors; #[cfg(feature = "servo")] #[macro_use] extern crate serde; #[cfg(feature = "servo")] extern crate webrender_api; extern crate servo_arc; #[cfg(feature = "servo")] extern crate servo_atoms; #[cfg(feature = "servo")] extern crate servo_url; #[cfg(feature = "servo")] pub use webrender_api::DevicePixel; use cssparser::{CowRcStr, Token}; use selectors::parser::SelectorParseErrorKind; #[cfg(feature = "servo")] use servo_atoms::Atom; /// One hardware pixel. /// /// This unit corresponds to the smallest addressable element of the display hardware. #[cfg(not(feature = "servo"))] #[derive(Clone, Copy, Debug)] pub enum DevicePixel {} /// Represents a mobile style pinch zoom factor. /// TODO(gw): Once WR supports pinch zoom, use a type directly from webrender_api. #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize, MallocSizeOf))] pub struct PinchZoomFactor(f32); impl PinchZoomFactor { /// Construct a new pinch zoom factor. pub fn new(scale: f32) -> PinchZoomFactor
/// Get the pinch zoom factor as an untyped float. pub fn get(&self) -> f32 { self.0 } } /// One CSS "px" in the coordinate system of the "initial viewport": /// <http://www.w3.org/TR/css-device-adapt/#initial-viewport> /// /// `CSSPixel` is equal to `DeviceIndependentPixel` times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport /// so it still exactly fits the visible area. /// /// At the default zoom level of 100%, one `CSSPixel` is equal to one `DeviceIndependentPixel`. However, if the /// document is zoomed in or out then this scale may be larger or smaller. #[derive(Clone, Copy, Debug)] pub enum CSSPixel {} // In summary, the hierarchy of pixel units and the factors to convert from one to the next: // // DevicePixel // / hidpi_ratio => DeviceIndependentPixel // / desktop_zoom => CSSPixel pub mod cursor; pub mod specified_value_info; #[macro_use] pub mod values; #[macro_use] pub mod viewport; pub use specified_value_info::{CssType, KeywordsCollectFn, SpecifiedValueInfo}; pub use values::{Comma, CommaWithSpace, CssWriter, OneOrMoreSeparated, Separator, Space, ToCss}; /// The error type for all CSS parsing routines. pub type ParseError<'i> = cssparser::ParseError<'i, StyleParseErrorKind<'i>>; /// Error in property value parsing pub type ValueParseError<'i> = cssparser::ParseError<'i, ValueParseErrorKind<'i>>; #[derive(Clone, Debug, PartialEq)] /// Errors that can be encountered while parsing CSS values. pub enum StyleParseErrorKind<'i> { /// A bad URL token in a DVB. BadUrlInDeclarationValueBlock(CowRcStr<'i>), /// A bad string token in a DVB. BadStringInDeclarationValueBlock(CowRcStr<'i>), /// Unexpected closing parenthesis in a DVB. UnbalancedCloseParenthesisInDeclarationValueBlock, /// Unexpected closing bracket in a DVB. UnbalancedCloseSquareBracketInDeclarationValueBlock, /// Unexpected closing curly bracket in a DVB. UnbalancedCloseCurlyBracketInDeclarationValueBlock, /// A property declaration value had input remaining after successfully parsing. PropertyDeclarationValueNotExhausted, /// An unexpected dimension token was encountered. UnexpectedDimension(CowRcStr<'i>), /// Expected identifier not found. ExpectedIdentifier(Token<'i>), /// Missing or invalid media feature name. MediaQueryExpectedFeatureName(CowRcStr<'i>), /// Missing or invalid media feature value. MediaQueryExpectedFeatureValue, /// min- or max- properties must have a value. RangedExpressionWithNoValue, /// A function was encountered that was not expected. UnexpectedFunction(CowRcStr<'i>), /// @namespace must be before any rule but @charset and @import UnexpectedNamespaceRule, /// @import must be before any rule but @charset UnexpectedImportRule, /// Unexpected @charset rule encountered. UnexpectedCharsetRule, /// Unsupported @ rule UnsupportedAtRule(CowRcStr<'i>), /// A placeholder for many sources of errors that require more specific variants. UnspecifiedError, /// An unexpected token was found within a namespace rule. UnexpectedTokenWithinNamespace(Token<'i>), /// An error was encountered while parsing a property value. ValueError(ValueParseErrorKind<'i>), /// An error was encountered while parsing a selector SelectorError(SelectorParseErrorKind<'i>), /// The property declaration was for an unknown property. UnknownProperty(CowRcStr<'i>), /// An unknown vendor-specific identifier was encountered. UnknownVendorProperty, /// The property declaration was for a disabled experimental property. ExperimentalProperty, /// The property declaration contained an invalid color value. InvalidColor(CowRcStr<'i>, Token<'i>), /// The property declaration contained an invalid filter value. InvalidFilter(CowRcStr<'i>, Token<'i>), /// The property declaration contained an invalid value. OtherInvalidValue(CowRcStr<'i>), /// The declaration contained an animation property, and we were parsing /// this as a keyframe block (so that property should be ignored). /// /// See: https://drafts.csswg.org/css-animations/#keyframes AnimationPropertyInKeyframeBlock, /// The property is not allowed within a page rule. NotAllowedInPageRule, } impl<'i> From<ValueParseErrorKind<'i>> for StyleParseErrorKind<'i> { fn from(this: ValueParseErrorKind<'i>) -> Self { StyleParseErrorKind::ValueError(this) } } impl<'i> From<SelectorParseErrorKind<'i>> for StyleParseErrorKind<'i> { fn from(this: SelectorParseErrorKind<'i>) -> Self { StyleParseErrorKind::SelectorError(this) } } /// Specific errors that can be encountered while parsing property values. #[derive(Clone, Debug, PartialEq)] pub enum ValueParseErrorKind<'i> { /// An invalid token was encountered while parsing a color value. InvalidColor(Token<'i>), /// An invalid filter value was encountered. InvalidFilter(Token<'i>), } impl<'i> StyleParseErrorKind<'i> { /// Create an InvalidValue parse error pub fn new_invalid(name: CowRcStr<'i>, value_error: ParseError<'i>) -> ParseError<'i> { let variant = match value_error.kind { cssparser::ParseErrorKind::Custom(StyleParseErrorKind::ValueError(e)) => { match e { ValueParseErrorKind::InvalidColor(token) => { StyleParseErrorKind::InvalidColor(name, token) } ValueParseErrorKind::InvalidFilter(token) => { StyleParseErrorKind::InvalidFilter(name, token) } } } _ => StyleParseErrorKind::OtherInvalidValue(name), }; cssparser::ParseError { kind: cssparser::ParseErrorKind::Custom(variant), location: value_error.location, } } } bitflags! { /// The mode to use when parsing values. pub struct ParsingMode: u8 { /// In CSS; lengths must have units, except for zero values, where the unit can be omitted. /// <https://www.w3.org/TR/css3-values/#lengths> const DEFAULT = 0x00; /// In SVG; a coordinate or length value without a unit identifier (e.g., "25") is assumed /// to be in user units (px). /// <https://www.w3.org/TR/SVG/coords.html#Units> const ALLOW_UNITLESS_LENGTH = 0x01; /// In SVG; out-of-range values are not treated as an error in parsing. /// <https://www.w3.org/TR/SVG/implnote.html#RangeClamping> const ALLOW_ALL_NUMERIC_VALUES = 0x02; } } impl ParsingMode { /// Whether the parsing mode allows unitless lengths for non-zero values to be intpreted as px. #[inline] pub fn allows_unitless_lengths(&self) -> bool { self.intersects(ParsingMode::ALLOW_UNITLESS_LENGTH) } /// Whether the parsing mode allows all numeric values. #[inline] pub fn allows_all_numeric_values(&self) -> bool { self.intersects(ParsingMode::ALLOW_ALL_NUMERIC_VALUES) } } #[cfg(feature = "servo")] /// Speculatively execute paint code in the worklet thread pool. pub trait SpeculativePainter: Send + Sync { /// <https://drafts.css-houdini.org/css-paint-api/#draw-a-paint-image> fn speculatively_draw_a_paint_image(&self, properties: Vec<(Atom, String)>, arguments: Vec<String>); }
{ PinchZoomFactor(scale) }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of in script so that the devtools crate can be //! modified independently of the rest of Servo. #![crate_name = "style_traits"] #![crate_type = "rlib"] #![deny(unsafe_code, missing_docs)] extern crate app_units; #[macro_use] extern crate bitflags; #[macro_use] extern crate cssparser; extern crate euclid; extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; extern crate selectors; #[cfg(feature = "servo")] #[macro_use] extern crate serde; #[cfg(feature = "servo")] extern crate webrender_api; extern crate servo_arc; #[cfg(feature = "servo")] extern crate servo_atoms; #[cfg(feature = "servo")] extern crate servo_url; #[cfg(feature = "servo")] pub use webrender_api::DevicePixel; use cssparser::{CowRcStr, Token}; use selectors::parser::SelectorParseErrorKind; #[cfg(feature = "servo")] use servo_atoms::Atom; /// One hardware pixel. /// /// This unit corresponds to the smallest addressable element of the display hardware. #[cfg(not(feature = "servo"))] #[derive(Clone, Copy, Debug)] pub enum DevicePixel {} /// Represents a mobile style pinch zoom factor. /// TODO(gw): Once WR supports pinch zoom, use a type directly from webrender_api. #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize, MallocSizeOf))] pub struct PinchZoomFactor(f32); impl PinchZoomFactor { /// Construct a new pinch zoom factor. pub fn new(scale: f32) -> PinchZoomFactor { PinchZoomFactor(scale) } /// Get the pinch zoom factor as an untyped float. pub fn get(&self) -> f32 { self.0 } } /// One CSS "px" in the coordinate system of the "initial viewport": /// <http://www.w3.org/TR/css-device-adapt/#initial-viewport> /// /// `CSSPixel` is equal to `DeviceIndependentPixel` times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport /// so it still exactly fits the visible area. /// /// At the default zoom level of 100%, one `CSSPixel` is equal to one `DeviceIndependentPixel`. However, if the /// document is zoomed in or out then this scale may be larger or smaller. #[derive(Clone, Copy, Debug)] pub enum CSSPixel {} // In summary, the hierarchy of pixel units and the factors to convert from one to the next: // // DevicePixel // / hidpi_ratio => DeviceIndependentPixel // / desktop_zoom => CSSPixel pub mod cursor; pub mod specified_value_info; #[macro_use] pub mod values; #[macro_use] pub mod viewport; pub use specified_value_info::{CssType, KeywordsCollectFn, SpecifiedValueInfo}; pub use values::{Comma, CommaWithSpace, CssWriter, OneOrMoreSeparated, Separator, Space, ToCss}; /// The error type for all CSS parsing routines. pub type ParseError<'i> = cssparser::ParseError<'i, StyleParseErrorKind<'i>>; /// Error in property value parsing pub type ValueParseError<'i> = cssparser::ParseError<'i, ValueParseErrorKind<'i>>; #[derive(Clone, Debug, PartialEq)] /// Errors that can be encountered while parsing CSS values. pub enum StyleParseErrorKind<'i> { /// A bad URL token in a DVB. BadUrlInDeclarationValueBlock(CowRcStr<'i>), /// A bad string token in a DVB. BadStringInDeclarationValueBlock(CowRcStr<'i>), /// Unexpected closing parenthesis in a DVB. UnbalancedCloseParenthesisInDeclarationValueBlock, /// Unexpected closing bracket in a DVB. UnbalancedCloseSquareBracketInDeclarationValueBlock, /// Unexpected closing curly bracket in a DVB. UnbalancedCloseCurlyBracketInDeclarationValueBlock, /// A property declaration value had input remaining after successfully parsing. PropertyDeclarationValueNotExhausted, /// An unexpected dimension token was encountered. UnexpectedDimension(CowRcStr<'i>), /// Expected identifier not found. ExpectedIdentifier(Token<'i>), /// Missing or invalid media feature name. MediaQueryExpectedFeatureName(CowRcStr<'i>), /// Missing or invalid media feature value. MediaQueryExpectedFeatureValue, /// min- or max- properties must have a value. RangedExpressionWithNoValue, /// A function was encountered that was not expected. UnexpectedFunction(CowRcStr<'i>), /// @namespace must be before any rule but @charset and @import UnexpectedNamespaceRule, /// @import must be before any rule but @charset UnexpectedImportRule, /// Unexpected @charset rule encountered. UnexpectedCharsetRule, /// Unsupported @ rule UnsupportedAtRule(CowRcStr<'i>), /// A placeholder for many sources of errors that require more specific variants. UnspecifiedError, /// An unexpected token was found within a namespace rule. UnexpectedTokenWithinNamespace(Token<'i>), /// An error was encountered while parsing a property value. ValueError(ValueParseErrorKind<'i>), /// An error was encountered while parsing a selector SelectorError(SelectorParseErrorKind<'i>), /// The property declaration was for an unknown property. UnknownProperty(CowRcStr<'i>), /// An unknown vendor-specific identifier was encountered. UnknownVendorProperty, /// The property declaration was for a disabled experimental property. ExperimentalProperty, /// The property declaration contained an invalid color value. InvalidColor(CowRcStr<'i>, Token<'i>), /// The property declaration contained an invalid filter value. InvalidFilter(CowRcStr<'i>, Token<'i>), /// The property declaration contained an invalid value. OtherInvalidValue(CowRcStr<'i>), /// The declaration contained an animation property, and we were parsing /// this as a keyframe block (so that property should be ignored). /// /// See: https://drafts.csswg.org/css-animations/#keyframes AnimationPropertyInKeyframeBlock, /// The property is not allowed within a page rule. NotAllowedInPageRule, } impl<'i> From<ValueParseErrorKind<'i>> for StyleParseErrorKind<'i> { fn
(this: ValueParseErrorKind<'i>) -> Self { StyleParseErrorKind::ValueError(this) } } impl<'i> From<SelectorParseErrorKind<'i>> for StyleParseErrorKind<'i> { fn from(this: SelectorParseErrorKind<'i>) -> Self { StyleParseErrorKind::SelectorError(this) } } /// Specific errors that can be encountered while parsing property values. #[derive(Clone, Debug, PartialEq)] pub enum ValueParseErrorKind<'i> { /// An invalid token was encountered while parsing a color value. InvalidColor(Token<'i>), /// An invalid filter value was encountered. InvalidFilter(Token<'i>), } impl<'i> StyleParseErrorKind<'i> { /// Create an InvalidValue parse error pub fn new_invalid(name: CowRcStr<'i>, value_error: ParseError<'i>) -> ParseError<'i> { let variant = match value_error.kind { cssparser::ParseErrorKind::Custom(StyleParseErrorKind::ValueError(e)) => { match e { ValueParseErrorKind::InvalidColor(token) => { StyleParseErrorKind::InvalidColor(name, token) } ValueParseErrorKind::InvalidFilter(token) => { StyleParseErrorKind::InvalidFilter(name, token) } } } _ => StyleParseErrorKind::OtherInvalidValue(name), }; cssparser::ParseError { kind: cssparser::ParseErrorKind::Custom(variant), location: value_error.location, } } } bitflags! { /// The mode to use when parsing values. pub struct ParsingMode: u8 { /// In CSS; lengths must have units, except for zero values, where the unit can be omitted. /// <https://www.w3.org/TR/css3-values/#lengths> const DEFAULT = 0x00; /// In SVG; a coordinate or length value without a unit identifier (e.g., "25") is assumed /// to be in user units (px). /// <https://www.w3.org/TR/SVG/coords.html#Units> const ALLOW_UNITLESS_LENGTH = 0x01; /// In SVG; out-of-range values are not treated as an error in parsing. /// <https://www.w3.org/TR/SVG/implnote.html#RangeClamping> const ALLOW_ALL_NUMERIC_VALUES = 0x02; } } impl ParsingMode { /// Whether the parsing mode allows unitless lengths for non-zero values to be intpreted as px. #[inline] pub fn allows_unitless_lengths(&self) -> bool { self.intersects(ParsingMode::ALLOW_UNITLESS_LENGTH) } /// Whether the parsing mode allows all numeric values. #[inline] pub fn allows_all_numeric_values(&self) -> bool { self.intersects(ParsingMode::ALLOW_ALL_NUMERIC_VALUES) } } #[cfg(feature = "servo")] /// Speculatively execute paint code in the worklet thread pool. pub trait SpeculativePainter: Send + Sync { /// <https://drafts.css-houdini.org/css-paint-api/#draw-a-paint-image> fn speculatively_draw_a_paint_image(&self, properties: Vec<(Atom, String)>, arguments: Vec<String>); }
from
identifier_name
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/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of in script so that the devtools crate can be //! modified independently of the rest of Servo. #![crate_name = "style_traits"] #![crate_type = "rlib"] #![deny(unsafe_code, missing_docs)] extern crate app_units; #[macro_use] extern crate bitflags; #[macro_use] extern crate cssparser; extern crate euclid; extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; extern crate selectors; #[cfg(feature = "servo")] #[macro_use] extern crate serde; #[cfg(feature = "servo")] extern crate webrender_api; extern crate servo_arc; #[cfg(feature = "servo")] extern crate servo_atoms; #[cfg(feature = "servo")] extern crate servo_url; #[cfg(feature = "servo")] pub use webrender_api::DevicePixel; use cssparser::{CowRcStr, Token}; use selectors::parser::SelectorParseErrorKind; #[cfg(feature = "servo")] use servo_atoms::Atom; /// One hardware pixel. /// /// This unit corresponds to the smallest addressable element of the display hardware. #[cfg(not(feature = "servo"))] #[derive(Clone, Copy, Debug)] pub enum DevicePixel {} /// Represents a mobile style pinch zoom factor. /// TODO(gw): Once WR supports pinch zoom, use a type directly from webrender_api. #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize, MallocSizeOf))] pub struct PinchZoomFactor(f32); impl PinchZoomFactor { /// Construct a new pinch zoom factor. pub fn new(scale: f32) -> PinchZoomFactor { PinchZoomFactor(scale) } /// Get the pinch zoom factor as an untyped float. pub fn get(&self) -> f32 { self.0 } } /// One CSS "px" in the coordinate system of the "initial viewport": /// <http://www.w3.org/TR/css-device-adapt/#initial-viewport> /// /// `CSSPixel` is equal to `DeviceIndependentPixel` times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport /// so it still exactly fits the visible area. /// /// At the default zoom level of 100%, one `CSSPixel` is equal to one `DeviceIndependentPixel`. However, if the /// document is zoomed in or out then this scale may be larger or smaller. #[derive(Clone, Copy, Debug)] pub enum CSSPixel {} // In summary, the hierarchy of pixel units and the factors to convert from one to the next: // // DevicePixel // / hidpi_ratio => DeviceIndependentPixel // / desktop_zoom => CSSPixel pub mod cursor; pub mod specified_value_info; #[macro_use] pub mod values; #[macro_use] pub mod viewport; pub use specified_value_info::{CssType, KeywordsCollectFn, SpecifiedValueInfo}; pub use values::{Comma, CommaWithSpace, CssWriter, OneOrMoreSeparated, Separator, Space, ToCss}; /// The error type for all CSS parsing routines. pub type ParseError<'i> = cssparser::ParseError<'i, StyleParseErrorKind<'i>>; /// Error in property value parsing pub type ValueParseError<'i> = cssparser::ParseError<'i, ValueParseErrorKind<'i>>; #[derive(Clone, Debug, PartialEq)] /// Errors that can be encountered while parsing CSS values. pub enum StyleParseErrorKind<'i> { /// A bad URL token in a DVB. BadUrlInDeclarationValueBlock(CowRcStr<'i>), /// A bad string token in a DVB. BadStringInDeclarationValueBlock(CowRcStr<'i>), /// Unexpected closing parenthesis in a DVB. UnbalancedCloseParenthesisInDeclarationValueBlock, /// Unexpected closing bracket in a DVB. UnbalancedCloseSquareBracketInDeclarationValueBlock, /// Unexpected closing curly bracket in a DVB.
UnbalancedCloseCurlyBracketInDeclarationValueBlock, /// A property declaration value had input remaining after successfully parsing. PropertyDeclarationValueNotExhausted, /// An unexpected dimension token was encountered. UnexpectedDimension(CowRcStr<'i>), /// Expected identifier not found. ExpectedIdentifier(Token<'i>), /// Missing or invalid media feature name. MediaQueryExpectedFeatureName(CowRcStr<'i>), /// Missing or invalid media feature value. MediaQueryExpectedFeatureValue, /// min- or max- properties must have a value. RangedExpressionWithNoValue, /// A function was encountered that was not expected. UnexpectedFunction(CowRcStr<'i>), /// @namespace must be before any rule but @charset and @import UnexpectedNamespaceRule, /// @import must be before any rule but @charset UnexpectedImportRule, /// Unexpected @charset rule encountered. UnexpectedCharsetRule, /// Unsupported @ rule UnsupportedAtRule(CowRcStr<'i>), /// A placeholder for many sources of errors that require more specific variants. UnspecifiedError, /// An unexpected token was found within a namespace rule. UnexpectedTokenWithinNamespace(Token<'i>), /// An error was encountered while parsing a property value. ValueError(ValueParseErrorKind<'i>), /// An error was encountered while parsing a selector SelectorError(SelectorParseErrorKind<'i>), /// The property declaration was for an unknown property. UnknownProperty(CowRcStr<'i>), /// An unknown vendor-specific identifier was encountered. UnknownVendorProperty, /// The property declaration was for a disabled experimental property. ExperimentalProperty, /// The property declaration contained an invalid color value. InvalidColor(CowRcStr<'i>, Token<'i>), /// The property declaration contained an invalid filter value. InvalidFilter(CowRcStr<'i>, Token<'i>), /// The property declaration contained an invalid value. OtherInvalidValue(CowRcStr<'i>), /// The declaration contained an animation property, and we were parsing /// this as a keyframe block (so that property should be ignored). /// /// See: https://drafts.csswg.org/css-animations/#keyframes AnimationPropertyInKeyframeBlock, /// The property is not allowed within a page rule. NotAllowedInPageRule, } impl<'i> From<ValueParseErrorKind<'i>> for StyleParseErrorKind<'i> { fn from(this: ValueParseErrorKind<'i>) -> Self { StyleParseErrorKind::ValueError(this) } } impl<'i> From<SelectorParseErrorKind<'i>> for StyleParseErrorKind<'i> { fn from(this: SelectorParseErrorKind<'i>) -> Self { StyleParseErrorKind::SelectorError(this) } } /// Specific errors that can be encountered while parsing property values. #[derive(Clone, Debug, PartialEq)] pub enum ValueParseErrorKind<'i> { /// An invalid token was encountered while parsing a color value. InvalidColor(Token<'i>), /// An invalid filter value was encountered. InvalidFilter(Token<'i>), } impl<'i> StyleParseErrorKind<'i> { /// Create an InvalidValue parse error pub fn new_invalid(name: CowRcStr<'i>, value_error: ParseError<'i>) -> ParseError<'i> { let variant = match value_error.kind { cssparser::ParseErrorKind::Custom(StyleParseErrorKind::ValueError(e)) => { match e { ValueParseErrorKind::InvalidColor(token) => { StyleParseErrorKind::InvalidColor(name, token) } ValueParseErrorKind::InvalidFilter(token) => { StyleParseErrorKind::InvalidFilter(name, token) } } } _ => StyleParseErrorKind::OtherInvalidValue(name), }; cssparser::ParseError { kind: cssparser::ParseErrorKind::Custom(variant), location: value_error.location, } } } bitflags! { /// The mode to use when parsing values. pub struct ParsingMode: u8 { /// In CSS; lengths must have units, except for zero values, where the unit can be omitted. /// <https://www.w3.org/TR/css3-values/#lengths> const DEFAULT = 0x00; /// In SVG; a coordinate or length value without a unit identifier (e.g., "25") is assumed /// to be in user units (px). /// <https://www.w3.org/TR/SVG/coords.html#Units> const ALLOW_UNITLESS_LENGTH = 0x01; /// In SVG; out-of-range values are not treated as an error in parsing. /// <https://www.w3.org/TR/SVG/implnote.html#RangeClamping> const ALLOW_ALL_NUMERIC_VALUES = 0x02; } } impl ParsingMode { /// Whether the parsing mode allows unitless lengths for non-zero values to be intpreted as px. #[inline] pub fn allows_unitless_lengths(&self) -> bool { self.intersects(ParsingMode::ALLOW_UNITLESS_LENGTH) } /// Whether the parsing mode allows all numeric values. #[inline] pub fn allows_all_numeric_values(&self) -> bool { self.intersects(ParsingMode::ALLOW_ALL_NUMERIC_VALUES) } } #[cfg(feature = "servo")] /// Speculatively execute paint code in the worklet thread pool. pub trait SpeculativePainter: Send + Sync { /// <https://drafts.css-houdini.org/css-paint-api/#draw-a-paint-image> fn speculatively_draw_a_paint_image(&self, properties: Vec<(Atom, String)>, arguments: Vec<String>); }
random_line_split
rustc.rs
//! Shim which is passed to Cargo as "rustc" when running the bootstrap. //! //! This shim will take care of some various tasks that our build process //! requires that Cargo can't quite do through normal configuration: //! //! 1. When compiling build scripts and build dependencies, we need a guaranteed //! full standard library available. The only compiler which actually has //! this is the snapshot, so we detect this situation and always compile with //! the snapshot compiler. //! 2. We pass a bunch of `--cfg` and other flags based on what we're compiling //! (and this slightly differs based on a whether we're using a snapshot or //! not), so we do that all here. //! //! This may one day be replaced by RUSTFLAGS, but the dynamic nature of //! switching compilers for the bootstrap and for build scripts will probably //! never get replaced. use std::env; use std::path::PathBuf; use std::process::{Child, Command}; use std::str::FromStr; use std::time::Instant; fn main() { let args = env::args_os().skip(1).collect::<Vec<_>>(); // Detect whether or not we're a build script depending on whether --target // is passed (a bit janky...) let target = args.windows(2).find(|w| &*w[0] == "--target").and_then(|w| w[1].to_str()); let version = args.iter().find(|w| &**w == "-vV"); let verbose = match env::var("RUSTC_VERBOSE") { Ok(s) => usize::from_str(&s).expect("RUSTC_VERBOSE should be an integer"), Err(_) => 0, }; // Use a different compiler for build scripts, since there may not yet be a // libstd for the real compiler to use. However, if Cargo is attempting to // determine the version of the compiler, the real compiler needs to be // used. Currently, these two states are differentiated based on whether // --target and -vV is/isn't passed. let (rustc, libdir) = if target.is_none() && version.is_none() { ("RUSTC_SNAPSHOT", "RUSTC_SNAPSHOT_LIBDIR") } else { ("RUSTC_REAL", "RUSTC_LIBDIR") }; let stage = env::var("RUSTC_STAGE").expect("RUSTC_STAGE was not set"); let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set"); let on_fail = env::var_os("RUSTC_ON_FAIL").map(Command::new); let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc)); let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir)); let mut dylib_path = bootstrap::util::dylib_path(); dylib_path.insert(0, PathBuf::from(&libdir)); let mut cmd = Command::new(rustc); cmd.args(&args).env(bootstrap::util::dylib_path_var(), env::join_paths(&dylib_path).unwrap()); // Get the name of the crate we're compiling, if any. let crate_name = args.windows(2).find(|args| args[0] == "--crate-name").and_then(|args| args[1].to_str()); if let Some(crate_name) = crate_name { if let Some(target) = env::var_os("RUSTC_TIME") { if target == "all" || target.into_string().unwrap().split(',').any(|c| c.trim() == crate_name) { cmd.arg("-Ztime"); } } } // Print backtrace in case of ICE if env::var("RUSTC_BACKTRACE_ON_ICE").is_ok() && env::var("RUST_BACKTRACE").is_err() { cmd.env("RUST_BACKTRACE", "1"); } if let Ok(lint_flags) = env::var("RUSTC_LINT_FLAGS") { cmd.args(lint_flags.split_whitespace()); } if target.is_some() { // The stage0 compiler has a special sysroot distinct from what we // actually downloaded, so we just always pass the `--sysroot` option, // unless one is already set. if!args.iter().any(|arg| arg == "--sysroot")
// If we're compiling specifically the `panic_abort` crate then we pass // the `-C panic=abort` option. Note that we do not do this for any // other crate intentionally as this is the only crate for now that we // ship with panic=abort. // // This... is a bit of a hack how we detect this. Ideally this // information should be encoded in the crate I guess? Would likely // require an RFC amendment to RFC 1513, however. // // `compiler_builtins` are unconditionally compiled with panic=abort to // workaround undefined references to `rust_eh_unwind_resume` generated // otherwise, see issue https://github.com/rust-lang/rust/issues/43095. if crate_name == Some("panic_abort") || crate_name == Some("compiler_builtins") && stage!= "0" { cmd.arg("-C").arg("panic=abort"); } } else { // FIXME(rust-lang/cargo#5754) we shouldn't be using special env vars // here, but rather Cargo should know what flags to pass rustc itself. // Override linker if necessary. if let Ok(host_linker) = env::var("RUSTC_HOST_LINKER") { cmd.arg(format!("-Clinker={}", host_linker)); } if env::var_os("RUSTC_HOST_FUSE_LD_LLD").is_some() { cmd.arg("-Clink-args=-fuse-ld=lld"); } if let Ok(s) = env::var("RUSTC_HOST_CRT_STATIC") { if s == "true" { cmd.arg("-C").arg("target-feature=+crt-static"); } if s == "false" { cmd.arg("-C").arg("target-feature=-crt-static"); } } if stage == "0" { // Cargo doesn't pass RUSTFLAGS to proc_macros: // https://github.com/rust-lang/cargo/issues/4423 // Set `--cfg=bootstrap` explicitly instead. cmd.arg("--cfg=bootstrap"); } } if let Ok(map) = env::var("RUSTC_DEBUGINFO_MAP") { cmd.arg("--remap-path-prefix").arg(&map); } // Force all crates compiled by this compiler to (a) be unstable and (b) // allow the `rustc_private` feature to link to other unstable crates // also in the sysroot. We also do this for host crates, since those // may be proc macros, in which case we might ship them. if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() && (stage!= "0" || target.is_some()) { cmd.arg("-Z").arg("force-unstable-if-unmarked"); } let is_test = args.iter().any(|a| a == "--test"); if verbose > 1 { let rust_env_vars = env::vars().filter(|(k, _)| k.starts_with("RUST") || k.starts_with("CARGO")); let prefix = if is_test { "[RUSTC-SHIM] rustc --test" } else { "[RUSTC-SHIM] rustc" }; let prefix = match crate_name { Some(crate_name) => format!("{} {}", prefix, crate_name), None => prefix.to_string(), }; for (i, (k, v)) in rust_env_vars.enumerate() { eprintln!("{} env[{}]: {:?}={:?}", prefix, i, k, v); } eprintln!("{} working directory: {}", prefix, env::current_dir().unwrap().display()); eprintln!( "{} command: {:?}={:?} {:?}", prefix, bootstrap::util::dylib_path_var(), env::join_paths(&dylib_path).unwrap(), cmd, ); eprintln!("{} sysroot: {:?}", prefix, sysroot); eprintln!("{} libdir: {:?}", prefix, libdir); } let start = Instant::now(); let (child, status) = { let errmsg = format!("\nFailed to run:\n{:?}\n-------------", cmd); let mut child = cmd.spawn().expect(&errmsg); let status = child.wait().expect(&errmsg); (child, status) }; if env::var_os("RUSTC_PRINT_STEP_TIMINGS").is_some() || env::var_os("RUSTC_PRINT_STEP_RUSAGE").is_some() { if let Some(crate_name) = crate_name { let dur = start.elapsed(); // If the user requested resource usage data, then // include that in addition to the timing output. let rusage_data = env::var_os("RUSTC_PRINT_STEP_RUSAGE").and_then(|_| format_rusage_data(child)); eprintln!( "[RUSTC-TIMING] {} test:{} {}.{:03}{}{}", crate_name, is_test, dur.as_secs(), dur.subsec_millis(), if rusage_data.is_some() { " " } else { "" }, rusage_data.unwrap_or(String::new()), ); } } if status.success() { std::process::exit(0); // note: everything below here is unreachable. do not put code that // should run on success, after this block. } if verbose > 0 { println!("\nDid not run successfully: {}\n{:?}\n-------------", status, cmd); } if let Some(mut on_fail) = on_fail { on_fail.status().expect("Could not run the on_fail command"); } // Preserve the exit code. In case of signal, exit with 0xfe since it's // awkward to preserve this status in a cross-platform way. match status.code() { Some(i) => std::process::exit(i), None => { eprintln!("rustc exited with {}", status); std::process::exit(0xfe); } } } #[cfg(all(not(unix), not(windows)))] // In the future we can add this for more platforms fn format_rusage_data(_child: Child) -> Option<String> { None } #[cfg(windows)] fn format_rusage_data(child: Child) -> Option<String> { use std::os::windows::io::AsRawHandle; use winapi::um::{processthreadsapi, psapi, timezoneapi}; let handle = child.as_raw_handle(); macro_rules! try_bool { ($e:expr) => { if $e!= 1 { return None; } }; } let mut user_filetime = Default::default(); let mut user_time = Default::default(); let mut kernel_filetime = Default::default(); let mut kernel_time = Default::default(); let mut memory_counters = psapi::PROCESS_MEMORY_COUNTERS::default(); unsafe { try_bool!(processthreadsapi::GetProcessTimes( handle, &mut Default::default(), &mut Default::default(), &mut kernel_filetime, &mut user_filetime, )); try_bool!(timezoneapi::FileTimeToSystemTime(&user_filetime, &mut user_time)); try_bool!(timezoneapi::FileTimeToSystemTime(&kernel_filetime, &mut kernel_time)); // Unlike on Linux with RUSAGE_CHILDREN, this will only return memory information for the process // with the given handle and none of that process's children. try_bool!(psapi::GetProcessMemoryInfo( handle as _, &mut memory_counters as *mut _ as _, std::mem::size_of::<psapi::PROCESS_MEMORY_COUNTERS_EX>() as u32, )); } // Guide on interpreting these numbers: // https://docs.microsoft.com/en-us/windows/win32/psapi/process-memory-usage-information let peak_working_set = memory_counters.PeakWorkingSetSize / 1024; let peak_page_file = memory_counters.PeakPagefileUsage / 1024; let peak_paged_pool = memory_counters.QuotaPeakPagedPoolUsage / 1024; let peak_nonpaged_pool = memory_counters.QuotaPeakNonPagedPoolUsage / 1024; Some(format!( "user: {USER_SEC}.{USER_USEC:03} \ sys: {SYS_SEC}.{SYS_USEC:03} \ peak working set (kb): {PEAK_WORKING_SET} \ peak page file usage (kb): {PEAK_PAGE_FILE} \ peak paged pool usage (kb): {PEAK_PAGED_POOL} \ peak non-paged pool usage (kb): {PEAK_NONPAGED_POOL} \ page faults: {PAGE_FAULTS}", USER_SEC = user_time.wSecond + (user_time.wMinute * 60), USER_USEC = user_time.wMilliseconds, SYS_SEC = kernel_time.wSecond + (kernel_time.wMinute * 60), SYS_USEC = kernel_time.wMilliseconds, PEAK_WORKING_SET = peak_working_set, PEAK_PAGE_FILE = peak_page_file, PEAK_PAGED_POOL = peak_paged_pool, PEAK_NONPAGED_POOL = peak_nonpaged_pool, PAGE_FAULTS = memory_counters.PageFaultCount, )) } #[cfg(unix)] /// Tries to build a string with human readable data for several of the rusage /// fields. Note that we are focusing mainly on data that we believe to be /// supplied on Linux (the `rusage` struct has other fields in it but they are /// currently unsupported by Linux). fn format_rusage_data(_child: Child) -> Option<String> { let rusage: libc::rusage = unsafe { let mut recv = std::mem::zeroed(); // -1 is RUSAGE_CHILDREN, which means to get the rusage for all children // (and grandchildren, etc) processes that have respectively terminated // and been waited for. let retval = libc::getrusage(-1, &mut recv); if retval!= 0 { return None; } recv }; // Mac OS X reports the maxrss in bytes, not kb. let divisor = if env::consts::OS == "macos" { 1024 } else { 1 }; let maxrss = (rusage.ru_maxrss + (divisor - 1)) / divisor; let mut init_str = format!( "user: {USER_SEC}.{USER_USEC:03} \ sys: {SYS_SEC}.{SYS_USEC:03} \ max rss (kb): {MAXRSS}", USER_SEC = rusage.ru_utime.tv_sec, USER_USEC = rusage.ru_utime.tv_usec, SYS_SEC = rusage.ru_stime.tv_sec, SYS_USEC = rusage.ru_stime.tv_usec, MAXRSS = maxrss ); // The remaining rusage stats vary in platform support. So we treat // uniformly zero values in each category as "not worth printing", since it // either means no events of that type occurred, or that the platform // does not support it. let minflt = rusage.ru_minflt; let majflt = rusage.ru_majflt; if minflt!= 0 || majflt!= 0 { init_str.push_str(&format!(" page reclaims: {} page faults: {}", minflt, majflt)); } let inblock = rusage.ru_inblock; let oublock = rusage.ru_oublock; if inblock!= 0 || oublock!= 0 { init_str.push_str(&format!(" fs block inputs: {} fs block outputs: {}", inblock, oublock)); } let nvcsw = rusage.ru_nvcsw; let nivcsw = rusage.ru_nivcsw; if nvcsw!= 0 || nivcsw!= 0 { init_str.push_str(&format!( " voluntary ctxt switches: {} involuntary ctxt switches: {}", nvcsw, nivcsw )); } return Some(init_str); }
{ cmd.arg("--sysroot").arg(&sysroot); }
conditional_block
rustc.rs
//! Shim which is passed to Cargo as "rustc" when running the bootstrap. //! //! This shim will take care of some various tasks that our build process //! requires that Cargo can't quite do through normal configuration: //! //! 1. When compiling build scripts and build dependencies, we need a guaranteed //! full standard library available. The only compiler which actually has //! this is the snapshot, so we detect this situation and always compile with //! the snapshot compiler. //! 2. We pass a bunch of `--cfg` and other flags based on what we're compiling //! (and this slightly differs based on a whether we're using a snapshot or //! not), so we do that all here. //! //! This may one day be replaced by RUSTFLAGS, but the dynamic nature of //! switching compilers for the bootstrap and for build scripts will probably //! never get replaced. use std::env; use std::path::PathBuf; use std::process::{Child, Command}; use std::str::FromStr; use std::time::Instant; fn main() { let args = env::args_os().skip(1).collect::<Vec<_>>(); // Detect whether or not we're a build script depending on whether --target // is passed (a bit janky...) let target = args.windows(2).find(|w| &*w[0] == "--target").and_then(|w| w[1].to_str()); let version = args.iter().find(|w| &**w == "-vV"); let verbose = match env::var("RUSTC_VERBOSE") { Ok(s) => usize::from_str(&s).expect("RUSTC_VERBOSE should be an integer"), Err(_) => 0, }; // Use a different compiler for build scripts, since there may not yet be a // libstd for the real compiler to use. However, if Cargo is attempting to // determine the version of the compiler, the real compiler needs to be // used. Currently, these two states are differentiated based on whether // --target and -vV is/isn't passed. let (rustc, libdir) = if target.is_none() && version.is_none() { ("RUSTC_SNAPSHOT", "RUSTC_SNAPSHOT_LIBDIR") } else { ("RUSTC_REAL", "RUSTC_LIBDIR") }; let stage = env::var("RUSTC_STAGE").expect("RUSTC_STAGE was not set"); let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set"); let on_fail = env::var_os("RUSTC_ON_FAIL").map(Command::new); let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc)); let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir)); let mut dylib_path = bootstrap::util::dylib_path(); dylib_path.insert(0, PathBuf::from(&libdir)); let mut cmd = Command::new(rustc); cmd.args(&args).env(bootstrap::util::dylib_path_var(), env::join_paths(&dylib_path).unwrap()); // Get the name of the crate we're compiling, if any. let crate_name = args.windows(2).find(|args| args[0] == "--crate-name").and_then(|args| args[1].to_str()); if let Some(crate_name) = crate_name { if let Some(target) = env::var_os("RUSTC_TIME") { if target == "all" || target.into_string().unwrap().split(',').any(|c| c.trim() == crate_name) { cmd.arg("-Ztime"); } } } // Print backtrace in case of ICE if env::var("RUSTC_BACKTRACE_ON_ICE").is_ok() && env::var("RUST_BACKTRACE").is_err() { cmd.env("RUST_BACKTRACE", "1"); } if let Ok(lint_flags) = env::var("RUSTC_LINT_FLAGS") { cmd.args(lint_flags.split_whitespace()); } if target.is_some() { // The stage0 compiler has a special sysroot distinct from what we // actually downloaded, so we just always pass the `--sysroot` option, // unless one is already set. if!args.iter().any(|arg| arg == "--sysroot") { cmd.arg("--sysroot").arg(&sysroot); } // If we're compiling specifically the `panic_abort` crate then we pass // the `-C panic=abort` option. Note that we do not do this for any // other crate intentionally as this is the only crate for now that we // ship with panic=abort. // // This... is a bit of a hack how we detect this. Ideally this // information should be encoded in the crate I guess? Would likely // require an RFC amendment to RFC 1513, however. // // `compiler_builtins` are unconditionally compiled with panic=abort to // workaround undefined references to `rust_eh_unwind_resume` generated // otherwise, see issue https://github.com/rust-lang/rust/issues/43095. if crate_name == Some("panic_abort") || crate_name == Some("compiler_builtins") && stage!= "0" { cmd.arg("-C").arg("panic=abort"); } } else { // FIXME(rust-lang/cargo#5754) we shouldn't be using special env vars // here, but rather Cargo should know what flags to pass rustc itself. // Override linker if necessary. if let Ok(host_linker) = env::var("RUSTC_HOST_LINKER") { cmd.arg(format!("-Clinker={}", host_linker)); } if env::var_os("RUSTC_HOST_FUSE_LD_LLD").is_some() { cmd.arg("-Clink-args=-fuse-ld=lld"); } if let Ok(s) = env::var("RUSTC_HOST_CRT_STATIC") { if s == "true" { cmd.arg("-C").arg("target-feature=+crt-static"); } if s == "false" { cmd.arg("-C").arg("target-feature=-crt-static"); } } if stage == "0" { // Cargo doesn't pass RUSTFLAGS to proc_macros: // https://github.com/rust-lang/cargo/issues/4423 // Set `--cfg=bootstrap` explicitly instead. cmd.arg("--cfg=bootstrap"); } } if let Ok(map) = env::var("RUSTC_DEBUGINFO_MAP") { cmd.arg("--remap-path-prefix").arg(&map); } // Force all crates compiled by this compiler to (a) be unstable and (b) // allow the `rustc_private` feature to link to other unstable crates // also in the sysroot. We also do this for host crates, since those // may be proc macros, in which case we might ship them. if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() && (stage!= "0" || target.is_some()) { cmd.arg("-Z").arg("force-unstable-if-unmarked"); } let is_test = args.iter().any(|a| a == "--test"); if verbose > 1 { let rust_env_vars = env::vars().filter(|(k, _)| k.starts_with("RUST") || k.starts_with("CARGO")); let prefix = if is_test { "[RUSTC-SHIM] rustc --test" } else { "[RUSTC-SHIM] rustc" }; let prefix = match crate_name { Some(crate_name) => format!("{} {}", prefix, crate_name), None => prefix.to_string(), }; for (i, (k, v)) in rust_env_vars.enumerate() { eprintln!("{} env[{}]: {:?}={:?}", prefix, i, k, v); } eprintln!("{} working directory: {}", prefix, env::current_dir().unwrap().display()); eprintln!( "{} command: {:?}={:?} {:?}", prefix, bootstrap::util::dylib_path_var(), env::join_paths(&dylib_path).unwrap(), cmd, ); eprintln!("{} sysroot: {:?}", prefix, sysroot); eprintln!("{} libdir: {:?}", prefix, libdir); } let start = Instant::now(); let (child, status) = { let errmsg = format!("\nFailed to run:\n{:?}\n-------------", cmd); let mut child = cmd.spawn().expect(&errmsg); let status = child.wait().expect(&errmsg); (child, status) }; if env::var_os("RUSTC_PRINT_STEP_TIMINGS").is_some() || env::var_os("RUSTC_PRINT_STEP_RUSAGE").is_some() { if let Some(crate_name) = crate_name { let dur = start.elapsed(); // If the user requested resource usage data, then // include that in addition to the timing output. let rusage_data = env::var_os("RUSTC_PRINT_STEP_RUSAGE").and_then(|_| format_rusage_data(child)); eprintln!( "[RUSTC-TIMING] {} test:{} {}.{:03}{}{}", crate_name, is_test, dur.as_secs(), dur.subsec_millis(), if rusage_data.is_some() { " " } else { "" }, rusage_data.unwrap_or(String::new()), ); } } if status.success() { std::process::exit(0); // note: everything below here is unreachable. do not put code that // should run on success, after this block. } if verbose > 0 { println!("\nDid not run successfully: {}\n{:?}\n-------------", status, cmd); } if let Some(mut on_fail) = on_fail { on_fail.status().expect("Could not run the on_fail command"); } // Preserve the exit code. In case of signal, exit with 0xfe since it's // awkward to preserve this status in a cross-platform way. match status.code() { Some(i) => std::process::exit(i), None => { eprintln!("rustc exited with {}", status); std::process::exit(0xfe); } } } #[cfg(all(not(unix), not(windows)))] // In the future we can add this for more platforms fn format_rusage_data(_child: Child) -> Option<String> { None } #[cfg(windows)] fn format_rusage_data(child: Child) -> Option<String> { use std::os::windows::io::AsRawHandle; use winapi::um::{processthreadsapi, psapi, timezoneapi}; let handle = child.as_raw_handle(); macro_rules! try_bool { ($e:expr) => { if $e!= 1 { return None; } }; } let mut user_filetime = Default::default(); let mut user_time = Default::default(); let mut kernel_filetime = Default::default(); let mut kernel_time = Default::default(); let mut memory_counters = psapi::PROCESS_MEMORY_COUNTERS::default(); unsafe { try_bool!(processthreadsapi::GetProcessTimes( handle, &mut Default::default(), &mut Default::default(), &mut kernel_filetime, &mut user_filetime, )); try_bool!(timezoneapi::FileTimeToSystemTime(&user_filetime, &mut user_time)); try_bool!(timezoneapi::FileTimeToSystemTime(&kernel_filetime, &mut kernel_time)); // Unlike on Linux with RUSAGE_CHILDREN, this will only return memory information for the process // with the given handle and none of that process's children. try_bool!(psapi::GetProcessMemoryInfo( handle as _, &mut memory_counters as *mut _ as _, std::mem::size_of::<psapi::PROCESS_MEMORY_COUNTERS_EX>() as u32, )); } // Guide on interpreting these numbers: // https://docs.microsoft.com/en-us/windows/win32/psapi/process-memory-usage-information let peak_working_set = memory_counters.PeakWorkingSetSize / 1024; let peak_page_file = memory_counters.PeakPagefileUsage / 1024; let peak_paged_pool = memory_counters.QuotaPeakPagedPoolUsage / 1024; let peak_nonpaged_pool = memory_counters.QuotaPeakNonPagedPoolUsage / 1024; Some(format!( "user: {USER_SEC}.{USER_USEC:03} \ sys: {SYS_SEC}.{SYS_USEC:03} \ peak working set (kb): {PEAK_WORKING_SET} \ peak page file usage (kb): {PEAK_PAGE_FILE} \ peak paged pool usage (kb): {PEAK_PAGED_POOL} \ peak non-paged pool usage (kb): {PEAK_NONPAGED_POOL} \ page faults: {PAGE_FAULTS}", USER_SEC = user_time.wSecond + (user_time.wMinute * 60), USER_USEC = user_time.wMilliseconds, SYS_SEC = kernel_time.wSecond + (kernel_time.wMinute * 60), SYS_USEC = kernel_time.wMilliseconds, PEAK_WORKING_SET = peak_working_set, PEAK_PAGE_FILE = peak_page_file, PEAK_PAGED_POOL = peak_paged_pool, PEAK_NONPAGED_POOL = peak_nonpaged_pool, PAGE_FAULTS = memory_counters.PageFaultCount, )) } #[cfg(unix)] /// Tries to build a string with human readable data for several of the rusage /// fields. Note that we are focusing mainly on data that we believe to be /// supplied on Linux (the `rusage` struct has other fields in it but they are /// currently unsupported by Linux). fn format_rusage_data(_child: Child) -> Option<String>
USER_SEC = rusage.ru_utime.tv_sec, USER_USEC = rusage.ru_utime.tv_usec, SYS_SEC = rusage.ru_stime.tv_sec, SYS_USEC = rusage.ru_stime.tv_usec, MAXRSS = maxrss ); // The remaining rusage stats vary in platform support. So we treat // uniformly zero values in each category as "not worth printing", since it // either means no events of that type occurred, or that the platform // does not support it. let minflt = rusage.ru_minflt; let majflt = rusage.ru_majflt; if minflt!= 0 || majflt!= 0 { init_str.push_str(&format!(" page reclaims: {} page faults: {}", minflt, majflt)); } let inblock = rusage.ru_inblock; let oublock = rusage.ru_oublock; if inblock!= 0 || oublock!= 0 { init_str.push_str(&format!(" fs block inputs: {} fs block outputs: {}", inblock, oublock)); } let nvcsw = rusage.ru_nvcsw; let nivcsw = rusage.ru_nivcsw; if nvcsw!= 0 || nivcsw!= 0 { init_str.push_str(&format!( " voluntary ctxt switches: {} involuntary ctxt switches: {}", nvcsw, nivcsw )); } return Some(init_str); }
{ let rusage: libc::rusage = unsafe { let mut recv = std::mem::zeroed(); // -1 is RUSAGE_CHILDREN, which means to get the rusage for all children // (and grandchildren, etc) processes that have respectively terminated // and been waited for. let retval = libc::getrusage(-1, &mut recv); if retval != 0 { return None; } recv }; // Mac OS X reports the maxrss in bytes, not kb. let divisor = if env::consts::OS == "macos" { 1024 } else { 1 }; let maxrss = (rusage.ru_maxrss + (divisor - 1)) / divisor; let mut init_str = format!( "user: {USER_SEC}.{USER_USEC:03} \ sys: {SYS_SEC}.{SYS_USEC:03} \ max rss (kb): {MAXRSS}",
identifier_body
rustc.rs
//! Shim which is passed to Cargo as "rustc" when running the bootstrap. //! //! This shim will take care of some various tasks that our build process //! requires that Cargo can't quite do through normal configuration: //! //! 1. When compiling build scripts and build dependencies, we need a guaranteed //! full standard library available. The only compiler which actually has //! this is the snapshot, so we detect this situation and always compile with //! the snapshot compiler. //! 2. We pass a bunch of `--cfg` and other flags based on what we're compiling //! (and this slightly differs based on a whether we're using a snapshot or //! not), so we do that all here. //! //! This may one day be replaced by RUSTFLAGS, but the dynamic nature of //! switching compilers for the bootstrap and for build scripts will probably //! never get replaced. use std::env; use std::path::PathBuf; use std::process::{Child, Command}; use std::str::FromStr; use std::time::Instant; fn main() { let args = env::args_os().skip(1).collect::<Vec<_>>(); // Detect whether or not we're a build script depending on whether --target // is passed (a bit janky...) let target = args.windows(2).find(|w| &*w[0] == "--target").and_then(|w| w[1].to_str()); let version = args.iter().find(|w| &**w == "-vV"); let verbose = match env::var("RUSTC_VERBOSE") { Ok(s) => usize::from_str(&s).expect("RUSTC_VERBOSE should be an integer"), Err(_) => 0, }; // Use a different compiler for build scripts, since there may not yet be a // libstd for the real compiler to use. However, if Cargo is attempting to // determine the version of the compiler, the real compiler needs to be // used. Currently, these two states are differentiated based on whether // --target and -vV is/isn't passed. let (rustc, libdir) = if target.is_none() && version.is_none() { ("RUSTC_SNAPSHOT", "RUSTC_SNAPSHOT_LIBDIR") } else { ("RUSTC_REAL", "RUSTC_LIBDIR") }; let stage = env::var("RUSTC_STAGE").expect("RUSTC_STAGE was not set"); let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set"); let on_fail = env::var_os("RUSTC_ON_FAIL").map(Command::new); let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc)); let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir)); let mut dylib_path = bootstrap::util::dylib_path(); dylib_path.insert(0, PathBuf::from(&libdir)); let mut cmd = Command::new(rustc); cmd.args(&args).env(bootstrap::util::dylib_path_var(), env::join_paths(&dylib_path).unwrap()); // Get the name of the crate we're compiling, if any. let crate_name = args.windows(2).find(|args| args[0] == "--crate-name").and_then(|args| args[1].to_str()); if let Some(crate_name) = crate_name { if let Some(target) = env::var_os("RUSTC_TIME") { if target == "all" || target.into_string().unwrap().split(',').any(|c| c.trim() == crate_name) { cmd.arg("-Ztime"); } } } // Print backtrace in case of ICE if env::var("RUSTC_BACKTRACE_ON_ICE").is_ok() && env::var("RUST_BACKTRACE").is_err() { cmd.env("RUST_BACKTRACE", "1"); } if let Ok(lint_flags) = env::var("RUSTC_LINT_FLAGS") { cmd.args(lint_flags.split_whitespace()); } if target.is_some() { // The stage0 compiler has a special sysroot distinct from what we // actually downloaded, so we just always pass the `--sysroot` option, // unless one is already set. if!args.iter().any(|arg| arg == "--sysroot") { cmd.arg("--sysroot").arg(&sysroot); } // If we're compiling specifically the `panic_abort` crate then we pass // the `-C panic=abort` option. Note that we do not do this for any // other crate intentionally as this is the only crate for now that we // ship with panic=abort. // // This... is a bit of a hack how we detect this. Ideally this // information should be encoded in the crate I guess? Would likely // require an RFC amendment to RFC 1513, however. // // `compiler_builtins` are unconditionally compiled with panic=abort to // workaround undefined references to `rust_eh_unwind_resume` generated // otherwise, see issue https://github.com/rust-lang/rust/issues/43095. if crate_name == Some("panic_abort") || crate_name == Some("compiler_builtins") && stage!= "0" { cmd.arg("-C").arg("panic=abort"); } } else { // FIXME(rust-lang/cargo#5754) we shouldn't be using special env vars // here, but rather Cargo should know what flags to pass rustc itself. // Override linker if necessary. if let Ok(host_linker) = env::var("RUSTC_HOST_LINKER") { cmd.arg(format!("-Clinker={}", host_linker)); } if env::var_os("RUSTC_HOST_FUSE_LD_LLD").is_some() { cmd.arg("-Clink-args=-fuse-ld=lld"); } if let Ok(s) = env::var("RUSTC_HOST_CRT_STATIC") { if s == "true" { cmd.arg("-C").arg("target-feature=+crt-static"); } if s == "false" { cmd.arg("-C").arg("target-feature=-crt-static"); } } if stage == "0" { // Cargo doesn't pass RUSTFLAGS to proc_macros: // https://github.com/rust-lang/cargo/issues/4423 // Set `--cfg=bootstrap` explicitly instead. cmd.arg("--cfg=bootstrap"); } } if let Ok(map) = env::var("RUSTC_DEBUGINFO_MAP") { cmd.arg("--remap-path-prefix").arg(&map); } // Force all crates compiled by this compiler to (a) be unstable and (b) // allow the `rustc_private` feature to link to other unstable crates // also in the sysroot. We also do this for host crates, since those // may be proc macros, in which case we might ship them. if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() && (stage!= "0" || target.is_some()) { cmd.arg("-Z").arg("force-unstable-if-unmarked"); } let is_test = args.iter().any(|a| a == "--test"); if verbose > 1 { let rust_env_vars = env::vars().filter(|(k, _)| k.starts_with("RUST") || k.starts_with("CARGO")); let prefix = if is_test { "[RUSTC-SHIM] rustc --test" } else { "[RUSTC-SHIM] rustc" }; let prefix = match crate_name { Some(crate_name) => format!("{} {}", prefix, crate_name), None => prefix.to_string(), }; for (i, (k, v)) in rust_env_vars.enumerate() { eprintln!("{} env[{}]: {:?}={:?}", prefix, i, k, v); } eprintln!("{} working directory: {}", prefix, env::current_dir().unwrap().display()); eprintln!( "{} command: {:?}={:?} {:?}", prefix, bootstrap::util::dylib_path_var(), env::join_paths(&dylib_path).unwrap(), cmd, ); eprintln!("{} sysroot: {:?}", prefix, sysroot); eprintln!("{} libdir: {:?}", prefix, libdir); } let start = Instant::now(); let (child, status) = { let errmsg = format!("\nFailed to run:\n{:?}\n-------------", cmd); let mut child = cmd.spawn().expect(&errmsg); let status = child.wait().expect(&errmsg); (child, status) }; if env::var_os("RUSTC_PRINT_STEP_TIMINGS").is_some() || env::var_os("RUSTC_PRINT_STEP_RUSAGE").is_some() { if let Some(crate_name) = crate_name { let dur = start.elapsed(); // If the user requested resource usage data, then // include that in addition to the timing output. let rusage_data = env::var_os("RUSTC_PRINT_STEP_RUSAGE").and_then(|_| format_rusage_data(child)); eprintln!( "[RUSTC-TIMING] {} test:{} {}.{:03}{}{}", crate_name, is_test, dur.as_secs(), dur.subsec_millis(), if rusage_data.is_some() { " " } else { "" }, rusage_data.unwrap_or(String::new()), ); } } if status.success() { std::process::exit(0); // note: everything below here is unreachable. do not put code that // should run on success, after this block. } if verbose > 0 { println!("\nDid not run successfully: {}\n{:?}\n-------------", status, cmd); } if let Some(mut on_fail) = on_fail { on_fail.status().expect("Could not run the on_fail command"); } // Preserve the exit code. In case of signal, exit with 0xfe since it's // awkward to preserve this status in a cross-platform way. match status.code() { Some(i) => std::process::exit(i), None => { eprintln!("rustc exited with {}", status); std::process::exit(0xfe); } } } #[cfg(all(not(unix), not(windows)))] // In the future we can add this for more platforms fn format_rusage_data(_child: Child) -> Option<String> { None } #[cfg(windows)] fn
(child: Child) -> Option<String> { use std::os::windows::io::AsRawHandle; use winapi::um::{processthreadsapi, psapi, timezoneapi}; let handle = child.as_raw_handle(); macro_rules! try_bool { ($e:expr) => { if $e!= 1 { return None; } }; } let mut user_filetime = Default::default(); let mut user_time = Default::default(); let mut kernel_filetime = Default::default(); let mut kernel_time = Default::default(); let mut memory_counters = psapi::PROCESS_MEMORY_COUNTERS::default(); unsafe { try_bool!(processthreadsapi::GetProcessTimes( handle, &mut Default::default(), &mut Default::default(), &mut kernel_filetime, &mut user_filetime, )); try_bool!(timezoneapi::FileTimeToSystemTime(&user_filetime, &mut user_time)); try_bool!(timezoneapi::FileTimeToSystemTime(&kernel_filetime, &mut kernel_time)); // Unlike on Linux with RUSAGE_CHILDREN, this will only return memory information for the process // with the given handle and none of that process's children. try_bool!(psapi::GetProcessMemoryInfo( handle as _, &mut memory_counters as *mut _ as _, std::mem::size_of::<psapi::PROCESS_MEMORY_COUNTERS_EX>() as u32, )); } // Guide on interpreting these numbers: // https://docs.microsoft.com/en-us/windows/win32/psapi/process-memory-usage-information let peak_working_set = memory_counters.PeakWorkingSetSize / 1024; let peak_page_file = memory_counters.PeakPagefileUsage / 1024; let peak_paged_pool = memory_counters.QuotaPeakPagedPoolUsage / 1024; let peak_nonpaged_pool = memory_counters.QuotaPeakNonPagedPoolUsage / 1024; Some(format!( "user: {USER_SEC}.{USER_USEC:03} \ sys: {SYS_SEC}.{SYS_USEC:03} \ peak working set (kb): {PEAK_WORKING_SET} \ peak page file usage (kb): {PEAK_PAGE_FILE} \ peak paged pool usage (kb): {PEAK_PAGED_POOL} \ peak non-paged pool usage (kb): {PEAK_NONPAGED_POOL} \ page faults: {PAGE_FAULTS}", USER_SEC = user_time.wSecond + (user_time.wMinute * 60), USER_USEC = user_time.wMilliseconds, SYS_SEC = kernel_time.wSecond + (kernel_time.wMinute * 60), SYS_USEC = kernel_time.wMilliseconds, PEAK_WORKING_SET = peak_working_set, PEAK_PAGE_FILE = peak_page_file, PEAK_PAGED_POOL = peak_paged_pool, PEAK_NONPAGED_POOL = peak_nonpaged_pool, PAGE_FAULTS = memory_counters.PageFaultCount, )) } #[cfg(unix)] /// Tries to build a string with human readable data for several of the rusage /// fields. Note that we are focusing mainly on data that we believe to be /// supplied on Linux (the `rusage` struct has other fields in it but they are /// currently unsupported by Linux). fn format_rusage_data(_child: Child) -> Option<String> { let rusage: libc::rusage = unsafe { let mut recv = std::mem::zeroed(); // -1 is RUSAGE_CHILDREN, which means to get the rusage for all children // (and grandchildren, etc) processes that have respectively terminated // and been waited for. let retval = libc::getrusage(-1, &mut recv); if retval!= 0 { return None; } recv }; // Mac OS X reports the maxrss in bytes, not kb. let divisor = if env::consts::OS == "macos" { 1024 } else { 1 }; let maxrss = (rusage.ru_maxrss + (divisor - 1)) / divisor; let mut init_str = format!( "user: {USER_SEC}.{USER_USEC:03} \ sys: {SYS_SEC}.{SYS_USEC:03} \ max rss (kb): {MAXRSS}", USER_SEC = rusage.ru_utime.tv_sec, USER_USEC = rusage.ru_utime.tv_usec, SYS_SEC = rusage.ru_stime.tv_sec, SYS_USEC = rusage.ru_stime.tv_usec, MAXRSS = maxrss ); // The remaining rusage stats vary in platform support. So we treat // uniformly zero values in each category as "not worth printing", since it // either means no events of that type occurred, or that the platform // does not support it. let minflt = rusage.ru_minflt; let majflt = rusage.ru_majflt; if minflt!= 0 || majflt!= 0 { init_str.push_str(&format!(" page reclaims: {} page faults: {}", minflt, majflt)); } let inblock = rusage.ru_inblock; let oublock = rusage.ru_oublock; if inblock!= 0 || oublock!= 0 { init_str.push_str(&format!(" fs block inputs: {} fs block outputs: {}", inblock, oublock)); } let nvcsw = rusage.ru_nvcsw; let nivcsw = rusage.ru_nivcsw; if nvcsw!= 0 || nivcsw!= 0 { init_str.push_str(&format!( " voluntary ctxt switches: {} involuntary ctxt switches: {}", nvcsw, nivcsw )); } return Some(init_str); }
format_rusage_data
identifier_name
rustc.rs
//! Shim which is passed to Cargo as "rustc" when running the bootstrap. //! //! This shim will take care of some various tasks that our build process //! requires that Cargo can't quite do through normal configuration: //! //! 1. When compiling build scripts and build dependencies, we need a guaranteed //! full standard library available. The only compiler which actually has //! this is the snapshot, so we detect this situation and always compile with //! the snapshot compiler. //! 2. We pass a bunch of `--cfg` and other flags based on what we're compiling //! (and this slightly differs based on a whether we're using a snapshot or //! not), so we do that all here. //! //! This may one day be replaced by RUSTFLAGS, but the dynamic nature of //! switching compilers for the bootstrap and for build scripts will probably //! never get replaced. use std::env; use std::path::PathBuf; use std::process::{Child, Command}; use std::str::FromStr; use std::time::Instant; fn main() { let args = env::args_os().skip(1).collect::<Vec<_>>(); // Detect whether or not we're a build script depending on whether --target // is passed (a bit janky...) let target = args.windows(2).find(|w| &*w[0] == "--target").and_then(|w| w[1].to_str()); let version = args.iter().find(|w| &**w == "-vV"); let verbose = match env::var("RUSTC_VERBOSE") { Ok(s) => usize::from_str(&s).expect("RUSTC_VERBOSE should be an integer"), Err(_) => 0, }; // Use a different compiler for build scripts, since there may not yet be a // libstd for the real compiler to use. However, if Cargo is attempting to // determine the version of the compiler, the real compiler needs to be // used. Currently, these two states are differentiated based on whether // --target and -vV is/isn't passed. let (rustc, libdir) = if target.is_none() && version.is_none() { ("RUSTC_SNAPSHOT", "RUSTC_SNAPSHOT_LIBDIR") } else { ("RUSTC_REAL", "RUSTC_LIBDIR") }; let stage = env::var("RUSTC_STAGE").expect("RUSTC_STAGE was not set");
let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc)); let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir)); let mut dylib_path = bootstrap::util::dylib_path(); dylib_path.insert(0, PathBuf::from(&libdir)); let mut cmd = Command::new(rustc); cmd.args(&args).env(bootstrap::util::dylib_path_var(), env::join_paths(&dylib_path).unwrap()); // Get the name of the crate we're compiling, if any. let crate_name = args.windows(2).find(|args| args[0] == "--crate-name").and_then(|args| args[1].to_str()); if let Some(crate_name) = crate_name { if let Some(target) = env::var_os("RUSTC_TIME") { if target == "all" || target.into_string().unwrap().split(',').any(|c| c.trim() == crate_name) { cmd.arg("-Ztime"); } } } // Print backtrace in case of ICE if env::var("RUSTC_BACKTRACE_ON_ICE").is_ok() && env::var("RUST_BACKTRACE").is_err() { cmd.env("RUST_BACKTRACE", "1"); } if let Ok(lint_flags) = env::var("RUSTC_LINT_FLAGS") { cmd.args(lint_flags.split_whitespace()); } if target.is_some() { // The stage0 compiler has a special sysroot distinct from what we // actually downloaded, so we just always pass the `--sysroot` option, // unless one is already set. if!args.iter().any(|arg| arg == "--sysroot") { cmd.arg("--sysroot").arg(&sysroot); } // If we're compiling specifically the `panic_abort` crate then we pass // the `-C panic=abort` option. Note that we do not do this for any // other crate intentionally as this is the only crate for now that we // ship with panic=abort. // // This... is a bit of a hack how we detect this. Ideally this // information should be encoded in the crate I guess? Would likely // require an RFC amendment to RFC 1513, however. // // `compiler_builtins` are unconditionally compiled with panic=abort to // workaround undefined references to `rust_eh_unwind_resume` generated // otherwise, see issue https://github.com/rust-lang/rust/issues/43095. if crate_name == Some("panic_abort") || crate_name == Some("compiler_builtins") && stage!= "0" { cmd.arg("-C").arg("panic=abort"); } } else { // FIXME(rust-lang/cargo#5754) we shouldn't be using special env vars // here, but rather Cargo should know what flags to pass rustc itself. // Override linker if necessary. if let Ok(host_linker) = env::var("RUSTC_HOST_LINKER") { cmd.arg(format!("-Clinker={}", host_linker)); } if env::var_os("RUSTC_HOST_FUSE_LD_LLD").is_some() { cmd.arg("-Clink-args=-fuse-ld=lld"); } if let Ok(s) = env::var("RUSTC_HOST_CRT_STATIC") { if s == "true" { cmd.arg("-C").arg("target-feature=+crt-static"); } if s == "false" { cmd.arg("-C").arg("target-feature=-crt-static"); } } if stage == "0" { // Cargo doesn't pass RUSTFLAGS to proc_macros: // https://github.com/rust-lang/cargo/issues/4423 // Set `--cfg=bootstrap` explicitly instead. cmd.arg("--cfg=bootstrap"); } } if let Ok(map) = env::var("RUSTC_DEBUGINFO_MAP") { cmd.arg("--remap-path-prefix").arg(&map); } // Force all crates compiled by this compiler to (a) be unstable and (b) // allow the `rustc_private` feature to link to other unstable crates // also in the sysroot. We also do this for host crates, since those // may be proc macros, in which case we might ship them. if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() && (stage!= "0" || target.is_some()) { cmd.arg("-Z").arg("force-unstable-if-unmarked"); } let is_test = args.iter().any(|a| a == "--test"); if verbose > 1 { let rust_env_vars = env::vars().filter(|(k, _)| k.starts_with("RUST") || k.starts_with("CARGO")); let prefix = if is_test { "[RUSTC-SHIM] rustc --test" } else { "[RUSTC-SHIM] rustc" }; let prefix = match crate_name { Some(crate_name) => format!("{} {}", prefix, crate_name), None => prefix.to_string(), }; for (i, (k, v)) in rust_env_vars.enumerate() { eprintln!("{} env[{}]: {:?}={:?}", prefix, i, k, v); } eprintln!("{} working directory: {}", prefix, env::current_dir().unwrap().display()); eprintln!( "{} command: {:?}={:?} {:?}", prefix, bootstrap::util::dylib_path_var(), env::join_paths(&dylib_path).unwrap(), cmd, ); eprintln!("{} sysroot: {:?}", prefix, sysroot); eprintln!("{} libdir: {:?}", prefix, libdir); } let start = Instant::now(); let (child, status) = { let errmsg = format!("\nFailed to run:\n{:?}\n-------------", cmd); let mut child = cmd.spawn().expect(&errmsg); let status = child.wait().expect(&errmsg); (child, status) }; if env::var_os("RUSTC_PRINT_STEP_TIMINGS").is_some() || env::var_os("RUSTC_PRINT_STEP_RUSAGE").is_some() { if let Some(crate_name) = crate_name { let dur = start.elapsed(); // If the user requested resource usage data, then // include that in addition to the timing output. let rusage_data = env::var_os("RUSTC_PRINT_STEP_RUSAGE").and_then(|_| format_rusage_data(child)); eprintln!( "[RUSTC-TIMING] {} test:{} {}.{:03}{}{}", crate_name, is_test, dur.as_secs(), dur.subsec_millis(), if rusage_data.is_some() { " " } else { "" }, rusage_data.unwrap_or(String::new()), ); } } if status.success() { std::process::exit(0); // note: everything below here is unreachable. do not put code that // should run on success, after this block. } if verbose > 0 { println!("\nDid not run successfully: {}\n{:?}\n-------------", status, cmd); } if let Some(mut on_fail) = on_fail { on_fail.status().expect("Could not run the on_fail command"); } // Preserve the exit code. In case of signal, exit with 0xfe since it's // awkward to preserve this status in a cross-platform way. match status.code() { Some(i) => std::process::exit(i), None => { eprintln!("rustc exited with {}", status); std::process::exit(0xfe); } } } #[cfg(all(not(unix), not(windows)))] // In the future we can add this for more platforms fn format_rusage_data(_child: Child) -> Option<String> { None } #[cfg(windows)] fn format_rusage_data(child: Child) -> Option<String> { use std::os::windows::io::AsRawHandle; use winapi::um::{processthreadsapi, psapi, timezoneapi}; let handle = child.as_raw_handle(); macro_rules! try_bool { ($e:expr) => { if $e!= 1 { return None; } }; } let mut user_filetime = Default::default(); let mut user_time = Default::default(); let mut kernel_filetime = Default::default(); let mut kernel_time = Default::default(); let mut memory_counters = psapi::PROCESS_MEMORY_COUNTERS::default(); unsafe { try_bool!(processthreadsapi::GetProcessTimes( handle, &mut Default::default(), &mut Default::default(), &mut kernel_filetime, &mut user_filetime, )); try_bool!(timezoneapi::FileTimeToSystemTime(&user_filetime, &mut user_time)); try_bool!(timezoneapi::FileTimeToSystemTime(&kernel_filetime, &mut kernel_time)); // Unlike on Linux with RUSAGE_CHILDREN, this will only return memory information for the process // with the given handle and none of that process's children. try_bool!(psapi::GetProcessMemoryInfo( handle as _, &mut memory_counters as *mut _ as _, std::mem::size_of::<psapi::PROCESS_MEMORY_COUNTERS_EX>() as u32, )); } // Guide on interpreting these numbers: // https://docs.microsoft.com/en-us/windows/win32/psapi/process-memory-usage-information let peak_working_set = memory_counters.PeakWorkingSetSize / 1024; let peak_page_file = memory_counters.PeakPagefileUsage / 1024; let peak_paged_pool = memory_counters.QuotaPeakPagedPoolUsage / 1024; let peak_nonpaged_pool = memory_counters.QuotaPeakNonPagedPoolUsage / 1024; Some(format!( "user: {USER_SEC}.{USER_USEC:03} \ sys: {SYS_SEC}.{SYS_USEC:03} \ peak working set (kb): {PEAK_WORKING_SET} \ peak page file usage (kb): {PEAK_PAGE_FILE} \ peak paged pool usage (kb): {PEAK_PAGED_POOL} \ peak non-paged pool usage (kb): {PEAK_NONPAGED_POOL} \ page faults: {PAGE_FAULTS}", USER_SEC = user_time.wSecond + (user_time.wMinute * 60), USER_USEC = user_time.wMilliseconds, SYS_SEC = kernel_time.wSecond + (kernel_time.wMinute * 60), SYS_USEC = kernel_time.wMilliseconds, PEAK_WORKING_SET = peak_working_set, PEAK_PAGE_FILE = peak_page_file, PEAK_PAGED_POOL = peak_paged_pool, PEAK_NONPAGED_POOL = peak_nonpaged_pool, PAGE_FAULTS = memory_counters.PageFaultCount, )) } #[cfg(unix)] /// Tries to build a string with human readable data for several of the rusage /// fields. Note that we are focusing mainly on data that we believe to be /// supplied on Linux (the `rusage` struct has other fields in it but they are /// currently unsupported by Linux). fn format_rusage_data(_child: Child) -> Option<String> { let rusage: libc::rusage = unsafe { let mut recv = std::mem::zeroed(); // -1 is RUSAGE_CHILDREN, which means to get the rusage for all children // (and grandchildren, etc) processes that have respectively terminated // and been waited for. let retval = libc::getrusage(-1, &mut recv); if retval!= 0 { return None; } recv }; // Mac OS X reports the maxrss in bytes, not kb. let divisor = if env::consts::OS == "macos" { 1024 } else { 1 }; let maxrss = (rusage.ru_maxrss + (divisor - 1)) / divisor; let mut init_str = format!( "user: {USER_SEC}.{USER_USEC:03} \ sys: {SYS_SEC}.{SYS_USEC:03} \ max rss (kb): {MAXRSS}", USER_SEC = rusage.ru_utime.tv_sec, USER_USEC = rusage.ru_utime.tv_usec, SYS_SEC = rusage.ru_stime.tv_sec, SYS_USEC = rusage.ru_stime.tv_usec, MAXRSS = maxrss ); // The remaining rusage stats vary in platform support. So we treat // uniformly zero values in each category as "not worth printing", since it // either means no events of that type occurred, or that the platform // does not support it. let minflt = rusage.ru_minflt; let majflt = rusage.ru_majflt; if minflt!= 0 || majflt!= 0 { init_str.push_str(&format!(" page reclaims: {} page faults: {}", minflt, majflt)); } let inblock = rusage.ru_inblock; let oublock = rusage.ru_oublock; if inblock!= 0 || oublock!= 0 { init_str.push_str(&format!(" fs block inputs: {} fs block outputs: {}", inblock, oublock)); } let nvcsw = rusage.ru_nvcsw; let nivcsw = rusage.ru_nivcsw; if nvcsw!= 0 || nivcsw!= 0 { init_str.push_str(&format!( " voluntary ctxt switches: {} involuntary ctxt switches: {}", nvcsw, nivcsw )); } return Some(init_str); }
let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set"); let on_fail = env::var_os("RUSTC_ON_FAIL").map(Command::new);
random_line_split
scroll_viewer_mode.rs
/// The `ScrollMode` defines the mode of a scroll direction. #[derive(Copy, Debug, Clone, PartialEq)] pub enum ScrollMode { /// Scrolling will process by `ScrollViewer` logic Auto, /// Scrolling could be handled from outside. It will not be /// process by `ScrollViewer` logic. Custom, /// Scrolling will be disabled. Disabled, } impl Default for ScrollMode { fn default() -> Self { ScrollMode::Auto } } impl From<&str> for ScrollMode { fn
(s: &str) -> ScrollMode { match s { "Custom" | "custom" => ScrollMode::Custom, "Disabled" | "disabled" => ScrollMode::Disabled, _ => ScrollMode::Auto, } } } /// `ScrollViewerMode` describes the vertical and horizontal scroll /// behavior of the `ScrollViewer`. #[derive(Debug, Copy, Clone, PartialEq)] pub struct ScrollViewerMode { /// Vertical scroll mode. pub vertical: ScrollMode, /// Horizontal scroll mode. pub horizontal: ScrollMode, } // --- Conversions --- impl From<(&str, &str)> for ScrollViewerMode { fn from(s: (&str, &str)) -> ScrollViewerMode { ScrollViewerMode { horizontal: ScrollMode::from(s.0), vertical: ScrollMode::from(s.1), } } } impl Default for ScrollViewerMode { fn default() -> ScrollViewerMode { ScrollViewerMode { vertical: ScrollMode::Auto, horizontal: ScrollMode::Auto, } } }
from
identifier_name
scroll_viewer_mode.rs
/// The `ScrollMode` defines the mode of a scroll direction. #[derive(Copy, Debug, Clone, PartialEq)] pub enum ScrollMode { /// Scrolling will process by `ScrollViewer` logic Auto, /// Scrolling could be handled from outside. It will not be /// process by `ScrollViewer` logic. Custom, /// Scrolling will be disabled. Disabled, } impl Default for ScrollMode { fn default() -> Self { ScrollMode::Auto } } impl From<&str> for ScrollMode { fn from(s: &str) -> ScrollMode { match s { "Custom" | "custom" => ScrollMode::Custom, "Disabled" | "disabled" => ScrollMode::Disabled, _ => ScrollMode::Auto, } } } /// `ScrollViewerMode` describes the vertical and horizontal scroll /// behavior of the `ScrollViewer`. #[derive(Debug, Copy, Clone, PartialEq)] pub struct ScrollViewerMode { /// Vertical scroll mode. pub vertical: ScrollMode, /// Horizontal scroll mode. pub horizontal: ScrollMode, } // --- Conversions --- impl From<(&str, &str)> for ScrollViewerMode { fn from(s: (&str, &str)) -> ScrollViewerMode { ScrollViewerMode { horizontal: ScrollMode::from(s.0),
} } } impl Default for ScrollViewerMode { fn default() -> ScrollViewerMode { ScrollViewerMode { vertical: ScrollMode::Auto, horizontal: ScrollMode::Auto, } } }
vertical: ScrollMode::from(s.1),
random_line_split
macro_crate_test.rs
// Copyright 2013-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. // force-host #![feature(globs, plugin_registrar, macro_rules, quote, managed_boxes)] extern crate syntax; extern crate rustc; use syntax::ast::{TokenTree, Item, MetaItem}; use syntax::codemap::Span; use syntax::ext::base::*; use syntax::parse::token; use rustc::plugin::Registry; use std::gc::{Gc, GC}; #[macro_export] macro_rules! exported_macro (() => (2i)) macro_rules! unexported_macro (() => (3i)) #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("make_a_1", expand_make_a_1); reg.register_syntax_extension( token::intern("into_foo"), ItemModifier(expand_into_foo)); } fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult> { if!tts.is_empty()
MacExpr::new(quote_expr!(cx, 1i)) } fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: Gc<MetaItem>, it: Gc<Item>) -> Gc<Item> { box(GC) Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone() } } pub fn foo() {}
{ cx.span_fatal(sp, "make_a_1 takes no arguments"); }
conditional_block
macro_crate_test.rs
// Copyright 2013-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. // force-host #![feature(globs, plugin_registrar, macro_rules, quote, managed_boxes)] extern crate syntax; extern crate rustc; use syntax::ast::{TokenTree, Item, MetaItem}; use syntax::codemap::Span; use syntax::ext::base::*; use syntax::parse::token; use rustc::plugin::Registry; use std::gc::{Gc, GC}; #[macro_export] macro_rules! exported_macro (() => (2i)) macro_rules! unexported_macro (() => (3i)) #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry)
fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult> { if!tts.is_empty() { cx.span_fatal(sp, "make_a_1 takes no arguments"); } MacExpr::new(quote_expr!(cx, 1i)) } fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: Gc<MetaItem>, it: Gc<Item>) -> Gc<Item> { box(GC) Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone() } } pub fn foo() {}
{ reg.register_macro("make_a_1", expand_make_a_1); reg.register_syntax_extension( token::intern("into_foo"), ItemModifier(expand_into_foo)); }
identifier_body
macro_crate_test.rs
// Copyright 2013-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. // force-host #![feature(globs, plugin_registrar, macro_rules, quote, managed_boxes)] extern crate syntax; extern crate rustc; use syntax::ast::{TokenTree, Item, MetaItem}; use syntax::codemap::Span; use syntax::ext::base::*; use syntax::parse::token; use rustc::plugin::Registry; use std::gc::{Gc, GC}; #[macro_export] macro_rules! exported_macro (() => (2i)) macro_rules! unexported_macro (() => (3i)) #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("make_a_1", expand_make_a_1); reg.register_syntax_extension( token::intern("into_foo"), ItemModifier(expand_into_foo)); } fn
(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult> { if!tts.is_empty() { cx.span_fatal(sp, "make_a_1 takes no arguments"); } MacExpr::new(quote_expr!(cx, 1i)) } fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: Gc<MetaItem>, it: Gc<Item>) -> Gc<Item> { box(GC) Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone() } } pub fn foo() {}
expand_make_a_1
identifier_name
macro_crate_test.rs
// Copyright 2013-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. // force-host #![feature(globs, plugin_registrar, macro_rules, quote, managed_boxes)] extern crate syntax; extern crate rustc; use syntax::ast::{TokenTree, Item, MetaItem}; use syntax::codemap::Span; use syntax::ext::base::*; use syntax::parse::token; use rustc::plugin::Registry; use std::gc::{Gc, GC}; #[macro_export] macro_rules! exported_macro (() => (2i)) macro_rules! unexported_macro (() => (3i)) #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("make_a_1", expand_make_a_1); reg.register_syntax_extension( token::intern("into_foo"), ItemModifier(expand_into_foo)); } fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult> { if!tts.is_empty() { cx.span_fatal(sp, "make_a_1 takes no arguments"); } MacExpr::new(quote_expr!(cx, 1i)) }
-> Gc<Item> { box(GC) Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone() } } pub fn foo() {}
fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: Gc<MetaItem>, it: Gc<Item>)
random_line_split
string.rs
use std::fmt; use std::ops; #[derive(Clone, Eq)] pub enum StringOrStatic { String(String), Static(&'static str), } impl From<&str> for StringOrStatic { fn from(s: &str) -> Self { StringOrStatic::String(s.to_owned()) } } impl From<String> for StringOrStatic { fn from(s: String) -> Self { StringOrStatic::String(s) } } impl StringOrStatic { pub fn
(&self) -> &str { match self { StringOrStatic::String(s) => &s, StringOrStatic::Static(s) => s, } } pub fn to_string(&self) -> String { format!("{}", self) } } impl ops::Deref for StringOrStatic { type Target = str; fn deref(&self) -> &str { self.as_str() } } impl PartialEq<StringOrStatic> for StringOrStatic { fn eq(&self, other: &StringOrStatic) -> bool { self.as_str() == other.as_str() } } impl PartialEq<str> for StringOrStatic { fn eq(&self, other: &str) -> bool { self.as_str() == other } } impl PartialEq<&str> for StringOrStatic { fn eq(&self, other: &&str) -> bool { self.as_str() == *other } } impl PartialEq<StringOrStatic> for str { fn eq(&self, other: &StringOrStatic) -> bool { self == other.as_str() } } impl PartialEq<StringOrStatic> for &str { fn eq(&self, other: &StringOrStatic) -> bool { *self == other.as_str() } } impl fmt::Display for StringOrStatic { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { StringOrStatic::String(s) => fmt::Display::fmt(s, f), StringOrStatic::Static(s) => fmt::Display::fmt(s, f), } } }
as_str
identifier_name
string.rs
use std::fmt; use std::ops; #[derive(Clone, Eq)] pub enum StringOrStatic { String(String), Static(&'static str), } impl From<&str> for StringOrStatic { fn from(s: &str) -> Self { StringOrStatic::String(s.to_owned()) }
} impl From<String> for StringOrStatic { fn from(s: String) -> Self { StringOrStatic::String(s) } } impl StringOrStatic { pub fn as_str(&self) -> &str { match self { StringOrStatic::String(s) => &s, StringOrStatic::Static(s) => s, } } pub fn to_string(&self) -> String { format!("{}", self) } } impl ops::Deref for StringOrStatic { type Target = str; fn deref(&self) -> &str { self.as_str() } } impl PartialEq<StringOrStatic> for StringOrStatic { fn eq(&self, other: &StringOrStatic) -> bool { self.as_str() == other.as_str() } } impl PartialEq<str> for StringOrStatic { fn eq(&self, other: &str) -> bool { self.as_str() == other } } impl PartialEq<&str> for StringOrStatic { fn eq(&self, other: &&str) -> bool { self.as_str() == *other } } impl PartialEq<StringOrStatic> for str { fn eq(&self, other: &StringOrStatic) -> bool { self == other.as_str() } } impl PartialEq<StringOrStatic> for &str { fn eq(&self, other: &StringOrStatic) -> bool { *self == other.as_str() } } impl fmt::Display for StringOrStatic { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { StringOrStatic::String(s) => fmt::Display::fmt(s, f), StringOrStatic::Static(s) => fmt::Display::fmt(s, f), } } }
random_line_split
socket.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. use std::convert::From; use std::io; use std::io::{ErrorKind, Read, Write}; use std::net::{Shutdown, TcpStream}; use {TransportErrorKind, new_transport_error}; use super::{ReadHalf, TIoChannel, WriteHalf}; /// Bidirectional TCP/IP channel. /// /// # Examples /// /// Create a `TTcpChannel`. /// /// ```no_run /// use std::io::{Read, Write}; /// use thrift::transport::TTcpChannel; /// /// let mut c = TTcpChannel::new(); /// c.open("localhost:9090").unwrap(); /// /// let mut buf = vec![0u8; 4]; /// c.read(&mut buf).unwrap(); /// c.write(&vec![0, 1, 2]).unwrap(); /// ``` /// /// Create a `TTcpChannel` by wrapping an existing `TcpStream`. /// /// ```no_run /// use std::io::{Read, Write}; /// use std::net::TcpStream; /// use thrift::transport::TTcpChannel; /// /// let stream = TcpStream::connect("127.0.0.1:9189").unwrap(); /// /// // no need to call c.open() since we've already connected above /// let mut c = TTcpChannel::with_stream(stream); /// /// let mut buf = vec![0u8; 4]; /// c.read(&mut buf).unwrap(); /// c.write(&vec![0, 1, 2]).unwrap(); /// ``` #[derive(Debug, Default)] pub struct TTcpChannel { stream: Option<TcpStream>, } impl TTcpChannel { /// Create an uninitialized `TTcpChannel`. /// /// The returned instance must be opened using `TTcpChannel::open(...)` /// before it can be used. pub fn new() -> TTcpChannel { TTcpChannel { stream: None } } /// Create a `TTcpChannel` that wraps an existing `TcpStream`. /// /// The passed-in stream is assumed to have been opened before being wrapped /// by the created `TTcpChannel` instance. pub fn with_stream(stream: TcpStream) -> TTcpChannel { TTcpChannel { stream: Some(stream) } } /// Connect to `remote_address`, which should have the form `host:port`. pub fn open(&mut self, remote_address: &str) -> ::Result<()> { if self.stream.is_some() { Err( new_transport_error( TransportErrorKind::AlreadyOpen, "tcp connection previously opened", ), ) } else { match TcpStream::connect(&remote_address) { Ok(s) => { self.stream = Some(s); Ok(()) } Err(e) => Err(From::from(e)), } } } /// Shut down this channel. /// /// Both send and receive halves are closed, and this instance can no /// longer be used to communicate with another endpoint. pub fn close(&mut self) -> ::Result<()> { self.if_set(|s| s.shutdown(Shutdown::Both)) .map_err(From::from) } fn if_set<F, T>(&mut self, mut stream_operation: F) -> io::Result<T> where F: FnMut(&mut TcpStream) -> io::Result<T>,
} impl TIoChannel for TTcpChannel { fn split(self) -> ::Result<(ReadHalf<Self>, WriteHalf<Self>)> where Self: Sized, { let mut s = self; s.stream .as_mut() .and_then(|s| s.try_clone().ok()) .map( |cloned| { (ReadHalf { handle: TTcpChannel { stream: s.stream.take() } }, WriteHalf { handle: TTcpChannel { stream: Some(cloned) } }) }, ) .ok_or_else( || { new_transport_error( TransportErrorKind::Unknown, "cannot clone underlying tcp stream", ) }, ) } } impl Read for TTcpChannel { fn read(&mut self, b: &mut [u8]) -> io::Result<usize> { self.if_set(|s| s.read(b)) } } impl Write for TTcpChannel { fn write(&mut self, b: &[u8]) -> io::Result<usize> { self.if_set(|s| s.write_all(b)).map(|_| b.len()) } fn flush(&mut self) -> io::Result<()> { self.if_set(|s| s.flush()) } }
{ if let Some(ref mut s) = self.stream { stream_operation(s) } else { Err(io::Error::new(ErrorKind::NotConnected, "tcp endpoint not connected"),) } }
identifier_body
socket.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. use std::convert::From; use std::io; use std::io::{ErrorKind, Read, Write}; use std::net::{Shutdown, TcpStream}; use {TransportErrorKind, new_transport_error}; use super::{ReadHalf, TIoChannel, WriteHalf}; /// Bidirectional TCP/IP channel. /// /// # Examples /// /// Create a `TTcpChannel`. /// /// ```no_run /// use std::io::{Read, Write}; /// use thrift::transport::TTcpChannel; /// /// let mut c = TTcpChannel::new(); /// c.open("localhost:9090").unwrap(); /// /// let mut buf = vec![0u8; 4]; /// c.read(&mut buf).unwrap(); /// c.write(&vec![0, 1, 2]).unwrap(); /// ``` /// /// Create a `TTcpChannel` by wrapping an existing `TcpStream`. /// /// ```no_run /// use std::io::{Read, Write}; /// use std::net::TcpStream; /// use thrift::transport::TTcpChannel; /// /// let stream = TcpStream::connect("127.0.0.1:9189").unwrap(); /// /// // no need to call c.open() since we've already connected above /// let mut c = TTcpChannel::with_stream(stream); /// /// let mut buf = vec![0u8; 4]; /// c.read(&mut buf).unwrap(); /// c.write(&vec![0, 1, 2]).unwrap(); /// ``` #[derive(Debug, Default)] pub struct TTcpChannel { stream: Option<TcpStream>, } impl TTcpChannel { /// Create an uninitialized `TTcpChannel`. /// /// The returned instance must be opened using `TTcpChannel::open(...)` /// before it can be used. pub fn new() -> TTcpChannel { TTcpChannel { stream: None } } /// Create a `TTcpChannel` that wraps an existing `TcpStream`. /// /// The passed-in stream is assumed to have been opened before being wrapped /// by the created `TTcpChannel` instance. pub fn with_stream(stream: TcpStream) -> TTcpChannel { TTcpChannel { stream: Some(stream) } } /// Connect to `remote_address`, which should have the form `host:port`. pub fn open(&mut self, remote_address: &str) -> ::Result<()> { if self.stream.is_some() { Err( new_transport_error( TransportErrorKind::AlreadyOpen, "tcp connection previously opened", ), ) } else { match TcpStream::connect(&remote_address) { Ok(s) => { self.stream = Some(s); Ok(()) } Err(e) => Err(From::from(e)), } } } /// Shut down this channel. /// /// Both send and receive halves are closed, and this instance can no /// longer be used to communicate with another endpoint. pub fn close(&mut self) -> ::Result<()> { self.if_set(|s| s.shutdown(Shutdown::Both)) .map_err(From::from) } fn if_set<F, T>(&mut self, mut stream_operation: F) -> io::Result<T> where F: FnMut(&mut TcpStream) -> io::Result<T>, { if let Some(ref mut s) = self.stream
else { Err(io::Error::new(ErrorKind::NotConnected, "tcp endpoint not connected"),) } } } impl TIoChannel for TTcpChannel { fn split(self) -> ::Result<(ReadHalf<Self>, WriteHalf<Self>)> where Self: Sized, { let mut s = self; s.stream .as_mut() .and_then(|s| s.try_clone().ok()) .map( |cloned| { (ReadHalf { handle: TTcpChannel { stream: s.stream.take() } }, WriteHalf { handle: TTcpChannel { stream: Some(cloned) } }) }, ) .ok_or_else( || { new_transport_error( TransportErrorKind::Unknown, "cannot clone underlying tcp stream", ) }, ) } } impl Read for TTcpChannel { fn read(&mut self, b: &mut [u8]) -> io::Result<usize> { self.if_set(|s| s.read(b)) } } impl Write for TTcpChannel { fn write(&mut self, b: &[u8]) -> io::Result<usize> { self.if_set(|s| s.write_all(b)).map(|_| b.len()) } fn flush(&mut self) -> io::Result<()> { self.if_set(|s| s.flush()) } }
{ stream_operation(s) }
conditional_block
socket.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. use std::convert::From; use std::io; use std::io::{ErrorKind, Read, Write}; use std::net::{Shutdown, TcpStream}; use {TransportErrorKind, new_transport_error}; use super::{ReadHalf, TIoChannel, WriteHalf}; /// Bidirectional TCP/IP channel. /// /// # Examples /// /// Create a `TTcpChannel`. /// /// ```no_run /// use std::io::{Read, Write}; /// use thrift::transport::TTcpChannel; /// /// let mut c = TTcpChannel::new(); /// c.open("localhost:9090").unwrap(); /// /// let mut buf = vec![0u8; 4]; /// c.read(&mut buf).unwrap(); /// c.write(&vec![0, 1, 2]).unwrap(); /// ``` /// /// Create a `TTcpChannel` by wrapping an existing `TcpStream`. /// /// ```no_run /// use std::io::{Read, Write}; /// use std::net::TcpStream; /// use thrift::transport::TTcpChannel; /// /// let stream = TcpStream::connect("127.0.0.1:9189").unwrap(); /// /// // no need to call c.open() since we've already connected above /// let mut c = TTcpChannel::with_stream(stream); /// /// let mut buf = vec![0u8; 4]; /// c.read(&mut buf).unwrap(); /// c.write(&vec![0, 1, 2]).unwrap(); /// ``` #[derive(Debug, Default)] pub struct TTcpChannel { stream: Option<TcpStream>, } impl TTcpChannel { /// Create an uninitialized `TTcpChannel`. /// /// The returned instance must be opened using `TTcpChannel::open(...)` /// before it can be used. pub fn new() -> TTcpChannel { TTcpChannel { stream: None } } /// Create a `TTcpChannel` that wraps an existing `TcpStream`. /// /// The passed-in stream is assumed to have been opened before being wrapped /// by the created `TTcpChannel` instance. pub fn with_stream(stream: TcpStream) -> TTcpChannel { TTcpChannel { stream: Some(stream) } } /// Connect to `remote_address`, which should have the form `host:port`. pub fn open(&mut self, remote_address: &str) -> ::Result<()> { if self.stream.is_some() { Err( new_transport_error(
) } else { match TcpStream::connect(&remote_address) { Ok(s) => { self.stream = Some(s); Ok(()) } Err(e) => Err(From::from(e)), } } } /// Shut down this channel. /// /// Both send and receive halves are closed, and this instance can no /// longer be used to communicate with another endpoint. pub fn close(&mut self) -> ::Result<()> { self.if_set(|s| s.shutdown(Shutdown::Both)) .map_err(From::from) } fn if_set<F, T>(&mut self, mut stream_operation: F) -> io::Result<T> where F: FnMut(&mut TcpStream) -> io::Result<T>, { if let Some(ref mut s) = self.stream { stream_operation(s) } else { Err(io::Error::new(ErrorKind::NotConnected, "tcp endpoint not connected"),) } } } impl TIoChannel for TTcpChannel { fn split(self) -> ::Result<(ReadHalf<Self>, WriteHalf<Self>)> where Self: Sized, { let mut s = self; s.stream .as_mut() .and_then(|s| s.try_clone().ok()) .map( |cloned| { (ReadHalf { handle: TTcpChannel { stream: s.stream.take() } }, WriteHalf { handle: TTcpChannel { stream: Some(cloned) } }) }, ) .ok_or_else( || { new_transport_error( TransportErrorKind::Unknown, "cannot clone underlying tcp stream", ) }, ) } } impl Read for TTcpChannel { fn read(&mut self, b: &mut [u8]) -> io::Result<usize> { self.if_set(|s| s.read(b)) } } impl Write for TTcpChannel { fn write(&mut self, b: &[u8]) -> io::Result<usize> { self.if_set(|s| s.write_all(b)).map(|_| b.len()) } fn flush(&mut self) -> io::Result<()> { self.if_set(|s| s.flush()) } }
TransportErrorKind::AlreadyOpen, "tcp connection previously opened", ),
random_line_split
socket.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. use std::convert::From; use std::io; use std::io::{ErrorKind, Read, Write}; use std::net::{Shutdown, TcpStream}; use {TransportErrorKind, new_transport_error}; use super::{ReadHalf, TIoChannel, WriteHalf}; /// Bidirectional TCP/IP channel. /// /// # Examples /// /// Create a `TTcpChannel`. /// /// ```no_run /// use std::io::{Read, Write}; /// use thrift::transport::TTcpChannel; /// /// let mut c = TTcpChannel::new(); /// c.open("localhost:9090").unwrap(); /// /// let mut buf = vec![0u8; 4]; /// c.read(&mut buf).unwrap(); /// c.write(&vec![0, 1, 2]).unwrap(); /// ``` /// /// Create a `TTcpChannel` by wrapping an existing `TcpStream`. /// /// ```no_run /// use std::io::{Read, Write}; /// use std::net::TcpStream; /// use thrift::transport::TTcpChannel; /// /// let stream = TcpStream::connect("127.0.0.1:9189").unwrap(); /// /// // no need to call c.open() since we've already connected above /// let mut c = TTcpChannel::with_stream(stream); /// /// let mut buf = vec![0u8; 4]; /// c.read(&mut buf).unwrap(); /// c.write(&vec![0, 1, 2]).unwrap(); /// ``` #[derive(Debug, Default)] pub struct TTcpChannel { stream: Option<TcpStream>, } impl TTcpChannel { /// Create an uninitialized `TTcpChannel`. /// /// The returned instance must be opened using `TTcpChannel::open(...)` /// before it can be used. pub fn new() -> TTcpChannel { TTcpChannel { stream: None } } /// Create a `TTcpChannel` that wraps an existing `TcpStream`. /// /// The passed-in stream is assumed to have been opened before being wrapped /// by the created `TTcpChannel` instance. pub fn with_stream(stream: TcpStream) -> TTcpChannel { TTcpChannel { stream: Some(stream) } } /// Connect to `remote_address`, which should have the form `host:port`. pub fn open(&mut self, remote_address: &str) -> ::Result<()> { if self.stream.is_some() { Err( new_transport_error( TransportErrorKind::AlreadyOpen, "tcp connection previously opened", ), ) } else { match TcpStream::connect(&remote_address) { Ok(s) => { self.stream = Some(s); Ok(()) } Err(e) => Err(From::from(e)), } } } /// Shut down this channel. /// /// Both send and receive halves are closed, and this instance can no /// longer be used to communicate with another endpoint. pub fn close(&mut self) -> ::Result<()> { self.if_set(|s| s.shutdown(Shutdown::Both)) .map_err(From::from) } fn
<F, T>(&mut self, mut stream_operation: F) -> io::Result<T> where F: FnMut(&mut TcpStream) -> io::Result<T>, { if let Some(ref mut s) = self.stream { stream_operation(s) } else { Err(io::Error::new(ErrorKind::NotConnected, "tcp endpoint not connected"),) } } } impl TIoChannel for TTcpChannel { fn split(self) -> ::Result<(ReadHalf<Self>, WriteHalf<Self>)> where Self: Sized, { let mut s = self; s.stream .as_mut() .and_then(|s| s.try_clone().ok()) .map( |cloned| { (ReadHalf { handle: TTcpChannel { stream: s.stream.take() } }, WriteHalf { handle: TTcpChannel { stream: Some(cloned) } }) }, ) .ok_or_else( || { new_transport_error( TransportErrorKind::Unknown, "cannot clone underlying tcp stream", ) }, ) } } impl Read for TTcpChannel { fn read(&mut self, b: &mut [u8]) -> io::Result<usize> { self.if_set(|s| s.read(b)) } } impl Write for TTcpChannel { fn write(&mut self, b: &[u8]) -> io::Result<usize> { self.if_set(|s| s.write_all(b)).map(|_| b.len()) } fn flush(&mut self) -> io::Result<()> { self.if_set(|s| s.flush()) } }
if_set
identifier_name
thread_local.rs
use std::cell::RefCell; use std::mem; use thread::Thread; pub struct Data { pub current_thread: Thread, pub parkable: bool, // i.e. for frame stack lock } pub unsafe fn init(data: Data) { set_data_ptr(Box::new(RefCell::new(data))); } pub fn data() -> &'static RefCell<Data> { unsafe{&*get_data_ptr()} }
let mut data: *const RefCell<Data>; asm!("movq %fs:0, $0" : "=r"(data) ::: "volatile"); data } #[cfg(target_arch = "x86_64")] unsafe fn set_data_ptr(data: Box<RefCell<Data>>) { let data_ptr: *const RefCell<Data> = mem::transmute(data); asm!("movq $0, %fs:0" :: "r"(data_ptr) :: "volatile"); }
#[cfg(target_arch = "x86_64")] unsafe fn get_data_ptr() -> *const RefCell<Data> {
random_line_split
thread_local.rs
use std::cell::RefCell; use std::mem; use thread::Thread; pub struct Data { pub current_thread: Thread, pub parkable: bool, // i.e. for frame stack lock } pub unsafe fn init(data: Data) { set_data_ptr(Box::new(RefCell::new(data))); } pub fn data() -> &'static RefCell<Data> { unsafe{&*get_data_ptr()} } #[cfg(target_arch = "x86_64")] unsafe fn get_data_ptr() -> *const RefCell<Data> { let mut data: *const RefCell<Data>; asm!("movq %fs:0, $0" : "=r"(data) ::: "volatile"); data } #[cfg(target_arch = "x86_64")] unsafe fn set_data_ptr(data: Box<RefCell<Data>>)
{ let data_ptr: *const RefCell<Data> = mem::transmute(data); asm!("movq $0, %fs:0" :: "r"(data_ptr) :: "volatile"); }
identifier_body
thread_local.rs
use std::cell::RefCell; use std::mem; use thread::Thread; pub struct Data { pub current_thread: Thread, pub parkable: bool, // i.e. for frame stack lock } pub unsafe fn init(data: Data) { set_data_ptr(Box::new(RefCell::new(data))); } pub fn data() -> &'static RefCell<Data> { unsafe{&*get_data_ptr()} } #[cfg(target_arch = "x86_64")] unsafe fn
() -> *const RefCell<Data> { let mut data: *const RefCell<Data>; asm!("movq %fs:0, $0" : "=r"(data) ::: "volatile"); data } #[cfg(target_arch = "x86_64")] unsafe fn set_data_ptr(data: Box<RefCell<Data>>) { let data_ptr: *const RefCell<Data> = mem::transmute(data); asm!("movq $0, %fs:0" :: "r"(data_ptr) :: "volatile"); }
get_data_ptr
identifier_name
label.rs
use Scalar; use color::{Color, Colorable}; use elmesque::Element; use graphics::character::CharacterCache; use label::FontSize; use theme::Theme; use ui::GlyphCache; use widget::{self, Widget, WidgetId}; /// Displays some given text centred within a rectangle. #[derive(Clone, Debug)] pub struct Label<'a> { common: widget::CommonBuilder, text: &'a str, style: Style, maybe_parent_id: Option<WidgetId>, } /// The styling for a Label's renderable Element. #[allow(missing_docs, missing_copy_implementations)] #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)] pub struct Style { maybe_font_size: Option<FontSize>, maybe_color: Option<Color>, } /// The state to be stored between updates for the Label. #[derive(Clone, Debug, PartialEq)] pub struct State(String); impl<'a> Label<'a> { /// Construct a new Label widget. pub fn new(text: &'a str) -> Label<'a> { Label { common: widget::CommonBuilder::new(), text: text, style: Style::new(), maybe_parent_id: None, } } /// Set the font size for the label. #[inline] pub fn font_size(mut self, size: FontSize) -> Label<'a> { self.style.maybe_font_size = Some(size); self } } impl<'a> Widget for Label<'a> { type State = State; type Style = Style; fn common(&self) -> &widget::CommonBuilder { &self.common } fn common_mut(&mut self) -> &mut widget::CommonBuilder { &mut self.common } fn unique_kind(&self) -> &'static str { "Label" } fn init_state(&self) -> State { State(String::new()) } fn style(&self) -> Style { self.style.clone() } fn default_width<C: CharacterCache>(&self, theme: &Theme, glyph_cache: &GlyphCache<C>) -> Scalar { glyph_cache.width(self.style.font_size(theme), self.text) } fn default_height(&self, theme: &Theme) -> Scalar { self.style.font_size(theme) as Scalar } /// Update the state of the Label. fn update<'b, 'c, C>(self, args: widget::UpdateArgs<'b, 'c, Self, C>) -> Option<State>
let widget::UpdateArgs { prev_state,.. } = args; let widget::State { state: State(ref string),.. } = *prev_state; if &string[..]!= self.text { Some(State(self.text.to_string())) } else { None } } /// Construct an Element for the Label. fn draw<'b, C>(args: widget::DrawArgs<'b, Self, C>) -> Element where C: CharacterCache, { use elmesque::form::{text, collage}; use elmesque::text::Text; let widget::DrawArgs { state, style, theme,.. } = args; let widget::State { state: State(ref string), dim, xy,.. } = *state; let size = style.font_size(theme); let color = style.color(theme); let form = text(Text::from_string(string.clone()) .color(color) .height(size as f64)).shift(xy[0].floor(), xy[1].floor()); collage(dim[0] as i32, dim[1] as i32, vec![form]) } } impl Style { /// Construct the default Style. pub fn new() -> Style { Style { maybe_color: None, maybe_font_size: None, } } /// Get the Color for an Element. pub fn color(&self, theme: &Theme) -> Color { self.maybe_color.unwrap_or(theme.label_color) } /// Get the label font size for an Element. pub fn font_size(&self, theme: &Theme) -> FontSize { self.maybe_font_size.unwrap_or(theme.font_size_medium) } } impl<'a> Colorable for Label<'a> { fn color(mut self, color: Color) -> Self { self.style.maybe_color = Some(color); self } }
where C: CharacterCache, {
random_line_split
label.rs
use Scalar; use color::{Color, Colorable}; use elmesque::Element; use graphics::character::CharacterCache; use label::FontSize; use theme::Theme; use ui::GlyphCache; use widget::{self, Widget, WidgetId}; /// Displays some given text centred within a rectangle. #[derive(Clone, Debug)] pub struct Label<'a> { common: widget::CommonBuilder, text: &'a str, style: Style, maybe_parent_id: Option<WidgetId>, } /// The styling for a Label's renderable Element. #[allow(missing_docs, missing_copy_implementations)] #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)] pub struct Style { maybe_font_size: Option<FontSize>, maybe_color: Option<Color>, } /// The state to be stored between updates for the Label. #[derive(Clone, Debug, PartialEq)] pub struct State(String); impl<'a> Label<'a> { /// Construct a new Label widget. pub fn new(text: &'a str) -> Label<'a> { Label { common: widget::CommonBuilder::new(), text: text, style: Style::new(), maybe_parent_id: None, } } /// Set the font size for the label. #[inline] pub fn font_size(mut self, size: FontSize) -> Label<'a> { self.style.maybe_font_size = Some(size); self } } impl<'a> Widget for Label<'a> { type State = State; type Style = Style; fn common(&self) -> &widget::CommonBuilder { &self.common } fn
(&mut self) -> &mut widget::CommonBuilder { &mut self.common } fn unique_kind(&self) -> &'static str { "Label" } fn init_state(&self) -> State { State(String::new()) } fn style(&self) -> Style { self.style.clone() } fn default_width<C: CharacterCache>(&self, theme: &Theme, glyph_cache: &GlyphCache<C>) -> Scalar { glyph_cache.width(self.style.font_size(theme), self.text) } fn default_height(&self, theme: &Theme) -> Scalar { self.style.font_size(theme) as Scalar } /// Update the state of the Label. fn update<'b, 'c, C>(self, args: widget::UpdateArgs<'b, 'c, Self, C>) -> Option<State> where C: CharacterCache, { let widget::UpdateArgs { prev_state,.. } = args; let widget::State { state: State(ref string),.. } = *prev_state; if &string[..]!= self.text { Some(State(self.text.to_string())) } else { None } } /// Construct an Element for the Label. fn draw<'b, C>(args: widget::DrawArgs<'b, Self, C>) -> Element where C: CharacterCache, { use elmesque::form::{text, collage}; use elmesque::text::Text; let widget::DrawArgs { state, style, theme,.. } = args; let widget::State { state: State(ref string), dim, xy,.. } = *state; let size = style.font_size(theme); let color = style.color(theme); let form = text(Text::from_string(string.clone()) .color(color) .height(size as f64)).shift(xy[0].floor(), xy[1].floor()); collage(dim[0] as i32, dim[1] as i32, vec![form]) } } impl Style { /// Construct the default Style. pub fn new() -> Style { Style { maybe_color: None, maybe_font_size: None, } } /// Get the Color for an Element. pub fn color(&self, theme: &Theme) -> Color { self.maybe_color.unwrap_or(theme.label_color) } /// Get the label font size for an Element. pub fn font_size(&self, theme: &Theme) -> FontSize { self.maybe_font_size.unwrap_or(theme.font_size_medium) } } impl<'a> Colorable for Label<'a> { fn color(mut self, color: Color) -> Self { self.style.maybe_color = Some(color); self } }
common_mut
identifier_name
label.rs
use Scalar; use color::{Color, Colorable}; use elmesque::Element; use graphics::character::CharacterCache; use label::FontSize; use theme::Theme; use ui::GlyphCache; use widget::{self, Widget, WidgetId}; /// Displays some given text centred within a rectangle. #[derive(Clone, Debug)] pub struct Label<'a> { common: widget::CommonBuilder, text: &'a str, style: Style, maybe_parent_id: Option<WidgetId>, } /// The styling for a Label's renderable Element. #[allow(missing_docs, missing_copy_implementations)] #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)] pub struct Style { maybe_font_size: Option<FontSize>, maybe_color: Option<Color>, } /// The state to be stored between updates for the Label. #[derive(Clone, Debug, PartialEq)] pub struct State(String); impl<'a> Label<'a> { /// Construct a new Label widget. pub fn new(text: &'a str) -> Label<'a> { Label { common: widget::CommonBuilder::new(), text: text, style: Style::new(), maybe_parent_id: None, } } /// Set the font size for the label. #[inline] pub fn font_size(mut self, size: FontSize) -> Label<'a> { self.style.maybe_font_size = Some(size); self } } impl<'a> Widget for Label<'a> { type State = State; type Style = Style; fn common(&self) -> &widget::CommonBuilder { &self.common } fn common_mut(&mut self) -> &mut widget::CommonBuilder { &mut self.common } fn unique_kind(&self) -> &'static str { "Label" } fn init_state(&self) -> State { State(String::new()) } fn style(&self) -> Style { self.style.clone() } fn default_width<C: CharacterCache>(&self, theme: &Theme, glyph_cache: &GlyphCache<C>) -> Scalar { glyph_cache.width(self.style.font_size(theme), self.text) } fn default_height(&self, theme: &Theme) -> Scalar { self.style.font_size(theme) as Scalar } /// Update the state of the Label. fn update<'b, 'c, C>(self, args: widget::UpdateArgs<'b, 'c, Self, C>) -> Option<State> where C: CharacterCache, { let widget::UpdateArgs { prev_state,.. } = args; let widget::State { state: State(ref string),.. } = *prev_state; if &string[..]!= self.text
else { None } } /// Construct an Element for the Label. fn draw<'b, C>(args: widget::DrawArgs<'b, Self, C>) -> Element where C: CharacterCache, { use elmesque::form::{text, collage}; use elmesque::text::Text; let widget::DrawArgs { state, style, theme,.. } = args; let widget::State { state: State(ref string), dim, xy,.. } = *state; let size = style.font_size(theme); let color = style.color(theme); let form = text(Text::from_string(string.clone()) .color(color) .height(size as f64)).shift(xy[0].floor(), xy[1].floor()); collage(dim[0] as i32, dim[1] as i32, vec![form]) } } impl Style { /// Construct the default Style. pub fn new() -> Style { Style { maybe_color: None, maybe_font_size: None, } } /// Get the Color for an Element. pub fn color(&self, theme: &Theme) -> Color { self.maybe_color.unwrap_or(theme.label_color) } /// Get the label font size for an Element. pub fn font_size(&self, theme: &Theme) -> FontSize { self.maybe_font_size.unwrap_or(theme.font_size_medium) } } impl<'a> Colorable for Label<'a> { fn color(mut self, color: Color) -> Self { self.style.maybe_color = Some(color); self } }
{ Some(State(self.text.to_string())) }
conditional_block
main.rs
extern crate piston; extern crate graphics; extern crate piston_window; extern crate time; extern crate rand; extern crate ai_behavior; extern crate cgmath; extern crate opengl_graphics; mod app; mod entitymanager; mod entity; mod system; mod player; mod config; mod person; mod personspawner; mod graphics_context; use entity::Entity; use graphics_context::GraphicsContext; use piston_window::{ PistonWindow, WindowSettings }; use piston::input::*; use piston::event_loop::*; use opengl_graphics::*; use rand::Rng; use cgmath::Vector2; fn main() { let mut rng = rand::thread_rng(); let seed: [u32;4] = [rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>()]; let opengl = OpenGL::V3_2; let mut window: PistonWindow = WindowSettings::new("GGJ2016", [800, 600])
.unwrap_or_else(|e| { panic!("Failed to build PistonWindow: {}", e) }); window.set_ups(60); let mut background_textures :Vec<String> = Vec::new(); background_textures.push(String::from("assets/img/ground/placeholder_01.jpg")); background_textures.push(String::from("assets/img/ground/placeholder_02.jpg")); let mut gl = GlGraphics::new(opengl); let mut ctx = GraphicsContext::new(800, 600, seed, background_textures); ctx.load_textures(); let player_tex = String::from("assets/img/emoji/78.png"); let person_tex = String::from("assets/img/emoji/77.png"); ctx.load_texture(&player_tex); ctx.load_texture(&person_tex); ctx.load_texture(&String::from("assets/img/emoji/33.png")); let mut app = app::App::new(player_tex); app.add_system(Box::new(personspawner::PersonSpawner::new())); app.add_entity(Box::new(person::Person::new(person_tex, Vector2::new(50.0, 50.0)))); // Add player to entities (player instanciated in app) //app.add_entity(Box::new(player::Player::new())); for e in window { if let Some(args) = e.press_args() { app.key_press(args); } if let Some(args) = e.release_args() { app.key_release(args); } if let Some(args) = e.update_args() { app.update(args); } ctx.update_translation(app.get_player().get_position().x as u32, app.get_player().get_position().y as u32); if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, gl| { ctx.render(args, c, gl); app.render(&mut ctx, c, gl); }); } } }
.exit_on_esc(true) .opengl(opengl) .build()
random_line_split
main.rs
extern crate piston; extern crate graphics; extern crate piston_window; extern crate time; extern crate rand; extern crate ai_behavior; extern crate cgmath; extern crate opengl_graphics; mod app; mod entitymanager; mod entity; mod system; mod player; mod config; mod person; mod personspawner; mod graphics_context; use entity::Entity; use graphics_context::GraphicsContext; use piston_window::{ PistonWindow, WindowSettings }; use piston::input::*; use piston::event_loop::*; use opengl_graphics::*; use rand::Rng; use cgmath::Vector2; fn
() { let mut rng = rand::thread_rng(); let seed: [u32;4] = [rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>()]; let opengl = OpenGL::V3_2; let mut window: PistonWindow = WindowSettings::new("GGJ2016", [800, 600]) .exit_on_esc(true) .opengl(opengl) .build() .unwrap_or_else(|e| { panic!("Failed to build PistonWindow: {}", e) }); window.set_ups(60); let mut background_textures :Vec<String> = Vec::new(); background_textures.push(String::from("assets/img/ground/placeholder_01.jpg")); background_textures.push(String::from("assets/img/ground/placeholder_02.jpg")); let mut gl = GlGraphics::new(opengl); let mut ctx = GraphicsContext::new(800, 600, seed, background_textures); ctx.load_textures(); let player_tex = String::from("assets/img/emoji/78.png"); let person_tex = String::from("assets/img/emoji/77.png"); ctx.load_texture(&player_tex); ctx.load_texture(&person_tex); ctx.load_texture(&String::from("assets/img/emoji/33.png")); let mut app = app::App::new(player_tex); app.add_system(Box::new(personspawner::PersonSpawner::new())); app.add_entity(Box::new(person::Person::new(person_tex, Vector2::new(50.0, 50.0)))); // Add player to entities (player instanciated in app) //app.add_entity(Box::new(player::Player::new())); for e in window { if let Some(args) = e.press_args() { app.key_press(args); } if let Some(args) = e.release_args() { app.key_release(args); } if let Some(args) = e.update_args() { app.update(args); } ctx.update_translation(app.get_player().get_position().x as u32, app.get_player().get_position().y as u32); if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, gl| { ctx.render(args, c, gl); app.render(&mut ctx, c, gl); }); } } }
main
identifier_name
main.rs
extern crate piston; extern crate graphics; extern crate piston_window; extern crate time; extern crate rand; extern crate ai_behavior; extern crate cgmath; extern crate opengl_graphics; mod app; mod entitymanager; mod entity; mod system; mod player; mod config; mod person; mod personspawner; mod graphics_context; use entity::Entity; use graphics_context::GraphicsContext; use piston_window::{ PistonWindow, WindowSettings }; use piston::input::*; use piston::event_loop::*; use opengl_graphics::*; use rand::Rng; use cgmath::Vector2; fn main()
let person_tex = String::from("assets/img/emoji/77.png"); ctx.load_texture(&player_tex); ctx.load_texture(&person_tex); ctx.load_texture(&String::from("assets/img/emoji/33.png")); let mut app = app::App::new(player_tex); app.add_system(Box::new(personspawner::PersonSpawner::new())); app.add_entity(Box::new(person::Person::new(person_tex, Vector2::new(50.0, 50.0)))); // Add player to entities (player instanciated in app) //app.add_entity(Box::new(player::Player::new())); for e in window { if let Some(args) = e.press_args() { app.key_press(args); } if let Some(args) = e.release_args() { app.key_release(args); } if let Some(args) = e.update_args() { app.update(args); } ctx.update_translation(app.get_player().get_position().x as u32, app.get_player().get_position().y as u32); if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, gl| { ctx.render(args, c, gl); app.render(&mut ctx, c, gl); }); } } }
{ let mut rng = rand::thread_rng(); let seed: [u32;4] = [rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>()]; let opengl = OpenGL::V3_2; let mut window: PistonWindow = WindowSettings::new("GGJ2016", [800, 600]) .exit_on_esc(true) .opengl(opengl) .build() .unwrap_or_else(|e| { panic!("Failed to build PistonWindow: {}", e) }); window.set_ups(60); let mut background_textures :Vec<String> = Vec::new(); background_textures.push(String::from("assets/img/ground/placeholder_01.jpg")); background_textures.push(String::from("assets/img/ground/placeholder_02.jpg")); let mut gl = GlGraphics::new(opengl); let mut ctx = GraphicsContext::new(800, 600, seed, background_textures); ctx.load_textures(); let player_tex = String::from("assets/img/emoji/78.png");
identifier_body
main.rs
extern crate piston; extern crate graphics; extern crate piston_window; extern crate time; extern crate rand; extern crate ai_behavior; extern crate cgmath; extern crate opengl_graphics; mod app; mod entitymanager; mod entity; mod system; mod player; mod config; mod person; mod personspawner; mod graphics_context; use entity::Entity; use graphics_context::GraphicsContext; use piston_window::{ PistonWindow, WindowSettings }; use piston::input::*; use piston::event_loop::*; use opengl_graphics::*; use rand::Rng; use cgmath::Vector2; fn main() { let mut rng = rand::thread_rng(); let seed: [u32;4] = [rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>()]; let opengl = OpenGL::V3_2; let mut window: PistonWindow = WindowSettings::new("GGJ2016", [800, 600]) .exit_on_esc(true) .opengl(opengl) .build() .unwrap_or_else(|e| { panic!("Failed to build PistonWindow: {}", e) }); window.set_ups(60); let mut background_textures :Vec<String> = Vec::new(); background_textures.push(String::from("assets/img/ground/placeholder_01.jpg")); background_textures.push(String::from("assets/img/ground/placeholder_02.jpg")); let mut gl = GlGraphics::new(opengl); let mut ctx = GraphicsContext::new(800, 600, seed, background_textures); ctx.load_textures(); let player_tex = String::from("assets/img/emoji/78.png"); let person_tex = String::from("assets/img/emoji/77.png"); ctx.load_texture(&player_tex); ctx.load_texture(&person_tex); ctx.load_texture(&String::from("assets/img/emoji/33.png")); let mut app = app::App::new(player_tex); app.add_system(Box::new(personspawner::PersonSpawner::new())); app.add_entity(Box::new(person::Person::new(person_tex, Vector2::new(50.0, 50.0)))); // Add player to entities (player instanciated in app) //app.add_entity(Box::new(player::Player::new())); for e in window { if let Some(args) = e.press_args()
if let Some(args) = e.release_args() { app.key_release(args); } if let Some(args) = e.update_args() { app.update(args); } ctx.update_translation(app.get_player().get_position().x as u32, app.get_player().get_position().y as u32); if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, gl| { ctx.render(args, c, gl); app.render(&mut ctx, c, gl); }); } } }
{ app.key_press(args); }
conditional_block
ziptuple.rs
use super::size_hint; /// See [`multizip`](../fn.multizip.html) for more information. #[derive(Clone)] pub struct Zip<T> { t: T,
#[deprecated(note = "Renamed to multizip")] pub fn new<U>(t: U) -> Zip<T> where Zip<T>: From<U>, Zip<T>: Iterator, { multizip(t) } } /// An iterator that generalizes *.zip()* and allows running multiple iterators in lockstep. /// /// The iterator `Zip<(I, J,..., M)>` is formed from a tuple of iterators (or values that /// implement `IntoIterator`) and yields elements /// until any of the subiterators yields `None`. /// /// The iterator element type is a tuple like like `(A, B,..., E)` where `A` to `E` are the /// element types of the subiterator. /// /// ``` /// use itertools::multizip; /// /// // Iterate over three sequences side-by-side /// let mut xs = [0, 0, 0]; /// let ys = [69, 107, 101]; /// /// for (i, a, b) in multizip((0..100, &mut xs, &ys)) { /// *a = i ^ *b; /// } /// /// assert_eq!(xs, [69, 106, 103]); /// ``` pub fn multizip<T, U>(t: U) -> Zip<T> where Zip<T>: From<U>, Zip<T>: Iterator, { Zip::from(t) } macro_rules! impl_zip_iter { ($($B:ident),*) => ( #[allow(non_snake_case)] impl<$($B: IntoIterator),*> From<($($B,)*)> for Zip<($($B::IntoIter,)*)> { fn from(t: ($($B,)*)) -> Self { let ($($B,)*) = t; Zip { t: ($($B.into_iter(),)*) } } } #[allow(non_snake_case)] #[allow(unused_assignments)] impl<$($B),*> Iterator for Zip<($($B,)*)> where $( $B: Iterator, )* { type Item = ($($B::Item,)*); fn next(&mut self) -> Option<Self::Item> { let ($(ref mut $B,)*) = self.t; // NOTE: Just like iter::Zip, we check the iterators // for None in order. We may finish unevenly (some // iterators gave n + 1 elements, some only n). $( let $B = match $B.next() { None => return None, Some(elt) => elt }; )* Some(($($B,)*)) } fn size_hint(&self) -> (usize, Option<usize>) { let sh = (::std::usize::MAX, None); let ($(ref $B,)*) = self.t; $( let sh = size_hint::min($B.size_hint(), sh); )* sh } } #[allow(non_snake_case)] impl<$($B),*> ExactSizeIterator for Zip<($($B,)*)> where $( $B: ExactSizeIterator, )* { } ); } impl_zip_iter!(A); impl_zip_iter!(A, B); impl_zip_iter!(A, B, C); impl_zip_iter!(A, B, C, D); impl_zip_iter!(A, B, C, D, E); impl_zip_iter!(A, B, C, D, E, F); impl_zip_iter!(A, B, C, D, E, F, G); impl_zip_iter!(A, B, C, D, E, F, G, H);
} impl<T> Zip<T> { /// Deprecated: renamed to multizip
random_line_split
ziptuple.rs
use super::size_hint; /// See [`multizip`](../fn.multizip.html) for more information. #[derive(Clone)] pub struct Zip<T> { t: T, } impl<T> Zip<T> { /// Deprecated: renamed to multizip #[deprecated(note = "Renamed to multizip")] pub fn new<U>(t: U) -> Zip<T> where Zip<T>: From<U>, Zip<T>: Iterator,
} /// An iterator that generalizes *.zip()* and allows running multiple iterators in lockstep. /// /// The iterator `Zip<(I, J,..., M)>` is formed from a tuple of iterators (or values that /// implement `IntoIterator`) and yields elements /// until any of the subiterators yields `None`. /// /// The iterator element type is a tuple like like `(A, B,..., E)` where `A` to `E` are the /// element types of the subiterator. /// /// ``` /// use itertools::multizip; /// /// // Iterate over three sequences side-by-side /// let mut xs = [0, 0, 0]; /// let ys = [69, 107, 101]; /// /// for (i, a, b) in multizip((0..100, &mut xs, &ys)) { /// *a = i ^ *b; /// } /// /// assert_eq!(xs, [69, 106, 103]); /// ``` pub fn multizip<T, U>(t: U) -> Zip<T> where Zip<T>: From<U>, Zip<T>: Iterator, { Zip::from(t) } macro_rules! impl_zip_iter { ($($B:ident),*) => ( #[allow(non_snake_case)] impl<$($B: IntoIterator),*> From<($($B,)*)> for Zip<($($B::IntoIter,)*)> { fn from(t: ($($B,)*)) -> Self { let ($($B,)*) = t; Zip { t: ($($B.into_iter(),)*) } } } #[allow(non_snake_case)] #[allow(unused_assignments)] impl<$($B),*> Iterator for Zip<($($B,)*)> where $( $B: Iterator, )* { type Item = ($($B::Item,)*); fn next(&mut self) -> Option<Self::Item> { let ($(ref mut $B,)*) = self.t; // NOTE: Just like iter::Zip, we check the iterators // for None in order. We may finish unevenly (some // iterators gave n + 1 elements, some only n). $( let $B = match $B.next() { None => return None, Some(elt) => elt }; )* Some(($($B,)*)) } fn size_hint(&self) -> (usize, Option<usize>) { let sh = (::std::usize::MAX, None); let ($(ref $B,)*) = self.t; $( let sh = size_hint::min($B.size_hint(), sh); )* sh } } #[allow(non_snake_case)] impl<$($B),*> ExactSizeIterator for Zip<($($B,)*)> where $( $B: ExactSizeIterator, )* { } ); } impl_zip_iter!(A); impl_zip_iter!(A, B); impl_zip_iter!(A, B, C); impl_zip_iter!(A, B, C, D); impl_zip_iter!(A, B, C, D, E); impl_zip_iter!(A, B, C, D, E, F); impl_zip_iter!(A, B, C, D, E, F, G); impl_zip_iter!(A, B, C, D, E, F, G, H);
{ multizip(t) }
identifier_body
ziptuple.rs
use super::size_hint; /// See [`multizip`](../fn.multizip.html) for more information. #[derive(Clone)] pub struct Zip<T> { t: T, } impl<T> Zip<T> { /// Deprecated: renamed to multizip #[deprecated(note = "Renamed to multizip")] pub fn
<U>(t: U) -> Zip<T> where Zip<T>: From<U>, Zip<T>: Iterator, { multizip(t) } } /// An iterator that generalizes *.zip()* and allows running multiple iterators in lockstep. /// /// The iterator `Zip<(I, J,..., M)>` is formed from a tuple of iterators (or values that /// implement `IntoIterator`) and yields elements /// until any of the subiterators yields `None`. /// /// The iterator element type is a tuple like like `(A, B,..., E)` where `A` to `E` are the /// element types of the subiterator. /// /// ``` /// use itertools::multizip; /// /// // Iterate over three sequences side-by-side /// let mut xs = [0, 0, 0]; /// let ys = [69, 107, 101]; /// /// for (i, a, b) in multizip((0..100, &mut xs, &ys)) { /// *a = i ^ *b; /// } /// /// assert_eq!(xs, [69, 106, 103]); /// ``` pub fn multizip<T, U>(t: U) -> Zip<T> where Zip<T>: From<U>, Zip<T>: Iterator, { Zip::from(t) } macro_rules! impl_zip_iter { ($($B:ident),*) => ( #[allow(non_snake_case)] impl<$($B: IntoIterator),*> From<($($B,)*)> for Zip<($($B::IntoIter,)*)> { fn from(t: ($($B,)*)) -> Self { let ($($B,)*) = t; Zip { t: ($($B.into_iter(),)*) } } } #[allow(non_snake_case)] #[allow(unused_assignments)] impl<$($B),*> Iterator for Zip<($($B,)*)> where $( $B: Iterator, )* { type Item = ($($B::Item,)*); fn next(&mut self) -> Option<Self::Item> { let ($(ref mut $B,)*) = self.t; // NOTE: Just like iter::Zip, we check the iterators // for None in order. We may finish unevenly (some // iterators gave n + 1 elements, some only n). $( let $B = match $B.next() { None => return None, Some(elt) => elt }; )* Some(($($B,)*)) } fn size_hint(&self) -> (usize, Option<usize>) { let sh = (::std::usize::MAX, None); let ($(ref $B,)*) = self.t; $( let sh = size_hint::min($B.size_hint(), sh); )* sh } } #[allow(non_snake_case)] impl<$($B),*> ExactSizeIterator for Zip<($($B,)*)> where $( $B: ExactSizeIterator, )* { } ); } impl_zip_iter!(A); impl_zip_iter!(A, B); impl_zip_iter!(A, B, C); impl_zip_iter!(A, B, C, D); impl_zip_iter!(A, B, C, D, E); impl_zip_iter!(A, B, C, D, E, F); impl_zip_iter!(A, B, C, D, E, F, G); impl_zip_iter!(A, B, C, D, E, F, G, H);
new
identifier_name
totaleq.rs
// Copyright 2013 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. use ast::{MetaItem, Item, Expr}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; pub fn expand_deriving_totaleq(cx: &ExtCtxt, span: Span, mitem: @MetaItem, in_items: ~[@Item]) -> ~[@Item] { fn cs_equals(cx: &ExtCtxt, span: Span, substr: &Substructure) -> @Expr
let trait_def = TraitDef { cx: cx, span: span, path: Path::new(~["std", "cmp", "TotalEq"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ MethodDef { name: "equals", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: ~[borrowed_self()], ret_ty: Literal(Path::new(~["bool"])), inline: true, const_nonmatching: true, combine_substructure: cs_equals } ] }; trait_def.expand(mitem, in_items) }
{ cs_and(|cx, span, _, _| cx.expr_bool(span, false), cx, span, substr) }
identifier_body
totaleq.rs
// Copyright 2013 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. use ast::{MetaItem, Item, Expr}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; pub fn
(cx: &ExtCtxt, span: Span, mitem: @MetaItem, in_items: ~[@Item]) -> ~[@Item] { fn cs_equals(cx: &ExtCtxt, span: Span, substr: &Substructure) -> @Expr { cs_and(|cx, span, _, _| cx.expr_bool(span, false), cx, span, substr) } let trait_def = TraitDef { cx: cx, span: span, path: Path::new(~["std", "cmp", "TotalEq"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ MethodDef { name: "equals", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: ~[borrowed_self()], ret_ty: Literal(Path::new(~["bool"])), inline: true, const_nonmatching: true, combine_substructure: cs_equals } ] }; trait_def.expand(mitem, in_items) }
expand_deriving_totaleq
identifier_name
totaleq.rs
// Copyright 2013 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. use ast::{MetaItem, Item, Expr}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; pub fn expand_deriving_totaleq(cx: &ExtCtxt, span: Span, mitem: @MetaItem, in_items: ~[@Item]) -> ~[@Item] { fn cs_equals(cx: &ExtCtxt, span: Span, substr: &Substructure) -> @Expr { cs_and(|cx, span, _, _| cx.expr_bool(span, false), cx, span, substr) } let trait_def = TraitDef { cx: cx, span: span, path: Path::new(~["std", "cmp", "TotalEq"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ MethodDef { name: "equals", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: ~[borrowed_self()], ret_ty: Literal(Path::new(~["bool"])), inline: true, const_nonmatching: true, combine_substructure: cs_equals
} ] }; trait_def.expand(mitem, in_items) }
random_line_split
sprites.rs
use sdl2::rect::Rect; use sdl2::video::Window; use sdl2::render::{Texture, Canvas}; pub struct Sprite<'a> { rect: Rect, pub size: Rect, texture: &'a Texture, } impl<'a> Sprite<'a> { pub fn
(&self, x: i32, y: i32, canvas: &mut Canvas<Window>) { let pos_rect = Rect::new(x, y, self.size.width(), self.size.height()); match canvas.copy(&self.texture, Some(self.rect), Some(pos_rect)) { Err(e) => println!("canvas copy error: {}", e), _ => {} } } } pub struct SpriteSheet { pub sprite_width: u32, pub sprite_height: u32, padding: u32, pub texture: Texture, } impl SpriteSheet { pub fn new(texture: Texture, sprite_width: u32, sprite_height: u32, padding: u32) -> Self { SpriteSheet { sprite_width, sprite_height, padding, texture: texture, } } // Creates a sprite object pub fn get_sprite(&self, index: usize) -> Sprite { let texture_query = self.texture.query(); let sheet_width = texture_query.width; let columns = sheet_width / (self.sprite_width + self.padding); let sheet_x = index as u32 % columns; let sheet_y = index as u32 / columns; let px = sheet_x * (self.sprite_width + self.padding); let py = sheet_y * (self.sprite_height + self.padding); Sprite { rect: Rect::new(px as i32, py as i32, self.sprite_width, self.sprite_height), size: Rect::new(0, 0, self.sprite_width, self.sprite_height), texture: &self.texture, } } }
draw
identifier_name
sprites.rs
use sdl2::rect::Rect; use sdl2::video::Window; use sdl2::render::{Texture, Canvas}; pub struct Sprite<'a> { rect: Rect, pub size: Rect, texture: &'a Texture, } impl<'a> Sprite<'a> { pub fn draw(&self, x: i32, y: i32, canvas: &mut Canvas<Window>) { let pos_rect = Rect::new(x, y, self.size.width(), self.size.height()); match canvas.copy(&self.texture, Some(self.rect), Some(pos_rect)) { Err(e) => println!("canvas copy error: {}", e), _ =>
} } } pub struct SpriteSheet { pub sprite_width: u32, pub sprite_height: u32, padding: u32, pub texture: Texture, } impl SpriteSheet { pub fn new(texture: Texture, sprite_width: u32, sprite_height: u32, padding: u32) -> Self { SpriteSheet { sprite_width, sprite_height, padding, texture: texture, } } // Creates a sprite object pub fn get_sprite(&self, index: usize) -> Sprite { let texture_query = self.texture.query(); let sheet_width = texture_query.width; let columns = sheet_width / (self.sprite_width + self.padding); let sheet_x = index as u32 % columns; let sheet_y = index as u32 / columns; let px = sheet_x * (self.sprite_width + self.padding); let py = sheet_y * (self.sprite_height + self.padding); Sprite { rect: Rect::new(px as i32, py as i32, self.sprite_width, self.sprite_height), size: Rect::new(0, 0, self.sprite_width, self.sprite_height), texture: &self.texture, } } }
{}
conditional_block
sprites.rs
use sdl2::rect::Rect; use sdl2::video::Window; use sdl2::render::{Texture, Canvas}; pub struct Sprite<'a> { rect: Rect, pub size: Rect, texture: &'a Texture, } impl<'a> Sprite<'a> { pub fn draw(&self, x: i32, y: i32, canvas: &mut Canvas<Window>) { let pos_rect = Rect::new(x, y, self.size.width(), self.size.height()); match canvas.copy(&self.texture, Some(self.rect), Some(pos_rect)) { Err(e) => println!("canvas copy error: {}", e), _ => {} } } } pub struct SpriteSheet { pub sprite_width: u32, pub sprite_height: u32, padding: u32, pub texture: Texture, } impl SpriteSheet { pub fn new(texture: Texture, sprite_width: u32, sprite_height: u32, padding: u32) -> Self { SpriteSheet { sprite_width,
} // Creates a sprite object pub fn get_sprite(&self, index: usize) -> Sprite { let texture_query = self.texture.query(); let sheet_width = texture_query.width; let columns = sheet_width / (self.sprite_width + self.padding); let sheet_x = index as u32 % columns; let sheet_y = index as u32 / columns; let px = sheet_x * (self.sprite_width + self.padding); let py = sheet_y * (self.sprite_height + self.padding); Sprite { rect: Rect::new(px as i32, py as i32, self.sprite_width, self.sprite_height), size: Rect::new(0, 0, self.sprite_width, self.sprite_height), texture: &self.texture, } } }
sprite_height, padding, texture: texture, }
random_line_split
sprites.rs
use sdl2::rect::Rect; use sdl2::video::Window; use sdl2::render::{Texture, Canvas}; pub struct Sprite<'a> { rect: Rect, pub size: Rect, texture: &'a Texture, } impl<'a> Sprite<'a> { pub fn draw(&self, x: i32, y: i32, canvas: &mut Canvas<Window>)
} pub struct SpriteSheet { pub sprite_width: u32, pub sprite_height: u32, padding: u32, pub texture: Texture, } impl SpriteSheet { pub fn new(texture: Texture, sprite_width: u32, sprite_height: u32, padding: u32) -> Self { SpriteSheet { sprite_width, sprite_height, padding, texture: texture, } } // Creates a sprite object pub fn get_sprite(&self, index: usize) -> Sprite { let texture_query = self.texture.query(); let sheet_width = texture_query.width; let columns = sheet_width / (self.sprite_width + self.padding); let sheet_x = index as u32 % columns; let sheet_y = index as u32 / columns; let px = sheet_x * (self.sprite_width + self.padding); let py = sheet_y * (self.sprite_height + self.padding); Sprite { rect: Rect::new(px as i32, py as i32, self.sprite_width, self.sprite_height), size: Rect::new(0, 0, self.sprite_width, self.sprite_height), texture: &self.texture, } } }
{ let pos_rect = Rect::new(x, y, self.size.width(), self.size.height()); match canvas.copy(&self.texture, Some(self.rect), Some(pos_rect)) { Err(e) => println!("canvas copy error: {}", e), _ => {} } }
identifier_body
motion.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 https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS Motion Path. use crate::values::specified::SVGPathData; /// The <size> in ray() function. /// /// https://drafts.fxtf.org/motion-1/#valdef-offsetpath-size #[allow(missing_docs)] #[derive( Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(u8)] pub enum
{ ClosestSide, ClosestCorner, FarthestSide, FarthestCorner, Sides, } /// The `ray()` function, `ray( [ <angle> && <size> && contain? ] )` /// /// https://drafts.fxtf.org/motion-1/#valdef-offsetpath-ray #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C)] pub struct RayFunction<Angle> { /// The bearing angle with `0deg` pointing up and positive angles /// representing clockwise rotation. pub angle: Angle, /// Decide the path length used when `offset-distance` is expressed /// as a percentage. #[animation(constant)] pub size: RaySize, /// Clamp `offset-distance` so that the box is entirely contained /// within the path. #[animation(constant)] #[css(represents_keyword)] pub contain: bool, } /// The offset-path value. /// /// https://drafts.fxtf.org/motion-1/#offset-path-property #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericOffsetPath<Angle> { // We could merge SVGPathData into ShapeSource, so we could reuse them. However, // we don't want to support other value for offset-path, so use SVGPathData only for now. /// Path value for path(<string>). #[css(function)] Path(SVGPathData), /// ray() function, which defines a path in the polar coordinate system. #[css(function)] Ray(RayFunction<Angle>), /// None value. #[animation(error)] None, // Bug 1186329: Implement <basic-shape>, <geometry-box>, and <url>. } pub use self::GenericOffsetPath as OffsetPath; impl<Angle> OffsetPath<Angle> { /// Return None. #[inline] pub fn none() -> Self { OffsetPath::None } }
RaySize
identifier_name
motion.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 https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS Motion Path. use crate::values::specified::SVGPathData; /// The <size> in ray() function. /// /// https://drafts.fxtf.org/motion-1/#valdef-offsetpath-size #[allow(missing_docs)] #[derive( Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(u8)] pub enum RaySize { ClosestSide, ClosestCorner, FarthestSide, FarthestCorner, Sides, } /// The `ray()` function, `ray( [ <angle> && <size> && contain? ] )` /// /// https://drafts.fxtf.org/motion-1/#valdef-offsetpath-ray #[derive( Animate, Clone, ComputeSquaredDistance, Debug,
ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C)] pub struct RayFunction<Angle> { /// The bearing angle with `0deg` pointing up and positive angles /// representing clockwise rotation. pub angle: Angle, /// Decide the path length used when `offset-distance` is expressed /// as a percentage. #[animation(constant)] pub size: RaySize, /// Clamp `offset-distance` so that the box is entirely contained /// within the path. #[animation(constant)] #[css(represents_keyword)] pub contain: bool, } /// The offset-path value. /// /// https://drafts.fxtf.org/motion-1/#offset-path-property #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericOffsetPath<Angle> { // We could merge SVGPathData into ShapeSource, so we could reuse them. However, // we don't want to support other value for offset-path, so use SVGPathData only for now. /// Path value for path(<string>). #[css(function)] Path(SVGPathData), /// ray() function, which defines a path in the polar coordinate system. #[css(function)] Ray(RayFunction<Angle>), /// None value. #[animation(error)] None, // Bug 1186329: Implement <basic-shape>, <geometry-box>, and <url>. } pub use self::GenericOffsetPath as OffsetPath; impl<Angle> OffsetPath<Angle> { /// Return None. #[inline] pub fn none() -> Self { OffsetPath::None } }
MallocSizeOf, PartialEq, SpecifiedValueInfo,
random_line_split
read_exact.rs
use crate::io::AsyncRead; use futures_core::future::Future; use futures_core::ready; use futures_core::task::{Context, Poll}; use std::io; use std::mem; use std::pin::Pin; /// Future for the [`read_exact`](super::AsyncReadExt::read_exact) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct ReadExact<'a, R:?Sized> { reader: &'a mut R, buf: &'a mut [u8], } impl<R:?Sized + Unpin> Unpin for ReadExact<'_, R> {} impl<'a, R: AsyncRead +?Sized + Unpin> ReadExact<'a, R> { pub(super) fn new(reader: &'a mut R, buf: &'a mut [u8]) -> Self { Self { reader, buf } } } impl<R: AsyncRead +?Sized + Unpin> Future for ReadExact<'_, R> { type Output = io::Result<()>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = &mut *self; while!this.buf.is_empty() { let n = ready!(Pin::new(&mut this.reader).poll_read(cx, this.buf))?;
return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())); } } Poll::Ready(Ok(())) } }
{ let (_, rest) = mem::replace(&mut this.buf, &mut []).split_at_mut(n); this.buf = rest; } if n == 0 {
random_line_split
read_exact.rs
use crate::io::AsyncRead; use futures_core::future::Future; use futures_core::ready; use futures_core::task::{Context, Poll}; use std::io; use std::mem; use std::pin::Pin; /// Future for the [`read_exact`](super::AsyncReadExt::read_exact) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct ReadExact<'a, R:?Sized> { reader: &'a mut R, buf: &'a mut [u8], } impl<R:?Sized + Unpin> Unpin for ReadExact<'_, R> {} impl<'a, R: AsyncRead +?Sized + Unpin> ReadExact<'a, R> { pub(super) fn new(reader: &'a mut R, buf: &'a mut [u8]) -> Self { Self { reader, buf } } } impl<R: AsyncRead +?Sized + Unpin> Future for ReadExact<'_, R> { type Output = io::Result<()>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = &mut *self; while!this.buf.is_empty() { let n = ready!(Pin::new(&mut this.reader).poll_read(cx, this.buf))?; { let (_, rest) = mem::replace(&mut this.buf, &mut []).split_at_mut(n); this.buf = rest; } if n == 0
} Poll::Ready(Ok(())) } }
{ return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())); }
conditional_block
read_exact.rs
use crate::io::AsyncRead; use futures_core::future::Future; use futures_core::ready; use futures_core::task::{Context, Poll}; use std::io; use std::mem; use std::pin::Pin; /// Future for the [`read_exact`](super::AsyncReadExt::read_exact) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct ReadExact<'a, R:?Sized> { reader: &'a mut R, buf: &'a mut [u8], } impl<R:?Sized + Unpin> Unpin for ReadExact<'_, R> {} impl<'a, R: AsyncRead +?Sized + Unpin> ReadExact<'a, R> { pub(super) fn new(reader: &'a mut R, buf: &'a mut [u8]) -> Self { Self { reader, buf } } } impl<R: AsyncRead +?Sized + Unpin> Future for ReadExact<'_, R> { type Output = io::Result<()>; fn
(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = &mut *self; while!this.buf.is_empty() { let n = ready!(Pin::new(&mut this.reader).poll_read(cx, this.buf))?; { let (_, rest) = mem::replace(&mut this.buf, &mut []).split_at_mut(n); this.buf = rest; } if n == 0 { return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())); } } Poll::Ready(Ok(())) } }
poll
identifier_name
read_exact.rs
use crate::io::AsyncRead; use futures_core::future::Future; use futures_core::ready; use futures_core::task::{Context, Poll}; use std::io; use std::mem; use std::pin::Pin; /// Future for the [`read_exact`](super::AsyncReadExt::read_exact) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct ReadExact<'a, R:?Sized> { reader: &'a mut R, buf: &'a mut [u8], } impl<R:?Sized + Unpin> Unpin for ReadExact<'_, R> {} impl<'a, R: AsyncRead +?Sized + Unpin> ReadExact<'a, R> { pub(super) fn new(reader: &'a mut R, buf: &'a mut [u8]) -> Self { Self { reader, buf } } } impl<R: AsyncRead +?Sized + Unpin> Future for ReadExact<'_, R> { type Output = io::Result<()>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>
}
{ let this = &mut *self; while !this.buf.is_empty() { let n = ready!(Pin::new(&mut this.reader).poll_read(cx, this.buf))?; { let (_, rest) = mem::replace(&mut this.buf, &mut []).split_at_mut(n); this.buf = rest; } if n == 0 { return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())); } } Poll::Ready(Ok(())) }
identifier_body
fs.rs
// Copyright 2015 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. //! Unix-specific extensions to primitives in the `std::fs` module. #![stable(feature = "rust1", since = "1.0.0")] use prelude::v1::*; use fs::{self, Permissions, OpenOptions}; use io; use mem; use os::raw::c_long; use os::unix::raw; use path::Path; use sys::platform; use sys; use sys_common::{FromInner, AsInner, AsInnerMut}; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const USER_READ: raw::mode_t = 0o400; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const USER_WRITE: raw::mode_t = 0o200; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const USER_EXECUTE: raw::mode_t = 0o100; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const USER_RWX: raw::mode_t = 0o700; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const GROUP_READ: raw::mode_t = 0o040; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const GROUP_WRITE: raw::mode_t = 0o020; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const GROUP_EXECUTE: raw::mode_t = 0o010; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const GROUP_RWX: raw::mode_t = 0o070; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const OTHER_READ: raw::mode_t = 0o004; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const OTHER_WRITE: raw::mode_t = 0o002; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const OTHER_EXECUTE: raw::mode_t = 0o001; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const OTHER_RWX: raw::mode_t = 0o007; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const ALL_READ: raw::mode_t = 0o444; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const ALL_WRITE: raw::mode_t = 0o222; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const ALL_EXECUTE: raw::mode_t = 0o111; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const ALL_RWX: raw::mode_t = 0o777; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const SETUID: raw::mode_t = 0o4000; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const SETGID: raw::mode_t = 0o2000; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const STICKY_BIT: raw::mode_t = 0o1000; /// Unix-specific extensions to `Permissions` #[unstable(feature = "fs_ext", reason = "may want a more useful mode abstraction")] pub trait PermissionsExt { fn mode(&self) -> raw::mode_t; fn set_mode(&mut self, mode: raw::mode_t); fn from_mode(mode: raw::mode_t) -> Self; } impl PermissionsExt for Permissions { fn mode(&self) -> raw::mode_t { self.as_inner().mode() } fn set_mode(&mut self, mode: raw::mode_t) { *self = FromInner::from_inner(FromInner::from_inner(mode)); } fn from_mode(mode: raw::mode_t) -> Permissions { FromInner::from_inner(FromInner::from_inner(mode)) } } /// Unix-specific extensions to `OpenOptions` #[unstable(feature = "fs_ext", reason = "may want a more useful mode abstraction")] pub trait OpenOptionsExt { /// Sets the mode bits that a new file will be created with. /// /// If a new file is created as part of a `File::open_opts` call then this /// specified `mode` will be used as the permission bits for the new file. fn mode(&mut self, mode: raw::mode_t) -> &mut Self; } impl OpenOptionsExt for OpenOptions { fn mode(&mut self, mode: raw::mode_t) -> &mut OpenOptions { self.as_inner_mut().mode(mode); self } } #[unstable(feature = "metadata_ext", reason = "recently added API")] pub struct Metadata(sys::fs::FileAttr); #[unstable(feature = "metadata_ext", reason = "recently added API")] pub trait MetadataExt { fn as_raw(&self) -> &Metadata; } impl MetadataExt for fs::Metadata { fn as_raw(&self) -> &Metadata { let inner: &sys::fs::FileAttr = self.as_inner(); unsafe { mem::transmute(inner) } } } impl AsInner<platform::raw::stat> for Metadata { fn as_inner(&self) -> &platform::raw::stat { self.0.as_inner() } } // Hm, why are there casts here to the returned type, shouldn't the types always // be the same? Right you are! Turns out, however, on android at least the types // in the raw `stat` structure are not the same as the types being returned. Who // knew! // // As a result to make sure this compiles for all platforms we do the manual // casts and rely on manual lowering to `stat` if the raw type is desired. #[unstable(feature = "metadata_ext", reason = "recently added API")] impl Metadata { pub fn dev(&self) -> raw::dev_t { self.0.raw().st_dev as raw::dev_t } pub fn ino(&self) -> raw::ino_t { self.0.raw().st_ino as raw::ino_t } pub fn mode(&self) -> raw::mode_t { self.0.raw().st_mode as raw::mode_t } pub fn nlink(&self) -> raw::nlink_t { self.0.raw().st_nlink as raw::nlink_t } pub fn uid(&self) -> raw::uid_t { self.0.raw().st_uid as raw::uid_t } pub fn gid(&self) -> raw::gid_t { self.0.raw().st_gid as raw::gid_t } pub fn rdev(&self) -> raw::dev_t { self.0.raw().st_rdev as raw::dev_t } pub fn size(&self) -> raw::off_t { self.0.raw().st_size as raw::off_t } pub fn atime(&self) -> raw::time_t { self.0.raw().st_atime } pub fn atime_nsec(&self) -> c_long { self.0.raw().st_atime_nsec as c_long } pub fn mtime(&self) -> raw::time_t { self.0.raw().st_mtime } pub fn
(&self) -> c_long { self.0.raw().st_mtime_nsec as c_long } pub fn ctime(&self) -> raw::time_t { self.0.raw().st_ctime } pub fn ctime_nsec(&self) -> c_long { self.0.raw().st_ctime_nsec as c_long } pub fn blksize(&self) -> raw::blksize_t { self.0.raw().st_blksize as raw::blksize_t } pub fn blocks(&self) -> raw::blkcnt_t { self.0.raw().st_blocks as raw::blkcnt_t } } #[unstable(feature = "dir_entry_ext", reason = "recently added API")] pub trait DirEntryExt { fn ino(&self) -> raw::ino_t; } impl DirEntryExt for fs::DirEntry { fn ino(&self) -> raw::ino_t { self.as_inner().ino() } } /// Creates a new symbolic link on the filesystem. /// /// The `dst` path will be a symbolic link pointing to the `src` path. /// /// # Note /// /// On Windows, you must specify whether a symbolic link points to a file /// or directory. Use `os::windows::fs::symlink_file` to create a /// symbolic link to a file, or `os::windows::fs::symlink_dir` to create a /// symbolic link to a directory. Additionally, the process must have /// `SeCreateSymbolicLinkPrivilege` in order to be able to create a /// symbolic link. /// /// # Examples /// /// ``` /// use std::os::unix::fs; /// /// # fn foo() -> std::io::Result<()> { /// try!(fs::symlink("a.txt", "b.txt")); /// # Ok(()) /// # } /// ``` #[stable(feature = "symlink", since = "1.1.0")] pub fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> { sys::fs::symlink(src.as_ref(), dst.as_ref()) } #[unstable(feature = "dir_builder", reason = "recently added API")] /// An extension trait for `fs::DirBuilder` for unix-specific options. pub trait DirBuilderExt { /// Sets the mode to create new directories with. This option defaults to /// 0o777. fn mode(&mut self, mode: raw::mode_t) -> &mut Self; } impl DirBuilderExt for fs::DirBuilder { fn mode(&mut self, mode: raw::mode_t) -> &mut fs::DirBuilder { self.as_inner_mut().set_mode(mode); self } }
mtime_nsec
identifier_name
fs.rs
// Copyright 2015 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. //! Unix-specific extensions to primitives in the `std::fs` module. #![stable(feature = "rust1", since = "1.0.0")] use prelude::v1::*; use fs::{self, Permissions, OpenOptions}; use io; use mem; use os::raw::c_long; use os::unix::raw; use path::Path; use sys::platform; use sys; use sys_common::{FromInner, AsInner, AsInnerMut}; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const USER_READ: raw::mode_t = 0o400; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const USER_WRITE: raw::mode_t = 0o200; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const USER_EXECUTE: raw::mode_t = 0o100; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const USER_RWX: raw::mode_t = 0o700; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const GROUP_READ: raw::mode_t = 0o040; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const GROUP_WRITE: raw::mode_t = 0o020; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const GROUP_EXECUTE: raw::mode_t = 0o010; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const GROUP_RWX: raw::mode_t = 0o070; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const OTHER_READ: raw::mode_t = 0o004; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const OTHER_WRITE: raw::mode_t = 0o002; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const OTHER_EXECUTE: raw::mode_t = 0o001; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const OTHER_RWX: raw::mode_t = 0o007; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const ALL_READ: raw::mode_t = 0o444; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const ALL_WRITE: raw::mode_t = 0o222; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const ALL_EXECUTE: raw::mode_t = 0o111; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const ALL_RWX: raw::mode_t = 0o777; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const SETUID: raw::mode_t = 0o4000; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const SETGID: raw::mode_t = 0o2000; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const STICKY_BIT: raw::mode_t = 0o1000; /// Unix-specific extensions to `Permissions` #[unstable(feature = "fs_ext", reason = "may want a more useful mode abstraction")] pub trait PermissionsExt { fn mode(&self) -> raw::mode_t; fn set_mode(&mut self, mode: raw::mode_t); fn from_mode(mode: raw::mode_t) -> Self; } impl PermissionsExt for Permissions { fn mode(&self) -> raw::mode_t { self.as_inner().mode() } fn set_mode(&mut self, mode: raw::mode_t) { *self = FromInner::from_inner(FromInner::from_inner(mode)); } fn from_mode(mode: raw::mode_t) -> Permissions { FromInner::from_inner(FromInner::from_inner(mode)) } } /// Unix-specific extensions to `OpenOptions` #[unstable(feature = "fs_ext", reason = "may want a more useful mode abstraction")] pub trait OpenOptionsExt { /// Sets the mode bits that a new file will be created with. /// /// If a new file is created as part of a `File::open_opts` call then this /// specified `mode` will be used as the permission bits for the new file. fn mode(&mut self, mode: raw::mode_t) -> &mut Self; } impl OpenOptionsExt for OpenOptions { fn mode(&mut self, mode: raw::mode_t) -> &mut OpenOptions { self.as_inner_mut().mode(mode); self } } #[unstable(feature = "metadata_ext", reason = "recently added API")] pub struct Metadata(sys::fs::FileAttr); #[unstable(feature = "metadata_ext", reason = "recently added API")] pub trait MetadataExt { fn as_raw(&self) -> &Metadata; } impl MetadataExt for fs::Metadata { fn as_raw(&self) -> &Metadata { let inner: &sys::fs::FileAttr = self.as_inner(); unsafe { mem::transmute(inner) } } } impl AsInner<platform::raw::stat> for Metadata { fn as_inner(&self) -> &platform::raw::stat { self.0.as_inner() } } // Hm, why are there casts here to the returned type, shouldn't the types always // be the same? Right you are! Turns out, however, on android at least the types // in the raw `stat` structure are not the same as the types being returned. Who // knew! // // As a result to make sure this compiles for all platforms we do the manual // casts and rely on manual lowering to `stat` if the raw type is desired. #[unstable(feature = "metadata_ext", reason = "recently added API")] impl Metadata { pub fn dev(&self) -> raw::dev_t { self.0.raw().st_dev as raw::dev_t } pub fn ino(&self) -> raw::ino_t { self.0.raw().st_ino as raw::ino_t } pub fn mode(&self) -> raw::mode_t { self.0.raw().st_mode as raw::mode_t } pub fn nlink(&self) -> raw::nlink_t { self.0.raw().st_nlink as raw::nlink_t } pub fn uid(&self) -> raw::uid_t { self.0.raw().st_uid as raw::uid_t } pub fn gid(&self) -> raw::gid_t { self.0.raw().st_gid as raw::gid_t } pub fn rdev(&self) -> raw::dev_t { self.0.raw().st_rdev as raw::dev_t } pub fn size(&self) -> raw::off_t { self.0.raw().st_size as raw::off_t } pub fn atime(&self) -> raw::time_t { self.0.raw().st_atime } pub fn atime_nsec(&self) -> c_long { self.0.raw().st_atime_nsec as c_long } pub fn mtime(&self) -> raw::time_t { self.0.raw().st_mtime } pub fn mtime_nsec(&self) -> c_long { self.0.raw().st_mtime_nsec as c_long } pub fn ctime(&self) -> raw::time_t { self.0.raw().st_ctime } pub fn ctime_nsec(&self) -> c_long { self.0.raw().st_ctime_nsec as c_long } pub fn blksize(&self) -> raw::blksize_t { self.0.raw().st_blksize as raw::blksize_t } pub fn blocks(&self) -> raw::blkcnt_t { self.0.raw().st_blocks as raw::blkcnt_t } } #[unstable(feature = "dir_entry_ext", reason = "recently added API")] pub trait DirEntryExt { fn ino(&self) -> raw::ino_t; } impl DirEntryExt for fs::DirEntry { fn ino(&self) -> raw::ino_t { self.as_inner().ino() } } /// Creates a new symbolic link on the filesystem. /// /// The `dst` path will be a symbolic link pointing to the `src` path. /// /// # Note /// /// On Windows, you must specify whether a symbolic link points to a file /// or directory. Use `os::windows::fs::symlink_file` to create a /// symbolic link to a file, or `os::windows::fs::symlink_dir` to create a /// symbolic link to a directory. Additionally, the process must have /// `SeCreateSymbolicLinkPrivilege` in order to be able to create a /// symbolic link. /// /// # Examples /// /// ``` /// use std::os::unix::fs; /// /// # fn foo() -> std::io::Result<()> { /// try!(fs::symlink("a.txt", "b.txt")); /// # Ok(()) /// # } /// ``` #[stable(feature = "symlink", since = "1.1.0")] pub fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()>
#[unstable(feature = "dir_builder", reason = "recently added API")] /// An extension trait for `fs::DirBuilder` for unix-specific options. pub trait DirBuilderExt { /// Sets the mode to create new directories with. This option defaults to /// 0o777. fn mode(&mut self, mode: raw::mode_t) -> &mut Self; } impl DirBuilderExt for fs::DirBuilder { fn mode(&mut self, mode: raw::mode_t) -> &mut fs::DirBuilder { self.as_inner_mut().set_mode(mode); self } }
{ sys::fs::symlink(src.as_ref(), dst.as_ref()) }
identifier_body
fs.rs
// Copyright 2015 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. //! Unix-specific extensions to primitives in the `std::fs` module. #![stable(feature = "rust1", since = "1.0.0")] use prelude::v1::*; use fs::{self, Permissions, OpenOptions}; use io; use mem; use os::raw::c_long; use os::unix::raw; use path::Path; use sys::platform; use sys; use sys_common::{FromInner, AsInner, AsInnerMut}; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const USER_READ: raw::mode_t = 0o400; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const USER_WRITE: raw::mode_t = 0o200; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const USER_EXECUTE: raw::mode_t = 0o100; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const USER_RWX: raw::mode_t = 0o700; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const GROUP_READ: raw::mode_t = 0o040; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const GROUP_WRITE: raw::mode_t = 0o020; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const GROUP_EXECUTE: raw::mode_t = 0o010; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const GROUP_RWX: raw::mode_t = 0o070; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const OTHER_READ: raw::mode_t = 0o004; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const OTHER_WRITE: raw::mode_t = 0o002; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const OTHER_EXECUTE: raw::mode_t = 0o001; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const OTHER_RWX: raw::mode_t = 0o007; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const ALL_READ: raw::mode_t = 0o444; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const ALL_WRITE: raw::mode_t = 0o222; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const ALL_EXECUTE: raw::mode_t = 0o111; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const ALL_RWX: raw::mode_t = 0o777; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const SETUID: raw::mode_t = 0o4000; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const SETGID: raw::mode_t = 0o2000; #[unstable(feature = "fs_mode", reason = "recently added API")] pub const STICKY_BIT: raw::mode_t = 0o1000; /// Unix-specific extensions to `Permissions` #[unstable(feature = "fs_ext", reason = "may want a more useful mode abstraction")] pub trait PermissionsExt { fn mode(&self) -> raw::mode_t; fn set_mode(&mut self, mode: raw::mode_t); fn from_mode(mode: raw::mode_t) -> Self; } impl PermissionsExt for Permissions { fn mode(&self) -> raw::mode_t { self.as_inner().mode() } fn set_mode(&mut self, mode: raw::mode_t) { *self = FromInner::from_inner(FromInner::from_inner(mode)); } fn from_mode(mode: raw::mode_t) -> Permissions { FromInner::from_inner(FromInner::from_inner(mode)) } } /// Unix-specific extensions to `OpenOptions` #[unstable(feature = "fs_ext", reason = "may want a more useful mode abstraction")] pub trait OpenOptionsExt { /// Sets the mode bits that a new file will be created with. /// /// If a new file is created as part of a `File::open_opts` call then this /// specified `mode` will be used as the permission bits for the new file. fn mode(&mut self, mode: raw::mode_t) -> &mut Self; } impl OpenOptionsExt for OpenOptions { fn mode(&mut self, mode: raw::mode_t) -> &mut OpenOptions { self.as_inner_mut().mode(mode); self } } #[unstable(feature = "metadata_ext", reason = "recently added API")] pub struct Metadata(sys::fs::FileAttr); #[unstable(feature = "metadata_ext", reason = "recently added API")] pub trait MetadataExt { fn as_raw(&self) -> &Metadata; } impl MetadataExt for fs::Metadata { fn as_raw(&self) -> &Metadata { let inner: &sys::fs::FileAttr = self.as_inner(); unsafe { mem::transmute(inner) } } } impl AsInner<platform::raw::stat> for Metadata { fn as_inner(&self) -> &platform::raw::stat { self.0.as_inner() } } // Hm, why are there casts here to the returned type, shouldn't the types always // be the same? Right you are! Turns out, however, on android at least the types // in the raw `stat` structure are not the same as the types being returned. Who // knew! // // As a result to make sure this compiles for all platforms we do the manual // casts and rely on manual lowering to `stat` if the raw type is desired. #[unstable(feature = "metadata_ext", reason = "recently added API")]
impl Metadata { pub fn dev(&self) -> raw::dev_t { self.0.raw().st_dev as raw::dev_t } pub fn ino(&self) -> raw::ino_t { self.0.raw().st_ino as raw::ino_t } pub fn mode(&self) -> raw::mode_t { self.0.raw().st_mode as raw::mode_t } pub fn nlink(&self) -> raw::nlink_t { self.0.raw().st_nlink as raw::nlink_t } pub fn uid(&self) -> raw::uid_t { self.0.raw().st_uid as raw::uid_t } pub fn gid(&self) -> raw::gid_t { self.0.raw().st_gid as raw::gid_t } pub fn rdev(&self) -> raw::dev_t { self.0.raw().st_rdev as raw::dev_t } pub fn size(&self) -> raw::off_t { self.0.raw().st_size as raw::off_t } pub fn atime(&self) -> raw::time_t { self.0.raw().st_atime } pub fn atime_nsec(&self) -> c_long { self.0.raw().st_atime_nsec as c_long } pub fn mtime(&self) -> raw::time_t { self.0.raw().st_mtime } pub fn mtime_nsec(&self) -> c_long { self.0.raw().st_mtime_nsec as c_long } pub fn ctime(&self) -> raw::time_t { self.0.raw().st_ctime } pub fn ctime_nsec(&self) -> c_long { self.0.raw().st_ctime_nsec as c_long } pub fn blksize(&self) -> raw::blksize_t { self.0.raw().st_blksize as raw::blksize_t } pub fn blocks(&self) -> raw::blkcnt_t { self.0.raw().st_blocks as raw::blkcnt_t } } #[unstable(feature = "dir_entry_ext", reason = "recently added API")] pub trait DirEntryExt { fn ino(&self) -> raw::ino_t; } impl DirEntryExt for fs::DirEntry { fn ino(&self) -> raw::ino_t { self.as_inner().ino() } } /// Creates a new symbolic link on the filesystem. /// /// The `dst` path will be a symbolic link pointing to the `src` path. /// /// # Note /// /// On Windows, you must specify whether a symbolic link points to a file /// or directory. Use `os::windows::fs::symlink_file` to create a /// symbolic link to a file, or `os::windows::fs::symlink_dir` to create a /// symbolic link to a directory. Additionally, the process must have /// `SeCreateSymbolicLinkPrivilege` in order to be able to create a /// symbolic link. /// /// # Examples /// /// ``` /// use std::os::unix::fs; /// /// # fn foo() -> std::io::Result<()> { /// try!(fs::symlink("a.txt", "b.txt")); /// # Ok(()) /// # } /// ``` #[stable(feature = "symlink", since = "1.1.0")] pub fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> { sys::fs::symlink(src.as_ref(), dst.as_ref()) } #[unstable(feature = "dir_builder", reason = "recently added API")] /// An extension trait for `fs::DirBuilder` for unix-specific options. pub trait DirBuilderExt { /// Sets the mode to create new directories with. This option defaults to /// 0o777. fn mode(&mut self, mode: raw::mode_t) -> &mut Self; } impl DirBuilderExt for fs::DirBuilder { fn mode(&mut self, mode: raw::mode_t) -> &mut fs::DirBuilder { self.as_inner_mut().set_mode(mode); self } }
random_line_split
greatfet.rs
#![allow(missing_docs)]
use hal::lpc17xx::pin; use hal::pin::Gpio; use hal::pin::GpioDirection; pub struct Led { pin: pin::Pin, } impl Led { pub fn new(idx: u8) -> Led { Led { pin: match idx { 0 => get_led(pin::Port::Port3, 14), 1 => get_led(pin::Port::Port2, 1), 2 => get_led(pin::Port::Port3, 13), 3 => get_led(pin::Port::Port3, 12), _ => unsafe { abort() }, } } } pub fn on(&self) { self.pin.set_low(); } pub fn off(&self) { self.pin.set_high(); } } fn get_led(port: pin::Port, pin: u8) -> pin::Pin { pin::Pin::new( port, pin, pin::Function::Gpio, Some(GpioDirection::Out)) }
use core::intrinsics::abort;
random_line_split
greatfet.rs
#![allow(missing_docs)] use core::intrinsics::abort; use hal::lpc17xx::pin; use hal::pin::Gpio; use hal::pin::GpioDirection; pub struct Led { pin: pin::Pin, } impl Led { pub fn
(idx: u8) -> Led { Led { pin: match idx { 0 => get_led(pin::Port::Port3, 14), 1 => get_led(pin::Port::Port2, 1), 2 => get_led(pin::Port::Port3, 13), 3 => get_led(pin::Port::Port3, 12), _ => unsafe { abort() }, } } } pub fn on(&self) { self.pin.set_low(); } pub fn off(&self) { self.pin.set_high(); } } fn get_led(port: pin::Port, pin: u8) -> pin::Pin { pin::Pin::new( port, pin, pin::Function::Gpio, Some(GpioDirection::Out)) }
new
identifier_name
greatfet.rs
#![allow(missing_docs)] use core::intrinsics::abort; use hal::lpc17xx::pin; use hal::pin::Gpio; use hal::pin::GpioDirection; pub struct Led { pin: pin::Pin, } impl Led { pub fn new(idx: u8) -> Led { Led { pin: match idx { 0 => get_led(pin::Port::Port3, 14), 1 => get_led(pin::Port::Port2, 1), 2 => get_led(pin::Port::Port3, 13), 3 => get_led(pin::Port::Port3, 12), _ => unsafe { abort() }, } } } pub fn on(&self) { self.pin.set_low(); } pub fn off(&self)
} fn get_led(port: pin::Port, pin: u8) -> pin::Pin { pin::Pin::new( port, pin, pin::Function::Gpio, Some(GpioDirection::Out)) }
{ self.pin.set_high(); }
identifier_body
gain.rs
use super::super::api; pub fn information_gain<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, criterion: &api::Criterion<T>) -> f64 { let e = target_entropy(data, view); let fe = entropy(data, view, criterion); e - fe } fn entropy_helper<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, value: bool, criterion: &api::Criterion<T>) -> f64 { let mut total = 0; let mut classes = vec![0; data.target_count]; for index in view.iter() { let record = &data.records[*index]; if criterion(&record.0) == value { classes[record.1 as usize] += 1; total += 1; } } let mut result = 0f64; for class in classes.iter() { if *class!= 0 { let p = (*class as f64) / (total as f64); result += p * p.log2() } } -result } fn entropy<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, criterion: &api::Criterion<T>) -> f64 { let total = data.records.len(); let mut ccs = vec![0u8, 0u8]; let values = vec![false, true]; for index in view.iter() { let record = &data.records[*index]; let i = match criterion(&record.0) { false => 0, true => 1, }; ccs[i] += 1; } let mut result = 0f64; for i in 0..2 { let p = (ccs[i] as f64) / (total as f64); result += p * entropy_helper(data, view, values[i], criterion); } result } fn target_entropy<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView) -> f64
{ let total = data.records.len(); let mut classes = vec![0; data.target_count]; for index in view.iter() { let record = &data.records[*index]; classes[record.1 as usize] += 1; } for class in classes.iter() { if *class == 0 { return 0f64 } } let mut result = 0f64; for class in classes.iter() { let p = (*class as f64) / (total as f64); result += p * p.log2() } -result }
identifier_body
gain.rs
use super::super::api; pub fn
<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, criterion: &api::Criterion<T>) -> f64 { let e = target_entropy(data, view); let fe = entropy(data, view, criterion); e - fe } fn entropy_helper<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, value: bool, criterion: &api::Criterion<T>) -> f64 { let mut total = 0; let mut classes = vec![0; data.target_count]; for index in view.iter() { let record = &data.records[*index]; if criterion(&record.0) == value { classes[record.1 as usize] += 1; total += 1; } } let mut result = 0f64; for class in classes.iter() { if *class!= 0 { let p = (*class as f64) / (total as f64); result += p * p.log2() } } -result } fn entropy<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, criterion: &api::Criterion<T>) -> f64 { let total = data.records.len(); let mut ccs = vec![0u8, 0u8]; let values = vec![false, true]; for index in view.iter() { let record = &data.records[*index]; let i = match criterion(&record.0) { false => 0, true => 1, }; ccs[i] += 1; } let mut result = 0f64; for i in 0..2 { let p = (ccs[i] as f64) / (total as f64); result += p * entropy_helper(data, view, values[i], criterion); } result } fn target_entropy<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView) -> f64 { let total = data.records.len(); let mut classes = vec![0; data.target_count]; for index in view.iter() { let record = &data.records[*index]; classes[record.1 as usize] += 1; } for class in classes.iter() { if *class == 0 { return 0f64 } } let mut result = 0f64; for class in classes.iter() { let p = (*class as f64) / (total as f64); result += p * p.log2() } -result }
information_gain
identifier_name
gain.rs
use super::super::api; pub fn information_gain<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, criterion: &api::Criterion<T>) -> f64 { let e = target_entropy(data, view); let fe = entropy(data, view, criterion); e - fe
fn entropy_helper<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, value: bool, criterion: &api::Criterion<T>) -> f64 { let mut total = 0; let mut classes = vec![0; data.target_count]; for index in view.iter() { let record = &data.records[*index]; if criterion(&record.0) == value { classes[record.1 as usize] += 1; total += 1; } } let mut result = 0f64; for class in classes.iter() { if *class!= 0 { let p = (*class as f64) / (total as f64); result += p * p.log2() } } -result } fn entropy<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, criterion: &api::Criterion<T>) -> f64 { let total = data.records.len(); let mut ccs = vec![0u8, 0u8]; let values = vec![false, true]; for index in view.iter() { let record = &data.records[*index]; let i = match criterion(&record.0) { false => 0, true => 1, }; ccs[i] += 1; } let mut result = 0f64; for i in 0..2 { let p = (ccs[i] as f64) / (total as f64); result += p * entropy_helper(data, view, values[i], criterion); } result } fn target_entropy<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView) -> f64 { let total = data.records.len(); let mut classes = vec![0; data.target_count]; for index in view.iter() { let record = &data.records[*index]; classes[record.1 as usize] += 1; } for class in classes.iter() { if *class == 0 { return 0f64 } } let mut result = 0f64; for class in classes.iter() { let p = (*class as f64) / (total as f64); result += p * p.log2() } -result }
}
random_line_split
cci_impl_lib.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. #![crate_name="cci_impl_lib"] pub trait uint_helpers { fn to<F>(&self, v: uint, f: F) where F: FnMut(uint); } impl uint_helpers for uint { #[inline] fn to<F>(&self, v: uint, mut f: F) where F: FnMut(uint) { let mut i = *self;
i += 1; } } }
while i < v { f(i);
random_line_split
cci_impl_lib.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. #![crate_name="cci_impl_lib"] pub trait uint_helpers { fn to<F>(&self, v: uint, f: F) where F: FnMut(uint); } impl uint_helpers for uint { #[inline] fn
<F>(&self, v: uint, mut f: F) where F: FnMut(uint) { let mut i = *self; while i < v { f(i); i += 1; } } }
to
identifier_name
cci_impl_lib.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. #![crate_name="cci_impl_lib"] pub trait uint_helpers { fn to<F>(&self, v: uint, f: F) where F: FnMut(uint); } impl uint_helpers for uint { #[inline] fn to<F>(&self, v: uint, mut f: F) where F: FnMut(uint)
}
{ let mut i = *self; while i < v { f(i); i += 1; } }
identifier_body
commit.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Helper library for rendering commit info use std::collections::{BTreeMap, HashSet}; use std::io::Write; use anyhow::Error; use chrono::{DateTime, FixedOffset, Local, TimeZone}; use serde_derive::Serialize; use source_control::types as thrift; use crate::args::commit_id::map_commit_ids; use crate::lib::commit_id::render_commit_id; #[derive(Serialize)] pub(crate) struct CommitInfo { pub r#type: String, // For JSON output, always "commit". pub ids: BTreeMap<String, String>, pub parents: Vec<BTreeMap<String, String>>, pub message: String, pub date: DateTime<FixedOffset>, pub timestamp: i64, pub timezone: i32, pub author: String, pub generation: i64, pub extra: BTreeMap<String, String>, pub extra_hex: BTreeMap<String, String>, }
impl TryFrom<&thrift::CommitInfo> for CommitInfo { type Error = Error; fn try_from(commit: &thrift::CommitInfo) -> Result<CommitInfo, Error> { let ids = map_commit_ids(commit.ids.values()); let parents = commit .parents .iter() .map(|ids| map_commit_ids(ids.values())) .collect(); let message = commit.message.clone(); let author = commit.author.clone(); // The commit date is recorded as a timestamp plus timezone pair, where // the timezone is seconds east of UTC. let timestamp = commit.date; let timezone = commit.tz; let date = FixedOffset::east(timezone).timestamp(timestamp, 0); // Extras are binary data, but usually we want to render them as // strings. In the case that they are not UTF-8 strings, they're // probably a commit hash, so we should hex-encode them. Record extras // that are valid UTF-8 as strings, and hex encode the rest. let mut extra = BTreeMap::new(); let mut extra_hex = BTreeMap::new(); for (name, value) in commit.extra.iter() { match std::str::from_utf8(value) { Ok(value) => extra.insert(name.clone(), value.to_string()), Err(_) => extra_hex.insert(name.clone(), faster_hex::hex_string(value)), }; } Ok(CommitInfo { r#type: "commit".to_string(), ids, parents, message, date, timestamp, timezone, author, generation: commit.generation, extra, extra_hex, }) } } pub(crate) fn render_commit_summary( commit: &CommitInfo, requested: &str, schemes: &HashSet<String>, w: &mut dyn Write, ) -> Result<(), Error> { render_commit_id( Some(("Commit", " ")), "\n", &requested, &commit.ids, schemes, w, )?; write!(w, "\n")?; let date = commit.date.to_string(); let local_date = commit.date.with_timezone(&Local).to_string(); if date!= local_date { write!(w, "Date: {} ({})\n", date, local_date)?; } else { write!(w, "Date: {}\n", date)?; } write!(w, "Author: {}\n", commit.author)?; write!( w, "Summary: {}\n", commit.message.lines().next().unwrap_or("") )?; Ok(()) } pub(crate) fn render_commit_info( commit: &CommitInfo, requested: &str, schemes: &HashSet<String>, w: &mut dyn Write, ) -> Result<(), Error> { render_commit_id( Some(("Commit", " ")), "\n", &requested, &commit.ids, schemes, w, )?; write!(w, "\n")?; for (i, parent) in commit.parents.iter().enumerate() { let header = if commit.parents.len() == 1 { "Parent".to_string() } else { format!("Parent-{}", i) }; render_commit_id( Some((&header, " ")), "\n", &format!("Parent {} of {}", i, requested), parent, &schemes, w, )?; write!(w, "\n")?; } let date = commit.date.to_string(); let local_date = commit.date.with_timezone(&Local).to_string(); if date!= local_date { write!(w, "Date: {} ({})\n", date, local_date)?; } else { write!(w, "Date: {}\n", date)?; } write!(w, "Author: {}\n", commit.author)?; write!(w, "Generation: {}\n", commit.generation)?; if!commit.extra.is_empty() { write!(w, "Extra:\n")?; for (name, value) in commit.extra.iter() { write!(w, " {}={}\n", name, value)?; } } if!commit.extra_hex.is_empty() { write!(w, "Extra-Binary:\n")?; for (name, value) in commit.extra_hex.iter() { write!(w, " {}={}\n", name, value)?; } } write!(w, "\n{}\n", commit.message)?; Ok(()) }
random_line_split
commit.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Helper library for rendering commit info use std::collections::{BTreeMap, HashSet}; use std::io::Write; use anyhow::Error; use chrono::{DateTime, FixedOffset, Local, TimeZone}; use serde_derive::Serialize; use source_control::types as thrift; use crate::args::commit_id::map_commit_ids; use crate::lib::commit_id::render_commit_id; #[derive(Serialize)] pub(crate) struct CommitInfo { pub r#type: String, // For JSON output, always "commit". pub ids: BTreeMap<String, String>, pub parents: Vec<BTreeMap<String, String>>, pub message: String, pub date: DateTime<FixedOffset>, pub timestamp: i64, pub timezone: i32, pub author: String, pub generation: i64, pub extra: BTreeMap<String, String>, pub extra_hex: BTreeMap<String, String>, } impl TryFrom<&thrift::CommitInfo> for CommitInfo { type Error = Error; fn
(commit: &thrift::CommitInfo) -> Result<CommitInfo, Error> { let ids = map_commit_ids(commit.ids.values()); let parents = commit .parents .iter() .map(|ids| map_commit_ids(ids.values())) .collect(); let message = commit.message.clone(); let author = commit.author.clone(); // The commit date is recorded as a timestamp plus timezone pair, where // the timezone is seconds east of UTC. let timestamp = commit.date; let timezone = commit.tz; let date = FixedOffset::east(timezone).timestamp(timestamp, 0); // Extras are binary data, but usually we want to render them as // strings. In the case that they are not UTF-8 strings, they're // probably a commit hash, so we should hex-encode them. Record extras // that are valid UTF-8 as strings, and hex encode the rest. let mut extra = BTreeMap::new(); let mut extra_hex = BTreeMap::new(); for (name, value) in commit.extra.iter() { match std::str::from_utf8(value) { Ok(value) => extra.insert(name.clone(), value.to_string()), Err(_) => extra_hex.insert(name.clone(), faster_hex::hex_string(value)), }; } Ok(CommitInfo { r#type: "commit".to_string(), ids, parents, message, date, timestamp, timezone, author, generation: commit.generation, extra, extra_hex, }) } } pub(crate) fn render_commit_summary( commit: &CommitInfo, requested: &str, schemes: &HashSet<String>, w: &mut dyn Write, ) -> Result<(), Error> { render_commit_id( Some(("Commit", " ")), "\n", &requested, &commit.ids, schemes, w, )?; write!(w, "\n")?; let date = commit.date.to_string(); let local_date = commit.date.with_timezone(&Local).to_string(); if date!= local_date { write!(w, "Date: {} ({})\n", date, local_date)?; } else { write!(w, "Date: {}\n", date)?; } write!(w, "Author: {}\n", commit.author)?; write!( w, "Summary: {}\n", commit.message.lines().next().unwrap_or("") )?; Ok(()) } pub(crate) fn render_commit_info( commit: &CommitInfo, requested: &str, schemes: &HashSet<String>, w: &mut dyn Write, ) -> Result<(), Error> { render_commit_id( Some(("Commit", " ")), "\n", &requested, &commit.ids, schemes, w, )?; write!(w, "\n")?; for (i, parent) in commit.parents.iter().enumerate() { let header = if commit.parents.len() == 1 { "Parent".to_string() } else { format!("Parent-{}", i) }; render_commit_id( Some((&header, " ")), "\n", &format!("Parent {} of {}", i, requested), parent, &schemes, w, )?; write!(w, "\n")?; } let date = commit.date.to_string(); let local_date = commit.date.with_timezone(&Local).to_string(); if date!= local_date { write!(w, "Date: {} ({})\n", date, local_date)?; } else { write!(w, "Date: {}\n", date)?; } write!(w, "Author: {}\n", commit.author)?; write!(w, "Generation: {}\n", commit.generation)?; if!commit.extra.is_empty() { write!(w, "Extra:\n")?; for (name, value) in commit.extra.iter() { write!(w, " {}={}\n", name, value)?; } } if!commit.extra_hex.is_empty() { write!(w, "Extra-Binary:\n")?; for (name, value) in commit.extra_hex.iter() { write!(w, " {}={}\n", name, value)?; } } write!(w, "\n{}\n", commit.message)?; Ok(()) }
try_from
identifier_name
broad_phase_filter2.rs
extern crate nalgebra as na; use na::{Isometry2, Point2, RealField, Vector2}; use ncollide2d::broad_phase::BroadPhasePairFilter; use ncollide2d::shape::{Ball, Cuboid, ShapeHandle}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::DefaultJointConstraintSet; use nphysics2d::joint::{FreeJoint, RevoluteJoint}; use nphysics2d::object::{ BodyPartHandle, BodySet, Collider, ColliderAnchor, ColliderDesc, ColliderSet, DefaultBodyHandle, DefaultBodySet, DefaultColliderHandle, DefaultColliderSet, Ground, MultibodyDesc, }; use nphysics2d::world::{ BroadPhasePairFilterSets, DefaultGeometricalWorld, DefaultMechanicalWorld, }; use nphysics_testbed2d::Testbed; struct NoMultibodySelfContactFilter; impl<N, Bodies, Colliders> BroadPhasePairFilter<N, BroadPhasePairFilterSets<'_, N, Bodies, Colliders>> for NoMultibodySelfContactFilter where N: RealField, Bodies: BodySet<N>, Colliders: ColliderSet<N, Bodies::Handle>, { fn is_pair_valid( &self, h1: Colliders::Handle, h2: Colliders::Handle, set: &BroadPhasePairFilterSets<'_, N, Bodies, Colliders>, ) -> bool { let a1 = set.colliders().get(h1).map(|c| c.anchor()); let a2 = set.colliders().get(h2).map(|c| c.anchor()); match (a1, a2) { ( Some(ColliderAnchor::OnBodyPart { body_part: part1,.. }), Some(ColliderAnchor::OnBodyPart { body_part: part2,.. }), ) => part1.0!= part2.0, // Don't collide if the two parts belong to the same body. _ => true, } } } /* * NOTE: The `r` macro is only here to convert from f64 to the `N` scalar type. * This simplifies experimentation with various scalar types (f32, fixed-point numbers, etc.) */ pub fn init_world<N: RealField>(testbed: &mut Testbed<N>) { /* * World */ let mechanical_world = DefaultMechanicalWorld::new(Vector2::new(r!(0.0), r!(-9.81))); let geometrical_world = DefaultGeometricalWorld::new(); let mut bodies = DefaultBodySet::new(); let mut colliders = DefaultColliderSet::new(); let joint_constraints = DefaultJointConstraintSet::new(); let force_generators = DefaultForceGeneratorSet::new(); /* * Ground */ let ground_size = r!(25.0); let ground_shape = ShapeHandle::new(Cuboid::new(Vector2::new(ground_size, r!(1.0)))); let ground_handle = bodies.insert(Ground::new()); let co = ColliderDesc::new(ground_shape) .translation(-Vector2::y()) .build(BodyPartHandle(ground_handle, 0)); colliders.insert(co); /* * Create the ragdolls */ build_ragdolls(&mut bodies, &mut colliders); /* * Run the simulation. */ testbed.set_ground_handle(Some(ground_handle)); testbed.set_broad_phase_pair_filter(NoMultibodySelfContactFilter); testbed.set_world( mechanical_world, geometrical_world, bodies, colliders, joint_constraints, force_generators, ); testbed.look_at(Point2::new(0.0, 5.0), 25.0); } fn build_ragdolls<N: RealField>( bodies: &mut DefaultBodySet<N>, colliders: &mut DefaultColliderSet<N>, ) { let body_rady = r!(1.2); let body_radx = r!(0.2); let head_rad = r!(0.4); let member_rad = r!(0.1); let arm_length = r!(0.9); let leg_length = r!(1.4); let space = r!(0.1); let body_geom = ShapeHandle::new(Cuboid::new(Vector2::new(body_radx, body_rady))); let head_geom = ShapeHandle::new(Ball::new(head_rad)); let arm_geom = ShapeHandle::new(Cuboid::new(Vector2::new(member_rad, arm_length))); let leg_geom = ShapeHandle::new(Cuboid::new(Vector2::new(member_rad, leg_length))); // The position of the free joint will be modified in the // final loop of this function (before we actually build the // ragdoll body into the World. let free = FreeJoint::new(Isometry2::new(Vector2::zeros(), na::zero())); let spherical = RevoluteJoint::new(na::zero()); /* * Body. */ let body_collider = ColliderDesc::new(body_geom).density(r!(0.3)); let mut body = MultibodyDesc::new(free); /* * Head. */ let head_collider = ColliderDesc::new(head_geom).density(r!(0.3)); body.add_child(spherical).set_parent_shift(Vector2::new( r!(0.0), body_rady + head_rad + space * r!(2.0), )); /* * Arms. */ let arm_collider = ColliderDesc::new(arm_geom).density(r!(0.3)); body.add_child(spherical) .set_parent_shift(Vector2::new(body_radx + r!(2.0) * space, body_rady)) .set_body_shift(Vector2::new(r!(0.0), arm_length + space)); body.add_child(spherical) .set_parent_shift(Vector2::new(-body_radx - r!(2.0) * space, body_rady)) .set_body_shift(Vector2::new(r!(0.0), arm_length + space)); /* * Legs. */ let leg_collider = ColliderDesc::new(leg_geom).density(r!(0.3)); body.add_child(spherical) .set_parent_shift(Vector2::new(body_radx, -body_rady)) .set_body_shift(Vector2::new(r!(0.0), leg_length + space)); body.add_child(spherical) .set_parent_shift(Vector2::new(-body_radx, -body_rady)) .set_body_shift(Vector2::new(r!(0.0), leg_length + space)); let n = 5; let shiftx = r!(2.0); let shifty = r!(6.5); for i in 0usize..n { for j in 0usize..n { let x = r!(i as f64) * shiftx - r!(n as f64) * shiftx / r!(2.0); let y = r!(j as f64) * shifty + r!(6.0); let free = FreeJoint::new(Isometry2::translation(x, y)); let ragdoll = body.set_joint(free).build(); let ragdoll_handle = bodies.insert(ragdoll); colliders.insert(body_collider.build(BodyPartHandle(ragdoll_handle, 0))); colliders.insert(head_collider.build(BodyPartHandle(ragdoll_handle, 1))); colliders.insert(arm_collider.build(BodyPartHandle(ragdoll_handle, 2))); colliders.insert(arm_collider.build(BodyPartHandle(ragdoll_handle, 3))); colliders.insert(leg_collider.build(BodyPartHandle(ragdoll_handle, 4))); colliders.insert(leg_collider.build(BodyPartHandle(ragdoll_handle, 5))); } } } fn main()
{ let mut testbed = Testbed::<f32>::new_empty(); init_world(&mut testbed); testbed.run(); }
identifier_body
broad_phase_filter2.rs
extern crate nalgebra as na; use na::{Isometry2, Point2, RealField, Vector2}; use ncollide2d::broad_phase::BroadPhasePairFilter; use ncollide2d::shape::{Ball, Cuboid, ShapeHandle}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::DefaultJointConstraintSet; use nphysics2d::joint::{FreeJoint, RevoluteJoint}; use nphysics2d::object::{ BodyPartHandle, BodySet, Collider, ColliderAnchor, ColliderDesc, ColliderSet, DefaultBodyHandle, DefaultBodySet, DefaultColliderHandle, DefaultColliderSet, Ground, MultibodyDesc, }; use nphysics2d::world::{ BroadPhasePairFilterSets, DefaultGeometricalWorld, DefaultMechanicalWorld, }; use nphysics_testbed2d::Testbed; struct
; impl<N, Bodies, Colliders> BroadPhasePairFilter<N, BroadPhasePairFilterSets<'_, N, Bodies, Colliders>> for NoMultibodySelfContactFilter where N: RealField, Bodies: BodySet<N>, Colliders: ColliderSet<N, Bodies::Handle>, { fn is_pair_valid( &self, h1: Colliders::Handle, h2: Colliders::Handle, set: &BroadPhasePairFilterSets<'_, N, Bodies, Colliders>, ) -> bool { let a1 = set.colliders().get(h1).map(|c| c.anchor()); let a2 = set.colliders().get(h2).map(|c| c.anchor()); match (a1, a2) { ( Some(ColliderAnchor::OnBodyPart { body_part: part1,.. }), Some(ColliderAnchor::OnBodyPart { body_part: part2,.. }), ) => part1.0!= part2.0, // Don't collide if the two parts belong to the same body. _ => true, } } } /* * NOTE: The `r` macro is only here to convert from f64 to the `N` scalar type. * This simplifies experimentation with various scalar types (f32, fixed-point numbers, etc.) */ pub fn init_world<N: RealField>(testbed: &mut Testbed<N>) { /* * World */ let mechanical_world = DefaultMechanicalWorld::new(Vector2::new(r!(0.0), r!(-9.81))); let geometrical_world = DefaultGeometricalWorld::new(); let mut bodies = DefaultBodySet::new(); let mut colliders = DefaultColliderSet::new(); let joint_constraints = DefaultJointConstraintSet::new(); let force_generators = DefaultForceGeneratorSet::new(); /* * Ground */ let ground_size = r!(25.0); let ground_shape = ShapeHandle::new(Cuboid::new(Vector2::new(ground_size, r!(1.0)))); let ground_handle = bodies.insert(Ground::new()); let co = ColliderDesc::new(ground_shape) .translation(-Vector2::y()) .build(BodyPartHandle(ground_handle, 0)); colliders.insert(co); /* * Create the ragdolls */ build_ragdolls(&mut bodies, &mut colliders); /* * Run the simulation. */ testbed.set_ground_handle(Some(ground_handle)); testbed.set_broad_phase_pair_filter(NoMultibodySelfContactFilter); testbed.set_world( mechanical_world, geometrical_world, bodies, colliders, joint_constraints, force_generators, ); testbed.look_at(Point2::new(0.0, 5.0), 25.0); } fn build_ragdolls<N: RealField>( bodies: &mut DefaultBodySet<N>, colliders: &mut DefaultColliderSet<N>, ) { let body_rady = r!(1.2); let body_radx = r!(0.2); let head_rad = r!(0.4); let member_rad = r!(0.1); let arm_length = r!(0.9); let leg_length = r!(1.4); let space = r!(0.1); let body_geom = ShapeHandle::new(Cuboid::new(Vector2::new(body_radx, body_rady))); let head_geom = ShapeHandle::new(Ball::new(head_rad)); let arm_geom = ShapeHandle::new(Cuboid::new(Vector2::new(member_rad, arm_length))); let leg_geom = ShapeHandle::new(Cuboid::new(Vector2::new(member_rad, leg_length))); // The position of the free joint will be modified in the // final loop of this function (before we actually build the // ragdoll body into the World. let free = FreeJoint::new(Isometry2::new(Vector2::zeros(), na::zero())); let spherical = RevoluteJoint::new(na::zero()); /* * Body. */ let body_collider = ColliderDesc::new(body_geom).density(r!(0.3)); let mut body = MultibodyDesc::new(free); /* * Head. */ let head_collider = ColliderDesc::new(head_geom).density(r!(0.3)); body.add_child(spherical).set_parent_shift(Vector2::new( r!(0.0), body_rady + head_rad + space * r!(2.0), )); /* * Arms. */ let arm_collider = ColliderDesc::new(arm_geom).density(r!(0.3)); body.add_child(spherical) .set_parent_shift(Vector2::new(body_radx + r!(2.0) * space, body_rady)) .set_body_shift(Vector2::new(r!(0.0), arm_length + space)); body.add_child(spherical) .set_parent_shift(Vector2::new(-body_radx - r!(2.0) * space, body_rady)) .set_body_shift(Vector2::new(r!(0.0), arm_length + space)); /* * Legs. */ let leg_collider = ColliderDesc::new(leg_geom).density(r!(0.3)); body.add_child(spherical) .set_parent_shift(Vector2::new(body_radx, -body_rady)) .set_body_shift(Vector2::new(r!(0.0), leg_length + space)); body.add_child(spherical) .set_parent_shift(Vector2::new(-body_radx, -body_rady)) .set_body_shift(Vector2::new(r!(0.0), leg_length + space)); let n = 5; let shiftx = r!(2.0); let shifty = r!(6.5); for i in 0usize..n { for j in 0usize..n { let x = r!(i as f64) * shiftx - r!(n as f64) * shiftx / r!(2.0); let y = r!(j as f64) * shifty + r!(6.0); let free = FreeJoint::new(Isometry2::translation(x, y)); let ragdoll = body.set_joint(free).build(); let ragdoll_handle = bodies.insert(ragdoll); colliders.insert(body_collider.build(BodyPartHandle(ragdoll_handle, 0))); colliders.insert(head_collider.build(BodyPartHandle(ragdoll_handle, 1))); colliders.insert(arm_collider.build(BodyPartHandle(ragdoll_handle, 2))); colliders.insert(arm_collider.build(BodyPartHandle(ragdoll_handle, 3))); colliders.insert(leg_collider.build(BodyPartHandle(ragdoll_handle, 4))); colliders.insert(leg_collider.build(BodyPartHandle(ragdoll_handle, 5))); } } } fn main() { let mut testbed = Testbed::<f32>::new_empty(); init_world(&mut testbed); testbed.run(); }
NoMultibodySelfContactFilter
identifier_name
broad_phase_filter2.rs
extern crate nalgebra as na; use na::{Isometry2, Point2, RealField, Vector2}; use ncollide2d::broad_phase::BroadPhasePairFilter; use ncollide2d::shape::{Ball, Cuboid, ShapeHandle}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::DefaultJointConstraintSet; use nphysics2d::joint::{FreeJoint, RevoluteJoint}; use nphysics2d::object::{ BodyPartHandle, BodySet, Collider, ColliderAnchor, ColliderDesc, ColliderSet, DefaultBodyHandle, DefaultBodySet, DefaultColliderHandle, DefaultColliderSet, Ground, MultibodyDesc, }; use nphysics2d::world::{ BroadPhasePairFilterSets, DefaultGeometricalWorld, DefaultMechanicalWorld, }; use nphysics_testbed2d::Testbed; struct NoMultibodySelfContactFilter; impl<N, Bodies, Colliders> BroadPhasePairFilter<N, BroadPhasePairFilterSets<'_, N, Bodies, Colliders>> for NoMultibodySelfContactFilter where N: RealField, Bodies: BodySet<N>, Colliders: ColliderSet<N, Bodies::Handle>, { fn is_pair_valid( &self, h1: Colliders::Handle, h2: Colliders::Handle, set: &BroadPhasePairFilterSets<'_, N, Bodies, Colliders>, ) -> bool { let a1 = set.colliders().get(h1).map(|c| c.anchor()); let a2 = set.colliders().get(h2).map(|c| c.anchor()); match (a1, a2) { ( Some(ColliderAnchor::OnBodyPart { body_part: part1,.. }), Some(ColliderAnchor::OnBodyPart { body_part: part2,.. }), ) => part1.0!= part2.0, // Don't collide if the two parts belong to the same body. _ => true, } } }
* This simplifies experimentation with various scalar types (f32, fixed-point numbers, etc.) */ pub fn init_world<N: RealField>(testbed: &mut Testbed<N>) { /* * World */ let mechanical_world = DefaultMechanicalWorld::new(Vector2::new(r!(0.0), r!(-9.81))); let geometrical_world = DefaultGeometricalWorld::new(); let mut bodies = DefaultBodySet::new(); let mut colliders = DefaultColliderSet::new(); let joint_constraints = DefaultJointConstraintSet::new(); let force_generators = DefaultForceGeneratorSet::new(); /* * Ground */ let ground_size = r!(25.0); let ground_shape = ShapeHandle::new(Cuboid::new(Vector2::new(ground_size, r!(1.0)))); let ground_handle = bodies.insert(Ground::new()); let co = ColliderDesc::new(ground_shape) .translation(-Vector2::y()) .build(BodyPartHandle(ground_handle, 0)); colliders.insert(co); /* * Create the ragdolls */ build_ragdolls(&mut bodies, &mut colliders); /* * Run the simulation. */ testbed.set_ground_handle(Some(ground_handle)); testbed.set_broad_phase_pair_filter(NoMultibodySelfContactFilter); testbed.set_world( mechanical_world, geometrical_world, bodies, colliders, joint_constraints, force_generators, ); testbed.look_at(Point2::new(0.0, 5.0), 25.0); } fn build_ragdolls<N: RealField>( bodies: &mut DefaultBodySet<N>, colliders: &mut DefaultColliderSet<N>, ) { let body_rady = r!(1.2); let body_radx = r!(0.2); let head_rad = r!(0.4); let member_rad = r!(0.1); let arm_length = r!(0.9); let leg_length = r!(1.4); let space = r!(0.1); let body_geom = ShapeHandle::new(Cuboid::new(Vector2::new(body_radx, body_rady))); let head_geom = ShapeHandle::new(Ball::new(head_rad)); let arm_geom = ShapeHandle::new(Cuboid::new(Vector2::new(member_rad, arm_length))); let leg_geom = ShapeHandle::new(Cuboid::new(Vector2::new(member_rad, leg_length))); // The position of the free joint will be modified in the // final loop of this function (before we actually build the // ragdoll body into the World. let free = FreeJoint::new(Isometry2::new(Vector2::zeros(), na::zero())); let spherical = RevoluteJoint::new(na::zero()); /* * Body. */ let body_collider = ColliderDesc::new(body_geom).density(r!(0.3)); let mut body = MultibodyDesc::new(free); /* * Head. */ let head_collider = ColliderDesc::new(head_geom).density(r!(0.3)); body.add_child(spherical).set_parent_shift(Vector2::new( r!(0.0), body_rady + head_rad + space * r!(2.0), )); /* * Arms. */ let arm_collider = ColliderDesc::new(arm_geom).density(r!(0.3)); body.add_child(spherical) .set_parent_shift(Vector2::new(body_radx + r!(2.0) * space, body_rady)) .set_body_shift(Vector2::new(r!(0.0), arm_length + space)); body.add_child(spherical) .set_parent_shift(Vector2::new(-body_radx - r!(2.0) * space, body_rady)) .set_body_shift(Vector2::new(r!(0.0), arm_length + space)); /* * Legs. */ let leg_collider = ColliderDesc::new(leg_geom).density(r!(0.3)); body.add_child(spherical) .set_parent_shift(Vector2::new(body_radx, -body_rady)) .set_body_shift(Vector2::new(r!(0.0), leg_length + space)); body.add_child(spherical) .set_parent_shift(Vector2::new(-body_radx, -body_rady)) .set_body_shift(Vector2::new(r!(0.0), leg_length + space)); let n = 5; let shiftx = r!(2.0); let shifty = r!(6.5); for i in 0usize..n { for j in 0usize..n { let x = r!(i as f64) * shiftx - r!(n as f64) * shiftx / r!(2.0); let y = r!(j as f64) * shifty + r!(6.0); let free = FreeJoint::new(Isometry2::translation(x, y)); let ragdoll = body.set_joint(free).build(); let ragdoll_handle = bodies.insert(ragdoll); colliders.insert(body_collider.build(BodyPartHandle(ragdoll_handle, 0))); colliders.insert(head_collider.build(BodyPartHandle(ragdoll_handle, 1))); colliders.insert(arm_collider.build(BodyPartHandle(ragdoll_handle, 2))); colliders.insert(arm_collider.build(BodyPartHandle(ragdoll_handle, 3))); colliders.insert(leg_collider.build(BodyPartHandle(ragdoll_handle, 4))); colliders.insert(leg_collider.build(BodyPartHandle(ragdoll_handle, 5))); } } } fn main() { let mut testbed = Testbed::<f32>::new_empty(); init_world(&mut testbed); testbed.run(); }
/* * NOTE: The `r` macro is only here to convert from f64 to the `N` scalar type.
random_line_split
websocket.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::InheritTypes::EventTargetCast; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::WebSocketBinding; use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketMethods; use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketConstants; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{Temporary, JSRef}; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::eventtarget::{EventTarget, EventTargetHelpers, WebSocketTypeId}; use servo_net::resource_task::{Load, LoadData, LoadResponse}; use servo_util::str::DOMString; use std::ascii::IntoBytes; use std::comm::channel; use url::Url; #[dom_struct] pub struct WebSocket { eventtarget: EventTarget, url: DOMString, response: LoadResponse, state: u16 } impl WebSocket { pub fn new_inherited(url: DOMString, resp: LoadResponse, state_value: u16) -> WebSocket { WebSocket { eventtarget: EventTarget::new_inherited(WebSocketTypeId), url: url, response: resp, state: state_value } } pub fn
(global: &GlobalRef, url: DOMString) -> Temporary<WebSocket> { let resource_task = global.resource_task(); let ws_url = Url::parse(url.as_slice()).unwrap(); let(start_chan, start_port) = channel(); resource_task.send(Load(LoadData::new(ws_url), start_chan)); let resp = start_port.recv(); reflect_dom_object(box WebSocket::new_inherited(url, resp, WebSocketConstants::OPEN), global, WebSocketBinding::Wrap) } pub fn Constructor(global: &GlobalRef, url: DOMString) -> Fallible<Temporary<WebSocket>> { Ok(WebSocket::new(global, url)) } } impl Reflectable for WebSocket { fn reflector<'a>(&'a self) -> &'a Reflector { self.eventtarget.reflector() } } impl<'a> WebSocketMethods for JSRef<'a, WebSocket> { event_handler!(open, GetOnopen, SetOnopen) event_handler!(error, GetOnerror, SetOnerror) event_handler!(close, GetOnclose, SetOnclose) event_handler!(message, GetOnmessage, SetOnmessage) fn Send(self, message: DOMString) { if self.state == WebSocketConstants::OPEN { let message_u8: Vec<u8>=message.to_string().into_bytes(); assert!(message.len() <= 125); let mut payload: Vec<u8> = Vec::with_capacity(2 + message_u8.len()); /* We are sending a single framed unmasked text message. Referring to http://tools.ietf.org/html/rfc6455#section-5.7. 10000001 this indicates FIN bit=1 and the opcode is 0001 which means it is a text frame and the decimal equivalent is 129 */ const ENTRY1: u8 = 0x81; payload.push(ENTRY1); payload.push(message.len() as u8); payload.push_all(message_u8.as_slice()); } else { return; } } fn Close(self) { } fn Url(self) -> DOMString { self.url.clone() } }
new
identifier_name
websocket.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::InheritTypes::EventTargetCast; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::WebSocketBinding; use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketMethods; use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketConstants; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{Temporary, JSRef}; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::eventtarget::{EventTarget, EventTargetHelpers, WebSocketTypeId}; use servo_net::resource_task::{Load, LoadData, LoadResponse}; use servo_util::str::DOMString; use std::ascii::IntoBytes; use std::comm::channel; use url::Url; #[dom_struct] pub struct WebSocket { eventtarget: EventTarget, url: DOMString, response: LoadResponse, state: u16 } impl WebSocket { pub fn new_inherited(url: DOMString, resp: LoadResponse, state_value: u16) -> WebSocket { WebSocket { eventtarget: EventTarget::new_inherited(WebSocketTypeId), url: url, response: resp, state: state_value } } pub fn new(global: &GlobalRef, url: DOMString) -> Temporary<WebSocket>
pub fn Constructor(global: &GlobalRef, url: DOMString) -> Fallible<Temporary<WebSocket>> { Ok(WebSocket::new(global, url)) } } impl Reflectable for WebSocket { fn reflector<'a>(&'a self) -> &'a Reflector { self.eventtarget.reflector() } } impl<'a> WebSocketMethods for JSRef<'a, WebSocket> { event_handler!(open, GetOnopen, SetOnopen) event_handler!(error, GetOnerror, SetOnerror) event_handler!(close, GetOnclose, SetOnclose) event_handler!(message, GetOnmessage, SetOnmessage) fn Send(self, message: DOMString) { if self.state == WebSocketConstants::OPEN { let message_u8: Vec<u8>=message.to_string().into_bytes(); assert!(message.len() <= 125); let mut payload: Vec<u8> = Vec::with_capacity(2 + message_u8.len()); /* We are sending a single framed unmasked text message. Referring to http://tools.ietf.org/html/rfc6455#section-5.7. 10000001 this indicates FIN bit=1 and the opcode is 0001 which means it is a text frame and the decimal equivalent is 129 */ const ENTRY1: u8 = 0x81; payload.push(ENTRY1); payload.push(message.len() as u8); payload.push_all(message_u8.as_slice()); } else { return; } } fn Close(self) { } fn Url(self) -> DOMString { self.url.clone() } }
{ let resource_task = global.resource_task(); let ws_url = Url::parse(url.as_slice()).unwrap(); let(start_chan, start_port) = channel(); resource_task.send(Load(LoadData::new(ws_url), start_chan)); let resp = start_port.recv(); reflect_dom_object(box WebSocket::new_inherited(url, resp, WebSocketConstants::OPEN), global, WebSocketBinding::Wrap) }
identifier_body
websocket.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::InheritTypes::EventTargetCast; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::WebSocketBinding; use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketMethods; use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketConstants; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{Temporary, JSRef}; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::eventtarget::{EventTarget, EventTargetHelpers, WebSocketTypeId}; use servo_net::resource_task::{Load, LoadData, LoadResponse}; use servo_util::str::DOMString; use std::ascii::IntoBytes; use std::comm::channel; use url::Url; #[dom_struct] pub struct WebSocket { eventtarget: EventTarget, url: DOMString, response: LoadResponse, state: u16 } impl WebSocket { pub fn new_inherited(url: DOMString, resp: LoadResponse, state_value: u16) -> WebSocket { WebSocket { eventtarget: EventTarget::new_inherited(WebSocketTypeId), url: url, response: resp, state: state_value } } pub fn new(global: &GlobalRef, url: DOMString) -> Temporary<WebSocket> { let resource_task = global.resource_task(); let ws_url = Url::parse(url.as_slice()).unwrap(); let(start_chan, start_port) = channel(); resource_task.send(Load(LoadData::new(ws_url), start_chan)); let resp = start_port.recv(); reflect_dom_object(box WebSocket::new_inherited(url, resp, WebSocketConstants::OPEN), global, WebSocketBinding::Wrap) } pub fn Constructor(global: &GlobalRef, url: DOMString) -> Fallible<Temporary<WebSocket>> { Ok(WebSocket::new(global, url)) } } impl Reflectable for WebSocket { fn reflector<'a>(&'a self) -> &'a Reflector { self.eventtarget.reflector() } } impl<'a> WebSocketMethods for JSRef<'a, WebSocket> { event_handler!(open, GetOnopen, SetOnopen) event_handler!(error, GetOnerror, SetOnerror) event_handler!(close, GetOnclose, SetOnclose) event_handler!(message, GetOnmessage, SetOnmessage) fn Send(self, message: DOMString) { if self.state == WebSocketConstants::OPEN { let message_u8: Vec<u8>=message.to_string().into_bytes(); assert!(message.len() <= 125); let mut payload: Vec<u8> = Vec::with_capacity(2 + message_u8.len()); /* We are sending a single framed unmasked text message. Referring to http://tools.ietf.org/html/rfc6455#section-5.7. 10000001 this indicates FIN bit=1 and the opcode is 0001 which means it is a text frame and the decimal equivalent is 129 */ const ENTRY1: u8 = 0x81; payload.push(ENTRY1); payload.push(message.len() as u8); payload.push_all(message_u8.as_slice()); } else
} fn Close(self) { } fn Url(self) -> DOMString { self.url.clone() } }
{ return; }
conditional_block
websocket.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::InheritTypes::EventTargetCast; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::WebSocketBinding; use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketMethods; use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketConstants; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{Temporary, JSRef}; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::eventtarget::{EventTarget, EventTargetHelpers, WebSocketTypeId}; use servo_net::resource_task::{Load, LoadData, LoadResponse}; use servo_util::str::DOMString; use std::ascii::IntoBytes; use std::comm::channel; use url::Url; #[dom_struct] pub struct WebSocket { eventtarget: EventTarget, url: DOMString, response: LoadResponse, state: u16 } impl WebSocket { pub fn new_inherited(url: DOMString, resp: LoadResponse, state_value: u16) -> WebSocket { WebSocket { eventtarget: EventTarget::new_inherited(WebSocketTypeId), url: url, response: resp, state: state_value } } pub fn new(global: &GlobalRef, url: DOMString) -> Temporary<WebSocket> { let resource_task = global.resource_task(); let ws_url = Url::parse(url.as_slice()).unwrap(); let(start_chan, start_port) = channel(); resource_task.send(Load(LoadData::new(ws_url), start_chan)); let resp = start_port.recv(); reflect_dom_object(box WebSocket::new_inherited(url, resp, WebSocketConstants::OPEN), global, WebSocketBinding::Wrap) } pub fn Constructor(global: &GlobalRef, url: DOMString) -> Fallible<Temporary<WebSocket>> { Ok(WebSocket::new(global, url)) } } impl Reflectable for WebSocket { fn reflector<'a>(&'a self) -> &'a Reflector { self.eventtarget.reflector() } } impl<'a> WebSocketMethods for JSRef<'a, WebSocket> { event_handler!(open, GetOnopen, SetOnopen) event_handler!(error, GetOnerror, SetOnerror) event_handler!(close, GetOnclose, SetOnclose) event_handler!(message, GetOnmessage, SetOnmessage) fn Send(self, message: DOMString) { if self.state == WebSocketConstants::OPEN { let message_u8: Vec<u8>=message.to_string().into_bytes(); assert!(message.len() <= 125); let mut payload: Vec<u8> = Vec::with_capacity(2 + message_u8.len()); /* We are sending a single framed unmasked text message. Referring to http://tools.ietf.org/html/rfc6455#section-5.7. 10000001 this indicates FIN bit=1 and the opcode is 0001 which means it is a text frame and the decimal equivalent is 129 */ const ENTRY1: u8 = 0x81; payload.push(ENTRY1); payload.push(message.len() as u8); payload.push_all(message_u8.as_slice()); } else { return; } } fn Close(self) { } fn Url(self) -> DOMString { self.url.clone() } }
random_line_split
exterior.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. #![feature(managed_boxes)] use std::cell::Cell; use std::gc::{Gc, GC}; struct Point {x: int, y: int, z: int} fn f(p: Gc<Cell<Point>>)
pub fn main() { let a: Point = Point {x: 10, y: 11, z: 12}; let b: Gc<Cell<Point>> = box(GC) Cell::new(a); assert_eq!(b.get().z, 12); f(b); assert_eq!(a.z, 12); assert_eq!(b.get().z, 13); }
{ assert!((p.get().z == 12)); p.set(Point {x: 10, y: 11, z: 13}); assert!((p.get().z == 13)); }
identifier_body
exterior.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. #![feature(managed_boxes)] use std::cell::Cell; use std::gc::{Gc, GC};
fn f(p: Gc<Cell<Point>>) { assert!((p.get().z == 12)); p.set(Point {x: 10, y: 11, z: 13}); assert!((p.get().z == 13)); } pub fn main() { let a: Point = Point {x: 10, y: 11, z: 12}; let b: Gc<Cell<Point>> = box(GC) Cell::new(a); assert_eq!(b.get().z, 12); f(b); assert_eq!(a.z, 12); assert_eq!(b.get().z, 13); }
struct Point {x: int, y: int, z: int}
random_line_split
exterior.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. #![feature(managed_boxes)] use std::cell::Cell; use std::gc::{Gc, GC}; struct Point {x: int, y: int, z: int} fn f(p: Gc<Cell<Point>>) { assert!((p.get().z == 12)); p.set(Point {x: 10, y: 11, z: 13}); assert!((p.get().z == 13)); } pub fn
() { let a: Point = Point {x: 10, y: 11, z: 12}; let b: Gc<Cell<Point>> = box(GC) Cell::new(a); assert_eq!(b.get().z, 12); f(b); assert_eq!(a.z, 12); assert_eq!(b.get().z, 13); }
main
identifier_name