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 |
---|---|---|---|---|
cat-file.rs | extern crate gitters;
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
use gitters::cli;
use gitters::commits;
use gitters::objects;
use gitters::revisions;
const USAGE: &'static str = "
cat-file - Provide content or type and size information for repository objects
Usage:
cat-file -t <object>
cat-file -s <object>
cat-file -e <object>
cat-file -p <object>
cat-file (-h | --help)
Options:
-h --help Show this screen.
-t Instead of the content, show the object type identified by <object>.
-s Instead of the content, show the object size identified by <object>.
-e Surpress all output; instead exit with zero status if <object> exists and is a valid
object.
-p Pretty-print the contents of <object> based on its type.
";
#[derive(RustcDecodable)]
struct Args {
flag_t: bool,
flag_s: bool,
flag_e: bool,
flag_p: bool,
arg_object: String,
}
fn show_type(name: &objects::Name) -> cli::Result {
let header = try!(cli::wrap_with_status(objects::read_header(&name), 1));
let object_type = match header.object_type {
objects::Type::Blob => "blob",
objects::Type::Tree => "tree",
objects::Type::Commit => "commit",
};
println!("{}", object_type);
cli::success()
}
fn show_size(name: &objects::Name) -> cli::Result {
let header = try!(cli::wrap_with_status(objects::read_header(&name), 1));
println!("{}", header.content_length);
cli::success()
}
fn check_validity(name: &objects::Name) -> cli::Result {
try!(cli::wrap_with_status(objects::read_header(&name), 1)); | fn show_contents(name: &objects::Name) -> cli::Result {
let obj = try!(cli::wrap_with_status(objects::read_object(&name), 1));
match obj {
objects::Object::Commit(commit) => {
let objects::Name(name) = commit.name;
println!("commit {}", name);
let objects::Name(tree) = commit.tree;
println!("tree : {}", tree);
if commit.parent.is_some() {
let objects::Name(parent) = commit.parent.unwrap();
println!("parent : {}", parent);
}
let commits::CommitUser { name, date } = commit.author;
println!("author : {} at {}", name, date);
let commits::CommitUser { name, date } = commit.committer;
println!("committer: {} at {}", name, date);
println!("");
println!("{}", commit.message);
},
objects::Object::Blob(contents) => {
// Don't use println, as we don't want to include an extra newline at the end of the
// blob contents.
print!("{}", contents);
},
_ => { /* Not handled yet */ }
}
cli::success()
}
fn dispatch_for_args(args: &Args) -> cli::Result {
let name = try!(cli::wrap_with_status(revisions::resolve(&args.arg_object), 1));
if args.flag_t {
show_type(&name)
} else if args.flag_s {
show_size(&name)
} else if args.flag_e {
check_validity(&name)
} else if args.flag_p {
show_contents(&name)
} else {
Err(cli::Error { message: "No flags specified".to_string(), status: 2 })
}
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
cli::exit_with(dispatch_for_args(&args))
} | cli::success()
}
| random_line_split |
cat-file.rs | extern crate gitters;
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
use gitters::cli;
use gitters::commits;
use gitters::objects;
use gitters::revisions;
const USAGE: &'static str = "
cat-file - Provide content or type and size information for repository objects
Usage:
cat-file -t <object>
cat-file -s <object>
cat-file -e <object>
cat-file -p <object>
cat-file (-h | --help)
Options:
-h --help Show this screen.
-t Instead of the content, show the object type identified by <object>.
-s Instead of the content, show the object size identified by <object>.
-e Surpress all output; instead exit with zero status if <object> exists and is a valid
object.
-p Pretty-print the contents of <object> based on its type.
";
#[derive(RustcDecodable)]
struct Args {
flag_t: bool,
flag_s: bool,
flag_e: bool,
flag_p: bool,
arg_object: String,
}
fn show_type(name: &objects::Name) -> cli::Result {
let header = try!(cli::wrap_with_status(objects::read_header(&name), 1));
let object_type = match header.object_type {
objects::Type::Blob => "blob",
objects::Type::Tree => "tree",
objects::Type::Commit => "commit",
};
println!("{}", object_type);
cli::success()
}
fn show_size(name: &objects::Name) -> cli::Result {
let header = try!(cli::wrap_with_status(objects::read_header(&name), 1));
println!("{}", header.content_length);
cli::success()
}
fn check_validity(name: &objects::Name) -> cli::Result {
try!(cli::wrap_with_status(objects::read_header(&name), 1));
cli::success()
}
fn show_contents(name: &objects::Name) -> cli::Result {
let obj = try!(cli::wrap_with_status(objects::read_object(&name), 1));
match obj {
objects::Object::Commit(commit) => {
let objects::Name(name) = commit.name;
println!("commit {}", name);
let objects::Name(tree) = commit.tree;
println!("tree : {}", tree);
if commit.parent.is_some() {
let objects::Name(parent) = commit.parent.unwrap();
println!("parent : {}", parent);
}
let commits::CommitUser { name, date } = commit.author;
println!("author : {} at {}", name, date);
let commits::CommitUser { name, date } = commit.committer;
println!("committer: {} at {}", name, date);
println!("");
println!("{}", commit.message);
},
objects::Object::Blob(contents) => {
// Don't use println, as we don't want to include an extra newline at the end of the
// blob contents.
print!("{}", contents);
},
_ => { /* Not handled yet */ }
}
cli::success()
}
fn dispatch_for_args(args: &Args) -> cli::Result {
let name = try!(cli::wrap_with_status(revisions::resolve(&args.arg_object), 1));
if args.flag_t | else if args.flag_s {
show_size(&name)
} else if args.flag_e {
check_validity(&name)
} else if args.flag_p {
show_contents(&name)
} else {
Err(cli::Error { message: "No flags specified".to_string(), status: 2 })
}
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
cli::exit_with(dispatch_for_args(&args))
}
| {
show_type(&name)
} | conditional_block |
cat-file.rs | extern crate gitters;
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
use gitters::cli;
use gitters::commits;
use gitters::objects;
use gitters::revisions;
const USAGE: &'static str = "
cat-file - Provide content or type and size information for repository objects
Usage:
cat-file -t <object>
cat-file -s <object>
cat-file -e <object>
cat-file -p <object>
cat-file (-h | --help)
Options:
-h --help Show this screen.
-t Instead of the content, show the object type identified by <object>.
-s Instead of the content, show the object size identified by <object>.
-e Surpress all output; instead exit with zero status if <object> exists and is a valid
object.
-p Pretty-print the contents of <object> based on its type.
";
#[derive(RustcDecodable)]
struct Args {
flag_t: bool,
flag_s: bool,
flag_e: bool,
flag_p: bool,
arg_object: String,
}
fn show_type(name: &objects::Name) -> cli::Result {
let header = try!(cli::wrap_with_status(objects::read_header(&name), 1));
let object_type = match header.object_type {
objects::Type::Blob => "blob",
objects::Type::Tree => "tree",
objects::Type::Commit => "commit",
};
println!("{}", object_type);
cli::success()
}
fn show_size(name: &objects::Name) -> cli::Result {
let header = try!(cli::wrap_with_status(objects::read_header(&name), 1));
println!("{}", header.content_length);
cli::success()
}
fn check_validity(name: &objects::Name) -> cli::Result {
try!(cli::wrap_with_status(objects::read_header(&name), 1));
cli::success()
}
fn | (name: &objects::Name) -> cli::Result {
let obj = try!(cli::wrap_with_status(objects::read_object(&name), 1));
match obj {
objects::Object::Commit(commit) => {
let objects::Name(name) = commit.name;
println!("commit {}", name);
let objects::Name(tree) = commit.tree;
println!("tree : {}", tree);
if commit.parent.is_some() {
let objects::Name(parent) = commit.parent.unwrap();
println!("parent : {}", parent);
}
let commits::CommitUser { name, date } = commit.author;
println!("author : {} at {}", name, date);
let commits::CommitUser { name, date } = commit.committer;
println!("committer: {} at {}", name, date);
println!("");
println!("{}", commit.message);
},
objects::Object::Blob(contents) => {
// Don't use println, as we don't want to include an extra newline at the end of the
// blob contents.
print!("{}", contents);
},
_ => { /* Not handled yet */ }
}
cli::success()
}
fn dispatch_for_args(args: &Args) -> cli::Result {
let name = try!(cli::wrap_with_status(revisions::resolve(&args.arg_object), 1));
if args.flag_t {
show_type(&name)
} else if args.flag_s {
show_size(&name)
} else if args.flag_e {
check_validity(&name)
} else if args.flag_p {
show_contents(&name)
} else {
Err(cli::Error { message: "No flags specified".to_string(), status: 2 })
}
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
cli::exit_with(dispatch_for_args(&args))
}
| show_contents | identifier_name |
cat-file.rs | extern crate gitters;
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
use gitters::cli;
use gitters::commits;
use gitters::objects;
use gitters::revisions;
const USAGE: &'static str = "
cat-file - Provide content or type and size information for repository objects
Usage:
cat-file -t <object>
cat-file -s <object>
cat-file -e <object>
cat-file -p <object>
cat-file (-h | --help)
Options:
-h --help Show this screen.
-t Instead of the content, show the object type identified by <object>.
-s Instead of the content, show the object size identified by <object>.
-e Surpress all output; instead exit with zero status if <object> exists and is a valid
object.
-p Pretty-print the contents of <object> based on its type.
";
#[derive(RustcDecodable)]
struct Args {
flag_t: bool,
flag_s: bool,
flag_e: bool,
flag_p: bool,
arg_object: String,
}
fn show_type(name: &objects::Name) -> cli::Result {
let header = try!(cli::wrap_with_status(objects::read_header(&name), 1));
let object_type = match header.object_type {
objects::Type::Blob => "blob",
objects::Type::Tree => "tree",
objects::Type::Commit => "commit",
};
println!("{}", object_type);
cli::success()
}
fn show_size(name: &objects::Name) -> cli::Result {
let header = try!(cli::wrap_with_status(objects::read_header(&name), 1));
println!("{}", header.content_length);
cli::success()
}
fn check_validity(name: &objects::Name) -> cli::Result {
try!(cli::wrap_with_status(objects::read_header(&name), 1));
cli::success()
}
fn show_contents(name: &objects::Name) -> cli::Result |
println!("");
println!("{}", commit.message);
},
objects::Object::Blob(contents) => {
// Don't use println, as we don't want to include an extra newline at the end of the
// blob contents.
print!("{}", contents);
},
_ => { /* Not handled yet */ }
}
cli::success()
}
fn dispatch_for_args(args: &Args) -> cli::Result {
let name = try!(cli::wrap_with_status(revisions::resolve(&args.arg_object), 1));
if args.flag_t {
show_type(&name)
} else if args.flag_s {
show_size(&name)
} else if args.flag_e {
check_validity(&name)
} else if args.flag_p {
show_contents(&name)
} else {
Err(cli::Error { message: "No flags specified".to_string(), status: 2 })
}
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
cli::exit_with(dispatch_for_args(&args))
}
| {
let obj = try!(cli::wrap_with_status(objects::read_object(&name), 1));
match obj {
objects::Object::Commit(commit) => {
let objects::Name(name) = commit.name;
println!("commit {}", name);
let objects::Name(tree) = commit.tree;
println!("tree : {}", tree);
if commit.parent.is_some() {
let objects::Name(parent) = commit.parent.unwrap();
println!("parent : {}", parent);
}
let commits::CommitUser { name, date } = commit.author;
println!("author : {} at {}", name, date);
let commits::CommitUser { name, date } = commit.committer;
println!("committer: {} at {}", name, date); | identifier_body |
edgeop_lsys.rs | extern crate rand;
extern crate evo;
extern crate petgraph;
#[macro_use]
extern crate graph_annealing;
extern crate pcg;
extern crate triadic_census;
extern crate lindenmayer_system;
extern crate graph_edge_evolution;
extern crate asexp;
extern crate expression;
extern crate expression_num;
extern crate expression_closed01;
extern crate matplotlib;
extern crate closed01;
extern crate graph_io_gml;
extern crate nsga2;
#[path="genome/genome_edgeop_lsys.rs"]
pub mod genome;
use std::str::FromStr;
use rand::{Rng, SeedableRng};
use rand::os::OsRng;
use pcg::PcgRng;
use evo::Probability;
use nsga2::{Driver, DriverConfig};
use genome::{Genome, Toolbox};
use graph_annealing::helper::to_weighted_vec;
use graph_annealing::goal::{FitnessFunction, Goal};
use graph_annealing::graph;
pub use graph_annealing::UniformDistribution;
use graph_annealing::stat::Stat;
use petgraph::{Directed, EdgeDirection, Graph};
use triadic_census::OptDenseDigraph;
use std::fs::File;
use genome::{RuleMutOp, RuleProductionMutOp, VarOp};
use genome::edgeop::{EdgeOp, edgeops_to_graph};
use genome::expr_op::{FlatExprOp, RecursiveExprOp, EXPR_NAME};
use std::io::Read;
use asexp::Sexp;
use asexp::sexp::pp;
use std::env;
use std::collections::BTreeMap;
use std::fmt::Debug;
use matplotlib::{Env, Plot};
struct ReseedRecorder {
reseeds: Vec<(u64, u64)>
}
/*
impl Reseeder<pcg::RcgRng> for ReseedRecorder {
fn reseed(&mut self, rng: &mut pcg::RcgRng) {
let mut r = rand::thread_rng();
let s1 = r.next_u64();
let s2 = r.next_u64();
self.reseeds.push((s1, s2));
rng.reseed([s1, s2]);
}
}
*/
const MAX_OBJECTIVES: usize = 3;
fn graph_to_sexp<N, E, F, G>(g: &Graph<N, E, Directed>,
node_weight_map: F,
edge_weight_map: G)
-> Sexp
where F: Fn(&N) -> Option<Sexp>,
G: Fn(&E) -> Option<Sexp>
{
let mut nodes = Vec::new();
for node_idx in g.node_indices() {
let edges: Vec<_> = g.edges_directed(node_idx, EdgeDirection::Outgoing)
.map(|(target_node, edge_weight)| {
match edge_weight_map(edge_weight) {
Some(w) => Sexp::from((target_node.index(), w)),
None => Sexp::from(target_node.index()),
}
})
.collect();
let mut def = vec![
(Sexp::from("id"), Sexp::from(node_idx.index())),
(Sexp::from("edges"), Sexp::Array(edges)),
];
match node_weight_map(&g[node_idx]) {
Some(w) => def.push((Sexp::from("weight"), w)),
None => {}
}
nodes.push(Sexp::Map(def));
}
Sexp::Map(vec![
(Sexp::from("version"), Sexp::from(1usize)),
(Sexp::from("nodes"), Sexp::Array(nodes)),
])
}
#[derive(Debug)]
struct ConfigGenome {
max_iter: usize,
rules: usize,
initial_len: usize,
symbol_arity: usize,
num_params: usize,
prob_terminal: Probability,
}
#[derive(Debug)]
struct Config {
ngen: usize,
mu: usize,
lambda: usize,
k: usize,
seed: Vec<u64>,
objectives: Vec<Objective>,
graph: Graph<f32, f32, Directed>,
edge_ops: Vec<(EdgeOp, u32)>,
var_ops: Vec<(VarOp, u32)>,
rule_mut_ops: Vec<(RuleMutOp, u32)>,
rule_prod_ops: Vec<(RuleProductionMutOp, u32)>,
flat_expr_op: Vec<(FlatExprOp, u32)>,
recursive_expr_op: Vec<(RecursiveExprOp, u32)>,
genome: ConfigGenome,
plot: bool,
weight: f64,
}
#[derive(Debug)]
struct Objective {
fitness_function: FitnessFunction,
threshold: f32,
}
fn parse_ops<T, I>(map: &BTreeMap<String, Sexp>, key: &str) -> Vec<(T, u32)>
where T: FromStr<Err = I> + UniformDistribution,
I: Debug
{
if let Some(&Sexp::Map(ref list)) = map.get(key) {
let mut ops: Vec<(T, u32)> = Vec::new();
for &(ref k, ref v) in list.iter() {
ops.push((T::from_str(k.get_str().unwrap()).unwrap(),
v.get_uint().unwrap() as u32));
}
ops
} else {
T::uniform_distribution()
}
}
fn convert_weight(w: Option<&Sexp>) -> Option<f32> {
match w {
Some(s) => s.get_float().map(|f| f as f32),
None => {
// use a default
Some(0.0)
}
}
}
fn parse_config(sexp: Sexp) -> Config {
let map = sexp.into_map().unwrap();
// number of generations
let ngen: usize = map.get("ngen").and_then(|v| v.get_uint()).unwrap() as usize;
// size of population
let mu: usize = map.get("mu").and_then(|v| v.get_uint()).unwrap() as usize;
// size of offspring population
let lambda: usize = map.get("lambda").and_then(|v| v.get_uint()).unwrap() as usize;
// tournament selection
let k: usize = map.get("k").and_then(|v| v.get_uint()).unwrap_or(2) as usize;
assert!(k > 0);
let plot: bool = map.get("plot").map(|v| v.get_str() == Some("true")).unwrap_or(false);
let weight: f64 = map.get("weight").and_then(|v| v.get_float()).unwrap_or(1.0);
let seed: Vec<u64>;
if let Some(seed_expr) = map.get("seed") {
seed = seed_expr.get_uint_vec().unwrap();
} else {
println!("Use OsRng to generate seed..");
let mut rng = OsRng::new().unwrap();
seed = (0..2).map(|_| rng.next_u64()).collect();
}
// Parse objectives and thresholds
let mut objectives: Vec<Objective> = Vec::new();
if let Some(&Sexp::Map(ref list)) = map.get("objectives") {
for &(ref k, ref v) in list.iter() {
objectives.push(Objective {
fitness_function: FitnessFunction::from_str(k.get_str().unwrap()).unwrap(),
threshold: v.get_float().unwrap() as f32,
});
}
} else {
panic!("Map expected");
}
if objectives.len() > MAX_OBJECTIVES {
panic!("Max {} objectives allowed", MAX_OBJECTIVES);
}
// read graph
let graph_file = map.get("graph").unwrap().get_str().unwrap();
println!("Using graph file: {}", graph_file);
let graph_s = {
let mut graph_file = File::open(graph_file).unwrap();
let mut graph_s = String::new();
let _ = graph_file.read_to_string(&mut graph_s).unwrap();
graph_s
};
let graph = graph_io_gml::parse_gml(&graph_s,
&convert_weight,
&convert_weight)
.unwrap();
println!("graph: {:?}", graph);
let graph = graph::normalize_graph(&graph);
let genome_map = map.get("genome").unwrap().clone().into_map().unwrap();
Config {
ngen: ngen,
mu: mu,
lambda: lambda,
k: k,
plot: plot,
weight: weight,
seed: seed,
objectives: objectives,
graph: graph,
edge_ops: parse_ops(&map, "edge_ops"),
var_ops: parse_ops(&map, "var_ops"),
rule_mut_ops: parse_ops(&map, "rule_mut_ops"),
rule_prod_ops: parse_ops(&map, "rule_prod_mut_ops"),
flat_expr_op: parse_ops(&map, "flat_expr_ops"),
recursive_expr_op: parse_ops(&map, "recursive_expr_ops"),
genome: ConfigGenome {
rules: genome_map.get("rules").and_then(|v| v.get_uint()).unwrap() as usize,
symbol_arity: genome_map.get("symbol_arity").and_then(|v| v.get_uint()).unwrap() as usize,
num_params: genome_map.get("num_params").and_then(|v| v.get_uint()).unwrap() as usize,
initial_len: genome_map.get("initial_len").and_then(|v| v.get_uint()).unwrap() as usize,
max_iter: genome_map.get("max_iter").and_then(|v| v.get_uint()).unwrap() as usize,
prob_terminal: Probability::new(genome_map.get("prob_terminal").and_then(|v| v.get_float()).unwrap() as f32),
},
}
}
fn main() |
let driver_config = DriverConfig {
mu: config.mu,
lambda: config.lambda,
k: config.k,
ngen: config.ngen,
num_objectives: num_objectives
};
let toolbox = Toolbox::new(Goal::new(OptDenseDigraph::from(config.graph.clone())),
config.objectives
.iter()
.map(|o| o.threshold)
.collect(),
config.objectives
.iter()
.map(|o| o.fitness_function.clone())
.collect(),
config.genome.max_iter, // iterations
config.genome.rules, // num_rules
config.genome.initial_len, // initial rule length
config.genome.symbol_arity, // we use 1-ary symbols
config.genome.num_params,
config.genome.prob_terminal,
to_weighted_vec(&config.edge_ops),
to_weighted_vec(&config.flat_expr_op),
to_weighted_vec(&config.recursive_expr_op),
to_weighted_vec(&config.var_ops),
to_weighted_vec(&config.rule_mut_ops),
to_weighted_vec(&config.rule_prod_ops));
assert!(config.seed.len() == 2);
let mut rng: PcgRng = SeedableRng::from_seed([config.seed[0], config.seed[1]]);
//let mut rng = rand::thread_rng();
let selected_population = toolbox.run(&mut rng, &driver_config, config.weight, &|iteration, duration, num_optima, population| {
let duration_ms = (duration as f32) / 1_000_000.0;
print!("# {:>6}", iteration);
let fitness_values = population.fitness_to_vec();
// XXX: Assume we have at least two objectives
let mut x = Vec::new();
let mut y = Vec::new();
for f in fitness_values.iter() {
x.push(f.objectives[0]);
y.push(f.objectives[1]);
}
if config.plot {
plot.clf();
plot.title(&format!("Iteration: {}", iteration));
plot.grid(true);
plot.scatter(&x, &y);
plot.draw();
}
// calculate a min/max/avg value for each objective.
let stats: Vec<Stat<f32>> = (0..num_objectives)
.into_iter()
.map(|i| {
Stat::from_iter(fitness_values.iter().map(|o| o.objectives[i]))
.unwrap()
})
.collect();
for stat in stats.iter() {
print!(" | ");
print!("{:>8.2}", stat.min);
print!("{:>9.2}", stat.avg);
print!("{:>10.2}", stat.max);
}
print!(" | {:>5} | {:>8.0} ms", num_optima, duration_ms);
println!("");
if num_optima > 0 {
println!("Found premature optimum in Iteration {}", iteration);
}
});
println!("===========================================================");
let mut best_solutions: Vec<(Genome, _)> = Vec::new();
selected_population.all_of_rank(0, &mut |ind, fit| {
if fit.objectives[0] < 0.1 && fit.objectives[1] < 0.1 {
best_solutions.push((ind.clone(), fit.clone()));
}
});
println!("Target graph");
let sexp = graph_to_sexp(&graph::normalize_graph_closed01(&config.graph),
|nw| Some(Sexp::from(nw.get())),
|ew| Some(Sexp::from(ew.get())));
println!("{}", pp(&sexp));
let mut solutions: Vec<Sexp> = Vec::new();
for (_i, &(ref ind, ref fitness)) in best_solutions.iter().enumerate() {
let genome: Sexp = ind.into();
let edge_ops = ind.to_edge_ops(&toolbox.axiom_args, toolbox.iterations);
let g = edgeops_to_graph(&edge_ops);
// output as sexp
let graph_sexp = graph_to_sexp(g.ref_graph(),
|&nw| Some(Sexp::from(nw)),
|&ew| Some(Sexp::from(ew)));
solutions.push(Sexp::Map(
vec![
(Sexp::from("fitness"), Sexp::from((fitness.objectives[0], fitness.objectives[1], fitness.objectives[2]))),
(Sexp::from("genome"), genome),
(Sexp::from("graph"), graph_sexp),
]
));
/*
draw_graph(g.ref_graph(),
// XXX: name
&format!("edgeop_lsys_g{}_f{}_i{}.svg",
config.ngen,
fitness.objectives[1] as usize,
i));
*/
}
println!("{}", pp(&Sexp::from(("solutions", Sexp::Array(solutions)))));
//println!("])");
println!("{:#?}", config);
}
| {
println!("Using expr system: {}", EXPR_NAME);
let env = Env::new();
let plot = Plot::new(&env);
let mut s = String::new();
let configfile = env::args().nth(1).unwrap();
let _ = File::open(configfile).unwrap().read_to_string(&mut s).unwrap();
let expr = asexp::Sexp::parse_toplevel(&s).unwrap();
let config = parse_config(expr);
println!("{:#?}", config);
if config.plot {
plot.interactive();
plot.show();
}
let num_objectives = config.objectives.len(); | identifier_body |
edgeop_lsys.rs | extern crate rand;
extern crate evo;
extern crate petgraph;
#[macro_use]
extern crate graph_annealing;
extern crate pcg;
extern crate triadic_census;
extern crate lindenmayer_system;
extern crate graph_edge_evolution;
extern crate asexp;
extern crate expression;
extern crate expression_num;
extern crate expression_closed01;
extern crate matplotlib;
extern crate closed01;
extern crate graph_io_gml;
extern crate nsga2;
#[path="genome/genome_edgeop_lsys.rs"]
pub mod genome;
use std::str::FromStr;
use rand::{Rng, SeedableRng};
use rand::os::OsRng;
use pcg::PcgRng;
use evo::Probability;
use nsga2::{Driver, DriverConfig};
use genome::{Genome, Toolbox};
use graph_annealing::helper::to_weighted_vec;
use graph_annealing::goal::{FitnessFunction, Goal};
use graph_annealing::graph;
pub use graph_annealing::UniformDistribution;
use graph_annealing::stat::Stat;
use petgraph::{Directed, EdgeDirection, Graph};
use triadic_census::OptDenseDigraph;
use std::fs::File;
use genome::{RuleMutOp, RuleProductionMutOp, VarOp};
use genome::edgeop::{EdgeOp, edgeops_to_graph};
use genome::expr_op::{FlatExprOp, RecursiveExprOp, EXPR_NAME};
use std::io::Read;
use asexp::Sexp;
use asexp::sexp::pp;
use std::env;
use std::collections::BTreeMap;
use std::fmt::Debug;
use matplotlib::{Env, Plot};
struct ReseedRecorder {
reseeds: Vec<(u64, u64)>
}
/*
impl Reseeder<pcg::RcgRng> for ReseedRecorder {
fn reseed(&mut self, rng: &mut pcg::RcgRng) {
let mut r = rand::thread_rng();
let s1 = r.next_u64();
let s2 = r.next_u64();
self.reseeds.push((s1, s2));
rng.reseed([s1, s2]);
}
}
*/
const MAX_OBJECTIVES: usize = 3;
fn graph_to_sexp<N, E, F, G>(g: &Graph<N, E, Directed>,
node_weight_map: F,
edge_weight_map: G)
-> Sexp
where F: Fn(&N) -> Option<Sexp>,
G: Fn(&E) -> Option<Sexp>
{
let mut nodes = Vec::new();
for node_idx in g.node_indices() {
let edges: Vec<_> = g.edges_directed(node_idx, EdgeDirection::Outgoing)
.map(|(target_node, edge_weight)| {
match edge_weight_map(edge_weight) {
Some(w) => Sexp::from((target_node.index(), w)),
None => Sexp::from(target_node.index()),
}
})
.collect();
let mut def = vec![
(Sexp::from("id"), Sexp::from(node_idx.index())),
(Sexp::from("edges"), Sexp::Array(edges)),
];
match node_weight_map(&g[node_idx]) {
Some(w) => def.push((Sexp::from("weight"), w)),
None => {}
}
nodes.push(Sexp::Map(def));
}
Sexp::Map(vec![
(Sexp::from("version"), Sexp::from(1usize)),
(Sexp::from("nodes"), Sexp::Array(nodes)),
])
}
#[derive(Debug)]
struct ConfigGenome {
max_iter: usize,
rules: usize,
initial_len: usize,
symbol_arity: usize,
num_params: usize,
prob_terminal: Probability,
}
#[derive(Debug)]
struct Config {
ngen: usize,
mu: usize,
lambda: usize,
k: usize,
seed: Vec<u64>,
objectives: Vec<Objective>,
graph: Graph<f32, f32, Directed>,
edge_ops: Vec<(EdgeOp, u32)>,
var_ops: Vec<(VarOp, u32)>,
rule_mut_ops: Vec<(RuleMutOp, u32)>,
rule_prod_ops: Vec<(RuleProductionMutOp, u32)>,
flat_expr_op: Vec<(FlatExprOp, u32)>,
recursive_expr_op: Vec<(RecursiveExprOp, u32)>,
genome: ConfigGenome,
plot: bool,
weight: f64,
}
| struct Objective {
fitness_function: FitnessFunction,
threshold: f32,
}
fn parse_ops<T, I>(map: &BTreeMap<String, Sexp>, key: &str) -> Vec<(T, u32)>
where T: FromStr<Err = I> + UniformDistribution,
I: Debug
{
if let Some(&Sexp::Map(ref list)) = map.get(key) {
let mut ops: Vec<(T, u32)> = Vec::new();
for &(ref k, ref v) in list.iter() {
ops.push((T::from_str(k.get_str().unwrap()).unwrap(),
v.get_uint().unwrap() as u32));
}
ops
} else {
T::uniform_distribution()
}
}
fn convert_weight(w: Option<&Sexp>) -> Option<f32> {
match w {
Some(s) => s.get_float().map(|f| f as f32),
None => {
// use a default
Some(0.0)
}
}
}
fn parse_config(sexp: Sexp) -> Config {
let map = sexp.into_map().unwrap();
// number of generations
let ngen: usize = map.get("ngen").and_then(|v| v.get_uint()).unwrap() as usize;
// size of population
let mu: usize = map.get("mu").and_then(|v| v.get_uint()).unwrap() as usize;
// size of offspring population
let lambda: usize = map.get("lambda").and_then(|v| v.get_uint()).unwrap() as usize;
// tournament selection
let k: usize = map.get("k").and_then(|v| v.get_uint()).unwrap_or(2) as usize;
assert!(k > 0);
let plot: bool = map.get("plot").map(|v| v.get_str() == Some("true")).unwrap_or(false);
let weight: f64 = map.get("weight").and_then(|v| v.get_float()).unwrap_or(1.0);
let seed: Vec<u64>;
if let Some(seed_expr) = map.get("seed") {
seed = seed_expr.get_uint_vec().unwrap();
} else {
println!("Use OsRng to generate seed..");
let mut rng = OsRng::new().unwrap();
seed = (0..2).map(|_| rng.next_u64()).collect();
}
// Parse objectives and thresholds
let mut objectives: Vec<Objective> = Vec::new();
if let Some(&Sexp::Map(ref list)) = map.get("objectives") {
for &(ref k, ref v) in list.iter() {
objectives.push(Objective {
fitness_function: FitnessFunction::from_str(k.get_str().unwrap()).unwrap(),
threshold: v.get_float().unwrap() as f32,
});
}
} else {
panic!("Map expected");
}
if objectives.len() > MAX_OBJECTIVES {
panic!("Max {} objectives allowed", MAX_OBJECTIVES);
}
// read graph
let graph_file = map.get("graph").unwrap().get_str().unwrap();
println!("Using graph file: {}", graph_file);
let graph_s = {
let mut graph_file = File::open(graph_file).unwrap();
let mut graph_s = String::new();
let _ = graph_file.read_to_string(&mut graph_s).unwrap();
graph_s
};
let graph = graph_io_gml::parse_gml(&graph_s,
&convert_weight,
&convert_weight)
.unwrap();
println!("graph: {:?}", graph);
let graph = graph::normalize_graph(&graph);
let genome_map = map.get("genome").unwrap().clone().into_map().unwrap();
Config {
ngen: ngen,
mu: mu,
lambda: lambda,
k: k,
plot: plot,
weight: weight,
seed: seed,
objectives: objectives,
graph: graph,
edge_ops: parse_ops(&map, "edge_ops"),
var_ops: parse_ops(&map, "var_ops"),
rule_mut_ops: parse_ops(&map, "rule_mut_ops"),
rule_prod_ops: parse_ops(&map, "rule_prod_mut_ops"),
flat_expr_op: parse_ops(&map, "flat_expr_ops"),
recursive_expr_op: parse_ops(&map, "recursive_expr_ops"),
genome: ConfigGenome {
rules: genome_map.get("rules").and_then(|v| v.get_uint()).unwrap() as usize,
symbol_arity: genome_map.get("symbol_arity").and_then(|v| v.get_uint()).unwrap() as usize,
num_params: genome_map.get("num_params").and_then(|v| v.get_uint()).unwrap() as usize,
initial_len: genome_map.get("initial_len").and_then(|v| v.get_uint()).unwrap() as usize,
max_iter: genome_map.get("max_iter").and_then(|v| v.get_uint()).unwrap() as usize,
prob_terminal: Probability::new(genome_map.get("prob_terminal").and_then(|v| v.get_float()).unwrap() as f32),
},
}
}
fn main() {
println!("Using expr system: {}", EXPR_NAME);
let env = Env::new();
let plot = Plot::new(&env);
let mut s = String::new();
let configfile = env::args().nth(1).unwrap();
let _ = File::open(configfile).unwrap().read_to_string(&mut s).unwrap();
let expr = asexp::Sexp::parse_toplevel(&s).unwrap();
let config = parse_config(expr);
println!("{:#?}", config);
if config.plot {
plot.interactive();
plot.show();
}
let num_objectives = config.objectives.len();
let driver_config = DriverConfig {
mu: config.mu,
lambda: config.lambda,
k: config.k,
ngen: config.ngen,
num_objectives: num_objectives
};
let toolbox = Toolbox::new(Goal::new(OptDenseDigraph::from(config.graph.clone())),
config.objectives
.iter()
.map(|o| o.threshold)
.collect(),
config.objectives
.iter()
.map(|o| o.fitness_function.clone())
.collect(),
config.genome.max_iter, // iterations
config.genome.rules, // num_rules
config.genome.initial_len, // initial rule length
config.genome.symbol_arity, // we use 1-ary symbols
config.genome.num_params,
config.genome.prob_terminal,
to_weighted_vec(&config.edge_ops),
to_weighted_vec(&config.flat_expr_op),
to_weighted_vec(&config.recursive_expr_op),
to_weighted_vec(&config.var_ops),
to_weighted_vec(&config.rule_mut_ops),
to_weighted_vec(&config.rule_prod_ops));
assert!(config.seed.len() == 2);
let mut rng: PcgRng = SeedableRng::from_seed([config.seed[0], config.seed[1]]);
//let mut rng = rand::thread_rng();
let selected_population = toolbox.run(&mut rng, &driver_config, config.weight, &|iteration, duration, num_optima, population| {
let duration_ms = (duration as f32) / 1_000_000.0;
print!("# {:>6}", iteration);
let fitness_values = population.fitness_to_vec();
// XXX: Assume we have at least two objectives
let mut x = Vec::new();
let mut y = Vec::new();
for f in fitness_values.iter() {
x.push(f.objectives[0]);
y.push(f.objectives[1]);
}
if config.plot {
plot.clf();
plot.title(&format!("Iteration: {}", iteration));
plot.grid(true);
plot.scatter(&x, &y);
plot.draw();
}
// calculate a min/max/avg value for each objective.
let stats: Vec<Stat<f32>> = (0..num_objectives)
.into_iter()
.map(|i| {
Stat::from_iter(fitness_values.iter().map(|o| o.objectives[i]))
.unwrap()
})
.collect();
for stat in stats.iter() {
print!(" | ");
print!("{:>8.2}", stat.min);
print!("{:>9.2}", stat.avg);
print!("{:>10.2}", stat.max);
}
print!(" | {:>5} | {:>8.0} ms", num_optima, duration_ms);
println!("");
if num_optima > 0 {
println!("Found premature optimum in Iteration {}", iteration);
}
});
println!("===========================================================");
let mut best_solutions: Vec<(Genome, _)> = Vec::new();
selected_population.all_of_rank(0, &mut |ind, fit| {
if fit.objectives[0] < 0.1 && fit.objectives[1] < 0.1 {
best_solutions.push((ind.clone(), fit.clone()));
}
});
println!("Target graph");
let sexp = graph_to_sexp(&graph::normalize_graph_closed01(&config.graph),
|nw| Some(Sexp::from(nw.get())),
|ew| Some(Sexp::from(ew.get())));
println!("{}", pp(&sexp));
let mut solutions: Vec<Sexp> = Vec::new();
for (_i, &(ref ind, ref fitness)) in best_solutions.iter().enumerate() {
let genome: Sexp = ind.into();
let edge_ops = ind.to_edge_ops(&toolbox.axiom_args, toolbox.iterations);
let g = edgeops_to_graph(&edge_ops);
// output as sexp
let graph_sexp = graph_to_sexp(g.ref_graph(),
|&nw| Some(Sexp::from(nw)),
|&ew| Some(Sexp::from(ew)));
solutions.push(Sexp::Map(
vec![
(Sexp::from("fitness"), Sexp::from((fitness.objectives[0], fitness.objectives[1], fitness.objectives[2]))),
(Sexp::from("genome"), genome),
(Sexp::from("graph"), graph_sexp),
]
));
/*
draw_graph(g.ref_graph(),
// XXX: name
&format!("edgeop_lsys_g{}_f{}_i{}.svg",
config.ngen,
fitness.objectives[1] as usize,
i));
*/
}
println!("{}", pp(&Sexp::from(("solutions", Sexp::Array(solutions)))));
//println!("])");
println!("{:#?}", config);
} | #[derive(Debug)] | random_line_split |
edgeop_lsys.rs | extern crate rand;
extern crate evo;
extern crate petgraph;
#[macro_use]
extern crate graph_annealing;
extern crate pcg;
extern crate triadic_census;
extern crate lindenmayer_system;
extern crate graph_edge_evolution;
extern crate asexp;
extern crate expression;
extern crate expression_num;
extern crate expression_closed01;
extern crate matplotlib;
extern crate closed01;
extern crate graph_io_gml;
extern crate nsga2;
#[path="genome/genome_edgeop_lsys.rs"]
pub mod genome;
use std::str::FromStr;
use rand::{Rng, SeedableRng};
use rand::os::OsRng;
use pcg::PcgRng;
use evo::Probability;
use nsga2::{Driver, DriverConfig};
use genome::{Genome, Toolbox};
use graph_annealing::helper::to_weighted_vec;
use graph_annealing::goal::{FitnessFunction, Goal};
use graph_annealing::graph;
pub use graph_annealing::UniformDistribution;
use graph_annealing::stat::Stat;
use petgraph::{Directed, EdgeDirection, Graph};
use triadic_census::OptDenseDigraph;
use std::fs::File;
use genome::{RuleMutOp, RuleProductionMutOp, VarOp};
use genome::edgeop::{EdgeOp, edgeops_to_graph};
use genome::expr_op::{FlatExprOp, RecursiveExprOp, EXPR_NAME};
use std::io::Read;
use asexp::Sexp;
use asexp::sexp::pp;
use std::env;
use std::collections::BTreeMap;
use std::fmt::Debug;
use matplotlib::{Env, Plot};
struct ReseedRecorder {
reseeds: Vec<(u64, u64)>
}
/*
impl Reseeder<pcg::RcgRng> for ReseedRecorder {
fn reseed(&mut self, rng: &mut pcg::RcgRng) {
let mut r = rand::thread_rng();
let s1 = r.next_u64();
let s2 = r.next_u64();
self.reseeds.push((s1, s2));
rng.reseed([s1, s2]);
}
}
*/
const MAX_OBJECTIVES: usize = 3;
fn graph_to_sexp<N, E, F, G>(g: &Graph<N, E, Directed>,
node_weight_map: F,
edge_weight_map: G)
-> Sexp
where F: Fn(&N) -> Option<Sexp>,
G: Fn(&E) -> Option<Sexp>
{
let mut nodes = Vec::new();
for node_idx in g.node_indices() {
let edges: Vec<_> = g.edges_directed(node_idx, EdgeDirection::Outgoing)
.map(|(target_node, edge_weight)| {
match edge_weight_map(edge_weight) {
Some(w) => Sexp::from((target_node.index(), w)),
None => Sexp::from(target_node.index()),
}
})
.collect();
let mut def = vec![
(Sexp::from("id"), Sexp::from(node_idx.index())),
(Sexp::from("edges"), Sexp::Array(edges)),
];
match node_weight_map(&g[node_idx]) {
Some(w) => def.push((Sexp::from("weight"), w)),
None => {}
}
nodes.push(Sexp::Map(def));
}
Sexp::Map(vec![
(Sexp::from("version"), Sexp::from(1usize)),
(Sexp::from("nodes"), Sexp::Array(nodes)),
])
}
#[derive(Debug)]
struct ConfigGenome {
max_iter: usize,
rules: usize,
initial_len: usize,
symbol_arity: usize,
num_params: usize,
prob_terminal: Probability,
}
#[derive(Debug)]
struct Config {
ngen: usize,
mu: usize,
lambda: usize,
k: usize,
seed: Vec<u64>,
objectives: Vec<Objective>,
graph: Graph<f32, f32, Directed>,
edge_ops: Vec<(EdgeOp, u32)>,
var_ops: Vec<(VarOp, u32)>,
rule_mut_ops: Vec<(RuleMutOp, u32)>,
rule_prod_ops: Vec<(RuleProductionMutOp, u32)>,
flat_expr_op: Vec<(FlatExprOp, u32)>,
recursive_expr_op: Vec<(RecursiveExprOp, u32)>,
genome: ConfigGenome,
plot: bool,
weight: f64,
}
#[derive(Debug)]
struct Objective {
fitness_function: FitnessFunction,
threshold: f32,
}
fn parse_ops<T, I>(map: &BTreeMap<String, Sexp>, key: &str) -> Vec<(T, u32)>
where T: FromStr<Err = I> + UniformDistribution,
I: Debug
{
if let Some(&Sexp::Map(ref list)) = map.get(key) {
let mut ops: Vec<(T, u32)> = Vec::new();
for &(ref k, ref v) in list.iter() {
ops.push((T::from_str(k.get_str().unwrap()).unwrap(),
v.get_uint().unwrap() as u32));
}
ops
} else {
T::uniform_distribution()
}
}
fn | (w: Option<&Sexp>) -> Option<f32> {
match w {
Some(s) => s.get_float().map(|f| f as f32),
None => {
// use a default
Some(0.0)
}
}
}
fn parse_config(sexp: Sexp) -> Config {
let map = sexp.into_map().unwrap();
// number of generations
let ngen: usize = map.get("ngen").and_then(|v| v.get_uint()).unwrap() as usize;
// size of population
let mu: usize = map.get("mu").and_then(|v| v.get_uint()).unwrap() as usize;
// size of offspring population
let lambda: usize = map.get("lambda").and_then(|v| v.get_uint()).unwrap() as usize;
// tournament selection
let k: usize = map.get("k").and_then(|v| v.get_uint()).unwrap_or(2) as usize;
assert!(k > 0);
let plot: bool = map.get("plot").map(|v| v.get_str() == Some("true")).unwrap_or(false);
let weight: f64 = map.get("weight").and_then(|v| v.get_float()).unwrap_or(1.0);
let seed: Vec<u64>;
if let Some(seed_expr) = map.get("seed") {
seed = seed_expr.get_uint_vec().unwrap();
} else {
println!("Use OsRng to generate seed..");
let mut rng = OsRng::new().unwrap();
seed = (0..2).map(|_| rng.next_u64()).collect();
}
// Parse objectives and thresholds
let mut objectives: Vec<Objective> = Vec::new();
if let Some(&Sexp::Map(ref list)) = map.get("objectives") {
for &(ref k, ref v) in list.iter() {
objectives.push(Objective {
fitness_function: FitnessFunction::from_str(k.get_str().unwrap()).unwrap(),
threshold: v.get_float().unwrap() as f32,
});
}
} else {
panic!("Map expected");
}
if objectives.len() > MAX_OBJECTIVES {
panic!("Max {} objectives allowed", MAX_OBJECTIVES);
}
// read graph
let graph_file = map.get("graph").unwrap().get_str().unwrap();
println!("Using graph file: {}", graph_file);
let graph_s = {
let mut graph_file = File::open(graph_file).unwrap();
let mut graph_s = String::new();
let _ = graph_file.read_to_string(&mut graph_s).unwrap();
graph_s
};
let graph = graph_io_gml::parse_gml(&graph_s,
&convert_weight,
&convert_weight)
.unwrap();
println!("graph: {:?}", graph);
let graph = graph::normalize_graph(&graph);
let genome_map = map.get("genome").unwrap().clone().into_map().unwrap();
Config {
ngen: ngen,
mu: mu,
lambda: lambda,
k: k,
plot: plot,
weight: weight,
seed: seed,
objectives: objectives,
graph: graph,
edge_ops: parse_ops(&map, "edge_ops"),
var_ops: parse_ops(&map, "var_ops"),
rule_mut_ops: parse_ops(&map, "rule_mut_ops"),
rule_prod_ops: parse_ops(&map, "rule_prod_mut_ops"),
flat_expr_op: parse_ops(&map, "flat_expr_ops"),
recursive_expr_op: parse_ops(&map, "recursive_expr_ops"),
genome: ConfigGenome {
rules: genome_map.get("rules").and_then(|v| v.get_uint()).unwrap() as usize,
symbol_arity: genome_map.get("symbol_arity").and_then(|v| v.get_uint()).unwrap() as usize,
num_params: genome_map.get("num_params").and_then(|v| v.get_uint()).unwrap() as usize,
initial_len: genome_map.get("initial_len").and_then(|v| v.get_uint()).unwrap() as usize,
max_iter: genome_map.get("max_iter").and_then(|v| v.get_uint()).unwrap() as usize,
prob_terminal: Probability::new(genome_map.get("prob_terminal").and_then(|v| v.get_float()).unwrap() as f32),
},
}
}
fn main() {
println!("Using expr system: {}", EXPR_NAME);
let env = Env::new();
let plot = Plot::new(&env);
let mut s = String::new();
let configfile = env::args().nth(1).unwrap();
let _ = File::open(configfile).unwrap().read_to_string(&mut s).unwrap();
let expr = asexp::Sexp::parse_toplevel(&s).unwrap();
let config = parse_config(expr);
println!("{:#?}", config);
if config.plot {
plot.interactive();
plot.show();
}
let num_objectives = config.objectives.len();
let driver_config = DriverConfig {
mu: config.mu,
lambda: config.lambda,
k: config.k,
ngen: config.ngen,
num_objectives: num_objectives
};
let toolbox = Toolbox::new(Goal::new(OptDenseDigraph::from(config.graph.clone())),
config.objectives
.iter()
.map(|o| o.threshold)
.collect(),
config.objectives
.iter()
.map(|o| o.fitness_function.clone())
.collect(),
config.genome.max_iter, // iterations
config.genome.rules, // num_rules
config.genome.initial_len, // initial rule length
config.genome.symbol_arity, // we use 1-ary symbols
config.genome.num_params,
config.genome.prob_terminal,
to_weighted_vec(&config.edge_ops),
to_weighted_vec(&config.flat_expr_op),
to_weighted_vec(&config.recursive_expr_op),
to_weighted_vec(&config.var_ops),
to_weighted_vec(&config.rule_mut_ops),
to_weighted_vec(&config.rule_prod_ops));
assert!(config.seed.len() == 2);
let mut rng: PcgRng = SeedableRng::from_seed([config.seed[0], config.seed[1]]);
//let mut rng = rand::thread_rng();
let selected_population = toolbox.run(&mut rng, &driver_config, config.weight, &|iteration, duration, num_optima, population| {
let duration_ms = (duration as f32) / 1_000_000.0;
print!("# {:>6}", iteration);
let fitness_values = population.fitness_to_vec();
// XXX: Assume we have at least two objectives
let mut x = Vec::new();
let mut y = Vec::new();
for f in fitness_values.iter() {
x.push(f.objectives[0]);
y.push(f.objectives[1]);
}
if config.plot {
plot.clf();
plot.title(&format!("Iteration: {}", iteration));
plot.grid(true);
plot.scatter(&x, &y);
plot.draw();
}
// calculate a min/max/avg value for each objective.
let stats: Vec<Stat<f32>> = (0..num_objectives)
.into_iter()
.map(|i| {
Stat::from_iter(fitness_values.iter().map(|o| o.objectives[i]))
.unwrap()
})
.collect();
for stat in stats.iter() {
print!(" | ");
print!("{:>8.2}", stat.min);
print!("{:>9.2}", stat.avg);
print!("{:>10.2}", stat.max);
}
print!(" | {:>5} | {:>8.0} ms", num_optima, duration_ms);
println!("");
if num_optima > 0 {
println!("Found premature optimum in Iteration {}", iteration);
}
});
println!("===========================================================");
let mut best_solutions: Vec<(Genome, _)> = Vec::new();
selected_population.all_of_rank(0, &mut |ind, fit| {
if fit.objectives[0] < 0.1 && fit.objectives[1] < 0.1 {
best_solutions.push((ind.clone(), fit.clone()));
}
});
println!("Target graph");
let sexp = graph_to_sexp(&graph::normalize_graph_closed01(&config.graph),
|nw| Some(Sexp::from(nw.get())),
|ew| Some(Sexp::from(ew.get())));
println!("{}", pp(&sexp));
let mut solutions: Vec<Sexp> = Vec::new();
for (_i, &(ref ind, ref fitness)) in best_solutions.iter().enumerate() {
let genome: Sexp = ind.into();
let edge_ops = ind.to_edge_ops(&toolbox.axiom_args, toolbox.iterations);
let g = edgeops_to_graph(&edge_ops);
// output as sexp
let graph_sexp = graph_to_sexp(g.ref_graph(),
|&nw| Some(Sexp::from(nw)),
|&ew| Some(Sexp::from(ew)));
solutions.push(Sexp::Map(
vec![
(Sexp::from("fitness"), Sexp::from((fitness.objectives[0], fitness.objectives[1], fitness.objectives[2]))),
(Sexp::from("genome"), genome),
(Sexp::from("graph"), graph_sexp),
]
));
/*
draw_graph(g.ref_graph(),
// XXX: name
&format!("edgeop_lsys_g{}_f{}_i{}.svg",
config.ngen,
fitness.objectives[1] as usize,
i));
*/
}
println!("{}", pp(&Sexp::from(("solutions", Sexp::Array(solutions)))));
//println!("])");
println!("{:#?}", config);
}
| convert_weight | identifier_name |
htmlareaelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLAreaElementDerived;
use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast};
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::HTMLAreaElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, NodeHelpers, ElementNodeTypeId};
use dom::virtualmethods::VirtualMethods;
use servo_util::atom::Atom;
use servo_util::str::DOMString;
#[deriving(Encodable)]
#[must_root]
pub struct HTMLAreaElement {
pub htmlelement: HTMLElement
}
impl HTMLAreaElementDerived for EventTarget {
fn is_htmlareaelement(&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLAreaElementTypeId))
}
}
impl HTMLAreaElement {
pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLAreaElement {
HTMLAreaElement {
htmlelement: HTMLElement::new_inherited(HTMLAreaElementTypeId, localName, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLAreaElement> {
let element = HTMLAreaElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLAreaElementBinding::Wrap)
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLAreaElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.after_set_attr(name, value.clone()),
_ => (),
}
| }
}
fn before_remove_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.before_remove_attr(name, value.clone()),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
match name.as_slice() {
"href" => node.set_enabled_state(false),
_ => ()
}
}
}
impl Reflectable for HTMLAreaElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
} | let node: JSRef<Node> = NodeCast::from_ref(*self);
match name.as_slice() {
"href" => node.set_enabled_state(true),
_ => () | random_line_split |
htmlareaelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLAreaElementDerived;
use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast};
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::HTMLAreaElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, NodeHelpers, ElementNodeTypeId};
use dom::virtualmethods::VirtualMethods;
use servo_util::atom::Atom;
use servo_util::str::DOMString;
#[deriving(Encodable)]
#[must_root]
pub struct HTMLAreaElement {
pub htmlelement: HTMLElement
}
impl HTMLAreaElementDerived for EventTarget {
fn is_htmlareaelement(&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLAreaElementTypeId))
}
}
impl HTMLAreaElement {
pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLAreaElement {
HTMLAreaElement {
htmlelement: HTMLElement::new_inherited(HTMLAreaElementTypeId, localName, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLAreaElement> |
}
impl<'a> VirtualMethods for JSRef<'a, HTMLAreaElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.after_set_attr(name, value.clone()),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
match name.as_slice() {
"href" => node.set_enabled_state(true),
_ => ()
}
}
fn before_remove_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.before_remove_attr(name, value.clone()),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
match name.as_slice() {
"href" => node.set_enabled_state(false),
_ => ()
}
}
}
impl Reflectable for HTMLAreaElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
| {
let element = HTMLAreaElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLAreaElementBinding::Wrap)
} | identifier_body |
htmlareaelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLAreaElementDerived;
use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast};
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::HTMLAreaElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, NodeHelpers, ElementNodeTypeId};
use dom::virtualmethods::VirtualMethods;
use servo_util::atom::Atom;
use servo_util::str::DOMString;
#[deriving(Encodable)]
#[must_root]
pub struct HTMLAreaElement {
pub htmlelement: HTMLElement
}
impl HTMLAreaElementDerived for EventTarget {
fn | (&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLAreaElementTypeId))
}
}
impl HTMLAreaElement {
pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLAreaElement {
HTMLAreaElement {
htmlelement: HTMLElement::new_inherited(HTMLAreaElementTypeId, localName, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLAreaElement> {
let element = HTMLAreaElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLAreaElementBinding::Wrap)
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLAreaElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.after_set_attr(name, value.clone()),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
match name.as_slice() {
"href" => node.set_enabled_state(true),
_ => ()
}
}
fn before_remove_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.before_remove_attr(name, value.clone()),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
match name.as_slice() {
"href" => node.set_enabled_state(false),
_ => ()
}
}
}
impl Reflectable for HTMLAreaElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
| is_htmlareaelement | identifier_name |
sizing.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/. */
//! https://drafts.csswg.org/css-sizing/
use crate::style_ext::ComputedValuesExt;
use style::properties::ComputedValues;
use style::values::computed::{Length, LengthPercentage, Percentage};
use style::values::generics::length::MaxSize;
use style::Zero;
/// Which min/max-content values should be computed during box construction
#[derive(Clone, Copy, Debug)]
pub(crate) enum ContentSizesRequest {
Inline,
None,
}
impl ContentSizesRequest {
pub fn inline_if(condition: bool) -> Self {
if condition {
Self::Inline
} else {
Self::None
}
}
pub fn requests_inline(self) -> bool {
match self {
Self::Inline => true,
Self::None => false,
}
}
pub fn if_requests_inline<T>(self, f: impl FnOnce() -> T) -> Option<T> {
match self {
Self::Inline => Some(f()),
Self::None => None,
}
}
pub fn compute(self, compute_inline: impl FnOnce() -> ContentSizes) -> BoxContentSizes {
match self {
Self::Inline => BoxContentSizes::Inline(compute_inline()),
Self::None => BoxContentSizes::NoneWereRequested,
}
}
}
#[derive(Clone, Debug, Serialize)]
pub(crate) struct ContentSizes {
pub min_content: Length,
pub max_content: Length,
}
/// https://drafts.csswg.org/css-sizing/#intrinsic-sizes
impl ContentSizes {
pub fn zero() -> Self {
Self {
min_content: Length::zero(),
max_content: Length::zero(),
}
}
pub fn max_assign(&mut self, other: &Self) {
self.min_content.max_assign(other.min_content);
self.max_content.max_assign(other.max_content);
}
/// Relevant to outer intrinsic inline sizes, for percentages from padding and margin.
pub fn adjust_for_pbm_percentages(&mut self, percentages: Percentage) {
// " Note that this may yield an infinite result, but undefined results
// (zero divided by zero) must be treated as zero. "
if self.max_content.px() == 0. {
// Avoid a potential `NaN`.
// Zero is already the result we want regardless of `denominator`.
} else {
let denominator = (1. - percentages.0).max(0.);
self.max_content = Length::new(self.max_content.px() / denominator);
}
}
}
/// Optional min/max-content for storage in the box tree
#[derive(Debug, Serialize)]
pub(crate) enum BoxContentSizes {
NoneWereRequested, // … during box construction
Inline(ContentSizes),
}
impl BoxContentSizes {
fn expect_inline(&self) -> &ContentSizes {
match self {
Self::NoneWereRequested => panic!("Accessing content size that was not requested"),
Self::Inline(s) => s,
}
}
/// https://dbaron.org/css/intrinsic/#outer-intrinsic
pub fn outer_inline(&self, style: &ComputedValues) -> ContentSizes {
let (mut outer, percentages) = self.outer_inline_and_percentages(style);
outer.adjust_for_pbm_percentages(percentages);
outer
}
pub(crate) fn outer_inline_and_percentages(
&self,
style: &ComputedValues,
) -> (ContentSizes, Percentage) {
// FIXME: account for 'box-sizing'
let inline_size = style.box_size().inline;
let min_inline_size = style
.min_box_size()
.inline
.percentage_relative_to(Length::zero())
.auto_is(Length::zero);
let max_inline_size = match style.max_box_size().inline {
MaxSize::None => None,
MaxSize::LengthPercentage(ref lp) => lp.to_length(),
};
let clamp = |l: Length| l.clamp_between_extremums(min_inline_size, max_inline_size);
// Percentages for 'width' are treated as 'auto'
let inline_size = inline_size.map(|lp| lp.to_length());
// The (inner) min/max-content are only used for 'auto'
let mut outer = match inline_size.non_auto().flatten() {
None => {
let inner = self.expect_inline().clone();
ContentSizes {
min_content: clamp(inner.min_content),
max_content: clamp(inner.max_content),
}
},
Some(length) => {
let length = clamp(length);
ContentSizes {
min_content: length,
max_content: length,
}
},
};
let mut pbm_lengths = Length::zero(); | let border = style.border_width();
let margin = style.margin();
pbm_lengths += border.inline_sum();
let mut add = |x: LengthPercentage| {
if let Some(l) = x.to_length() {
pbm_lengths += l;
}
if let Some(p) = x.to_percentage() {
pbm_percentages += p;
}
};
add(padding.inline_start);
add(padding.inline_end);
margin.inline_start.non_auto().map(&mut add);
margin.inline_end.non_auto().map(&mut add);
outer.min_content += pbm_lengths;
outer.max_content += pbm_lengths;
(outer, pbm_percentages)
}
/// https://drafts.csswg.org/css2/visudet.html#shrink-to-fit-float
pub(crate) fn shrink_to_fit(&self, available_size: Length) -> Length {
let inline = self.expect_inline();
available_size
.max(inline.min_content)
.min(inline.max_content)
}
} | let mut pbm_percentages = Percentage::zero();
let padding = style.padding(); | random_line_split |
sizing.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/. */
//! https://drafts.csswg.org/css-sizing/
use crate::style_ext::ComputedValuesExt;
use style::properties::ComputedValues;
use style::values::computed::{Length, LengthPercentage, Percentage};
use style::values::generics::length::MaxSize;
use style::Zero;
/// Which min/max-content values should be computed during box construction
#[derive(Clone, Copy, Debug)]
pub(crate) enum ContentSizesRequest {
Inline,
None,
}
impl ContentSizesRequest {
pub fn inline_if(condition: bool) -> Self {
if condition {
Self::Inline
} else {
Self::None
}
}
pub fn requests_inline(self) -> bool {
match self {
Self::Inline => true,
Self::None => false,
}
}
pub fn if_requests_inline<T>(self, f: impl FnOnce() -> T) -> Option<T> {
match self {
Self::Inline => Some(f()),
Self::None => None,
}
}
pub fn compute(self, compute_inline: impl FnOnce() -> ContentSizes) -> BoxContentSizes {
match self {
Self::Inline => BoxContentSizes::Inline(compute_inline()),
Self::None => BoxContentSizes::NoneWereRequested,
}
}
}
#[derive(Clone, Debug, Serialize)]
pub(crate) struct ContentSizes {
pub min_content: Length,
pub max_content: Length,
}
/// https://drafts.csswg.org/css-sizing/#intrinsic-sizes
impl ContentSizes {
pub fn zero() -> Self {
Self {
min_content: Length::zero(),
max_content: Length::zero(),
}
}
pub fn max_assign(&mut self, other: &Self) {
self.min_content.max_assign(other.min_content);
self.max_content.max_assign(other.max_content);
}
/// Relevant to outer intrinsic inline sizes, for percentages from padding and margin.
pub fn adjust_for_pbm_percentages(&mut self, percentages: Percentage) {
// " Note that this may yield an infinite result, but undefined results
// (zero divided by zero) must be treated as zero. "
if self.max_content.px() == 0. {
// Avoid a potential `NaN`.
// Zero is already the result we want regardless of `denominator`.
} else {
let denominator = (1. - percentages.0).max(0.);
self.max_content = Length::new(self.max_content.px() / denominator);
}
}
}
/// Optional min/max-content for storage in the box tree
#[derive(Debug, Serialize)]
pub(crate) enum BoxContentSizes {
NoneWereRequested, // … during box construction
Inline(ContentSizes),
}
impl BoxContentSizes {
fn expect_inline(&self) -> &ContentSizes {
match self {
Self::NoneWereRequested => panic!("Accessing content size that was not requested"),
Self::Inline(s) => s,
}
}
/// https://dbaron.org/css/intrinsic/#outer-intrinsic
pub fn outer_inline(&self, style: &ComputedValues) -> ContentSizes {
let (mut outer, percentages) = self.outer_inline_and_percentages(style);
outer.adjust_for_pbm_percentages(percentages);
outer
}
pub(crate) fn outer_inline_and_percentages(
&self,
style: &ComputedValues,
) -> (ContentSizes, Percentage) {
// FIXME: account for 'box-sizing'
let inline_size = style.box_size().inline;
let min_inline_size = style
.min_box_size()
.inline
.percentage_relative_to(Length::zero())
.auto_is(Length::zero);
let max_inline_size = match style.max_box_size().inline {
MaxSize::None => None,
MaxSize::LengthPercentage(ref lp) => lp.to_length(),
};
let clamp = |l: Length| l.clamp_between_extremums(min_inline_size, max_inline_size);
// Percentages for 'width' are treated as 'auto'
let inline_size = inline_size.map(|lp| lp.to_length());
// The (inner) min/max-content are only used for 'auto'
let mut outer = match inline_size.non_auto().flatten() {
None => {
let inner = self.expect_inline().clone();
ContentSizes {
min_content: clamp(inner.min_content),
max_content: clamp(inner.max_content),
}
},
Some(length) => {
let length = clamp(length);
ContentSizes {
min_content: length,
max_content: length,
}
},
};
let mut pbm_lengths = Length::zero();
let mut pbm_percentages = Percentage::zero();
let padding = style.padding();
let border = style.border_width();
let margin = style.margin();
pbm_lengths += border.inline_sum();
let mut add = |x: LengthPercentage| {
if let Some(l) = x.to_length() {
pbm_lengths += l;
}
if let Some(p) = x.to_percentage() {
pbm_percentages += p;
}
};
add(padding.inline_start);
add(padding.inline_end);
margin.inline_start.non_auto().map(&mut add);
margin.inline_end.non_auto().map(&mut add);
outer.min_content += pbm_lengths;
outer.max_content += pbm_lengths;
(outer, pbm_percentages)
}
/// https://drafts.csswg.org/css2/visudet.html#shrink-to-fit-float
pub(crate) fn shrink_to_fit(&self, available_size: Length) -> Length {
| let inline = self.expect_inline();
available_size
.max(inline.min_content)
.min(inline.max_content)
}
} | identifier_body |
|
sizing.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/. */
//! https://drafts.csswg.org/css-sizing/
use crate::style_ext::ComputedValuesExt;
use style::properties::ComputedValues;
use style::values::computed::{Length, LengthPercentage, Percentage};
use style::values::generics::length::MaxSize;
use style::Zero;
/// Which min/max-content values should be computed during box construction
#[derive(Clone, Copy, Debug)]
pub(crate) enum ContentSizesRequest {
Inline,
None,
}
impl ContentSizesRequest {
pub fn inline_if(condition: bool) -> Self {
if condition {
Self::Inline
} else {
Self::None
}
}
pub fn requests_inline(self) -> bool {
match self {
Self::Inline => true,
Self::None => false,
}
}
pub fn if_requests_inline<T>(self, f: impl FnOnce() -> T) -> Option<T> {
match self {
Self::Inline => Some(f()),
Self::None => None,
}
}
pub fn compute(self, compute_inline: impl FnOnce() -> ContentSizes) -> BoxContentSizes {
match self {
Self::Inline => BoxContentSizes::Inline(compute_inline()),
Self::None => BoxContentSizes::NoneWereRequested,
}
}
}
#[derive(Clone, Debug, Serialize)]
pub(crate) struct ContentSizes {
pub min_content: Length,
pub max_content: Length,
}
/// https://drafts.csswg.org/css-sizing/#intrinsic-sizes
impl ContentSizes {
pub fn | () -> Self {
Self {
min_content: Length::zero(),
max_content: Length::zero(),
}
}
pub fn max_assign(&mut self, other: &Self) {
self.min_content.max_assign(other.min_content);
self.max_content.max_assign(other.max_content);
}
/// Relevant to outer intrinsic inline sizes, for percentages from padding and margin.
pub fn adjust_for_pbm_percentages(&mut self, percentages: Percentage) {
// " Note that this may yield an infinite result, but undefined results
// (zero divided by zero) must be treated as zero. "
if self.max_content.px() == 0. {
// Avoid a potential `NaN`.
// Zero is already the result we want regardless of `denominator`.
} else {
let denominator = (1. - percentages.0).max(0.);
self.max_content = Length::new(self.max_content.px() / denominator);
}
}
}
/// Optional min/max-content for storage in the box tree
#[derive(Debug, Serialize)]
pub(crate) enum BoxContentSizes {
NoneWereRequested, // … during box construction
Inline(ContentSizes),
}
impl BoxContentSizes {
fn expect_inline(&self) -> &ContentSizes {
match self {
Self::NoneWereRequested => panic!("Accessing content size that was not requested"),
Self::Inline(s) => s,
}
}
/// https://dbaron.org/css/intrinsic/#outer-intrinsic
pub fn outer_inline(&self, style: &ComputedValues) -> ContentSizes {
let (mut outer, percentages) = self.outer_inline_and_percentages(style);
outer.adjust_for_pbm_percentages(percentages);
outer
}
pub(crate) fn outer_inline_and_percentages(
&self,
style: &ComputedValues,
) -> (ContentSizes, Percentage) {
// FIXME: account for 'box-sizing'
let inline_size = style.box_size().inline;
let min_inline_size = style
.min_box_size()
.inline
.percentage_relative_to(Length::zero())
.auto_is(Length::zero);
let max_inline_size = match style.max_box_size().inline {
MaxSize::None => None,
MaxSize::LengthPercentage(ref lp) => lp.to_length(),
};
let clamp = |l: Length| l.clamp_between_extremums(min_inline_size, max_inline_size);
// Percentages for 'width' are treated as 'auto'
let inline_size = inline_size.map(|lp| lp.to_length());
// The (inner) min/max-content are only used for 'auto'
let mut outer = match inline_size.non_auto().flatten() {
None => {
let inner = self.expect_inline().clone();
ContentSizes {
min_content: clamp(inner.min_content),
max_content: clamp(inner.max_content),
}
},
Some(length) => {
let length = clamp(length);
ContentSizes {
min_content: length,
max_content: length,
}
},
};
let mut pbm_lengths = Length::zero();
let mut pbm_percentages = Percentage::zero();
let padding = style.padding();
let border = style.border_width();
let margin = style.margin();
pbm_lengths += border.inline_sum();
let mut add = |x: LengthPercentage| {
if let Some(l) = x.to_length() {
pbm_lengths += l;
}
if let Some(p) = x.to_percentage() {
pbm_percentages += p;
}
};
add(padding.inline_start);
add(padding.inline_end);
margin.inline_start.non_auto().map(&mut add);
margin.inline_end.non_auto().map(&mut add);
outer.min_content += pbm_lengths;
outer.max_content += pbm_lengths;
(outer, pbm_percentages)
}
/// https://drafts.csswg.org/css2/visudet.html#shrink-to-fit-float
pub(crate) fn shrink_to_fit(&self, available_size: Length) -> Length {
let inline = self.expect_inline();
available_size
.max(inline.min_content)
.min(inline.max_content)
}
}
| zero | identifier_name |
worker.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg};
use dom::abstractworker::{SharedRt, SimpleWorkerErrorHandler};
use dom::abstractworker::WorkerScriptMsg;
use dom::bindings::codegen::Bindings::WorkerBinding;
use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope;
use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use dom::messageevent::MessageEvent;
use dom::workerglobalscope::prepare_workerscope_init;
use dom_struct::dom_struct;
use ipc_channel::ipc;
use js::jsapi::{HandleValue, JSAutoCompartment, JSContext};
use js::jsval::UndefinedValue;
use script_traits::WorkerScriptLoadOrigin;
use std::cell::Cell;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Sender, channel};
use task::TaskOnce;
pub type TrustedWorkerAddress = Trusted<Worker>;
// https://html.spec.whatwg.org/multipage/#worker
#[dom_struct]
pub struct Worker {
eventtarget: EventTarget,
#[ignore_malloc_size_of = "Defined in std"]
/// Sender to the Receiver associated with the DedicatedWorkerGlobalScope
/// this Worker created.
sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
#[ignore_malloc_size_of = "Arc"]
closing: Arc<AtomicBool>,
#[ignore_malloc_size_of = "Defined in rust-mozjs"]
runtime: Arc<Mutex<Option<SharedRt>>>,
terminated: Cell<bool>,
}
impl Worker {
fn new_inherited(sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
closing: Arc<AtomicBool>) -> Worker {
Worker {
eventtarget: EventTarget::new_inherited(),
sender: sender,
closing: closing,
runtime: Arc::new(Mutex::new(None)),
terminated: Cell::new(false),
}
}
pub fn new(global: &GlobalScope,
sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
closing: Arc<AtomicBool>) -> DomRoot<Worker> {
reflect_dom_object(Box::new(Worker::new_inherited(sender, closing)),
global,
WorkerBinding::Wrap)
}
// https://html.spec.whatwg.org/multipage/#dom-worker
#[allow(unsafe_code)]
pub fn Constructor(global: &GlobalScope, script_url: DOMString) -> Fallible<DomRoot<Worker>> {
// Step 2-4.
let worker_url = match global.api_base_url().join(&script_url) {
Ok(url) => url,
Err(_) => return Err(Error::Syntax),
};
let (sender, receiver) = channel();
let closing = Arc::new(AtomicBool::new(false));
let worker = Worker::new(global, sender.clone(), closing.clone());
let worker_ref = Trusted::new(&*worker);
let worker_load_origin = WorkerScriptLoadOrigin {
referrer_url: None,
referrer_policy: None,
pipeline_id: Some(global.pipeline_id()),
};
let (devtools_sender, devtools_receiver) = ipc::channel().unwrap();
let worker_id = global.get_next_worker_id();
if let Some(ref chan) = global.devtools_chan() {
let pipeline_id = global.pipeline_id();
let title = format!("Worker for {}", worker_url);
let page_info = DevtoolsPageInfo {
title: title,
url: worker_url.clone(),
};
let _ = chan.send(ScriptToDevtoolsControlMsg::NewGlobal((pipeline_id, Some(worker_id)),
devtools_sender.clone(),
page_info));
}
let init = prepare_workerscope_init(global, Some(devtools_sender));
DedicatedWorkerGlobalScope::run_worker_scope(
init, worker_url, devtools_receiver, worker.runtime.clone(), worker_ref,
global.script_chan(), sender, receiver, worker_load_origin, closing);
Ok(worker)
}
pub fn is_closing(&self) -> bool {
self.closing.load(Ordering::SeqCst)
}
pub fn is_terminated(&self) -> bool {
self.terminated.get()
}
pub fn handle_message(address: TrustedWorkerAddress,
data: StructuredCloneData) {
let worker = address.root();
if worker.is_terminated() {
return;
}
let global = worker.global();
let target = worker.upcast();
let _ac = JSAutoCompartment::new(global.get_cx(), target.reflector().get_jsobject().get());
rooted!(in(global.get_cx()) let mut message = UndefinedValue());
data.read(&global, message.handle_mut());
MessageEvent::dispatch_jsval(target, &global, message.handle());
}
pub fn | (address: TrustedWorkerAddress) {
let worker = address.root();
worker.upcast().fire_event(atom!("error"));
}
}
impl WorkerMethods for Worker {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-worker-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult {
let data = StructuredCloneData::write(cx, message)?;
let address = Trusted::new(self);
// NOTE: step 9 of https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage
// indicates that a nonexistent communication channel should result in a silent error.
let _ = self.sender.send((address, WorkerScriptMsg::DOMMessage(data)));
Ok(())
}
// https://html.spec.whatwg.org/multipage/#terminate-a-worker
fn Terminate(&self) {
// Step 1
if self.closing.swap(true, Ordering::SeqCst) {
return;
}
// Step 2
self.terminated.set(true);
// Step 3
if let Some(runtime) = *self.runtime.lock().unwrap() {
runtime.request_interrupt();
}
}
// https://html.spec.whatwg.org/multipage/#handler-worker-onmessage
event_handler!(message, GetOnmessage, SetOnmessage);
// https://html.spec.whatwg.org/multipage/#handler-workerglobalscope-onerror
event_handler!(error, GetOnerror, SetOnerror);
}
impl TaskOnce for SimpleWorkerErrorHandler<Worker> {
#[allow(unrooted_must_root)]
fn run_once(self) {
Worker::dispatch_simple_error(self.addr);
}
}
| dispatch_simple_error | identifier_name |
worker.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg};
use dom::abstractworker::{SharedRt, SimpleWorkerErrorHandler};
use dom::abstractworker::WorkerScriptMsg;
use dom::bindings::codegen::Bindings::WorkerBinding;
use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope;
use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use dom::messageevent::MessageEvent;
use dom::workerglobalscope::prepare_workerscope_init;
use dom_struct::dom_struct;
use ipc_channel::ipc;
use js::jsapi::{HandleValue, JSAutoCompartment, JSContext};
use js::jsval::UndefinedValue;
use script_traits::WorkerScriptLoadOrigin;
use std::cell::Cell;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Sender, channel};
use task::TaskOnce;
pub type TrustedWorkerAddress = Trusted<Worker>;
// https://html.spec.whatwg.org/multipage/#worker
#[dom_struct]
pub struct Worker {
eventtarget: EventTarget,
#[ignore_malloc_size_of = "Defined in std"]
/// Sender to the Receiver associated with the DedicatedWorkerGlobalScope
/// this Worker created.
sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
#[ignore_malloc_size_of = "Arc"]
closing: Arc<AtomicBool>,
#[ignore_malloc_size_of = "Defined in rust-mozjs"]
runtime: Arc<Mutex<Option<SharedRt>>>,
terminated: Cell<bool>,
}
impl Worker {
fn new_inherited(sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
closing: Arc<AtomicBool>) -> Worker {
Worker {
eventtarget: EventTarget::new_inherited(),
sender: sender,
closing: closing,
runtime: Arc::new(Mutex::new(None)),
terminated: Cell::new(false),
}
}
pub fn new(global: &GlobalScope,
sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
closing: Arc<AtomicBool>) -> DomRoot<Worker> {
reflect_dom_object(Box::new(Worker::new_inherited(sender, closing)),
global,
WorkerBinding::Wrap)
}
// https://html.spec.whatwg.org/multipage/#dom-worker
#[allow(unsafe_code)]
pub fn Constructor(global: &GlobalScope, script_url: DOMString) -> Fallible<DomRoot<Worker>> {
// Step 2-4.
let worker_url = match global.api_base_url().join(&script_url) {
Ok(url) => url,
Err(_) => return Err(Error::Syntax),
};
let (sender, receiver) = channel();
let closing = Arc::new(AtomicBool::new(false));
let worker = Worker::new(global, sender.clone(), closing.clone());
let worker_ref = Trusted::new(&*worker);
let worker_load_origin = WorkerScriptLoadOrigin {
referrer_url: None,
referrer_policy: None,
pipeline_id: Some(global.pipeline_id()),
};
let (devtools_sender, devtools_receiver) = ipc::channel().unwrap();
let worker_id = global.get_next_worker_id();
if let Some(ref chan) = global.devtools_chan() {
let pipeline_id = global.pipeline_id();
let title = format!("Worker for {}", worker_url);
let page_info = DevtoolsPageInfo {
title: title,
url: worker_url.clone(),
};
let _ = chan.send(ScriptToDevtoolsControlMsg::NewGlobal((pipeline_id, Some(worker_id)),
devtools_sender.clone(),
page_info));
}
let init = prepare_workerscope_init(global, Some(devtools_sender));
DedicatedWorkerGlobalScope::run_worker_scope(
init, worker_url, devtools_receiver, worker.runtime.clone(), worker_ref,
global.script_chan(), sender, receiver, worker_load_origin, closing);
Ok(worker)
}
pub fn is_closing(&self) -> bool {
self.closing.load(Ordering::SeqCst)
}
pub fn is_terminated(&self) -> bool {
self.terminated.get()
}
pub fn handle_message(address: TrustedWorkerAddress,
data: StructuredCloneData) {
let worker = address.root();
if worker.is_terminated() |
let global = worker.global();
let target = worker.upcast();
let _ac = JSAutoCompartment::new(global.get_cx(), target.reflector().get_jsobject().get());
rooted!(in(global.get_cx()) let mut message = UndefinedValue());
data.read(&global, message.handle_mut());
MessageEvent::dispatch_jsval(target, &global, message.handle());
}
pub fn dispatch_simple_error(address: TrustedWorkerAddress) {
let worker = address.root();
worker.upcast().fire_event(atom!("error"));
}
}
impl WorkerMethods for Worker {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-worker-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult {
let data = StructuredCloneData::write(cx, message)?;
let address = Trusted::new(self);
// NOTE: step 9 of https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage
// indicates that a nonexistent communication channel should result in a silent error.
let _ = self.sender.send((address, WorkerScriptMsg::DOMMessage(data)));
Ok(())
}
// https://html.spec.whatwg.org/multipage/#terminate-a-worker
fn Terminate(&self) {
// Step 1
if self.closing.swap(true, Ordering::SeqCst) {
return;
}
// Step 2
self.terminated.set(true);
// Step 3
if let Some(runtime) = *self.runtime.lock().unwrap() {
runtime.request_interrupt();
}
}
// https://html.spec.whatwg.org/multipage/#handler-worker-onmessage
event_handler!(message, GetOnmessage, SetOnmessage);
// https://html.spec.whatwg.org/multipage/#handler-workerglobalscope-onerror
event_handler!(error, GetOnerror, SetOnerror);
}
impl TaskOnce for SimpleWorkerErrorHandler<Worker> {
#[allow(unrooted_must_root)]
fn run_once(self) {
Worker::dispatch_simple_error(self.addr);
}
}
| {
return;
} | conditional_block |
worker.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg};
use dom::abstractworker::{SharedRt, SimpleWorkerErrorHandler};
use dom::abstractworker::WorkerScriptMsg;
use dom::bindings::codegen::Bindings::WorkerBinding;
use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope;
use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use dom::messageevent::MessageEvent;
use dom::workerglobalscope::prepare_workerscope_init;
use dom_struct::dom_struct;
use ipc_channel::ipc;
use js::jsapi::{HandleValue, JSAutoCompartment, JSContext};
use js::jsval::UndefinedValue;
use script_traits::WorkerScriptLoadOrigin;
use std::cell::Cell;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Sender, channel};
use task::TaskOnce;
pub type TrustedWorkerAddress = Trusted<Worker>;
// https://html.spec.whatwg.org/multipage/#worker
#[dom_struct]
pub struct Worker {
eventtarget: EventTarget,
#[ignore_malloc_size_of = "Defined in std"]
/// Sender to the Receiver associated with the DedicatedWorkerGlobalScope
/// this Worker created.
sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
#[ignore_malloc_size_of = "Arc"]
closing: Arc<AtomicBool>,
#[ignore_malloc_size_of = "Defined in rust-mozjs"]
runtime: Arc<Mutex<Option<SharedRt>>>,
terminated: Cell<bool>,
}
impl Worker {
fn new_inherited(sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
closing: Arc<AtomicBool>) -> Worker {
Worker {
eventtarget: EventTarget::new_inherited(),
sender: sender,
closing: closing,
runtime: Arc::new(Mutex::new(None)),
terminated: Cell::new(false),
}
} |
pub fn new(global: &GlobalScope,
sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
closing: Arc<AtomicBool>) -> DomRoot<Worker> {
reflect_dom_object(Box::new(Worker::new_inherited(sender, closing)),
global,
WorkerBinding::Wrap)
}
// https://html.spec.whatwg.org/multipage/#dom-worker
#[allow(unsafe_code)]
pub fn Constructor(global: &GlobalScope, script_url: DOMString) -> Fallible<DomRoot<Worker>> {
// Step 2-4.
let worker_url = match global.api_base_url().join(&script_url) {
Ok(url) => url,
Err(_) => return Err(Error::Syntax),
};
let (sender, receiver) = channel();
let closing = Arc::new(AtomicBool::new(false));
let worker = Worker::new(global, sender.clone(), closing.clone());
let worker_ref = Trusted::new(&*worker);
let worker_load_origin = WorkerScriptLoadOrigin {
referrer_url: None,
referrer_policy: None,
pipeline_id: Some(global.pipeline_id()),
};
let (devtools_sender, devtools_receiver) = ipc::channel().unwrap();
let worker_id = global.get_next_worker_id();
if let Some(ref chan) = global.devtools_chan() {
let pipeline_id = global.pipeline_id();
let title = format!("Worker for {}", worker_url);
let page_info = DevtoolsPageInfo {
title: title,
url: worker_url.clone(),
};
let _ = chan.send(ScriptToDevtoolsControlMsg::NewGlobal((pipeline_id, Some(worker_id)),
devtools_sender.clone(),
page_info));
}
let init = prepare_workerscope_init(global, Some(devtools_sender));
DedicatedWorkerGlobalScope::run_worker_scope(
init, worker_url, devtools_receiver, worker.runtime.clone(), worker_ref,
global.script_chan(), sender, receiver, worker_load_origin, closing);
Ok(worker)
}
pub fn is_closing(&self) -> bool {
self.closing.load(Ordering::SeqCst)
}
pub fn is_terminated(&self) -> bool {
self.terminated.get()
}
pub fn handle_message(address: TrustedWorkerAddress,
data: StructuredCloneData) {
let worker = address.root();
if worker.is_terminated() {
return;
}
let global = worker.global();
let target = worker.upcast();
let _ac = JSAutoCompartment::new(global.get_cx(), target.reflector().get_jsobject().get());
rooted!(in(global.get_cx()) let mut message = UndefinedValue());
data.read(&global, message.handle_mut());
MessageEvent::dispatch_jsval(target, &global, message.handle());
}
pub fn dispatch_simple_error(address: TrustedWorkerAddress) {
let worker = address.root();
worker.upcast().fire_event(atom!("error"));
}
}
impl WorkerMethods for Worker {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-worker-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult {
let data = StructuredCloneData::write(cx, message)?;
let address = Trusted::new(self);
// NOTE: step 9 of https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage
// indicates that a nonexistent communication channel should result in a silent error.
let _ = self.sender.send((address, WorkerScriptMsg::DOMMessage(data)));
Ok(())
}
// https://html.spec.whatwg.org/multipage/#terminate-a-worker
fn Terminate(&self) {
// Step 1
if self.closing.swap(true, Ordering::SeqCst) {
return;
}
// Step 2
self.terminated.set(true);
// Step 3
if let Some(runtime) = *self.runtime.lock().unwrap() {
runtime.request_interrupt();
}
}
// https://html.spec.whatwg.org/multipage/#handler-worker-onmessage
event_handler!(message, GetOnmessage, SetOnmessage);
// https://html.spec.whatwg.org/multipage/#handler-workerglobalscope-onerror
event_handler!(error, GetOnerror, SetOnerror);
}
impl TaskOnce for SimpleWorkerErrorHandler<Worker> {
#[allow(unrooted_must_root)]
fn run_once(self) {
Worker::dispatch_simple_error(self.addr);
}
} | random_line_split |
|
overloaded-deref-count.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.
use std::cell::Cell;
use std::ops::{Deref, DerefMut};
use std::vec::Vec;
struct DerefCounter<T> {
count_imm: Cell<uint>,
count_mut: uint,
value: T
}
impl<T> DerefCounter<T> {
fn new(value: T) -> DerefCounter<T> {
DerefCounter {
count_imm: Cell::new(0),
count_mut: 0,
value: value
}
}
fn counts(&self) -> (uint, uint) {
(self.count_imm.get(), self.count_mut)
}
} | self.count_imm.set(self.count_imm.get() + 1);
&self.value
}
}
impl<T> DerefMut<T> for DerefCounter<T> {
fn deref_mut(&mut self) -> &mut T {
self.count_mut += 1;
&mut self.value
}
}
pub fn main() {
let mut n = DerefCounter::new(0i);
let mut v = DerefCounter::new(Vec::new());
let _ = *n; // Immutable deref + copy a POD.
assert_eq!(n.counts(), (1, 0));
let _ = (&*n, &*v); // Immutable deref + borrow.
assert_eq!(n.counts(), (2, 0)); assert_eq!(v.counts(), (1, 0));
let _ = (&mut *n, &mut *v); // Mutable deref + mutable borrow.
assert_eq!(n.counts(), (2, 1)); assert_eq!(v.counts(), (1, 1));
let mut v2 = Vec::new();
v2.push(1i);
*n = 5; *v = v2; // Mutable deref + assignment.
assert_eq!(n.counts(), (2, 2)); assert_eq!(v.counts(), (1, 2));
*n -= 3; // Mutable deref + assignment with binary operation.
assert_eq!(n.counts(), (2, 3));
// Immutable deref used for calling a method taking &self. (The
// typechecker is smarter now about doing this.)
(*n).to_string();
assert_eq!(n.counts(), (3, 3));
// Mutable deref used for calling a method taking &mut self.
(*v).push(2);
assert_eq!(v.counts(), (1, 3));
// Check the final states.
assert_eq!(*n, 2);
let expected: &[_] = &[1, 2];
assert_eq!((*v).as_slice(), expected);
} |
impl<T> Deref<T> for DerefCounter<T> {
fn deref(&self) -> &T { | random_line_split |
overloaded-deref-count.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.
use std::cell::Cell;
use std::ops::{Deref, DerefMut};
use std::vec::Vec;
struct DerefCounter<T> {
count_imm: Cell<uint>,
count_mut: uint,
value: T
}
impl<T> DerefCounter<T> {
fn new(value: T) -> DerefCounter<T> {
DerefCounter {
count_imm: Cell::new(0),
count_mut: 0,
value: value
}
}
fn | (&self) -> (uint, uint) {
(self.count_imm.get(), self.count_mut)
}
}
impl<T> Deref<T> for DerefCounter<T> {
fn deref(&self) -> &T {
self.count_imm.set(self.count_imm.get() + 1);
&self.value
}
}
impl<T> DerefMut<T> for DerefCounter<T> {
fn deref_mut(&mut self) -> &mut T {
self.count_mut += 1;
&mut self.value
}
}
pub fn main() {
let mut n = DerefCounter::new(0i);
let mut v = DerefCounter::new(Vec::new());
let _ = *n; // Immutable deref + copy a POD.
assert_eq!(n.counts(), (1, 0));
let _ = (&*n, &*v); // Immutable deref + borrow.
assert_eq!(n.counts(), (2, 0)); assert_eq!(v.counts(), (1, 0));
let _ = (&mut *n, &mut *v); // Mutable deref + mutable borrow.
assert_eq!(n.counts(), (2, 1)); assert_eq!(v.counts(), (1, 1));
let mut v2 = Vec::new();
v2.push(1i);
*n = 5; *v = v2; // Mutable deref + assignment.
assert_eq!(n.counts(), (2, 2)); assert_eq!(v.counts(), (1, 2));
*n -= 3; // Mutable deref + assignment with binary operation.
assert_eq!(n.counts(), (2, 3));
// Immutable deref used for calling a method taking &self. (The
// typechecker is smarter now about doing this.)
(*n).to_string();
assert_eq!(n.counts(), (3, 3));
// Mutable deref used for calling a method taking &mut self.
(*v).push(2);
assert_eq!(v.counts(), (1, 3));
// Check the final states.
assert_eq!(*n, 2);
let expected: &[_] = &[1, 2];
assert_eq!((*v).as_slice(), expected);
}
| counts | identifier_name |
overloaded-deref-count.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.
use std::cell::Cell;
use std::ops::{Deref, DerefMut};
use std::vec::Vec;
struct DerefCounter<T> {
count_imm: Cell<uint>,
count_mut: uint,
value: T
}
impl<T> DerefCounter<T> {
fn new(value: T) -> DerefCounter<T> {
DerefCounter {
count_imm: Cell::new(0),
count_mut: 0,
value: value
}
}
fn counts(&self) -> (uint, uint) |
}
impl<T> Deref<T> for DerefCounter<T> {
fn deref(&self) -> &T {
self.count_imm.set(self.count_imm.get() + 1);
&self.value
}
}
impl<T> DerefMut<T> for DerefCounter<T> {
fn deref_mut(&mut self) -> &mut T {
self.count_mut += 1;
&mut self.value
}
}
pub fn main() {
let mut n = DerefCounter::new(0i);
let mut v = DerefCounter::new(Vec::new());
let _ = *n; // Immutable deref + copy a POD.
assert_eq!(n.counts(), (1, 0));
let _ = (&*n, &*v); // Immutable deref + borrow.
assert_eq!(n.counts(), (2, 0)); assert_eq!(v.counts(), (1, 0));
let _ = (&mut *n, &mut *v); // Mutable deref + mutable borrow.
assert_eq!(n.counts(), (2, 1)); assert_eq!(v.counts(), (1, 1));
let mut v2 = Vec::new();
v2.push(1i);
*n = 5; *v = v2; // Mutable deref + assignment.
assert_eq!(n.counts(), (2, 2)); assert_eq!(v.counts(), (1, 2));
*n -= 3; // Mutable deref + assignment with binary operation.
assert_eq!(n.counts(), (2, 3));
// Immutable deref used for calling a method taking &self. (The
// typechecker is smarter now about doing this.)
(*n).to_string();
assert_eq!(n.counts(), (3, 3));
// Mutable deref used for calling a method taking &mut self.
(*v).push(2);
assert_eq!(v.counts(), (1, 3));
// Check the final states.
assert_eq!(*n, 2);
let expected: &[_] = &[1, 2];
assert_eq!((*v).as_slice(), expected);
}
| {
(self.count_imm.get(), self.count_mut)
} | identifier_body |
iter.rs | use ::NbitsVec;
use num::PrimInt;
use typenum::NonZero;
use typenum::uint::Unsigned;
pub struct Iter<'a, N:'a, Block: 'a> where N: Unsigned + NonZero, Block: PrimInt {
vec: &'a NbitsVec<N, Block>,
pos: usize,
}
impl<'a, N:'a, Block: 'a> Iter<'a, N, Block> where N: Unsigned + NonZero, Block: PrimInt {
}
impl<'a, N:'a, Block: 'a> Iterator for Iter<'a, N, Block> where N: Unsigned + NonZero, Block: PrimInt {
type Item = Block;
#[inline]
fn next(&mut self) -> Option<Block> {
self.pos += 1;
if self.vec.len() > self.pos | else {
None
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
match self.vec.len() {
len if len > self.pos => {
let diff = len - self.pos;
(diff, Some(diff))
},
_ => (0, None),
}
}
#[inline]
fn count(self) -> usize {
self.size_hint().0
}
#[inline]
fn nth(&mut self, n: usize) -> Option<Block> {
self.pos += n;
if self.vec.len() > self.pos {
Some(self.vec.get(self.pos))
} else {
None
}
}
}
impl<'a, N:'a, Block: 'a> IntoIterator for &'a NbitsVec<N, Block> where N: Unsigned + NonZero, Block: PrimInt {
type Item = Block;
type IntoIter = Iter<'a, N, Block>;
fn into_iter(self) -> Iter<'a, N, Block> {
Iter {
vec: self,
pos: 0,
}
}
}
#[cfg(test)]
mod tests {
use ::{NbitsVec, N2};
type NV = NbitsVec<N2, usize>;
#[test]
fn into_iter() {
let vec = NV::new();
for val in vec.into_iter() {
let _ = val;
}
}
}
| {
Some(self.vec.get(self.pos))
} | conditional_block |
iter.rs | use ::NbitsVec;
use num::PrimInt;
use typenum::NonZero;
use typenum::uint::Unsigned;
pub struct Iter<'a, N:'a, Block: 'a> where N: Unsigned + NonZero, Block: PrimInt {
vec: &'a NbitsVec<N, Block>,
pos: usize,
}
impl<'a, N:'a, Block: 'a> Iter<'a, N, Block> where N: Unsigned + NonZero, Block: PrimInt {
}
impl<'a, N:'a, Block: 'a> Iterator for Iter<'a, N, Block> where N: Unsigned + NonZero, Block: PrimInt {
type Item = Block;
#[inline]
fn next(&mut self) -> Option<Block> {
self.pos += 1;
if self.vec.len() > self.pos {
Some(self.vec.get(self.pos))
} else {
None
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
match self.vec.len() {
len if len > self.pos => {
let diff = len - self.pos;
(diff, Some(diff))
},
_ => (0, None),
}
}
#[inline]
fn | (self) -> usize {
self.size_hint().0
}
#[inline]
fn nth(&mut self, n: usize) -> Option<Block> {
self.pos += n;
if self.vec.len() > self.pos {
Some(self.vec.get(self.pos))
} else {
None
}
}
}
impl<'a, N:'a, Block: 'a> IntoIterator for &'a NbitsVec<N, Block> where N: Unsigned + NonZero, Block: PrimInt {
type Item = Block;
type IntoIter = Iter<'a, N, Block>;
fn into_iter(self) -> Iter<'a, N, Block> {
Iter {
vec: self,
pos: 0,
}
}
}
#[cfg(test)]
mod tests {
use ::{NbitsVec, N2};
type NV = NbitsVec<N2, usize>;
#[test]
fn into_iter() {
let vec = NV::new();
for val in vec.into_iter() {
let _ = val;
}
}
}
| count | identifier_name |
iter.rs | use ::NbitsVec;
use num::PrimInt;
use typenum::NonZero;
use typenum::uint::Unsigned;
pub struct Iter<'a, N:'a, Block: 'a> where N: Unsigned + NonZero, Block: PrimInt {
vec: &'a NbitsVec<N, Block>,
pos: usize,
}
impl<'a, N:'a, Block: 'a> Iter<'a, N, Block> where N: Unsigned + NonZero, Block: PrimInt {
}
impl<'a, N:'a, Block: 'a> Iterator for Iter<'a, N, Block> where N: Unsigned + NonZero, Block: PrimInt {
type Item = Block;
#[inline]
fn next(&mut self) -> Option<Block> {
self.pos += 1;
if self.vec.len() > self.pos {
Some(self.vec.get(self.pos))
} else {
None
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
match self.vec.len() {
len if len > self.pos => {
let diff = len - self.pos;
(diff, Some(diff))
},
_ => (0, None),
}
}
#[inline]
fn count(self) -> usize {
self.size_hint().0
}
#[inline]
fn nth(&mut self, n: usize) -> Option<Block> |
}
impl<'a, N:'a, Block: 'a> IntoIterator for &'a NbitsVec<N, Block> where N: Unsigned + NonZero, Block: PrimInt {
type Item = Block;
type IntoIter = Iter<'a, N, Block>;
fn into_iter(self) -> Iter<'a, N, Block> {
Iter {
vec: self,
pos: 0,
}
}
}
#[cfg(test)]
mod tests {
use ::{NbitsVec, N2};
type NV = NbitsVec<N2, usize>;
#[test]
fn into_iter() {
let vec = NV::new();
for val in vec.into_iter() {
let _ = val;
}
}
}
| {
self.pos += n;
if self.vec.len() > self.pos {
Some(self.vec.get(self.pos))
} else {
None
}
} | identifier_body |
iter.rs | use ::NbitsVec;
use num::PrimInt;
use typenum::NonZero;
use typenum::uint::Unsigned;
pub struct Iter<'a, N:'a, Block: 'a> where N: Unsigned + NonZero, Block: PrimInt {
vec: &'a NbitsVec<N, Block>,
pos: usize,
}
impl<'a, N:'a, Block: 'a> Iter<'a, N, Block> where N: Unsigned + NonZero, Block: PrimInt {
}
impl<'a, N:'a, Block: 'a> Iterator for Iter<'a, N, Block> where N: Unsigned + NonZero, Block: PrimInt {
type Item = Block;
#[inline]
fn next(&mut self) -> Option<Block> {
self.pos += 1;
if self.vec.len() > self.pos {
Some(self.vec.get(self.pos))
} else {
None
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
match self.vec.len() {
len if len > self.pos => {
let diff = len - self.pos;
(diff, Some(diff))
},
_ => (0, None),
}
}
| #[inline]
fn nth(&mut self, n: usize) -> Option<Block> {
self.pos += n;
if self.vec.len() > self.pos {
Some(self.vec.get(self.pos))
} else {
None
}
}
}
impl<'a, N:'a, Block: 'a> IntoIterator for &'a NbitsVec<N, Block> where N: Unsigned + NonZero, Block: PrimInt {
type Item = Block;
type IntoIter = Iter<'a, N, Block>;
fn into_iter(self) -> Iter<'a, N, Block> {
Iter {
vec: self,
pos: 0,
}
}
}
#[cfg(test)]
mod tests {
use ::{NbitsVec, N2};
type NV = NbitsVec<N2, usize>;
#[test]
fn into_iter() {
let vec = NV::new();
for val in vec.into_iter() {
let _ = val;
}
}
} | #[inline]
fn count(self) -> usize {
self.size_hint().0
}
| random_line_split |
rec-align-u64.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.
// Issue #2303
mod rusti {
#[abi = "rust-intrinsic"]
pub extern "rust-intrinsic" {
pub fn pref_align_of<T>() -> uint;
pub fn min_align_of<T>() -> uint;
}
}
// This is the type with the questionable alignment
struct Inner {
c64: u64
}
// This is the type that contains the type with the
// questionable alignment, for testing
struct Outer {
c8: u8,
t: Inner
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
mod m {
#[cfg(target_arch = "x86")]
pub mod m {
pub fn align() -> uint { 4u }
pub fn size() -> uint { 12u }
}
#[cfg(target_arch = "x86_64")]
mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
#[cfg(target_os = "win32")]
mod m {
#[cfg(target_arch = "x86")]
pub mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
#[cfg(target_os = "android")]
mod m {
#[cfg(target_arch = "arm")]
pub mod m {
pub fn align() -> uint { 4u }
pub fn size() -> uint { 12u } | pub fn main() {
unsafe {
let x = Outer {c8: 22u8, t: Inner {c64: 44u64}};
// Send it through the shape code
let y = fmt!("%?", x);
debug!("align inner = %?", rusti::min_align_of::<Inner>());
debug!("size outer = %?", sys::size_of::<Outer>());
debug!("y = %s", y);
// per clang/gcc the alignment of `Inner` is 4 on x86.
assert!(rusti::min_align_of::<Inner>() == m::m::align());
// per clang/gcc the size of `Outer` should be 12
// because `Inner`s alignment was 4.
assert!(sys::size_of::<Outer>() == m::m::size());
assert!(y == ~"{c8: 22, t: {c64: 44}}");
}
} | }
}
| random_line_split |
rec-align-u64.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.
// Issue #2303
mod rusti {
#[abi = "rust-intrinsic"]
pub extern "rust-intrinsic" {
pub fn pref_align_of<T>() -> uint;
pub fn min_align_of<T>() -> uint;
}
}
// This is the type with the questionable alignment
struct Inner {
c64: u64
}
// This is the type that contains the type with the
// questionable alignment, for testing
struct Outer {
c8: u8,
t: Inner
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
mod m {
#[cfg(target_arch = "x86")]
pub mod m {
pub fn align() -> uint { 4u }
pub fn size() -> uint { 12u }
}
#[cfg(target_arch = "x86_64")]
mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
#[cfg(target_os = "win32")]
mod m {
#[cfg(target_arch = "x86")]
pub mod m {
pub fn | () -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
#[cfg(target_os = "android")]
mod m {
#[cfg(target_arch = "arm")]
pub mod m {
pub fn align() -> uint { 4u }
pub fn size() -> uint { 12u }
}
}
pub fn main() {
unsafe {
let x = Outer {c8: 22u8, t: Inner {c64: 44u64}};
// Send it through the shape code
let y = fmt!("%?", x);
debug!("align inner = %?", rusti::min_align_of::<Inner>());
debug!("size outer = %?", sys::size_of::<Outer>());
debug!("y = %s", y);
// per clang/gcc the alignment of `Inner` is 4 on x86.
assert!(rusti::min_align_of::<Inner>() == m::m::align());
// per clang/gcc the size of `Outer` should be 12
// because `Inner`s alignment was 4.
assert!(sys::size_of::<Outer>() == m::m::size());
assert!(y == ~"{c8: 22, t: {c64: 44}}");
}
}
| align | identifier_name |
rec-align-u64.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.
// Issue #2303
mod rusti {
#[abi = "rust-intrinsic"]
pub extern "rust-intrinsic" {
pub fn pref_align_of<T>() -> uint;
pub fn min_align_of<T>() -> uint;
}
}
// This is the type with the questionable alignment
struct Inner {
c64: u64
}
// This is the type that contains the type with the
// questionable alignment, for testing
struct Outer {
c8: u8,
t: Inner
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
mod m {
#[cfg(target_arch = "x86")]
pub mod m {
pub fn align() -> uint |
pub fn size() -> uint { 12u }
}
#[cfg(target_arch = "x86_64")]
mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
#[cfg(target_os = "win32")]
mod m {
#[cfg(target_arch = "x86")]
pub mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
#[cfg(target_os = "android")]
mod m {
#[cfg(target_arch = "arm")]
pub mod m {
pub fn align() -> uint { 4u }
pub fn size() -> uint { 12u }
}
}
pub fn main() {
unsafe {
let x = Outer {c8: 22u8, t: Inner {c64: 44u64}};
// Send it through the shape code
let y = fmt!("%?", x);
debug!("align inner = %?", rusti::min_align_of::<Inner>());
debug!("size outer = %?", sys::size_of::<Outer>());
debug!("y = %s", y);
// per clang/gcc the alignment of `Inner` is 4 on x86.
assert!(rusti::min_align_of::<Inner>() == m::m::align());
// per clang/gcc the size of `Outer` should be 12
// because `Inner`s alignment was 4.
assert!(sys::size_of::<Outer>() == m::m::size());
assert!(y == ~"{c8: 22, t: {c64: 44}}");
}
}
| { 4u } | identifier_body |
main.rs | //Test File gtk_test
extern crate gtk;
//Custom mods
mod system_io;
mod gtk_converter;
pub mod m_config;
//Os interaction
use std::process::Command;
use std::process::ChildStdout;
use std::io;
use std::io::prelude::*;
use gtk::Builder;
use gtk::prelude::*;
// make moving clones into closures more convenient
//shameless copied from the examples
macro_rules! clone {
(@param _) => ( _ );
(@param $x:ident) => ( $x );
($($n:ident),+ => move || $body:expr) => (
{
$( let $n = $n.clone(); )+
move || $body
}
);
($($n:ident),+ => move |$($p:tt),+| $body:expr) => (
{
$( let $n = $n.clone(); )+
move |$(clone!(@param $p),)+| $body
}
);
}
fn execute_command(location: &String, command: &String, arguments: &String) |
fn convert_to_str(x: &str) -> &str{
x
}
fn main() {
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let glade_src = include_str!("shipload.glade");
let builder = Builder::new();
builder.add_from_string(glade_src).unwrap();
//**********************************************
//Crucial
let configuration = m_config::create_config();
//Main
//Get Window
let window: gtk::Window = builder.get_object("window").unwrap();
//Close Button
let close_button: gtk::Button = builder.get_object("B_Close").unwrap();
//Set Header bar information
let header: gtk::HeaderBar = builder.get_object("Header").unwrap();
let pref_window: gtk::Window = builder.get_object("W_Preferences").unwrap();
let pref_button: gtk::Button = builder.get_object("B_Preferences").unwrap();
let pref_close: gtk::Button = builder.get_object("Pref_Close").unwrap();
let pref_save: gtk::Button = builder.get_object("Pref_Save").unwrap();
//Cargo
let cargo_build: gtk::Button = builder.get_object("B_Cargo_Build").unwrap();
let cargo_build_folder: gtk::FileChooserButton = builder.get_object("Cargo_Build_FolderChooser").unwrap();
let cargo_build_arguments: gtk::Entry = builder.get_object("Cargo_Build_ExtraOptions_Entry").unwrap();
let cargo_run_run: gtk::Button = builder.get_object("B_Cargo_Run").unwrap();
let cargo_run_arguments: gtk::Entry = builder.get_object("Cargo_Run_ExtraOptions_Entry").unwrap();
//RustUp
let ru_install_Button: gtk::Button = builder.get_object("B_NT_Install").unwrap();
let ru_install_channel: gtk::ComboBoxText = builder.get_object("RU_New_Channel").unwrap();
let ru_activate_channel_chooser: gtk::ComboBoxText = builder.get_object("RU_Active_Channel").unwrap();
let ru_activate_channel_button: gtk::Button = builder.get_object("B_NT_Activate").unwrap();
let ru_update_button: gtk::Button = builder.get_object("B_RU_Update").unwrap();
//Crates.io
let text_buffer: gtk::TextBuffer = builder.get_object("CratesTextBuffer").unwrap();
let search_button: gtk::Button = builder.get_object("CratesSearch").unwrap();
let search_entry: gtk::Entry = builder.get_object("CratesSearch_Entry").unwrap();
let level_bar: gtk::LevelBar = builder.get_object("SearchLevel").unwrap();
//**********************************************
//Main
header.set_title("Teddy");
header.set_subtitle("Rolf");
//Close event
close_button.connect_clicked(move |_| {
println!("Closing normal!");
gtk::main_quit();
Inhibit(false);
});
//Window Close event
window.connect_delete_event(|_,_| {
gtk::main_quit();
Inhibit(false)
});
//Preferences show event
pref_button.connect_clicked(clone!(pref_window => move |_| {
pref_window.show_all();
}));
//Hide, without save
pref_close.connect_clicked(clone!(pref_window => move |_| {
pref_window.hide();
}));
//Hide, with save
pref_save.connect_clicked(clone!(pref_window => move |_| {
pref_window.hide();
}));
//Cargo
cargo_build.connect_clicked(clone!(cargo_build_folder, cargo_build_arguments => move |_|{
let argument_string: String = gtk_converter::text_from_entry(&cargo_build_arguments);
let locationstr: String = gtk_converter::path_from_filechooser(&cargo_build_folder);
execute_command(&locationstr, &"cargo build".to_string(), &argument_string.to_string());
}));
cargo_run_run.connect_clicked(clone!(cargo_run_arguments, cargo_build_folder => move |_|{
let argument_string: String = gtk_converter::text_from_entry(&cargo_run_arguments);
let locationstr: String = gtk_converter::path_from_filechooser(&cargo_build_folder);
system_io::execute_command(&locationstr, &"cargo run".to_string(), &argument_string.to_string());
}));
//RustUp
//Install new toolchain
ru_install_Button.connect_clicked(clone!(ru_install_channel => move |_| {
//Sort output
let entry = ru_install_channel.get_active_text();
let mut to_install: String =String::from("NoContent");
match entry {
Some(e) => to_install = e,
None => {}
}
//Join install command/argument
let execute_string: String = String::from("toolchain install ") + to_install.as_str();
//INstall
system_io::execute_command(&String::from("~/"), &String::from("rustup"), &execute_string);
println!("Installed: {}", to_install);
}));
//Activate channel
ru_activate_channel_button.connect_clicked(clone!(ru_activate_channel_chooser => move |_|{
//Sort output
let entry = ru_install_channel.get_active_text();
let mut to_activate: String =String::from("NoContent");
match entry {
Some(e) => to_activate = e,
None => {}
}
let activate_arg: String = String::from("default ") + to_activate.as_str();
system_io::execute_command(&String::from("~/"), &String::from("rustup"), &activate_arg);
}));
//Update everything
ru_update_button.connect_clicked(|_| {
system_io::execute_command(&String::from("~/"), &String::from("rustup"), &String::from("update"));
});
//Crates.io
search_button.connect_clicked(clone!(text_buffer, search_entry => move |_| {
let entry: String = gtk_converter::text_from_entry(&search_entry);
while level_bar.get_value()!= 0.2 {
level_bar.set_value(0.2);
}
println!("Outside: {}", entry);
level_bar.set_value(0.5);
let output = Command::new("cargo").arg("search")
.arg(entry)
.arg("--limit")
.arg("40")
.output()
.expect("Failed to ls");
let out: String = String::from_utf8(output.stdout).expect("Not UTF-8");
level_bar.set_value(0.75);
let last: &str = convert_to_str(&out);
text_buffer.set_text(last);
level_bar.set_value(1.0);
}));
window.show_all();
gtk::main();
}
| {
Command::new("xterm")
.arg("-hold")
.arg("-e")
.arg("cd ".to_string() + location + " && " + command + " " + arguments)
.spawn()
.expect("Failed to run command");
} | identifier_body |
main.rs | //Test File gtk_test
extern crate gtk;
//Custom mods
mod system_io;
mod gtk_converter;
pub mod m_config;
//Os interaction
use std::process::Command;
use std::process::ChildStdout;
use std::io;
use std::io::prelude::*;
use gtk::Builder;
use gtk::prelude::*;
// make moving clones into closures more convenient
//shameless copied from the examples
macro_rules! clone {
(@param _) => ( _ );
(@param $x:ident) => ( $x );
($($n:ident),+ => move || $body:expr) => (
{
$( let $n = $n.clone(); )+
move || $body
}
);
($($n:ident),+ => move |$($p:tt),+| $body:expr) => (
{
$( let $n = $n.clone(); )+
move |$(clone!(@param $p),)+| $body
}
);
}
fn | (location: &String, command: &String, arguments: &String){
Command::new("xterm")
.arg("-hold")
.arg("-e")
.arg("cd ".to_string() + location + " && " + command + " " + arguments)
.spawn()
.expect("Failed to run command");
}
fn convert_to_str(x: &str) -> &str{
x
}
fn main() {
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let glade_src = include_str!("shipload.glade");
let builder = Builder::new();
builder.add_from_string(glade_src).unwrap();
//**********************************************
//Crucial
let configuration = m_config::create_config();
//Main
//Get Window
let window: gtk::Window = builder.get_object("window").unwrap();
//Close Button
let close_button: gtk::Button = builder.get_object("B_Close").unwrap();
//Set Header bar information
let header: gtk::HeaderBar = builder.get_object("Header").unwrap();
let pref_window: gtk::Window = builder.get_object("W_Preferences").unwrap();
let pref_button: gtk::Button = builder.get_object("B_Preferences").unwrap();
let pref_close: gtk::Button = builder.get_object("Pref_Close").unwrap();
let pref_save: gtk::Button = builder.get_object("Pref_Save").unwrap();
//Cargo
let cargo_build: gtk::Button = builder.get_object("B_Cargo_Build").unwrap();
let cargo_build_folder: gtk::FileChooserButton = builder.get_object("Cargo_Build_FolderChooser").unwrap();
let cargo_build_arguments: gtk::Entry = builder.get_object("Cargo_Build_ExtraOptions_Entry").unwrap();
let cargo_run_run: gtk::Button = builder.get_object("B_Cargo_Run").unwrap();
let cargo_run_arguments: gtk::Entry = builder.get_object("Cargo_Run_ExtraOptions_Entry").unwrap();
//RustUp
let ru_install_Button: gtk::Button = builder.get_object("B_NT_Install").unwrap();
let ru_install_channel: gtk::ComboBoxText = builder.get_object("RU_New_Channel").unwrap();
let ru_activate_channel_chooser: gtk::ComboBoxText = builder.get_object("RU_Active_Channel").unwrap();
let ru_activate_channel_button: gtk::Button = builder.get_object("B_NT_Activate").unwrap();
let ru_update_button: gtk::Button = builder.get_object("B_RU_Update").unwrap();
//Crates.io
let text_buffer: gtk::TextBuffer = builder.get_object("CratesTextBuffer").unwrap();
let search_button: gtk::Button = builder.get_object("CratesSearch").unwrap();
let search_entry: gtk::Entry = builder.get_object("CratesSearch_Entry").unwrap();
let level_bar: gtk::LevelBar = builder.get_object("SearchLevel").unwrap();
//**********************************************
//Main
header.set_title("Teddy");
header.set_subtitle("Rolf");
//Close event
close_button.connect_clicked(move |_| {
println!("Closing normal!");
gtk::main_quit();
Inhibit(false);
});
//Window Close event
window.connect_delete_event(|_,_| {
gtk::main_quit();
Inhibit(false)
});
//Preferences show event
pref_button.connect_clicked(clone!(pref_window => move |_| {
pref_window.show_all();
}));
//Hide, without save
pref_close.connect_clicked(clone!(pref_window => move |_| {
pref_window.hide();
}));
//Hide, with save
pref_save.connect_clicked(clone!(pref_window => move |_| {
pref_window.hide();
}));
//Cargo
cargo_build.connect_clicked(clone!(cargo_build_folder, cargo_build_arguments => move |_|{
let argument_string: String = gtk_converter::text_from_entry(&cargo_build_arguments);
let locationstr: String = gtk_converter::path_from_filechooser(&cargo_build_folder);
execute_command(&locationstr, &"cargo build".to_string(), &argument_string.to_string());
}));
cargo_run_run.connect_clicked(clone!(cargo_run_arguments, cargo_build_folder => move |_|{
let argument_string: String = gtk_converter::text_from_entry(&cargo_run_arguments);
let locationstr: String = gtk_converter::path_from_filechooser(&cargo_build_folder);
system_io::execute_command(&locationstr, &"cargo run".to_string(), &argument_string.to_string());
}));
//RustUp
//Install new toolchain
ru_install_Button.connect_clicked(clone!(ru_install_channel => move |_| {
//Sort output
let entry = ru_install_channel.get_active_text();
let mut to_install: String =String::from("NoContent");
match entry {
Some(e) => to_install = e,
None => {}
}
//Join install command/argument
let execute_string: String = String::from("toolchain install ") + to_install.as_str();
//INstall
system_io::execute_command(&String::from("~/"), &String::from("rustup"), &execute_string);
println!("Installed: {}", to_install);
}));
//Activate channel
ru_activate_channel_button.connect_clicked(clone!(ru_activate_channel_chooser => move |_|{
//Sort output
let entry = ru_install_channel.get_active_text();
let mut to_activate: String =String::from("NoContent");
match entry {
Some(e) => to_activate = e,
None => {}
}
let activate_arg: String = String::from("default ") + to_activate.as_str();
system_io::execute_command(&String::from("~/"), &String::from("rustup"), &activate_arg);
}));
//Update everything
ru_update_button.connect_clicked(|_| {
system_io::execute_command(&String::from("~/"), &String::from("rustup"), &String::from("update"));
});
//Crates.io
search_button.connect_clicked(clone!(text_buffer, search_entry => move |_| {
let entry: String = gtk_converter::text_from_entry(&search_entry);
while level_bar.get_value()!= 0.2 {
level_bar.set_value(0.2);
}
println!("Outside: {}", entry);
level_bar.set_value(0.5);
let output = Command::new("cargo").arg("search")
.arg(entry)
.arg("--limit")
.arg("40")
.output()
.expect("Failed to ls");
let out: String = String::from_utf8(output.stdout).expect("Not UTF-8");
level_bar.set_value(0.75);
let last: &str = convert_to_str(&out);
text_buffer.set_text(last);
level_bar.set_value(1.0);
}));
window.show_all();
gtk::main();
}
| execute_command | identifier_name |
main.rs | //Test File gtk_test
extern crate gtk;
//Custom mods
mod system_io;
mod gtk_converter;
pub mod m_config;
//Os interaction
use std::process::Command;
use std::process::ChildStdout;
use std::io;
use std::io::prelude::*;
use gtk::Builder;
use gtk::prelude::*;
// make moving clones into closures more convenient
//shameless copied from the examples
macro_rules! clone {
(@param _) => ( _ );
(@param $x:ident) => ( $x );
($($n:ident),+ => move || $body:expr) => (
{
$( let $n = $n.clone(); )+
move || $body
}
);
($($n:ident),+ => move |$($p:tt),+| $body:expr) => (
{
$( let $n = $n.clone(); )+
move |$(clone!(@param $p),)+| $body
}
);
}
fn execute_command(location: &String, command: &String, arguments: &String){
Command::new("xterm")
.arg("-hold")
.arg("-e")
.arg("cd ".to_string() + location + " && " + command + " " + arguments)
.spawn()
.expect("Failed to run command");
}
fn convert_to_str(x: &str) -> &str{
x
}
fn main() {
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let glade_src = include_str!("shipload.glade");
let builder = Builder::new();
builder.add_from_string(glade_src).unwrap();
//**********************************************
//Crucial
let configuration = m_config::create_config();
//Main
//Get Window
let window: gtk::Window = builder.get_object("window").unwrap();
//Close Button
let close_button: gtk::Button = builder.get_object("B_Close").unwrap();
//Set Header bar information
let header: gtk::HeaderBar = builder.get_object("Header").unwrap();
let pref_window: gtk::Window = builder.get_object("W_Preferences").unwrap();
let pref_button: gtk::Button = builder.get_object("B_Preferences").unwrap();
let pref_close: gtk::Button = builder.get_object("Pref_Close").unwrap();
let pref_save: gtk::Button = builder.get_object("Pref_Save").unwrap();
//Cargo
let cargo_build: gtk::Button = builder.get_object("B_Cargo_Build").unwrap();
let cargo_build_folder: gtk::FileChooserButton = builder.get_object("Cargo_Build_FolderChooser").unwrap();
let cargo_build_arguments: gtk::Entry = builder.get_object("Cargo_Build_ExtraOptions_Entry").unwrap();
let cargo_run_run: gtk::Button = builder.get_object("B_Cargo_Run").unwrap();
let cargo_run_arguments: gtk::Entry = builder.get_object("Cargo_Run_ExtraOptions_Entry").unwrap();
//RustUp
let ru_install_Button: gtk::Button = builder.get_object("B_NT_Install").unwrap();
let ru_install_channel: gtk::ComboBoxText = builder.get_object("RU_New_Channel").unwrap();
let ru_activate_channel_chooser: gtk::ComboBoxText = builder.get_object("RU_Active_Channel").unwrap();
let ru_activate_channel_button: gtk::Button = builder.get_object("B_NT_Activate").unwrap();
let ru_update_button: gtk::Button = builder.get_object("B_RU_Update").unwrap();
//Crates.io
let text_buffer: gtk::TextBuffer = builder.get_object("CratesTextBuffer").unwrap();
let search_button: gtk::Button = builder.get_object("CratesSearch").unwrap();
let search_entry: gtk::Entry = builder.get_object("CratesSearch_Entry").unwrap();
let level_bar: gtk::LevelBar = builder.get_object("SearchLevel").unwrap();
//**********************************************
//Main
header.set_title("Teddy");
header.set_subtitle("Rolf");
//Close event
close_button.connect_clicked(move |_| {
println!("Closing normal!");
gtk::main_quit();
Inhibit(false);
});
//Window Close event
window.connect_delete_event(|_,_| {
gtk::main_quit();
Inhibit(false)
});
//Preferences show event
pref_button.connect_clicked(clone!(pref_window => move |_| {
pref_window.show_all();
}));
//Hide, without save
pref_close.connect_clicked(clone!(pref_window => move |_| {
pref_window.hide();
}));
| pref_window.hide();
}));
//Cargo
cargo_build.connect_clicked(clone!(cargo_build_folder, cargo_build_arguments => move |_|{
let argument_string: String = gtk_converter::text_from_entry(&cargo_build_arguments);
let locationstr: String = gtk_converter::path_from_filechooser(&cargo_build_folder);
execute_command(&locationstr, &"cargo build".to_string(), &argument_string.to_string());
}));
cargo_run_run.connect_clicked(clone!(cargo_run_arguments, cargo_build_folder => move |_|{
let argument_string: String = gtk_converter::text_from_entry(&cargo_run_arguments);
let locationstr: String = gtk_converter::path_from_filechooser(&cargo_build_folder);
system_io::execute_command(&locationstr, &"cargo run".to_string(), &argument_string.to_string());
}));
//RustUp
//Install new toolchain
ru_install_Button.connect_clicked(clone!(ru_install_channel => move |_| {
//Sort output
let entry = ru_install_channel.get_active_text();
let mut to_install: String =String::from("NoContent");
match entry {
Some(e) => to_install = e,
None => {}
}
//Join install command/argument
let execute_string: String = String::from("toolchain install ") + to_install.as_str();
//INstall
system_io::execute_command(&String::from("~/"), &String::from("rustup"), &execute_string);
println!("Installed: {}", to_install);
}));
//Activate channel
ru_activate_channel_button.connect_clicked(clone!(ru_activate_channel_chooser => move |_|{
//Sort output
let entry = ru_install_channel.get_active_text();
let mut to_activate: String =String::from("NoContent");
match entry {
Some(e) => to_activate = e,
None => {}
}
let activate_arg: String = String::from("default ") + to_activate.as_str();
system_io::execute_command(&String::from("~/"), &String::from("rustup"), &activate_arg);
}));
//Update everything
ru_update_button.connect_clicked(|_| {
system_io::execute_command(&String::from("~/"), &String::from("rustup"), &String::from("update"));
});
//Crates.io
search_button.connect_clicked(clone!(text_buffer, search_entry => move |_| {
let entry: String = gtk_converter::text_from_entry(&search_entry);
while level_bar.get_value()!= 0.2 {
level_bar.set_value(0.2);
}
println!("Outside: {}", entry);
level_bar.set_value(0.5);
let output = Command::new("cargo").arg("search")
.arg(entry)
.arg("--limit")
.arg("40")
.output()
.expect("Failed to ls");
let out: String = String::from_utf8(output.stdout).expect("Not UTF-8");
level_bar.set_value(0.75);
let last: &str = convert_to_str(&out);
text_buffer.set_text(last);
level_bar.set_value(1.0);
}));
window.show_all();
gtk::main();
} | //Hide, with save
pref_save.connect_clicked(clone!(pref_window => move |_| { | random_line_split |
main.rs | //Test File gtk_test
extern crate gtk;
//Custom mods
mod system_io;
mod gtk_converter;
pub mod m_config;
//Os interaction
use std::process::Command;
use std::process::ChildStdout;
use std::io;
use std::io::prelude::*;
use gtk::Builder;
use gtk::prelude::*;
// make moving clones into closures more convenient
//shameless copied from the examples
macro_rules! clone {
(@param _) => ( _ );
(@param $x:ident) => ( $x );
($($n:ident),+ => move || $body:expr) => (
{
$( let $n = $n.clone(); )+
move || $body
}
);
($($n:ident),+ => move |$($p:tt),+| $body:expr) => (
{
$( let $n = $n.clone(); )+
move |$(clone!(@param $p),)+| $body
}
);
}
fn execute_command(location: &String, command: &String, arguments: &String){
Command::new("xterm")
.arg("-hold")
.arg("-e")
.arg("cd ".to_string() + location + " && " + command + " " + arguments)
.spawn()
.expect("Failed to run command");
}
fn convert_to_str(x: &str) -> &str{
x
}
fn main() {
if gtk::init().is_err() |
let glade_src = include_str!("shipload.glade");
let builder = Builder::new();
builder.add_from_string(glade_src).unwrap();
//**********************************************
//Crucial
let configuration = m_config::create_config();
//Main
//Get Window
let window: gtk::Window = builder.get_object("window").unwrap();
//Close Button
let close_button: gtk::Button = builder.get_object("B_Close").unwrap();
//Set Header bar information
let header: gtk::HeaderBar = builder.get_object("Header").unwrap();
let pref_window: gtk::Window = builder.get_object("W_Preferences").unwrap();
let pref_button: gtk::Button = builder.get_object("B_Preferences").unwrap();
let pref_close: gtk::Button = builder.get_object("Pref_Close").unwrap();
let pref_save: gtk::Button = builder.get_object("Pref_Save").unwrap();
//Cargo
let cargo_build: gtk::Button = builder.get_object("B_Cargo_Build").unwrap();
let cargo_build_folder: gtk::FileChooserButton = builder.get_object("Cargo_Build_FolderChooser").unwrap();
let cargo_build_arguments: gtk::Entry = builder.get_object("Cargo_Build_ExtraOptions_Entry").unwrap();
let cargo_run_run: gtk::Button = builder.get_object("B_Cargo_Run").unwrap();
let cargo_run_arguments: gtk::Entry = builder.get_object("Cargo_Run_ExtraOptions_Entry").unwrap();
//RustUp
let ru_install_Button: gtk::Button = builder.get_object("B_NT_Install").unwrap();
let ru_install_channel: gtk::ComboBoxText = builder.get_object("RU_New_Channel").unwrap();
let ru_activate_channel_chooser: gtk::ComboBoxText = builder.get_object("RU_Active_Channel").unwrap();
let ru_activate_channel_button: gtk::Button = builder.get_object("B_NT_Activate").unwrap();
let ru_update_button: gtk::Button = builder.get_object("B_RU_Update").unwrap();
//Crates.io
let text_buffer: gtk::TextBuffer = builder.get_object("CratesTextBuffer").unwrap();
let search_button: gtk::Button = builder.get_object("CratesSearch").unwrap();
let search_entry: gtk::Entry = builder.get_object("CratesSearch_Entry").unwrap();
let level_bar: gtk::LevelBar = builder.get_object("SearchLevel").unwrap();
//**********************************************
//Main
header.set_title("Teddy");
header.set_subtitle("Rolf");
//Close event
close_button.connect_clicked(move |_| {
println!("Closing normal!");
gtk::main_quit();
Inhibit(false);
});
//Window Close event
window.connect_delete_event(|_,_| {
gtk::main_quit();
Inhibit(false)
});
//Preferences show event
pref_button.connect_clicked(clone!(pref_window => move |_| {
pref_window.show_all();
}));
//Hide, without save
pref_close.connect_clicked(clone!(pref_window => move |_| {
pref_window.hide();
}));
//Hide, with save
pref_save.connect_clicked(clone!(pref_window => move |_| {
pref_window.hide();
}));
//Cargo
cargo_build.connect_clicked(clone!(cargo_build_folder, cargo_build_arguments => move |_|{
let argument_string: String = gtk_converter::text_from_entry(&cargo_build_arguments);
let locationstr: String = gtk_converter::path_from_filechooser(&cargo_build_folder);
execute_command(&locationstr, &"cargo build".to_string(), &argument_string.to_string());
}));
cargo_run_run.connect_clicked(clone!(cargo_run_arguments, cargo_build_folder => move |_|{
let argument_string: String = gtk_converter::text_from_entry(&cargo_run_arguments);
let locationstr: String = gtk_converter::path_from_filechooser(&cargo_build_folder);
system_io::execute_command(&locationstr, &"cargo run".to_string(), &argument_string.to_string());
}));
//RustUp
//Install new toolchain
ru_install_Button.connect_clicked(clone!(ru_install_channel => move |_| {
//Sort output
let entry = ru_install_channel.get_active_text();
let mut to_install: String =String::from("NoContent");
match entry {
Some(e) => to_install = e,
None => {}
}
//Join install command/argument
let execute_string: String = String::from("toolchain install ") + to_install.as_str();
//INstall
system_io::execute_command(&String::from("~/"), &String::from("rustup"), &execute_string);
println!("Installed: {}", to_install);
}));
//Activate channel
ru_activate_channel_button.connect_clicked(clone!(ru_activate_channel_chooser => move |_|{
//Sort output
let entry = ru_install_channel.get_active_text();
let mut to_activate: String =String::from("NoContent");
match entry {
Some(e) => to_activate = e,
None => {}
}
let activate_arg: String = String::from("default ") + to_activate.as_str();
system_io::execute_command(&String::from("~/"), &String::from("rustup"), &activate_arg);
}));
//Update everything
ru_update_button.connect_clicked(|_| {
system_io::execute_command(&String::from("~/"), &String::from("rustup"), &String::from("update"));
});
//Crates.io
search_button.connect_clicked(clone!(text_buffer, search_entry => move |_| {
let entry: String = gtk_converter::text_from_entry(&search_entry);
while level_bar.get_value()!= 0.2 {
level_bar.set_value(0.2);
}
println!("Outside: {}", entry);
level_bar.set_value(0.5);
let output = Command::new("cargo").arg("search")
.arg(entry)
.arg("--limit")
.arg("40")
.output()
.expect("Failed to ls");
let out: String = String::from_utf8(output.stdout).expect("Not UTF-8");
level_bar.set_value(0.75);
let last: &str = convert_to_str(&out);
text_buffer.set_text(last);
level_bar.set_value(1.0);
}));
window.show_all();
gtk::main();
}
| {
println!("Failed to initialize GTK.");
return;
} | conditional_block |
event.rs | //! Event handling (mouse, keyboard, controller, touch screen, etc.)
//!
//! See [`Event`](enum.Event.html) for more information.
//!
//! # Unstable
//!
//! There are still many unanswered questions about the design of the events API in the turtle
//! crate. This module may change or be completely removed in the future. There will definitely
//! be *some* events API in the future, but it may end up looking different than it does today.
use serde::{Serialize, Deserialize};
use glutin::{
dpi::{LogicalSize, PhysicalPosition},
event::{self as glutin_event, WindowEvent, KeyboardInput},
};
use crate::Point;
/// Possible events returned from [`Drawing::poll_event()`](../struct.Drawing.html#method.poll_event).
///
/// Events are used to make programs more interactive. See that method's documentation for more
/// information about how to use events.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Event {
/// Sent when a keyboard key is pressed or released
Key(Key, PressedState),
/// Sent when a mouse button is pressed or released
MouseButton(MouseButton, PressedState),
/// Sent when the mouse is moving. Only sent when the mouse is over the window.
/// `x` and `y` represent the new coordinates of where the mouse is currently.
///
/// Coordinates are relative to the center of the window.
MouseMove(Point),
/// Sent when the mouse is scrolled. Only sent when the mouse is over the window.
/// `x` and `y` are in scroll ticks.
MouseScroll { x: f64, y: f64 },
/// Sent when the window gets resized
WindowResized { width: u32, height: u32 },
/// Sent when the window focus changes
///
/// The boolean value is true if the window is in focus.
WindowFocused(bool),
/// Sent when the cursor enters or leaves the window
///
/// The boolean value is true if the cursor entered the window, and false if it left.
WindowCursor(bool),
/// Sent when the window is closed
WindowClosed,
}
impl Event {
/// Returns `None` if the input event is not a supported variant of `Event`
#[cfg_attr(any(feature = "test", test), allow(dead_code))]
pub(crate) fn from_window_event(
event: WindowEvent,
scale_factor: f64,
to_logical: impl FnOnce(PhysicalPosition<f64>) -> Point,
) -> Option<Self> {
match event {
WindowEvent::Resized(size) => {
let LogicalSize {width, height} = size.to_logical(scale_factor);
Some(Event::WindowResized {width, height})
},
WindowEvent::KeyboardInput {input: KeyboardInput {state, virtual_keycode,..},..} => {
Some(Event::Key(
Key::from_keycode(virtual_keycode?)?,
PressedState::from_state(state),
))
},
WindowEvent::CursorEntered {..} => Some(Event::WindowCursor(true)),
WindowEvent::CursorLeft {..} => Some(Event::WindowCursor(false)),
WindowEvent::CursorMoved {position,..} => {
Some(Event::MouseMove(to_logical(position)))
},
WindowEvent::MouseInput {state, button,..} => Some(Event::MouseButton(
MouseButton::from_button(button)?,
PressedState::from_state(state),
)),
WindowEvent::Focused(focused) => Some(Event::WindowFocused(focused)),
WindowEvent::Destroyed => Some(Event::WindowClosed),
WindowEvent::Moved(_) |
WindowEvent::CloseRequested |
WindowEvent::DroppedFile(_) |
WindowEvent::HoveredFile(_) |
WindowEvent::HoveredFileCancelled |
WindowEvent::ReceivedCharacter(_) |
WindowEvent::ModifiersChanged(_) |
WindowEvent::MouseWheel {..} |
WindowEvent::TouchpadPressure {..} |
WindowEvent::AxisMotion {..} |
WindowEvent::Touch(_) |
WindowEvent::ScaleFactorChanged {..} |
WindowEvent::ThemeChanged(_) => None, // Not supported
}
}
}
//TODO: Documentation
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum PressedState {
Pressed,
Released,
}
impl PressedState {
#[cfg_attr(any(feature = "test", test), allow(dead_code))]
fn from_state(state: glutin_event::ElementState) -> PressedState {
match state {
glutin_event::ElementState::Pressed => PressedState::Pressed,
glutin_event::ElementState::Released => PressedState::Released,
}
}
}
//TODO: Documentation
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum Key {
/// The '1' key above the letters.
Num1,
/// The '2' key above the letters.
Num2,
/// The '3' key above the letters.
Num3,
/// The '4' key above the letters.
Num4,
/// The '5' key above the letters.
Num5,
/// The '6' key above the letters.
Num6,
/// The '7' key above the letters.
Num7,
/// The '8' key above the letters.
Num8,
/// The '9' key above the letters.
Num9,
/// The '0' key above the letters.
Num0,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
/// The Escape key, next to F1
Esc,
F1,
F2, | F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
Home,
Delete,
End,
/// The PageDown (PgDn) key
PageDown,
/// The PageUp (PgUp) key
PageUp,
/// The backspace key, right above Enter/Return
Backspace,
/// The Enter/Return key, below Backspace
Return,
/// The spacebar key
Space,
/// The up arrow key
UpArrow,
/// The left arrow key
LeftArrow,
/// The right arrow key
RightArrow,
/// The down arrow key
DownArrow,
Numpad0,
Numpad1,
Numpad2,
Numpad3,
Numpad4,
Numpad5,
Numpad6,
Numpad7,
Numpad8,
Numpad9,
NumpadComma,
NumpadEnter,
NumpadEquals,
Apostrophe,
At,
Backslash,
Backtick,
Colon,
Comma,
Decimal,
Divide,
Equals,
Minus,
Multiply,
Period,
Plus,
/// The left bracket `[` key
LeftBracket,
/// The left bracket `]` key
RightBracket,
Semicolon,
Slash,
Tab,
}
impl Key {
#[cfg_attr(any(feature = "test", test), allow(dead_code))]
fn from_keycode(key: glutin_event::VirtualKeyCode) -> Option<Self> {
use glutin_event::VirtualKeyCode::*;
#[deny(unreachable_patterns, unused_variables)]
Some(match key {
Key1 => Key::Num1,
Key2 => Key::Num2,
Key3 => Key::Num3,
Key4 => Key::Num4,
Key5 => Key::Num5,
Key6 => Key::Num6,
Key7 => Key::Num7,
Key8 => Key::Num8,
Key9 => Key::Num9,
Key0 => Key::Num0,
A => Key::A,
B => Key::B,
C => Key::C,
D => Key::D,
E => Key::E,
F => Key::F,
G => Key::G,
H => Key::H,
I => Key::I,
J => Key::J,
K => Key::K,
L => Key::L,
M => Key::M,
N => Key::N,
O => Key::O,
P => Key::P,
Q => Key::Q,
R => Key::R,
S => Key::S,
T => Key::T,
U => Key::U,
V => Key::V,
W => Key::W,
X => Key::X,
Y => Key::Y,
Z => Key::Z,
Escape => Key::Esc,
F1 => Key::F1,
F2 => Key::F2,
F3 => Key::F3,
F4 => Key::F4,
F5 => Key::F5,
F6 => Key::F6,
F7 => Key::F7,
F8 => Key::F8,
F9 => Key::F9,
F10 => Key::F10,
F11 => Key::F11,
F12 => Key::F12,
F13 => Key::F13,
F14 => Key::F14,
F15 => Key::F15,
F16 => Key::F16,
F17 => Key::F17,
F18 => Key::F18,
F19 => Key::F19,
F20 => Key::F20,
F21 => Key::F21,
F22 => Key::F22,
F23 => Key::F23,
F24 => Key::F24,
Home => Key::Home,
Delete => Key::Delete,
End => Key::End,
PageDown => Key::PageDown,
PageUp => Key::PageUp,
Back => Key::Backspace,
Return => Key::Return,
Space => Key::Space,
Left => Key::LeftArrow,
Up => Key::UpArrow,
Right => Key::RightArrow,
Down => Key::DownArrow,
Numpad0 => Key::Numpad0,
Numpad1 => Key::Numpad1,
Numpad2 => Key::Numpad2,
Numpad3 => Key::Numpad3,
Numpad4 => Key::Numpad4,
Numpad5 => Key::Numpad5,
Numpad6 => Key::Numpad6,
Numpad7 => Key::Numpad7,
Numpad8 => Key::Numpad8,
Numpad9 => Key::Numpad9,
Apostrophe => Key::Apostrophe,
At => Key::At,
Backslash => Key::Backslash,
Colon => Key::Colon,
Comma => Key::Comma,
Equals => Key::Equals,
Grave => Key::Backtick,
LBracket => Key::LeftBracket,
NumpadAdd | Plus => Key::Plus,
NumpadComma => Key::NumpadComma,
NumpadDecimal => Key::Decimal,
NumpadDivide => Key::Divide,
NumpadEnter => Key::NumpadEnter,
NumpadEquals => Key::NumpadEquals,
NumpadMultiply | Asterisk => Key::Multiply,
NumpadSubtract | Minus => Key::Minus,
Period => Key::Period,
RBracket => Key::RightBracket,
Semicolon => Key::Semicolon,
Slash => Key::Slash,
Tab => Key::Tab,
// Unsupported keys (could be changed in the future)
Snapshot |
Scroll |
Pause |
Insert |
Compose |
Caret |
Numlock |
AbntC1 |
AbntC2 |
Apps |
Ax |
Calculator |
Capital |
Convert |
Kana |
Kanji |
LAlt |
LControl |
LShift |
LWin |
Mail |
MediaSelect |
MediaStop |
Mute |
MyComputer |
NavigateForward |
NavigateBackward |
NextTrack |
NoConvert |
OEM102 |
PlayPause |
Power |
PrevTrack |
RAlt |
RControl |
RShift |
RWin |
Sleep |
Stop |
Sysrq |
Underline |
Unlabeled |
VolumeDown |
VolumeUp |
Wake |
WebBack |
WebFavorites |
WebForward |
WebHome |
WebRefresh |
WebSearch |
WebStop |
Yen |
Copy |
Paste |
Cut => return None,
})
}
}
//TODO: Documentation
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum MouseButton {
/// The left mouse button
LeftButton,
/// The middle mouse button
MiddleButton,
/// The right mouse button
RightButton,
}
impl MouseButton {
#[cfg_attr(any(feature = "test", test), allow(dead_code))]
fn from_button(button: glutin_event::MouseButton) -> Option<Self> {
use glutin_event::MouseButton::*;
#[deny(unreachable_patterns, unused_variables)]
match button {
Left => Some(MouseButton::LeftButton),
Middle => Some(MouseButton::MiddleButton),
Right => Some(MouseButton::RightButton),
Other(_) => None,
}
}
} | F3,
F4,
F5, | random_line_split |
event.rs | //! Event handling (mouse, keyboard, controller, touch screen, etc.)
//!
//! See [`Event`](enum.Event.html) for more information.
//!
//! # Unstable
//!
//! There are still many unanswered questions about the design of the events API in the turtle
//! crate. This module may change or be completely removed in the future. There will definitely
//! be *some* events API in the future, but it may end up looking different than it does today.
use serde::{Serialize, Deserialize};
use glutin::{
dpi::{LogicalSize, PhysicalPosition},
event::{self as glutin_event, WindowEvent, KeyboardInput},
};
use crate::Point;
/// Possible events returned from [`Drawing::poll_event()`](../struct.Drawing.html#method.poll_event).
///
/// Events are used to make programs more interactive. See that method's documentation for more
/// information about how to use events.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Event {
/// Sent when a keyboard key is pressed or released
Key(Key, PressedState),
/// Sent when a mouse button is pressed or released
MouseButton(MouseButton, PressedState),
/// Sent when the mouse is moving. Only sent when the mouse is over the window.
/// `x` and `y` represent the new coordinates of where the mouse is currently.
///
/// Coordinates are relative to the center of the window.
MouseMove(Point),
/// Sent when the mouse is scrolled. Only sent when the mouse is over the window.
/// `x` and `y` are in scroll ticks.
MouseScroll { x: f64, y: f64 },
/// Sent when the window gets resized
WindowResized { width: u32, height: u32 },
/// Sent when the window focus changes
///
/// The boolean value is true if the window is in focus.
WindowFocused(bool),
/// Sent when the cursor enters or leaves the window
///
/// The boolean value is true if the cursor entered the window, and false if it left.
WindowCursor(bool),
/// Sent when the window is closed
WindowClosed,
}
impl Event {
/// Returns `None` if the input event is not a supported variant of `Event`
#[cfg_attr(any(feature = "test", test), allow(dead_code))]
pub(crate) fn from_window_event(
event: WindowEvent,
scale_factor: f64,
to_logical: impl FnOnce(PhysicalPosition<f64>) -> Point,
) -> Option<Self> {
match event {
WindowEvent::Resized(size) => {
let LogicalSize {width, height} = size.to_logical(scale_factor);
Some(Event::WindowResized {width, height})
},
WindowEvent::KeyboardInput {input: KeyboardInput {state, virtual_keycode,..},..} => {
Some(Event::Key(
Key::from_keycode(virtual_keycode?)?,
PressedState::from_state(state),
))
},
WindowEvent::CursorEntered {..} => Some(Event::WindowCursor(true)),
WindowEvent::CursorLeft {..} => Some(Event::WindowCursor(false)),
WindowEvent::CursorMoved {position,..} => {
Some(Event::MouseMove(to_logical(position)))
},
WindowEvent::MouseInput {state, button,..} => Some(Event::MouseButton(
MouseButton::from_button(button)?,
PressedState::from_state(state),
)),
WindowEvent::Focused(focused) => Some(Event::WindowFocused(focused)),
WindowEvent::Destroyed => Some(Event::WindowClosed),
WindowEvent::Moved(_) |
WindowEvent::CloseRequested |
WindowEvent::DroppedFile(_) |
WindowEvent::HoveredFile(_) |
WindowEvent::HoveredFileCancelled |
WindowEvent::ReceivedCharacter(_) |
WindowEvent::ModifiersChanged(_) |
WindowEvent::MouseWheel {..} |
WindowEvent::TouchpadPressure {..} |
WindowEvent::AxisMotion {..} |
WindowEvent::Touch(_) |
WindowEvent::ScaleFactorChanged {..} |
WindowEvent::ThemeChanged(_) => None, // Not supported
}
}
}
//TODO: Documentation
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum PressedState {
Pressed,
Released,
}
impl PressedState {
#[cfg_attr(any(feature = "test", test), allow(dead_code))]
fn | (state: glutin_event::ElementState) -> PressedState {
match state {
glutin_event::ElementState::Pressed => PressedState::Pressed,
glutin_event::ElementState::Released => PressedState::Released,
}
}
}
//TODO: Documentation
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum Key {
/// The '1' key above the letters.
Num1,
/// The '2' key above the letters.
Num2,
/// The '3' key above the letters.
Num3,
/// The '4' key above the letters.
Num4,
/// The '5' key above the letters.
Num5,
/// The '6' key above the letters.
Num6,
/// The '7' key above the letters.
Num7,
/// The '8' key above the letters.
Num8,
/// The '9' key above the letters.
Num9,
/// The '0' key above the letters.
Num0,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
/// The Escape key, next to F1
Esc,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
Home,
Delete,
End,
/// The PageDown (PgDn) key
PageDown,
/// The PageUp (PgUp) key
PageUp,
/// The backspace key, right above Enter/Return
Backspace,
/// The Enter/Return key, below Backspace
Return,
/// The spacebar key
Space,
/// The up arrow key
UpArrow,
/// The left arrow key
LeftArrow,
/// The right arrow key
RightArrow,
/// The down arrow key
DownArrow,
Numpad0,
Numpad1,
Numpad2,
Numpad3,
Numpad4,
Numpad5,
Numpad6,
Numpad7,
Numpad8,
Numpad9,
NumpadComma,
NumpadEnter,
NumpadEquals,
Apostrophe,
At,
Backslash,
Backtick,
Colon,
Comma,
Decimal,
Divide,
Equals,
Minus,
Multiply,
Period,
Plus,
/// The left bracket `[` key
LeftBracket,
/// The left bracket `]` key
RightBracket,
Semicolon,
Slash,
Tab,
}
impl Key {
#[cfg_attr(any(feature = "test", test), allow(dead_code))]
fn from_keycode(key: glutin_event::VirtualKeyCode) -> Option<Self> {
use glutin_event::VirtualKeyCode::*;
#[deny(unreachable_patterns, unused_variables)]
Some(match key {
Key1 => Key::Num1,
Key2 => Key::Num2,
Key3 => Key::Num3,
Key4 => Key::Num4,
Key5 => Key::Num5,
Key6 => Key::Num6,
Key7 => Key::Num7,
Key8 => Key::Num8,
Key9 => Key::Num9,
Key0 => Key::Num0,
A => Key::A,
B => Key::B,
C => Key::C,
D => Key::D,
E => Key::E,
F => Key::F,
G => Key::G,
H => Key::H,
I => Key::I,
J => Key::J,
K => Key::K,
L => Key::L,
M => Key::M,
N => Key::N,
O => Key::O,
P => Key::P,
Q => Key::Q,
R => Key::R,
S => Key::S,
T => Key::T,
U => Key::U,
V => Key::V,
W => Key::W,
X => Key::X,
Y => Key::Y,
Z => Key::Z,
Escape => Key::Esc,
F1 => Key::F1,
F2 => Key::F2,
F3 => Key::F3,
F4 => Key::F4,
F5 => Key::F5,
F6 => Key::F6,
F7 => Key::F7,
F8 => Key::F8,
F9 => Key::F9,
F10 => Key::F10,
F11 => Key::F11,
F12 => Key::F12,
F13 => Key::F13,
F14 => Key::F14,
F15 => Key::F15,
F16 => Key::F16,
F17 => Key::F17,
F18 => Key::F18,
F19 => Key::F19,
F20 => Key::F20,
F21 => Key::F21,
F22 => Key::F22,
F23 => Key::F23,
F24 => Key::F24,
Home => Key::Home,
Delete => Key::Delete,
End => Key::End,
PageDown => Key::PageDown,
PageUp => Key::PageUp,
Back => Key::Backspace,
Return => Key::Return,
Space => Key::Space,
Left => Key::LeftArrow,
Up => Key::UpArrow,
Right => Key::RightArrow,
Down => Key::DownArrow,
Numpad0 => Key::Numpad0,
Numpad1 => Key::Numpad1,
Numpad2 => Key::Numpad2,
Numpad3 => Key::Numpad3,
Numpad4 => Key::Numpad4,
Numpad5 => Key::Numpad5,
Numpad6 => Key::Numpad6,
Numpad7 => Key::Numpad7,
Numpad8 => Key::Numpad8,
Numpad9 => Key::Numpad9,
Apostrophe => Key::Apostrophe,
At => Key::At,
Backslash => Key::Backslash,
Colon => Key::Colon,
Comma => Key::Comma,
Equals => Key::Equals,
Grave => Key::Backtick,
LBracket => Key::LeftBracket,
NumpadAdd | Plus => Key::Plus,
NumpadComma => Key::NumpadComma,
NumpadDecimal => Key::Decimal,
NumpadDivide => Key::Divide,
NumpadEnter => Key::NumpadEnter,
NumpadEquals => Key::NumpadEquals,
NumpadMultiply | Asterisk => Key::Multiply,
NumpadSubtract | Minus => Key::Minus,
Period => Key::Period,
RBracket => Key::RightBracket,
Semicolon => Key::Semicolon,
Slash => Key::Slash,
Tab => Key::Tab,
// Unsupported keys (could be changed in the future)
Snapshot |
Scroll |
Pause |
Insert |
Compose |
Caret |
Numlock |
AbntC1 |
AbntC2 |
Apps |
Ax |
Calculator |
Capital |
Convert |
Kana |
Kanji |
LAlt |
LControl |
LShift |
LWin |
Mail |
MediaSelect |
MediaStop |
Mute |
MyComputer |
NavigateForward |
NavigateBackward |
NextTrack |
NoConvert |
OEM102 |
PlayPause |
Power |
PrevTrack |
RAlt |
RControl |
RShift |
RWin |
Sleep |
Stop |
Sysrq |
Underline |
Unlabeled |
VolumeDown |
VolumeUp |
Wake |
WebBack |
WebFavorites |
WebForward |
WebHome |
WebRefresh |
WebSearch |
WebStop |
Yen |
Copy |
Paste |
Cut => return None,
})
}
}
//TODO: Documentation
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum MouseButton {
/// The left mouse button
LeftButton,
/// The middle mouse button
MiddleButton,
/// The right mouse button
RightButton,
}
impl MouseButton {
#[cfg_attr(any(feature = "test", test), allow(dead_code))]
fn from_button(button: glutin_event::MouseButton) -> Option<Self> {
use glutin_event::MouseButton::*;
#[deny(unreachable_patterns, unused_variables)]
match button {
Left => Some(MouseButton::LeftButton),
Middle => Some(MouseButton::MiddleButton),
Right => Some(MouseButton::RightButton),
Other(_) => None,
}
}
}
| from_state | identifier_name |
event.rs | //! Event handling (mouse, keyboard, controller, touch screen, etc.)
//!
//! See [`Event`](enum.Event.html) for more information.
//!
//! # Unstable
//!
//! There are still many unanswered questions about the design of the events API in the turtle
//! crate. This module may change or be completely removed in the future. There will definitely
//! be *some* events API in the future, but it may end up looking different than it does today.
use serde::{Serialize, Deserialize};
use glutin::{
dpi::{LogicalSize, PhysicalPosition},
event::{self as glutin_event, WindowEvent, KeyboardInput},
};
use crate::Point;
/// Possible events returned from [`Drawing::poll_event()`](../struct.Drawing.html#method.poll_event).
///
/// Events are used to make programs more interactive. See that method's documentation for more
/// information about how to use events.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Event {
/// Sent when a keyboard key is pressed or released
Key(Key, PressedState),
/// Sent when a mouse button is pressed or released
MouseButton(MouseButton, PressedState),
/// Sent when the mouse is moving. Only sent when the mouse is over the window.
/// `x` and `y` represent the new coordinates of where the mouse is currently.
///
/// Coordinates are relative to the center of the window.
MouseMove(Point),
/// Sent when the mouse is scrolled. Only sent when the mouse is over the window.
/// `x` and `y` are in scroll ticks.
MouseScroll { x: f64, y: f64 },
/// Sent when the window gets resized
WindowResized { width: u32, height: u32 },
/// Sent when the window focus changes
///
/// The boolean value is true if the window is in focus.
WindowFocused(bool),
/// Sent when the cursor enters or leaves the window
///
/// The boolean value is true if the cursor entered the window, and false if it left.
WindowCursor(bool),
/// Sent when the window is closed
WindowClosed,
}
impl Event {
/// Returns `None` if the input event is not a supported variant of `Event`
#[cfg_attr(any(feature = "test", test), allow(dead_code))]
pub(crate) fn from_window_event(
event: WindowEvent,
scale_factor: f64,
to_logical: impl FnOnce(PhysicalPosition<f64>) -> Point,
) -> Option<Self> {
match event {
WindowEvent::Resized(size) => {
let LogicalSize {width, height} = size.to_logical(scale_factor);
Some(Event::WindowResized {width, height})
},
WindowEvent::KeyboardInput {input: KeyboardInput {state, virtual_keycode,..},..} => {
Some(Event::Key(
Key::from_keycode(virtual_keycode?)?,
PressedState::from_state(state),
))
},
WindowEvent::CursorEntered {..} => Some(Event::WindowCursor(true)),
WindowEvent::CursorLeft {..} => Some(Event::WindowCursor(false)),
WindowEvent::CursorMoved {position,..} => {
Some(Event::MouseMove(to_logical(position)))
},
WindowEvent::MouseInput {state, button,..} => Some(Event::MouseButton(
MouseButton::from_button(button)?,
PressedState::from_state(state),
)),
WindowEvent::Focused(focused) => Some(Event::WindowFocused(focused)),
WindowEvent::Destroyed => Some(Event::WindowClosed),
WindowEvent::Moved(_) |
WindowEvent::CloseRequested |
WindowEvent::DroppedFile(_) |
WindowEvent::HoveredFile(_) |
WindowEvent::HoveredFileCancelled |
WindowEvent::ReceivedCharacter(_) |
WindowEvent::ModifiersChanged(_) |
WindowEvent::MouseWheel {..} |
WindowEvent::TouchpadPressure {..} |
WindowEvent::AxisMotion {..} |
WindowEvent::Touch(_) |
WindowEvent::ScaleFactorChanged {..} |
WindowEvent::ThemeChanged(_) => None, // Not supported
}
}
}
//TODO: Documentation
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum PressedState {
Pressed,
Released,
}
impl PressedState {
#[cfg_attr(any(feature = "test", test), allow(dead_code))]
fn from_state(state: glutin_event::ElementState) -> PressedState |
}
//TODO: Documentation
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum Key {
/// The '1' key above the letters.
Num1,
/// The '2' key above the letters.
Num2,
/// The '3' key above the letters.
Num3,
/// The '4' key above the letters.
Num4,
/// The '5' key above the letters.
Num5,
/// The '6' key above the letters.
Num6,
/// The '7' key above the letters.
Num7,
/// The '8' key above the letters.
Num8,
/// The '9' key above the letters.
Num9,
/// The '0' key above the letters.
Num0,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
/// The Escape key, next to F1
Esc,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
Home,
Delete,
End,
/// The PageDown (PgDn) key
PageDown,
/// The PageUp (PgUp) key
PageUp,
/// The backspace key, right above Enter/Return
Backspace,
/// The Enter/Return key, below Backspace
Return,
/// The spacebar key
Space,
/// The up arrow key
UpArrow,
/// The left arrow key
LeftArrow,
/// The right arrow key
RightArrow,
/// The down arrow key
DownArrow,
Numpad0,
Numpad1,
Numpad2,
Numpad3,
Numpad4,
Numpad5,
Numpad6,
Numpad7,
Numpad8,
Numpad9,
NumpadComma,
NumpadEnter,
NumpadEquals,
Apostrophe,
At,
Backslash,
Backtick,
Colon,
Comma,
Decimal,
Divide,
Equals,
Minus,
Multiply,
Period,
Plus,
/// The left bracket `[` key
LeftBracket,
/// The left bracket `]` key
RightBracket,
Semicolon,
Slash,
Tab,
}
impl Key {
#[cfg_attr(any(feature = "test", test), allow(dead_code))]
fn from_keycode(key: glutin_event::VirtualKeyCode) -> Option<Self> {
use glutin_event::VirtualKeyCode::*;
#[deny(unreachable_patterns, unused_variables)]
Some(match key {
Key1 => Key::Num1,
Key2 => Key::Num2,
Key3 => Key::Num3,
Key4 => Key::Num4,
Key5 => Key::Num5,
Key6 => Key::Num6,
Key7 => Key::Num7,
Key8 => Key::Num8,
Key9 => Key::Num9,
Key0 => Key::Num0,
A => Key::A,
B => Key::B,
C => Key::C,
D => Key::D,
E => Key::E,
F => Key::F,
G => Key::G,
H => Key::H,
I => Key::I,
J => Key::J,
K => Key::K,
L => Key::L,
M => Key::M,
N => Key::N,
O => Key::O,
P => Key::P,
Q => Key::Q,
R => Key::R,
S => Key::S,
T => Key::T,
U => Key::U,
V => Key::V,
W => Key::W,
X => Key::X,
Y => Key::Y,
Z => Key::Z,
Escape => Key::Esc,
F1 => Key::F1,
F2 => Key::F2,
F3 => Key::F3,
F4 => Key::F4,
F5 => Key::F5,
F6 => Key::F6,
F7 => Key::F7,
F8 => Key::F8,
F9 => Key::F9,
F10 => Key::F10,
F11 => Key::F11,
F12 => Key::F12,
F13 => Key::F13,
F14 => Key::F14,
F15 => Key::F15,
F16 => Key::F16,
F17 => Key::F17,
F18 => Key::F18,
F19 => Key::F19,
F20 => Key::F20,
F21 => Key::F21,
F22 => Key::F22,
F23 => Key::F23,
F24 => Key::F24,
Home => Key::Home,
Delete => Key::Delete,
End => Key::End,
PageDown => Key::PageDown,
PageUp => Key::PageUp,
Back => Key::Backspace,
Return => Key::Return,
Space => Key::Space,
Left => Key::LeftArrow,
Up => Key::UpArrow,
Right => Key::RightArrow,
Down => Key::DownArrow,
Numpad0 => Key::Numpad0,
Numpad1 => Key::Numpad1,
Numpad2 => Key::Numpad2,
Numpad3 => Key::Numpad3,
Numpad4 => Key::Numpad4,
Numpad5 => Key::Numpad5,
Numpad6 => Key::Numpad6,
Numpad7 => Key::Numpad7,
Numpad8 => Key::Numpad8,
Numpad9 => Key::Numpad9,
Apostrophe => Key::Apostrophe,
At => Key::At,
Backslash => Key::Backslash,
Colon => Key::Colon,
Comma => Key::Comma,
Equals => Key::Equals,
Grave => Key::Backtick,
LBracket => Key::LeftBracket,
NumpadAdd | Plus => Key::Plus,
NumpadComma => Key::NumpadComma,
NumpadDecimal => Key::Decimal,
NumpadDivide => Key::Divide,
NumpadEnter => Key::NumpadEnter,
NumpadEquals => Key::NumpadEquals,
NumpadMultiply | Asterisk => Key::Multiply,
NumpadSubtract | Minus => Key::Minus,
Period => Key::Period,
RBracket => Key::RightBracket,
Semicolon => Key::Semicolon,
Slash => Key::Slash,
Tab => Key::Tab,
// Unsupported keys (could be changed in the future)
Snapshot |
Scroll |
Pause |
Insert |
Compose |
Caret |
Numlock |
AbntC1 |
AbntC2 |
Apps |
Ax |
Calculator |
Capital |
Convert |
Kana |
Kanji |
LAlt |
LControl |
LShift |
LWin |
Mail |
MediaSelect |
MediaStop |
Mute |
MyComputer |
NavigateForward |
NavigateBackward |
NextTrack |
NoConvert |
OEM102 |
PlayPause |
Power |
PrevTrack |
RAlt |
RControl |
RShift |
RWin |
Sleep |
Stop |
Sysrq |
Underline |
Unlabeled |
VolumeDown |
VolumeUp |
Wake |
WebBack |
WebFavorites |
WebForward |
WebHome |
WebRefresh |
WebSearch |
WebStop |
Yen |
Copy |
Paste |
Cut => return None,
})
}
}
//TODO: Documentation
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum MouseButton {
/// The left mouse button
LeftButton,
/// The middle mouse button
MiddleButton,
/// The right mouse button
RightButton,
}
impl MouseButton {
#[cfg_attr(any(feature = "test", test), allow(dead_code))]
fn from_button(button: glutin_event::MouseButton) -> Option<Self> {
use glutin_event::MouseButton::*;
#[deny(unreachable_patterns, unused_variables)]
match button {
Left => Some(MouseButton::LeftButton),
Middle => Some(MouseButton::MiddleButton),
Right => Some(MouseButton::RightButton),
Other(_) => None,
}
}
}
| {
match state {
glutin_event::ElementState::Pressed => PressedState::Pressed,
glutin_event::ElementState::Released => PressedState::Released,
}
} | identifier_body |
borrowck-lend-flow-loop.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.
// Note: the borrowck analysis is currently flow-insensitive.
// Therefore, some of these errors are marked as spurious and could be
// corrected by a simple change to the analysis. The others are
// either genuine or would require more advanced changes. The latter
// cases are noted.
fn borrow(_v: &int) {}
fn borrow_mut(_v: &mut int) {}
fn cond() -> bool { fail!() }
fn for_func(_f: &fn() -> bool) -> bool { fail!() }
fn produce<T>() -> T { fail!(); }
fn inc(v: &mut ~int) {
*v = ~(**v + 1);
}
fn loop_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire loop.
let mut v = ~3;
let mut x = &mut v;
**x += 1;
loop {
borrow(v); //~ ERROR cannot borrow
}
}
fn block_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire closure call.
let mut v = ~3;
let mut x = &mut v;
for 3.times {
borrow(v); //~ ERROR cannot borrow
}
*x = ~5;
}
fn loop_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
loop {
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
}
}
fn while_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
while cond() {
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
}
}
fn | () {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
for for_func {
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
}
}
fn loop_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
loop {
borrow_mut(v);
_x = &v;
break;
}
borrow_mut(v); //~ ERROR cannot borrow
}
fn while_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
while cond() {
borrow_mut(v);
_x = &v;
break;
}
borrow_mut(v); //~ ERROR cannot borrow
}
fn for_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
for for_func {
// here we cannot be sure that `for_func` respects the break below
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
break;
}
borrow_mut(v); //~ ERROR cannot borrow
}
fn while_aliased_mut_cond(cond: bool, cond2: bool) {
let mut v = ~3;
let mut w = ~4;
let mut x = &mut w;
while cond {
**x += 1;
borrow(v); //~ ERROR cannot borrow
if cond2 {
x = &mut v; //~ ERROR cannot borrow
}
}
}
fn loop_break_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) {
// Here we check that when you break out of an inner loop, the
// borrows that go out of scope as you exit the inner loop are
// removed from the bitset.
while cond() {
while cond() {
// this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
if!f(&mut *r) {
break; //...so it is not live as exit the `while` loop here
}
}
}
}
fn loop_loop_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) {
// Similar to `loop_break_pops_scopes` but for the `loop` keyword
while cond() {
while cond() {
// this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
if!f(&mut *r) {
loop; //...so it is not live as exit (and re-enter) the `while` loop here
}
}
}
}
fn main() {}
| for_loop_aliased_mut | identifier_name |
borrowck-lend-flow-loop.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.
// Note: the borrowck analysis is currently flow-insensitive.
// Therefore, some of these errors are marked as spurious and could be
// corrected by a simple change to the analysis. The others are
// either genuine or would require more advanced changes. The latter
// cases are noted.
fn borrow(_v: &int) {}
fn borrow_mut(_v: &mut int) {}
fn cond() -> bool { fail!() }
fn for_func(_f: &fn() -> bool) -> bool { fail!() }
fn produce<T>() -> T { fail!(); }
fn inc(v: &mut ~int) {
*v = ~(**v + 1);
}
fn loop_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire loop.
let mut v = ~3;
let mut x = &mut v;
**x += 1;
loop {
borrow(v); //~ ERROR cannot borrow
}
}
fn block_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire closure call.
let mut v = ~3;
let mut x = &mut v;
for 3.times {
borrow(v); //~ ERROR cannot borrow
}
*x = ~5;
}
fn loop_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
loop {
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
}
}
fn while_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
while cond() {
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
}
}
fn for_loop_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
for for_func {
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
}
}
fn loop_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
loop {
borrow_mut(v);
_x = &v;
break;
}
borrow_mut(v); //~ ERROR cannot borrow
}
fn while_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
while cond() {
borrow_mut(v);
_x = &v;
break;
}
borrow_mut(v); //~ ERROR cannot borrow
}
fn for_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
for for_func {
// here we cannot be sure that `for_func` respects the break below
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
break;
}
borrow_mut(v); //~ ERROR cannot borrow
}
fn while_aliased_mut_cond(cond: bool, cond2: bool) {
let mut v = ~3;
let mut w = ~4;
let mut x = &mut w;
while cond {
**x += 1;
borrow(v); //~ ERROR cannot borrow
if cond2 {
x = &mut v; //~ ERROR cannot borrow
}
}
}
fn loop_break_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) {
// Here we check that when you break out of an inner loop, the
// borrows that go out of scope as you exit the inner loop are
// removed from the bitset.
while cond() {
while cond() {
// this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
if!f(&mut *r) {
break; //...so it is not live as exit the `while` loop here
}
}
}
}
fn loop_loop_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) {
// Similar to `loop_break_pops_scopes` but for the `loop` keyword
while cond() {
while cond() {
// this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
if!f(&mut *r) |
}
}
}
fn main() {}
| {
loop; // ...so it is not live as exit (and re-enter) the `while` loop here
} | conditional_block |
borrowck-lend-flow-loop.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.
// Note: the borrowck analysis is currently flow-insensitive.
// Therefore, some of these errors are marked as spurious and could be
// corrected by a simple change to the analysis. The others are
// either genuine or would require more advanced changes. The latter
// cases are noted.
fn borrow(_v: &int) {}
fn borrow_mut(_v: &mut int) |
fn cond() -> bool { fail!() }
fn for_func(_f: &fn() -> bool) -> bool { fail!() }
fn produce<T>() -> T { fail!(); }
fn inc(v: &mut ~int) {
*v = ~(**v + 1);
}
fn loop_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire loop.
let mut v = ~3;
let mut x = &mut v;
**x += 1;
loop {
borrow(v); //~ ERROR cannot borrow
}
}
fn block_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire closure call.
let mut v = ~3;
let mut x = &mut v;
for 3.times {
borrow(v); //~ ERROR cannot borrow
}
*x = ~5;
}
fn loop_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
loop {
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
}
}
fn while_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
while cond() {
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
}
}
fn for_loop_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
for for_func {
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
}
}
fn loop_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
loop {
borrow_mut(v);
_x = &v;
break;
}
borrow_mut(v); //~ ERROR cannot borrow
}
fn while_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
while cond() {
borrow_mut(v);
_x = &v;
break;
}
borrow_mut(v); //~ ERROR cannot borrow
}
fn for_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
for for_func {
// here we cannot be sure that `for_func` respects the break below
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
break;
}
borrow_mut(v); //~ ERROR cannot borrow
}
fn while_aliased_mut_cond(cond: bool, cond2: bool) {
let mut v = ~3;
let mut w = ~4;
let mut x = &mut w;
while cond {
**x += 1;
borrow(v); //~ ERROR cannot borrow
if cond2 {
x = &mut v; //~ ERROR cannot borrow
}
}
}
fn loop_break_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) {
// Here we check that when you break out of an inner loop, the
// borrows that go out of scope as you exit the inner loop are
// removed from the bitset.
while cond() {
while cond() {
// this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
if!f(&mut *r) {
break; //...so it is not live as exit the `while` loop here
}
}
}
}
fn loop_loop_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) {
// Similar to `loop_break_pops_scopes` but for the `loop` keyword
while cond() {
while cond() {
// this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
if!f(&mut *r) {
loop; //...so it is not live as exit (and re-enter) the `while` loop here
}
}
}
}
fn main() {}
| {} | identifier_body |
borrowck-lend-flow-loop.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.
// Note: the borrowck analysis is currently flow-insensitive.
// Therefore, some of these errors are marked as spurious and could be
// corrected by a simple change to the analysis. The others are
// either genuine or would require more advanced changes. The latter
// cases are noted.
fn borrow(_v: &int) {}
fn borrow_mut(_v: &mut int) {}
fn cond() -> bool { fail!() }
fn for_func(_f: &fn() -> bool) -> bool { fail!() }
fn produce<T>() -> T { fail!(); }
fn inc(v: &mut ~int) {
*v = ~(**v + 1);
}
fn loop_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire loop.
let mut v = ~3;
let mut x = &mut v;
**x += 1;
loop {
borrow(v); //~ ERROR cannot borrow
}
}
fn block_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire closure call.
let mut v = ~3;
let mut x = &mut v;
for 3.times {
borrow(v); //~ ERROR cannot borrow
}
*x = ~5;
}
fn loop_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
loop {
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
}
}
fn while_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
while cond() {
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
}
}
fn for_loop_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
for for_func {
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
}
}
fn loop_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
loop {
borrow_mut(v);
_x = &v;
break;
}
borrow_mut(v); //~ ERROR cannot borrow
}
fn while_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
while cond() {
borrow_mut(v);
_x = &v;
break;
}
borrow_mut(v); //~ ERROR cannot borrow
}
fn for_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
for for_func {
// here we cannot be sure that `for_func` respects the break below
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
break;
}
borrow_mut(v); //~ ERROR cannot borrow
}
fn while_aliased_mut_cond(cond: bool, cond2: bool) {
let mut v = ~3;
let mut w = ~4;
let mut x = &mut w;
while cond {
**x += 1;
borrow(v); //~ ERROR cannot borrow
if cond2 {
x = &mut v; //~ ERROR cannot borrow
}
}
}
fn loop_break_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) {
// Here we check that when you break out of an inner loop, the
// borrows that go out of scope as you exit the inner loop are
// removed from the bitset.
while cond() {
while cond() {
// this borrow is limited to the scope of `r`... | break; //...so it is not live as exit the `while` loop here
}
}
}
}
fn loop_loop_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) {
// Similar to `loop_break_pops_scopes` but for the `loop` keyword
while cond() {
while cond() {
// this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
if!f(&mut *r) {
loop; //...so it is not live as exit (and re-enter) the `while` loop here
}
}
}
}
fn main() {} | let r: &'r mut uint = produce();
if !f(&mut *r) { | random_line_split |
source.rs | use crate::{Interest, Registry, Token};
use std::io;
/// An event source that may be registered with [`Registry`].
///
/// Types that implement `event::Source` can be registered with
/// `Registry`. Users of Mio **should not** use the `event::Source` trait
/// functions directly. Instead, the equivalent functions on `Registry` should
/// be used.
///
/// See [`Registry`] for more details.
///
/// [`Registry`]:../struct.Registry.html
///
/// # Implementing `event::Source`
///
/// Event sources are always backed by system handles, such as sockets or other
/// system handles. These `event::Source`s will be monitored by the system
/// selector. An implementation of `Source` will almost always delegates to a
/// lower level handle. Examples of this are [`TcpStream`]s, or the *unix only*
/// [`SourceFd`].
///
/// [`TcpStream`]:../net/struct.TcpStream.html
/// [`SourceFd`]:../unix/struct.SourceFd.html
///
/// # Dropping `event::Source`s
///
/// All `event::Source`s, unless otherwise specified, need to be [deregistered]
/// before being dropped for them to not leak resources. This goes against the
/// normal drop behaviour of types in Rust which cleanup after themselves, e.g.
/// a `File` will close itself. However since deregistering needs access to
/// [`Registry`] this cannot be done while being dropped.
///
/// [deregistered]:../struct.Registry.html#method.deregister
///
/// # Examples
///
/// Implementing `Source` on a struct containing a socket:
///
#[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
#[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
/// use mio::{Interest, Registry, Token};
/// use mio::event::Source;
/// use mio::net::TcpStream;
///
/// use std::io;
///
/// # #[allow(dead_code)]
/// pub struct MySource {
/// socket: TcpStream,
/// }
///
/// impl Source for MySource {
/// fn register(&mut self, registry: &Registry, token: Token, interests: Interest)
/// -> io::Result<()>
/// {
/// // Delegate the `register` call to `socket`
/// self.socket.register(registry, token, interests)
/// }
///
/// fn reregister(&mut self, registry: &Registry, token: Token, interests: Interest)
/// -> io::Result<()>
/// {
/// // Delegate the `reregister` call to `socket`
/// self.socket.reregister(registry, token, interests)
/// }
///
/// fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
/// // Delegate the `deregister` call to `socket`
/// self.socket.deregister(registry)
/// }
/// }
/// ```
pub trait Source {
/// Register `self` with the given `Registry` instance.
///
/// This function should not be called directly. Use [`Registry::register`]
/// instead. Implementors should handle registration by delegating the call
/// to another `Source` type.
///
/// [`Registry::register`]:../struct.Registry.html#method.register
fn register(
&mut self,
registry: &Registry,
token: Token,
interests: Interest,
) -> io::Result<()>;
/// Re-register `self` with the given `Registry` instance.
///
/// This function should not be called directly. Use
/// [`Registry::reregister`] instead. Implementors should handle | ///
/// [`Registry::reregister`]:../struct.Registry.html#method.reregister
fn reregister(
&mut self,
registry: &Registry,
token: Token,
interests: Interest,
) -> io::Result<()>;
/// Deregister `self` from the given `Registry` instance.
///
/// This function should not be called directly. Use
/// [`Registry::deregister`] instead. Implementors should handle
/// deregistration by delegating the call to another `Source` type.
///
/// [`Registry::deregister`]:../struct.Registry.html#method.deregister
fn deregister(&mut self, registry: &Registry) -> io::Result<()>;
}
impl<T> Source for Box<T>
where
T: Source +?Sized,
{
fn register(
&mut self,
registry: &Registry,
token: Token,
interests: Interest,
) -> io::Result<()> {
(&mut **self).register(registry, token, interests)
}
fn reregister(
&mut self,
registry: &Registry,
token: Token,
interests: Interest,
) -> io::Result<()> {
(&mut **self).reregister(registry, token, interests)
}
fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
(&mut **self).deregister(registry)
}
} | /// re-registration by either delegating the call to another `Source` type. | random_line_split |
source.rs | use crate::{Interest, Registry, Token};
use std::io;
/// An event source that may be registered with [`Registry`].
///
/// Types that implement `event::Source` can be registered with
/// `Registry`. Users of Mio **should not** use the `event::Source` trait
/// functions directly. Instead, the equivalent functions on `Registry` should
/// be used.
///
/// See [`Registry`] for more details.
///
/// [`Registry`]:../struct.Registry.html
///
/// # Implementing `event::Source`
///
/// Event sources are always backed by system handles, such as sockets or other
/// system handles. These `event::Source`s will be monitored by the system
/// selector. An implementation of `Source` will almost always delegates to a
/// lower level handle. Examples of this are [`TcpStream`]s, or the *unix only*
/// [`SourceFd`].
///
/// [`TcpStream`]:../net/struct.TcpStream.html
/// [`SourceFd`]:../unix/struct.SourceFd.html
///
/// # Dropping `event::Source`s
///
/// All `event::Source`s, unless otherwise specified, need to be [deregistered]
/// before being dropped for them to not leak resources. This goes against the
/// normal drop behaviour of types in Rust which cleanup after themselves, e.g.
/// a `File` will close itself. However since deregistering needs access to
/// [`Registry`] this cannot be done while being dropped.
///
/// [deregistered]:../struct.Registry.html#method.deregister
///
/// # Examples
///
/// Implementing `Source` on a struct containing a socket:
///
#[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
#[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
/// use mio::{Interest, Registry, Token};
/// use mio::event::Source;
/// use mio::net::TcpStream;
///
/// use std::io;
///
/// # #[allow(dead_code)]
/// pub struct MySource {
/// socket: TcpStream,
/// }
///
/// impl Source for MySource {
/// fn register(&mut self, registry: &Registry, token: Token, interests: Interest)
/// -> io::Result<()>
/// {
/// // Delegate the `register` call to `socket`
/// self.socket.register(registry, token, interests)
/// }
///
/// fn reregister(&mut self, registry: &Registry, token: Token, interests: Interest)
/// -> io::Result<()>
/// {
/// // Delegate the `reregister` call to `socket`
/// self.socket.reregister(registry, token, interests)
/// }
///
/// fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
/// // Delegate the `deregister` call to `socket`
/// self.socket.deregister(registry)
/// }
/// }
/// ```
pub trait Source {
/// Register `self` with the given `Registry` instance.
///
/// This function should not be called directly. Use [`Registry::register`]
/// instead. Implementors should handle registration by delegating the call
/// to another `Source` type.
///
/// [`Registry::register`]:../struct.Registry.html#method.register
fn register(
&mut self,
registry: &Registry,
token: Token,
interests: Interest,
) -> io::Result<()>;
/// Re-register `self` with the given `Registry` instance.
///
/// This function should not be called directly. Use
/// [`Registry::reregister`] instead. Implementors should handle
/// re-registration by either delegating the call to another `Source` type.
///
/// [`Registry::reregister`]:../struct.Registry.html#method.reregister
fn reregister(
&mut self,
registry: &Registry,
token: Token,
interests: Interest,
) -> io::Result<()>;
/// Deregister `self` from the given `Registry` instance.
///
/// This function should not be called directly. Use
/// [`Registry::deregister`] instead. Implementors should handle
/// deregistration by delegating the call to another `Source` type.
///
/// [`Registry::deregister`]:../struct.Registry.html#method.deregister
fn deregister(&mut self, registry: &Registry) -> io::Result<()>;
}
impl<T> Source for Box<T>
where
T: Source +?Sized,
{
fn | (
&mut self,
registry: &Registry,
token: Token,
interests: Interest,
) -> io::Result<()> {
(&mut **self).register(registry, token, interests)
}
fn reregister(
&mut self,
registry: &Registry,
token: Token,
interests: Interest,
) -> io::Result<()> {
(&mut **self).reregister(registry, token, interests)
}
fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
(&mut **self).deregister(registry)
}
}
| register | identifier_name |
source.rs | use crate::{Interest, Registry, Token};
use std::io;
/// An event source that may be registered with [`Registry`].
///
/// Types that implement `event::Source` can be registered with
/// `Registry`. Users of Mio **should not** use the `event::Source` trait
/// functions directly. Instead, the equivalent functions on `Registry` should
/// be used.
///
/// See [`Registry`] for more details.
///
/// [`Registry`]:../struct.Registry.html
///
/// # Implementing `event::Source`
///
/// Event sources are always backed by system handles, such as sockets or other
/// system handles. These `event::Source`s will be monitored by the system
/// selector. An implementation of `Source` will almost always delegates to a
/// lower level handle. Examples of this are [`TcpStream`]s, or the *unix only*
/// [`SourceFd`].
///
/// [`TcpStream`]:../net/struct.TcpStream.html
/// [`SourceFd`]:../unix/struct.SourceFd.html
///
/// # Dropping `event::Source`s
///
/// All `event::Source`s, unless otherwise specified, need to be [deregistered]
/// before being dropped for them to not leak resources. This goes against the
/// normal drop behaviour of types in Rust which cleanup after themselves, e.g.
/// a `File` will close itself. However since deregistering needs access to
/// [`Registry`] this cannot be done while being dropped.
///
/// [deregistered]:../struct.Registry.html#method.deregister
///
/// # Examples
///
/// Implementing `Source` on a struct containing a socket:
///
#[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
#[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
/// use mio::{Interest, Registry, Token};
/// use mio::event::Source;
/// use mio::net::TcpStream;
///
/// use std::io;
///
/// # #[allow(dead_code)]
/// pub struct MySource {
/// socket: TcpStream,
/// }
///
/// impl Source for MySource {
/// fn register(&mut self, registry: &Registry, token: Token, interests: Interest)
/// -> io::Result<()>
/// {
/// // Delegate the `register` call to `socket`
/// self.socket.register(registry, token, interests)
/// }
///
/// fn reregister(&mut self, registry: &Registry, token: Token, interests: Interest)
/// -> io::Result<()>
/// {
/// // Delegate the `reregister` call to `socket`
/// self.socket.reregister(registry, token, interests)
/// }
///
/// fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
/// // Delegate the `deregister` call to `socket`
/// self.socket.deregister(registry)
/// }
/// }
/// ```
pub trait Source {
/// Register `self` with the given `Registry` instance.
///
/// This function should not be called directly. Use [`Registry::register`]
/// instead. Implementors should handle registration by delegating the call
/// to another `Source` type.
///
/// [`Registry::register`]:../struct.Registry.html#method.register
fn register(
&mut self,
registry: &Registry,
token: Token,
interests: Interest,
) -> io::Result<()>;
/// Re-register `self` with the given `Registry` instance.
///
/// This function should not be called directly. Use
/// [`Registry::reregister`] instead. Implementors should handle
/// re-registration by either delegating the call to another `Source` type.
///
/// [`Registry::reregister`]:../struct.Registry.html#method.reregister
fn reregister(
&mut self,
registry: &Registry,
token: Token,
interests: Interest,
) -> io::Result<()>;
/// Deregister `self` from the given `Registry` instance.
///
/// This function should not be called directly. Use
/// [`Registry::deregister`] instead. Implementors should handle
/// deregistration by delegating the call to another `Source` type.
///
/// [`Registry::deregister`]:../struct.Registry.html#method.deregister
fn deregister(&mut self, registry: &Registry) -> io::Result<()>;
}
impl<T> Source for Box<T>
where
T: Source +?Sized,
{
fn register(
&mut self,
registry: &Registry,
token: Token,
interests: Interest,
) -> io::Result<()> {
(&mut **self).register(registry, token, interests)
}
fn reregister(
&mut self,
registry: &Registry,
token: Token,
interests: Interest,
) -> io::Result<()> {
(&mut **self).reregister(registry, token, interests)
}
fn deregister(&mut self, registry: &Registry) -> io::Result<()> |
}
| {
(&mut **self).deregister(registry)
} | identifier_body |
random.rs | use rand::{
distributions::Alphanumeric,
prelude::{Rng, SeedableRng, StdRng},
};
const OPERATORS: &[char] = &[
'+', '-', '<', '>', '(', ')', '*', '/', '&', '|', '!', ',', '.',
];
pub struct | (StdRng);
impl Rand {
pub fn new(seed: usize) -> Self {
Rand(StdRng::seed_from_u64(seed as u64))
}
pub fn unsigned(&mut self, max: usize) -> usize {
self.0.gen_range(0..max + 1)
}
pub fn words(&mut self, max_count: usize) -> Vec<u8> {
let mut result = Vec::new();
let word_count = self.unsigned(max_count);
for i in 0..word_count {
if i > 0 {
if self.unsigned(5) == 0 {
result.push('\n' as u8);
} else {
result.push(''as u8);
}
}
if self.unsigned(3) == 0 {
let index = self.unsigned(OPERATORS.len() - 1);
result.push(OPERATORS[index] as u8);
} else {
for _ in 0..self.unsigned(8) {
result.push(self.0.sample(Alphanumeric) as u8);
}
}
}
result
}
}
| Rand | identifier_name |
random.rs | use rand::{
distributions::Alphanumeric,
prelude::{Rng, SeedableRng, StdRng},
};
const OPERATORS: &[char] = &[
'+', '-', '<', '>', '(', ')', '*', '/', '&', '|', '!', ',', '.',
];
pub struct Rand(StdRng);
impl Rand {
pub fn new(seed: usize) -> Self {
Rand(StdRng::seed_from_u64(seed as u64))
}
pub fn unsigned(&mut self, max: usize) -> usize {
self.0.gen_range(0..max + 1)
} | for i in 0..word_count {
if i > 0 {
if self.unsigned(5) == 0 {
result.push('\n' as u8);
} else {
result.push(''as u8);
}
}
if self.unsigned(3) == 0 {
let index = self.unsigned(OPERATORS.len() - 1);
result.push(OPERATORS[index] as u8);
} else {
for _ in 0..self.unsigned(8) {
result.push(self.0.sample(Alphanumeric) as u8);
}
}
}
result
}
} |
pub fn words(&mut self, max_count: usize) -> Vec<u8> {
let mut result = Vec::new();
let word_count = self.unsigned(max_count); | random_line_split |
random.rs | use rand::{
distributions::Alphanumeric,
prelude::{Rng, SeedableRng, StdRng},
};
const OPERATORS: &[char] = &[
'+', '-', '<', '>', '(', ')', '*', '/', '&', '|', '!', ',', '.',
];
pub struct Rand(StdRng);
impl Rand {
pub fn new(seed: usize) -> Self {
Rand(StdRng::seed_from_u64(seed as u64))
}
pub fn unsigned(&mut self, max: usize) -> usize {
self.0.gen_range(0..max + 1)
}
pub fn words(&mut self, max_count: usize) -> Vec<u8> {
let mut result = Vec::new();
let word_count = self.unsigned(max_count);
for i in 0..word_count {
if i > 0 {
if self.unsigned(5) == 0 {
result.push('\n' as u8);
} else {
result.push(''as u8);
}
}
if self.unsigned(3) == 0 {
let index = self.unsigned(OPERATORS.len() - 1);
result.push(OPERATORS[index] as u8);
} else |
}
result
}
}
| {
for _ in 0..self.unsigned(8) {
result.push(self.0.sample(Alphanumeric) as u8);
}
} | conditional_block |
version.rs | /*!
Querying SDL Version
*/
use std::ffi::CStr;
use std::fmt;
use crate::sys;
/// A structure that contains information about the version of SDL in use.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct Version {
/// major version
pub major: u8,
/// minor version
pub minor: u8,
/// update version (patchlevel)
pub patch: u8,
}
impl Version {
/// Convert a raw *SDL_version to Version.
pub fn from_ll(v: sys::SDL_version) -> Version {
Version {
major: v.major,
minor: v.minor,
patch: v.patch,
}
}
}
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch) |
/// Get the version of SDL that is linked against your program.
#[doc(alias = "SDL_GetVersion")]
pub fn version() -> Version {
unsafe {
let mut cver = sys::SDL_version {
major: 0,
minor: 0,
patch: 0,
};
sys::SDL_GetVersion(&mut cver);
Version::from_ll(cver)
}
}
/// Get the code revision of SDL that is linked against your program.
#[doc(alias = "SDL_GetRevision")]
pub fn revision() -> String {
unsafe {
let rev = sys::SDL_GetRevision();
CStr::from_ptr(rev as *const _).to_str().unwrap().to_owned()
}
}
/// Get the revision number of SDL that is linked against your program.
#[doc(alias = "SDL_GetRevisionNumber")]
pub fn revision_number() -> i32 {
unsafe { sys::SDL_GetRevisionNumber() }
} | }
} | random_line_split |
version.rs | /*!
Querying SDL Version
*/
use std::ffi::CStr;
use std::fmt;
use crate::sys;
/// A structure that contains information about the version of SDL in use.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct Version {
/// major version
pub major: u8,
/// minor version
pub minor: u8,
/// update version (patchlevel)
pub patch: u8,
}
impl Version {
/// Convert a raw *SDL_version to Version.
pub fn from_ll(v: sys::SDL_version) -> Version {
Version {
major: v.major,
minor: v.minor,
patch: v.patch,
}
}
}
impl fmt::Display for Version {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
}
}
/// Get the version of SDL that is linked against your program.
#[doc(alias = "SDL_GetVersion")]
pub fn version() -> Version {
unsafe {
let mut cver = sys::SDL_version {
major: 0,
minor: 0,
patch: 0,
};
sys::SDL_GetVersion(&mut cver);
Version::from_ll(cver)
}
}
/// Get the code revision of SDL that is linked against your program.
#[doc(alias = "SDL_GetRevision")]
pub fn revision() -> String {
unsafe {
let rev = sys::SDL_GetRevision();
CStr::from_ptr(rev as *const _).to_str().unwrap().to_owned()
}
}
/// Get the revision number of SDL that is linked against your program.
#[doc(alias = "SDL_GetRevisionNumber")]
pub fn revision_number() -> i32 {
unsafe { sys::SDL_GetRevisionNumber() }
}
| fmt | identifier_name |
version.rs | /*!
Querying SDL Version
*/
use std::ffi::CStr;
use std::fmt;
use crate::sys;
/// A structure that contains information about the version of SDL in use.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct Version {
/// major version
pub major: u8,
/// minor version
pub minor: u8,
/// update version (patchlevel)
pub patch: u8,
}
impl Version {
/// Convert a raw *SDL_version to Version.
pub fn from_ll(v: sys::SDL_version) -> Version {
Version {
major: v.major,
minor: v.minor,
patch: v.patch,
}
}
}
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
/// Get the version of SDL that is linked against your program.
#[doc(alias = "SDL_GetVersion")]
pub fn version() -> Version {
unsafe {
let mut cver = sys::SDL_version {
major: 0,
minor: 0,
patch: 0,
};
sys::SDL_GetVersion(&mut cver);
Version::from_ll(cver)
}
}
/// Get the code revision of SDL that is linked against your program.
#[doc(alias = "SDL_GetRevision")]
pub fn revision() -> String {
unsafe {
let rev = sys::SDL_GetRevision();
CStr::from_ptr(rev as *const _).to_str().unwrap().to_owned()
}
}
/// Get the revision number of SDL that is linked against your program.
#[doc(alias = "SDL_GetRevisionNumber")]
pub fn revision_number() -> i32 {
unsafe { sys::SDL_GetRevisionNumber() }
}
| {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
} | identifier_body |
app.rs | use actix::prelude::*;
use actix_web::*;
use actors::{ForwardA2AMsg, GetEndpoint};
use actors::forward_agent::ForwardAgent;
use bytes::Bytes;
use domain::config::AppConfig;
use futures::*;
const MAX_PAYLOAD_SIZE: usize = 105_906_176;
pub struct AppState {
pub forward_agent: Addr<ForwardAgent>,
}
pub fn | (config: AppConfig, forward_agent: Addr<ForwardAgent>) -> App<AppState> {
App::with_state(AppState { forward_agent })
.prefix(config.prefix)
.middleware(middleware::Logger::default()) // enable logger
.resource("", |r| r.method(http::Method::GET).with(_get_endpoint_details))
.resource("/msg", |r| r.method(http::Method::POST).with(_forward_message))
}
fn _get_endpoint_details(state: State<AppState>) -> FutureResponse<HttpResponse> {
state.forward_agent
.send(GetEndpoint {})
.from_err()
.map(|res| match res {
Ok(endpoint) => HttpResponse::Ok().json(&endpoint),
Err(err) => HttpResponse::InternalServerError().body(format!("{:?}", err)).into(), // FIXME: Better error
})
.responder()
}
fn _forward_message((state, req): (State<AppState>, HttpRequest<AppState>)) -> FutureResponse<HttpResponse> {
req
.body()
.limit(MAX_PAYLOAD_SIZE)
.from_err()
.and_then(move |body| {
state.forward_agent
.send(ForwardA2AMsg(body.to_vec()))
.from_err()
.and_then(|res| match res {
Ok(msg) => Ok(Bytes::from(msg).into()),
Err(err) => Ok(HttpResponse::InternalServerError().body(format!("{:?}", err)).into()), // FIXME: Better error
})
})
.responder()
}
| new | identifier_name |
app.rs | use actix::prelude::*;
use actix_web::*;
use actors::{ForwardA2AMsg, GetEndpoint};
use actors::forward_agent::ForwardAgent;
use bytes::Bytes;
use domain::config::AppConfig;
use futures::*;
const MAX_PAYLOAD_SIZE: usize = 105_906_176;
pub struct AppState {
pub forward_agent: Addr<ForwardAgent>,
}
pub fn new(config: AppConfig, forward_agent: Addr<ForwardAgent>) -> App<AppState> |
fn _get_endpoint_details(state: State<AppState>) -> FutureResponse<HttpResponse> {
state.forward_agent
.send(GetEndpoint {})
.from_err()
.map(|res| match res {
Ok(endpoint) => HttpResponse::Ok().json(&endpoint),
Err(err) => HttpResponse::InternalServerError().body(format!("{:?}", err)).into(), // FIXME: Better error
})
.responder()
}
fn _forward_message((state, req): (State<AppState>, HttpRequest<AppState>)) -> FutureResponse<HttpResponse> {
req
.body()
.limit(MAX_PAYLOAD_SIZE)
.from_err()
.and_then(move |body| {
state.forward_agent
.send(ForwardA2AMsg(body.to_vec()))
.from_err()
.and_then(|res| match res {
Ok(msg) => Ok(Bytes::from(msg).into()),
Err(err) => Ok(HttpResponse::InternalServerError().body(format!("{:?}", err)).into()), // FIXME: Better error
})
})
.responder()
}
| {
App::with_state(AppState { forward_agent })
.prefix(config.prefix)
.middleware(middleware::Logger::default()) // enable logger
.resource("", |r| r.method(http::Method::GET).with(_get_endpoint_details))
.resource("/msg", |r| r.method(http::Method::POST).with(_forward_message))
} | identifier_body |
app.rs | use actix::prelude::*;
use actix_web::*;
use actors::{ForwardA2AMsg, GetEndpoint};
use actors::forward_agent::ForwardAgent;
use bytes::Bytes;
use domain::config::AppConfig;
use futures::*;
const MAX_PAYLOAD_SIZE: usize = 105_906_176;
pub struct AppState {
pub forward_agent: Addr<ForwardAgent>,
}
pub fn new(config: AppConfig, forward_agent: Addr<ForwardAgent>) -> App<AppState> {
App::with_state(AppState { forward_agent })
.prefix(config.prefix)
.middleware(middleware::Logger::default()) // enable logger
.resource("", |r| r.method(http::Method::GET).with(_get_endpoint_details))
.resource("/msg", |r| r.method(http::Method::POST).with(_forward_message))
}
fn _get_endpoint_details(state: State<AppState>) -> FutureResponse<HttpResponse> {
state.forward_agent
.send(GetEndpoint {})
.from_err()
.map(|res| match res {
Ok(endpoint) => HttpResponse::Ok().json(&endpoint),
Err(err) => HttpResponse::InternalServerError().body(format!("{:?}", err)).into(), // FIXME: Better error | })
.responder()
}
fn _forward_message((state, req): (State<AppState>, HttpRequest<AppState>)) -> FutureResponse<HttpResponse> {
req
.body()
.limit(MAX_PAYLOAD_SIZE)
.from_err()
.and_then(move |body| {
state.forward_agent
.send(ForwardA2AMsg(body.to_vec()))
.from_err()
.and_then(|res| match res {
Ok(msg) => Ok(Bytes::from(msg).into()),
Err(err) => Ok(HttpResponse::InternalServerError().body(format!("{:?}", err)).into()), // FIXME: Better error
})
})
.responder()
} | random_line_split |
|
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(ascii)]
#![feature(as_unsafe_cell)]
#![feature(borrow_state)]
#![feature(box_syntax)]
#![feature(cell_extras)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(fnbox)]
#![feature(hashmap_hasher)]
#![feature(iter_arith)]
#![feature(mpsc_select)]
#![feature(nonzero)]
#![feature(on_unimplemented)]
#![feature(peekable_is_empty)]
#![feature(plugin)]
#![feature(slice_patterns)]
#![feature(str_utf16)]
#![feature(unicode)]
#![deny(unsafe_code)]
#![allow(non_snake_case)]
#![doc = "The script crate contains all matters DOM."]
#![plugin(plugins)]
extern crate angle;
extern crate app_units;
#[macro_use]
extern crate bitflags;
extern crate canvas;
extern crate canvas_traits;
extern crate caseless;
extern crate core;
extern crate cssparser;
extern crate devtools_traits;
extern crate encoding;
extern crate euclid;
extern crate fnv;
extern crate html5ever;
extern crate hyper;
extern crate image;
extern crate ipc_channel;
extern crate js;
extern crate libc;
#[macro_use]
extern crate log;
extern crate msg;
extern crate net_traits;
extern crate num;
extern crate offscreen_gl_context;
#[macro_use]
extern crate profile_traits;
extern crate rand;
extern crate ref_slice;
extern crate rustc_serialize;
extern crate rustc_unicode;
extern crate script_traits;
#[macro_use(state_pseudo_classes)] extern crate selectors;
extern crate serde;
extern crate smallvec;
#[macro_use(atom, ns)] extern crate string_cache;
#[macro_use]
extern crate style;
extern crate style_traits;
extern crate tendril;
extern crate time;
extern crate unicase;
extern crate url;
#[macro_use]
extern crate util;
extern crate uuid;
extern crate websocket;
extern crate xml5ever;
pub mod clipboard_provider;
pub mod cors;
mod devtools;
pub mod document_loader;
#[macro_use]
pub mod dom;
pub mod layout_interface;
mod mem;
mod network_listener;
pub mod page;
pub mod parse;
pub mod reporter;
#[allow(unsafe_code)]
pub mod script_task;
pub mod textinput;
mod timers;
mod unpremultiplytable;
mod webdriver_handlers;
use dom::bindings::codegen::RegisterBindings;
use js::jsapi::SetDOMProxyInformation;
use std::ptr;
#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn perform_platform_specific_initialization() {
use std::mem;
// 4096 is default max on many linux systems
const MAX_FILE_LIMIT: libc::rlim_t = 4096;
// Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe {
let mut rlim: libc::rlimit = mem::uninitialized();
match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => {
if rlim.rlim_cur >= MAX_FILE_LIMIT {
// we have more than enough
return;
}
rlim.rlim_cur = match rlim.rlim_max {
libc::RLIM_INFINITY => MAX_FILE_LIMIT,
_ => {
if rlim.rlim_max < MAX_FILE_LIMIT | else {
MAX_FILE_LIMIT
}
}
};
match libc::setrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => (),
_ => warn!("Failed to set file count limit"),
};
},
_ => warn!("Failed to get file count limit"),
};
}
}
#[cfg(not(target_os = "linux"))]
fn perform_platform_specific_initialization() {}
#[allow(unsafe_code)]
pub fn init() {
unsafe {
assert_eq!(js::jsapi::JS_Init(), true);
SetDOMProxyInformation(ptr::null(), 0, Some(script_task::shadow_check_callback));
}
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
perform_platform_specific_initialization();
}
| {
rlim.rlim_max
} | 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/. */
#![feature(ascii)]
#![feature(as_unsafe_cell)]
#![feature(borrow_state)]
#![feature(box_syntax)]
#![feature(cell_extras)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(fnbox)]
#![feature(hashmap_hasher)]
#![feature(iter_arith)]
#![feature(mpsc_select)]
#![feature(nonzero)]
#![feature(on_unimplemented)]
#![feature(peekable_is_empty)]
#![feature(plugin)]
#![feature(slice_patterns)]
#![feature(str_utf16)]
#![feature(unicode)]
#![deny(unsafe_code)]
#![allow(non_snake_case)]
#![doc = "The script crate contains all matters DOM."]
#![plugin(plugins)]
extern crate angle;
extern crate app_units;
#[macro_use]
extern crate bitflags;
extern crate canvas;
extern crate canvas_traits;
extern crate caseless;
extern crate core;
extern crate cssparser;
extern crate devtools_traits;
extern crate encoding;
extern crate euclid;
extern crate fnv;
extern crate html5ever;
extern crate hyper;
extern crate image;
extern crate ipc_channel;
extern crate js;
extern crate libc;
#[macro_use]
extern crate log;
extern crate msg;
extern crate net_traits;
extern crate num;
extern crate offscreen_gl_context;
#[macro_use]
extern crate profile_traits;
extern crate rand;
extern crate ref_slice;
extern crate rustc_serialize;
extern crate rustc_unicode;
extern crate script_traits;
#[macro_use(state_pseudo_classes)] extern crate selectors;
extern crate serde;
extern crate smallvec;
#[macro_use(atom, ns)] extern crate string_cache;
#[macro_use]
extern crate style;
extern crate style_traits;
extern crate tendril;
extern crate time;
extern crate unicase;
extern crate url;
#[macro_use]
extern crate util;
extern crate uuid;
extern crate websocket;
extern crate xml5ever;
pub mod clipboard_provider;
pub mod cors;
mod devtools;
pub mod document_loader;
#[macro_use]
pub mod dom;
pub mod layout_interface;
mod mem;
mod network_listener;
pub mod page;
pub mod parse;
pub mod reporter;
#[allow(unsafe_code)]
pub mod script_task;
pub mod textinput;
mod timers;
mod unpremultiplytable;
mod webdriver_handlers;
use dom::bindings::codegen::RegisterBindings;
use js::jsapi::SetDOMProxyInformation;
use std::ptr;
#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn perform_platform_specific_initialization() {
use std::mem;
// 4096 is default max on many linux systems | // Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe {
let mut rlim: libc::rlimit = mem::uninitialized();
match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => {
if rlim.rlim_cur >= MAX_FILE_LIMIT {
// we have more than enough
return;
}
rlim.rlim_cur = match rlim.rlim_max {
libc::RLIM_INFINITY => MAX_FILE_LIMIT,
_ => {
if rlim.rlim_max < MAX_FILE_LIMIT {
rlim.rlim_max
} else {
MAX_FILE_LIMIT
}
}
};
match libc::setrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => (),
_ => warn!("Failed to set file count limit"),
};
},
_ => warn!("Failed to get file count limit"),
};
}
}
#[cfg(not(target_os = "linux"))]
fn perform_platform_specific_initialization() {}
#[allow(unsafe_code)]
pub fn init() {
unsafe {
assert_eq!(js::jsapi::JS_Init(), true);
SetDOMProxyInformation(ptr::null(), 0, Some(script_task::shadow_check_callback));
}
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
perform_platform_specific_initialization();
} | const MAX_FILE_LIMIT: libc::rlim_t = 4096;
| random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(ascii)]
#![feature(as_unsafe_cell)]
#![feature(borrow_state)]
#![feature(box_syntax)]
#![feature(cell_extras)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(fnbox)]
#![feature(hashmap_hasher)]
#![feature(iter_arith)]
#![feature(mpsc_select)]
#![feature(nonzero)]
#![feature(on_unimplemented)]
#![feature(peekable_is_empty)]
#![feature(plugin)]
#![feature(slice_patterns)]
#![feature(str_utf16)]
#![feature(unicode)]
#![deny(unsafe_code)]
#![allow(non_snake_case)]
#![doc = "The script crate contains all matters DOM."]
#![plugin(plugins)]
extern crate angle;
extern crate app_units;
#[macro_use]
extern crate bitflags;
extern crate canvas;
extern crate canvas_traits;
extern crate caseless;
extern crate core;
extern crate cssparser;
extern crate devtools_traits;
extern crate encoding;
extern crate euclid;
extern crate fnv;
extern crate html5ever;
extern crate hyper;
extern crate image;
extern crate ipc_channel;
extern crate js;
extern crate libc;
#[macro_use]
extern crate log;
extern crate msg;
extern crate net_traits;
extern crate num;
extern crate offscreen_gl_context;
#[macro_use]
extern crate profile_traits;
extern crate rand;
extern crate ref_slice;
extern crate rustc_serialize;
extern crate rustc_unicode;
extern crate script_traits;
#[macro_use(state_pseudo_classes)] extern crate selectors;
extern crate serde;
extern crate smallvec;
#[macro_use(atom, ns)] extern crate string_cache;
#[macro_use]
extern crate style;
extern crate style_traits;
extern crate tendril;
extern crate time;
extern crate unicase;
extern crate url;
#[macro_use]
extern crate util;
extern crate uuid;
extern crate websocket;
extern crate xml5ever;
pub mod clipboard_provider;
pub mod cors;
mod devtools;
pub mod document_loader;
#[macro_use]
pub mod dom;
pub mod layout_interface;
mod mem;
mod network_listener;
pub mod page;
pub mod parse;
pub mod reporter;
#[allow(unsafe_code)]
pub mod script_task;
pub mod textinput;
mod timers;
mod unpremultiplytable;
mod webdriver_handlers;
use dom::bindings::codegen::RegisterBindings;
use js::jsapi::SetDOMProxyInformation;
use std::ptr;
#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn | () {
use std::mem;
// 4096 is default max on many linux systems
const MAX_FILE_LIMIT: libc::rlim_t = 4096;
// Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe {
let mut rlim: libc::rlimit = mem::uninitialized();
match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => {
if rlim.rlim_cur >= MAX_FILE_LIMIT {
// we have more than enough
return;
}
rlim.rlim_cur = match rlim.rlim_max {
libc::RLIM_INFINITY => MAX_FILE_LIMIT,
_ => {
if rlim.rlim_max < MAX_FILE_LIMIT {
rlim.rlim_max
} else {
MAX_FILE_LIMIT
}
}
};
match libc::setrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => (),
_ => warn!("Failed to set file count limit"),
};
},
_ => warn!("Failed to get file count limit"),
};
}
}
#[cfg(not(target_os = "linux"))]
fn perform_platform_specific_initialization() {}
#[allow(unsafe_code)]
pub fn init() {
unsafe {
assert_eq!(js::jsapi::JS_Init(), true);
SetDOMProxyInformation(ptr::null(), 0, Some(script_task::shadow_check_callback));
}
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
perform_platform_specific_initialization();
}
| perform_platform_specific_initialization | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(ascii)]
#![feature(as_unsafe_cell)]
#![feature(borrow_state)]
#![feature(box_syntax)]
#![feature(cell_extras)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(fnbox)]
#![feature(hashmap_hasher)]
#![feature(iter_arith)]
#![feature(mpsc_select)]
#![feature(nonzero)]
#![feature(on_unimplemented)]
#![feature(peekable_is_empty)]
#![feature(plugin)]
#![feature(slice_patterns)]
#![feature(str_utf16)]
#![feature(unicode)]
#![deny(unsafe_code)]
#![allow(non_snake_case)]
#![doc = "The script crate contains all matters DOM."]
#![plugin(plugins)]
extern crate angle;
extern crate app_units;
#[macro_use]
extern crate bitflags;
extern crate canvas;
extern crate canvas_traits;
extern crate caseless;
extern crate core;
extern crate cssparser;
extern crate devtools_traits;
extern crate encoding;
extern crate euclid;
extern crate fnv;
extern crate html5ever;
extern crate hyper;
extern crate image;
extern crate ipc_channel;
extern crate js;
extern crate libc;
#[macro_use]
extern crate log;
extern crate msg;
extern crate net_traits;
extern crate num;
extern crate offscreen_gl_context;
#[macro_use]
extern crate profile_traits;
extern crate rand;
extern crate ref_slice;
extern crate rustc_serialize;
extern crate rustc_unicode;
extern crate script_traits;
#[macro_use(state_pseudo_classes)] extern crate selectors;
extern crate serde;
extern crate smallvec;
#[macro_use(atom, ns)] extern crate string_cache;
#[macro_use]
extern crate style;
extern crate style_traits;
extern crate tendril;
extern crate time;
extern crate unicase;
extern crate url;
#[macro_use]
extern crate util;
extern crate uuid;
extern crate websocket;
extern crate xml5ever;
pub mod clipboard_provider;
pub mod cors;
mod devtools;
pub mod document_loader;
#[macro_use]
pub mod dom;
pub mod layout_interface;
mod mem;
mod network_listener;
pub mod page;
pub mod parse;
pub mod reporter;
#[allow(unsafe_code)]
pub mod script_task;
pub mod textinput;
mod timers;
mod unpremultiplytable;
mod webdriver_handlers;
use dom::bindings::codegen::RegisterBindings;
use js::jsapi::SetDOMProxyInformation;
use std::ptr;
#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn perform_platform_specific_initialization() | rlim.rlim_max
} else {
MAX_FILE_LIMIT
}
}
};
match libc::setrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => (),
_ => warn!("Failed to set file count limit"),
};
},
_ => warn!("Failed to get file count limit"),
};
}
}
#[cfg(not(target_os = "linux"))]
fn perform_platform_specific_initialization() {}
#[allow(unsafe_code)]
pub fn init() {
unsafe {
assert_eq!(js::jsapi::JS_Init(), true);
SetDOMProxyInformation(ptr::null(), 0, Some(script_task::shadow_check_callback));
}
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
perform_platform_specific_initialization();
}
| {
use std::mem;
// 4096 is default max on many linux systems
const MAX_FILE_LIMIT: libc::rlim_t = 4096;
// Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe {
let mut rlim: libc::rlimit = mem::uninitialized();
match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => {
if rlim.rlim_cur >= MAX_FILE_LIMIT {
// we have more than enough
return;
}
rlim.rlim_cur = match rlim.rlim_max {
libc::RLIM_INFINITY => MAX_FILE_LIMIT,
_ => {
if rlim.rlim_max < MAX_FILE_LIMIT { | identifier_body |
events.rs | use std::sync::mpsc::{Sender, Receiver, channel};
use std::iter::Iterator;
use std::error::Error;
use error;
use frame::events::{ServerEvent as FrameServerEvent, SimpleServerEvent as FrameSimpleServerEvent,
SchemaChange as FrameSchemaChange};
use frame::parser::parse_frame;
use compression::Compression;
use transport::CDRSTransport;
/// Full Server Event which includes all details about occured change.
pub type ServerEvent = FrameServerEvent;
/// Simplified Server event. It should be used to represent an event
/// which consumer wants listen to.
pub type SimpleServerEvent = FrameSimpleServerEvent;
/// Reexport of `FrameSchemaChange`.
pub type SchemaChange = FrameSchemaChange;
/// Factory function which returns a `Listener` and related `EventStream.`
///
/// `Listener` provides only one function `start` to start listening. It
/// blocks a thread so should be moved into a separate one to no release
/// main thread.
///
/// `EventStream` is an iterator which returns new events once they come.
/// It is similar to `Receiver::iter`.
pub fn new_listener<X>(transport: X) -> (Listener<X>, EventStream) {
let (tx, rx) = channel();
let listener = Listener {
transport: transport,
tx: tx,
};
let stream = EventStream { rx: rx };
(listener, stream)
}
/// `Listener` provides only one function `start` to start listening. It
/// blocks a thread so should be moved into a separate one to no release
/// main thread.
pub struct Listener<X> {
transport: X,
tx: Sender<ServerEvent>,
}
impl<X: CDRSTransport> Listener<X> {
/// It starts a process of listening to new events. Locks a frame.
pub fn start(&mut self, compressor: &Compression) -> error::Result<()> {
loop {
let event_opt = try!(parse_frame(&mut self.transport, compressor))
.get_body()?
.into_server_event();
let event = if event_opt.is_some() | else {
continue;
};
match self.tx.send(event) {
Err(err) => return Err(error::Error::General(err.description().to_string())),
_ => continue,
}
}
}
}
/// `EventStream` is an iterator which returns new events once they come.
/// It is similar to `Receiver::iter`.
pub struct EventStream {
rx: Receiver<ServerEvent>,
}
impl Iterator for EventStream {
type Item = ServerEvent;
fn next(&mut self) -> Option<Self::Item> {
self.rx.recv().ok()
}
}
| {
// unwrap is safe is we've checked that event_opt.is_some()
event_opt.unwrap().event as ServerEvent
} | conditional_block |
events.rs | use std::sync::mpsc::{Sender, Receiver, channel};
use std::iter::Iterator;
use std::error::Error;
use error;
use frame::events::{ServerEvent as FrameServerEvent, SimpleServerEvent as FrameSimpleServerEvent,
SchemaChange as FrameSchemaChange};
use frame::parser::parse_frame;
use compression::Compression;
use transport::CDRSTransport;
/// Full Server Event which includes all details about occured change.
pub type ServerEvent = FrameServerEvent;
/// Simplified Server event. It should be used to represent an event
/// which consumer wants listen to.
pub type SimpleServerEvent = FrameSimpleServerEvent;
/// Reexport of `FrameSchemaChange`.
pub type SchemaChange = FrameSchemaChange;
/// Factory function which returns a `Listener` and related `EventStream.`
///
/// `Listener` provides only one function `start` to start listening. It
/// blocks a thread so should be moved into a separate one to no release | /// It is similar to `Receiver::iter`.
pub fn new_listener<X>(transport: X) -> (Listener<X>, EventStream) {
let (tx, rx) = channel();
let listener = Listener {
transport: transport,
tx: tx,
};
let stream = EventStream { rx: rx };
(listener, stream)
}
/// `Listener` provides only one function `start` to start listening. It
/// blocks a thread so should be moved into a separate one to no release
/// main thread.
pub struct Listener<X> {
transport: X,
tx: Sender<ServerEvent>,
}
impl<X: CDRSTransport> Listener<X> {
/// It starts a process of listening to new events. Locks a frame.
pub fn start(&mut self, compressor: &Compression) -> error::Result<()> {
loop {
let event_opt = try!(parse_frame(&mut self.transport, compressor))
.get_body()?
.into_server_event();
let event = if event_opt.is_some() {
// unwrap is safe is we've checked that event_opt.is_some()
event_opt.unwrap().event as ServerEvent
} else {
continue;
};
match self.tx.send(event) {
Err(err) => return Err(error::Error::General(err.description().to_string())),
_ => continue,
}
}
}
}
/// `EventStream` is an iterator which returns new events once they come.
/// It is similar to `Receiver::iter`.
pub struct EventStream {
rx: Receiver<ServerEvent>,
}
impl Iterator for EventStream {
type Item = ServerEvent;
fn next(&mut self) -> Option<Self::Item> {
self.rx.recv().ok()
}
} | /// main thread.
///
/// `EventStream` is an iterator which returns new events once they come. | random_line_split |
events.rs | use std::sync::mpsc::{Sender, Receiver, channel};
use std::iter::Iterator;
use std::error::Error;
use error;
use frame::events::{ServerEvent as FrameServerEvent, SimpleServerEvent as FrameSimpleServerEvent,
SchemaChange as FrameSchemaChange};
use frame::parser::parse_frame;
use compression::Compression;
use transport::CDRSTransport;
/// Full Server Event which includes all details about occured change.
pub type ServerEvent = FrameServerEvent;
/// Simplified Server event. It should be used to represent an event
/// which consumer wants listen to.
pub type SimpleServerEvent = FrameSimpleServerEvent;
/// Reexport of `FrameSchemaChange`.
pub type SchemaChange = FrameSchemaChange;
/// Factory function which returns a `Listener` and related `EventStream.`
///
/// `Listener` provides only one function `start` to start listening. It
/// blocks a thread so should be moved into a separate one to no release
/// main thread.
///
/// `EventStream` is an iterator which returns new events once they come.
/// It is similar to `Receiver::iter`.
pub fn new_listener<X>(transport: X) -> (Listener<X>, EventStream) {
let (tx, rx) = channel();
let listener = Listener {
transport: transport,
tx: tx,
};
let stream = EventStream { rx: rx };
(listener, stream)
}
/// `Listener` provides only one function `start` to start listening. It
/// blocks a thread so should be moved into a separate one to no release
/// main thread.
pub struct Listener<X> {
transport: X,
tx: Sender<ServerEvent>,
}
impl<X: CDRSTransport> Listener<X> {
/// It starts a process of listening to new events. Locks a frame.
pub fn start(&mut self, compressor: &Compression) -> error::Result<()> |
}
/// `EventStream` is an iterator which returns new events once they come.
/// It is similar to `Receiver::iter`.
pub struct EventStream {
rx: Receiver<ServerEvent>,
}
impl Iterator for EventStream {
type Item = ServerEvent;
fn next(&mut self) -> Option<Self::Item> {
self.rx.recv().ok()
}
}
| {
loop {
let event_opt = try!(parse_frame(&mut self.transport, compressor))
.get_body()?
.into_server_event();
let event = if event_opt.is_some() {
// unwrap is safe is we've checked that event_opt.is_some()
event_opt.unwrap().event as ServerEvent
} else {
continue;
};
match self.tx.send(event) {
Err(err) => return Err(error::Error::General(err.description().to_string())),
_ => continue,
}
}
} | identifier_body |
events.rs | use std::sync::mpsc::{Sender, Receiver, channel};
use std::iter::Iterator;
use std::error::Error;
use error;
use frame::events::{ServerEvent as FrameServerEvent, SimpleServerEvent as FrameSimpleServerEvent,
SchemaChange as FrameSchemaChange};
use frame::parser::parse_frame;
use compression::Compression;
use transport::CDRSTransport;
/// Full Server Event which includes all details about occured change.
pub type ServerEvent = FrameServerEvent;
/// Simplified Server event. It should be used to represent an event
/// which consumer wants listen to.
pub type SimpleServerEvent = FrameSimpleServerEvent;
/// Reexport of `FrameSchemaChange`.
pub type SchemaChange = FrameSchemaChange;
/// Factory function which returns a `Listener` and related `EventStream.`
///
/// `Listener` provides only one function `start` to start listening. It
/// blocks a thread so should be moved into a separate one to no release
/// main thread.
///
/// `EventStream` is an iterator which returns new events once they come.
/// It is similar to `Receiver::iter`.
pub fn new_listener<X>(transport: X) -> (Listener<X>, EventStream) {
let (tx, rx) = channel();
let listener = Listener {
transport: transport,
tx: tx,
};
let stream = EventStream { rx: rx };
(listener, stream)
}
/// `Listener` provides only one function `start` to start listening. It
/// blocks a thread so should be moved into a separate one to no release
/// main thread.
pub struct | <X> {
transport: X,
tx: Sender<ServerEvent>,
}
impl<X: CDRSTransport> Listener<X> {
/// It starts a process of listening to new events. Locks a frame.
pub fn start(&mut self, compressor: &Compression) -> error::Result<()> {
loop {
let event_opt = try!(parse_frame(&mut self.transport, compressor))
.get_body()?
.into_server_event();
let event = if event_opt.is_some() {
// unwrap is safe is we've checked that event_opt.is_some()
event_opt.unwrap().event as ServerEvent
} else {
continue;
};
match self.tx.send(event) {
Err(err) => return Err(error::Error::General(err.description().to_string())),
_ => continue,
}
}
}
}
/// `EventStream` is an iterator which returns new events once they come.
/// It is similar to `Receiver::iter`.
pub struct EventStream {
rx: Receiver<ServerEvent>,
}
impl Iterator for EventStream {
type Item = ServerEvent;
fn next(&mut self) -> Option<Self::Item> {
self.rx.recv().ok()
}
}
| Listener | identifier_name |
sample.rs | use std::collections::HashMap; | /// total number of events.
pub struct Sample<T> {
pub counts: HashMap<T,usize>,
pub total: usize,
}
impl<T: Eq + Hash> Sample<T> {
/// Creates a new Sample.
pub fn new() -> Sample<T> {
Sample {
counts: HashMap::new(),
total: 0,
}
}
/// Add an event to a sample.
pub fn add(&mut self, event: T) {
let count = self.counts.entry(event).or_insert(0);
*count += 1;
self.total += 1;
}
/// The probability of an event in a sample.
pub fn p(&self, event: &T) -> f64 {
let c = *self.counts.get(event).unwrap_or(&0);
(c as f64) / (self.total as f64)
}
}
// ---------------------------
impl<T: Eq + Hash> Extend<T> for Sample<T> {
fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) {
for k in iter { self.add(k); }
}
}
impl<T: Eq + Hash> FromIterator<T> for Sample<T> {
fn from_iter<I: IntoIterator<Item=T>>(iterable: I) -> Sample<T> {
let mut sample = Sample::new();
sample.extend( iterable.into_iter() );
sample
}
} | use std::hash::Hash;
use std::iter::FromIterator;
/// A collection of events, with a running total of counts for each event and | random_line_split |
sample.rs | use std::collections::HashMap;
use std::hash::Hash;
use std::iter::FromIterator;
/// A collection of events, with a running total of counts for each event and
/// total number of events.
pub struct Sample<T> {
pub counts: HashMap<T,usize>,
pub total: usize,
}
impl<T: Eq + Hash> Sample<T> {
/// Creates a new Sample.
pub fn new() -> Sample<T> {
Sample {
counts: HashMap::new(),
total: 0,
}
}
/// Add an event to a sample.
pub fn add(&mut self, event: T) {
let count = self.counts.entry(event).or_insert(0);
*count += 1;
self.total += 1;
}
/// The probability of an event in a sample.
pub fn | (&self, event: &T) -> f64 {
let c = *self.counts.get(event).unwrap_or(&0);
(c as f64) / (self.total as f64)
}
}
// ---------------------------
impl<T: Eq + Hash> Extend<T> for Sample<T> {
fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) {
for k in iter { self.add(k); }
}
}
impl<T: Eq + Hash> FromIterator<T> for Sample<T> {
fn from_iter<I: IntoIterator<Item=T>>(iterable: I) -> Sample<T> {
let mut sample = Sample::new();
sample.extend( iterable.into_iter() );
sample
}
}
| p | identifier_name |
htmlhrelement.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 cssparser::RGBA;
use dom::bindings::codegen::Bindings::HTMLHRElementBinding::{self, HTMLHRElementMethods};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{Element, RawLayoutElementHelpers};
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever_atoms::LocalName;
use style::attr::{AttrValue, LengthOrPercentageOrAuto};
#[dom_struct]
pub struct HTMLHRElement {
htmlelement: HTMLElement,
}
impl HTMLHRElement {
fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLHRElement {
HTMLHRElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLHRElement> {
Node::reflect_node(box HTMLHRElement::new_inherited(local_name, prefix, document),
document,
HTMLHRElementBinding::Wrap)
}
}
impl HTMLHRElementMethods for HTMLHRElement {
// https://html.spec.whatwg.org/multipage/#dom-hr-align
make_getter!(Align, "align");
// https://html.spec.whatwg.org/multipage/#dom-hr-align
make_atomic_setter!(SetAlign, "align");
// https://html.spec.whatwg.org/multipage/#dom-hr-color
make_getter!(Color, "color");
// https://html.spec.whatwg.org/multipage/#dom-hr-color
make_legacy_color_setter!(SetColor, "color");
// https://html.spec.whatwg.org/multipage/#dom-hr-width
make_getter!(Width, "width");
// https://html.spec.whatwg.org/multipage/#dom-hr-width
make_dimension_setter!(SetWidth, "width");
}
pub trait HTMLHRLayoutHelpers {
fn get_color(&self) -> Option<RGBA>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
}
impl HTMLHRLayoutHelpers for LayoutJS<HTMLHRElement> {
#[allow(unsafe_code)]
fn get_color(&self) -> Option<RGBA> {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("color"))
.and_then(AttrValue::as_color)
.cloned()
}
}
#[allow(unsafe_code)]
fn get_width(&self) -> LengthOrPercentageOrAuto {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("width"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthOrPercentageOrAuto::Auto)
}
}
}
impl VirtualMethods for HTMLHRElement {
fn | (&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("align") => AttrValue::from_dimension(value.into()),
&local_name!("color") => AttrValue::from_legacy_color(value.into()),
&local_name!("width") => AttrValue::from_dimension(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
| super_type | identifier_name |
htmlhrelement.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 cssparser::RGBA;
use dom::bindings::codegen::Bindings::HTMLHRElementBinding::{self, HTMLHRElementMethods};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{Element, RawLayoutElementHelpers};
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever_atoms::LocalName;
use style::attr::{AttrValue, LengthOrPercentageOrAuto};
#[dom_struct]
pub struct HTMLHRElement {
htmlelement: HTMLElement,
}
impl HTMLHRElement {
fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLHRElement {
HTMLHRElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLHRElement> {
Node::reflect_node(box HTMLHRElement::new_inherited(local_name, prefix, document),
document,
HTMLHRElementBinding::Wrap)
}
}
| impl HTMLHRElementMethods for HTMLHRElement {
// https://html.spec.whatwg.org/multipage/#dom-hr-align
make_getter!(Align, "align");
// https://html.spec.whatwg.org/multipage/#dom-hr-align
make_atomic_setter!(SetAlign, "align");
// https://html.spec.whatwg.org/multipage/#dom-hr-color
make_getter!(Color, "color");
// https://html.spec.whatwg.org/multipage/#dom-hr-color
make_legacy_color_setter!(SetColor, "color");
// https://html.spec.whatwg.org/multipage/#dom-hr-width
make_getter!(Width, "width");
// https://html.spec.whatwg.org/multipage/#dom-hr-width
make_dimension_setter!(SetWidth, "width");
}
pub trait HTMLHRLayoutHelpers {
fn get_color(&self) -> Option<RGBA>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
}
impl HTMLHRLayoutHelpers for LayoutJS<HTMLHRElement> {
#[allow(unsafe_code)]
fn get_color(&self) -> Option<RGBA> {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("color"))
.and_then(AttrValue::as_color)
.cloned()
}
}
#[allow(unsafe_code)]
fn get_width(&self) -> LengthOrPercentageOrAuto {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("width"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthOrPercentageOrAuto::Auto)
}
}
}
impl VirtualMethods for HTMLHRElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("align") => AttrValue::from_dimension(value.into()),
&local_name!("color") => AttrValue::from_legacy_color(value.into()),
&local_name!("width") => AttrValue::from_dimension(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
} | random_line_split |
|
sig.rs | use std::collections::HashMap; |
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use crypto::sha1::Sha1;
use super::util;
fn transform_payload<K, V>(d: &HashMap<K, V>) -> String
where K: AsRef<str> + Eq + Hash,
V: AsRef<str> + Eq + Hash
{
let mut kv_list: Vec<_> = d.iter().map(|(k, v)| (k.as_ref(), v.as_ref())).collect();
kv_list.sort_by(|a, b| a.0.cmp(b.0));
let mut result = String::new();
for (i, (k, v)) in kv_list.into_iter().enumerate() {
if i > 0 {
result.push('&');
}
result.push_str(k);
result.push('=');
result.push_str(v);
}
result
}
pub fn sign<K, V, S>(d: &HashMap<K, V>, secret: S) -> String
where K: AsRef<str> + Eq + Hash,
V: AsRef<str> + Eq + Hash,
S: AsRef<str>
{
let payload = transform_payload(d);
let mut hmac = Hmac::new(Sha1::new(), secret.as_ref().as_bytes());
hmac.input(payload.as_bytes());
util::b64encode(hmac.result().code())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_transform_payload() {
let x = {
let mut tmp: HashMap<&str, String> = HashMap::new();
tmp.insert("k2", "v2".to_string());
tmp.insert("k3", "v3".to_string());
tmp.insert("k1", "v1".to_string());
tmp
};
assert_eq!(transform_payload(&x), "k1=v1&k2=v2&k3=v3");
}
#[test]
fn test_sign() {
let x = {
let mut tmp: HashMap<&str, String> = HashMap::new();
tmp.insert("k2", "v2".to_string());
tmp.insert("k3", "v3".to_string());
tmp.insert("k1", "v1".to_string());
tmp
};
assert_eq!(sign(&x, "012345"), "iAKpGb9i8EKY8q4HPfiMdfb27OM=");
}
} | use std::hash::Hash; | random_line_split |
sig.rs | use std::collections::HashMap;
use std::hash::Hash;
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use crypto::sha1::Sha1;
use super::util;
fn transform_payload<K, V>(d: &HashMap<K, V>) -> String
where K: AsRef<str> + Eq + Hash,
V: AsRef<str> + Eq + Hash
{
let mut kv_list: Vec<_> = d.iter().map(|(k, v)| (k.as_ref(), v.as_ref())).collect();
kv_list.sort_by(|a, b| a.0.cmp(b.0));
let mut result = String::new();
for (i, (k, v)) in kv_list.into_iter().enumerate() {
if i > 0 {
result.push('&');
}
result.push_str(k);
result.push('=');
result.push_str(v);
}
result
}
pub fn | <K, V, S>(d: &HashMap<K, V>, secret: S) -> String
where K: AsRef<str> + Eq + Hash,
V: AsRef<str> + Eq + Hash,
S: AsRef<str>
{
let payload = transform_payload(d);
let mut hmac = Hmac::new(Sha1::new(), secret.as_ref().as_bytes());
hmac.input(payload.as_bytes());
util::b64encode(hmac.result().code())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_transform_payload() {
let x = {
let mut tmp: HashMap<&str, String> = HashMap::new();
tmp.insert("k2", "v2".to_string());
tmp.insert("k3", "v3".to_string());
tmp.insert("k1", "v1".to_string());
tmp
};
assert_eq!(transform_payload(&x), "k1=v1&k2=v2&k3=v3");
}
#[test]
fn test_sign() {
let x = {
let mut tmp: HashMap<&str, String> = HashMap::new();
tmp.insert("k2", "v2".to_string());
tmp.insert("k3", "v3".to_string());
tmp.insert("k1", "v1".to_string());
tmp
};
assert_eq!(sign(&x, "012345"), "iAKpGb9i8EKY8q4HPfiMdfb27OM=");
}
}
| sign | identifier_name |
sig.rs | use std::collections::HashMap;
use std::hash::Hash;
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use crypto::sha1::Sha1;
use super::util;
fn transform_payload<K, V>(d: &HashMap<K, V>) -> String
where K: AsRef<str> + Eq + Hash,
V: AsRef<str> + Eq + Hash
{
let mut kv_list: Vec<_> = d.iter().map(|(k, v)| (k.as_ref(), v.as_ref())).collect();
kv_list.sort_by(|a, b| a.0.cmp(b.0));
let mut result = String::new();
for (i, (k, v)) in kv_list.into_iter().enumerate() {
if i > 0 |
result.push_str(k);
result.push('=');
result.push_str(v);
}
result
}
pub fn sign<K, V, S>(d: &HashMap<K, V>, secret: S) -> String
where K: AsRef<str> + Eq + Hash,
V: AsRef<str> + Eq + Hash,
S: AsRef<str>
{
let payload = transform_payload(d);
let mut hmac = Hmac::new(Sha1::new(), secret.as_ref().as_bytes());
hmac.input(payload.as_bytes());
util::b64encode(hmac.result().code())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_transform_payload() {
let x = {
let mut tmp: HashMap<&str, String> = HashMap::new();
tmp.insert("k2", "v2".to_string());
tmp.insert("k3", "v3".to_string());
tmp.insert("k1", "v1".to_string());
tmp
};
assert_eq!(transform_payload(&x), "k1=v1&k2=v2&k3=v3");
}
#[test]
fn test_sign() {
let x = {
let mut tmp: HashMap<&str, String> = HashMap::new();
tmp.insert("k2", "v2".to_string());
tmp.insert("k3", "v3".to_string());
tmp.insert("k1", "v1".to_string());
tmp
};
assert_eq!(sign(&x, "012345"), "iAKpGb9i8EKY8q4HPfiMdfb27OM=");
}
}
| {
result.push('&');
} | conditional_block |
sig.rs | use std::collections::HashMap;
use std::hash::Hash;
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use crypto::sha1::Sha1;
use super::util;
fn transform_payload<K, V>(d: &HashMap<K, V>) -> String
where K: AsRef<str> + Eq + Hash,
V: AsRef<str> + Eq + Hash
{
let mut kv_list: Vec<_> = d.iter().map(|(k, v)| (k.as_ref(), v.as_ref())).collect();
kv_list.sort_by(|a, b| a.0.cmp(b.0));
let mut result = String::new();
for (i, (k, v)) in kv_list.into_iter().enumerate() {
if i > 0 {
result.push('&');
}
result.push_str(k);
result.push('=');
result.push_str(v);
}
result
}
pub fn sign<K, V, S>(d: &HashMap<K, V>, secret: S) -> String
where K: AsRef<str> + Eq + Hash,
V: AsRef<str> + Eq + Hash,
S: AsRef<str>
{
let payload = transform_payload(d);
let mut hmac = Hmac::new(Sha1::new(), secret.as_ref().as_bytes());
hmac.input(payload.as_bytes());
util::b64encode(hmac.result().code())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_transform_payload() {
let x = {
let mut tmp: HashMap<&str, String> = HashMap::new();
tmp.insert("k2", "v2".to_string());
tmp.insert("k3", "v3".to_string());
tmp.insert("k1", "v1".to_string());
tmp
};
assert_eq!(transform_payload(&x), "k1=v1&k2=v2&k3=v3");
}
#[test]
fn test_sign() |
}
| {
let x = {
let mut tmp: HashMap<&str, String> = HashMap::new();
tmp.insert("k2", "v2".to_string());
tmp.insert("k3", "v3".to_string());
tmp.insert("k1", "v1".to_string());
tmp
};
assert_eq!(sign(&x, "012345"), "iAKpGb9i8EKY8q4HPfiMdfb27OM=");
} | identifier_body |
zdt1.rs | /// ZDT1 bi-objective test function
///
/// Evaluates solution parameters using the ZDT1 [1] synthetic test
/// test function to produce two objective values.
///
/// [1 ]E. Zitzler, K. Deb, and L. Thiele. Comparison of Multiobjective
/// Evolutionary Algorithms: Empirical Results. Evolutionary
/// Computation, 8(2):173-195, 2000
pub fn | (parameters: [f32; 30]) -> [f32; 2] {
// objective function 1
let f1 = parameters[0];
// objective function 2
let mut g = 1_f32;
// g(x)
for i in 1..parameters.len() {
g = g + ((9_f32 / (parameters.len() as f32 - 1_f32)) * parameters[i]);
}
// h(f1, x)
let h = 1_f32 - (f1 / g).sqrt();
// f2(x)
let f2 = g * h;
return [f1, f2];
}
| zdt1 | identifier_name |
zdt1.rs | /// ZDT1 bi-objective test function
///
/// Evaluates solution parameters using the ZDT1 [1] synthetic test
/// test function to produce two objective values.
///
/// [1 ]E. Zitzler, K. Deb, and L. Thiele. Comparison of Multiobjective
/// Evolutionary Algorithms: Empirical Results. Evolutionary
/// Computation, 8(2):173-195, 2000
pub fn zdt1(parameters: [f32; 30]) -> [f32; 2] | {
// objective function 1
let f1 = parameters[0];
// objective function 2
let mut g = 1_f32;
// g(x)
for i in 1..parameters.len() {
g = g + ((9_f32 / (parameters.len() as f32 - 1_f32)) * parameters[i]);
}
// h(f1, x)
let h = 1_f32 - (f1 / g).sqrt();
// f2(x)
let f2 = g * h;
return [f1, f2];
} | identifier_body |
|
zdt1.rs | /// ZDT1 bi-objective test function
///
/// Evaluates solution parameters using the ZDT1 [1] synthetic test
/// test function to produce two objective values.
///
/// [1 ]E. Zitzler, K. Deb, and L. Thiele. Comparison of Multiobjective
/// Evolutionary Algorithms: Empirical Results. Evolutionary
/// Computation, 8(2):173-195, 2000 |
// objective function 1
let f1 = parameters[0];
// objective function 2
let mut g = 1_f32;
// g(x)
for i in 1..parameters.len() {
g = g + ((9_f32 / (parameters.len() as f32 - 1_f32)) * parameters[i]);
}
// h(f1, x)
let h = 1_f32 - (f1 / g).sqrt();
// f2(x)
let f2 = g * h;
return [f1, f2];
} | pub fn zdt1(parameters: [f32; 30]) -> [f32; 2] { | random_line_split |
revealer.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Hide and show with animation
use ffi;
use cast::{GTK_REVEALER};
use glib::{to_bool, to_gboolean};
/// GtkRevealer — Hide and show with animation
struct_Widget!(Revealer);
impl Revealer {
pub fn new() -> Option<Revealer> {
let tmp_pointer = unsafe { ffi::gtk_revealer_new() };
check_pointer!(tmp_pointer, Revealer)
}
pub fn get_reveal_child(&self) -> bool {
unsafe {
to_bool(ffi::gtk_revealer_get_reveal_child(GTK_REVEALER(self.pointer)))
}
}
pub fn set_reveal_child(&self, reveal_child: bool) {
unsafe {
ffi::gtk_revealer_set_reveal_child(GTK_REVEALER(self.pointer),
to_gboolean(reveal_child))
}
}
pub fn is_child_revealed(&self) -> bool {
| pub fn get_transition_duration(&self) -> u32 {
unsafe {
ffi::gtk_revealer_get_transition_duration(GTK_REVEALER(self.pointer))
}
}
pub fn set_transition_duration(&self, duration: u32) {
unsafe {
ffi::gtk_revealer_set_transition_duration(GTK_REVEALER(self.pointer), duration)
}
}
pub fn set_transition_type(&self, transition: ::RevealerTransitionType) {
unsafe {
ffi::gtk_revealer_set_transition_type(GTK_REVEALER(self.pointer), transition)
}
}
pub fn get_transition_type(&self) -> ::RevealerTransitionType {
unsafe {
ffi::gtk_revealer_get_transition_type(GTK_REVEALER(self.pointer))
}
}
}
impl_drop!(Revealer);
impl_TraitWidget!(Revealer);
impl ::ContainerTrait for Revealer {}
impl ::BinTrait for Revealer {}
| unsafe {
to_bool(ffi::gtk_revealer_get_child_revealed(GTK_REVEALER(self.pointer)))
}
}
| identifier_body |
revealer.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Hide and show with animation
use ffi;
use cast::{GTK_REVEALER};
use glib::{to_bool, to_gboolean};
/// GtkRevealer — Hide and show with animation
struct_Widget!(Revealer);
impl Revealer {
pub fn new() -> Option<Revealer> {
let tmp_pointer = unsafe { ffi::gtk_revealer_new() };
check_pointer!(tmp_pointer, Revealer)
}
pub fn get_reveal_child(&self) -> bool {
unsafe {
to_bool(ffi::gtk_revealer_get_reveal_child(GTK_REVEALER(self.pointer)))
}
}
pub fn set_reveal_child(&self, reveal_child: bool) {
unsafe {
ffi::gtk_revealer_set_reveal_child(GTK_REVEALER(self.pointer),
to_gboolean(reveal_child))
}
}
pub fn is_child_revealed(&self) -> bool {
unsafe {
to_bool(ffi::gtk_revealer_get_child_revealed(GTK_REVEALER(self.pointer)))
}
}
pub fn get_transition_duration(&self) -> u32 {
unsafe {
ffi::gtk_revealer_get_transition_duration(GTK_REVEALER(self.pointer))
}
}
pub fn set_transition_duration(&self, duration: u32) {
unsafe {
ffi::gtk_revealer_set_transition_duration(GTK_REVEALER(self.pointer), duration)
}
}
pub fn set_transition_type(&self, transition: ::RevealerTransitionType) {
unsafe {
ffi::gtk_revealer_set_transition_type(GTK_REVEALER(self.pointer), transition)
}
}
pub fn get_transition_type(&self) -> ::RevealerTransitionType {
unsafe {
ffi::gtk_revealer_get_transition_type(GTK_REVEALER(self.pointer))
}
}
} | impl ::ContainerTrait for Revealer {}
impl ::BinTrait for Revealer {} |
impl_drop!(Revealer);
impl_TraitWidget!(Revealer);
| random_line_split |
revealer.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Hide and show with animation
use ffi;
use cast::{GTK_REVEALER};
use glib::{to_bool, to_gboolean};
/// GtkRevealer — Hide and show with animation
struct_Widget!(Revealer);
impl Revealer {
pub fn new() -> Option<Revealer> {
let tmp_pointer = unsafe { ffi::gtk_revealer_new() };
check_pointer!(tmp_pointer, Revealer)
}
pub fn get_reveal_child(&self) -> bool {
unsafe {
to_bool(ffi::gtk_revealer_get_reveal_child(GTK_REVEALER(self.pointer)))
}
}
pub fn set_reveal_child(&self, reveal_child: bool) {
unsafe {
ffi::gtk_revealer_set_reveal_child(GTK_REVEALER(self.pointer),
to_gboolean(reveal_child))
}
}
pub fn is_child_revealed(&self) -> bool {
unsafe {
to_bool(ffi::gtk_revealer_get_child_revealed(GTK_REVEALER(self.pointer)))
}
}
pub fn get_transition_duration(&self) -> u32 {
unsafe {
ffi::gtk_revealer_get_transition_duration(GTK_REVEALER(self.pointer))
}
}
pub fn se | self, duration: u32) {
unsafe {
ffi::gtk_revealer_set_transition_duration(GTK_REVEALER(self.pointer), duration)
}
}
pub fn set_transition_type(&self, transition: ::RevealerTransitionType) {
unsafe {
ffi::gtk_revealer_set_transition_type(GTK_REVEALER(self.pointer), transition)
}
}
pub fn get_transition_type(&self) -> ::RevealerTransitionType {
unsafe {
ffi::gtk_revealer_get_transition_type(GTK_REVEALER(self.pointer))
}
}
}
impl_drop!(Revealer);
impl_TraitWidget!(Revealer);
impl ::ContainerTrait for Revealer {}
impl ::BinTrait for Revealer {}
| t_transition_duration(& | identifier_name |
regroup_gradient_stops.rs | // svgcleaner could help you to clean up your SVG files
// from unnecessary data.
// Copyright (C) 2012-2018 Evgeniy Reizner
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
use svgdom::{
Document,
ElementType,
Node,
};
use task::short::{EId, AId};
pub fn regroup_gradient_stops(doc: &mut Document) | if super::rm_dupl_defs::is_equal_stops(&node1, &node2) {
join_nodes.push(node2.clone());
nodes.remove(i2 - 1);
i2 -= 1;
}
}
if!join_nodes.is_empty() {
is_changed = true;
let mut new_lg = doc.create_element(EId::LinearGradient);
let new_id = gen_id(doc, "lg");
new_lg.set_id(new_id);
while node1.has_children() {
let mut c = node1.first_child().unwrap();
c.detach();
new_lg.append(&c);
}
node1.set_attribute((AId::XlinkHref, new_lg.clone()));
node1.insert_before(&new_lg);
for jn in &mut join_nodes {
while jn.has_children() {
let mut c = jn.first_child().unwrap();
c.remove();
}
jn.set_attribute((AId::XlinkHref, new_lg.clone()));
}
join_nodes.clear();
}
i1 += 1;
}
if is_changed {
// We must resolve attributes for gradients created above.
super::resolve_linear_gradient_attributes(doc);
}
}
fn gen_id(doc: &Document, prefix: &str) -> String {
let mut n = 1;
let mut s = String::new();
loop {
s.clear();
s.push_str(prefix);
s.push_str(&n.to_string());
// TODO: very slow
if!doc.descendants().any(|n| *n.id() == s) {
break;
}
n += 1;
}
s
}
#[cfg(test)]
mod tests {
use super::*;
use svgdom::{Document, ToStringWithOptions};
use task;
macro_rules! test {
($name:ident, $in_text:expr, $out_text:expr) => (
#[test]
fn $name() {
let mut doc = Document::from_str($in_text).unwrap();
task::resolve_linear_gradient_attributes(&doc);
task::resolve_radial_gradient_attributes(&doc);
task::resolve_stop_attributes(&doc).unwrap();
regroup_gradient_stops(&mut doc);
assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), $out_text);
}
)
}
test!(rm_1,
"<svg>
<linearGradient id='lg1' x1='50'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg2' x1='100'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
</svg>",
"<svg>
<linearGradient id='lg3'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg1' x1='50' xlink:href='#lg3'/>
<linearGradient id='lg2' x1='100' xlink:href='#lg3'/>
</svg>
");
test!(rm_2,
"<svg>
<linearGradient id='lg1' x1='50'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg3' x1='50'>
<stop offset='0.5'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg2' x1='100'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg4' x1='100'>
<stop offset='0.5'/>
<stop offset='1'/>
</linearGradient>
</svg>",
"<svg>
<linearGradient id='lg5'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg1' x1='50' xlink:href='#lg5'/>
<linearGradient id='lg6'>
<stop offset='0.5'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg3' x1='50' xlink:href='#lg6'/>
<linearGradient id='lg2' x1='100' xlink:href='#lg5'/>
<linearGradient id='lg4' x1='100' xlink:href='#lg6'/>
</svg>
");
}
| {
let mut nodes: Vec<Node> = doc.descendants()
.filter(|n| n.is_gradient())
.filter(|n| n.has_children())
.filter(|n| !n.has_attribute(AId::XlinkHref))
.collect();
let mut is_changed = false;
let mut join_nodes = Vec::new();
// TODO: join with rm_dupl_defs::rm_loop
let mut i1 = 0;
while i1 < nodes.len() {
let mut node1 = nodes[i1].clone();
let mut i2 = i1 + 1;
while i2 < nodes.len() {
let node2 = nodes[i2].clone();
i2 += 1;
| identifier_body |
regroup_gradient_stops.rs | // svgcleaner could help you to clean up your SVG files
// from unnecessary data.
// Copyright (C) 2012-2018 Evgeniy Reizner
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
use svgdom::{
Document,
ElementType,
Node,
};
use task::short::{EId, AId};
pub fn | (doc: &mut Document) {
let mut nodes: Vec<Node> = doc.descendants()
.filter(|n| n.is_gradient())
.filter(|n| n.has_children())
.filter(|n|!n.has_attribute(AId::XlinkHref))
.collect();
let mut is_changed = false;
let mut join_nodes = Vec::new();
// TODO: join with rm_dupl_defs::rm_loop
let mut i1 = 0;
while i1 < nodes.len() {
let mut node1 = nodes[i1].clone();
let mut i2 = i1 + 1;
while i2 < nodes.len() {
let node2 = nodes[i2].clone();
i2 += 1;
if super::rm_dupl_defs::is_equal_stops(&node1, &node2) {
join_nodes.push(node2.clone());
nodes.remove(i2 - 1);
i2 -= 1;
}
}
if!join_nodes.is_empty() {
is_changed = true;
let mut new_lg = doc.create_element(EId::LinearGradient);
let new_id = gen_id(doc, "lg");
new_lg.set_id(new_id);
while node1.has_children() {
let mut c = node1.first_child().unwrap();
c.detach();
new_lg.append(&c);
}
node1.set_attribute((AId::XlinkHref, new_lg.clone()));
node1.insert_before(&new_lg);
for jn in &mut join_nodes {
while jn.has_children() {
let mut c = jn.first_child().unwrap();
c.remove();
}
jn.set_attribute((AId::XlinkHref, new_lg.clone()));
}
join_nodes.clear();
}
i1 += 1;
}
if is_changed {
// We must resolve attributes for gradients created above.
super::resolve_linear_gradient_attributes(doc);
}
}
fn gen_id(doc: &Document, prefix: &str) -> String {
let mut n = 1;
let mut s = String::new();
loop {
s.clear();
s.push_str(prefix);
s.push_str(&n.to_string());
// TODO: very slow
if!doc.descendants().any(|n| *n.id() == s) {
break;
}
n += 1;
}
s
}
#[cfg(test)]
mod tests {
use super::*;
use svgdom::{Document, ToStringWithOptions};
use task;
macro_rules! test {
($name:ident, $in_text:expr, $out_text:expr) => (
#[test]
fn $name() {
let mut doc = Document::from_str($in_text).unwrap();
task::resolve_linear_gradient_attributes(&doc);
task::resolve_radial_gradient_attributes(&doc);
task::resolve_stop_attributes(&doc).unwrap();
regroup_gradient_stops(&mut doc);
assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), $out_text);
}
)
}
test!(rm_1,
"<svg>
<linearGradient id='lg1' x1='50'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg2' x1='100'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
</svg>",
"<svg>
<linearGradient id='lg3'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg1' x1='50' xlink:href='#lg3'/>
<linearGradient id='lg2' x1='100' xlink:href='#lg3'/>
</svg>
");
test!(rm_2,
"<svg>
<linearGradient id='lg1' x1='50'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg3' x1='50'>
<stop offset='0.5'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg2' x1='100'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg4' x1='100'>
<stop offset='0.5'/>
<stop offset='1'/>
</linearGradient>
</svg>",
"<svg>
<linearGradient id='lg5'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg1' x1='50' xlink:href='#lg5'/>
<linearGradient id='lg6'>
<stop offset='0.5'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg3' x1='50' xlink:href='#lg6'/>
<linearGradient id='lg2' x1='100' xlink:href='#lg5'/>
<linearGradient id='lg4' x1='100' xlink:href='#lg6'/>
</svg>
");
}
| regroup_gradient_stops | identifier_name |
regroup_gradient_stops.rs | // svgcleaner could help you to clean up your SVG files
// from unnecessary data.
// Copyright (C) 2012-2018 Evgeniy Reizner
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
use svgdom::{
Document,
ElementType,
Node,
};
use task::short::{EId, AId};
pub fn regroup_gradient_stops(doc: &mut Document) {
let mut nodes: Vec<Node> = doc.descendants()
.filter(|n| n.is_gradient())
.filter(|n| n.has_children())
.filter(|n|!n.has_attribute(AId::XlinkHref))
.collect();
let mut is_changed = false;
let mut join_nodes = Vec::new();
// TODO: join with rm_dupl_defs::rm_loop
let mut i1 = 0;
while i1 < nodes.len() {
let mut node1 = nodes[i1].clone();
let mut i2 = i1 + 1;
while i2 < nodes.len() {
let node2 = nodes[i2].clone();
i2 += 1;
if super::rm_dupl_defs::is_equal_stops(&node1, &node2) {
join_nodes.push(node2.clone());
nodes.remove(i2 - 1);
i2 -= 1;
}
}
if!join_nodes.is_empty() {
is_changed = true;
let mut new_lg = doc.create_element(EId::LinearGradient);
let new_id = gen_id(doc, "lg");
new_lg.set_id(new_id);
while node1.has_children() {
let mut c = node1.first_child().unwrap();
c.detach();
new_lg.append(&c);
}
node1.set_attribute((AId::XlinkHref, new_lg.clone()));
node1.insert_before(&new_lg);
for jn in &mut join_nodes {
while jn.has_children() {
let mut c = jn.first_child().unwrap();
c.remove();
}
jn.set_attribute((AId::XlinkHref, new_lg.clone()));
}
join_nodes.clear();
}
i1 += 1;
}
if is_changed {
// We must resolve attributes for gradients created above.
super::resolve_linear_gradient_attributes(doc);
}
}
fn gen_id(doc: &Document, prefix: &str) -> String {
let mut n = 1;
let mut s = String::new();
loop {
s.clear();
s.push_str(prefix);
s.push_str(&n.to_string());
// TODO: very slow
if!doc.descendants().any(|n| *n.id() == s) |
n += 1;
}
s
}
#[cfg(test)]
mod tests {
use super::*;
use svgdom::{Document, ToStringWithOptions};
use task;
macro_rules! test {
($name:ident, $in_text:expr, $out_text:expr) => (
#[test]
fn $name() {
let mut doc = Document::from_str($in_text).unwrap();
task::resolve_linear_gradient_attributes(&doc);
task::resolve_radial_gradient_attributes(&doc);
task::resolve_stop_attributes(&doc).unwrap();
regroup_gradient_stops(&mut doc);
assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), $out_text);
}
)
}
test!(rm_1,
"<svg>
<linearGradient id='lg1' x1='50'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg2' x1='100'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
</svg>",
"<svg>
<linearGradient id='lg3'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg1' x1='50' xlink:href='#lg3'/>
<linearGradient id='lg2' x1='100' xlink:href='#lg3'/>
</svg>
");
test!(rm_2,
"<svg>
<linearGradient id='lg1' x1='50'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg3' x1='50'>
<stop offset='0.5'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg2' x1='100'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg4' x1='100'>
<stop offset='0.5'/>
<stop offset='1'/>
</linearGradient>
</svg>",
"<svg>
<linearGradient id='lg5'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg1' x1='50' xlink:href='#lg5'/>
<linearGradient id='lg6'>
<stop offset='0.5'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg3' x1='50' xlink:href='#lg6'/>
<linearGradient id='lg2' x1='100' xlink:href='#lg5'/>
<linearGradient id='lg4' x1='100' xlink:href='#lg6'/>
</svg>
");
}
| {
break;
} | conditional_block |
regroup_gradient_stops.rs | // svgcleaner could help you to clean up your SVG files
// from unnecessary data.
// Copyright (C) 2012-2018 Evgeniy Reizner
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
use svgdom::{
Document,
ElementType,
Node,
};
use task::short::{EId, AId};
pub fn regroup_gradient_stops(doc: &mut Document) {
let mut nodes: Vec<Node> = doc.descendants()
.filter(|n| n.is_gradient())
.filter(|n| n.has_children())
.filter(|n|!n.has_attribute(AId::XlinkHref))
.collect();
let mut is_changed = false;
let mut join_nodes = Vec::new();
// TODO: join with rm_dupl_defs::rm_loop
let mut i1 = 0;
while i1 < nodes.len() {
let mut node1 = nodes[i1].clone();
let mut i2 = i1 + 1;
while i2 < nodes.len() {
let node2 = nodes[i2].clone();
i2 += 1;
if super::rm_dupl_defs::is_equal_stops(&node1, &node2) {
join_nodes.push(node2.clone());
nodes.remove(i2 - 1);
i2 -= 1;
}
}
if!join_nodes.is_empty() {
is_changed = true;
let mut new_lg = doc.create_element(EId::LinearGradient);
let new_id = gen_id(doc, "lg");
new_lg.set_id(new_id);
while node1.has_children() {
let mut c = node1.first_child().unwrap();
c.detach();
new_lg.append(&c);
}
node1.set_attribute((AId::XlinkHref, new_lg.clone()));
node1.insert_before(&new_lg);
for jn in &mut join_nodes {
while jn.has_children() {
let mut c = jn.first_child().unwrap();
c.remove();
}
jn.set_attribute((AId::XlinkHref, new_lg.clone()));
}
join_nodes.clear();
}
i1 += 1;
}
if is_changed {
// We must resolve attributes for gradients created above.
super::resolve_linear_gradient_attributes(doc);
}
}
fn gen_id(doc: &Document, prefix: &str) -> String {
let mut n = 1;
let mut s = String::new();
loop {
s.clear();
s.push_str(prefix);
s.push_str(&n.to_string());
// TODO: very slow
if!doc.descendants().any(|n| *n.id() == s) {
break;
}
n += 1;
}
s
}
#[cfg(test)]
mod tests {
use super::*;
use svgdom::{Document, ToStringWithOptions};
use task;
macro_rules! test {
($name:ident, $in_text:expr, $out_text:expr) => (
#[test]
fn $name() {
let mut doc = Document::from_str($in_text).unwrap();
task::resolve_linear_gradient_attributes(&doc);
task::resolve_radial_gradient_attributes(&doc);
task::resolve_stop_attributes(&doc).unwrap(); | )
}
test!(rm_1,
"<svg>
<linearGradient id='lg1' x1='50'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg2' x1='100'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
</svg>",
"<svg>
<linearGradient id='lg3'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg1' x1='50' xlink:href='#lg3'/>
<linearGradient id='lg2' x1='100' xlink:href='#lg3'/>
</svg>
");
test!(rm_2,
"<svg>
<linearGradient id='lg1' x1='50'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg3' x1='50'>
<stop offset='0.5'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg2' x1='100'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg4' x1='100'>
<stop offset='0.5'/>
<stop offset='1'/>
</linearGradient>
</svg>",
"<svg>
<linearGradient id='lg5'>
<stop offset='0'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg1' x1='50' xlink:href='#lg5'/>
<linearGradient id='lg6'>
<stop offset='0.5'/>
<stop offset='1'/>
</linearGradient>
<linearGradient id='lg3' x1='50' xlink:href='#lg6'/>
<linearGradient id='lg2' x1='100' xlink:href='#lg5'/>
<linearGradient id='lg4' x1='100' xlink:href='#lg6'/>
</svg>
");
} | regroup_gradient_stops(&mut doc);
assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), $out_text);
} | random_line_split |
document_loader.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/. */
//! Tracking of pending loads in a document.
//! https://html.spec.whatwg.org/multipage/#the-end
use dom::bindings::js::JS;
use dom::document::Document;
use ipc_channel::ipc::IpcSender;
use net_traits::{CoreResourceMsg, FetchResponseMsg, ResourceThreads, IpcSend};
use net_traits::request::RequestInit;
use std::thread;
use url::Url;
#[derive(JSTraceable, PartialEq, Clone, Debug, HeapSizeOf)]
pub enum LoadType {
Image(Url),
Script(Url),
Subframe(Url),
Stylesheet(Url),
PageSource(Url),
Media(Url),
}
impl LoadType {
fn url(&self) -> &Url {
match *self {
LoadType::Image(ref url) |
LoadType::Script(ref url) |
LoadType::Subframe(ref url) |
LoadType::Stylesheet(ref url) |
LoadType::Media(ref url) |
LoadType::PageSource(ref url) => url,
}
}
}
/// Canary value ensuring that manually added blocking loads (ie. ones that weren't
/// created via DocumentLoader::fetch_async) are always removed by the time
/// that the owner is destroyed.
#[derive(JSTraceable, HeapSizeOf)]
#[must_root]
pub struct LoadBlocker {
/// The document whose load event is blocked by this object existing.
doc: JS<Document>,
/// The load that is blocking the document's load event.
load: Option<LoadType>,
}
impl LoadBlocker {
/// Mark the document's load event as blocked on this new load.
pub fn new(doc: &Document, load: LoadType) -> LoadBlocker {
doc.mut_loader().add_blocking_load(load.clone());
LoadBlocker {
doc: JS::from_ref(doc),
load: Some(load),
}
}
/// Remove this load from the associated document's list of blocking loads.
pub fn terminate(blocker: &mut Option<LoadBlocker>) {
if let Some(this) = blocker.as_mut() {
this.doc.finish_load(this.load.take().unwrap());
}
*blocker = None;
}
/// Return the url associated with this load.
pub fn url(&self) -> Option<&Url> {
self.load.as_ref().map(LoadType::url)
}
}
impl Drop for LoadBlocker {
fn drop(&mut self) {
if!thread::panicking() {
debug_assert!(self.load.is_none());
}
}
}
#[derive(JSTraceable, HeapSizeOf)]
pub struct DocumentLoader {
resource_threads: ResourceThreads,
blocking_loads: Vec<LoadType>,
events_inhibited: bool,
}
impl DocumentLoader {
pub fn new(existing: &DocumentLoader) -> DocumentLoader {
DocumentLoader::new_with_threads(existing.resource_threads.clone(), None)
}
pub fn new_with_threads(resource_threads: ResourceThreads,
initial_load: Option<Url>) -> DocumentLoader |
/// Add a load to the list of blocking loads.
fn add_blocking_load(&mut self, load: LoadType) {
debug!("Adding blocking load {:?} ({}).", load, self.blocking_loads.len());
self.blocking_loads.push(load);
}
/// Initiate a new fetch.
pub fn fetch_async(&mut self,
load: LoadType,
request: RequestInit,
fetch_target: IpcSender<FetchResponseMsg>) {
self.add_blocking_load(load);
self.resource_threads.sender().send(CoreResourceMsg::Fetch(request, fetch_target)).unwrap();
}
/// Mark an in-progress network request complete.
pub fn finish_load(&mut self, load: &LoadType) {
debug!("Removing blocking load {:?} ({}).", load, self.blocking_loads.len());
let idx = self.blocking_loads.iter().position(|unfinished| *unfinished == *load);
self.blocking_loads.remove(idx.expect(&format!("unknown completed load {:?}", load)));
}
pub fn is_blocked(&self) -> bool {
// TODO: Ensure that we report blocked if parsing is still ongoing.
!self.blocking_loads.is_empty()
}
pub fn inhibit_events(&mut self) {
self.events_inhibited = true;
}
pub fn events_inhibited(&self) -> bool {
self.events_inhibited
}
pub fn resource_threads(&self) -> &ResourceThreads {
&self.resource_threads
}
}
| {
debug!("Initial blocking load {:?}.", initial_load);
let initial_loads = initial_load.into_iter().map(LoadType::PageSource).collect();
DocumentLoader {
resource_threads: resource_threads,
blocking_loads: initial_loads,
events_inhibited: false,
}
} | identifier_body |
document_loader.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/. */
//! Tracking of pending loads in a document.
//! https://html.spec.whatwg.org/multipage/#the-end
use dom::bindings::js::JS;
use dom::document::Document;
use ipc_channel::ipc::IpcSender;
use net_traits::{CoreResourceMsg, FetchResponseMsg, ResourceThreads, IpcSend};
use net_traits::request::RequestInit;
use std::thread;
use url::Url;
#[derive(JSTraceable, PartialEq, Clone, Debug, HeapSizeOf)]
pub enum LoadType {
Image(Url),
Script(Url),
Subframe(Url),
Stylesheet(Url),
PageSource(Url),
Media(Url),
}
impl LoadType {
fn url(&self) -> &Url {
match *self {
LoadType::Image(ref url) |
LoadType::Script(ref url) |
LoadType::Subframe(ref url) |
LoadType::Stylesheet(ref url) |
LoadType::Media(ref url) |
LoadType::PageSource(ref url) => url,
}
}
}
/// Canary value ensuring that manually added blocking loads (ie. ones that weren't
/// created via DocumentLoader::fetch_async) are always removed by the time
/// that the owner is destroyed.
#[derive(JSTraceable, HeapSizeOf)]
#[must_root]
pub struct LoadBlocker {
/// The document whose load event is blocked by this object existing.
doc: JS<Document>,
/// The load that is blocking the document's load event.
load: Option<LoadType>,
}
impl LoadBlocker {
/// Mark the document's load event as blocked on this new load.
pub fn new(doc: &Document, load: LoadType) -> LoadBlocker {
doc.mut_loader().add_blocking_load(load.clone());
LoadBlocker {
doc: JS::from_ref(doc),
load: Some(load),
}
}
/// Remove this load from the associated document's list of blocking loads.
pub fn terminate(blocker: &mut Option<LoadBlocker>) {
if let Some(this) = blocker.as_mut() {
this.doc.finish_load(this.load.take().unwrap());
}
*blocker = None;
}
/// Return the url associated with this load.
pub fn url(&self) -> Option<&Url> {
self.load.as_ref().map(LoadType::url)
}
}
impl Drop for LoadBlocker {
fn drop(&mut self) {
if!thread::panicking() |
}
}
#[derive(JSTraceable, HeapSizeOf)]
pub struct DocumentLoader {
resource_threads: ResourceThreads,
blocking_loads: Vec<LoadType>,
events_inhibited: bool,
}
impl DocumentLoader {
pub fn new(existing: &DocumentLoader) -> DocumentLoader {
DocumentLoader::new_with_threads(existing.resource_threads.clone(), None)
}
pub fn new_with_threads(resource_threads: ResourceThreads,
initial_load: Option<Url>) -> DocumentLoader {
debug!("Initial blocking load {:?}.", initial_load);
let initial_loads = initial_load.into_iter().map(LoadType::PageSource).collect();
DocumentLoader {
resource_threads: resource_threads,
blocking_loads: initial_loads,
events_inhibited: false,
}
}
/// Add a load to the list of blocking loads.
fn add_blocking_load(&mut self, load: LoadType) {
debug!("Adding blocking load {:?} ({}).", load, self.blocking_loads.len());
self.blocking_loads.push(load);
}
/// Initiate a new fetch.
pub fn fetch_async(&mut self,
load: LoadType,
request: RequestInit,
fetch_target: IpcSender<FetchResponseMsg>) {
self.add_blocking_load(load);
self.resource_threads.sender().send(CoreResourceMsg::Fetch(request, fetch_target)).unwrap();
}
/// Mark an in-progress network request complete.
pub fn finish_load(&mut self, load: &LoadType) {
debug!("Removing blocking load {:?} ({}).", load, self.blocking_loads.len());
let idx = self.blocking_loads.iter().position(|unfinished| *unfinished == *load);
self.blocking_loads.remove(idx.expect(&format!("unknown completed load {:?}", load)));
}
pub fn is_blocked(&self) -> bool {
// TODO: Ensure that we report blocked if parsing is still ongoing.
!self.blocking_loads.is_empty()
}
pub fn inhibit_events(&mut self) {
self.events_inhibited = true;
}
pub fn events_inhibited(&self) -> bool {
self.events_inhibited
}
pub fn resource_threads(&self) -> &ResourceThreads {
&self.resource_threads
}
}
| {
debug_assert!(self.load.is_none());
} | conditional_block |
document_loader.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/. */
//! Tracking of pending loads in a document.
//! https://html.spec.whatwg.org/multipage/#the-end
use dom::bindings::js::JS;
use dom::document::Document;
use ipc_channel::ipc::IpcSender;
use net_traits::{CoreResourceMsg, FetchResponseMsg, ResourceThreads, IpcSend};
use net_traits::request::RequestInit;
use std::thread;
use url::Url;
#[derive(JSTraceable, PartialEq, Clone, Debug, HeapSizeOf)]
pub enum LoadType {
Image(Url),
Script(Url),
Subframe(Url),
Stylesheet(Url),
PageSource(Url),
Media(Url),
}
impl LoadType {
fn url(&self) -> &Url {
match *self {
LoadType::Image(ref url) |
LoadType::Script(ref url) |
LoadType::Subframe(ref url) |
LoadType::Stylesheet(ref url) |
LoadType::Media(ref url) |
LoadType::PageSource(ref url) => url,
}
}
}
/// Canary value ensuring that manually added blocking loads (ie. ones that weren't
/// created via DocumentLoader::fetch_async) are always removed by the time
/// that the owner is destroyed.
#[derive(JSTraceable, HeapSizeOf)]
#[must_root]
pub struct LoadBlocker {
/// The document whose load event is blocked by this object existing.
doc: JS<Document>,
/// The load that is blocking the document's load event.
load: Option<LoadType>,
}
impl LoadBlocker {
/// Mark the document's load event as blocked on this new load. | doc: JS::from_ref(doc),
load: Some(load),
}
}
/// Remove this load from the associated document's list of blocking loads.
pub fn terminate(blocker: &mut Option<LoadBlocker>) {
if let Some(this) = blocker.as_mut() {
this.doc.finish_load(this.load.take().unwrap());
}
*blocker = None;
}
/// Return the url associated with this load.
pub fn url(&self) -> Option<&Url> {
self.load.as_ref().map(LoadType::url)
}
}
impl Drop for LoadBlocker {
fn drop(&mut self) {
if!thread::panicking() {
debug_assert!(self.load.is_none());
}
}
}
#[derive(JSTraceable, HeapSizeOf)]
pub struct DocumentLoader {
resource_threads: ResourceThreads,
blocking_loads: Vec<LoadType>,
events_inhibited: bool,
}
impl DocumentLoader {
pub fn new(existing: &DocumentLoader) -> DocumentLoader {
DocumentLoader::new_with_threads(existing.resource_threads.clone(), None)
}
pub fn new_with_threads(resource_threads: ResourceThreads,
initial_load: Option<Url>) -> DocumentLoader {
debug!("Initial blocking load {:?}.", initial_load);
let initial_loads = initial_load.into_iter().map(LoadType::PageSource).collect();
DocumentLoader {
resource_threads: resource_threads,
blocking_loads: initial_loads,
events_inhibited: false,
}
}
/// Add a load to the list of blocking loads.
fn add_blocking_load(&mut self, load: LoadType) {
debug!("Adding blocking load {:?} ({}).", load, self.blocking_loads.len());
self.blocking_loads.push(load);
}
/// Initiate a new fetch.
pub fn fetch_async(&mut self,
load: LoadType,
request: RequestInit,
fetch_target: IpcSender<FetchResponseMsg>) {
self.add_blocking_load(load);
self.resource_threads.sender().send(CoreResourceMsg::Fetch(request, fetch_target)).unwrap();
}
/// Mark an in-progress network request complete.
pub fn finish_load(&mut self, load: &LoadType) {
debug!("Removing blocking load {:?} ({}).", load, self.blocking_loads.len());
let idx = self.blocking_loads.iter().position(|unfinished| *unfinished == *load);
self.blocking_loads.remove(idx.expect(&format!("unknown completed load {:?}", load)));
}
pub fn is_blocked(&self) -> bool {
// TODO: Ensure that we report blocked if parsing is still ongoing.
!self.blocking_loads.is_empty()
}
pub fn inhibit_events(&mut self) {
self.events_inhibited = true;
}
pub fn events_inhibited(&self) -> bool {
self.events_inhibited
}
pub fn resource_threads(&self) -> &ResourceThreads {
&self.resource_threads
}
} | pub fn new(doc: &Document, load: LoadType) -> LoadBlocker {
doc.mut_loader().add_blocking_load(load.clone());
LoadBlocker { | random_line_split |
document_loader.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/. */
//! Tracking of pending loads in a document.
//! https://html.spec.whatwg.org/multipage/#the-end
use dom::bindings::js::JS;
use dom::document::Document;
use ipc_channel::ipc::IpcSender;
use net_traits::{CoreResourceMsg, FetchResponseMsg, ResourceThreads, IpcSend};
use net_traits::request::RequestInit;
use std::thread;
use url::Url;
#[derive(JSTraceable, PartialEq, Clone, Debug, HeapSizeOf)]
pub enum LoadType {
Image(Url),
Script(Url),
Subframe(Url),
Stylesheet(Url),
PageSource(Url),
Media(Url),
}
impl LoadType {
fn url(&self) -> &Url {
match *self {
LoadType::Image(ref url) |
LoadType::Script(ref url) |
LoadType::Subframe(ref url) |
LoadType::Stylesheet(ref url) |
LoadType::Media(ref url) |
LoadType::PageSource(ref url) => url,
}
}
}
/// Canary value ensuring that manually added blocking loads (ie. ones that weren't
/// created via DocumentLoader::fetch_async) are always removed by the time
/// that the owner is destroyed.
#[derive(JSTraceable, HeapSizeOf)]
#[must_root]
pub struct LoadBlocker {
/// The document whose load event is blocked by this object existing.
doc: JS<Document>,
/// The load that is blocking the document's load event.
load: Option<LoadType>,
}
impl LoadBlocker {
/// Mark the document's load event as blocked on this new load.
pub fn new(doc: &Document, load: LoadType) -> LoadBlocker {
doc.mut_loader().add_blocking_load(load.clone());
LoadBlocker {
doc: JS::from_ref(doc),
load: Some(load),
}
}
/// Remove this load from the associated document's list of blocking loads.
pub fn terminate(blocker: &mut Option<LoadBlocker>) {
if let Some(this) = blocker.as_mut() {
this.doc.finish_load(this.load.take().unwrap());
}
*blocker = None;
}
/// Return the url associated with this load.
pub fn url(&self) -> Option<&Url> {
self.load.as_ref().map(LoadType::url)
}
}
impl Drop for LoadBlocker {
fn drop(&mut self) {
if!thread::panicking() {
debug_assert!(self.load.is_none());
}
}
}
#[derive(JSTraceable, HeapSizeOf)]
pub struct DocumentLoader {
resource_threads: ResourceThreads,
blocking_loads: Vec<LoadType>,
events_inhibited: bool,
}
impl DocumentLoader {
pub fn | (existing: &DocumentLoader) -> DocumentLoader {
DocumentLoader::new_with_threads(existing.resource_threads.clone(), None)
}
pub fn new_with_threads(resource_threads: ResourceThreads,
initial_load: Option<Url>) -> DocumentLoader {
debug!("Initial blocking load {:?}.", initial_load);
let initial_loads = initial_load.into_iter().map(LoadType::PageSource).collect();
DocumentLoader {
resource_threads: resource_threads,
blocking_loads: initial_loads,
events_inhibited: false,
}
}
/// Add a load to the list of blocking loads.
fn add_blocking_load(&mut self, load: LoadType) {
debug!("Adding blocking load {:?} ({}).", load, self.blocking_loads.len());
self.blocking_loads.push(load);
}
/// Initiate a new fetch.
pub fn fetch_async(&mut self,
load: LoadType,
request: RequestInit,
fetch_target: IpcSender<FetchResponseMsg>) {
self.add_blocking_load(load);
self.resource_threads.sender().send(CoreResourceMsg::Fetch(request, fetch_target)).unwrap();
}
/// Mark an in-progress network request complete.
pub fn finish_load(&mut self, load: &LoadType) {
debug!("Removing blocking load {:?} ({}).", load, self.blocking_loads.len());
let idx = self.blocking_loads.iter().position(|unfinished| *unfinished == *load);
self.blocking_loads.remove(idx.expect(&format!("unknown completed load {:?}", load)));
}
pub fn is_blocked(&self) -> bool {
// TODO: Ensure that we report blocked if parsing is still ongoing.
!self.blocking_loads.is_empty()
}
pub fn inhibit_events(&mut self) {
self.events_inhibited = true;
}
pub fn events_inhibited(&self) -> bool {
self.events_inhibited
}
pub fn resource_threads(&self) -> &ResourceThreads {
&self.resource_threads
}
}
| new | identifier_name |
lib.rs | // =================================================================
//
// * WARNING *
//
// This file is generated!
//
// Changes made to this file will be overwritten. If changes are
// required to the generated code, the service_crategen project
// must be updated to generate the changes.
//
// =================================================================
#![doc(html_logo_url = "https://raw.githubusercontent.com/rusoto/rusoto/master/assets/logo-square.png")]
//! <p>Using the Amazon Cognito User Pools API, you can create a user pool to manage directories and users. You can authenticate a user to obtain tokens related to user identity and access policies.</p> <p>This API reference provides information about user pools in Amazon Cognito User Pools.</p> <p>For more information, see the Amazon Cognito Documentation.</p>
//!
//! If you're using the service, you're probably looking for [CognitoIdentityProviderClient](struct.CognitoIdentityProviderClient.html) and [CognitoIdentityProvider](trait.CognitoIdentityProvider.html).
| #[macro_use]
extern crate serde_derive;
extern crate serde_json;
mod generated;
mod custom;
pub use generated::*;
pub use custom::*; | extern crate futures;
extern crate rusoto_core;
extern crate serde; | random_line_split |
mod.rs | // Copyright 2017, Igor Shaula
// Licensed under the MIT License <LICENSE or
// http://opensource.org/licenses/MIT>. This file
// may not be copied, modified, or distributed
// except according to those terms.
use super::enums::*;
use super::RegKey;
use std::error::Error;
use std::fmt;
use std::io;
use winapi::shared::minwindef::DWORD;
macro_rules! read_value {
($s:ident) => {
match mem::replace(&mut $s.f_name, None) {
Some(ref s) => $s.key.get_value(s).map_err(DecoderError::IoError),
None => Err(DecoderError::NoFieldName),
}
};
}
macro_rules! parse_string {
($s:ident) => {{
let s: String = read_value!($s)?;
s.parse()
.map_err(|e| DecoderError::ParseError(format!("{:?}", e)))
}};
}
macro_rules! no_impl {
($e:expr) => {
Err(DecoderError::DecodeNotImplemented($e.to_owned()))
};
}
#[cfg(feature = "serialization-serde")]
mod serialization_serde;
#[derive(Debug)]
pub enum DecoderError {
DecodeNotImplemented(String),
DeserializerError(String),
IoError(io::Error),
ParseError(String),
NoFieldName,
}
impl fmt::Display for DecoderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl Error for DecoderError {}
impl From<io::Error> for DecoderError {
fn from(err: io::Error) -> DecoderError {
DecoderError::IoError(err)
}
}
pub type DecodeResult<T> = Result<T, DecoderError>;
#[derive(Debug)]
enum DecoderReadingState {
WaitingForKey,
WaitingForValue,
}
#[derive(Debug)]
enum DecoderEnumerationState {
EnumeratingKeys(DWORD),
EnumeratingValues(DWORD),
}
#[derive(Debug)]
pub struct Decoder {
key: RegKey, | enumeration_state: DecoderEnumerationState,
}
const DECODER_SAM: DWORD = KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
impl Decoder {
pub fn from_key(key: &RegKey) -> DecodeResult<Decoder> {
key.open_subkey_with_flags("", DECODER_SAM)
.map(Decoder::new)
.map_err(DecoderError::IoError)
}
fn new(key: RegKey) -> Decoder {
Decoder {
key,
f_name: None,
reading_state: DecoderReadingState::WaitingForKey,
enumeration_state: DecoderEnumerationState::EnumeratingKeys(0),
}
}
} | f_name: Option<String>,
reading_state: DecoderReadingState, | random_line_split |
mod.rs | // Copyright 2017, Igor Shaula
// Licensed under the MIT License <LICENSE or
// http://opensource.org/licenses/MIT>. This file
// may not be copied, modified, or distributed
// except according to those terms.
use super::enums::*;
use super::RegKey;
use std::error::Error;
use std::fmt;
use std::io;
use winapi::shared::minwindef::DWORD;
macro_rules! read_value {
($s:ident) => {
match mem::replace(&mut $s.f_name, None) {
Some(ref s) => $s.key.get_value(s).map_err(DecoderError::IoError),
None => Err(DecoderError::NoFieldName),
}
};
}
macro_rules! parse_string {
($s:ident) => {{
let s: String = read_value!($s)?;
s.parse()
.map_err(|e| DecoderError::ParseError(format!("{:?}", e)))
}};
}
macro_rules! no_impl {
($e:expr) => {
Err(DecoderError::DecodeNotImplemented($e.to_owned()))
};
}
#[cfg(feature = "serialization-serde")]
mod serialization_serde;
#[derive(Debug)]
pub enum DecoderError {
DecodeNotImplemented(String),
DeserializerError(String),
IoError(io::Error),
ParseError(String),
NoFieldName,
}
impl fmt::Display for DecoderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl Error for DecoderError {}
impl From<io::Error> for DecoderError {
fn | (err: io::Error) -> DecoderError {
DecoderError::IoError(err)
}
}
pub type DecodeResult<T> = Result<T, DecoderError>;
#[derive(Debug)]
enum DecoderReadingState {
WaitingForKey,
WaitingForValue,
}
#[derive(Debug)]
enum DecoderEnumerationState {
EnumeratingKeys(DWORD),
EnumeratingValues(DWORD),
}
#[derive(Debug)]
pub struct Decoder {
key: RegKey,
f_name: Option<String>,
reading_state: DecoderReadingState,
enumeration_state: DecoderEnumerationState,
}
const DECODER_SAM: DWORD = KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
impl Decoder {
pub fn from_key(key: &RegKey) -> DecodeResult<Decoder> {
key.open_subkey_with_flags("", DECODER_SAM)
.map(Decoder::new)
.map_err(DecoderError::IoError)
}
fn new(key: RegKey) -> Decoder {
Decoder {
key,
f_name: None,
reading_state: DecoderReadingState::WaitingForKey,
enumeration_state: DecoderEnumerationState::EnumeratingKeys(0),
}
}
}
| from | identifier_name |
main.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// This program is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
extern crate serde;
extern crate serde_json;
extern crate libproto;
extern crate util;
extern crate threadpool;
extern crate rustc_serialize;
extern crate protobuf;
#[macro_use]
extern crate log;
extern crate clap;
extern crate tx_pool;
extern crate cita_crypto as crypto;
extern crate proof;
extern crate pubsub;
extern crate engine_json;
extern crate engine;
extern crate parking_lot;
extern crate cpuprofiler;
extern crate cita_log;
extern crate dotenv;
pub mod core;
use clap::App;
use core::Spec;
use core::handler;
use cpuprofiler::PROFILER;
use libproto::*;
use log::LogLevelFilter;
use pubsub::start_pubsub;
use std::sync::mpsc::channel;
use std::thread;
use std::time::{Duration, Instant};
fn main() {
dotenv::dotenv().ok();
// Always print backtrace on panic.
::std::env::set_var("RUST_BACKTRACE", "1");
cita_log::format(LogLevelFilter::Info);
println!("CITA:consensus:poa");
let matches = App::new("authority_round")
.version("0.1")
.author("Cryptape")
.about("CITA Block Chain Node powered by Rust")
.args_from_usage("-c, --config=[FILE] 'Sets a custom config file'")
.args_from_usage("--prof-start=[TIME] 'Sets profiling start time (second from app start)'")
.args_from_usage("--prof-duration=[DURATION] 'Sets duration(second) of profiling'")
.get_matches();
let mut config_path = "config";
if let Some(c) = matches.value_of("config") {
trace!("Value for config: {}", c);
config_path = c;
}
//start profiling
let mut prof_start: u64 = 0;
let mut prof_duration: u64 = 0;
if let Some(start) = matches.value_of("prof-start") {
trace!("Value for prof-start: {}", start);
prof_start = start.parse::<u64>().unwrap();
}
if let Some(duration) = matches.value_of("prof-duration") {
trace!("Value for prof-duration: {}", duration);
prof_duration = duration.parse::<u64>().unwrap();
}
if prof_start!= 0 && prof_duration!= 0 |
let threadpool = threadpool::ThreadPool::new(2);
let (tx, rx) = channel();
let (tx_sub, rx_sub) = channel();
let (tx_pub, rx_pub) = channel();
start_pubsub("consensus", vec!["net.tx", "jsonrpc.new_tx", "net.msg", "chain.status"], tx_sub, rx_pub);
thread::spawn(move || loop {
let (key, body) = rx_sub.recv().unwrap();
let tx = tx.clone();
handler::receive(&threadpool, &tx, key_to_id(&key), body);
});
let spec = Spec::new_test_round(config_path);
let engine = spec.engine;
let ready = spec.rx;
let process = engine.clone();
let tx_pub1 = tx_pub.clone();
thread::spawn(move || loop {
let process = process.clone();
handler::process(process, &rx, tx_pub1.clone());
});
let seal = engine.clone();
let dur = engine.duration();
let mut old_height = 0;
let mut new_height = 0;
let tx_pub = tx_pub.clone();
thread::spawn(move || loop {
let seal = seal.clone();
trace!("seal worker lock!");
loop {
new_height = ready.recv().unwrap();
if new_height > old_height {
old_height = new_height;
break;
}
}
trace!("seal worker go {}!!!", new_height);
let now = Instant::now();
trace!("seal worker ready!");
handler::seal(seal, tx_pub.clone());
let elapsed = now.elapsed();
if let Some(dur1) = dur.checked_sub(elapsed) {
trace!("seal worker sleep!!!!!{:?}", dur1);
thread::sleep(dur1);
}
});
loop {
thread::sleep(Duration::from_millis(10000));
}
}
| {
thread::spawn(move || {
thread::sleep(Duration::new(prof_start, 0));
println!("******Profiling Start******");
PROFILER.lock().unwrap().start("./consensus_poa.profile").expect("Couldn't start");
thread::sleep(Duration::new(prof_duration, 0));
println!("******Profiling Stop******");
PROFILER.lock().unwrap().stop().unwrap();
});
} | conditional_block |
main.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// This program is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
extern crate serde;
extern crate serde_json;
extern crate libproto;
extern crate util;
extern crate threadpool;
extern crate rustc_serialize;
extern crate protobuf;
#[macro_use]
extern crate log;
extern crate clap;
extern crate tx_pool;
extern crate cita_crypto as crypto;
extern crate proof;
extern crate pubsub;
extern crate engine_json;
extern crate engine;
extern crate parking_lot;
extern crate cpuprofiler;
extern crate cita_log;
extern crate dotenv;
pub mod core;
use clap::App;
use core::Spec;
use core::handler;
use cpuprofiler::PROFILER;
use libproto::*;
use log::LogLevelFilter;
use pubsub::start_pubsub;
use std::sync::mpsc::channel;
use std::thread;
use std::time::{Duration, Instant};
fn | () {
dotenv::dotenv().ok();
// Always print backtrace on panic.
::std::env::set_var("RUST_BACKTRACE", "1");
cita_log::format(LogLevelFilter::Info);
println!("CITA:consensus:poa");
let matches = App::new("authority_round")
.version("0.1")
.author("Cryptape")
.about("CITA Block Chain Node powered by Rust")
.args_from_usage("-c, --config=[FILE] 'Sets a custom config file'")
.args_from_usage("--prof-start=[TIME] 'Sets profiling start time (second from app start)'")
.args_from_usage("--prof-duration=[DURATION] 'Sets duration(second) of profiling'")
.get_matches();
let mut config_path = "config";
if let Some(c) = matches.value_of("config") {
trace!("Value for config: {}", c);
config_path = c;
}
//start profiling
let mut prof_start: u64 = 0;
let mut prof_duration: u64 = 0;
if let Some(start) = matches.value_of("prof-start") {
trace!("Value for prof-start: {}", start);
prof_start = start.parse::<u64>().unwrap();
}
if let Some(duration) = matches.value_of("prof-duration") {
trace!("Value for prof-duration: {}", duration);
prof_duration = duration.parse::<u64>().unwrap();
}
if prof_start!= 0 && prof_duration!= 0 {
thread::spawn(move || {
thread::sleep(Duration::new(prof_start, 0));
println!("******Profiling Start******");
PROFILER.lock().unwrap().start("./consensus_poa.profile").expect("Couldn't start");
thread::sleep(Duration::new(prof_duration, 0));
println!("******Profiling Stop******");
PROFILER.lock().unwrap().stop().unwrap();
});
}
let threadpool = threadpool::ThreadPool::new(2);
let (tx, rx) = channel();
let (tx_sub, rx_sub) = channel();
let (tx_pub, rx_pub) = channel();
start_pubsub("consensus", vec!["net.tx", "jsonrpc.new_tx", "net.msg", "chain.status"], tx_sub, rx_pub);
thread::spawn(move || loop {
let (key, body) = rx_sub.recv().unwrap();
let tx = tx.clone();
handler::receive(&threadpool, &tx, key_to_id(&key), body);
});
let spec = Spec::new_test_round(config_path);
let engine = spec.engine;
let ready = spec.rx;
let process = engine.clone();
let tx_pub1 = tx_pub.clone();
thread::spawn(move || loop {
let process = process.clone();
handler::process(process, &rx, tx_pub1.clone());
});
let seal = engine.clone();
let dur = engine.duration();
let mut old_height = 0;
let mut new_height = 0;
let tx_pub = tx_pub.clone();
thread::spawn(move || loop {
let seal = seal.clone();
trace!("seal worker lock!");
loop {
new_height = ready.recv().unwrap();
if new_height > old_height {
old_height = new_height;
break;
}
}
trace!("seal worker go {}!!!", new_height);
let now = Instant::now();
trace!("seal worker ready!");
handler::seal(seal, tx_pub.clone());
let elapsed = now.elapsed();
if let Some(dur1) = dur.checked_sub(elapsed) {
trace!("seal worker sleep!!!!!{:?}", dur1);
thread::sleep(dur1);
}
});
loop {
thread::sleep(Duration::from_millis(10000));
}
}
| main | identifier_name |
main.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// This program is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
extern crate serde;
extern crate serde_json;
extern crate libproto;
extern crate util;
extern crate threadpool;
extern crate rustc_serialize;
extern crate protobuf;
#[macro_use]
extern crate log;
extern crate clap;
extern crate tx_pool;
extern crate cita_crypto as crypto;
extern crate proof;
extern crate pubsub;
extern crate engine_json;
extern crate engine;
extern crate parking_lot;
extern crate cpuprofiler;
extern crate cita_log;
extern crate dotenv;
pub mod core;
use clap::App;
use core::Spec;
use core::handler;
use cpuprofiler::PROFILER;
use libproto::*;
use log::LogLevelFilter;
use pubsub::start_pubsub;
use std::sync::mpsc::channel;
use std::thread;
use std::time::{Duration, Instant};
fn main() {
dotenv::dotenv().ok();
// Always print backtrace on panic.
::std::env::set_var("RUST_BACKTRACE", "1");
cita_log::format(LogLevelFilter::Info);
println!("CITA:consensus:poa");
let matches = App::new("authority_round")
.version("0.1")
.author("Cryptape")
.about("CITA Block Chain Node powered by Rust")
.args_from_usage("-c, --config=[FILE] 'Sets a custom config file'")
.args_from_usage("--prof-start=[TIME] 'Sets profiling start time (second from app start)'")
.args_from_usage("--prof-duration=[DURATION] 'Sets duration(second) of profiling'")
.get_matches();
let mut config_path = "config";
if let Some(c) = matches.value_of("config") {
trace!("Value for config: {}", c);
config_path = c;
}
//start profiling
let mut prof_start: u64 = 0;
let mut prof_duration: u64 = 0;
if let Some(start) = matches.value_of("prof-start") {
trace!("Value for prof-start: {}", start);
prof_start = start.parse::<u64>().unwrap();
}
if let Some(duration) = matches.value_of("prof-duration") {
trace!("Value for prof-duration: {}", duration);
prof_duration = duration.parse::<u64>().unwrap();
}
if prof_start!= 0 && prof_duration!= 0 {
thread::spawn(move || {
thread::sleep(Duration::new(prof_start, 0));
println!("******Profiling Start******");
PROFILER.lock().unwrap().start("./consensus_poa.profile").expect("Couldn't start");
thread::sleep(Duration::new(prof_duration, 0));
println!("******Profiling Stop******");
PROFILER.lock().unwrap().stop().unwrap();
});
}
let threadpool = threadpool::ThreadPool::new(2);
let (tx, rx) = channel();
let (tx_sub, rx_sub) = channel();
let (tx_pub, rx_pub) = channel();
start_pubsub("consensus", vec!["net.tx", "jsonrpc.new_tx", "net.msg", "chain.status"], tx_sub, rx_pub);
thread::spawn(move || loop {
let (key, body) = rx_sub.recv().unwrap();
let tx = tx.clone();
handler::receive(&threadpool, &tx, key_to_id(&key), body);
});
let spec = Spec::new_test_round(config_path);
let engine = spec.engine;
let ready = spec.rx;
let process = engine.clone();
let tx_pub1 = tx_pub.clone(); | let seal = engine.clone();
let dur = engine.duration();
let mut old_height = 0;
let mut new_height = 0;
let tx_pub = tx_pub.clone();
thread::spawn(move || loop {
let seal = seal.clone();
trace!("seal worker lock!");
loop {
new_height = ready.recv().unwrap();
if new_height > old_height {
old_height = new_height;
break;
}
}
trace!("seal worker go {}!!!", new_height);
let now = Instant::now();
trace!("seal worker ready!");
handler::seal(seal, tx_pub.clone());
let elapsed = now.elapsed();
if let Some(dur1) = dur.checked_sub(elapsed) {
trace!("seal worker sleep!!!!!{:?}", dur1);
thread::sleep(dur1);
}
});
loop {
thread::sleep(Duration::from_millis(10000));
}
} | thread::spawn(move || loop {
let process = process.clone();
handler::process(process, &rx, tx_pub1.clone());
});
| random_line_split |
main.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// This program is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
extern crate serde;
extern crate serde_json;
extern crate libproto;
extern crate util;
extern crate threadpool;
extern crate rustc_serialize;
extern crate protobuf;
#[macro_use]
extern crate log;
extern crate clap;
extern crate tx_pool;
extern crate cita_crypto as crypto;
extern crate proof;
extern crate pubsub;
extern crate engine_json;
extern crate engine;
extern crate parking_lot;
extern crate cpuprofiler;
extern crate cita_log;
extern crate dotenv;
pub mod core;
use clap::App;
use core::Spec;
use core::handler;
use cpuprofiler::PROFILER;
use libproto::*;
use log::LogLevelFilter;
use pubsub::start_pubsub;
use std::sync::mpsc::channel;
use std::thread;
use std::time::{Duration, Instant};
fn main() | config_path = c;
}
//start profiling
let mut prof_start: u64 = 0;
let mut prof_duration: u64 = 0;
if let Some(start) = matches.value_of("prof-start") {
trace!("Value for prof-start: {}", start);
prof_start = start.parse::<u64>().unwrap();
}
if let Some(duration) = matches.value_of("prof-duration") {
trace!("Value for prof-duration: {}", duration);
prof_duration = duration.parse::<u64>().unwrap();
}
if prof_start!= 0 && prof_duration!= 0 {
thread::spawn(move || {
thread::sleep(Duration::new(prof_start, 0));
println!("******Profiling Start******");
PROFILER.lock().unwrap().start("./consensus_poa.profile").expect("Couldn't start");
thread::sleep(Duration::new(prof_duration, 0));
println!("******Profiling Stop******");
PROFILER.lock().unwrap().stop().unwrap();
});
}
let threadpool = threadpool::ThreadPool::new(2);
let (tx, rx) = channel();
let (tx_sub, rx_sub) = channel();
let (tx_pub, rx_pub) = channel();
start_pubsub("consensus", vec!["net.tx", "jsonrpc.new_tx", "net.msg", "chain.status"], tx_sub, rx_pub);
thread::spawn(move || loop {
let (key, body) = rx_sub.recv().unwrap();
let tx = tx.clone();
handler::receive(&threadpool, &tx, key_to_id(&key), body);
});
let spec = Spec::new_test_round(config_path);
let engine = spec.engine;
let ready = spec.rx;
let process = engine.clone();
let tx_pub1 = tx_pub.clone();
thread::spawn(move || loop {
let process = process.clone();
handler::process(process, &rx, tx_pub1.clone());
});
let seal = engine.clone();
let dur = engine.duration();
let mut old_height = 0;
let mut new_height = 0;
let tx_pub = tx_pub.clone();
thread::spawn(move || loop {
let seal = seal.clone();
trace!("seal worker lock!");
loop {
new_height = ready.recv().unwrap();
if new_height > old_height {
old_height = new_height;
break;
}
}
trace!("seal worker go {}!!!", new_height);
let now = Instant::now();
trace!("seal worker ready!");
handler::seal(seal, tx_pub.clone());
let elapsed = now.elapsed();
if let Some(dur1) = dur.checked_sub(elapsed) {
trace!("seal worker sleep!!!!!{:?}", dur1);
thread::sleep(dur1);
}
});
loop {
thread::sleep(Duration::from_millis(10000));
}
}
| {
dotenv::dotenv().ok();
// Always print backtrace on panic.
::std::env::set_var("RUST_BACKTRACE", "1");
cita_log::format(LogLevelFilter::Info);
println!("CITA:consensus:poa");
let matches = App::new("authority_round")
.version("0.1")
.author("Cryptape")
.about("CITA Block Chain Node powered by Rust")
.args_from_usage("-c, --config=[FILE] 'Sets a custom config file'")
.args_from_usage("--prof-start=[TIME] 'Sets profiling start time (second from app start)'")
.args_from_usage("--prof-duration=[DURATION] 'Sets duration(second) of profiling'")
.get_matches();
let mut config_path = "config";
if let Some(c) = matches.value_of("config") {
trace!("Value for config: {}", c); | identifier_body |
runner.rs | use regex::Regex;
use state::Cucumber;
use event::request::{InvokeArgument, Request};
use event::response::{InvokeResponse, Response, StepMatchesResponse};
use definitions::registration::{CucumberRegistrar, SimpleStep};
use std::panic::{self, AssertUnwindSafe};
use std::str::FromStr;
/// The step runner for [Cucumber state](../state/struct.Cucumber.html)
///
/// The runner stands in for the Cucumber instance and provides an interface for
/// [Request](../event/request/enum.Request.html) events to be translated into
/// state changes and
/// step invocations, along with a
/// [Response](../event/response/enum.Response.html). These are typically
/// supplied by a running
/// [Server](../server/struct.Server.html), but may be supplied by a native
/// Gherkin implementation
/// later.
///
/// Typically this struct will only be instantiated by the user, and then
/// passed to a Server to
/// maintain.
///
#[allow(dead_code)]
pub struct WorldRunner<World> {
cuke: Cucumber<World>,
world: World,
}
impl<World> WorldRunner<World> {
#[allow(dead_code)]
pub fn new(world: World) -> WorldRunner<World> {
WorldRunner {
cuke: Cucumber::new(),
world: world,
}
}
}
/// An interface for implementers that can consume a
/// [Request](../event/request/enum.Request.html) and yield a
/// [Response](../event/response/enum.Response.html)
///
/// This generally refers to [WorldRunner](./struct.WorldRunner.html)
pub trait CommandRunner {
fn execute_cmd(&mut self, req: Request) -> Response;
}
impl<T: Fn(Request) -> Response> CommandRunner for T {
fn execute_cmd(&mut self, req: Request) -> Response {
self(req)
}
}
impl<World> CommandRunner for WorldRunner<World> {
fn execute_cmd(&mut self, req: Request) -> Response {
match req {
Request::BeginScenario(params) => {
self.cuke.tags = params.tags;
Response::BeginScenario
},
Request::Invoke(params) => {
let step = self.cuke
.step(u32::from_str(¶ms.id).unwrap())
.unwrap();
Response::Invoke(invoke_to_response(step, &self.cuke, &mut self.world, params.args))
},
Request::StepMatches(params) => {
let matches = self.cuke.find_match(¶ms.name_to_match);
if matches.len() == 0 {
Response::StepMatches(StepMatchesResponse::NoMatch)
} else {
Response::StepMatches(StepMatchesResponse::Match(matches))
}
},
Request::EndScenario(_) => {
self.cuke.tags = Vec::new();
Response::EndScenario
},
// TODO: For some reason, cucumber prints the ruby snippet too. Fix that
Request::SnippetText(params) => {
let text = format!(" // In a step registration block where cuke: &mut \
CucumberRegistrar<YourWorld>\n use cucumber::InvokeResponse;\n use \
cucumber::helpers::r;\n {}!(cuke, r(\"^{}$\"), Box::new(move |c, _, \
_| {{\n c.pending(\"TODO\")\n }}));",
params.step_keyword,
params.step_name);
Response::SnippetText(text)
},
}
}
}
impl<World> CucumberRegistrar<World> for WorldRunner<World> {
fn given(&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) |
fn when(&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) {
self.cuke.when(file, line, regex, step)
}
fn then(&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) {
self.cuke.then(file, line, regex, step)
}
}
pub fn invoke_to_response<World>(test_body: &SimpleStep<World>,
cuke: &Cucumber<World>,
world: &mut World,
args: Vec<InvokeArgument>)
-> InvokeResponse {
let result = panic::catch_unwind(AssertUnwindSafe(|| test_body(cuke, world, args)));
match result {
Ok(()) => InvokeResponse::Success,
Err(err) => {
// Yoinked from rustc libstd, with InvokeResponse added as a possible cast
let msg = match err.downcast_ref::<&'static str>() {
Some(s) => *s,
None => {
match err.downcast_ref::<String>() {
Some(s) => &s[..],
None => {
match err.downcast_ref::<InvokeResponse>() {
Some(s) => return s.clone(),
None => "Box<Any>",
}
},
}
},
};
InvokeResponse::fail_from_str(msg)
},
}
}
| {
self.cuke.given(file, line, regex, step)
} | identifier_body |
runner.rs | use regex::Regex;
use state::Cucumber;
use event::request::{InvokeArgument, Request};
use event::response::{InvokeResponse, Response, StepMatchesResponse};
use definitions::registration::{CucumberRegistrar, SimpleStep};
use std::panic::{self, AssertUnwindSafe};
use std::str::FromStr;
/// The step runner for [Cucumber state](../state/struct.Cucumber.html)
///
/// The runner stands in for the Cucumber instance and provides an interface for
/// [Request](../event/request/enum.Request.html) events to be translated into
/// state changes and
/// step invocations, along with a
/// [Response](../event/response/enum.Response.html). These are typically
/// supplied by a running
/// [Server](../server/struct.Server.html), but may be supplied by a native
/// Gherkin implementation
/// later.
///
/// Typically this struct will only be instantiated by the user, and then
/// passed to a Server to
/// maintain.
///
#[allow(dead_code)]
pub struct WorldRunner<World> {
cuke: Cucumber<World>,
world: World,
}
impl<World> WorldRunner<World> {
#[allow(dead_code)]
pub fn new(world: World) -> WorldRunner<World> {
WorldRunner {
cuke: Cucumber::new(),
world: world,
}
}
}
/// An interface for implementers that can consume a
/// [Request](../event/request/enum.Request.html) and yield a
/// [Response](../event/response/enum.Response.html)
///
/// This generally refers to [WorldRunner](./struct.WorldRunner.html)
pub trait CommandRunner {
fn execute_cmd(&mut self, req: Request) -> Response;
}
impl<T: Fn(Request) -> Response> CommandRunner for T {
fn execute_cmd(&mut self, req: Request) -> Response {
self(req)
}
}
impl<World> CommandRunner for WorldRunner<World> {
fn execute_cmd(&mut self, req: Request) -> Response {
match req {
Request::BeginScenario(params) => {
self.cuke.tags = params.tags;
Response::BeginScenario
},
Request::Invoke(params) => {
let step = self.cuke
.step(u32::from_str(¶ms.id).unwrap())
.unwrap();
Response::Invoke(invoke_to_response(step, &self.cuke, &mut self.world, params.args))
},
Request::StepMatches(params) => {
let matches = self.cuke.find_match(¶ms.name_to_match);
if matches.len() == 0 {
Response::StepMatches(StepMatchesResponse::NoMatch)
} else {
Response::StepMatches(StepMatchesResponse::Match(matches))
}
},
Request::EndScenario(_) => {
self.cuke.tags = Vec::new();
Response::EndScenario
},
// TODO: For some reason, cucumber prints the ruby snippet too. Fix that
Request::SnippetText(params) => {
let text = format!(" // In a step registration block where cuke: &mut \
CucumberRegistrar<YourWorld>\n use cucumber::InvokeResponse;\n use \
cucumber::helpers::r;\n {}!(cuke, r(\"^{}$\"), Box::new(move |c, _, \
_| {{\n c.pending(\"TODO\")\n }}));",
params.step_keyword,
params.step_name);
Response::SnippetText(text)
},
}
}
}
impl<World> CucumberRegistrar<World> for WorldRunner<World> {
fn given(&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) {
self.cuke.given(file, line, regex, step)
}
fn when(&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) {
self.cuke.when(file, line, regex, step)
}
fn then(&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) {
self.cuke.then(file, line, regex, step)
}
}
pub fn invoke_to_response<World>(test_body: &SimpleStep<World>,
cuke: &Cucumber<World>,
world: &mut World,
args: Vec<InvokeArgument>)
-> InvokeResponse {
let result = panic::catch_unwind(AssertUnwindSafe(|| test_body(cuke, world, args)));
match result {
Ok(()) => InvokeResponse::Success,
Err(err) => {
// Yoinked from rustc libstd, with InvokeResponse added as a possible cast
let msg = match err.downcast_ref::<&'static str>() {
Some(s) => *s,
None => {
match err.downcast_ref::<String>() {
Some(s) => &s[..],
None => {
match err.downcast_ref::<InvokeResponse>() {
Some(s) => return s.clone(),
None => "Box<Any>",
}
}, | }
},
};
InvokeResponse::fail_from_str(msg)
},
}
} | random_line_split |
|
runner.rs | use regex::Regex;
use state::Cucumber;
use event::request::{InvokeArgument, Request};
use event::response::{InvokeResponse, Response, StepMatchesResponse};
use definitions::registration::{CucumberRegistrar, SimpleStep};
use std::panic::{self, AssertUnwindSafe};
use std::str::FromStr;
/// The step runner for [Cucumber state](../state/struct.Cucumber.html)
///
/// The runner stands in for the Cucumber instance and provides an interface for
/// [Request](../event/request/enum.Request.html) events to be translated into
/// state changes and
/// step invocations, along with a
/// [Response](../event/response/enum.Response.html). These are typically
/// supplied by a running
/// [Server](../server/struct.Server.html), but may be supplied by a native
/// Gherkin implementation
/// later.
///
/// Typically this struct will only be instantiated by the user, and then
/// passed to a Server to
/// maintain.
///
#[allow(dead_code)]
pub struct WorldRunner<World> {
cuke: Cucumber<World>,
world: World,
}
impl<World> WorldRunner<World> {
#[allow(dead_code)]
pub fn new(world: World) -> WorldRunner<World> {
WorldRunner {
cuke: Cucumber::new(),
world: world,
}
}
}
/// An interface for implementers that can consume a
/// [Request](../event/request/enum.Request.html) and yield a
/// [Response](../event/response/enum.Response.html)
///
/// This generally refers to [WorldRunner](./struct.WorldRunner.html)
pub trait CommandRunner {
fn execute_cmd(&mut self, req: Request) -> Response;
}
impl<T: Fn(Request) -> Response> CommandRunner for T {
fn execute_cmd(&mut self, req: Request) -> Response {
self(req)
}
}
impl<World> CommandRunner for WorldRunner<World> {
fn execute_cmd(&mut self, req: Request) -> Response {
match req {
Request::BeginScenario(params) => {
self.cuke.tags = params.tags;
Response::BeginScenario
},
Request::Invoke(params) => {
let step = self.cuke
.step(u32::from_str(¶ms.id).unwrap())
.unwrap();
Response::Invoke(invoke_to_response(step, &self.cuke, &mut self.world, params.args))
},
Request::StepMatches(params) => | ,
Request::EndScenario(_) => {
self.cuke.tags = Vec::new();
Response::EndScenario
},
// TODO: For some reason, cucumber prints the ruby snippet too. Fix that
Request::SnippetText(params) => {
let text = format!(" // In a step registration block where cuke: &mut \
CucumberRegistrar<YourWorld>\n use cucumber::InvokeResponse;\n use \
cucumber::helpers::r;\n {}!(cuke, r(\"^{}$\"), Box::new(move |c, _, \
_| {{\n c.pending(\"TODO\")\n }}));",
params.step_keyword,
params.step_name);
Response::SnippetText(text)
},
}
}
}
impl<World> CucumberRegistrar<World> for WorldRunner<World> {
fn given(&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) {
self.cuke.given(file, line, regex, step)
}
fn when(&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) {
self.cuke.when(file, line, regex, step)
}
fn then(&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) {
self.cuke.then(file, line, regex, step)
}
}
pub fn invoke_to_response<World>(test_body: &SimpleStep<World>,
cuke: &Cucumber<World>,
world: &mut World,
args: Vec<InvokeArgument>)
-> InvokeResponse {
let result = panic::catch_unwind(AssertUnwindSafe(|| test_body(cuke, world, args)));
match result {
Ok(()) => InvokeResponse::Success,
Err(err) => {
// Yoinked from rustc libstd, with InvokeResponse added as a possible cast
let msg = match err.downcast_ref::<&'static str>() {
Some(s) => *s,
None => {
match err.downcast_ref::<String>() {
Some(s) => &s[..],
None => {
match err.downcast_ref::<InvokeResponse>() {
Some(s) => return s.clone(),
None => "Box<Any>",
}
},
}
},
};
InvokeResponse::fail_from_str(msg)
},
}
}
| {
let matches = self.cuke.find_match(¶ms.name_to_match);
if matches.len() == 0 {
Response::StepMatches(StepMatchesResponse::NoMatch)
} else {
Response::StepMatches(StepMatchesResponse::Match(matches))
}
} | conditional_block |
runner.rs | use regex::Regex;
use state::Cucumber;
use event::request::{InvokeArgument, Request};
use event::response::{InvokeResponse, Response, StepMatchesResponse};
use definitions::registration::{CucumberRegistrar, SimpleStep};
use std::panic::{self, AssertUnwindSafe};
use std::str::FromStr;
/// The step runner for [Cucumber state](../state/struct.Cucumber.html)
///
/// The runner stands in for the Cucumber instance and provides an interface for
/// [Request](../event/request/enum.Request.html) events to be translated into
/// state changes and
/// step invocations, along with a
/// [Response](../event/response/enum.Response.html). These are typically
/// supplied by a running
/// [Server](../server/struct.Server.html), but may be supplied by a native
/// Gherkin implementation
/// later.
///
/// Typically this struct will only be instantiated by the user, and then
/// passed to a Server to
/// maintain.
///
#[allow(dead_code)]
pub struct WorldRunner<World> {
cuke: Cucumber<World>,
world: World,
}
impl<World> WorldRunner<World> {
#[allow(dead_code)]
pub fn new(world: World) -> WorldRunner<World> {
WorldRunner {
cuke: Cucumber::new(),
world: world,
}
}
}
/// An interface for implementers that can consume a
/// [Request](../event/request/enum.Request.html) and yield a
/// [Response](../event/response/enum.Response.html)
///
/// This generally refers to [WorldRunner](./struct.WorldRunner.html)
pub trait CommandRunner {
fn execute_cmd(&mut self, req: Request) -> Response;
}
impl<T: Fn(Request) -> Response> CommandRunner for T {
fn execute_cmd(&mut self, req: Request) -> Response {
self(req)
}
}
impl<World> CommandRunner for WorldRunner<World> {
fn execute_cmd(&mut self, req: Request) -> Response {
match req {
Request::BeginScenario(params) => {
self.cuke.tags = params.tags;
Response::BeginScenario
},
Request::Invoke(params) => {
let step = self.cuke
.step(u32::from_str(¶ms.id).unwrap())
.unwrap();
Response::Invoke(invoke_to_response(step, &self.cuke, &mut self.world, params.args))
},
Request::StepMatches(params) => {
let matches = self.cuke.find_match(¶ms.name_to_match);
if matches.len() == 0 {
Response::StepMatches(StepMatchesResponse::NoMatch)
} else {
Response::StepMatches(StepMatchesResponse::Match(matches))
}
},
Request::EndScenario(_) => {
self.cuke.tags = Vec::new();
Response::EndScenario
},
// TODO: For some reason, cucumber prints the ruby snippet too. Fix that
Request::SnippetText(params) => {
let text = format!(" // In a step registration block where cuke: &mut \
CucumberRegistrar<YourWorld>\n use cucumber::InvokeResponse;\n use \
cucumber::helpers::r;\n {}!(cuke, r(\"^{}$\"), Box::new(move |c, _, \
_| {{\n c.pending(\"TODO\")\n }}));",
params.step_keyword,
params.step_name);
Response::SnippetText(text)
},
}
}
}
impl<World> CucumberRegistrar<World> for WorldRunner<World> {
fn given(&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) {
self.cuke.given(file, line, regex, step)
}
fn | (&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) {
self.cuke.when(file, line, regex, step)
}
fn then(&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) {
self.cuke.then(file, line, regex, step)
}
}
pub fn invoke_to_response<World>(test_body: &SimpleStep<World>,
cuke: &Cucumber<World>,
world: &mut World,
args: Vec<InvokeArgument>)
-> InvokeResponse {
let result = panic::catch_unwind(AssertUnwindSafe(|| test_body(cuke, world, args)));
match result {
Ok(()) => InvokeResponse::Success,
Err(err) => {
// Yoinked from rustc libstd, with InvokeResponse added as a possible cast
let msg = match err.downcast_ref::<&'static str>() {
Some(s) => *s,
None => {
match err.downcast_ref::<String>() {
Some(s) => &s[..],
None => {
match err.downcast_ref::<InvokeResponse>() {
Some(s) => return s.clone(),
None => "Box<Any>",
}
},
}
},
};
InvokeResponse::fail_from_str(msg)
},
}
}
| when | identifier_name |
quick.rs | //! An example using the Builder pattern API to configure the logger at run-time based on command
//! line arguments.
//!
//! The default output is `module::path: message`, and the "tag", which is the text to the left of
//! the colon, is colorized. This example allows the user to dynamically change the output based
//! on command line arguments.
//!
//! The [clap](https://crates.io/crates/clap) argument parser is used in this example, but loggerv
//! works with any argument parser.
extern crate ansi_term;
#[macro_use] extern crate log;
extern crate loggerv;
extern crate clap;
use clap::{Arg, App};
fn main() | warn!("This too is always printed to stderr");
info!("This is optional info printed to stdout"); // for./app -v or higher
debug!("This is optional debug printed to stdout"); // for./app -vv or higher
trace!("This is optional trace printed to stdout"); // for./app -vvv
}
| {
// Add the following line near the beginning of the main function for an application to enable
// colorized output on Windows 10.
//
// Based on documentation for the ansi_term crate, Windows 10 supports ANSI escape characters,
// but it must be enabled first using the `ansi_term::enable_ansi_support()` function. It is
// conditionally compiled and only exists for Windows builds. To avoid build errors on
// non-windows platforms, a cfg guard should be put in place.
#[cfg(windows)] ansi_term::enable_ansi_support().unwrap();
let args = App::new("app")
.arg(Arg::with_name("v")
.short("v")
.multiple(true)
.help("Sets the level of verbosity"))
.get_matches();
loggerv::init_with_verbosity(args.occurrences_of("v")).unwrap();
error!("This is always printed to stderr"); | identifier_body |
quick.rs | //! An example using the Builder pattern API to configure the logger at run-time based on command
//! line arguments.
//!
//! The default output is `module::path: message`, and the "tag", which is the text to the left of
//! the colon, is colorized. This example allows the user to dynamically change the output based
//! on command line arguments.
//!
//! The [clap](https://crates.io/crates/clap) argument parser is used in this example, but loggerv
//! works with any argument parser.
extern crate ansi_term;
#[macro_use] extern crate log;
extern crate loggerv;
extern crate clap;
use clap::{Arg, App};
fn | () {
// Add the following line near the beginning of the main function for an application to enable
// colorized output on Windows 10.
//
// Based on documentation for the ansi_term crate, Windows 10 supports ANSI escape characters,
// but it must be enabled first using the `ansi_term::enable_ansi_support()` function. It is
// conditionally compiled and only exists for Windows builds. To avoid build errors on
// non-windows platforms, a cfg guard should be put in place.
#[cfg(windows)] ansi_term::enable_ansi_support().unwrap();
let args = App::new("app")
.arg(Arg::with_name("v")
.short("v")
.multiple(true)
.help("Sets the level of verbosity"))
.get_matches();
loggerv::init_with_verbosity(args.occurrences_of("v")).unwrap();
error!("This is always printed to stderr");
warn!("This too is always printed to stderr");
info!("This is optional info printed to stdout"); // for./app -v or higher
debug!("This is optional debug printed to stdout"); // for./app -vv or higher
trace!("This is optional trace printed to stdout"); // for./app -vvv
}
| main | identifier_name |
quick.rs | //! An example using the Builder pattern API to configure the logger at run-time based on command
//! line arguments.
//!
//! The default output is `module::path: message`, and the "tag", which is the text to the left of
//! the colon, is colorized. This example allows the user to dynamically change the output based
//! on command line arguments.
//!
//! The [clap](https://crates.io/crates/clap) argument parser is used in this example, but loggerv
//! works with any argument parser.
extern crate ansi_term;
#[macro_use] extern crate log;
extern crate loggerv;
extern crate clap;
| //
// Based on documentation for the ansi_term crate, Windows 10 supports ANSI escape characters,
// but it must be enabled first using the `ansi_term::enable_ansi_support()` function. It is
// conditionally compiled and only exists for Windows builds. To avoid build errors on
// non-windows platforms, a cfg guard should be put in place.
#[cfg(windows)] ansi_term::enable_ansi_support().unwrap();
let args = App::new("app")
.arg(Arg::with_name("v")
.short("v")
.multiple(true)
.help("Sets the level of verbosity"))
.get_matches();
loggerv::init_with_verbosity(args.occurrences_of("v")).unwrap();
error!("This is always printed to stderr");
warn!("This too is always printed to stderr");
info!("This is optional info printed to stdout"); // for./app -v or higher
debug!("This is optional debug printed to stdout"); // for./app -vv or higher
trace!("This is optional trace printed to stdout"); // for./app -vvv
} | use clap::{Arg, App};
fn main() {
// Add the following line near the beginning of the main function for an application to enable
// colorized output on Windows 10. | random_line_split |
deserialization.rs | use alias::Alias;
use config::Config;
use consts::*;
use itertools::Itertools;
use family::Family;
use glib::functions;
use pango::Context;
use pango::ContextExt;
use pango::FontMapExt;
use pango::FontFamilyExt;
use range::Range;
use sxd_document::dom::Comment;
use sxd_document::dom::ChildOfElement;
use sxd_document::dom::Element;
use sxd_document::dom::Text;
use sxd_document::parser;
use std::cell::RefCell;
use std::fs::File;
use std::i32;
use std::io::Read;
use std::ops::Deref;
use std::ops::DerefMut;
pub fn list_families(context: &Context) -> Vec<RefCell<Family>> {
match context.get_font_map() {
Some(map) => {
map.list_families()
.iter()
.filter_map(|x| x.get_name())
.filter(|x|!["Sans", "Serif", "Monospace"].contains(&x.as_str()))
.map(|x| {
RefCell::new(Family {
name: x,
stripped_ranges: vec![],
})
})
.collect()
}
None => vec![],
}
}
pub fn parse_or_default<'a>(families: &'a Vec<RefCell<Family>>) -> Config<'a> {
let fc_config_path = functions::get_user_config_dir()
.expect("$XDG_CONFIG_HOME not set!")
.join("fontconfig/fonts.conf");
let config_parse = match File::open(fc_config_path.as_path()) {
Ok(mut f) => {
let mut buffer = String::new();
f.read_to_string(&mut buffer).expect(
"Failed to parse your fonts.conf file",
);
parser::parse(&buffer)
}
_ => parser::parse(DEFAULT_FONTS_CONF),
};
let config_package = match config_parse {
Ok(package) => package,
Err((_, errors)) => panic!("Error parsing fonts.conf!\n{}", errors.iter().join("\n")),
};
// scan matches collection
let mut scan_matches: Vec<&'a RefCell<Family>> = vec![];
// aliases collection
let mut aliases: Vec<Alias<'a>> = vec![];
{
let doc = config_package.as_document();
let old_root_element = doc.root().children()[0].element().expect(INVALID_CONFIG);
// rest of dom collection
let new_root_element = doc.create_element(old_root_element.name());
for attr in old_root_element.attributes() {
new_root_element.set_attribute_value(attr.name(), attr.value());
}
// group children to correct collections
for child in old_root_element.children() {
match child {
ChildOfElement::Comment(x) if is_typeholder_comment(x) => {}
ChildOfElement::Element(x) if prev_is_typeholder_comment(x) => {
if x.name().local_part() == "alias" {
aliases.push(parse_alias(x, families));
} else if x.name().local_part() == "match" &&
x.attribute_value("target").unwrap_or("") == "scan"
{
match update_family(x, families) {
Some(y) => scan_matches.push(y),
_ => {}
}
}
}
x => new_root_element.append_child(x),
}
}
// replace old_root_element with new_root_element
doc.root().append_child(new_root_element);
}
Config {
scan_matches: scan_matches,
aliases: aliases,
residue: config_package,
}
}
fn prev_is_typeholder_comment(x: Element) -> bool {
match x.preceding_siblings().last() {
Some(y) => {
match y.comment() {
Some(z) => is_typeholder_comment(z),
None => false,
}
}
None => false,
}
}
fn is_typeholder_comment(x: Comment) -> bool {
x.text().starts_with(TYPEHOLDER_COMMENT_PREFIX)
}
fn update_family<'a>(
e: Element,
families: &'a Vec<RefCell<Family>>,
) -> Option<&'a RefCell<Family>> {
let family_name = checked_text(checked_child_element(
"string",
checked_child_element("test", e),
)).text();
let matched_family = families.iter().find(|x| x.borrow().name == family_name);
if matched_family.is_some() {
let nil_range_template = ("nil", "Custom");
let mut current_range_templates = nil_range_template;
let charset_elem = checked_child_element(
"charset",
checked_child_element("minus", checked_child_element("edit", e)),
);
let ranges = charset_elem
.children()
.into_iter()
.group_by(|x| match x {
&ChildOfElement::Comment(y) => {
current_range_templates = y.text()
.splitn(2, ',')
.map(str::trim)
.next_tuple::<(_, _)>()
.expect(INVALID_CONFIG);
current_range_templates
}
&ChildOfElement::Element(y) if y.name().local_part() == "range" => {
current_range_templates
}
_ => nil_range_template,
})
.into_iter()
.map(|(k, group)| {
(
k,
group
.filter_map(|child| child.element())
.filter(|elem| elem.name().local_part() == "range")
.map(|range_elem| {
children_element("int", range_elem)
.map(|int_elem| {
i32::from_str_radix(&checked_text(int_elem).text()[2..], 16)
.expect(INVALID_CONFIG)
})
.next_tuple::<(_, _)>()
.expect(INVALID_CONFIG)
})
.collect_vec(),
)
})
.filter(|&(_, ref code_points)|!code_points.is_empty())
.coalesce(|mut r0, mut r1| if r0.0 == r1.0 {
r0.1.append(&mut r1.1);
Ok(r0)
} else {
Err((r0, r1))
})
.map(|(k, code_points)| match k.1 {
"Block" => Range::Block {
name: String::from(k.0),
code_points: code_points[0],
},
"Script" => Range::Script {
name: String::from(k.0),
code_points: code_points,
},
_ => Range::Custom {
name: String::from(k.0),
code_points: code_points[0],
},
})
.collect_vec();
matched_family
.unwrap()
.borrow_mut()
.deref_mut()
.stripped_ranges = ranges;
}
matched_family
}
fn parse_alias<'a>(e: Element, families: &'a Vec<RefCell<Family>>) -> Alias<'a> {
let alias_name = checked_text(checked_child_element("family", e)).text();
let p_list = children_element("family", checked_child_element("prefer", e))
.filter_map(|x| {
families.iter().find(|y| {
y.borrow().deref().name == checked_text(x).text()
})
})
.collect_vec();
Alias {
name: String::from(alias_name),
prefer_list: p_list,
}
}
fn checked_child_element<'a: 'd, 'd>(name: &'a str, e: Element<'d>) -> Element<'d> |
fn child_element<'a: 'd, 'd>(name: &'a str, e: Element<'d>) -> Option<Element<'d>> {
children_element(name, e).next()
}
fn children_element<'a: 'd, 'd>(
name: &'a str,
e: Element<'d>,
) -> impl Iterator<Item = Element<'d>> + 'd {
e.children()
.into_iter()
.filter_map(|x| x.element())
.filter(move |x| x.name().local_part() == name)
}
fn checked_text<'d>(e: Element<'d>) -> Text<'d> {
text(e).expect(&format!("Element {} has no text!", e.name().local_part()))
}
fn text<'d>(e: Element<'d>) -> Option<Text<'d>> {
e.children().into_iter().filter_map(|x| x.text()).next()
}
| {
child_element(name, e).expect(&format!(
"Element {} has no {} child!",
e.name().local_part(),
name
))
} | identifier_body |
deserialization.rs | use alias::Alias;
use config::Config;
use consts::*;
use itertools::Itertools;
use family::Family;
use glib::functions;
use pango::Context;
use pango::ContextExt;
use pango::FontMapExt;
use pango::FontFamilyExt;
use range::Range;
use sxd_document::dom::Comment;
use sxd_document::dom::ChildOfElement;
use sxd_document::dom::Element;
use sxd_document::dom::Text;
use sxd_document::parser;
use std::cell::RefCell;
use std::fs::File;
use std::i32;
use std::io::Read;
use std::ops::Deref;
use std::ops::DerefMut;
pub fn list_families(context: &Context) -> Vec<RefCell<Family>> {
match context.get_font_map() {
Some(map) => {
map.list_families()
.iter()
.filter_map(|x| x.get_name())
.filter(|x|!["Sans", "Serif", "Monospace"].contains(&x.as_str()))
.map(|x| {
RefCell::new(Family {
name: x,
stripped_ranges: vec![],
})
})
.collect()
}
None => vec![],
}
}
pub fn parse_or_default<'a>(families: &'a Vec<RefCell<Family>>) -> Config<'a> {
let fc_config_path = functions::get_user_config_dir()
.expect("$XDG_CONFIG_HOME not set!")
.join("fontconfig/fonts.conf");
let config_parse = match File::open(fc_config_path.as_path()) {
Ok(mut f) => {
let mut buffer = String::new();
f.read_to_string(&mut buffer).expect(
"Failed to parse your fonts.conf file",
);
parser::parse(&buffer)
}
_ => parser::parse(DEFAULT_FONTS_CONF),
};
let config_package = match config_parse {
Ok(package) => package,
Err((_, errors)) => panic!("Error parsing fonts.conf!\n{}", errors.iter().join("\n")),
};
// scan matches collection
let mut scan_matches: Vec<&'a RefCell<Family>> = vec![];
// aliases collection
let mut aliases: Vec<Alias<'a>> = vec![];
{
let doc = config_package.as_document();
let old_root_element = doc.root().children()[0].element().expect(INVALID_CONFIG);
// rest of dom collection
let new_root_element = doc.create_element(old_root_element.name());
for attr in old_root_element.attributes() {
new_root_element.set_attribute_value(attr.name(), attr.value());
}
// group children to correct collections
for child in old_root_element.children() {
match child {
ChildOfElement::Comment(x) if is_typeholder_comment(x) => {}
ChildOfElement::Element(x) if prev_is_typeholder_comment(x) => {
if x.name().local_part() == "alias" {
aliases.push(parse_alias(x, families));
} else if x.name().local_part() == "match" &&
x.attribute_value("target").unwrap_or("") == "scan"
{
match update_family(x, families) {
Some(y) => scan_matches.push(y),
_ => {}
}
}
}
x => new_root_element.append_child(x),
}
}
// replace old_root_element with new_root_element
doc.root().append_child(new_root_element);
}
Config {
scan_matches: scan_matches,
aliases: aliases,
residue: config_package,
}
}
fn prev_is_typeholder_comment(x: Element) -> bool {
match x.preceding_siblings().last() {
Some(y) => {
match y.comment() {
Some(z) => is_typeholder_comment(z),
None => false,
}
}
None => false,
}
}
fn is_typeholder_comment(x: Comment) -> bool {
x.text().starts_with(TYPEHOLDER_COMMENT_PREFIX)
}
fn update_family<'a>(
e: Element,
families: &'a Vec<RefCell<Family>>,
) -> Option<&'a RefCell<Family>> {
let family_name = checked_text(checked_child_element(
"string",
checked_child_element("test", e),
)).text();
let matched_family = families.iter().find(|x| x.borrow().name == family_name);
if matched_family.is_some() {
let nil_range_template = ("nil", "Custom");
let mut current_range_templates = nil_range_template;
let charset_elem = checked_child_element(
"charset",
checked_child_element("minus", checked_child_element("edit", e)),
);
let ranges = charset_elem
.children()
.into_iter()
.group_by(|x| match x {
&ChildOfElement::Comment(y) => {
current_range_templates = y.text()
.splitn(2, ',')
.map(str::trim)
.next_tuple::<(_, _)>()
.expect(INVALID_CONFIG);
current_range_templates
}
&ChildOfElement::Element(y) if y.name().local_part() == "range" => {
current_range_templates
}
_ => nil_range_template,
})
.into_iter()
.map(|(k, group)| {
(
k,
group
.filter_map(|child| child.element())
.filter(|elem| elem.name().local_part() == "range")
.map(|range_elem| {
children_element("int", range_elem)
.map(|int_elem| {
i32::from_str_radix(&checked_text(int_elem).text()[2..], 16)
.expect(INVALID_CONFIG)
})
.next_tuple::<(_, _)>()
.expect(INVALID_CONFIG)
})
.collect_vec(),
)
})
.filter(|&(_, ref code_points)|!code_points.is_empty())
.coalesce(|mut r0, mut r1| if r0.0 == r1.0 {
r0.1.append(&mut r1.1);
Ok(r0)
} else {
Err((r0, r1))
})
.map(|(k, code_points)| match k.1 {
"Block" => Range::Block {
name: String::from(k.0),
code_points: code_points[0],
},
"Script" => Range::Script {
name: String::from(k.0),
code_points: code_points,
},
_ => Range::Custom {
name: String::from(k.0),
code_points: code_points[0],
},
}) | .stripped_ranges = ranges;
}
matched_family
}
fn parse_alias<'a>(e: Element, families: &'a Vec<RefCell<Family>>) -> Alias<'a> {
let alias_name = checked_text(checked_child_element("family", e)).text();
let p_list = children_element("family", checked_child_element("prefer", e))
.filter_map(|x| {
families.iter().find(|y| {
y.borrow().deref().name == checked_text(x).text()
})
})
.collect_vec();
Alias {
name: String::from(alias_name),
prefer_list: p_list,
}
}
fn checked_child_element<'a: 'd, 'd>(name: &'a str, e: Element<'d>) -> Element<'d> {
child_element(name, e).expect(&format!(
"Element {} has no {} child!",
e.name().local_part(),
name
))
}
fn child_element<'a: 'd, 'd>(name: &'a str, e: Element<'d>) -> Option<Element<'d>> {
children_element(name, e).next()
}
fn children_element<'a: 'd, 'd>(
name: &'a str,
e: Element<'d>,
) -> impl Iterator<Item = Element<'d>> + 'd {
e.children()
.into_iter()
.filter_map(|x| x.element())
.filter(move |x| x.name().local_part() == name)
}
fn checked_text<'d>(e: Element<'d>) -> Text<'d> {
text(e).expect(&format!("Element {} has no text!", e.name().local_part()))
}
fn text<'d>(e: Element<'d>) -> Option<Text<'d>> {
e.children().into_iter().filter_map(|x| x.text()).next()
} | .collect_vec();
matched_family
.unwrap()
.borrow_mut()
.deref_mut() | random_line_split |
deserialization.rs | use alias::Alias;
use config::Config;
use consts::*;
use itertools::Itertools;
use family::Family;
use glib::functions;
use pango::Context;
use pango::ContextExt;
use pango::FontMapExt;
use pango::FontFamilyExt;
use range::Range;
use sxd_document::dom::Comment;
use sxd_document::dom::ChildOfElement;
use sxd_document::dom::Element;
use sxd_document::dom::Text;
use sxd_document::parser;
use std::cell::RefCell;
use std::fs::File;
use std::i32;
use std::io::Read;
use std::ops::Deref;
use std::ops::DerefMut;
pub fn | (context: &Context) -> Vec<RefCell<Family>> {
match context.get_font_map() {
Some(map) => {
map.list_families()
.iter()
.filter_map(|x| x.get_name())
.filter(|x|!["Sans", "Serif", "Monospace"].contains(&x.as_str()))
.map(|x| {
RefCell::new(Family {
name: x,
stripped_ranges: vec![],
})
})
.collect()
}
None => vec![],
}
}
pub fn parse_or_default<'a>(families: &'a Vec<RefCell<Family>>) -> Config<'a> {
let fc_config_path = functions::get_user_config_dir()
.expect("$XDG_CONFIG_HOME not set!")
.join("fontconfig/fonts.conf");
let config_parse = match File::open(fc_config_path.as_path()) {
Ok(mut f) => {
let mut buffer = String::new();
f.read_to_string(&mut buffer).expect(
"Failed to parse your fonts.conf file",
);
parser::parse(&buffer)
}
_ => parser::parse(DEFAULT_FONTS_CONF),
};
let config_package = match config_parse {
Ok(package) => package,
Err((_, errors)) => panic!("Error parsing fonts.conf!\n{}", errors.iter().join("\n")),
};
// scan matches collection
let mut scan_matches: Vec<&'a RefCell<Family>> = vec![];
// aliases collection
let mut aliases: Vec<Alias<'a>> = vec![];
{
let doc = config_package.as_document();
let old_root_element = doc.root().children()[0].element().expect(INVALID_CONFIG);
// rest of dom collection
let new_root_element = doc.create_element(old_root_element.name());
for attr in old_root_element.attributes() {
new_root_element.set_attribute_value(attr.name(), attr.value());
}
// group children to correct collections
for child in old_root_element.children() {
match child {
ChildOfElement::Comment(x) if is_typeholder_comment(x) => {}
ChildOfElement::Element(x) if prev_is_typeholder_comment(x) => {
if x.name().local_part() == "alias" {
aliases.push(parse_alias(x, families));
} else if x.name().local_part() == "match" &&
x.attribute_value("target").unwrap_or("") == "scan"
{
match update_family(x, families) {
Some(y) => scan_matches.push(y),
_ => {}
}
}
}
x => new_root_element.append_child(x),
}
}
// replace old_root_element with new_root_element
doc.root().append_child(new_root_element);
}
Config {
scan_matches: scan_matches,
aliases: aliases,
residue: config_package,
}
}
fn prev_is_typeholder_comment(x: Element) -> bool {
match x.preceding_siblings().last() {
Some(y) => {
match y.comment() {
Some(z) => is_typeholder_comment(z),
None => false,
}
}
None => false,
}
}
fn is_typeholder_comment(x: Comment) -> bool {
x.text().starts_with(TYPEHOLDER_COMMENT_PREFIX)
}
fn update_family<'a>(
e: Element,
families: &'a Vec<RefCell<Family>>,
) -> Option<&'a RefCell<Family>> {
let family_name = checked_text(checked_child_element(
"string",
checked_child_element("test", e),
)).text();
let matched_family = families.iter().find(|x| x.borrow().name == family_name);
if matched_family.is_some() {
let nil_range_template = ("nil", "Custom");
let mut current_range_templates = nil_range_template;
let charset_elem = checked_child_element(
"charset",
checked_child_element("minus", checked_child_element("edit", e)),
);
let ranges = charset_elem
.children()
.into_iter()
.group_by(|x| match x {
&ChildOfElement::Comment(y) => {
current_range_templates = y.text()
.splitn(2, ',')
.map(str::trim)
.next_tuple::<(_, _)>()
.expect(INVALID_CONFIG);
current_range_templates
}
&ChildOfElement::Element(y) if y.name().local_part() == "range" => {
current_range_templates
}
_ => nil_range_template,
})
.into_iter()
.map(|(k, group)| {
(
k,
group
.filter_map(|child| child.element())
.filter(|elem| elem.name().local_part() == "range")
.map(|range_elem| {
children_element("int", range_elem)
.map(|int_elem| {
i32::from_str_radix(&checked_text(int_elem).text()[2..], 16)
.expect(INVALID_CONFIG)
})
.next_tuple::<(_, _)>()
.expect(INVALID_CONFIG)
})
.collect_vec(),
)
})
.filter(|&(_, ref code_points)|!code_points.is_empty())
.coalesce(|mut r0, mut r1| if r0.0 == r1.0 {
r0.1.append(&mut r1.1);
Ok(r0)
} else {
Err((r0, r1))
})
.map(|(k, code_points)| match k.1 {
"Block" => Range::Block {
name: String::from(k.0),
code_points: code_points[0],
},
"Script" => Range::Script {
name: String::from(k.0),
code_points: code_points,
},
_ => Range::Custom {
name: String::from(k.0),
code_points: code_points[0],
},
})
.collect_vec();
matched_family
.unwrap()
.borrow_mut()
.deref_mut()
.stripped_ranges = ranges;
}
matched_family
}
fn parse_alias<'a>(e: Element, families: &'a Vec<RefCell<Family>>) -> Alias<'a> {
let alias_name = checked_text(checked_child_element("family", e)).text();
let p_list = children_element("family", checked_child_element("prefer", e))
.filter_map(|x| {
families.iter().find(|y| {
y.borrow().deref().name == checked_text(x).text()
})
})
.collect_vec();
Alias {
name: String::from(alias_name),
prefer_list: p_list,
}
}
fn checked_child_element<'a: 'd, 'd>(name: &'a str, e: Element<'d>) -> Element<'d> {
child_element(name, e).expect(&format!(
"Element {} has no {} child!",
e.name().local_part(),
name
))
}
fn child_element<'a: 'd, 'd>(name: &'a str, e: Element<'d>) -> Option<Element<'d>> {
children_element(name, e).next()
}
fn children_element<'a: 'd, 'd>(
name: &'a str,
e: Element<'d>,
) -> impl Iterator<Item = Element<'d>> + 'd {
e.children()
.into_iter()
.filter_map(|x| x.element())
.filter(move |x| x.name().local_part() == name)
}
fn checked_text<'d>(e: Element<'d>) -> Text<'d> {
text(e).expect(&format!("Element {} has no text!", e.name().local_part()))
}
fn text<'d>(e: Element<'d>) -> Option<Text<'d>> {
e.children().into_iter().filter_map(|x| x.text()).next()
}
| list_families | identifier_name |
lib.rs | extern crate anduin;
use anduin::logic::{Actable, lcm, Application};
use anduin::backends::vulkan;
use anduin::core;
use anduin::input::{InputProcessor, Key, InputType, InputEvent};
use anduin::graphics::Drawable;
use anduin::audio::{music, sound, PlaybackController};
use anduin::logic::ApplicationListener;
use anduin::files;
use std::thread::sleep;
use std::time::Duration;
use std::path::PathBuf;
use std::str::FromStr;
use std::fs;
fn create_test_vulkan_app() {
let mut vulkan_app = vulkan::VulkanApplication::init("Anduin", "desktop", Some(5), Box::new(Game{}));
println!("application created");
let game_loop = lcm::GameLoop::new();
println!("game_loop created");
vulkan_app.application.input.add_input_processor(Box::new(InputProcessorStuct{}));
println!("add_input_processor finished");
game_loop.run(&mut vulkan_app);
println!("game_loop runned");
vulkan_app.application.listener.as_mut().exit();
}
#[test]
fn open_file() {
/*for entry in fs::read_dir(".").expect("") {
let dir = entry.expect("");
println!("{:?}", dir.file_name());
println!("{:?}", dir.path());
}
let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
d.push("tests/resources/test.txt");
let path = d.to_str().expect("");*/
let path = "./tests/resources/test.txt";
println!("path {}", path);
let handle: files::FileHandle = files::Files::getFileHandle(path, files::PathType::Local);
let name: String = handle.name();
println!("name {}", name.as_str());
}
#[test]
fn play_sound() {
let music = music::Music::new("resources/music.ogg");
let sound = sound::Sound::new("resources/shot.wav");
music.play();
sound.play();
sleep(Duration::from_millis(5000));
}
#[test]
fn create_game_loop() {
let game_loop = lcm::GameLoop::new();
println!("Loop is created {:?}", game_loop);
}
#[test]
fn create_simple_scene() {
let scene = core::scene::Stage {root: core::scene::Node::new("Root Node")};
println!("Simple scene is created {:?}", scene);
}
fn create_simple_game()
{
let scene = core::scene::Stage {
root: core::scene::Node::build("Root Node", Actor{}, Control{}, Image{})
};
scene.update();
} |
/*fn test_input()
{
match event {
winit::Event::Moved(x, y) => {
window.set_title(&format!("Window pos: ({:?}, {:?})", x, y))
}
winit::Event::Resized(w, h) => {
window.set_title(&format!("Window size: ({:?}, {:?})", w, h))
}
winit::Event::Closed => {
println!("Window close requested.");
process::exit(0);
}
winit::Event::DroppedFile(path_buf) => println!("PathBuf {:?}", path_buf),
winit::Event::ReceivedCharacter(received_char) => {
println!("Received Char {:?}", received_char)
}
winit::Event::Focused(focused) => println!("Window focused: {:?}.", focused),
winit::Event::KeyboardInput(element_state, scancode, virtual_key_code) => {
println!("Element State: {:?}, ScanCode: {:?}, Virtual Key Code: {:?}",
element_state,
scancode,
virtual_key_code);
match (virtual_key_code, element_state) {
(Some(winit::VirtualKeyCode::Escape), _) => process::exit(0),
(Some(winit::VirtualKeyCode::R), _) => {
// Resize should cause the window to "refresh"
match window.get_inner_size() {
Some(size) => window.set_inner_size(size.0, size.1),
None => (),
}
}
(Some(key), winit::ElementState::Pressed) => {
&self.keys_states.insert(key, true);
for processor in &self.input_processors {
processor.key_down(key.translate());
}
}
(Some(key), winit::ElementState::Released) => {
&self.keys_states.insert(key, false);
for processor in &self.input_processors {
processor.key_up(key.translate());
}
}
_ => {}
}
}
a @ winit::Event::MouseMoved(_) => {
println!("{:?}", a);
}
winit::Event::MouseWheel(mouse_scroll_delta, touch_phase) => {
println!("Mouse Scroll Delta {:?}, Touch Phase {:?}",
mouse_scroll_delta,
touch_phase)
}
winit::Event::MouseInput(element_state, mouse_button) => {
println!("Element State {:?}, Mouse Button {:?}",
element_state,
mouse_button)
}
winit::Event::TouchpadPressure(f, i) => println!("F {:?}, I {:?}", f, i),
winit::Event::Awakened => println!("Awakened"),
winit::Event::Refresh => println!("Window refresh callback triggered."),
winit::Event::Suspended(is_suspended) => println!("Is suspended {:?}", is_suspended),
winit::Event::Touch(touch) => println!("Touch {:?}", touch),
}
}*/
/**
* Test Game Example
*/
struct Game {
}
impl ApplicationListener for Game {
fn init(&self) {
println!("init");
}
fn update(&mut self) {
println!("update");
// Input
// Logic
// Physics
}
fn resize(&self, width: i32, height: i32) {
println!("Resize to {}x{}", width, height);
}
fn render(&self) {
println!("render");
// Animation
// Render
}
fn pause(&self) {
println!("pause");
}
fn resume(&self) {
println!("resume");
}
fn dispose(&self) {
println!("dispose");
}
fn exit(&mut self) {
println!("exit");
}
}
pub struct InputProcessorStuct;
impl InputProcessor for InputProcessorStuct {
fn process(&self, keyboard_event: InputEvent) {
match keyboard_event.event_type {
InputType::KeyDown => self.key_down(keyboard_event.key),
InputType::KeyUp => self.key_up(keyboard_event.key),
_ => (),
}
}
fn key_down(&self, key: Key) {
println!("Key down {:?}", key)
}
fn key_up(&self, key: Key) {
println!("Key up {:?}", key)
}
}
struct Actor {
}
struct Image {
}
struct Control {
}
impl Actable for Actor {
fn update(&self) {
println!("Updating self");
}
}
impl Drawable for Image {
fn draw(&self) {
println!("Drawing self");
}
}
impl InputProcessor for Control {
fn key_down(&self, key: Key)
{
println!("Keypushed down: {:?}", key)
}
fn key_up(&self, key: Key)
{
println!("Keypushed up: {:?}", key)
}
}
/*
Simple game TC
Game game = new Game(width, height, title);
Screen menu_screen = new Screen(title);
Button new_game = new Button();
ButtonActionHandler start_game = new ButtonActionHandler(new_game);
Stage main_stage = new Stage(new Viewport(new Camera()));
main_stage.add(Ball{radius, Mesh{material, color}});
main_stage.add(Line{vec![{x1,y1}, {x2,y2}]});
*/ | random_line_split |
|
lib.rs | extern crate anduin;
use anduin::logic::{Actable, lcm, Application};
use anduin::backends::vulkan;
use anduin::core;
use anduin::input::{InputProcessor, Key, InputType, InputEvent};
use anduin::graphics::Drawable;
use anduin::audio::{music, sound, PlaybackController};
use anduin::logic::ApplicationListener;
use anduin::files;
use std::thread::sleep;
use std::time::Duration;
use std::path::PathBuf;
use std::str::FromStr;
use std::fs;
fn create_test_vulkan_app() {
let mut vulkan_app = vulkan::VulkanApplication::init("Anduin", "desktop", Some(5), Box::new(Game{}));
println!("application created");
let game_loop = lcm::GameLoop::new();
println!("game_loop created");
vulkan_app.application.input.add_input_processor(Box::new(InputProcessorStuct{}));
println!("add_input_processor finished");
game_loop.run(&mut vulkan_app);
println!("game_loop runned");
vulkan_app.application.listener.as_mut().exit();
}
#[test]
fn open_file() {
/*for entry in fs::read_dir(".").expect("") {
let dir = entry.expect("");
println!("{:?}", dir.file_name());
println!("{:?}", dir.path());
}
let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
d.push("tests/resources/test.txt");
let path = d.to_str().expect("");*/
let path = "./tests/resources/test.txt";
println!("path {}", path);
let handle: files::FileHandle = files::Files::getFileHandle(path, files::PathType::Local);
let name: String = handle.name();
println!("name {}", name.as_str());
}
#[test]
fn play_sound() {
let music = music::Music::new("resources/music.ogg");
let sound = sound::Sound::new("resources/shot.wav");
music.play();
sound.play();
sleep(Duration::from_millis(5000));
}
#[test]
fn create_game_loop() {
let game_loop = lcm::GameLoop::new();
println!("Loop is created {:?}", game_loop);
}
#[test]
fn create_simple_scene() {
let scene = core::scene::Stage {root: core::scene::Node::new("Root Node")};
println!("Simple scene is created {:?}", scene);
}
fn create_simple_game()
{
let scene = core::scene::Stage {
root: core::scene::Node::build("Root Node", Actor{}, Control{}, Image{})
};
scene.update();
}
/*fn test_input()
{
match event {
winit::Event::Moved(x, y) => {
window.set_title(&format!("Window pos: ({:?}, {:?})", x, y))
}
winit::Event::Resized(w, h) => {
window.set_title(&format!("Window size: ({:?}, {:?})", w, h))
}
winit::Event::Closed => {
println!("Window close requested.");
process::exit(0);
}
winit::Event::DroppedFile(path_buf) => println!("PathBuf {:?}", path_buf),
winit::Event::ReceivedCharacter(received_char) => {
println!("Received Char {:?}", received_char)
}
winit::Event::Focused(focused) => println!("Window focused: {:?}.", focused),
winit::Event::KeyboardInput(element_state, scancode, virtual_key_code) => {
println!("Element State: {:?}, ScanCode: {:?}, Virtual Key Code: {:?}",
element_state,
scancode,
virtual_key_code);
match (virtual_key_code, element_state) {
(Some(winit::VirtualKeyCode::Escape), _) => process::exit(0),
(Some(winit::VirtualKeyCode::R), _) => {
// Resize should cause the window to "refresh"
match window.get_inner_size() {
Some(size) => window.set_inner_size(size.0, size.1),
None => (),
}
}
(Some(key), winit::ElementState::Pressed) => {
&self.keys_states.insert(key, true);
for processor in &self.input_processors {
processor.key_down(key.translate());
}
}
(Some(key), winit::ElementState::Released) => {
&self.keys_states.insert(key, false);
for processor in &self.input_processors {
processor.key_up(key.translate());
}
}
_ => {}
}
}
a @ winit::Event::MouseMoved(_) => {
println!("{:?}", a);
}
winit::Event::MouseWheel(mouse_scroll_delta, touch_phase) => {
println!("Mouse Scroll Delta {:?}, Touch Phase {:?}",
mouse_scroll_delta,
touch_phase)
}
winit::Event::MouseInput(element_state, mouse_button) => {
println!("Element State {:?}, Mouse Button {:?}",
element_state,
mouse_button)
}
winit::Event::TouchpadPressure(f, i) => println!("F {:?}, I {:?}", f, i),
winit::Event::Awakened => println!("Awakened"),
winit::Event::Refresh => println!("Window refresh callback triggered."),
winit::Event::Suspended(is_suspended) => println!("Is suspended {:?}", is_suspended),
winit::Event::Touch(touch) => println!("Touch {:?}", touch),
}
}*/
/**
* Test Game Example
*/
struct Game {
}
impl ApplicationListener for Game {
fn init(&self) {
println!("init");
}
fn update(&mut self) {
println!("update");
// Input
// Logic
// Physics
}
fn resize(&self, width: i32, height: i32) {
println!("Resize to {}x{}", width, height);
}
fn render(&self) {
println!("render");
// Animation
// Render
}
fn pause(&self) {
println!("pause");
}
fn resume(&self) {
println!("resume");
}
fn dispose(&self) {
println!("dispose");
}
fn exit(&mut self) {
println!("exit");
}
}
pub struct | ;
impl InputProcessor for InputProcessorStuct {
fn process(&self, keyboard_event: InputEvent) {
match keyboard_event.event_type {
InputType::KeyDown => self.key_down(keyboard_event.key),
InputType::KeyUp => self.key_up(keyboard_event.key),
_ => (),
}
}
fn key_down(&self, key: Key) {
println!("Key down {:?}", key)
}
fn key_up(&self, key: Key) {
println!("Key up {:?}", key)
}
}
struct Actor {
}
struct Image {
}
struct Control {
}
impl Actable for Actor {
fn update(&self) {
println!("Updating self");
}
}
impl Drawable for Image {
fn draw(&self) {
println!("Drawing self");
}
}
impl InputProcessor for Control {
fn key_down(&self, key: Key)
{
println!("Keypushed down: {:?}", key)
}
fn key_up(&self, key: Key)
{
println!("Keypushed up: {:?}", key)
}
}
/*
Simple game TC
Game game = new Game(width, height, title);
Screen menu_screen = new Screen(title);
Button new_game = new Button();
ButtonActionHandler start_game = new ButtonActionHandler(new_game);
Stage main_stage = new Stage(new Viewport(new Camera()));
main_stage.add(Ball{radius, Mesh{material, color}});
main_stage.add(Line{vec![{x1,y1}, {x2,y2}]});
*/
| InputProcessorStuct | identifier_name |
lib.rs | extern crate anduin;
use anduin::logic::{Actable, lcm, Application};
use anduin::backends::vulkan;
use anduin::core;
use anduin::input::{InputProcessor, Key, InputType, InputEvent};
use anduin::graphics::Drawable;
use anduin::audio::{music, sound, PlaybackController};
use anduin::logic::ApplicationListener;
use anduin::files;
use std::thread::sleep;
use std::time::Duration;
use std::path::PathBuf;
use std::str::FromStr;
use std::fs;
fn create_test_vulkan_app() {
let mut vulkan_app = vulkan::VulkanApplication::init("Anduin", "desktop", Some(5), Box::new(Game{}));
println!("application created");
let game_loop = lcm::GameLoop::new();
println!("game_loop created");
vulkan_app.application.input.add_input_processor(Box::new(InputProcessorStuct{}));
println!("add_input_processor finished");
game_loop.run(&mut vulkan_app);
println!("game_loop runned");
vulkan_app.application.listener.as_mut().exit();
}
#[test]
fn open_file() {
/*for entry in fs::read_dir(".").expect("") {
let dir = entry.expect("");
println!("{:?}", dir.file_name());
println!("{:?}", dir.path());
}
let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
d.push("tests/resources/test.txt");
let path = d.to_str().expect("");*/
let path = "./tests/resources/test.txt";
println!("path {}", path);
let handle: files::FileHandle = files::Files::getFileHandle(path, files::PathType::Local);
let name: String = handle.name();
println!("name {}", name.as_str());
}
#[test]
fn play_sound() {
let music = music::Music::new("resources/music.ogg");
let sound = sound::Sound::new("resources/shot.wav");
music.play();
sound.play();
sleep(Duration::from_millis(5000));
}
#[test]
fn create_game_loop() {
let game_loop = lcm::GameLoop::new();
println!("Loop is created {:?}", game_loop);
}
#[test]
fn create_simple_scene() {
let scene = core::scene::Stage {root: core::scene::Node::new("Root Node")};
println!("Simple scene is created {:?}", scene);
}
fn create_simple_game()
{
let scene = core::scene::Stage {
root: core::scene::Node::build("Root Node", Actor{}, Control{}, Image{})
};
scene.update();
}
/*fn test_input()
{
match event {
winit::Event::Moved(x, y) => {
window.set_title(&format!("Window pos: ({:?}, {:?})", x, y))
}
winit::Event::Resized(w, h) => {
window.set_title(&format!("Window size: ({:?}, {:?})", w, h))
}
winit::Event::Closed => {
println!("Window close requested.");
process::exit(0);
}
winit::Event::DroppedFile(path_buf) => println!("PathBuf {:?}", path_buf),
winit::Event::ReceivedCharacter(received_char) => {
println!("Received Char {:?}", received_char)
}
winit::Event::Focused(focused) => println!("Window focused: {:?}.", focused),
winit::Event::KeyboardInput(element_state, scancode, virtual_key_code) => {
println!("Element State: {:?}, ScanCode: {:?}, Virtual Key Code: {:?}",
element_state,
scancode,
virtual_key_code);
match (virtual_key_code, element_state) {
(Some(winit::VirtualKeyCode::Escape), _) => process::exit(0),
(Some(winit::VirtualKeyCode::R), _) => {
// Resize should cause the window to "refresh"
match window.get_inner_size() {
Some(size) => window.set_inner_size(size.0, size.1),
None => (),
}
}
(Some(key), winit::ElementState::Pressed) => {
&self.keys_states.insert(key, true);
for processor in &self.input_processors {
processor.key_down(key.translate());
}
}
(Some(key), winit::ElementState::Released) => {
&self.keys_states.insert(key, false);
for processor in &self.input_processors {
processor.key_up(key.translate());
}
}
_ => {}
}
}
a @ winit::Event::MouseMoved(_) => {
println!("{:?}", a);
}
winit::Event::MouseWheel(mouse_scroll_delta, touch_phase) => {
println!("Mouse Scroll Delta {:?}, Touch Phase {:?}",
mouse_scroll_delta,
touch_phase)
}
winit::Event::MouseInput(element_state, mouse_button) => {
println!("Element State {:?}, Mouse Button {:?}",
element_state,
mouse_button)
}
winit::Event::TouchpadPressure(f, i) => println!("F {:?}, I {:?}", f, i),
winit::Event::Awakened => println!("Awakened"),
winit::Event::Refresh => println!("Window refresh callback triggered."),
winit::Event::Suspended(is_suspended) => println!("Is suspended {:?}", is_suspended),
winit::Event::Touch(touch) => println!("Touch {:?}", touch),
}
}*/
/**
* Test Game Example
*/
struct Game {
}
impl ApplicationListener for Game {
fn init(&self) {
println!("init");
}
fn update(&mut self) {
println!("update");
// Input
// Logic
// Physics
}
fn resize(&self, width: i32, height: i32) {
println!("Resize to {}x{}", width, height);
}
fn render(&self) {
println!("render");
// Animation
// Render
}
fn pause(&self) {
println!("pause");
}
fn resume(&self) {
println!("resume");
}
fn dispose(&self) {
println!("dispose");
}
fn exit(&mut self) {
println!("exit");
}
}
pub struct InputProcessorStuct;
impl InputProcessor for InputProcessorStuct {
fn process(&self, keyboard_event: InputEvent) |
fn key_down(&self, key: Key) {
println!("Key down {:?}", key)
}
fn key_up(&self, key: Key) {
println!("Key up {:?}", key)
}
}
struct Actor {
}
struct Image {
}
struct Control {
}
impl Actable for Actor {
fn update(&self) {
println!("Updating self");
}
}
impl Drawable for Image {
fn draw(&self) {
println!("Drawing self");
}
}
impl InputProcessor for Control {
fn key_down(&self, key: Key)
{
println!("Keypushed down: {:?}", key)
}
fn key_up(&self, key: Key)
{
println!("Keypushed up: {:?}", key)
}
}
/*
Simple game TC
Game game = new Game(width, height, title);
Screen menu_screen = new Screen(title);
Button new_game = new Button();
ButtonActionHandler start_game = new ButtonActionHandler(new_game);
Stage main_stage = new Stage(new Viewport(new Camera()));
main_stage.add(Ball{radius, Mesh{material, color}});
main_stage.add(Line{vec![{x1,y1}, {x2,y2}]});
*/
| {
match keyboard_event.event_type {
InputType::KeyDown => self.key_down(keyboard_event.key),
InputType::KeyUp => self.key_up(keyboard_event.key),
_ => (),
}
} | identifier_body |
aarch64.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.
use abi::call::{FnType, ArgType, Reg, RegKind, Uniform};
use abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>)
-> Option<Uniform>
where Ty: TyLayoutMethods<'a, C> + Copy,
C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout
{
arg.layout.homogeneous_aggregate(cx).and_then(|unit| {
let size = arg.layout.size;
// Ensure we have at most four uniquely addressable members.
if size > unit.size.checked_mul(4, cx).unwrap() {
return None;
}
let valid_unit = match unit.kind {
RegKind::Integer => false,
RegKind::Float => true,
RegKind::Vector => size.bits() == 64 || size.bits() == 128
};
if valid_unit {
Some(Uniform {
unit,
total: size
})
} else {
None
}
})
}
fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<'a, Ty>)
where Ty: TyLayoutMethods<'a, C> + Copy,
C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout
| };
ret.cast_to(Uniform {
unit,
total: size
});
return;
}
ret.make_indirect();
}
fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>)
where Ty: TyLayoutMethods<'a, C> + Copy,
C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout
{
if!arg.layout.is_aggregate() {
arg.extend_integer_width_to(32);
return;
}
if let Some(uniform) = is_homogeneous_aggregate(cx, arg) {
arg.cast_to(uniform);
return;
}
let size = arg.layout.size;
let bits = size.bits();
if bits <= 128 {
let unit = if bits <= 8 {
Reg::i8()
} else if bits <= 16 {
Reg::i16()
} else if bits <= 32 {
Reg::i32()
} else {
Reg::i64()
};
arg.cast_to(Uniform {
unit,
total: size
});
return;
}
arg.make_indirect();
}
pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType<'a, Ty>)
where Ty: TyLayoutMethods<'a, C> + Copy,
C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout
{
if!fty.ret.is_ignore() {
classify_ret_ty(cx, &mut fty.ret);
}
for arg in &mut fty.args {
if arg.is_ignore() { continue; }
classify_arg_ty(cx, arg);
}
}
| {
if !ret.layout.is_aggregate() {
ret.extend_integer_width_to(32);
return;
}
if let Some(uniform) = is_homogeneous_aggregate(cx, ret) {
ret.cast_to(uniform);
return;
}
let size = ret.layout.size;
let bits = size.bits();
if bits <= 128 {
let unit = if bits <= 8 {
Reg::i8()
} else if bits <= 16 {
Reg::i16()
} else if bits <= 32 {
Reg::i32()
} else {
Reg::i64() | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.