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 |
---|---|---|---|---|
perlin_2d_colors.rs | #![feature(old_path)]
extern crate image;
extern crate noise; | use std::num::Float;
fn to_color(value: f64, factor: f64) -> u8 {
let mut v = value.abs();
if v > 255.0 {
v = 255.0
}
(v * factor) as u8
}
fn main() {
let amp = 255.0;
let f = 0.01;
let noise_r = new_perlin_noise_2d(rand::random(), amp, f, 6);
let noise_g = new_perlin_noise_2d(rand::random(), amp, f, 6);
let noise_b = new_perlin_noise_2d(rand::random(), amp, f, 6);
let image = ImageBuffer::from_fn(128, 128, |x: u32, y: u32| {
let p = (x as f64, y as f64);
Rgb([
to_color(noise_r.value(p), 1.0),
to_color(noise_g.value(p), 1.0),
to_color(noise_b.value(p), 1.0)
])
});
match image.save(&Path::new("output.png")) {
Err(e) => panic!("Could not write file! {}", e),
Ok(..) => {},
};
} | extern crate rand;
use image::{ImageBuffer, Rgb};
use noise::Noise;
use noise::blocks::new_perlin_noise_2d; | random_line_split |
perlin_2d_colors.rs | #![feature(old_path)]
extern crate image;
extern crate noise;
extern crate rand;
use image::{ImageBuffer, Rgb};
use noise::Noise;
use noise::blocks::new_perlin_noise_2d;
use std::num::Float;
fn to_color(value: f64, factor: f64) -> u8 {
let mut v = value.abs();
if v > 255.0 {
v = 255.0
}
(v * factor) as u8
}
fn | () {
let amp = 255.0;
let f = 0.01;
let noise_r = new_perlin_noise_2d(rand::random(), amp, f, 6);
let noise_g = new_perlin_noise_2d(rand::random(), amp, f, 6);
let noise_b = new_perlin_noise_2d(rand::random(), amp, f, 6);
let image = ImageBuffer::from_fn(128, 128, |x: u32, y: u32| {
let p = (x as f64, y as f64);
Rgb([
to_color(noise_r.value(p), 1.0),
to_color(noise_g.value(p), 1.0),
to_color(noise_b.value(p), 1.0)
])
});
match image.save(&Path::new("output.png")) {
Err(e) => panic!("Could not write file! {}", e),
Ok(..) => {},
};
}
| main | identifier_name |
perlin_2d_colors.rs | #![feature(old_path)]
extern crate image;
extern crate noise;
extern crate rand;
use image::{ImageBuffer, Rgb};
use noise::Noise;
use noise::blocks::new_perlin_noise_2d;
use std::num::Float;
fn to_color(value: f64, factor: f64) -> u8 |
fn main() {
let amp = 255.0;
let f = 0.01;
let noise_r = new_perlin_noise_2d(rand::random(), amp, f, 6);
let noise_g = new_perlin_noise_2d(rand::random(), amp, f, 6);
let noise_b = new_perlin_noise_2d(rand::random(), amp, f, 6);
let image = ImageBuffer::from_fn(128, 128, |x: u32, y: u32| {
let p = (x as f64, y as f64);
Rgb([
to_color(noise_r.value(p), 1.0),
to_color(noise_g.value(p), 1.0),
to_color(noise_b.value(p), 1.0)
])
});
match image.save(&Path::new("output.png")) {
Err(e) => panic!("Could not write file! {}", e),
Ok(..) => {},
};
}
| {
let mut v = value.abs();
if v > 255.0 {
v = 255.0
}
(v * factor) as u8
} | identifier_body |
perlin_2d_colors.rs | #![feature(old_path)]
extern crate image;
extern crate noise;
extern crate rand;
use image::{ImageBuffer, Rgb};
use noise::Noise;
use noise::blocks::new_perlin_noise_2d;
use std::num::Float;
fn to_color(value: f64, factor: f64) -> u8 {
let mut v = value.abs();
if v > 255.0 |
(v * factor) as u8
}
fn main() {
let amp = 255.0;
let f = 0.01;
let noise_r = new_perlin_noise_2d(rand::random(), amp, f, 6);
let noise_g = new_perlin_noise_2d(rand::random(), amp, f, 6);
let noise_b = new_perlin_noise_2d(rand::random(), amp, f, 6);
let image = ImageBuffer::from_fn(128, 128, |x: u32, y: u32| {
let p = (x as f64, y as f64);
Rgb([
to_color(noise_r.value(p), 1.0),
to_color(noise_g.value(p), 1.0),
to_color(noise_b.value(p), 1.0)
])
});
match image.save(&Path::new("output.png")) {
Err(e) => panic!("Could not write file! {}", e),
Ok(..) => {},
};
}
| {
v = 255.0
} | conditional_block |
main.rs | #![feature(plugin, rustc_private)]
#![plugin(docopt_macros)]
extern crate cargo;
extern crate docopt;
extern crate graphviz;
extern crate rustc_serialize;
use cargo::core::{Resolve, SourceId, PackageId};
use graphviz as dot;
use std::borrow::{Cow};
use std::convert::Into;
use std::env;
use std::io;
use std::io::Write;
use std::fs::File;
use std::path::{Path, PathBuf};
docopt!(Flags, "
Generate a graph of package dependencies in graphviz format | cargo dot --help
Options:
-h, --help Show this message
-V, --version Print version info and exit
--lock-file=FILE Specify location of input file, default \"Cargo.lock\"
--dot-file=FILE Output to file, default prints to stdout
--source-labels Use sources for the label instead of package names
");
fn main() {
let mut argv: Vec<String> = env::args().collect();
if argv.len() > 0 {
argv[0] = "cargo".to_string();
}
let flags: Flags = Flags::docopt()
// cargo passes the exe name first, so we skip it
.argv(argv.into_iter())
.version(Some("0.2".to_string()))
.decode()
.unwrap_or_else(|e|
e.exit());
let dot_f_flag = if flags.flag_dot_file.is_empty() { None } else { Some(flags.flag_dot_file) };
let source_labels = flags.flag_source_labels;
let lock_path = unless_empty(flags.flag_lock_file, "Cargo.lock");
let lock_path = Path::new(&lock_path);
let lock_path_buf = absolutize(lock_path.to_path_buf());
let lock_path = lock_path_buf.as_path();
let proj_dir = lock_path.parent().unwrap(); // TODO: check for None
let src_id = SourceId::for_path(&proj_dir).unwrap();
let resolved = cargo::ops::load_lockfile(&lock_path, &src_id).unwrap()
.expect("Lock file not found.");
let mut graph = Graph::with_root(resolved.root(), source_labels);
graph.add_dependencies(&resolved);
match dot_f_flag {
None => graph.render_to(&mut io::stdout()),
Some(dot_file) => graph.render_to(&mut File::create(&Path::new(&dot_file)).unwrap())
};
}
fn absolutize(pb: PathBuf) -> PathBuf {
if pb.as_path().is_absolute() {
pb
} else {
std::env::current_dir().unwrap().join(&pb.as_path()).clone()
}
}
fn unless_empty(s: String, default: &str) -> String {
if s.is_empty() {
default.to_string()
} else {
s
}
}
pub type Nd = usize;
pub type Ed = (usize, usize);
pub struct Graph<'a> {
nodes: Vec<&'a PackageId>,
edges: Vec<Ed>,
source_labels: bool
}
impl<'a> Graph<'a> {
pub fn with_root(root: &PackageId, source_labels: bool) -> Graph {
Graph { nodes: vec![root], edges: vec![], source_labels: source_labels }
}
pub fn add_dependencies(&mut self, resolved: &'a Resolve) {
for crat in resolved.iter() {
match resolved.deps(crat) {
Some(crate_deps) => {
let idl = self.find_or_add(crat);
for dep in crate_deps {
let idr = self.find_or_add(dep);
self.edges.push((idl, idr));
};
},
None => { }
}
}
}
fn find_or_add(&mut self, new: &'a PackageId) -> usize {
for (i, id) in self.nodes.iter().enumerate() {
if *id == new {
return i
}
}
self.nodes.push(new);
self.nodes.len() - 1
}
pub fn render_to<W:Write>(&'a self, output: &mut W) {
match dot::render(self, output) {
Ok(_) => {},
Err(e) => panic!("error rendering graph: {}", e)
}
}
}
impl<'a> dot::Labeller<'a, Nd, Ed> for Graph<'a> {
fn graph_id(&self) -> dot::Id<'a> {
dot::Id::new(self.nodes[0].name()).unwrap_or(dot::Id::new("dependencies").unwrap())
}
fn node_id(&self, n: &Nd) -> dot::Id {
// unwrap is safe because N######## is a valid graphviz id
dot::Id::new(format!("N{}", *n)).unwrap()
}
fn node_label(&'a self, i: &Nd) -> dot::LabelText<'a> {
if!self.source_labels {
dot::LabelText::LabelStr(self.nodes[*i].name().into())
} else {
dot::LabelText::LabelStr(self.nodes[*i].source_id().url().to_string().into())
}
}
}
impl<'a> dot::GraphWalk<'a, Nd, Ed> for Graph<'a> {
fn nodes(&self) -> dot::Nodes<'a,Nd> {
(0..self.nodes.len()).collect()
}
fn edges(&self) -> dot::Edges<Ed> {
Cow::Borrowed(&self.edges[..])
}
fn source(&self, &(s, _): &Ed) -> Nd { s }
fn target(&self, &(_, t): &Ed) -> Nd { t }
} |
Usage: cargo dot [options] | random_line_split |
main.rs | #![feature(plugin, rustc_private)]
#![plugin(docopt_macros)]
extern crate cargo;
extern crate docopt;
extern crate graphviz;
extern crate rustc_serialize;
use cargo::core::{Resolve, SourceId, PackageId};
use graphviz as dot;
use std::borrow::{Cow};
use std::convert::Into;
use std::env;
use std::io;
use std::io::Write;
use std::fs::File;
use std::path::{Path, PathBuf};
docopt!(Flags, "
Generate a graph of package dependencies in graphviz format
Usage: cargo dot [options]
cargo dot --help
Options:
-h, --help Show this message
-V, --version Print version info and exit
--lock-file=FILE Specify location of input file, default \"Cargo.lock\"
--dot-file=FILE Output to file, default prints to stdout
--source-labels Use sources for the label instead of package names
");
fn main() |
let proj_dir = lock_path.parent().unwrap(); // TODO: check for None
let src_id = SourceId::for_path(&proj_dir).unwrap();
let resolved = cargo::ops::load_lockfile(&lock_path, &src_id).unwrap()
.expect("Lock file not found.");
let mut graph = Graph::with_root(resolved.root(), source_labels);
graph.add_dependencies(&resolved);
match dot_f_flag {
None => graph.render_to(&mut io::stdout()),
Some(dot_file) => graph.render_to(&mut File::create(&Path::new(&dot_file)).unwrap())
};
}
fn absolutize(pb: PathBuf) -> PathBuf {
if pb.as_path().is_absolute() {
pb
} else {
std::env::current_dir().unwrap().join(&pb.as_path()).clone()
}
}
fn unless_empty(s: String, default: &str) -> String {
if s.is_empty() {
default.to_string()
} else {
s
}
}
pub type Nd = usize;
pub type Ed = (usize, usize);
pub struct Graph<'a> {
nodes: Vec<&'a PackageId>,
edges: Vec<Ed>,
source_labels: bool
}
impl<'a> Graph<'a> {
pub fn with_root(root: &PackageId, source_labels: bool) -> Graph {
Graph { nodes: vec![root], edges: vec![], source_labels: source_labels }
}
pub fn add_dependencies(&mut self, resolved: &'a Resolve) {
for crat in resolved.iter() {
match resolved.deps(crat) {
Some(crate_deps) => {
let idl = self.find_or_add(crat);
for dep in crate_deps {
let idr = self.find_or_add(dep);
self.edges.push((idl, idr));
};
},
None => { }
}
}
}
fn find_or_add(&mut self, new: &'a PackageId) -> usize {
for (i, id) in self.nodes.iter().enumerate() {
if *id == new {
return i
}
}
self.nodes.push(new);
self.nodes.len() - 1
}
pub fn render_to<W:Write>(&'a self, output: &mut W) {
match dot::render(self, output) {
Ok(_) => {},
Err(e) => panic!("error rendering graph: {}", e)
}
}
}
impl<'a> dot::Labeller<'a, Nd, Ed> for Graph<'a> {
fn graph_id(&self) -> dot::Id<'a> {
dot::Id::new(self.nodes[0].name()).unwrap_or(dot::Id::new("dependencies").unwrap())
}
fn node_id(&self, n: &Nd) -> dot::Id {
// unwrap is safe because N######## is a valid graphviz id
dot::Id::new(format!("N{}", *n)).unwrap()
}
fn node_label(&'a self, i: &Nd) -> dot::LabelText<'a> {
if!self.source_labels {
dot::LabelText::LabelStr(self.nodes[*i].name().into())
} else {
dot::LabelText::LabelStr(self.nodes[*i].source_id().url().to_string().into())
}
}
}
impl<'a> dot::GraphWalk<'a, Nd, Ed> for Graph<'a> {
fn nodes(&self) -> dot::Nodes<'a,Nd> {
(0..self.nodes.len()).collect()
}
fn edges(&self) -> dot::Edges<Ed> {
Cow::Borrowed(&self.edges[..])
}
fn source(&self, &(s, _): &Ed) -> Nd { s }
fn target(&self, &(_, t): &Ed) -> Nd { t }
}
| {
let mut argv: Vec<String> = env::args().collect();
if argv.len() > 0 {
argv[0] = "cargo".to_string();
}
let flags: Flags = Flags::docopt()
// cargo passes the exe name first, so we skip it
.argv(argv.into_iter())
.version(Some("0.2".to_string()))
.decode()
.unwrap_or_else(|e|
e.exit());
let dot_f_flag = if flags.flag_dot_file.is_empty() { None } else { Some(flags.flag_dot_file) };
let source_labels = flags.flag_source_labels;
let lock_path = unless_empty(flags.flag_lock_file, "Cargo.lock");
let lock_path = Path::new(&lock_path);
let lock_path_buf = absolutize(lock_path.to_path_buf());
let lock_path = lock_path_buf.as_path(); | identifier_body |
main.rs | #![feature(plugin, rustc_private)]
#![plugin(docopt_macros)]
extern crate cargo;
extern crate docopt;
extern crate graphviz;
extern crate rustc_serialize;
use cargo::core::{Resolve, SourceId, PackageId};
use graphviz as dot;
use std::borrow::{Cow};
use std::convert::Into;
use std::env;
use std::io;
use std::io::Write;
use std::fs::File;
use std::path::{Path, PathBuf};
docopt!(Flags, "
Generate a graph of package dependencies in graphviz format
Usage: cargo dot [options]
cargo dot --help
Options:
-h, --help Show this message
-V, --version Print version info and exit
--lock-file=FILE Specify location of input file, default \"Cargo.lock\"
--dot-file=FILE Output to file, default prints to stdout
--source-labels Use sources for the label instead of package names
");
fn main() {
let mut argv: Vec<String> = env::args().collect();
if argv.len() > 0 {
argv[0] = "cargo".to_string();
}
let flags: Flags = Flags::docopt()
// cargo passes the exe name first, so we skip it
.argv(argv.into_iter())
.version(Some("0.2".to_string()))
.decode()
.unwrap_or_else(|e|
e.exit());
let dot_f_flag = if flags.flag_dot_file.is_empty() { None } else { Some(flags.flag_dot_file) };
let source_labels = flags.flag_source_labels;
let lock_path = unless_empty(flags.flag_lock_file, "Cargo.lock");
let lock_path = Path::new(&lock_path);
let lock_path_buf = absolutize(lock_path.to_path_buf());
let lock_path = lock_path_buf.as_path();
let proj_dir = lock_path.parent().unwrap(); // TODO: check for None
let src_id = SourceId::for_path(&proj_dir).unwrap();
let resolved = cargo::ops::load_lockfile(&lock_path, &src_id).unwrap()
.expect("Lock file not found.");
let mut graph = Graph::with_root(resolved.root(), source_labels);
graph.add_dependencies(&resolved);
match dot_f_flag {
None => graph.render_to(&mut io::stdout()),
Some(dot_file) => graph.render_to(&mut File::create(&Path::new(&dot_file)).unwrap())
};
}
fn absolutize(pb: PathBuf) -> PathBuf {
if pb.as_path().is_absolute() {
pb
} else {
std::env::current_dir().unwrap().join(&pb.as_path()).clone()
}
}
fn unless_empty(s: String, default: &str) -> String {
if s.is_empty() {
default.to_string()
} else {
s
}
}
pub type Nd = usize;
pub type Ed = (usize, usize);
pub struct Graph<'a> {
nodes: Vec<&'a PackageId>,
edges: Vec<Ed>,
source_labels: bool
}
impl<'a> Graph<'a> {
pub fn with_root(root: &PackageId, source_labels: bool) -> Graph {
Graph { nodes: vec![root], edges: vec![], source_labels: source_labels }
}
pub fn add_dependencies(&mut self, resolved: &'a Resolve) {
for crat in resolved.iter() {
match resolved.deps(crat) {
Some(crate_deps) => {
let idl = self.find_or_add(crat);
for dep in crate_deps {
let idr = self.find_or_add(dep);
self.edges.push((idl, idr));
};
},
None => { }
}
}
}
fn find_or_add(&mut self, new: &'a PackageId) -> usize {
for (i, id) in self.nodes.iter().enumerate() {
if *id == new {
return i
}
}
self.nodes.push(new);
self.nodes.len() - 1
}
pub fn render_to<W:Write>(&'a self, output: &mut W) {
match dot::render(self, output) {
Ok(_) => {},
Err(e) => panic!("error rendering graph: {}", e)
}
}
}
impl<'a> dot::Labeller<'a, Nd, Ed> for Graph<'a> {
fn graph_id(&self) -> dot::Id<'a> {
dot::Id::new(self.nodes[0].name()).unwrap_or(dot::Id::new("dependencies").unwrap())
}
fn node_id(&self, n: &Nd) -> dot::Id {
// unwrap is safe because N######## is a valid graphviz id
dot::Id::new(format!("N{}", *n)).unwrap()
}
fn node_label(&'a self, i: &Nd) -> dot::LabelText<'a> {
if!self.source_labels {
dot::LabelText::LabelStr(self.nodes[*i].name().into())
} else {
dot::LabelText::LabelStr(self.nodes[*i].source_id().url().to_string().into())
}
}
}
impl<'a> dot::GraphWalk<'a, Nd, Ed> for Graph<'a> {
fn nodes(&self) -> dot::Nodes<'a,Nd> {
(0..self.nodes.len()).collect()
}
fn edges(&self) -> dot::Edges<Ed> {
Cow::Borrowed(&self.edges[..])
}
fn | (&self, &(s, _): &Ed) -> Nd { s }
fn target(&self, &(_, t): &Ed) -> Nd { t }
}
| source | identifier_name |
main.rs | extern crate rand;
use rand::Rng;
fn | () {
loop {
let (player_one_score, player_two_score) = roll_for_both_players();
if player_one_score!= player_two_score {
if player_one_score > player_two_score {
println!("Player 1 wins!");
} else {
println!("Player 2 wins!");
}
return;
}
}
}
fn roll_for_both_players() -> (i32, i32) {
let mut player_one_score = 0;
let mut player_two_score = 0;
for _ in 0..3 {
let roll_for_player_one = rand::thread_rng().gen_range(1, 7);
let roll_for_player_two = rand::thread_rng().gen_range(1, 7);
println!("Player one rolled {}", roll_for_player_one);
println!("Player two rolled {}", roll_for_player_two);
player_one_score += roll_for_player_one;
player_two_score += roll_for_player_two;
}
(player_one_score, player_two_score)
}
| main | identifier_name |
main.rs | extern crate rand;
use rand::Rng;
fn main() {
loop {
let (player_one_score, player_two_score) = roll_for_both_players();
if player_one_score!= player_two_score |
}
}
fn roll_for_both_players() -> (i32, i32) {
let mut player_one_score = 0;
let mut player_two_score = 0;
for _ in 0..3 {
let roll_for_player_one = rand::thread_rng().gen_range(1, 7);
let roll_for_player_two = rand::thread_rng().gen_range(1, 7);
println!("Player one rolled {}", roll_for_player_one);
println!("Player two rolled {}", roll_for_player_two);
player_one_score += roll_for_player_one;
player_two_score += roll_for_player_two;
}
(player_one_score, player_two_score)
}
| {
if player_one_score > player_two_score {
println!("Player 1 wins!");
} else {
println!("Player 2 wins!");
}
return;
} | conditional_block |
main.rs | extern crate rand;
use rand::Rng;
fn main() {
loop {
let (player_one_score, player_two_score) = roll_for_both_players();
if player_one_score!= player_two_score {
if player_one_score > player_two_score {
println!("Player 1 wins!");
} else { | }
}
}
fn roll_for_both_players() -> (i32, i32) {
let mut player_one_score = 0;
let mut player_two_score = 0;
for _ in 0..3 {
let roll_for_player_one = rand::thread_rng().gen_range(1, 7);
let roll_for_player_two = rand::thread_rng().gen_range(1, 7);
println!("Player one rolled {}", roll_for_player_one);
println!("Player two rolled {}", roll_for_player_two);
player_one_score += roll_for_player_one;
player_two_score += roll_for_player_two;
}
(player_one_score, player_two_score)
} | println!("Player 2 wins!");
}
return; | random_line_split |
main.rs | extern crate rand;
use rand::Rng;
fn main() |
fn roll_for_both_players() -> (i32, i32) {
let mut player_one_score = 0;
let mut player_two_score = 0;
for _ in 0..3 {
let roll_for_player_one = rand::thread_rng().gen_range(1, 7);
let roll_for_player_two = rand::thread_rng().gen_range(1, 7);
println!("Player one rolled {}", roll_for_player_one);
println!("Player two rolled {}", roll_for_player_two);
player_one_score += roll_for_player_one;
player_two_score += roll_for_player_two;
}
(player_one_score, player_two_score)
}
| {
loop {
let (player_one_score, player_two_score) = roll_for_both_players();
if player_one_score != player_two_score {
if player_one_score > player_two_score {
println!("Player 1 wins!");
} else {
println!("Player 2 wins!");
}
return;
}
}
} | identifier_body |
graphs.rs | extern crate rand;
extern crate timely;
extern crate differential_dataflow;
use std::rc::Rc;
use rand::{Rng, SeedableRng, StdRng};
use timely::dataflow::*;
use differential_dataflow::input::Input;
use differential_dataflow::Collection;
use differential_dataflow::operators::*;
use differential_dataflow::trace::Trace;
use differential_dataflow::operators::arrange::ArrangeByKey;
use differential_dataflow::operators::arrange::ArrangeBySelf;
use differential_dataflow::trace::implementations::spine_fueled::Spine;
type Node = usize;
use differential_dataflow::trace::implementations::ord::OrdValBatch;
// use differential_dataflow::trace::implementations::ord::OrdValSpine;
// type GraphTrace<N> = Spine<usize, N, (), isize, Rc<GraphBatch<N>>>;
type GraphTrace = Spine<Node, Node, (), isize, Rc<OrdValBatch<Node, Node, (), isize>>>;
fn main() {
let nodes: usize = std::env::args().nth(1).unwrap().parse().unwrap();
let edges: usize = std::env::args().nth(2).unwrap().parse().unwrap();
// Our setting involves four read query types, and two updatable base relations.
//
// Q1: Point lookup: reads "state" associated with a node.
// Q2: One-hop lookup: reads "state" associated with neighbors of a node.
// Q3: Two-hop lookup: reads "state" associated with n-of-n's of a node.
// Q4: Shortest path: reports hop count between two query nodes.
//
// R1: "State": a pair of (node, T) for some type T that I don't currently know.
// R2: "Graph": pairs (node, node) indicating linkage between the two nodes.
timely::execute_from_args(std::env::args().skip(3), move |worker| {
let index = worker.index();
let peers = worker.peers();
let timer = ::std::time::Instant::now();
let (mut graph, mut trace) = worker.dataflow(|scope| {
let (graph_input, graph) = scope.new_collection();
let graph_indexed = graph.arrange_by_key();
// let graph_indexed = graph.arrange_by_key();
(graph_input, graph_indexed.trace)
});
let seed: &[_] = &[1, 2, 3, index];
let mut rng1: StdRng = SeedableRng::from_seed(seed); // rng for edge additions
// let mut rng2: StdRng = SeedableRng::from_seed(seed); // rng for edge deletions
if index == 0 { println!("performing workload on random graph with {} nodes, {} edges:", nodes, edges); }
let worker_edges = edges/peers + if index < (edges % peers) { 1 } else { 0 };
for _ in 0.. worker_edges {
graph.insert((rng1.gen_range(0, nodes) as Node, rng1.gen_range(0, nodes) as Node));
}
graph.close();
while worker.step() { }
if index == 0 { println!("{:?}\tgraph loaded", timer.elapsed()); }
// Phase 2: Reachability.
let mut roots = worker.dataflow(|scope| {
let (roots_input, roots) = scope.new_collection();
reach(&mut trace, roots);
roots_input
});
if index == 0 { roots.insert(0); }
roots.close();
while worker.step() { }
if index == 0 { println!("{:?}\treach complete", timer.elapsed()); }
// Phase 3: Breadth-first distance labeling.
let mut roots = worker.dataflow(|scope| {
let (roots_input, roots) = scope.new_collection();
bfs(&mut trace, roots);
roots_input
});
if index == 0 { roots.insert(0); }
roots.close();
while worker.step() { }
if index == 0 { println!("{:?}\tbfs complete", timer.elapsed()); }
}).unwrap();
}
// use differential_dataflow::trace::implementations::ord::OrdValSpine;
use differential_dataflow::operators::arrange::TraceAgent;
type TraceHandle = TraceAgent<Node, Node, (), isize, GraphTrace>;
fn reach<G: Scope<Timestamp = ()>> (
graph: &mut TraceHandle,
roots: Collection<G, Node>
) -> Collection<G, Node> |
fn bfs<G: Scope<Timestamp = ()>> (
graph: &mut TraceHandle,
roots: Collection<G, Node>
) -> Collection<G, (Node, u32)> {
let graph = graph.import(&roots.scope());
let roots = roots.map(|r| (r,0));
roots.iterate(|inner| {
let graph = graph.enter(&inner.scope());
let roots = roots.enter(&inner.scope());
graph.join_map(&inner, |_src,&dest,&dist| (dest, dist+1))
.concat(&roots)
.reduce(|_key, input, output| output.push((*input[0].0,1)))
})
}
// fn connected_components<G: Scope<Timestamp = ()>>(
// graph: &mut TraceHandle<Node>
// ) -> Collection<G, (Node, Node)> {
// // each edge (x,y) means that we need at least a label for the min of x and y.
// let nodes =
// graph
// .as_collection(|&k,&v| {
// let min = std::cmp::min(k,v);
// (min, min)
// })
// .consolidate();
// // each edge should exist in both directions.
// let edges = edges.map_in_place(|x| mem::swap(&mut x.0, &mut x.1))
// .concat(&edges);
// // don't actually use these labels, just grab the type
// nodes.filter(|_| false)
// .iterate(|inner| {
// let edges = edges.enter(&inner.scope());
// let nodes = nodes.enter_at(&inner.scope(), |r| 256 * (64 - r.1.leading_zeros() as u64));
// inner.join_map(&edges, |_k,l,d| (*d,*l))
// .concat(&nodes)
// .group(|_, s, t| { t.push((*s[0].0, 1)); } )
// })
// }
| {
let graph = graph.import(&roots.scope());
roots.iterate(|inner| {
let graph = graph.enter(&inner.scope());
let roots = roots.enter(&inner.scope());
// let reach = inner.concat(&roots).distinct_total().arrange_by_self();
// graph.join_core(&reach, |_src,&dst,&()| Some(dst))
graph.join_core(&inner.arrange_by_self(), |_src,&dst,&()| Some(dst))
.concat(&roots)
.distinct_total()
})
} | identifier_body |
graphs.rs | extern crate rand;
extern crate timely;
extern crate differential_dataflow;
use std::rc::Rc;
use rand::{Rng, SeedableRng, StdRng};
use timely::dataflow::*;
use differential_dataflow::input::Input;
use differential_dataflow::Collection;
use differential_dataflow::operators::*;
use differential_dataflow::trace::Trace;
use differential_dataflow::operators::arrange::ArrangeByKey;
use differential_dataflow::operators::arrange::ArrangeBySelf;
use differential_dataflow::trace::implementations::spine_fueled::Spine;
type Node = usize;
use differential_dataflow::trace::implementations::ord::OrdValBatch;
// use differential_dataflow::trace::implementations::ord::OrdValSpine;
// type GraphTrace<N> = Spine<usize, N, (), isize, Rc<GraphBatch<N>>>;
type GraphTrace = Spine<Node, Node, (), isize, Rc<OrdValBatch<Node, Node, (), isize>>>;
fn main() {
let nodes: usize = std::env::args().nth(1).unwrap().parse().unwrap();
let edges: usize = std::env::args().nth(2).unwrap().parse().unwrap();
// Our setting involves four read query types, and two updatable base relations.
//
// Q1: Point lookup: reads "state" associated with a node.
// Q2: One-hop lookup: reads "state" associated with neighbors of a node.
// Q3: Two-hop lookup: reads "state" associated with n-of-n's of a node.
// Q4: Shortest path: reports hop count between two query nodes.
//
// R1: "State": a pair of (node, T) for some type T that I don't currently know.
// R2: "Graph": pairs (node, node) indicating linkage between the two nodes.
timely::execute_from_args(std::env::args().skip(3), move |worker| {
| let (graph_input, graph) = scope.new_collection();
let graph_indexed = graph.arrange_by_key();
// let graph_indexed = graph.arrange_by_key();
(graph_input, graph_indexed.trace)
});
let seed: &[_] = &[1, 2, 3, index];
let mut rng1: StdRng = SeedableRng::from_seed(seed); // rng for edge additions
// let mut rng2: StdRng = SeedableRng::from_seed(seed); // rng for edge deletions
if index == 0 { println!("performing workload on random graph with {} nodes, {} edges:", nodes, edges); }
let worker_edges = edges/peers + if index < (edges % peers) { 1 } else { 0 };
for _ in 0.. worker_edges {
graph.insert((rng1.gen_range(0, nodes) as Node, rng1.gen_range(0, nodes) as Node));
}
graph.close();
while worker.step() { }
if index == 0 { println!("{:?}\tgraph loaded", timer.elapsed()); }
// Phase 2: Reachability.
let mut roots = worker.dataflow(|scope| {
let (roots_input, roots) = scope.new_collection();
reach(&mut trace, roots);
roots_input
});
if index == 0 { roots.insert(0); }
roots.close();
while worker.step() { }
if index == 0 { println!("{:?}\treach complete", timer.elapsed()); }
// Phase 3: Breadth-first distance labeling.
let mut roots = worker.dataflow(|scope| {
let (roots_input, roots) = scope.new_collection();
bfs(&mut trace, roots);
roots_input
});
if index == 0 { roots.insert(0); }
roots.close();
while worker.step() { }
if index == 0 { println!("{:?}\tbfs complete", timer.elapsed()); }
}).unwrap();
}
// use differential_dataflow::trace::implementations::ord::OrdValSpine;
use differential_dataflow::operators::arrange::TraceAgent;
type TraceHandle = TraceAgent<Node, Node, (), isize, GraphTrace>;
fn reach<G: Scope<Timestamp = ()>> (
graph: &mut TraceHandle,
roots: Collection<G, Node>
) -> Collection<G, Node> {
let graph = graph.import(&roots.scope());
roots.iterate(|inner| {
let graph = graph.enter(&inner.scope());
let roots = roots.enter(&inner.scope());
// let reach = inner.concat(&roots).distinct_total().arrange_by_self();
// graph.join_core(&reach, |_src,&dst,&()| Some(dst))
graph.join_core(&inner.arrange_by_self(), |_src,&dst,&()| Some(dst))
.concat(&roots)
.distinct_total()
})
}
fn bfs<G: Scope<Timestamp = ()>> (
graph: &mut TraceHandle,
roots: Collection<G, Node>
) -> Collection<G, (Node, u32)> {
let graph = graph.import(&roots.scope());
let roots = roots.map(|r| (r,0));
roots.iterate(|inner| {
let graph = graph.enter(&inner.scope());
let roots = roots.enter(&inner.scope());
graph.join_map(&inner, |_src,&dest,&dist| (dest, dist+1))
.concat(&roots)
.reduce(|_key, input, output| output.push((*input[0].0,1)))
})
}
// fn connected_components<G: Scope<Timestamp = ()>>(
// graph: &mut TraceHandle<Node>
// ) -> Collection<G, (Node, Node)> {
// // each edge (x,y) means that we need at least a label for the min of x and y.
// let nodes =
// graph
// .as_collection(|&k,&v| {
// let min = std::cmp::min(k,v);
// (min, min)
// })
// .consolidate();
// // each edge should exist in both directions.
// let edges = edges.map_in_place(|x| mem::swap(&mut x.0, &mut x.1))
// .concat(&edges);
// // don't actually use these labels, just grab the type
// nodes.filter(|_| false)
// .iterate(|inner| {
// let edges = edges.enter(&inner.scope());
// let nodes = nodes.enter_at(&inner.scope(), |r| 256 * (64 - r.1.leading_zeros() as u64));
// inner.join_map(&edges, |_k,l,d| (*d,*l))
// .concat(&nodes)
// .group(|_, s, t| { t.push((*s[0].0, 1)); } )
// })
// } | let index = worker.index();
let peers = worker.peers();
let timer = ::std::time::Instant::now();
let (mut graph, mut trace) = worker.dataflow(|scope| { | random_line_split |
graphs.rs | extern crate rand;
extern crate timely;
extern crate differential_dataflow;
use std::rc::Rc;
use rand::{Rng, SeedableRng, StdRng};
use timely::dataflow::*;
use differential_dataflow::input::Input;
use differential_dataflow::Collection;
use differential_dataflow::operators::*;
use differential_dataflow::trace::Trace;
use differential_dataflow::operators::arrange::ArrangeByKey;
use differential_dataflow::operators::arrange::ArrangeBySelf;
use differential_dataflow::trace::implementations::spine_fueled::Spine;
type Node = usize;
use differential_dataflow::trace::implementations::ord::OrdValBatch;
// use differential_dataflow::trace::implementations::ord::OrdValSpine;
// type GraphTrace<N> = Spine<usize, N, (), isize, Rc<GraphBatch<N>>>;
type GraphTrace = Spine<Node, Node, (), isize, Rc<OrdValBatch<Node, Node, (), isize>>>;
fn main() {
let nodes: usize = std::env::args().nth(1).unwrap().parse().unwrap();
let edges: usize = std::env::args().nth(2).unwrap().parse().unwrap();
// Our setting involves four read query types, and two updatable base relations.
//
// Q1: Point lookup: reads "state" associated with a node.
// Q2: One-hop lookup: reads "state" associated with neighbors of a node.
// Q3: Two-hop lookup: reads "state" associated with n-of-n's of a node.
// Q4: Shortest path: reports hop count between two query nodes.
//
// R1: "State": a pair of (node, T) for some type T that I don't currently know.
// R2: "Graph": pairs (node, node) indicating linkage between the two nodes.
timely::execute_from_args(std::env::args().skip(3), move |worker| {
let index = worker.index();
let peers = worker.peers();
let timer = ::std::time::Instant::now();
let (mut graph, mut trace) = worker.dataflow(|scope| {
let (graph_input, graph) = scope.new_collection();
let graph_indexed = graph.arrange_by_key();
// let graph_indexed = graph.arrange_by_key();
(graph_input, graph_indexed.trace)
});
let seed: &[_] = &[1, 2, 3, index];
let mut rng1: StdRng = SeedableRng::from_seed(seed); // rng for edge additions
// let mut rng2: StdRng = SeedableRng::from_seed(seed); // rng for edge deletions
if index == 0 { println!("performing workload on random graph with {} nodes, {} edges:", nodes, edges); }
let worker_edges = edges/peers + if index < (edges % peers) { 1 } else { 0 };
for _ in 0.. worker_edges {
graph.insert((rng1.gen_range(0, nodes) as Node, rng1.gen_range(0, nodes) as Node));
}
graph.close();
while worker.step() { }
if index == 0 { println!("{:?}\tgraph loaded", timer.elapsed()); }
// Phase 2: Reachability.
let mut roots = worker.dataflow(|scope| {
let (roots_input, roots) = scope.new_collection();
reach(&mut trace, roots);
roots_input
});
if index == 0 { roots.insert(0); }
roots.close();
while worker.step() { }
if index == 0 { println!("{:?}\treach complete", timer.elapsed()); }
// Phase 3: Breadth-first distance labeling.
let mut roots = worker.dataflow(|scope| {
let (roots_input, roots) = scope.new_collection();
bfs(&mut trace, roots);
roots_input
});
if index == 0 { roots.insert(0); }
roots.close();
while worker.step() { }
if index == 0 { println!("{:?}\tbfs complete", timer.elapsed()); }
}).unwrap();
}
// use differential_dataflow::trace::implementations::ord::OrdValSpine;
use differential_dataflow::operators::arrange::TraceAgent;
type TraceHandle = TraceAgent<Node, Node, (), isize, GraphTrace>;
fn | <G: Scope<Timestamp = ()>> (
graph: &mut TraceHandle,
roots: Collection<G, Node>
) -> Collection<G, Node> {
let graph = graph.import(&roots.scope());
roots.iterate(|inner| {
let graph = graph.enter(&inner.scope());
let roots = roots.enter(&inner.scope());
// let reach = inner.concat(&roots).distinct_total().arrange_by_self();
// graph.join_core(&reach, |_src,&dst,&()| Some(dst))
graph.join_core(&inner.arrange_by_self(), |_src,&dst,&()| Some(dst))
.concat(&roots)
.distinct_total()
})
}
fn bfs<G: Scope<Timestamp = ()>> (
graph: &mut TraceHandle,
roots: Collection<G, Node>
) -> Collection<G, (Node, u32)> {
let graph = graph.import(&roots.scope());
let roots = roots.map(|r| (r,0));
roots.iterate(|inner| {
let graph = graph.enter(&inner.scope());
let roots = roots.enter(&inner.scope());
graph.join_map(&inner, |_src,&dest,&dist| (dest, dist+1))
.concat(&roots)
.reduce(|_key, input, output| output.push((*input[0].0,1)))
})
}
// fn connected_components<G: Scope<Timestamp = ()>>(
// graph: &mut TraceHandle<Node>
// ) -> Collection<G, (Node, Node)> {
// // each edge (x,y) means that we need at least a label for the min of x and y.
// let nodes =
// graph
// .as_collection(|&k,&v| {
// let min = std::cmp::min(k,v);
// (min, min)
// })
// .consolidate();
// // each edge should exist in both directions.
// let edges = edges.map_in_place(|x| mem::swap(&mut x.0, &mut x.1))
// .concat(&edges);
// // don't actually use these labels, just grab the type
// nodes.filter(|_| false)
// .iterate(|inner| {
// let edges = edges.enter(&inner.scope());
// let nodes = nodes.enter_at(&inner.scope(), |r| 256 * (64 - r.1.leading_zeros() as u64));
// inner.join_map(&edges, |_k,l,d| (*d,*l))
// .concat(&nodes)
// .group(|_, s, t| { t.push((*s[0].0, 1)); } )
// })
// }
| reach | identifier_name |
graphs.rs | extern crate rand;
extern crate timely;
extern crate differential_dataflow;
use std::rc::Rc;
use rand::{Rng, SeedableRng, StdRng};
use timely::dataflow::*;
use differential_dataflow::input::Input;
use differential_dataflow::Collection;
use differential_dataflow::operators::*;
use differential_dataflow::trace::Trace;
use differential_dataflow::operators::arrange::ArrangeByKey;
use differential_dataflow::operators::arrange::ArrangeBySelf;
use differential_dataflow::trace::implementations::spine_fueled::Spine;
type Node = usize;
use differential_dataflow::trace::implementations::ord::OrdValBatch;
// use differential_dataflow::trace::implementations::ord::OrdValSpine;
// type GraphTrace<N> = Spine<usize, N, (), isize, Rc<GraphBatch<N>>>;
type GraphTrace = Spine<Node, Node, (), isize, Rc<OrdValBatch<Node, Node, (), isize>>>;
fn main() {
let nodes: usize = std::env::args().nth(1).unwrap().parse().unwrap();
let edges: usize = std::env::args().nth(2).unwrap().parse().unwrap();
// Our setting involves four read query types, and two updatable base relations.
//
// Q1: Point lookup: reads "state" associated with a node.
// Q2: One-hop lookup: reads "state" associated with neighbors of a node.
// Q3: Two-hop lookup: reads "state" associated with n-of-n's of a node.
// Q4: Shortest path: reports hop count between two query nodes.
//
// R1: "State": a pair of (node, T) for some type T that I don't currently know.
// R2: "Graph": pairs (node, node) indicating linkage between the two nodes.
timely::execute_from_args(std::env::args().skip(3), move |worker| {
let index = worker.index();
let peers = worker.peers();
let timer = ::std::time::Instant::now();
let (mut graph, mut trace) = worker.dataflow(|scope| {
let (graph_input, graph) = scope.new_collection();
let graph_indexed = graph.arrange_by_key();
// let graph_indexed = graph.arrange_by_key();
(graph_input, graph_indexed.trace)
});
let seed: &[_] = &[1, 2, 3, index];
let mut rng1: StdRng = SeedableRng::from_seed(seed); // rng for edge additions
// let mut rng2: StdRng = SeedableRng::from_seed(seed); // rng for edge deletions
if index == 0 { println!("performing workload on random graph with {} nodes, {} edges:", nodes, edges); }
let worker_edges = edges/peers + if index < (edges % peers) { 1 } else { 0 };
for _ in 0.. worker_edges {
graph.insert((rng1.gen_range(0, nodes) as Node, rng1.gen_range(0, nodes) as Node));
}
graph.close();
while worker.step() { }
if index == 0 { println!("{:?}\tgraph loaded", timer.elapsed()); }
// Phase 2: Reachability.
let mut roots = worker.dataflow(|scope| {
let (roots_input, roots) = scope.new_collection();
reach(&mut trace, roots);
roots_input
});
if index == 0 { roots.insert(0); }
roots.close();
while worker.step() { }
if index == 0 { println!("{:?}\treach complete", timer.elapsed()); }
// Phase 3: Breadth-first distance labeling.
let mut roots = worker.dataflow(|scope| {
let (roots_input, roots) = scope.new_collection();
bfs(&mut trace, roots);
roots_input
});
if index == 0 |
roots.close();
while worker.step() { }
if index == 0 { println!("{:?}\tbfs complete", timer.elapsed()); }
}).unwrap();
}
// use differential_dataflow::trace::implementations::ord::OrdValSpine;
use differential_dataflow::operators::arrange::TraceAgent;
type TraceHandle = TraceAgent<Node, Node, (), isize, GraphTrace>;
fn reach<G: Scope<Timestamp = ()>> (
graph: &mut TraceHandle,
roots: Collection<G, Node>
) -> Collection<G, Node> {
let graph = graph.import(&roots.scope());
roots.iterate(|inner| {
let graph = graph.enter(&inner.scope());
let roots = roots.enter(&inner.scope());
// let reach = inner.concat(&roots).distinct_total().arrange_by_self();
// graph.join_core(&reach, |_src,&dst,&()| Some(dst))
graph.join_core(&inner.arrange_by_self(), |_src,&dst,&()| Some(dst))
.concat(&roots)
.distinct_total()
})
}
fn bfs<G: Scope<Timestamp = ()>> (
graph: &mut TraceHandle,
roots: Collection<G, Node>
) -> Collection<G, (Node, u32)> {
let graph = graph.import(&roots.scope());
let roots = roots.map(|r| (r,0));
roots.iterate(|inner| {
let graph = graph.enter(&inner.scope());
let roots = roots.enter(&inner.scope());
graph.join_map(&inner, |_src,&dest,&dist| (dest, dist+1))
.concat(&roots)
.reduce(|_key, input, output| output.push((*input[0].0,1)))
})
}
// fn connected_components<G: Scope<Timestamp = ()>>(
// graph: &mut TraceHandle<Node>
// ) -> Collection<G, (Node, Node)> {
// // each edge (x,y) means that we need at least a label for the min of x and y.
// let nodes =
// graph
// .as_collection(|&k,&v| {
// let min = std::cmp::min(k,v);
// (min, min)
// })
// .consolidate();
// // each edge should exist in both directions.
// let edges = edges.map_in_place(|x| mem::swap(&mut x.0, &mut x.1))
// .concat(&edges);
// // don't actually use these labels, just grab the type
// nodes.filter(|_| false)
// .iterate(|inner| {
// let edges = edges.enter(&inner.scope());
// let nodes = nodes.enter_at(&inner.scope(), |r| 256 * (64 - r.1.leading_zeros() as u64));
// inner.join_map(&edges, |_k,l,d| (*d,*l))
// .concat(&nodes)
// .group(|_, s, t| { t.push((*s[0].0, 1)); } )
// })
// }
| { roots.insert(0); } | conditional_block |
sha256.rs | self) -> (Self, Self);
}
impl ToBits for u64 {
fn to_bits(self) -> (u64, u64) {
return (self >> 61, self << 3);
}
}
/// Adds the specified number of bytes to the bit count. panic!() if this would cause numeric
/// overflow.
fn add_bytes_to_bits<T: Int + ToBits>(bits: T, bytes: T) -> T {
let (new_high_bits, new_low_bits) = bytes.to_bits();
if new_high_bits > Int::zero() {
panic!("numeric overflow occurred.")
}
match bits.checked_add(new_low_bits) {
Some(x) => return x,
None => panic!("numeric overflow occurred.")
}
}
/// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it
/// must be processed. The input() method takes care of processing and then clearing the buffer
/// automatically. However, other methods do not and require the caller to process the buffer. Any
/// method that modifies the buffer directory or provides the caller with bytes that can be modified
/// results in those bytes being marked as used by the buffer.
trait FixedBuffer {
/// Input a vector of bytes. If the buffer becomes full, process it with the provided
/// function and then clear the buffer.
fn input<F>(&mut self, input: &[u8], func: F) where
F: FnMut(&[u8]);
/// Reset the buffer.
fn reset(&mut self);
/// Zero the buffer up until the specified index. The buffer position currently must not be
/// greater than that index.
fn zero_until(&mut self, idx: usize);
/// Get a slice of the buffer of the specified size. There must be at least that many bytes
/// remaining in the buffer.
fn next<'s>(&'s mut self, len: usize) -> &'s mut [u8];
/// Get the current buffer. The buffer must already be full. This clears the buffer as well.
fn full_buffer<'s>(&'s mut self) -> &'s [u8];
/// Get the current position of the buffer.
fn position(&self) -> usize;
/// Get the number of bytes remaining in the buffer until it is full.
fn remaining(&self) -> usize;
/// Get the size of the buffer
fn size(&self) -> usize;
}
/// A FixedBuffer of 64 bytes useful for implementing Sha256 which has a 64 byte blocksize.
struct FixedBuffer64 {
buffer: [u8; 64],
buffer_idx: usize,
}
impl FixedBuffer64 {
/// Create a new FixedBuffer64
fn new() -> FixedBuffer64 {
return FixedBuffer64 {
buffer: [0u8; 64],
buffer_idx: 0
};
}
}
impl FixedBuffer for FixedBuffer64 {
fn input<F>(&mut self, input: &[u8], mut func: F) where
F: FnMut(&[u8]),
{
let mut i = 0;
let size = self.size();
// If there is already data in the buffer, copy as much as we can into it and process
// the data if the buffer becomes full.
if self.buffer_idx!= 0 {
let buffer_remaining = size - self.buffer_idx;
if input.len() >= buffer_remaining {
copy_memory(
self.buffer.slice_mut(self.buffer_idx, size),
&input[0..buffer_remaining]);
self.buffer_idx = 0;
func(&self.buffer);
i += buffer_remaining;
} else {
copy_memory(
self.buffer.slice_mut(self.buffer_idx, self.buffer_idx + input.len()),
input);
self.buffer_idx += input.len();
return;
}
}
// While we have at least a full buffer size chunk's worth of data, process that data
// without copying it into the buffer
while input.len() - i >= size {
func(&input[i..(i + size)]);
i += size;
}
// Copy any input data into the buffer. At this point in the method, the amount of
// data left in the input vector will be less than the buffer size and the buffer will
// be empty.
let input_remaining = input.len() - i;
copy_memory(
self.buffer.slice_to_mut(input_remaining),
&input[i..]);
self.buffer_idx += input_remaining;
}
fn reset(&mut self) {
self.buffer_idx = 0;
}
fn zero_until(&mut self, idx: usize) {
assert!(idx >= self.buffer_idx);
self.buffer.slice_mut(self.buffer_idx, idx).set_memory(0);
self.buffer_idx = idx;
}
fn next<'s>(&'s mut self, len: usize) -> &'s mut [u8] {
self.buffer_idx += len;
return self.buffer.slice_mut(self.buffer_idx - len, self.buffer_idx);
}
fn full_buffer<'s>(&'s mut self) -> &'s [u8] {
assert!(self.buffer_idx == 64);
self.buffer_idx = 0;
return &self.buffer[0..64];
}
fn position(&self) -> usize { self.buffer_idx }
fn remaining(&self) -> usize { 64 - self.buffer_idx }
fn size(&self) -> usize { 64 }
}
/// The StandardPadding trait adds a method useful for Sha256 to a FixedBuffer struct.
trait StandardPadding {
/// Add padding to the buffer. The buffer must not be full when this method is called and is
/// guaranteed to have exactly rem remaining bytes when it returns. If there are not at least
/// rem bytes available, the buffer will be zero padded, processed, cleared, and then filled
/// with zeros again until only rem bytes are remaining.
fn standard_padding<F>(&mut self, rem: usize, func: F) where F: FnMut(&[u8]);
}
impl <T: FixedBuffer> StandardPadding for T {
fn standard_padding<F>(&mut self, rem: usize, mut func: F) where F: FnMut(&[u8]) {
let size = self.size();
self.next(1)[0] = 128;
if self.remaining() < rem {
self.zero_until(size);
func(self.full_buffer());
}
self.zero_until(size - rem);
}
}
/// The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2
/// family of digest functions.
pub trait Digest {
/// Provide message data.
///
/// # Arguments
///
/// * input - A vector of message data
fn input(&mut self, input: &[u8]);
/// Retrieve the digest result. This method may be called multiple times.
///
/// # Arguments
///
/// * out - the vector to hold the result. Must be large enough to contain output_bits().
fn result(&mut self, out: &mut [u8]);
/// Reset the digest. This method must be called after result() and before supplying more
/// data.
fn reset(&mut self);
/// Get the output size in bits.
fn output_bits(&self) -> usize;
/// Convenience function that feeds a string into a digest.
///
/// # Arguments
///
/// * `input` The string to feed into the digest
fn input_str(&mut self, input: &str) {
self.input(input.as_bytes());
}
/// Convenience function that retrieves the result of a digest as a
/// newly allocated vec of bytes.
fn result_bytes(&mut self) -> Vec<u8> {
let mut buf: Vec<u8> = repeat(0u8).take((self.output_bits()+7)/8).collect();
self.result(buf.as_mut_slice());
buf
}
/// Convenience function that retrieves the result of a digest as a
/// String in hexadecimal format.
fn result_str(&mut self) -> String {
self.result_bytes().to_hex().to_string()
}
}
// A structure that represents that state of a digest computation for the SHA-2 512 family of digest
// functions
struct Engine256State {
h0: u32,
h1: u32,
h2: u32,
h3: u32,
h4: u32,
h5: u32,
h6: u32,
h7: u32,
}
impl Engine256State {
fn new(h: &[u32; 8]) -> Engine256State {
return Engine256State {
h0: h[0],
h1: h[1],
h2: h[2],
h3: h[3],
h4: h[4],
h5: h[5],
h6: h[6],
h7: h[7]
};
}
fn reset(&mut self, h: &[u32; 8]) {
self.h0 = h[0];
self.h1 = h[1];
self.h2 = h[2];
self.h3 = h[3];
self.h4 = h[4];
self.h5 = h[5];
self.h6 = h[6];
self.h7 = h[7];
}
fn process_block(&mut self, data: &[u8]) {
fn ch(x: u32, y: u32, z: u32) -> u32 {
((x & y) ^ ((!x) & z))
}
fn maj(x: u32, y: u32, z: u32) -> u32 {
((x & y) ^ (x & z) ^ (y & z))
}
fn sum0(x: u32) -> u32 {
((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10))
}
fn sum1(x: u32) -> u32 {
((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7))
}
fn sigma0(x: u32) -> u32 {
((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3)
} |
fn sigma1(x: u32) -> u32 {
((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10)
}
let mut a = self.h0;
let mut b = self.h1;
let mut c = self.h2;
let mut d = self.h3;
let mut e = self.h4;
let mut f = self.h5;
let mut g = self.h6;
let mut h = self.h7;
let mut w = [0u32; 64];
// Sha-512 and Sha-256 use basically the same calculations which are implemented
// by these macros. Inlining the calculations seems to result in better generated code.
macro_rules! schedule_round { ($t:expr) => (
w[$t] = sigma1(w[$t - 2]) + w[$t - 7] + sigma0(w[$t - 15]) + w[$t - 16];
)
}
macro_rules! sha2_round {
($A:ident, $B:ident, $C:ident, $D:ident,
$E:ident, $F:ident, $G:ident, $H:ident, $K:ident, $t:expr) => (
{
$H += sum1($E) + ch($E, $F, $G) + $K[$t] + w[$t];
$D += $H;
$H += sum0($A) + maj($A, $B, $C);
}
)
}
read_u32v_be(w.slice_mut(0, 16), data);
// Putting the message schedule inside the same loop as the round calculations allows for
// the compiler to generate better code.
for t in range_step(0us, 48, 8) {
schedule_round!(t + 16);
schedule_round!(t + 17);
schedule_round!(t + 18);
schedule_round!(t + 19);
schedule_round!(t + 20);
schedule_round!(t + 21);
schedule_round!(t + 22);
schedule_round!(t + 23);
sha2_round!(a, b, c, d, e, f, g, h, K32, t);
sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1);
sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2);
sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3);
sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4);
sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5);
sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6);
sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7);
}
for t in range_step(48us, 64, 8) {
sha2_round!(a, b, c, d, e, f, g, h, K32, t);
sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1);
sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2);
sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3);
sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4);
sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5);
sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6);
sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7);
}
self.h0 += a;
self.h1 += b;
self.h2 += c;
self.h3 += d;
self.h4 += e;
self.h5 += f;
self.h6 += g;
self.h7 += h;
}
}
static K32: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
// A structure that keeps track of the state of the Sha-256 operation and contains the logic
// necessary to perform the final calculations.
struct Engine256 {
length_bits: u64,
buffer: FixedBuffer64,
state: Engine256State,
finished: bool,
}
impl Engine256 {
fn new(h: &[u32; 8]) -> Engine256 {
return Engine256 {
length_bits: 0,
buffer: FixedBuffer64::new(),
state: Engine256State::new(h),
finished: false
}
}
fn reset(&mut self, h: &[u32; 8]) {
self.length_bits = 0;
self.buffer.reset();
self.state.reset(h);
self.finished = false;
}
fn input(&mut self, input: &[u8]) {
assert!(!self.finished);
// Assumes that input.len() can be converted to u64 without overflow
self.length_bits = add_bytes_to_bits(self.length_bits, input.len() as u64);
let self_state = &mut self.state;
self.buffer.input(input, |input: &[u8]| { self_state.process_block(input) });
}
fn finish(&mut self) {
if self.finished {
return;
}
let self_state = &mut self.state;
self.buffer.standard_padding(8, |input: &[u8]| { self_state.process_block(input) });
write_u32_be(self.buffer.next(4), (self.length_bits >> 32) as u32 );
write_u32_be(self.buffer.next(4), self.length_bits as u32);
self_state.process_block(self.buffer.full_buffer());
self.finished = true;
}
}
/// The SHA-256 hash algorithm
pub struct Sha256 {
engine: Engine256
}
impl Sha256 {
/// Construct a new instance of a SHA-256 digest.
pub fn new() -> Sha256 {
Sha256 {
engine: Engine256::new(&H256)
}
}
}
impl Digest for Sha256 {
fn input(&mut self, d: &[u8]) {
self.engine.input(d);
}
fn result(&mut self, out: &mut [u8]) {
self.engine.finish();
write_u32_be(out.slice_mut(0, 4), self.engine.state.h0);
write_u32_be(out.slice_mut(4, 8), self.engine.state.h1);
write_u32_be(out.slice_mut(8, 12), self.engine.state.h2);
write_u32_be(out.slice_mut(12, 16), self.engine.state.h3);
write_u32_be(out.slice_mut(16, 20), self.engine.state.h4);
write_u32_be(out.slice_mut(20, 24), self.engine.state.h5);
write_u32_be(out.slice_mut(24, 28), self.engine.state.h6);
write_u32_be(out.slice_mut(28, 32), self.engine.state.h7);
}
fn reset(&mut self) {
self.engine.reset(&H256);
}
fn output_bits(&self) -> usize { 256 }
}
static H256: [u32; 8] = [
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19
];
#[cfg(test)]
mod tests {
extern crate rand;
use self::rand::Rng;
use self::rand::isaac::IsaacRng;
use serialize::hex::FromHex;
use std::iter::repeat;
use std::num::Int;
use super::{Digest, Sha256, FixedBuffer};
// A normal addition - no overflow occurs
#[test]
fn test_add_bytes_to_bits_ok() {
assert!(super::add_bytes_to_bits::<u64>(100, 10) == 180);
}
// A simple failure case - adding 1 to the max value
#[test]
#[should_fail]
fn test_add_bytes_to_bits_overflow() {
super::add_bytes_to_bits::<u64>(Int::max_value(), 1);
}
struct Test {
input: String,
output_str: String,
}
fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) {
// Test that it works when accepting the message all at once
for t in tests.iter() {
sh.reset();
sh.input_str(t.input.as_slice());
let out_str = sh.result_str();
assert!(out_str == t.output_str);
}
// Test that it works when accepting the message in pieces
for t in tests.iter() {
sh.reset();
let len = t.input.len();
let mut left = len;
while left > 0u {
let take = (left + 1us) / 2us;
sh.input_str(t.input
.slice(len - left, take + len - left));
left = left - take;
}
let out_str = sh.result_str();
assert!(out_str == t.output_str);
}
}
#[test]
fn test_sha256() {
// Examples from wikipedia
let wikipedia_tests = vec!(
Test {
input: "".to_string(),
output_str: "e3b0c44298fc1c149afb\
f4c8996fb92427ae41e4649b934ca495991b7852b855".to_string()
| random_line_split |
|
sha256.rs | ) -> (Self, Self);
}
impl ToBits for u64 {
fn to_bits(self) -> (u64, u64) {
return (self >> 61, self << 3);
}
}
/// Adds the specified number of bytes to the bit count. panic!() if this would cause numeric
/// overflow.
fn add_bytes_to_bits<T: Int + ToBits>(bits: T, bytes: T) -> T |
/// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it
/// must be processed. The input() method takes care of processing and then clearing the buffer
/// automatically. However, other methods do not and require the caller to process the buffer. Any
/// method that modifies the buffer directory or provides the caller with bytes that can be modified
/// results in those bytes being marked as used by the buffer.
trait FixedBuffer {
/// Input a vector of bytes. If the buffer becomes full, process it with the provided
/// function and then clear the buffer.
fn input<F>(&mut self, input: &[u8], func: F) where
F: FnMut(&[u8]);
/// Reset the buffer.
fn reset(&mut self);
/// Zero the buffer up until the specified index. The buffer position currently must not be
/// greater than that index.
fn zero_until(&mut self, idx: usize);
/// Get a slice of the buffer of the specified size. There must be at least that many bytes
/// remaining in the buffer.
fn next<'s>(&'s mut self, len: usize) -> &'s mut [u8];
/// Get the current buffer. The buffer must already be full. This clears the buffer as well.
fn full_buffer<'s>(&'s mut self) -> &'s [u8];
/// Get the current position of the buffer.
fn position(&self) -> usize;
/// Get the number of bytes remaining in the buffer until it is full.
fn remaining(&self) -> usize;
/// Get the size of the buffer
fn size(&self) -> usize;
}
/// A FixedBuffer of 64 bytes useful for implementing Sha256 which has a 64 byte blocksize.
struct FixedBuffer64 {
buffer: [u8; 64],
buffer_idx: usize,
}
impl FixedBuffer64 {
/// Create a new FixedBuffer64
fn new() -> FixedBuffer64 {
return FixedBuffer64 {
buffer: [0u8; 64],
buffer_idx: 0
};
}
}
impl FixedBuffer for FixedBuffer64 {
fn input<F>(&mut self, input: &[u8], mut func: F) where
F: FnMut(&[u8]),
{
let mut i = 0;
let size = self.size();
// If there is already data in the buffer, copy as much as we can into it and process
// the data if the buffer becomes full.
if self.buffer_idx!= 0 {
let buffer_remaining = size - self.buffer_idx;
if input.len() >= buffer_remaining {
copy_memory(
self.buffer.slice_mut(self.buffer_idx, size),
&input[0..buffer_remaining]);
self.buffer_idx = 0;
func(&self.buffer);
i += buffer_remaining;
} else {
copy_memory(
self.buffer.slice_mut(self.buffer_idx, self.buffer_idx + input.len()),
input);
self.buffer_idx += input.len();
return;
}
}
// While we have at least a full buffer size chunk's worth of data, process that data
// without copying it into the buffer
while input.len() - i >= size {
func(&input[i..(i + size)]);
i += size;
}
// Copy any input data into the buffer. At this point in the method, the amount of
// data left in the input vector will be less than the buffer size and the buffer will
// be empty.
let input_remaining = input.len() - i;
copy_memory(
self.buffer.slice_to_mut(input_remaining),
&input[i..]);
self.buffer_idx += input_remaining;
}
fn reset(&mut self) {
self.buffer_idx = 0;
}
fn zero_until(&mut self, idx: usize) {
assert!(idx >= self.buffer_idx);
self.buffer.slice_mut(self.buffer_idx, idx).set_memory(0);
self.buffer_idx = idx;
}
fn next<'s>(&'s mut self, len: usize) -> &'s mut [u8] {
self.buffer_idx += len;
return self.buffer.slice_mut(self.buffer_idx - len, self.buffer_idx);
}
fn full_buffer<'s>(&'s mut self) -> &'s [u8] {
assert!(self.buffer_idx == 64);
self.buffer_idx = 0;
return &self.buffer[0..64];
}
fn position(&self) -> usize { self.buffer_idx }
fn remaining(&self) -> usize { 64 - self.buffer_idx }
fn size(&self) -> usize { 64 }
}
/// The StandardPadding trait adds a method useful for Sha256 to a FixedBuffer struct.
trait StandardPadding {
/// Add padding to the buffer. The buffer must not be full when this method is called and is
/// guaranteed to have exactly rem remaining bytes when it returns. If there are not at least
/// rem bytes available, the buffer will be zero padded, processed, cleared, and then filled
/// with zeros again until only rem bytes are remaining.
fn standard_padding<F>(&mut self, rem: usize, func: F) where F: FnMut(&[u8]);
}
impl <T: FixedBuffer> StandardPadding for T {
fn standard_padding<F>(&mut self, rem: usize, mut func: F) where F: FnMut(&[u8]) {
let size = self.size();
self.next(1)[0] = 128;
if self.remaining() < rem {
self.zero_until(size);
func(self.full_buffer());
}
self.zero_until(size - rem);
}
}
/// The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2
/// family of digest functions.
pub trait Digest {
/// Provide message data.
///
/// # Arguments
///
/// * input - A vector of message data
fn input(&mut self, input: &[u8]);
/// Retrieve the digest result. This method may be called multiple times.
///
/// # Arguments
///
/// * out - the vector to hold the result. Must be large enough to contain output_bits().
fn result(&mut self, out: &mut [u8]);
/// Reset the digest. This method must be called after result() and before supplying more
/// data.
fn reset(&mut self);
/// Get the output size in bits.
fn output_bits(&self) -> usize;
/// Convenience function that feeds a string into a digest.
///
/// # Arguments
///
/// * `input` The string to feed into the digest
fn input_str(&mut self, input: &str) {
self.input(input.as_bytes());
}
/// Convenience function that retrieves the result of a digest as a
/// newly allocated vec of bytes.
fn result_bytes(&mut self) -> Vec<u8> {
let mut buf: Vec<u8> = repeat(0u8).take((self.output_bits()+7)/8).collect();
self.result(buf.as_mut_slice());
buf
}
/// Convenience function that retrieves the result of a digest as a
/// String in hexadecimal format.
fn result_str(&mut self) -> String {
self.result_bytes().to_hex().to_string()
}
}
// A structure that represents that state of a digest computation for the SHA-2 512 family of digest
// functions
struct Engine256State {
h0: u32,
h1: u32,
h2: u32,
h3: u32,
h4: u32,
h5: u32,
h6: u32,
h7: u32,
}
impl Engine256State {
fn new(h: &[u32; 8]) -> Engine256State {
return Engine256State {
h0: h[0],
h1: h[1],
h2: h[2],
h3: h[3],
h4: h[4],
h5: h[5],
h6: h[6],
h7: h[7]
};
}
fn reset(&mut self, h: &[u32; 8]) {
self.h0 = h[0];
self.h1 = h[1];
self.h2 = h[2];
self.h3 = h[3];
self.h4 = h[4];
self.h5 = h[5];
self.h6 = h[6];
self.h7 = h[7];
}
fn process_block(&mut self, data: &[u8]) {
fn ch(x: u32, y: u32, z: u32) -> u32 {
((x & y) ^ ((!x) & z))
}
fn maj(x: u32, y: u32, z: u32) -> u32 {
((x & y) ^ (x & z) ^ (y & z))
}
fn sum0(x: u32) -> u32 {
((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10))
}
fn sum1(x: u32) -> u32 {
((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7))
}
fn sigma0(x: u32) -> u32 {
((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3)
}
fn sigma1(x: u32) -> u32 {
((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10)
}
let mut a = self.h0;
let mut b = self.h1;
let mut c = self.h2;
let mut d = self.h3;
let mut e = self.h4;
let mut f = self.h5;
let mut g = self.h6;
let mut h = self.h7;
let mut w = [0u32; 64];
// Sha-512 and Sha-256 use basically the same calculations which are implemented
// by these macros. Inlining the calculations seems to result in better generated code.
macro_rules! schedule_round { ($t:expr) => (
w[$t] = sigma1(w[$t - 2]) + w[$t - 7] + sigma0(w[$t - 15]) + w[$t - 16];
)
}
macro_rules! sha2_round {
($A:ident, $B:ident, $C:ident, $D:ident,
$E:ident, $F:ident, $G:ident, $H:ident, $K:ident, $t:expr) => (
{
$H += sum1($E) + ch($E, $F, $G) + $K[$t] + w[$t];
$D += $H;
$H += sum0($A) + maj($A, $B, $C);
}
)
}
read_u32v_be(w.slice_mut(0, 16), data);
// Putting the message schedule inside the same loop as the round calculations allows for
// the compiler to generate better code.
for t in range_step(0us, 48, 8) {
schedule_round!(t + 16);
schedule_round!(t + 17);
schedule_round!(t + 18);
schedule_round!(t + 19);
schedule_round!(t + 20);
schedule_round!(t + 21);
schedule_round!(t + 22);
schedule_round!(t + 23);
sha2_round!(a, b, c, d, e, f, g, h, K32, t);
sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1);
sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2);
sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3);
sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4);
sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5);
sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6);
sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7);
}
for t in range_step(48us, 64, 8) {
sha2_round!(a, b, c, d, e, f, g, h, K32, t);
sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1);
sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2);
sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3);
sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4);
sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5);
sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6);
sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7);
}
self.h0 += a;
self.h1 += b;
self.h2 += c;
self.h3 += d;
self.h4 += e;
self.h5 += f;
self.h6 += g;
self.h7 += h;
}
}
static K32: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
// A structure that keeps track of the state of the Sha-256 operation and contains the logic
// necessary to perform the final calculations.
struct Engine256 {
length_bits: u64,
buffer: FixedBuffer64,
state: Engine256State,
finished: bool,
}
impl Engine256 {
fn new(h: &[u32; 8]) -> Engine256 {
return Engine256 {
length_bits: 0,
buffer: FixedBuffer64::new(),
state: Engine256State::new(h),
finished: false
}
}
fn reset(&mut self, h: &[u32; 8]) {
self.length_bits = 0;
self.buffer.reset();
self.state.reset(h);
self.finished = false;
}
fn input(&mut self, input: &[u8]) {
assert!(!self.finished);
// Assumes that input.len() can be converted to u64 without overflow
self.length_bits = add_bytes_to_bits(self.length_bits, input.len() as u64);
let self_state = &mut self.state;
self.buffer.input(input, |input: &[u8]| { self_state.process_block(input) });
}
fn finish(&mut self) {
if self.finished {
return;
}
let self_state = &mut self.state;
self.buffer.standard_padding(8, |input: &[u8]| { self_state.process_block(input) });
write_u32_be(self.buffer.next(4), (self.length_bits >> 32) as u32 );
write_u32_be(self.buffer.next(4), self.length_bits as u32);
self_state.process_block(self.buffer.full_buffer());
self.finished = true;
}
}
/// The SHA-256 hash algorithm
pub struct Sha256 {
engine: Engine256
}
impl Sha256 {
/// Construct a new instance of a SHA-256 digest.
pub fn new() -> Sha256 {
Sha256 {
engine: Engine256::new(&H256)
}
}
}
impl Digest for Sha256 {
fn input(&mut self, d: &[u8]) {
self.engine.input(d);
}
fn result(&mut self, out: &mut [u8]) {
self.engine.finish();
write_u32_be(out.slice_mut(0, 4), self.engine.state.h0);
write_u32_be(out.slice_mut(4, 8), self.engine.state.h1);
write_u32_be(out.slice_mut(8, 12), self.engine.state.h2);
write_u32_be(out.slice_mut(12, 16), self.engine.state.h3);
write_u32_be(out.slice_mut(16, 20), self.engine.state.h4);
write_u32_be(out.slice_mut(20, 24), self.engine.state.h5);
write_u32_be(out.slice_mut(24, 28), self.engine.state.h6);
write_u32_be(out.slice_mut(28, 32), self.engine.state.h7);
}
fn reset(&mut self) {
self.engine.reset(&H256);
}
fn output_bits(&self) -> usize { 256 }
}
static H256: [u32; 8] = [
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19
];
#[cfg(test)]
mod tests {
extern crate rand;
use self::rand::Rng;
use self::rand::isaac::IsaacRng;
use serialize::hex::FromHex;
use std::iter::repeat;
use std::num::Int;
use super::{Digest, Sha256, FixedBuffer};
// A normal addition - no overflow occurs
#[test]
fn test_add_bytes_to_bits_ok() {
assert!(super::add_bytes_to_bits::<u64>(100, 10) == 180);
}
// A simple failure case - adding 1 to the max value
#[test]
#[should_fail]
fn test_add_bytes_to_bits_overflow() {
super::add_bytes_to_bits::<u64>(Int::max_value(), 1);
}
struct Test {
input: String,
output_str: String,
}
fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) {
// Test that it works when accepting the message all at once
for t in tests.iter() {
sh.reset();
sh.input_str(t.input.as_slice());
let out_str = sh.result_str();
assert!(out_str == t.output_str);
}
// Test that it works when accepting the message in pieces
for t in tests.iter() {
sh.reset();
let len = t.input.len();
let mut left = len;
while left > 0u {
let take = (left + 1us) / 2us;
sh.input_str(t.input
.slice(len - left, take + len - left));
left = left - take;
}
let out_str = sh.result_str();
assert!(out_str == t.output_str);
}
}
#[test]
fn test_sha256() {
// Examples from wikipedia
let wikipedia_tests = vec!(
Test {
input: "".to_string(),
output_str: "e3b0c44298fc1c149afb\
f4c8996fb92427ae41e4649b934ca495991b7852b855".to_string()
| {
let (new_high_bits, new_low_bits) = bytes.to_bits();
if new_high_bits > Int::zero() {
panic!("numeric overflow occurred.")
}
match bits.checked_add(new_low_bits) {
Some(x) => return x,
None => panic!("numeric overflow occurred.")
}
} | identifier_body |
sha256.rs | _idx;
if input.len() >= buffer_remaining {
copy_memory(
self.buffer.slice_mut(self.buffer_idx, size),
&input[0..buffer_remaining]);
self.buffer_idx = 0;
func(&self.buffer);
i += buffer_remaining;
} else {
copy_memory(
self.buffer.slice_mut(self.buffer_idx, self.buffer_idx + input.len()),
input);
self.buffer_idx += input.len();
return;
}
}
// While we have at least a full buffer size chunk's worth of data, process that data
// without copying it into the buffer
while input.len() - i >= size {
func(&input[i..(i + size)]);
i += size;
}
// Copy any input data into the buffer. At this point in the method, the amount of
// data left in the input vector will be less than the buffer size and the buffer will
// be empty.
let input_remaining = input.len() - i;
copy_memory(
self.buffer.slice_to_mut(input_remaining),
&input[i..]);
self.buffer_idx += input_remaining;
}
fn reset(&mut self) {
self.buffer_idx = 0;
}
fn zero_until(&mut self, idx: usize) {
assert!(idx >= self.buffer_idx);
self.buffer.slice_mut(self.buffer_idx, idx).set_memory(0);
self.buffer_idx = idx;
}
fn next<'s>(&'s mut self, len: usize) -> &'s mut [u8] {
self.buffer_idx += len;
return self.buffer.slice_mut(self.buffer_idx - len, self.buffer_idx);
}
fn full_buffer<'s>(&'s mut self) -> &'s [u8] {
assert!(self.buffer_idx == 64);
self.buffer_idx = 0;
return &self.buffer[0..64];
}
fn position(&self) -> usize { self.buffer_idx }
fn remaining(&self) -> usize { 64 - self.buffer_idx }
fn size(&self) -> usize { 64 }
}
/// The StandardPadding trait adds a method useful for Sha256 to a FixedBuffer struct.
trait StandardPadding {
/// Add padding to the buffer. The buffer must not be full when this method is called and is
/// guaranteed to have exactly rem remaining bytes when it returns. If there are not at least
/// rem bytes available, the buffer will be zero padded, processed, cleared, and then filled
/// with zeros again until only rem bytes are remaining.
fn standard_padding<F>(&mut self, rem: usize, func: F) where F: FnMut(&[u8]);
}
impl <T: FixedBuffer> StandardPadding for T {
fn standard_padding<F>(&mut self, rem: usize, mut func: F) where F: FnMut(&[u8]) {
let size = self.size();
self.next(1)[0] = 128;
if self.remaining() < rem {
self.zero_until(size);
func(self.full_buffer());
}
self.zero_until(size - rem);
}
}
/// The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2
/// family of digest functions.
pub trait Digest {
/// Provide message data.
///
/// # Arguments
///
/// * input - A vector of message data
fn input(&mut self, input: &[u8]);
/// Retrieve the digest result. This method may be called multiple times.
///
/// # Arguments
///
/// * out - the vector to hold the result. Must be large enough to contain output_bits().
fn result(&mut self, out: &mut [u8]);
/// Reset the digest. This method must be called after result() and before supplying more
/// data.
fn reset(&mut self);
/// Get the output size in bits.
fn output_bits(&self) -> usize;
/// Convenience function that feeds a string into a digest.
///
/// # Arguments
///
/// * `input` The string to feed into the digest
fn input_str(&mut self, input: &str) {
self.input(input.as_bytes());
}
/// Convenience function that retrieves the result of a digest as a
/// newly allocated vec of bytes.
fn result_bytes(&mut self) -> Vec<u8> {
let mut buf: Vec<u8> = repeat(0u8).take((self.output_bits()+7)/8).collect();
self.result(buf.as_mut_slice());
buf
}
/// Convenience function that retrieves the result of a digest as a
/// String in hexadecimal format.
fn result_str(&mut self) -> String {
self.result_bytes().to_hex().to_string()
}
}
// A structure that represents that state of a digest computation for the SHA-2 512 family of digest
// functions
struct Engine256State {
h0: u32,
h1: u32,
h2: u32,
h3: u32,
h4: u32,
h5: u32,
h6: u32,
h7: u32,
}
impl Engine256State {
fn new(h: &[u32; 8]) -> Engine256State {
return Engine256State {
h0: h[0],
h1: h[1],
h2: h[2],
h3: h[3],
h4: h[4],
h5: h[5],
h6: h[6],
h7: h[7]
};
}
fn reset(&mut self, h: &[u32; 8]) {
self.h0 = h[0];
self.h1 = h[1];
self.h2 = h[2];
self.h3 = h[3];
self.h4 = h[4];
self.h5 = h[5];
self.h6 = h[6];
self.h7 = h[7];
}
fn process_block(&mut self, data: &[u8]) {
fn ch(x: u32, y: u32, z: u32) -> u32 {
((x & y) ^ ((!x) & z))
}
fn maj(x: u32, y: u32, z: u32) -> u32 {
((x & y) ^ (x & z) ^ (y & z))
}
fn sum0(x: u32) -> u32 {
((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10))
}
fn sum1(x: u32) -> u32 {
((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7))
}
fn sigma0(x: u32) -> u32 {
((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3)
}
fn sigma1(x: u32) -> u32 {
((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10)
}
let mut a = self.h0;
let mut b = self.h1;
let mut c = self.h2;
let mut d = self.h3;
let mut e = self.h4;
let mut f = self.h5;
let mut g = self.h6;
let mut h = self.h7;
let mut w = [0u32; 64];
// Sha-512 and Sha-256 use basically the same calculations which are implemented
// by these macros. Inlining the calculations seems to result in better generated code.
macro_rules! schedule_round { ($t:expr) => (
w[$t] = sigma1(w[$t - 2]) + w[$t - 7] + sigma0(w[$t - 15]) + w[$t - 16];
)
}
macro_rules! sha2_round {
($A:ident, $B:ident, $C:ident, $D:ident,
$E:ident, $F:ident, $G:ident, $H:ident, $K:ident, $t:expr) => (
{
$H += sum1($E) + ch($E, $F, $G) + $K[$t] + w[$t];
$D += $H;
$H += sum0($A) + maj($A, $B, $C);
}
)
}
read_u32v_be(w.slice_mut(0, 16), data);
// Putting the message schedule inside the same loop as the round calculations allows for
// the compiler to generate better code.
for t in range_step(0us, 48, 8) {
schedule_round!(t + 16);
schedule_round!(t + 17);
schedule_round!(t + 18);
schedule_round!(t + 19);
schedule_round!(t + 20);
schedule_round!(t + 21);
schedule_round!(t + 22);
schedule_round!(t + 23);
sha2_round!(a, b, c, d, e, f, g, h, K32, t);
sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1);
sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2);
sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3);
sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4);
sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5);
sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6);
sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7);
}
for t in range_step(48us, 64, 8) {
sha2_round!(a, b, c, d, e, f, g, h, K32, t);
sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1);
sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2);
sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3);
sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4);
sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5);
sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6);
sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7);
}
self.h0 += a;
self.h1 += b;
self.h2 += c;
self.h3 += d;
self.h4 += e;
self.h5 += f;
self.h6 += g;
self.h7 += h;
}
}
static K32: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
// A structure that keeps track of the state of the Sha-256 operation and contains the logic
// necessary to perform the final calculations.
struct Engine256 {
length_bits: u64,
buffer: FixedBuffer64,
state: Engine256State,
finished: bool,
}
impl Engine256 {
fn new(h: &[u32; 8]) -> Engine256 {
return Engine256 {
length_bits: 0,
buffer: FixedBuffer64::new(),
state: Engine256State::new(h),
finished: false
}
}
fn reset(&mut self, h: &[u32; 8]) {
self.length_bits = 0;
self.buffer.reset();
self.state.reset(h);
self.finished = false;
}
fn input(&mut self, input: &[u8]) {
assert!(!self.finished);
// Assumes that input.len() can be converted to u64 without overflow
self.length_bits = add_bytes_to_bits(self.length_bits, input.len() as u64);
let self_state = &mut self.state;
self.buffer.input(input, |input: &[u8]| { self_state.process_block(input) });
}
fn finish(&mut self) {
if self.finished {
return;
}
let self_state = &mut self.state;
self.buffer.standard_padding(8, |input: &[u8]| { self_state.process_block(input) });
write_u32_be(self.buffer.next(4), (self.length_bits >> 32) as u32 );
write_u32_be(self.buffer.next(4), self.length_bits as u32);
self_state.process_block(self.buffer.full_buffer());
self.finished = true;
}
}
/// The SHA-256 hash algorithm
pub struct Sha256 {
engine: Engine256
}
impl Sha256 {
/// Construct a new instance of a SHA-256 digest.
pub fn new() -> Sha256 {
Sha256 {
engine: Engine256::new(&H256)
}
}
}
impl Digest for Sha256 {
fn input(&mut self, d: &[u8]) {
self.engine.input(d);
}
fn result(&mut self, out: &mut [u8]) {
self.engine.finish();
write_u32_be(out.slice_mut(0, 4), self.engine.state.h0);
write_u32_be(out.slice_mut(4, 8), self.engine.state.h1);
write_u32_be(out.slice_mut(8, 12), self.engine.state.h2);
write_u32_be(out.slice_mut(12, 16), self.engine.state.h3);
write_u32_be(out.slice_mut(16, 20), self.engine.state.h4);
write_u32_be(out.slice_mut(20, 24), self.engine.state.h5);
write_u32_be(out.slice_mut(24, 28), self.engine.state.h6);
write_u32_be(out.slice_mut(28, 32), self.engine.state.h7);
}
fn reset(&mut self) {
self.engine.reset(&H256);
}
fn output_bits(&self) -> usize { 256 }
}
static H256: [u32; 8] = [
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19
];
#[cfg(test)]
mod tests {
extern crate rand;
use self::rand::Rng;
use self::rand::isaac::IsaacRng;
use serialize::hex::FromHex;
use std::iter::repeat;
use std::num::Int;
use super::{Digest, Sha256, FixedBuffer};
// A normal addition - no overflow occurs
#[test]
fn test_add_bytes_to_bits_ok() {
assert!(super::add_bytes_to_bits::<u64>(100, 10) == 180);
}
// A simple failure case - adding 1 to the max value
#[test]
#[should_fail]
fn test_add_bytes_to_bits_overflow() {
super::add_bytes_to_bits::<u64>(Int::max_value(), 1);
}
struct Test {
input: String,
output_str: String,
}
fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) {
// Test that it works when accepting the message all at once
for t in tests.iter() {
sh.reset();
sh.input_str(t.input.as_slice());
let out_str = sh.result_str();
assert!(out_str == t.output_str);
}
// Test that it works when accepting the message in pieces
for t in tests.iter() {
sh.reset();
let len = t.input.len();
let mut left = len;
while left > 0u {
let take = (left + 1us) / 2us;
sh.input_str(t.input
.slice(len - left, take + len - left));
left = left - take;
}
let out_str = sh.result_str();
assert!(out_str == t.output_str);
}
}
#[test]
fn test_sha256() {
// Examples from wikipedia
let wikipedia_tests = vec!(
Test {
input: "".to_string(),
output_str: "e3b0c44298fc1c149afb\
f4c8996fb92427ae41e4649b934ca495991b7852b855".to_string()
},
Test {
input: "The quick brown fox jumps over the lazy \
dog".to_string(),
output_str: "d7a8fbb307d7809469ca\
9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592".to_string()
},
Test {
input: "The quick brown fox jumps over the lazy \
dog.".to_string(),
output_str: "ef537f25c895bfa78252\
6529a9b63d97aa631564d5d789c2b765448c8635fb6c".to_string()
});
let tests = wikipedia_tests;
let mut sh = box Sha256::new();
test_hash(&mut *sh, tests.as_slice());
}
/// Feed 1,000,000 'a's into the digest with varying input sizes and check that the result is
/// correct.
fn test_digest_1million_random<D: Digest>(digest: &mut D, blocksize: usize, expected: &str) {
let total_size = 1000000;
let buffer: Vec<u8> = repeat('a' as u8).take(blocksize * 2).collect();
let mut rng = IsaacRng::new_unseeded();
let mut count = 0;
digest.reset();
while count < total_size {
let next: usize = rng.gen_range(0, 2 * blocksize + 1);
let remaining = total_size - count;
let size = if next > remaining { remaining } else { next };
digest.input(buffer.slice_to(size));
count += size;
}
let result_str = digest.result_str();
let result_bytes = digest.result_bytes();
assert_eq!(expected, result_str.as_slice());
let expected_vec: Vec<u8> = expected.from_hex()
.unwrap()
.into_iter()
.collect();
assert_eq!(expected_vec, result_bytes);
}
#[test]
fn | test_1million_random_sha256 | identifier_name |
|
test_apt.rs |
extern crate woko;
// use std::io::prelude::*;
#[cfg(test)]
mod tests {
use std::fs::File;
use std::io::Read;
use std::path::Path;
//use std::collections::HashMap;
use woko::apt;
fn | () -> String {
let mut f = File::open(Path::new("tests/apt.out")).unwrap();
let mut s = String::new();
f.read_to_string(&mut s).ok();
return s;
}
#[test]
fn test_woko_apt() {
let apts = apt::parse_from_string(&read()).unwrap();
let l122 = apts.get(121).unwrap();
assert_eq!(132, apts.len());
assert_eq!("http://archive.ubuntu.com/ubuntu/pool/main/r/rename/rename_0.20-4_all.deb", l122.url);
assert_eq!("rename_0.20-4_all.deb", l122.name);
assert_eq!(12010, l122.size);
assert_eq!("MD5Sum", l122.sum_type);
assert_eq!("6cf1938ef51145a469ccef181a9304ce", l122.sum);
}
}
| read | identifier_name |
test_apt.rs | extern crate woko; | #[cfg(test)]
mod tests {
use std::fs::File;
use std::io::Read;
use std::path::Path;
//use std::collections::HashMap;
use woko::apt;
fn read() -> String {
let mut f = File::open(Path::new("tests/apt.out")).unwrap();
let mut s = String::new();
f.read_to_string(&mut s).ok();
return s;
}
#[test]
fn test_woko_apt() {
let apts = apt::parse_from_string(&read()).unwrap();
let l122 = apts.get(121).unwrap();
assert_eq!(132, apts.len());
assert_eq!("http://archive.ubuntu.com/ubuntu/pool/main/r/rename/rename_0.20-4_all.deb", l122.url);
assert_eq!("rename_0.20-4_all.deb", l122.name);
assert_eq!(12010, l122.size);
assert_eq!("MD5Sum", l122.sum_type);
assert_eq!("6cf1938ef51145a469ccef181a9304ce", l122.sum);
}
} |
// use std::io::prelude::*;
| random_line_split |
test_apt.rs |
extern crate woko;
// use std::io::prelude::*;
#[cfg(test)]
mod tests {
use std::fs::File;
use std::io::Read;
use std::path::Path;
//use std::collections::HashMap;
use woko::apt;
fn read() -> String {
let mut f = File::open(Path::new("tests/apt.out")).unwrap();
let mut s = String::new();
f.read_to_string(&mut s).ok();
return s;
}
#[test]
fn test_woko_apt() |
}
| {
let apts = apt::parse_from_string(&read()).unwrap();
let l122 = apts.get(121).unwrap();
assert_eq!(132, apts.len());
assert_eq!("http://archive.ubuntu.com/ubuntu/pool/main/r/rename/rename_0.20-4_all.deb", l122.url);
assert_eq!("rename_0.20-4_all.deb", l122.name);
assert_eq!(12010, l122.size);
assert_eq!("MD5Sum", l122.sum_type);
assert_eq!("6cf1938ef51145a469ccef181a9304ce", l122.sum);
} | identifier_body |
to_toml.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use handlebars::{Handlebars, Helper, HelperDef, RenderContext, RenderError};
use toml;
use super::super::RenderResult;
#[derive(Clone, Copy)]
pub struct ToTomlHelper;
impl HelperDef for ToTomlHelper {
fn | (&self, h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> RenderResult<()> {
let param = h.param(0)
.ok_or_else(|| RenderError::new("Expected 1 parameter for \"toToml\""))?
.value();
let bytes = toml::ser::to_vec(¶m)
.map_err(|e| RenderError::new(format!("Can't serialize parameter to TOML: {}", e)))?;
rc.writer.write_all(bytes.as_ref())?;
Ok(())
}
}
pub static TO_TOML: ToTomlHelper = ToTomlHelper;
| call | identifier_name |
to_toml.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use handlebars::{Handlebars, Helper, HelperDef, RenderContext, RenderError};
use toml;
use super::super::RenderResult;
#[derive(Clone, Copy)]
pub struct ToTomlHelper;
| .value();
let bytes = toml::ser::to_vec(¶m)
.map_err(|e| RenderError::new(format!("Can't serialize parameter to TOML: {}", e)))?;
rc.writer.write_all(bytes.as_ref())?;
Ok(())
}
}
pub static TO_TOML: ToTomlHelper = ToTomlHelper; | impl HelperDef for ToTomlHelper {
fn call(&self, h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> RenderResult<()> {
let param = h.param(0)
.ok_or_else(|| RenderError::new("Expected 1 parameter for \"toToml\""))? | random_line_split |
timer.rs | use libc::{uint32_t, c_void};
use std::mem;
use sys::timer as ll;
pub fn get_ticks() -> u32 {
unsafe { ll::SDL_GetTicks() }
}
pub fn get_performance_counter() -> u64 {
unsafe { ll::SDL_GetPerformanceCounter() }
}
pub fn get_performance_frequency() -> u64 {
unsafe { ll::SDL_GetPerformanceFrequency() }
}
pub fn delay(ms: u32) {
unsafe { ll::SDL_Delay(ms) }
}
pub type TimerCallback<'a> = Box<FnMut() -> u32+'a+Sync>;
#[unstable = "Unstable because of move to unboxed closures and `box` syntax"]
pub struct Timer<'a> {
callback: Option<Box<TimerCallback<'a>>>,
_delay: u32,
raw: ll::SDL_TimerID,
}
impl<'a> Timer<'a> {
/// Constructs a new timer using the boxed closure `callback`.
/// The timer is started immediately, it will be cancelled either:
/// * when the timer is dropped
/// * or when the callback returns a non-positive continuation interval
pub fn new(delay: u32, callback: TimerCallback<'a>) -> Timer<'a> {
unsafe {
let callback = Box::new(callback);
let timer_id = ll::SDL_AddTimer(delay,
Some(c_timer_callback),
mem::transmute_copy(&callback));
Timer {
callback: Some(callback),
_delay: delay,
raw: timer_id,
}
}
}
/// Returns the closure as a trait-object and cancels the timer
/// by consuming it...
pub fn into_inner(mut self) -> TimerCallback<'a> {
*self.callback.take().unwrap()
}
}
#[unsafe_destructor]
impl<'a> Drop for Timer<'a> {
fn drop(&mut self) {
let ret = unsafe { ll::SDL_RemoveTimer(self.raw) };
if ret!= 1 |
}
}
extern "C" fn c_timer_callback(_interval: u32, param: *const c_void) -> uint32_t {
unsafe {
let f: *const Box<Fn() -> u32> = mem::transmute(param);
(*f)() as uint32_t
}
}
#[cfg(test)] use std::sync::{StaticMutex, MUTEX_INIT};
#[cfg(test)] static TIMER_INIT_LOCK: StaticMutex = MUTEX_INIT;
#[test]
fn test_timer_runs_multiple_times() {
use std::sync::{Arc, Mutex};
let _running = TIMER_INIT_LOCK.lock().unwrap();
::sdl::init(::sdl::INIT_TIMER).unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
let _timer = Timer::new(20, Box::new(|| {
// increment up to 10 times (0 -> 9)
// tick again in 100ms after each increment
//
let mut num = timer_num.lock().unwrap();
if *num < 9 {
*num += 1;
20
} else { 0 }
}));
delay(250); // tick the timer at least 10 times w/ 200ms of "buffer"
let num = local_num.lock().unwrap(); // read the number back
assert_eq!(*num, 9); // it should have incremented at least 10 times...
}
#[test]
fn test_timer_runs_at_least_once() {
use std::sync::{Arc, Mutex};
let _running = TIMER_INIT_LOCK.lock().unwrap();
::sdl::init(::sdl::INIT_TIMER).unwrap();
let local_flag = Arc::new(Mutex::new(false));
let timer_flag = local_flag.clone();
let _timer = Timer::new(20, Box::new(|| {
let mut flag = timer_flag.lock().unwrap();
*flag = true; 0
}));
delay(50);
let flag = local_flag.lock().unwrap();
assert_eq!(*flag, true);
}
#[test]
fn test_timer_can_be_recreated() {
use std::sync::{Arc, Mutex};
let _running = TIMER_INIT_LOCK.lock().unwrap();
::sdl::init(::sdl::INIT_TIMER).unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
// run the timer once and reclaim its closure
let timer_1 = Timer::new(20, Box::new(move|| {
let mut num = timer_num.lock().unwrap();
*num += 1; // increment the number
0 // do not run timer again
}));
// reclaim closure after timer runs
delay(50);
let closure = timer_1.into_inner();
// create a second timer and increment again
let _timer_2 = Timer::new(20, closure);
delay(50);
// check that timer was incremented twice
let num = local_num.lock().unwrap();
assert_eq!(*num, 2);
}
| {
println!("error dropping timer {}, maybe already removed.", self.raw);
} | conditional_block |
timer.rs | use libc::{uint32_t, c_void};
use std::mem;
use sys::timer as ll;
pub fn get_ticks() -> u32 {
unsafe { ll::SDL_GetTicks() }
}
pub fn get_performance_counter() -> u64 {
unsafe { ll::SDL_GetPerformanceCounter() }
}
pub fn get_performance_frequency() -> u64 {
unsafe { ll::SDL_GetPerformanceFrequency() }
}
pub fn delay(ms: u32) {
unsafe { ll::SDL_Delay(ms) }
}
pub type TimerCallback<'a> = Box<FnMut() -> u32+'a+Sync>;
#[unstable = "Unstable because of move to unboxed closures and `box` syntax"]
pub struct Timer<'a> {
callback: Option<Box<TimerCallback<'a>>>,
_delay: u32,
raw: ll::SDL_TimerID,
}
impl<'a> Timer<'a> {
/// Constructs a new timer using the boxed closure `callback`.
/// The timer is started immediately, it will be cancelled either:
/// * when the timer is dropped
/// * or when the callback returns a non-positive continuation interval
pub fn new(delay: u32, callback: TimerCallback<'a>) -> Timer<'a> {
unsafe {
let callback = Box::new(callback);
let timer_id = ll::SDL_AddTimer(delay,
Some(c_timer_callback),
mem::transmute_copy(&callback));
Timer {
callback: Some(callback),
_delay: delay,
raw: timer_id,
}
}
}
/// Returns the closure as a trait-object and cancels the timer
/// by consuming it...
pub fn into_inner(mut self) -> TimerCallback<'a> {
*self.callback.take().unwrap()
}
}
#[unsafe_destructor]
impl<'a> Drop for Timer<'a> {
fn drop(&mut self) {
let ret = unsafe { ll::SDL_RemoveTimer(self.raw) };
if ret!= 1 {
println!("error dropping timer {}, maybe already removed.", self.raw);
}
}
}
extern "C" fn c_timer_callback(_interval: u32, param: *const c_void) -> uint32_t |
#[cfg(test)] use std::sync::{StaticMutex, MUTEX_INIT};
#[cfg(test)] static TIMER_INIT_LOCK: StaticMutex = MUTEX_INIT;
#[test]
fn test_timer_runs_multiple_times() {
use std::sync::{Arc, Mutex};
let _running = TIMER_INIT_LOCK.lock().unwrap();
::sdl::init(::sdl::INIT_TIMER).unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
let _timer = Timer::new(20, Box::new(|| {
// increment up to 10 times (0 -> 9)
// tick again in 100ms after each increment
//
let mut num = timer_num.lock().unwrap();
if *num < 9 {
*num += 1;
20
} else { 0 }
}));
delay(250); // tick the timer at least 10 times w/ 200ms of "buffer"
let num = local_num.lock().unwrap(); // read the number back
assert_eq!(*num, 9); // it should have incremented at least 10 times...
}
#[test]
fn test_timer_runs_at_least_once() {
use std::sync::{Arc, Mutex};
let _running = TIMER_INIT_LOCK.lock().unwrap();
::sdl::init(::sdl::INIT_TIMER).unwrap();
let local_flag = Arc::new(Mutex::new(false));
let timer_flag = local_flag.clone();
let _timer = Timer::new(20, Box::new(|| {
let mut flag = timer_flag.lock().unwrap();
*flag = true; 0
}));
delay(50);
let flag = local_flag.lock().unwrap();
assert_eq!(*flag, true);
}
#[test]
fn test_timer_can_be_recreated() {
use std::sync::{Arc, Mutex};
let _running = TIMER_INIT_LOCK.lock().unwrap();
::sdl::init(::sdl::INIT_TIMER).unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
// run the timer once and reclaim its closure
let timer_1 = Timer::new(20, Box::new(move|| {
let mut num = timer_num.lock().unwrap();
*num += 1; // increment the number
0 // do not run timer again
}));
// reclaim closure after timer runs
delay(50);
let closure = timer_1.into_inner();
// create a second timer and increment again
let _timer_2 = Timer::new(20, closure);
delay(50);
// check that timer was incremented twice
let num = local_num.lock().unwrap();
assert_eq!(*num, 2);
}
| {
unsafe {
let f: *const Box<Fn() -> u32> = mem::transmute(param);
(*f)() as uint32_t
}
} | identifier_body |
timer.rs | use libc::{uint32_t, c_void};
use std::mem;
use sys::timer as ll;
pub fn get_ticks() -> u32 {
unsafe { ll::SDL_GetTicks() }
}
pub fn get_performance_counter() -> u64 {
unsafe { ll::SDL_GetPerformanceCounter() }
}
pub fn get_performance_frequency() -> u64 {
unsafe { ll::SDL_GetPerformanceFrequency() }
}
pub fn delay(ms: u32) {
unsafe { ll::SDL_Delay(ms) }
}
pub type TimerCallback<'a> = Box<FnMut() -> u32+'a+Sync>;
#[unstable = "Unstable because of move to unboxed closures and `box` syntax"]
pub struct Timer<'a> {
callback: Option<Box<TimerCallback<'a>>>,
_delay: u32,
raw: ll::SDL_TimerID,
}
impl<'a> Timer<'a> {
/// Constructs a new timer using the boxed closure `callback`.
/// The timer is started immediately, it will be cancelled either:
/// * when the timer is dropped
/// * or when the callback returns a non-positive continuation interval
pub fn new(delay: u32, callback: TimerCallback<'a>) -> Timer<'a> {
unsafe {
let callback = Box::new(callback);
let timer_id = ll::SDL_AddTimer(delay,
Some(c_timer_callback),
mem::transmute_copy(&callback));
Timer {
callback: Some(callback),
_delay: delay,
raw: timer_id,
}
}
}
/// Returns the closure as a trait-object and cancels the timer
/// by consuming it...
pub fn into_inner(mut self) -> TimerCallback<'a> {
*self.callback.take().unwrap()
}
}
#[unsafe_destructor]
impl<'a> Drop for Timer<'a> {
fn | (&mut self) {
let ret = unsafe { ll::SDL_RemoveTimer(self.raw) };
if ret!= 1 {
println!("error dropping timer {}, maybe already removed.", self.raw);
}
}
}
extern "C" fn c_timer_callback(_interval: u32, param: *const c_void) -> uint32_t {
unsafe {
let f: *const Box<Fn() -> u32> = mem::transmute(param);
(*f)() as uint32_t
}
}
#[cfg(test)] use std::sync::{StaticMutex, MUTEX_INIT};
#[cfg(test)] static TIMER_INIT_LOCK: StaticMutex = MUTEX_INIT;
#[test]
fn test_timer_runs_multiple_times() {
use std::sync::{Arc, Mutex};
let _running = TIMER_INIT_LOCK.lock().unwrap();
::sdl::init(::sdl::INIT_TIMER).unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
let _timer = Timer::new(20, Box::new(|| {
// increment up to 10 times (0 -> 9)
// tick again in 100ms after each increment
//
let mut num = timer_num.lock().unwrap();
if *num < 9 {
*num += 1;
20
} else { 0 }
}));
delay(250); // tick the timer at least 10 times w/ 200ms of "buffer"
let num = local_num.lock().unwrap(); // read the number back
assert_eq!(*num, 9); // it should have incremented at least 10 times...
}
#[test]
fn test_timer_runs_at_least_once() {
use std::sync::{Arc, Mutex};
let _running = TIMER_INIT_LOCK.lock().unwrap();
::sdl::init(::sdl::INIT_TIMER).unwrap();
let local_flag = Arc::new(Mutex::new(false));
let timer_flag = local_flag.clone();
let _timer = Timer::new(20, Box::new(|| {
let mut flag = timer_flag.lock().unwrap();
*flag = true; 0
}));
delay(50);
let flag = local_flag.lock().unwrap();
assert_eq!(*flag, true);
}
#[test]
fn test_timer_can_be_recreated() {
use std::sync::{Arc, Mutex};
let _running = TIMER_INIT_LOCK.lock().unwrap();
::sdl::init(::sdl::INIT_TIMER).unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
// run the timer once and reclaim its closure
let timer_1 = Timer::new(20, Box::new(move|| {
let mut num = timer_num.lock().unwrap();
*num += 1; // increment the number
0 // do not run timer again
}));
// reclaim closure after timer runs
delay(50);
let closure = timer_1.into_inner();
// create a second timer and increment again
let _timer_2 = Timer::new(20, closure);
delay(50);
// check that timer was incremented twice
let num = local_num.lock().unwrap();
assert_eq!(*num, 2);
}
| drop | identifier_name |
timer.rs | use libc::{uint32_t, c_void};
use std::mem;
use sys::timer as ll;
pub fn get_ticks() -> u32 {
unsafe { ll::SDL_GetTicks() }
}
pub fn get_performance_counter() -> u64 {
unsafe { ll::SDL_GetPerformanceCounter() }
}
pub fn get_performance_frequency() -> u64 {
unsafe { ll::SDL_GetPerformanceFrequency() }
}
pub fn delay(ms: u32) {
unsafe { ll::SDL_Delay(ms) }
}
pub type TimerCallback<'a> = Box<FnMut() -> u32+'a+Sync>;
#[unstable = "Unstable because of move to unboxed closures and `box` syntax"]
pub struct Timer<'a> {
callback: Option<Box<TimerCallback<'a>>>,
_delay: u32,
raw: ll::SDL_TimerID,
}
impl<'a> Timer<'a> {
/// Constructs a new timer using the boxed closure `callback`.
/// The timer is started immediately, it will be cancelled either:
/// * when the timer is dropped
/// * or when the callback returns a non-positive continuation interval
pub fn new(delay: u32, callback: TimerCallback<'a>) -> Timer<'a> {
unsafe {
let callback = Box::new(callback);
let timer_id = ll::SDL_AddTimer(delay,
Some(c_timer_callback),
mem::transmute_copy(&callback));
Timer {
callback: Some(callback),
_delay: delay,
raw: timer_id,
}
}
}
/// Returns the closure as a trait-object and cancels the timer
/// by consuming it...
pub fn into_inner(mut self) -> TimerCallback<'a> {
*self.callback.take().unwrap()
}
}
| impl<'a> Drop for Timer<'a> {
fn drop(&mut self) {
let ret = unsafe { ll::SDL_RemoveTimer(self.raw) };
if ret!= 1 {
println!("error dropping timer {}, maybe already removed.", self.raw);
}
}
}
extern "C" fn c_timer_callback(_interval: u32, param: *const c_void) -> uint32_t {
unsafe {
let f: *const Box<Fn() -> u32> = mem::transmute(param);
(*f)() as uint32_t
}
}
#[cfg(test)] use std::sync::{StaticMutex, MUTEX_INIT};
#[cfg(test)] static TIMER_INIT_LOCK: StaticMutex = MUTEX_INIT;
#[test]
fn test_timer_runs_multiple_times() {
use std::sync::{Arc, Mutex};
let _running = TIMER_INIT_LOCK.lock().unwrap();
::sdl::init(::sdl::INIT_TIMER).unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
let _timer = Timer::new(20, Box::new(|| {
// increment up to 10 times (0 -> 9)
// tick again in 100ms after each increment
//
let mut num = timer_num.lock().unwrap();
if *num < 9 {
*num += 1;
20
} else { 0 }
}));
delay(250); // tick the timer at least 10 times w/ 200ms of "buffer"
let num = local_num.lock().unwrap(); // read the number back
assert_eq!(*num, 9); // it should have incremented at least 10 times...
}
#[test]
fn test_timer_runs_at_least_once() {
use std::sync::{Arc, Mutex};
let _running = TIMER_INIT_LOCK.lock().unwrap();
::sdl::init(::sdl::INIT_TIMER).unwrap();
let local_flag = Arc::new(Mutex::new(false));
let timer_flag = local_flag.clone();
let _timer = Timer::new(20, Box::new(|| {
let mut flag = timer_flag.lock().unwrap();
*flag = true; 0
}));
delay(50);
let flag = local_flag.lock().unwrap();
assert_eq!(*flag, true);
}
#[test]
fn test_timer_can_be_recreated() {
use std::sync::{Arc, Mutex};
let _running = TIMER_INIT_LOCK.lock().unwrap();
::sdl::init(::sdl::INIT_TIMER).unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
// run the timer once and reclaim its closure
let timer_1 = Timer::new(20, Box::new(move|| {
let mut num = timer_num.lock().unwrap();
*num += 1; // increment the number
0 // do not run timer again
}));
// reclaim closure after timer runs
delay(50);
let closure = timer_1.into_inner();
// create a second timer and increment again
let _timer_2 = Timer::new(20, closure);
delay(50);
// check that timer was incremented twice
let num = local_num.lock().unwrap();
assert_eq!(*num, 2);
} | #[unsafe_destructor] | random_line_split |
by-move-pattern-binding.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.
enum E {
Foo,
Bar(String)
}
struct | {
x: E
}
fn f(x: String) {}
fn main() {
let s = S { x: E::Bar("hello".to_string()) };
match &s.x {
&E::Foo => {}
&E::Bar(identifier) => f(identifier.clone()) //~ ERROR cannot move
};
match &s.x {
&E::Foo => {}
&E::Bar(ref identifier) => println!("{}", *identifier)
};
}
| S | identifier_name |
by-move-pattern-binding.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.
| }
struct S {
x: E
}
fn f(x: String) {}
fn main() {
let s = S { x: E::Bar("hello".to_string()) };
match &s.x {
&E::Foo => {}
&E::Bar(identifier) => f(identifier.clone()) //~ ERROR cannot move
};
match &s.x {
&E::Foo => {}
&E::Bar(ref identifier) => println!("{}", *identifier)
};
} | enum E {
Foo,
Bar(String) | random_line_split |
by-move-pattern-binding.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.
enum E {
Foo,
Bar(String)
}
struct S {
x: E
}
fn f(x: String) |
fn main() {
let s = S { x: E::Bar("hello".to_string()) };
match &s.x {
&E::Foo => {}
&E::Bar(identifier) => f(identifier.clone()) //~ ERROR cannot move
};
match &s.x {
&E::Foo => {}
&E::Bar(ref identifier) => println!("{}", *identifier)
};
}
| {} | identifier_body |
hgid.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#[cfg(any(test, feature = "for-tests"))]
use std::collections::HashSet;
use std::io::Read;
use std::io::Write;
use std::io::{self};
#[cfg(any(test, feature = "for-tests"))]
use rand::RngCore;
use sha1::Digest;
use sha1::Sha1;
use crate::hash::AbstractHashType;
use crate::hash::HashTypeInfo;
use crate::parents::Parents;
/// A 20-byte identifier, often a hash. Nodes are used to uniquely identify
/// commits, file versions, and many other things.
///
///
/// # Serde Serialization
///
/// The `serde_with` module allows customization on `HgId` serialization:
/// - `#[serde(with = "types::serde_with::hgid::bytes")]` (current default)
/// - `#[serde(with = "types::serde_with::hgid::hex")]`
/// - `#[serde(with = "types::serde_with::hgid::tuple")]`
///
/// Using them can change the size or the type of serialization result:
///
/// | lib \ serde_with | hgid::tuple | hgid::bytes | hgid::hex |
/// |------------------|---------------------|--------------|-----------|
/// | mincode | 20 bytes | 21 bytes | 41 bytes |
/// | cbor | 21 to 41 bytes [1] | 21 bytes | 42 bytes |
/// | json | 41 to 81+ bytes [1] | invalid [2] | 42 bytes |
/// | python | Tuple[int] | bytes | str |
///
/// In general,
/// - `hgid::tuple` only works best for `mincode`.
/// - `hgid::bytes` works best for cbor, python.
/// - `hgid::hex` is useful for `json`, or other text-only formats.
///
/// Compatibility note:
/// - `hgid::tuple` cannot decode `hgid::bytes` or `hgid::hex` data.
/// - `hgid::hex` can decode `hgid::bytes` data, or vice-versa. They share a
/// same `deserialize` implementation.
/// - `hgid::hex` or `hgid::bytes` might be able to decode `hgid::tuple` data,
/// depending on how tuples are serialized. For example, mincode
/// does not add framing for tuples, so `hgid::bytes` cannot decode
/// `hgid::tuple` data; cbor adds framing for tuples, so `hgid::bytes`
/// can decode `hgid::tuple` data.
///
/// [1]: Depends on actual data of `HgId`.
/// [2]: JSON only supports utf-8 data.
pub type HgId = AbstractHashType<HgIdTypeInfo, 20>;
pub struct HgIdTypeInfo;
impl HashTypeInfo for HgIdTypeInfo {
const HASH_TYPE_NAME: &'static str = "HgId";
}
/// The nullid (0x00) is used throughout Mercurial to represent "None".
/// (For example, a commit will have a nullid p2, if it has no second parent).
pub const NULL_ID: HgId = HgId::from_byte_array([0; HgId::len()]);
/// The hard-coded 'working copy parent' Mercurial id.
pub const WDIR_ID: HgId = HgId::from_byte_array([0xff; HgId::len()]);
impl HgId {
pub fn null_id() -> &'static Self {
&NULL_ID
}
pub fn is_null(&self) -> bool {
self == &NULL_ID
}
pub const fn wdir_id() -> &'static Self {
&WDIR_ID
}
pub fn is_wdir(&self) -> bool {
self == &WDIR_ID
}
pub fn from_content(data: &[u8], parents: Parents) -> Self {
// Parents must be hashed in sorted order.
let (p1, p2) = match parents.into_nodes() {
(p1, p2) if p1 > p2 => (p2, p1),
(p1, p2) => (p1, p2),
};
let mut hasher = Sha1::new();
hasher.input(p1.as_ref());
hasher.input(p2.as_ref());
hasher.input(data);
let hash: [u8; 20] = hasher.result().into();
HgId::from_byte_array(hash)
}
#[cfg(any(test, feature = "for-tests"))]
pub fn random(rng: &mut dyn RngCore) -> Self {
let mut bytes = [0; HgId::len()];
rng.fill_bytes(&mut bytes);
loop {
let hgid = HgId::from(&bytes);
if!hgid.is_null() {
return hgid;
}
}
}
#[cfg(any(test, feature = "for-tests"))]
pub fn random_distinct(rng: &mut dyn RngCore, count: usize) -> Vec<Self> {
let mut nodes = Vec::new();
let mut nodeset = HashSet::new();
while nodes.len() < count {
let hgid = HgId::random(rng);
if!nodeset.contains(&hgid) {
nodeset.insert(hgid.clone());
nodes.push(hgid);
}
}
nodes
}
}
impl<'a> From<&'a [u8; HgId::len()]> for HgId {
fn from(bytes: &[u8; HgId::len()]) -> HgId {
HgId::from_byte_array(bytes.clone())
}
}
pub trait WriteHgIdExt {
/// Write a ``HgId`` directly to a stream.
///
/// # Examples
///
/// ```
/// use types::hgid::{HgId, WriteHgIdExt};
/// let mut v = vec![];
///
/// let n = HgId::null_id();
/// v.write_hgid(&n).expect("writing a hgid to a vec should work");
///
/// assert_eq!(v, vec![0; HgId::len()]);
/// ```
fn write_hgid(&mut self, value: &HgId) -> io::Result<()>;
}
impl<W: Write +?Sized> WriteHgIdExt for W {
fn write_hgid(&mut self, value: &HgId) -> io::Result<()> {
self.write_all(value.as_ref())
}
}
pub trait ReadHgIdExt {
/// Read a ``HgId`` directly from a stream.
///
/// # Examples
///
/// ```
/// use std::io::Cursor;
/// use types::hgid::{HgId, ReadHgIdExt};
/// let mut v = vec![0; HgId::len()];
/// let mut c = Cursor::new(v);
///
/// let n = c.read_hgid().expect("reading a hgid from a vec should work");
///
/// assert_eq!(&n, HgId::null_id());
/// ```
fn read_hgid(&mut self) -> io::Result<HgId>;
}
impl<R: Read +?Sized> ReadHgIdExt for R {
fn read_hgid(&mut self) -> io::Result<HgId> {
let mut bytes = [0; HgId::len()];
self.read_exact(&mut bytes)?;
Ok(HgId::from_byte_array(bytes))
}
}
#[cfg(any(test, feature = "for-tests"))]
pub mod mocks {
use super::HgId;
pub const ONES: HgId = HgId::from_byte_array([0x11; HgId::len()]);
pub const TWOS: HgId = HgId::from_byte_array([0x22; HgId::len()]);
pub const THREES: HgId = HgId::from_byte_array([0x33; HgId::len()]);
pub const FOURS: HgId = HgId::from_byte_array([0x44; HgId::len()]);
pub const FIVES: HgId = HgId::from_byte_array([0x55; HgId::len()]);
pub const SIXES: HgId = HgId::from_byte_array([0x66; HgId::len()]);
pub const SEVENS: HgId = HgId::from_byte_array([0x77; HgId::len()]);
pub const EIGHTS: HgId = HgId::from_byte_array([0x88; HgId::len()]);
pub const NINES: HgId = HgId::from_byte_array([0x99; HgId::len()]);
pub const AS: HgId = HgId::from_byte_array([0xAA; HgId::len()]);
pub const BS: HgId = HgId::from_byte_array([0xAB; HgId::len()]);
pub const CS: HgId = HgId::from_byte_array([0xCC; HgId::len()]);
pub const DS: HgId = HgId::from_byte_array([0xDD; HgId::len()]);
pub const ES: HgId = HgId::from_byte_array([0xEE; HgId::len()]);
pub const FS: HgId = HgId::from_byte_array([0xFF; HgId::len()]);
}
#[cfg(test)]
mod tests {
use quickcheck::quickcheck;
use serde::Deserialize;
use serde::Serialize;
use super::*;
#[test]
fn | () {
HgId::from_slice(&[0u8; 25]).expect_err("bad slice length");
}
#[test]
fn test_serde_with_using_cbor() {
// Note: this test is for CBOR. Other serializers like mincode
// or Thrift would have different backwards compatibility!
use serde_cbor::de::from_slice as decode;
use serde_cbor::ser::to_vec as encode;
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct Orig(#[serde(with = "crate::serde_with::hgid::tuple")] HgId);
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct Bytes(#[serde(with = "crate::serde_with::hgid::bytes")] HgId);
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct Hex(#[serde(with = "crate::serde_with::hgid::hex")] HgId);
let id: HgId = mocks::CS;
let orig = Orig(id);
let bytes = Bytes(id);
let hex = Hex(id);
let cbor_orig = encode(&orig).unwrap();
let cbor_bytes = encode(&bytes).unwrap();
let cbor_hex = encode(&hex).unwrap();
assert_eq!(cbor_orig.len(), 41);
assert_eq!(cbor_bytes.len(), 21);
assert_eq!(cbor_hex.len(), 42);
// Orig cannot decode bytes or hex.
assert_eq!(decode::<Orig>(&cbor_orig).unwrap().0, id);
decode::<Orig>(&cbor_bytes).unwrap_err();
decode::<Orig>(&cbor_hex).unwrap_err();
// Bytes can decode all 3 formats.
assert_eq!(decode::<Bytes>(&cbor_orig).unwrap().0, id);
assert_eq!(decode::<Bytes>(&cbor_bytes).unwrap().0, id);
assert_eq!(decode::<Bytes>(&cbor_hex).unwrap().0, id);
// Hex can decode all 3 formats.
assert_eq!(decode::<Hex>(&cbor_orig).unwrap().0, id);
assert_eq!(decode::<Hex>(&cbor_bytes).unwrap().0, id);
assert_eq!(decode::<Hex>(&cbor_hex).unwrap().0, id);
}
quickcheck! {
fn test_from_slice(hgid: HgId) -> bool {
hgid == HgId::from_slice(hgid.as_ref()).expect("from_slice")
}
}
}
| test_incorrect_length | identifier_name |
hgid.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#[cfg(any(test, feature = "for-tests"))]
use std::collections::HashSet;
use std::io::Read;
use std::io::Write;
use std::io::{self};
#[cfg(any(test, feature = "for-tests"))]
use rand::RngCore;
use sha1::Digest;
use sha1::Sha1;
use crate::hash::AbstractHashType;
use crate::hash::HashTypeInfo;
use crate::parents::Parents;
/// A 20-byte identifier, often a hash. Nodes are used to uniquely identify
/// commits, file versions, and many other things.
///
///
/// # Serde Serialization
///
/// The `serde_with` module allows customization on `HgId` serialization:
/// - `#[serde(with = "types::serde_with::hgid::bytes")]` (current default)
/// - `#[serde(with = "types::serde_with::hgid::hex")]`
/// - `#[serde(with = "types::serde_with::hgid::tuple")]`
///
/// Using them can change the size or the type of serialization result:
///
/// | lib \ serde_with | hgid::tuple | hgid::bytes | hgid::hex |
/// |------------------|---------------------|--------------|-----------|
/// | mincode | 20 bytes | 21 bytes | 41 bytes |
/// | cbor | 21 to 41 bytes [1] | 21 bytes | 42 bytes |
/// | json | 41 to 81+ bytes [1] | invalid [2] | 42 bytes |
/// | python | Tuple[int] | bytes | str |
///
/// In general,
/// - `hgid::tuple` only works best for `mincode`.
/// - `hgid::bytes` works best for cbor, python.
/// - `hgid::hex` is useful for `json`, or other text-only formats.
///
/// Compatibility note:
/// - `hgid::tuple` cannot decode `hgid::bytes` or `hgid::hex` data.
/// - `hgid::hex` can decode `hgid::bytes` data, or vice-versa. They share a
/// same `deserialize` implementation.
/// - `hgid::hex` or `hgid::bytes` might be able to decode `hgid::tuple` data,
/// depending on how tuples are serialized. For example, mincode
/// does not add framing for tuples, so `hgid::bytes` cannot decode
/// `hgid::tuple` data; cbor adds framing for tuples, so `hgid::bytes`
/// can decode `hgid::tuple` data.
///
/// [1]: Depends on actual data of `HgId`.
/// [2]: JSON only supports utf-8 data.
pub type HgId = AbstractHashType<HgIdTypeInfo, 20>;
pub struct HgIdTypeInfo;
impl HashTypeInfo for HgIdTypeInfo {
const HASH_TYPE_NAME: &'static str = "HgId";
}
/// The nullid (0x00) is used throughout Mercurial to represent "None".
/// (For example, a commit will have a nullid p2, if it has no second parent).
pub const NULL_ID: HgId = HgId::from_byte_array([0; HgId::len()]);
/// The hard-coded 'working copy parent' Mercurial id.
pub const WDIR_ID: HgId = HgId::from_byte_array([0xff; HgId::len()]);
impl HgId {
pub fn null_id() -> &'static Self {
&NULL_ID
}
pub fn is_null(&self) -> bool {
self == &NULL_ID
}
pub const fn wdir_id() -> &'static Self {
&WDIR_ID
}
pub fn is_wdir(&self) -> bool {
self == &WDIR_ID
}
pub fn from_content(data: &[u8], parents: Parents) -> Self |
#[cfg(any(test, feature = "for-tests"))]
pub fn random(rng: &mut dyn RngCore) -> Self {
let mut bytes = [0; HgId::len()];
rng.fill_bytes(&mut bytes);
loop {
let hgid = HgId::from(&bytes);
if!hgid.is_null() {
return hgid;
}
}
}
#[cfg(any(test, feature = "for-tests"))]
pub fn random_distinct(rng: &mut dyn RngCore, count: usize) -> Vec<Self> {
let mut nodes = Vec::new();
let mut nodeset = HashSet::new();
while nodes.len() < count {
let hgid = HgId::random(rng);
if!nodeset.contains(&hgid) {
nodeset.insert(hgid.clone());
nodes.push(hgid);
}
}
nodes
}
}
impl<'a> From<&'a [u8; HgId::len()]> for HgId {
fn from(bytes: &[u8; HgId::len()]) -> HgId {
HgId::from_byte_array(bytes.clone())
}
}
pub trait WriteHgIdExt {
/// Write a ``HgId`` directly to a stream.
///
/// # Examples
///
/// ```
/// use types::hgid::{HgId, WriteHgIdExt};
/// let mut v = vec![];
///
/// let n = HgId::null_id();
/// v.write_hgid(&n).expect("writing a hgid to a vec should work");
///
/// assert_eq!(v, vec![0; HgId::len()]);
/// ```
fn write_hgid(&mut self, value: &HgId) -> io::Result<()>;
}
impl<W: Write +?Sized> WriteHgIdExt for W {
fn write_hgid(&mut self, value: &HgId) -> io::Result<()> {
self.write_all(value.as_ref())
}
}
pub trait ReadHgIdExt {
/// Read a ``HgId`` directly from a stream.
///
/// # Examples
///
/// ```
/// use std::io::Cursor;
/// use types::hgid::{HgId, ReadHgIdExt};
/// let mut v = vec![0; HgId::len()];
/// let mut c = Cursor::new(v);
///
/// let n = c.read_hgid().expect("reading a hgid from a vec should work");
///
/// assert_eq!(&n, HgId::null_id());
/// ```
fn read_hgid(&mut self) -> io::Result<HgId>;
}
impl<R: Read +?Sized> ReadHgIdExt for R {
fn read_hgid(&mut self) -> io::Result<HgId> {
let mut bytes = [0; HgId::len()];
self.read_exact(&mut bytes)?;
Ok(HgId::from_byte_array(bytes))
}
}
#[cfg(any(test, feature = "for-tests"))]
pub mod mocks {
use super::HgId;
pub const ONES: HgId = HgId::from_byte_array([0x11; HgId::len()]);
pub const TWOS: HgId = HgId::from_byte_array([0x22; HgId::len()]);
pub const THREES: HgId = HgId::from_byte_array([0x33; HgId::len()]);
pub const FOURS: HgId = HgId::from_byte_array([0x44; HgId::len()]);
pub const FIVES: HgId = HgId::from_byte_array([0x55; HgId::len()]);
pub const SIXES: HgId = HgId::from_byte_array([0x66; HgId::len()]);
pub const SEVENS: HgId = HgId::from_byte_array([0x77; HgId::len()]);
pub const EIGHTS: HgId = HgId::from_byte_array([0x88; HgId::len()]);
pub const NINES: HgId = HgId::from_byte_array([0x99; HgId::len()]);
pub const AS: HgId = HgId::from_byte_array([0xAA; HgId::len()]);
pub const BS: HgId = HgId::from_byte_array([0xAB; HgId::len()]);
pub const CS: HgId = HgId::from_byte_array([0xCC; HgId::len()]);
pub const DS: HgId = HgId::from_byte_array([0xDD; HgId::len()]);
pub const ES: HgId = HgId::from_byte_array([0xEE; HgId::len()]);
pub const FS: HgId = HgId::from_byte_array([0xFF; HgId::len()]);
}
#[cfg(test)]
mod tests {
use quickcheck::quickcheck;
use serde::Deserialize;
use serde::Serialize;
use super::*;
#[test]
fn test_incorrect_length() {
HgId::from_slice(&[0u8; 25]).expect_err("bad slice length");
}
#[test]
fn test_serde_with_using_cbor() {
// Note: this test is for CBOR. Other serializers like mincode
// or Thrift would have different backwards compatibility!
use serde_cbor::de::from_slice as decode;
use serde_cbor::ser::to_vec as encode;
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct Orig(#[serde(with = "crate::serde_with::hgid::tuple")] HgId);
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct Bytes(#[serde(with = "crate::serde_with::hgid::bytes")] HgId);
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct Hex(#[serde(with = "crate::serde_with::hgid::hex")] HgId);
let id: HgId = mocks::CS;
let orig = Orig(id);
let bytes = Bytes(id);
let hex = Hex(id);
let cbor_orig = encode(&orig).unwrap();
let cbor_bytes = encode(&bytes).unwrap();
let cbor_hex = encode(&hex).unwrap();
assert_eq!(cbor_orig.len(), 41);
assert_eq!(cbor_bytes.len(), 21);
assert_eq!(cbor_hex.len(), 42);
// Orig cannot decode bytes or hex.
assert_eq!(decode::<Orig>(&cbor_orig).unwrap().0, id);
decode::<Orig>(&cbor_bytes).unwrap_err();
decode::<Orig>(&cbor_hex).unwrap_err();
// Bytes can decode all 3 formats.
assert_eq!(decode::<Bytes>(&cbor_orig).unwrap().0, id);
assert_eq!(decode::<Bytes>(&cbor_bytes).unwrap().0, id);
assert_eq!(decode::<Bytes>(&cbor_hex).unwrap().0, id);
// Hex can decode all 3 formats.
assert_eq!(decode::<Hex>(&cbor_orig).unwrap().0, id);
assert_eq!(decode::<Hex>(&cbor_bytes).unwrap().0, id);
assert_eq!(decode::<Hex>(&cbor_hex).unwrap().0, id);
}
quickcheck! {
fn test_from_slice(hgid: HgId) -> bool {
hgid == HgId::from_slice(hgid.as_ref()).expect("from_slice")
}
}
}
| {
// Parents must be hashed in sorted order.
let (p1, p2) = match parents.into_nodes() {
(p1, p2) if p1 > p2 => (p2, p1),
(p1, p2) => (p1, p2),
};
let mut hasher = Sha1::new();
hasher.input(p1.as_ref());
hasher.input(p2.as_ref());
hasher.input(data);
let hash: [u8; 20] = hasher.result().into();
HgId::from_byte_array(hash)
} | identifier_body |
hgid.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#[cfg(any(test, feature = "for-tests"))]
use std::collections::HashSet;
use std::io::Read;
use std::io::Write;
use std::io::{self};
#[cfg(any(test, feature = "for-tests"))]
use rand::RngCore;
use sha1::Digest;
use sha1::Sha1;
use crate::hash::AbstractHashType;
use crate::hash::HashTypeInfo;
use crate::parents::Parents;
/// A 20-byte identifier, often a hash. Nodes are used to uniquely identify
/// commits, file versions, and many other things.
///
///
/// # Serde Serialization
///
/// The `serde_with` module allows customization on `HgId` serialization:
/// - `#[serde(with = "types::serde_with::hgid::bytes")]` (current default)
/// - `#[serde(with = "types::serde_with::hgid::hex")]`
/// - `#[serde(with = "types::serde_with::hgid::tuple")]`
///
/// Using them can change the size or the type of serialization result:
///
/// | lib \ serde_with | hgid::tuple | hgid::bytes | hgid::hex |
/// |------------------|---------------------|--------------|-----------|
/// | mincode | 20 bytes | 21 bytes | 41 bytes |
/// | cbor | 21 to 41 bytes [1] | 21 bytes | 42 bytes |
/// | json | 41 to 81+ bytes [1] | invalid [2] | 42 bytes |
/// | python | Tuple[int] | bytes | str |
///
/// In general,
/// - `hgid::tuple` only works best for `mincode`.
/// - `hgid::bytes` works best for cbor, python.
/// - `hgid::hex` is useful for `json`, or other text-only formats.
///
/// Compatibility note:
/// - `hgid::tuple` cannot decode `hgid::bytes` or `hgid::hex` data.
/// - `hgid::hex` can decode `hgid::bytes` data, or vice-versa. They share a
/// same `deserialize` implementation.
/// - `hgid::hex` or `hgid::bytes` might be able to decode `hgid::tuple` data,
/// depending on how tuples are serialized. For example, mincode
/// does not add framing for tuples, so `hgid::bytes` cannot decode
/// `hgid::tuple` data; cbor adds framing for tuples, so `hgid::bytes`
/// can decode `hgid::tuple` data.
///
/// [1]: Depends on actual data of `HgId`.
/// [2]: JSON only supports utf-8 data.
pub type HgId = AbstractHashType<HgIdTypeInfo, 20>;
pub struct HgIdTypeInfo;
impl HashTypeInfo for HgIdTypeInfo {
const HASH_TYPE_NAME: &'static str = "HgId";
}
/// The nullid (0x00) is used throughout Mercurial to represent "None".
/// (For example, a commit will have a nullid p2, if it has no second parent).
pub const NULL_ID: HgId = HgId::from_byte_array([0; HgId::len()]);
/// The hard-coded 'working copy parent' Mercurial id.
pub const WDIR_ID: HgId = HgId::from_byte_array([0xff; HgId::len()]);
impl HgId {
pub fn null_id() -> &'static Self {
&NULL_ID
}
pub fn is_null(&self) -> bool {
self == &NULL_ID
}
pub const fn wdir_id() -> &'static Self {
&WDIR_ID
}
pub fn is_wdir(&self) -> bool {
self == &WDIR_ID
}
pub fn from_content(data: &[u8], parents: Parents) -> Self {
// Parents must be hashed in sorted order.
let (p1, p2) = match parents.into_nodes() {
(p1, p2) if p1 > p2 => (p2, p1),
(p1, p2) => (p1, p2),
};
let mut hasher = Sha1::new();
hasher.input(p1.as_ref());
hasher.input(p2.as_ref());
hasher.input(data);
let hash: [u8; 20] = hasher.result().into();
HgId::from_byte_array(hash)
}
#[cfg(any(test, feature = "for-tests"))]
pub fn random(rng: &mut dyn RngCore) -> Self {
let mut bytes = [0; HgId::len()];
rng.fill_bytes(&mut bytes);
loop {
let hgid = HgId::from(&bytes);
if!hgid.is_null() {
return hgid;
}
}
}
#[cfg(any(test, feature = "for-tests"))]
pub fn random_distinct(rng: &mut dyn RngCore, count: usize) -> Vec<Self> {
let mut nodes = Vec::new();
let mut nodeset = HashSet::new();
while nodes.len() < count {
let hgid = HgId::random(rng);
if!nodeset.contains(&hgid) |
}
nodes
}
}
impl<'a> From<&'a [u8; HgId::len()]> for HgId {
fn from(bytes: &[u8; HgId::len()]) -> HgId {
HgId::from_byte_array(bytes.clone())
}
}
pub trait WriteHgIdExt {
/// Write a ``HgId`` directly to a stream.
///
/// # Examples
///
/// ```
/// use types::hgid::{HgId, WriteHgIdExt};
/// let mut v = vec![];
///
/// let n = HgId::null_id();
/// v.write_hgid(&n).expect("writing a hgid to a vec should work");
///
/// assert_eq!(v, vec![0; HgId::len()]);
/// ```
fn write_hgid(&mut self, value: &HgId) -> io::Result<()>;
}
impl<W: Write +?Sized> WriteHgIdExt for W {
fn write_hgid(&mut self, value: &HgId) -> io::Result<()> {
self.write_all(value.as_ref())
}
}
pub trait ReadHgIdExt {
/// Read a ``HgId`` directly from a stream.
///
/// # Examples
///
/// ```
/// use std::io::Cursor;
/// use types::hgid::{HgId, ReadHgIdExt};
/// let mut v = vec![0; HgId::len()];
/// let mut c = Cursor::new(v);
///
/// let n = c.read_hgid().expect("reading a hgid from a vec should work");
///
/// assert_eq!(&n, HgId::null_id());
/// ```
fn read_hgid(&mut self) -> io::Result<HgId>;
}
impl<R: Read +?Sized> ReadHgIdExt for R {
fn read_hgid(&mut self) -> io::Result<HgId> {
let mut bytes = [0; HgId::len()];
self.read_exact(&mut bytes)?;
Ok(HgId::from_byte_array(bytes))
}
}
#[cfg(any(test, feature = "for-tests"))]
pub mod mocks {
use super::HgId;
pub const ONES: HgId = HgId::from_byte_array([0x11; HgId::len()]);
pub const TWOS: HgId = HgId::from_byte_array([0x22; HgId::len()]);
pub const THREES: HgId = HgId::from_byte_array([0x33; HgId::len()]);
pub const FOURS: HgId = HgId::from_byte_array([0x44; HgId::len()]);
pub const FIVES: HgId = HgId::from_byte_array([0x55; HgId::len()]);
pub const SIXES: HgId = HgId::from_byte_array([0x66; HgId::len()]);
pub const SEVENS: HgId = HgId::from_byte_array([0x77; HgId::len()]);
pub const EIGHTS: HgId = HgId::from_byte_array([0x88; HgId::len()]);
pub const NINES: HgId = HgId::from_byte_array([0x99; HgId::len()]);
pub const AS: HgId = HgId::from_byte_array([0xAA; HgId::len()]);
pub const BS: HgId = HgId::from_byte_array([0xAB; HgId::len()]);
pub const CS: HgId = HgId::from_byte_array([0xCC; HgId::len()]);
pub const DS: HgId = HgId::from_byte_array([0xDD; HgId::len()]);
pub const ES: HgId = HgId::from_byte_array([0xEE; HgId::len()]);
pub const FS: HgId = HgId::from_byte_array([0xFF; HgId::len()]);
}
#[cfg(test)]
mod tests {
use quickcheck::quickcheck;
use serde::Deserialize;
use serde::Serialize;
use super::*;
#[test]
fn test_incorrect_length() {
HgId::from_slice(&[0u8; 25]).expect_err("bad slice length");
}
#[test]
fn test_serde_with_using_cbor() {
// Note: this test is for CBOR. Other serializers like mincode
// or Thrift would have different backwards compatibility!
use serde_cbor::de::from_slice as decode;
use serde_cbor::ser::to_vec as encode;
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct Orig(#[serde(with = "crate::serde_with::hgid::tuple")] HgId);
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct Bytes(#[serde(with = "crate::serde_with::hgid::bytes")] HgId);
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct Hex(#[serde(with = "crate::serde_with::hgid::hex")] HgId);
let id: HgId = mocks::CS;
let orig = Orig(id);
let bytes = Bytes(id);
let hex = Hex(id);
let cbor_orig = encode(&orig).unwrap();
let cbor_bytes = encode(&bytes).unwrap();
let cbor_hex = encode(&hex).unwrap();
assert_eq!(cbor_orig.len(), 41);
assert_eq!(cbor_bytes.len(), 21);
assert_eq!(cbor_hex.len(), 42);
// Orig cannot decode bytes or hex.
assert_eq!(decode::<Orig>(&cbor_orig).unwrap().0, id);
decode::<Orig>(&cbor_bytes).unwrap_err();
decode::<Orig>(&cbor_hex).unwrap_err();
// Bytes can decode all 3 formats.
assert_eq!(decode::<Bytes>(&cbor_orig).unwrap().0, id);
assert_eq!(decode::<Bytes>(&cbor_bytes).unwrap().0, id);
assert_eq!(decode::<Bytes>(&cbor_hex).unwrap().0, id);
// Hex can decode all 3 formats.
assert_eq!(decode::<Hex>(&cbor_orig).unwrap().0, id);
assert_eq!(decode::<Hex>(&cbor_bytes).unwrap().0, id);
assert_eq!(decode::<Hex>(&cbor_hex).unwrap().0, id);
}
quickcheck! {
fn test_from_slice(hgid: HgId) -> bool {
hgid == HgId::from_slice(hgid.as_ref()).expect("from_slice")
}
}
}
| {
nodeset.insert(hgid.clone());
nodes.push(hgid);
} | conditional_block |
hgid.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#[cfg(any(test, feature = "for-tests"))]
use std::collections::HashSet;
use std::io::Read;
use std::io::Write;
use std::io::{self};
#[cfg(any(test, feature = "for-tests"))]
use rand::RngCore;
use sha1::Digest;
use sha1::Sha1;
use crate::hash::AbstractHashType;
use crate::hash::HashTypeInfo;
use crate::parents::Parents;
/// A 20-byte identifier, often a hash. Nodes are used to uniquely identify
/// commits, file versions, and many other things.
///
///
/// # Serde Serialization
///
/// The `serde_with` module allows customization on `HgId` serialization:
/// - `#[serde(with = "types::serde_with::hgid::bytes")]` (current default)
/// - `#[serde(with = "types::serde_with::hgid::hex")]`
/// - `#[serde(with = "types::serde_with::hgid::tuple")]`
///
/// Using them can change the size or the type of serialization result:
///
/// | lib \ serde_with | hgid::tuple | hgid::bytes | hgid::hex |
/// |------------------|---------------------|--------------|-----------|
/// | mincode | 20 bytes | 21 bytes | 41 bytes |
/// | cbor | 21 to 41 bytes [1] | 21 bytes | 42 bytes |
/// | json | 41 to 81+ bytes [1] | invalid [2] | 42 bytes |
/// | python | Tuple[int] | bytes | str |
///
/// In general,
/// - `hgid::tuple` only works best for `mincode`.
/// - `hgid::bytes` works best for cbor, python.
/// - `hgid::hex` is useful for `json`, or other text-only formats.
///
/// Compatibility note:
/// - `hgid::tuple` cannot decode `hgid::bytes` or `hgid::hex` data.
/// - `hgid::hex` can decode `hgid::bytes` data, or vice-versa. They share a
/// same `deserialize` implementation.
/// - `hgid::hex` or `hgid::bytes` might be able to decode `hgid::tuple` data,
/// depending on how tuples are serialized. For example, mincode
/// does not add framing for tuples, so `hgid::bytes` cannot decode
/// `hgid::tuple` data; cbor adds framing for tuples, so `hgid::bytes`
/// can decode `hgid::tuple` data.
///
/// [1]: Depends on actual data of `HgId`.
/// [2]: JSON only supports utf-8 data.
pub type HgId = AbstractHashType<HgIdTypeInfo, 20>;
pub struct HgIdTypeInfo;
impl HashTypeInfo for HgIdTypeInfo {
const HASH_TYPE_NAME: &'static str = "HgId";
}
/// The nullid (0x00) is used throughout Mercurial to represent "None".
/// (For example, a commit will have a nullid p2, if it has no second parent).
pub const NULL_ID: HgId = HgId::from_byte_array([0; HgId::len()]);
/// The hard-coded 'working copy parent' Mercurial id.
pub const WDIR_ID: HgId = HgId::from_byte_array([0xff; HgId::len()]);
impl HgId {
pub fn null_id() -> &'static Self {
&NULL_ID
}
pub fn is_null(&self) -> bool {
self == &NULL_ID
}
pub const fn wdir_id() -> &'static Self {
&WDIR_ID
}
pub fn is_wdir(&self) -> bool {
self == &WDIR_ID
}
pub fn from_content(data: &[u8], parents: Parents) -> Self {
// Parents must be hashed in sorted order.
let (p1, p2) = match parents.into_nodes() {
(p1, p2) if p1 > p2 => (p2, p1),
(p1, p2) => (p1, p2),
};
let mut hasher = Sha1::new();
hasher.input(p1.as_ref());
hasher.input(p2.as_ref());
hasher.input(data);
let hash: [u8; 20] = hasher.result().into();
HgId::from_byte_array(hash)
}
#[cfg(any(test, feature = "for-tests"))]
pub fn random(rng: &mut dyn RngCore) -> Self {
let mut bytes = [0; HgId::len()];
rng.fill_bytes(&mut bytes);
loop {
let hgid = HgId::from(&bytes);
if!hgid.is_null() {
return hgid;
}
}
}
#[cfg(any(test, feature = "for-tests"))]
pub fn random_distinct(rng: &mut dyn RngCore, count: usize) -> Vec<Self> {
let mut nodes = Vec::new();
let mut nodeset = HashSet::new();
while nodes.len() < count {
let hgid = HgId::random(rng);
if!nodeset.contains(&hgid) {
nodeset.insert(hgid.clone());
nodes.push(hgid);
}
}
nodes
}
}
impl<'a> From<&'a [u8; HgId::len()]> for HgId {
fn from(bytes: &[u8; HgId::len()]) -> HgId {
HgId::from_byte_array(bytes.clone())
}
}
pub trait WriteHgIdExt {
/// Write a ``HgId`` directly to a stream.
///
/// # Examples
///
/// ```
/// use types::hgid::{HgId, WriteHgIdExt};
/// let mut v = vec![];
///
/// let n = HgId::null_id();
/// v.write_hgid(&n).expect("writing a hgid to a vec should work");
///
/// assert_eq!(v, vec![0; HgId::len()]);
/// ```
fn write_hgid(&mut self, value: &HgId) -> io::Result<()>;
}
impl<W: Write +?Sized> WriteHgIdExt for W {
fn write_hgid(&mut self, value: &HgId) -> io::Result<()> {
self.write_all(value.as_ref())
}
}
pub trait ReadHgIdExt {
/// Read a ``HgId`` directly from a stream.
///
/// # Examples
///
/// ```
/// use std::io::Cursor;
/// use types::hgid::{HgId, ReadHgIdExt};
/// let mut v = vec![0; HgId::len()];
/// let mut c = Cursor::new(v);
///
/// let n = c.read_hgid().expect("reading a hgid from a vec should work");
///
/// assert_eq!(&n, HgId::null_id());
/// ```
fn read_hgid(&mut self) -> io::Result<HgId>;
}
impl<R: Read +?Sized> ReadHgIdExt for R {
fn read_hgid(&mut self) -> io::Result<HgId> {
let mut bytes = [0; HgId::len()];
self.read_exact(&mut bytes)?;
Ok(HgId::from_byte_array(bytes))
}
}
#[cfg(any(test, feature = "for-tests"))]
pub mod mocks {
use super::HgId;
pub const ONES: HgId = HgId::from_byte_array([0x11; HgId::len()]);
pub const TWOS: HgId = HgId::from_byte_array([0x22; HgId::len()]);
pub const THREES: HgId = HgId::from_byte_array([0x33; HgId::len()]);
pub const FOURS: HgId = HgId::from_byte_array([0x44; HgId::len()]);
pub const FIVES: HgId = HgId::from_byte_array([0x55; HgId::len()]);
pub const SIXES: HgId = HgId::from_byte_array([0x66; HgId::len()]);
pub const SEVENS: HgId = HgId::from_byte_array([0x77; HgId::len()]);
pub const EIGHTS: HgId = HgId::from_byte_array([0x88; HgId::len()]);
pub const NINES: HgId = HgId::from_byte_array([0x99; HgId::len()]);
pub const AS: HgId = HgId::from_byte_array([0xAA; HgId::len()]);
pub const BS: HgId = HgId::from_byte_array([0xAB; HgId::len()]);
pub const CS: HgId = HgId::from_byte_array([0xCC; HgId::len()]);
pub const DS: HgId = HgId::from_byte_array([0xDD; HgId::len()]);
pub const ES: HgId = HgId::from_byte_array([0xEE; HgId::len()]);
pub const FS: HgId = HgId::from_byte_array([0xFF; HgId::len()]);
}
#[cfg(test)] |
use super::*;
#[test]
fn test_incorrect_length() {
HgId::from_slice(&[0u8; 25]).expect_err("bad slice length");
}
#[test]
fn test_serde_with_using_cbor() {
// Note: this test is for CBOR. Other serializers like mincode
// or Thrift would have different backwards compatibility!
use serde_cbor::de::from_slice as decode;
use serde_cbor::ser::to_vec as encode;
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct Orig(#[serde(with = "crate::serde_with::hgid::tuple")] HgId);
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct Bytes(#[serde(with = "crate::serde_with::hgid::bytes")] HgId);
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct Hex(#[serde(with = "crate::serde_with::hgid::hex")] HgId);
let id: HgId = mocks::CS;
let orig = Orig(id);
let bytes = Bytes(id);
let hex = Hex(id);
let cbor_orig = encode(&orig).unwrap();
let cbor_bytes = encode(&bytes).unwrap();
let cbor_hex = encode(&hex).unwrap();
assert_eq!(cbor_orig.len(), 41);
assert_eq!(cbor_bytes.len(), 21);
assert_eq!(cbor_hex.len(), 42);
// Orig cannot decode bytes or hex.
assert_eq!(decode::<Orig>(&cbor_orig).unwrap().0, id);
decode::<Orig>(&cbor_bytes).unwrap_err();
decode::<Orig>(&cbor_hex).unwrap_err();
// Bytes can decode all 3 formats.
assert_eq!(decode::<Bytes>(&cbor_orig).unwrap().0, id);
assert_eq!(decode::<Bytes>(&cbor_bytes).unwrap().0, id);
assert_eq!(decode::<Bytes>(&cbor_hex).unwrap().0, id);
// Hex can decode all 3 formats.
assert_eq!(decode::<Hex>(&cbor_orig).unwrap().0, id);
assert_eq!(decode::<Hex>(&cbor_bytes).unwrap().0, id);
assert_eq!(decode::<Hex>(&cbor_hex).unwrap().0, id);
}
quickcheck! {
fn test_from_slice(hgid: HgId) -> bool {
hgid == HgId::from_slice(hgid.as_ref()).expect("from_slice")
}
}
} | mod tests {
use quickcheck::quickcheck;
use serde::Deserialize;
use serde::Serialize; | random_line_split |
matcher.rs | #![feature(test)]
extern crate rff;
extern crate test;
use test::Bencher;
use rff::matcher::matches;
#[bench]
fn bench_matches(b: &mut Bencher) {
b.iter(|| matches("amor", "app/models/order.rb"))
}
#[bench]
fn bench_matches_utf8(b: &mut Bencher) {
b.iter(|| matches("ß", "WEIẞ"))
}
#[bench]
fn bench_matches_mixed(b: &mut Bencher) {
b.iter(|| matches("abc", "abØ"))
}
#[bench]
fn benc | &mut Bencher) {
b.iter(|| matches("app/models", "app/models/order.rb"))
}
#[bench]
fn bench_matches_mixed_case(b: &mut Bencher) {
b.iter(|| matches("AMOr", "App/Models/Order.rb"))
}
#[bench]
fn bench_matches_multiple(b: &mut Bencher) {
b.iter(|| {
matches("amor", "app/models/order.rb");
matches("amor", "spec/models/order_spec.rb");
matches("amor", "other_garbage.rb");
matches("amor", "Gemfile");
matches("amor", "node_modules/test/a/thing.js");
matches("amor", "vendor/bundle/ruby/gem.rb")
})
}
#[bench]
fn bench_matches_eq(b: &mut Bencher) {
b.iter(|| {
matches("Gemfile", "Gemfile");
matches("gemfile", "Gemfile")
})
}
| h_matches_more_specific(b: | identifier_name |
matcher.rs | #![feature(test)]
extern crate rff;
extern crate test;
use test::Bencher;
use rff::matcher::matches;
#[bench]
fn bench_matches(b: &mut Bencher) {
b.iter(|| matches("amor", "app/models/order.rb"))
} | fn bench_matches_utf8(b: &mut Bencher) {
b.iter(|| matches("ß", "WEIẞ"))
}
#[bench]
fn bench_matches_mixed(b: &mut Bencher) {
b.iter(|| matches("abc", "abØ"))
}
#[bench]
fn bench_matches_more_specific(b: &mut Bencher) {
b.iter(|| matches("app/models", "app/models/order.rb"))
}
#[bench]
fn bench_matches_mixed_case(b: &mut Bencher) {
b.iter(|| matches("AMOr", "App/Models/Order.rb"))
}
#[bench]
fn bench_matches_multiple(b: &mut Bencher) {
b.iter(|| {
matches("amor", "app/models/order.rb");
matches("amor", "spec/models/order_spec.rb");
matches("amor", "other_garbage.rb");
matches("amor", "Gemfile");
matches("amor", "node_modules/test/a/thing.js");
matches("amor", "vendor/bundle/ruby/gem.rb")
})
}
#[bench]
fn bench_matches_eq(b: &mut Bencher) {
b.iter(|| {
matches("Gemfile", "Gemfile");
matches("gemfile", "Gemfile")
})
} |
#[bench] | random_line_split |
matcher.rs | #![feature(test)]
extern crate rff;
extern crate test;
use test::Bencher;
use rff::matcher::matches;
#[bench]
fn bench_matches(b: &mut Bencher) {
b.iter(|| matches("amor", "app/models/order.rb"))
}
#[bench]
fn bench_matches_utf8(b: &mut Bencher) {
b.iter(|| matches("ß", "WEIẞ"))
}
#[bench]
fn bench_matches_mixed(b: &mut Bencher) {
b.iter(|| matches("abc", "abØ"))
}
#[bench]
fn bench_matches_more_specific(b: &mut Bencher) {
b.iter(|| matches("app/models", "app/models/order.rb"))
}
#[bench]
fn bench_matches_mixed_case(b: &mut Bencher) {
b.iter(|| matches("AMOr", "App/Models/Order.rb"))
}
#[bench]
fn bench_matches_multiple(b: &mut Bencher) {
| bench]
fn bench_matches_eq(b: &mut Bencher) {
b.iter(|| {
matches("Gemfile", "Gemfile");
matches("gemfile", "Gemfile")
})
}
| b.iter(|| {
matches("amor", "app/models/order.rb");
matches("amor", "spec/models/order_spec.rb");
matches("amor", "other_garbage.rb");
matches("amor", "Gemfile");
matches("amor", "node_modules/test/a/thing.js");
matches("amor", "vendor/bundle/ruby/gem.rb")
})
}
#[ | identifier_body |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations ───────────────┐
// Std Library Option ──────────────────┘
// An integer division that doesn't `panic!`
fn checked_division(dividend: i32, divisor: i32) -> Option<i32> {
if di | // Failure is represented as the `None` variant
None
} else {
// Result is wrapped in a `Some` variant
Some(dividend / divisor)
}
}
// This function handles a division that may not succeed
fn try_division(dividend: i32, divisor: i32) {
// `Option` values can be pattern matched, just like other enums
match checked_division(dividend, divisor) {
None => println!("{} / {} failed!", dividend, divisor),
Some(quotient) => {
println!("{} / {} = {}", dividend, divisor, quotient)
},
}
}
fn main() {
try_division(4, 2);
try_division(1, 0);
// Binding `None` to a variable needs to be type annotated
let none: Option<i32> = None;
let _equivalent_none = None::<i32>;
let optional_float = Some(0f32);
// Unwrapping a `Some` variant will extract the value wrapped.
println!("{:?} unwraps to {:?}", optional_float, optional_float.unwrap());
// Unwrapping a `None` variant will `panic!`
println!("{:?} unwraps to {:?}", none, none.unwrap());
}
| visor == 0 {
| identifier_name |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations ───────────────┐
// Std Library Option ──────────────────┘
// An integer division that doesn't `panic!`
fn checked_division(dividend: i32, divisor: i32) -> Option<i32> {
if divisor == 0 {
// Failure is represented as the `None` variant
None
} else {
// Result is wrapped in a `Some` variant
Some(dividend / divisor)
}
}
// This function handles a division that may not succeed
fn try_division(dividend: i32, divisor: i32) {
// `Option` values can be pattern matched, just like other enums
match checked_division(dividend, divisor) {
None => println!("{} / {} failed!", dividend, divisor),
Some(quotient) => {
println!("{} / {} = {}", dividend, divisor, quotient)
| // Binding `None` to a variable needs to be type annotated
let none: Option<i32> = None;
let _equivalent_none = None::<i32>;
let optional_float = Some(0f32);
// Unwrapping a `Some` variant will extract the value wrapped.
println!("{:?} unwraps to {:?}", optional_float, optional_float.unwrap());
// Unwrapping a `None` variant will `panic!`
println!("{:?} unwraps to {:?}", none, none.unwrap());
}
| },
}
}
fn main() {
try_division(4, 2);
try_division(1, 0);
| conditional_block |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations ───────────────┐
// Std Library Option ──────────────────┘
// An integer division that doesn't `panic!`
fn checked_division(dividend: i32, divisor: i32) -> Option<i32> {
if divisor == 0 {
// Failure is represented as the `None` variant
None
} else { | }
}
// This function handles a division that may not succeed
fn try_division(dividend: i32, divisor: i32) {
// `Option` values can be pattern matched, just like other enums
match checked_division(dividend, divisor) {
None => println!("{} / {} failed!", dividend, divisor),
Some(quotient) => {
println!("{} / {} = {}", dividend, divisor, quotient)
},
}
}
fn main() {
try_division(4, 2);
try_division(1, 0);
// Binding `None` to a variable needs to be type annotated
let none: Option<i32> = None;
let _equivalent_none = None::<i32>;
let optional_float = Some(0f32);
// Unwrapping a `Some` variant will extract the value wrapped.
println!("{:?} unwraps to {:?}", optional_float, optional_float.unwrap());
// Unwrapping a `None` variant will `panic!`
println!("{:?} unwraps to {:?}", none, none.unwrap());
} | // Result is wrapped in a `Some` variant
Some(dividend / divisor) | random_line_split |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations ───────────────┐
// Std Library Option ──────────────────┘
// An integer division that doesn't `panic!`
fn checked_division(dividend: i32, divisor: i32) -> Option<i32> {
if divisor == 0 {
// Failure is represented as the `None` variant
None
} else {
// Result is wrapped in a `Some` variant
Some(dividend / divisor)
}
}
// This function handles a division that may not succeed
fn try_division(dividend: i32, divisor: i32) {
// `Option` values can be pattern matched, just like other enums
| nding `None` to a variable needs to be type annotated
let none: Option<i32> = None;
let _equivalent_none = None::<i32>;
let optional_float = Some(0f32);
// Unwrapping a `Some` variant will extract the value wrapped.
println!("{:?} unwraps to {:?}", optional_float, optional_float.unwrap());
// Unwrapping a `None` variant will `panic!`
println!("{:?} unwraps to {:?}", none, none.unwrap());
}
| match checked_division(dividend, divisor) {
None => println!("{} / {} failed!", dividend, divisor),
Some(quotient) => {
println!("{} / {} = {}", dividend, divisor, quotient)
},
}
}
fn main() {
try_division(4, 2);
try_division(1, 0);
// Bi | identifier_body |
regions-early-bound-used-in-bound-method.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.
// Tests that you can use a fn lifetime parameter as part of
// the value for a type parameter in a bound.
trait GetRef<'a> {
fn get(&self) -> &'a int;
}
struct Box<'a> {
t: &'a int
}
impl<'a> Copy for Box<'a> {}
impl<'a> GetRef<'a> for Box<'a> {
fn get(&self) -> &'a int {
self.t
}
}
impl<'a> Box<'a> {
fn add<'b,G:GetRef<'b>>(&self, g2: G) -> int |
}
pub fn main() {
let b1 = Box { t: &3 };
assert_eq!(b1.add(b1), 6);
}
| {
*self.t + *g2.get()
} | identifier_body |
regions-early-bound-used-in-bound-method.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests that you can use a fn lifetime parameter as part of
// the value for a type parameter in a bound.
trait GetRef<'a> {
fn get(&self) -> &'a int;
}
struct Box<'a> {
t: &'a int
}
impl<'a> Copy for Box<'a> {}
impl<'a> GetRef<'a> for Box<'a> {
fn get(&self) -> &'a int {
self.t
}
}
impl<'a> Box<'a> {
fn add<'b,G:GetRef<'b>>(&self, g2: G) -> int {
*self.t + *g2.get()
}
}
pub fn main() {
let b1 = Box { t: &3 };
assert_eq!(b1.add(b1), 6);
} | // 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 | random_line_split |
regions-early-bound-used-in-bound-method.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.
// Tests that you can use a fn lifetime parameter as part of
// the value for a type parameter in a bound.
trait GetRef<'a> {
fn get(&self) -> &'a int;
}
struct | <'a> {
t: &'a int
}
impl<'a> Copy for Box<'a> {}
impl<'a> GetRef<'a> for Box<'a> {
fn get(&self) -> &'a int {
self.t
}
}
impl<'a> Box<'a> {
fn add<'b,G:GetRef<'b>>(&self, g2: G) -> int {
*self.t + *g2.get()
}
}
pub fn main() {
let b1 = Box { t: &3 };
assert_eq!(b1.add(b1), 6);
}
| Box | identifier_name |
lib.rs | //! # r2d2-mysql
//! MySQL support for the r2d2 connection pool (Rust). see [`r2d2`](http://github.com/sfackler/r2d2.git) .
//!
//! #### Install
//! Just include another `[dependencies.*]` section into your Cargo.toml:
//!
//! ```toml
//! [dependencies.r2d2_mysql]
//! git = "https://github.com/outersky/r2d2-mysql"
//! version="*"
//! ```
//! #### Sample
//!
//! ```
//! extern crate mysql;
//! extern crate r2d2_mysql;
//! extern crate r2d2;
//!
//! use std::env;
//! use std::sync::Arc;
//! use std::thread;
//! use mysql::{Opts,OptsBuilder};
//! use mysql::prelude::Queryable;
//! use r2d2_mysql::MysqlConnectionManager;
//!
//! fn main() {
//! let url = env::var("DATABASE_URL").unwrap();
//! let opts = Opts::from_url(&url).unwrap();
//! let builder = OptsBuilder::from_opts(opts);
//! let manager = MysqlConnectionManager::new(builder);
//! let pool = Arc::new(r2d2::Pool::builder().max_size(4).build(manager).unwrap());
//!
//! let mut tasks = vec![];
//!
//! for _ in 0..3 {
//! let pool = pool.clone();
//! let th = thread::spawn(move || {
//! let mut conn = pool.get()
//! .map_err(|err| {
//! println!(
//! "get connection from pool error in line:{}! error: {:?}",
//! line!(),
//! err
//! )
//! })
//! .unwrap();
//! let _ = conn.query("SELECT version()").map(|_: Vec<String>| ()).map_err(|err| {
//! println!("execute query error in line:{}! error: {:?}", line!(), err)
//! });
//! });
//! tasks.push(th);
//! }
//!
//! for th in tasks {
//! let _ = th.join();
//! }
//! }
//! ```
//!
#![doc(html_root_url = "http://outersky.github.io/r2d2-mysql/doc/v0.2.0/r2d2_mysql/")]
#![crate_name = "r2d2_mysql"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
pub extern crate mysql;
pub extern crate r2d2;
pub mod pool;
pub use pool::MysqlConnectionManager;
#[cfg(test)]
mod test {
use mysql::{Opts, OptsBuilder};
use mysql::prelude::Queryable;
use r2d2;
use std::env;
use std::sync::Arc;
use std::thread;
use super::MysqlConnectionManager;
#[test]
fn | () {
let url = env::var("DATABASE_URL").unwrap();
let opts = Opts::from_url(&url).unwrap();
let builder = OptsBuilder::from_opts(opts);
let manager = MysqlConnectionManager::new(builder);
let pool = Arc::new(r2d2::Pool::builder().max_size(4).build(manager).unwrap());
let mut tasks = vec![];
for _ in 0..3 {
let pool = pool.clone();
let th = thread::spawn(move || {
let mut conn = pool.get()
.map_err(|err| {
println!(
"get connection from pool error in line:{}! error: {:?}",
line!(),
err
)
})
.unwrap();
let _ = conn.query("SELECT version()").map(|_: Vec<String>| ()).map_err(|err| {
println!("execute query error in line:{}! error: {:?}", line!(), err)
});
});
tasks.push(th);
}
for th in tasks {
let _ = th.join();
}
}
}
| query_pool | identifier_name |
lib.rs | //! # r2d2-mysql
//! MySQL support for the r2d2 connection pool (Rust). see [`r2d2`](http://github.com/sfackler/r2d2.git) .
//!
//! #### Install
//! Just include another `[dependencies.*]` section into your Cargo.toml:
//!
//! ```toml
//! [dependencies.r2d2_mysql]
//! git = "https://github.com/outersky/r2d2-mysql"
//! version="*"
//! ```
//! #### Sample
//!
//! ```
//! extern crate mysql;
//! extern crate r2d2_mysql;
//! extern crate r2d2;
//!
//! use std::env;
//! use std::sync::Arc;
//! use std::thread;
//! use mysql::{Opts,OptsBuilder};
//! use mysql::prelude::Queryable;
//! use r2d2_mysql::MysqlConnectionManager;
//!
//! fn main() {
//! let url = env::var("DATABASE_URL").unwrap();
//! let opts = Opts::from_url(&url).unwrap();
//! let builder = OptsBuilder::from_opts(opts);
//! let manager = MysqlConnectionManager::new(builder);
//! let pool = Arc::new(r2d2::Pool::builder().max_size(4).build(manager).unwrap());
//!
//! let mut tasks = vec![];
//!
//! for _ in 0..3 {
//! let pool = pool.clone();
//! let th = thread::spawn(move || {
//! let mut conn = pool.get()
//! .map_err(|err| {
//! println!(
//! "get connection from pool error in line:{}! error: {:?}",
//! line!(),
//! err
//! )
//! })
//! .unwrap();
//! let _ = conn.query("SELECT version()").map(|_: Vec<String>| ()).map_err(|err| {
//! println!("execute query error in line:{}! error: {:?}", line!(), err)
//! });
//! });
//! tasks.push(th);
//! }
//!
//! for th in tasks {
//! let _ = th.join();
//! }
//! }
//! ```
//!
#![doc(html_root_url = "http://outersky.github.io/r2d2-mysql/doc/v0.2.0/r2d2_mysql/")]
#![crate_name = "r2d2_mysql"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
pub extern crate mysql;
pub extern crate r2d2;
pub mod pool;
pub use pool::MysqlConnectionManager;
#[cfg(test)]
mod test {
use mysql::{Opts, OptsBuilder};
use mysql::prelude::Queryable;
use r2d2;
use std::env;
use std::sync::Arc;
use std::thread;
use super::MysqlConnectionManager;
#[test]
fn query_pool() | .unwrap();
let _ = conn.query("SELECT version()").map(|_: Vec<String>| ()).map_err(|err| {
println!("execute query error in line:{}! error: {:?}", line!(), err)
});
});
tasks.push(th);
}
for th in tasks {
let _ = th.join();
}
}
}
| {
let url = env::var("DATABASE_URL").unwrap();
let opts = Opts::from_url(&url).unwrap();
let builder = OptsBuilder::from_opts(opts);
let manager = MysqlConnectionManager::new(builder);
let pool = Arc::new(r2d2::Pool::builder().max_size(4).build(manager).unwrap());
let mut tasks = vec![];
for _ in 0..3 {
let pool = pool.clone();
let th = thread::spawn(move || {
let mut conn = pool.get()
.map_err(|err| {
println!(
"get connection from pool error in line:{} ! error: {:?}",
line!(),
err
)
}) | identifier_body |
lib.rs | //! # r2d2-mysql
//! MySQL support for the r2d2 connection pool (Rust). see [`r2d2`](http://github.com/sfackler/r2d2.git) .
//!
//! #### Install
//! Just include another `[dependencies.*]` section into your Cargo.toml:
//!
//! ```toml
//! [dependencies.r2d2_mysql]
//! git = "https://github.com/outersky/r2d2-mysql"
//! version="*"
//! ```
//! #### Sample
//!
//! ```
//! extern crate mysql;
//! extern crate r2d2_mysql;
//! extern crate r2d2;
//!
//! use std::env;
//! use std::sync::Arc;
//! use std::thread;
//! use mysql::{Opts,OptsBuilder};
//! use mysql::prelude::Queryable;
//! use r2d2_mysql::MysqlConnectionManager;
//!
//! fn main() {
//! let url = env::var("DATABASE_URL").unwrap();
//! let opts = Opts::from_url(&url).unwrap();
//! let builder = OptsBuilder::from_opts(opts);
//! let manager = MysqlConnectionManager::new(builder);
//! let pool = Arc::new(r2d2::Pool::builder().max_size(4).build(manager).unwrap());
//!
//! let mut tasks = vec![];
//!
//! for _ in 0..3 {
//! let pool = pool.clone();
//! let th = thread::spawn(move || {
//! let mut conn = pool.get()
//! .map_err(|err| {
//! println!(
//! "get connection from pool error in line:{}! error: {:?}",
//! line!(),
//! err
//! )
//! })
//! .unwrap();
//! let _ = conn.query("SELECT version()").map(|_: Vec<String>| ()).map_err(|err| {
//! println!("execute query error in line:{}! error: {:?}", line!(), err)
//! });
//! });
//! tasks.push(th);
//! }
//!
//! for th in tasks {
//! let _ = th.join();
//! }
//! } | //! ```
//!
#![doc(html_root_url = "http://outersky.github.io/r2d2-mysql/doc/v0.2.0/r2d2_mysql/")]
#![crate_name = "r2d2_mysql"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
pub extern crate mysql;
pub extern crate r2d2;
pub mod pool;
pub use pool::MysqlConnectionManager;
#[cfg(test)]
mod test {
use mysql::{Opts, OptsBuilder};
use mysql::prelude::Queryable;
use r2d2;
use std::env;
use std::sync::Arc;
use std::thread;
use super::MysqlConnectionManager;
#[test]
fn query_pool() {
let url = env::var("DATABASE_URL").unwrap();
let opts = Opts::from_url(&url).unwrap();
let builder = OptsBuilder::from_opts(opts);
let manager = MysqlConnectionManager::new(builder);
let pool = Arc::new(r2d2::Pool::builder().max_size(4).build(manager).unwrap());
let mut tasks = vec![];
for _ in 0..3 {
let pool = pool.clone();
let th = thread::spawn(move || {
let mut conn = pool.get()
.map_err(|err| {
println!(
"get connection from pool error in line:{}! error: {:?}",
line!(),
err
)
})
.unwrap();
let _ = conn.query("SELECT version()").map(|_: Vec<String>| ()).map_err(|err| {
println!("execute query error in line:{}! error: {:?}", line!(), err)
});
});
tasks.push(th);
}
for th in tasks {
let _ = th.join();
}
}
} | random_line_split |
|
build.rs | #[cfg(feature = "with-syntex")]
mod inner {
extern crate syntex;
extern crate syntex_syntax as syntax;
use std::env;
use std::path::Path;
use self::syntax::codemap::Span;
use self::syntax::ext::base::{self, ExtCtxt};
use self::syntax::tokenstream::TokenTree;
pub fn main() {
let out_dir = env::var_os("OUT_DIR").unwrap();
let mut registry = syntex::Registry::new(); | ($macro_name: ident, $name: ident) => {
fn $name<'cx>(
cx: &'cx mut ExtCtxt,
sp: Span,
tts: &[TokenTree],
) -> Box<base::MacResult + 'cx> {
syntax::ext::quote::$name(cx, sp, tts)
}
registry.add_macro(stringify!($macro_name), $name);
}
}
register_quote_macro!(quote_ty, expand_quote_ty);
register_quote_macro!(quote_item, expand_quote_item);
register_quote_macro!(quote_tokens, expand_quote_tokens);
register_quote_macro!(quote_expr, expand_quote_expr);
let src = Path::new("src/lib.in.rs");
let dst = Path::new(&out_dir).join("lib.rs");
registry.expand("", &src, &dst).unwrap();
}
}
#[cfg(not(feature = "with-syntex"))]
mod inner {
pub fn main() {}
}
fn main() {
inner::main();
} |
macro_rules! register_quote_macro { | random_line_split |
build.rs | #[cfg(feature = "with-syntex")]
mod inner {
extern crate syntex;
extern crate syntex_syntax as syntax;
use std::env;
use std::path::Path;
use self::syntax::codemap::Span;
use self::syntax::ext::base::{self, ExtCtxt};
use self::syntax::tokenstream::TokenTree;
pub fn main() {
let out_dir = env::var_os("OUT_DIR").unwrap();
let mut registry = syntex::Registry::new();
macro_rules! register_quote_macro {
($macro_name: ident, $name: ident) => {
fn $name<'cx>(
cx: &'cx mut ExtCtxt,
sp: Span,
tts: &[TokenTree],
) -> Box<base::MacResult + 'cx> {
syntax::ext::quote::$name(cx, sp, tts)
}
registry.add_macro(stringify!($macro_name), $name);
}
}
register_quote_macro!(quote_ty, expand_quote_ty);
register_quote_macro!(quote_item, expand_quote_item);
register_quote_macro!(quote_tokens, expand_quote_tokens);
register_quote_macro!(quote_expr, expand_quote_expr);
let src = Path::new("src/lib.in.rs");
let dst = Path::new(&out_dir).join("lib.rs");
registry.expand("", &src, &dst).unwrap();
}
}
#[cfg(not(feature = "with-syntex"))]
mod inner {
pub fn main() |
}
fn main() {
inner::main();
}
| {} | identifier_body |
build.rs | #[cfg(feature = "with-syntex")]
mod inner {
extern crate syntex;
extern crate syntex_syntax as syntax;
use std::env;
use std::path::Path;
use self::syntax::codemap::Span;
use self::syntax::ext::base::{self, ExtCtxt};
use self::syntax::tokenstream::TokenTree;
pub fn | () {
let out_dir = env::var_os("OUT_DIR").unwrap();
let mut registry = syntex::Registry::new();
macro_rules! register_quote_macro {
($macro_name: ident, $name: ident) => {
fn $name<'cx>(
cx: &'cx mut ExtCtxt,
sp: Span,
tts: &[TokenTree],
) -> Box<base::MacResult + 'cx> {
syntax::ext::quote::$name(cx, sp, tts)
}
registry.add_macro(stringify!($macro_name), $name);
}
}
register_quote_macro!(quote_ty, expand_quote_ty);
register_quote_macro!(quote_item, expand_quote_item);
register_quote_macro!(quote_tokens, expand_quote_tokens);
register_quote_macro!(quote_expr, expand_quote_expr);
let src = Path::new("src/lib.in.rs");
let dst = Path::new(&out_dir).join("lib.rs");
registry.expand("", &src, &dst).unwrap();
}
}
#[cfg(not(feature = "with-syntex"))]
mod inner {
pub fn main() {}
}
fn main() {
inner::main();
}
| main | identifier_name |
config.rs | //! Utilities for managing the configuration of the website.
//!
//! The configuration should contain values that I expect to change. This way, I can edit them all
//! in a single human-readable file instead of having to track down the values in the code.
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use log::*;
use serde::Deserialize;
use serde_yaml;
use url::Url;
use url_serde;
use crate::errors::*;
/// Configuration values for the website.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Config {
/// A link to a PDF copy of my Resume.
#[serde(with = "url_serde")]
pub resume_link: Url,
}
fn parse_config<R>(reader: R) -> Result<Config>
where
R: Read,
{
let config = serde_yaml::from_reader(reader)?;
Ok(config)
}
/// Load the website configuration from a path.
pub fn load<P>(config_path: P) -> Result<Config>
where
P: AsRef<Path>,
{
let path = config_path.as_ref().to_str().unwrap();
info!("loading configuration from {}", path);
let config_file = File::open(&config_path).chain_err(|| "error opening config file")?;
parse_config(config_file)
}
#[cfg(test)]
mod tests {
use super::*;
use url::Url;
#[test]
fn load_config() |
}
| {
let test_config = String::from(
r#"
---
resume_link: http://google.com
"#,
);
let expected_config = Config {
resume_link: Url::parse("http://google.com").unwrap(),
};
assert_eq!(
expected_config,
super::parse_config(test_config.as_bytes()).unwrap()
);
} | identifier_body |
config.rs | //! Utilities for managing the configuration of the website.
//!
//! The configuration should contain values that I expect to change. This way, I can edit them all
//! in a single human-readable file instead of having to track down the values in the code.
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use log::*;
use serde::Deserialize;
use serde_yaml;
use url::Url;
use url_serde;
use crate::errors::*;
/// Configuration values for the website.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Config {
/// A link to a PDF copy of my Resume.
#[serde(with = "url_serde")]
pub resume_link: Url,
}
fn parse_config<R>(reader: R) -> Result<Config>
where
R: Read,
{
let config = serde_yaml::from_reader(reader)?;
Ok(config)
}
/// Load the website configuration from a path.
pub fn load<P>(config_path: P) -> Result<Config>
where
P: AsRef<Path>,
{
let path = config_path.as_ref().to_str().unwrap();
info!("loading configuration from {}", path);
let config_file = File::open(&config_path).chain_err(|| "error opening config file")?;
parse_config(config_file)
}
#[cfg(test)]
mod tests {
use super::*;
use url::Url;
#[test]
fn | () {
let test_config = String::from(
r#"
---
resume_link: http://google.com
"#,
);
let expected_config = Config {
resume_link: Url::parse("http://google.com").unwrap(),
};
assert_eq!(
expected_config,
super::parse_config(test_config.as_bytes()).unwrap()
);
}
}
| load_config | identifier_name |
config.rs | //! Utilities for managing the configuration of the website.
//!
//! The configuration should contain values that I expect to change. This way, I can edit them all
//! in a single human-readable file instead of having to track down the values in the code.
use std::fs::File; | use serde_yaml;
use url::Url;
use url_serde;
use crate::errors::*;
/// Configuration values for the website.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Config {
/// A link to a PDF copy of my Resume.
#[serde(with = "url_serde")]
pub resume_link: Url,
}
fn parse_config<R>(reader: R) -> Result<Config>
where
R: Read,
{
let config = serde_yaml::from_reader(reader)?;
Ok(config)
}
/// Load the website configuration from a path.
pub fn load<P>(config_path: P) -> Result<Config>
where
P: AsRef<Path>,
{
let path = config_path.as_ref().to_str().unwrap();
info!("loading configuration from {}", path);
let config_file = File::open(&config_path).chain_err(|| "error opening config file")?;
parse_config(config_file)
}
#[cfg(test)]
mod tests {
use super::*;
use url::Url;
#[test]
fn load_config() {
let test_config = String::from(
r#"
---
resume_link: http://google.com
"#,
);
let expected_config = Config {
resume_link: Url::parse("http://google.com").unwrap(),
};
assert_eq!(
expected_config,
super::parse_config(test_config.as_bytes()).unwrap()
);
}
} | use std::io::prelude::*;
use std::path::Path;
use log::*;
use serde::Deserialize; | random_line_split |
os.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.
//! Implementation of `std::os` functionality for Windows
#![allow(nonstandard_style)]
use os::windows::prelude::*;
use error::Error as StdError;
use ffi::{OsString, OsStr};
use fmt;
use io;
use os::windows::ffi::EncodeWide;
use path::{self, PathBuf};
use ptr;
use slice;
use sys::{c, cvt};
use sys::handle::Handle;
use super::to_u16s;
pub fn errno() -> i32 {
unsafe { c::GetLastError() as i32 }
}
/// Gets a detailed string description for the given error number.
pub fn error_string(mut errnum: i32) -> String {
// This value is calculated from the macro
// MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
let langId = 0x0800 as c::DWORD;
let mut buf = [0 as c::WCHAR; 2048];
unsafe {
let mut module = ptr::null_mut();
let mut flags = 0;
// NTSTATUS errors may be encoded as HRESULT, which may returned from
// GetLastError. For more information about Windows error codes, see
// `[MS-ERREF]`: https://msdn.microsoft.com/en-us/library/cc231198.aspx
if (errnum & c::FACILITY_NT_BIT as i32)!= 0 {
// format according to https://support.microsoft.com/en-us/help/259693
const NTDLL_DLL: &[u16] = &['N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _,
'.' as _, 'D' as _, 'L' as _, 'L' as _, 0];
module = c::GetModuleHandleW(NTDLL_DLL.as_ptr());
if module!= ptr::null_mut() {
errnum ^= c::FACILITY_NT_BIT as i32;
flags = c::FORMAT_MESSAGE_FROM_HMODULE;
}
}
let res = c::FormatMessageW(flags | c::FORMAT_MESSAGE_FROM_SYSTEM |
c::FORMAT_MESSAGE_IGNORE_INSERTS,
module,
errnum as c::DWORD,
langId,
buf.as_mut_ptr(),
buf.len() as c::DWORD,
ptr::null()) as usize;
if res == 0 {
// Sometimes FormatMessageW can fail e.g., system doesn't like langId,
let fm_err = errno();
return format!("OS Error {} (FormatMessageW() returned error {})",
errnum, fm_err);
}
match String::from_utf16(&buf[..res]) {
Ok(mut msg) => {
// Trim trailing CRLF inserted by FormatMessageW
let len = msg.trim_end().len();
msg.truncate(len);
msg
},
Err(..) => format!("OS Error {} (FormatMessageW() returned \
invalid UTF-16)", errnum),
}
}
}
pub struct Env {
base: c::LPWCH,
cur: c::LPWCH,
}
impl Iterator for Env {
type Item = (OsString, OsString);
fn next(&mut self) -> Option<(OsString, OsString)> {
loop {
unsafe {
if *self.cur == 0 { return None }
let p = &*self.cur as *const u16;
let mut len = 0;
while *p.offset(len)!= 0 {
len += 1;
}
let s = slice::from_raw_parts(p, len as usize);
self.cur = self.cur.offset(len + 1);
// Windows allows environment variables to start with an equals
// symbol (in any other position, this is the separator between
// variable name and value). Since`s` has at least length 1 at
// this point (because the empty string terminates the array of
// environment variables), we can safely slice.
let pos = match s[1..].iter().position(|&u| u == b'=' as u16).map(|p| p + 1) {
Some(p) => p,
None => continue,
};
return Some((
OsStringExt::from_wide(&s[..pos]),
OsStringExt::from_wide(&s[pos+1..]),
))
}
}
}
}
impl Drop for Env {
fn drop(&mut self) {
unsafe { c::FreeEnvironmentStringsW(self.base); }
}
}
pub fn env() -> Env {
unsafe {
let ch = c::GetEnvironmentStringsW();
if ch as usize == 0 {
panic!("failure getting env string from OS: {}",
io::Error::last_os_error());
}
Env { base: ch, cur: ch }
}
}
pub struct SplitPaths<'a> {
data: EncodeWide<'a>,
must_yield: bool,
}
pub fn split_paths(unparsed: &OsStr) -> SplitPaths {
SplitPaths {
data: unparsed.encode_wide(),
must_yield: true,
}
}
impl<'a> Iterator for SplitPaths<'a> {
type Item = PathBuf;
fn next(&mut self) -> Option<PathBuf> {
// On Windows, the PATH environment variable is semicolon separated.
// Double quotes are used as a way of introducing literal semicolons
// (since c:\some;dir is a valid Windows path). Double quotes are not
// themselves permitted in path names, so there is no way to escape a
// double quote. Quoted regions can appear in arbitrary locations, so
//
// c:\foo;c:\som"e;di"r;c:\bar
//
// Should parse as [c:\foo, c:\some;dir, c:\bar].
//
// (The above is based on testing; there is no clear reference available
// for the grammar.)
let must_yield = self.must_yield;
self.must_yield = false;
let mut in_progress = Vec::new();
let mut in_quote = false;
for b in self.data.by_ref() {
if b == '"' as u16 {
in_quote =!in_quote;
} else if b == ';' as u16 &&!in_quote {
self.must_yield = true;
break
} else {
in_progress.push(b)
}
}
if!must_yield && in_progress.is_empty() {
None
} else {
Some(super::os2path(&in_progress))
}
}
}
#[derive(Debug)]
pub struct JoinPathsError;
pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
where I: Iterator<Item=T>, T: AsRef<OsStr>
{
let mut joined = Vec::new();
let sep = b';' as u16;
for (i, path) in paths.enumerate() {
let path = path.as_ref();
if i > 0 { joined.push(sep) }
let v = path.encode_wide().collect::<Vec<u16>>();
if v.contains(&(b'"' as u16)) {
return Err(JoinPathsError)
} else if v.contains(&sep) {
joined.push(b'"' as u16);
joined.extend_from_slice(&v[..]);
joined.push(b'"' as u16);
} else {
joined.extend_from_slice(&v[..]);
}
}
Ok(OsStringExt::from_wide(&joined[..]))
}
impl fmt::Display for JoinPathsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"path segment contains `\"`".fmt(f)
}
}
impl StdError for JoinPathsError {
fn description(&self) -> &str { "failed to join paths" }
}
pub fn current_exe() -> io::Result<PathBuf> {
super::fill_utf16_buf(|buf, sz| unsafe {
c::GetModuleFileNameW(ptr::null_mut(), buf, sz)
}, super::os2path)
}
pub fn getcwd() -> io::Result<PathBuf> {
super::fill_utf16_buf(|buf, sz| unsafe {
c::GetCurrentDirectoryW(sz, buf)
}, super::os2path)
}
pub fn chdir(p: &path::Path) -> io::Result<()> {
let p: &OsStr = p.as_ref();
let mut p = p.encode_wide().collect::<Vec<_>>();
p.push(0);
cvt(unsafe {
c::SetCurrentDirectoryW(p.as_ptr())
}).map(|_| ())
}
pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
let k = to_u16s(k)?;
let res = super::fill_utf16_buf(|buf, sz| unsafe {
c::GetEnvironmentVariableW(k.as_ptr(), buf, sz)
}, |buf| {
OsStringExt::from_wide(buf)
});
match res {
Ok(value) => Ok(Some(value)),
Err(e) => {
if e.raw_os_error() == Some(c::ERROR_ENVVAR_NOT_FOUND as i32) {
Ok(None)
} else {
Err(e)
}
}
}
}
pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
let k = to_u16s(k)?;
let v = to_u16s(v)?;
cvt(unsafe {
c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr())
}).map(|_| ())
}
pub fn unsetenv(n: &OsStr) -> io::Result<()> {
let v = to_u16s(n)?;
cvt(unsafe {
c::SetEnvironmentVariableW(v.as_ptr(), ptr::null())
}).map(|_| ())
}
pub fn temp_dir() -> PathBuf {
super::fill_utf16_buf(|buf, sz| unsafe {
c::GetTempPathW(sz, buf)
}, super::os2path).unwrap()
}
pub fn home_dir() -> Option<PathBuf> {
::env::var_os("HOME").or_else(|| {
::env::var_os("USERPROFILE")
}).map(PathBuf::from).or_else(|| unsafe {
let me = c::GetCurrentProcess();
let mut token = ptr::null_mut();
if c::OpenProcessToken(me, c::TOKEN_READ, &mut token) == 0 {
return None
}
let _handle = Handle::new(token);
super::fill_utf16_buf(|buf, mut sz| {
match c::GetUserProfileDirectoryW(token, buf, &mut sz) {
0 if c::GetLastError()!= c::ERROR_INSUFFICIENT_BUFFER => 0,
0 => sz,
_ => sz - 1, // sz includes the null terminator
}
}, super::os2path).ok()
})
}
pub fn exit(code: i32) ->! {
unsafe { c::ExitProcess(code as c::UINT) }
}
pub fn | () -> u32 {
unsafe { c::GetCurrentProcessId() as u32 }
}
#[cfg(test)]
mod tests {
use io::Error;
use sys::c;
// tests `error_string` above
#[test]
fn ntstatus_error() {
const STATUS_UNSUCCESSFUL: u32 = 0xc000_0001;
assert!(!Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FACILITY_NT_BIT) as _)
.to_string().contains("FormatMessageW() returned error"));
}
}
| getpid | identifier_name |
os.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.
//! Implementation of `std::os` functionality for Windows
#![allow(nonstandard_style)]
use os::windows::prelude::*;
use error::Error as StdError;
use ffi::{OsString, OsStr};
use fmt;
use io;
use os::windows::ffi::EncodeWide;
use path::{self, PathBuf};
use ptr;
use slice;
use sys::{c, cvt};
use sys::handle::Handle;
use super::to_u16s;
pub fn errno() -> i32 {
unsafe { c::GetLastError() as i32 }
}
/// Gets a detailed string description for the given error number.
pub fn error_string(mut errnum: i32) -> String {
// This value is calculated from the macro
// MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
let langId = 0x0800 as c::DWORD;
let mut buf = [0 as c::WCHAR; 2048];
unsafe {
let mut module = ptr::null_mut();
let mut flags = 0;
// NTSTATUS errors may be encoded as HRESULT, which may returned from
// GetLastError. For more information about Windows error codes, see
// `[MS-ERREF]`: https://msdn.microsoft.com/en-us/library/cc231198.aspx
if (errnum & c::FACILITY_NT_BIT as i32)!= 0 {
// format according to https://support.microsoft.com/en-us/help/259693
const NTDLL_DLL: &[u16] = &['N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _,
'.' as _, 'D' as _, 'L' as _, 'L' as _, 0];
module = c::GetModuleHandleW(NTDLL_DLL.as_ptr());
if module!= ptr::null_mut() {
errnum ^= c::FACILITY_NT_BIT as i32;
flags = c::FORMAT_MESSAGE_FROM_HMODULE;
}
}
let res = c::FormatMessageW(flags | c::FORMAT_MESSAGE_FROM_SYSTEM |
c::FORMAT_MESSAGE_IGNORE_INSERTS,
module,
errnum as c::DWORD,
langId,
buf.as_mut_ptr(),
buf.len() as c::DWORD,
ptr::null()) as usize;
if res == 0 {
// Sometimes FormatMessageW can fail e.g., system doesn't like langId,
let fm_err = errno();
return format!("OS Error {} (FormatMessageW() returned error {})",
errnum, fm_err);
}
match String::from_utf16(&buf[..res]) {
Ok(mut msg) => {
// Trim trailing CRLF inserted by FormatMessageW
let len = msg.trim_end().len();
msg.truncate(len);
msg
},
Err(..) => format!("OS Error {} (FormatMessageW() returned \
invalid UTF-16)", errnum),
}
}
}
pub struct Env {
base: c::LPWCH,
cur: c::LPWCH,
}
impl Iterator for Env {
type Item = (OsString, OsString);
fn next(&mut self) -> Option<(OsString, OsString)> {
loop {
unsafe {
if *self.cur == 0 { return None }
let p = &*self.cur as *const u16;
let mut len = 0;
while *p.offset(len)!= 0 {
len += 1;
}
let s = slice::from_raw_parts(p, len as usize);
self.cur = self.cur.offset(len + 1);
// Windows allows environment variables to start with an equals
// symbol (in any other position, this is the separator between
// variable name and value). Since`s` has at least length 1 at
// this point (because the empty string terminates the array of
// environment variables), we can safely slice.
let pos = match s[1..].iter().position(|&u| u == b'=' as u16).map(|p| p + 1) {
Some(p) => p,
None => continue,
};
return Some((
OsStringExt::from_wide(&s[..pos]),
OsStringExt::from_wide(&s[pos+1..]),
))
}
}
}
}
impl Drop for Env {
fn drop(&mut self) {
unsafe { c::FreeEnvironmentStringsW(self.base); }
}
}
pub fn env() -> Env {
unsafe {
let ch = c::GetEnvironmentStringsW();
if ch as usize == 0 {
panic!("failure getting env string from OS: {}",
io::Error::last_os_error());
}
Env { base: ch, cur: ch }
}
}
pub struct SplitPaths<'a> {
data: EncodeWide<'a>,
must_yield: bool,
}
pub fn split_paths(unparsed: &OsStr) -> SplitPaths {
SplitPaths {
data: unparsed.encode_wide(),
must_yield: true,
}
}
impl<'a> Iterator for SplitPaths<'a> {
type Item = PathBuf;
fn next(&mut self) -> Option<PathBuf> {
// On Windows, the PATH environment variable is semicolon separated.
// Double quotes are used as a way of introducing literal semicolons
// (since c:\some;dir is a valid Windows path). Double quotes are not
// themselves permitted in path names, so there is no way to escape a
// double quote. Quoted regions can appear in arbitrary locations, so
//
// c:\foo;c:\som"e;di"r;c:\bar
//
// Should parse as [c:\foo, c:\some;dir, c:\bar].
//
// (The above is based on testing; there is no clear reference available
// for the grammar.)
let must_yield = self.must_yield;
self.must_yield = false;
let mut in_progress = Vec::new();
let mut in_quote = false;
for b in self.data.by_ref() {
if b == '"' as u16 {
in_quote =!in_quote;
} else if b == ';' as u16 &&!in_quote {
self.must_yield = true;
break
} else {
in_progress.push(b)
}
}
if!must_yield && in_progress.is_empty() {
None
} else {
Some(super::os2path(&in_progress))
}
}
}
#[derive(Debug)]
pub struct JoinPathsError;
pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
where I: Iterator<Item=T>, T: AsRef<OsStr>
{
let mut joined = Vec::new();
let sep = b';' as u16;
for (i, path) in paths.enumerate() {
let path = path.as_ref();
if i > 0 { joined.push(sep) }
let v = path.encode_wide().collect::<Vec<u16>>();
if v.contains(&(b'"' as u16)) {
return Err(JoinPathsError)
} else if v.contains(&sep) | else {
joined.extend_from_slice(&v[..]);
}
}
Ok(OsStringExt::from_wide(&joined[..]))
}
impl fmt::Display for JoinPathsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"path segment contains `\"`".fmt(f)
}
}
impl StdError for JoinPathsError {
fn description(&self) -> &str { "failed to join paths" }
}
pub fn current_exe() -> io::Result<PathBuf> {
super::fill_utf16_buf(|buf, sz| unsafe {
c::GetModuleFileNameW(ptr::null_mut(), buf, sz)
}, super::os2path)
}
pub fn getcwd() -> io::Result<PathBuf> {
super::fill_utf16_buf(|buf, sz| unsafe {
c::GetCurrentDirectoryW(sz, buf)
}, super::os2path)
}
pub fn chdir(p: &path::Path) -> io::Result<()> {
let p: &OsStr = p.as_ref();
let mut p = p.encode_wide().collect::<Vec<_>>();
p.push(0);
cvt(unsafe {
c::SetCurrentDirectoryW(p.as_ptr())
}).map(|_| ())
}
pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
let k = to_u16s(k)?;
let res = super::fill_utf16_buf(|buf, sz| unsafe {
c::GetEnvironmentVariableW(k.as_ptr(), buf, sz)
}, |buf| {
OsStringExt::from_wide(buf)
});
match res {
Ok(value) => Ok(Some(value)),
Err(e) => {
if e.raw_os_error() == Some(c::ERROR_ENVVAR_NOT_FOUND as i32) {
Ok(None)
} else {
Err(e)
}
}
}
}
pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
let k = to_u16s(k)?;
let v = to_u16s(v)?;
cvt(unsafe {
c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr())
}).map(|_| ())
}
pub fn unsetenv(n: &OsStr) -> io::Result<()> {
let v = to_u16s(n)?;
cvt(unsafe {
c::SetEnvironmentVariableW(v.as_ptr(), ptr::null())
}).map(|_| ())
}
pub fn temp_dir() -> PathBuf {
super::fill_utf16_buf(|buf, sz| unsafe {
c::GetTempPathW(sz, buf)
}, super::os2path).unwrap()
}
pub fn home_dir() -> Option<PathBuf> {
::env::var_os("HOME").or_else(|| {
::env::var_os("USERPROFILE")
}).map(PathBuf::from).or_else(|| unsafe {
let me = c::GetCurrentProcess();
let mut token = ptr::null_mut();
if c::OpenProcessToken(me, c::TOKEN_READ, &mut token) == 0 {
return None
}
let _handle = Handle::new(token);
super::fill_utf16_buf(|buf, mut sz| {
match c::GetUserProfileDirectoryW(token, buf, &mut sz) {
0 if c::GetLastError()!= c::ERROR_INSUFFICIENT_BUFFER => 0,
0 => sz,
_ => sz - 1, // sz includes the null terminator
}
}, super::os2path).ok()
})
}
pub fn exit(code: i32) ->! {
unsafe { c::ExitProcess(code as c::UINT) }
}
pub fn getpid() -> u32 {
unsafe { c::GetCurrentProcessId() as u32 }
}
#[cfg(test)]
mod tests {
use io::Error;
use sys::c;
// tests `error_string` above
#[test]
fn ntstatus_error() {
const STATUS_UNSUCCESSFUL: u32 = 0xc000_0001;
assert!(!Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FACILITY_NT_BIT) as _)
.to_string().contains("FormatMessageW() returned error"));
}
}
| {
joined.push(b'"' as u16);
joined.extend_from_slice(&v[..]);
joined.push(b'"' as u16);
} | conditional_block |
os.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.
//! Implementation of `std::os` functionality for Windows
#![allow(nonstandard_style)]
use os::windows::prelude::*;
use error::Error as StdError;
use ffi::{OsString, OsStr};
use fmt;
use io;
use os::windows::ffi::EncodeWide;
use path::{self, PathBuf};
use ptr;
use slice;
use sys::{c, cvt};
use sys::handle::Handle;
use super::to_u16s;
pub fn errno() -> i32 {
unsafe { c::GetLastError() as i32 }
}
/// Gets a detailed string description for the given error number.
pub fn error_string(mut errnum: i32) -> String {
// This value is calculated from the macro
// MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
let langId = 0x0800 as c::DWORD;
let mut buf = [0 as c::WCHAR; 2048];
unsafe {
let mut module = ptr::null_mut();
let mut flags = 0;
// NTSTATUS errors may be encoded as HRESULT, which may returned from
// GetLastError. For more information about Windows error codes, see
// `[MS-ERREF]`: https://msdn.microsoft.com/en-us/library/cc231198.aspx
if (errnum & c::FACILITY_NT_BIT as i32)!= 0 {
// format according to https://support.microsoft.com/en-us/help/259693
const NTDLL_DLL: &[u16] = &['N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _,
'.' as _, 'D' as _, 'L' as _, 'L' as _, 0];
module = c::GetModuleHandleW(NTDLL_DLL.as_ptr());
if module!= ptr::null_mut() {
errnum ^= c::FACILITY_NT_BIT as i32;
flags = c::FORMAT_MESSAGE_FROM_HMODULE;
}
}
let res = c::FormatMessageW(flags | c::FORMAT_MESSAGE_FROM_SYSTEM |
c::FORMAT_MESSAGE_IGNORE_INSERTS,
module,
errnum as c::DWORD,
langId,
buf.as_mut_ptr(),
buf.len() as c::DWORD,
ptr::null()) as usize;
if res == 0 {
// Sometimes FormatMessageW can fail e.g., system doesn't like langId,
let fm_err = errno();
return format!("OS Error {} (FormatMessageW() returned error {})",
errnum, fm_err);
}
match String::from_utf16(&buf[..res]) {
Ok(mut msg) => {
// Trim trailing CRLF inserted by FormatMessageW
let len = msg.trim_end().len();
msg.truncate(len);
msg
},
Err(..) => format!("OS Error {} (FormatMessageW() returned \
invalid UTF-16)", errnum),
}
}
}
pub struct Env {
base: c::LPWCH,
cur: c::LPWCH,
}
impl Iterator for Env {
type Item = (OsString, OsString);
fn next(&mut self) -> Option<(OsString, OsString)> | };
return Some((
OsStringExt::from_wide(&s[..pos]),
OsStringExt::from_wide(&s[pos+1..]),
))
}
}
}
}
impl Drop for Env {
fn drop(&mut self) {
unsafe { c::FreeEnvironmentStringsW(self.base); }
}
}
pub fn env() -> Env {
unsafe {
let ch = c::GetEnvironmentStringsW();
if ch as usize == 0 {
panic!("failure getting env string from OS: {}",
io::Error::last_os_error());
}
Env { base: ch, cur: ch }
}
}
pub struct SplitPaths<'a> {
data: EncodeWide<'a>,
must_yield: bool,
}
pub fn split_paths(unparsed: &OsStr) -> SplitPaths {
SplitPaths {
data: unparsed.encode_wide(),
must_yield: true,
}
}
impl<'a> Iterator for SplitPaths<'a> {
type Item = PathBuf;
fn next(&mut self) -> Option<PathBuf> {
// On Windows, the PATH environment variable is semicolon separated.
// Double quotes are used as a way of introducing literal semicolons
// (since c:\some;dir is a valid Windows path). Double quotes are not
// themselves permitted in path names, so there is no way to escape a
// double quote. Quoted regions can appear in arbitrary locations, so
//
// c:\foo;c:\som"e;di"r;c:\bar
//
// Should parse as [c:\foo, c:\some;dir, c:\bar].
//
// (The above is based on testing; there is no clear reference available
// for the grammar.)
let must_yield = self.must_yield;
self.must_yield = false;
let mut in_progress = Vec::new();
let mut in_quote = false;
for b in self.data.by_ref() {
if b == '"' as u16 {
in_quote =!in_quote;
} else if b == ';' as u16 &&!in_quote {
self.must_yield = true;
break
} else {
in_progress.push(b)
}
}
if!must_yield && in_progress.is_empty() {
None
} else {
Some(super::os2path(&in_progress))
}
}
}
#[derive(Debug)]
pub struct JoinPathsError;
pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
where I: Iterator<Item=T>, T: AsRef<OsStr>
{
let mut joined = Vec::new();
let sep = b';' as u16;
for (i, path) in paths.enumerate() {
let path = path.as_ref();
if i > 0 { joined.push(sep) }
let v = path.encode_wide().collect::<Vec<u16>>();
if v.contains(&(b'"' as u16)) {
return Err(JoinPathsError)
} else if v.contains(&sep) {
joined.push(b'"' as u16);
joined.extend_from_slice(&v[..]);
joined.push(b'"' as u16);
} else {
joined.extend_from_slice(&v[..]);
}
}
Ok(OsStringExt::from_wide(&joined[..]))
}
impl fmt::Display for JoinPathsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"path segment contains `\"`".fmt(f)
}
}
impl StdError for JoinPathsError {
fn description(&self) -> &str { "failed to join paths" }
}
pub fn current_exe() -> io::Result<PathBuf> {
super::fill_utf16_buf(|buf, sz| unsafe {
c::GetModuleFileNameW(ptr::null_mut(), buf, sz)
}, super::os2path)
}
pub fn getcwd() -> io::Result<PathBuf> {
super::fill_utf16_buf(|buf, sz| unsafe {
c::GetCurrentDirectoryW(sz, buf)
}, super::os2path)
}
pub fn chdir(p: &path::Path) -> io::Result<()> {
let p: &OsStr = p.as_ref();
let mut p = p.encode_wide().collect::<Vec<_>>();
p.push(0);
cvt(unsafe {
c::SetCurrentDirectoryW(p.as_ptr())
}).map(|_| ())
}
pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
let k = to_u16s(k)?;
let res = super::fill_utf16_buf(|buf, sz| unsafe {
c::GetEnvironmentVariableW(k.as_ptr(), buf, sz)
}, |buf| {
OsStringExt::from_wide(buf)
});
match res {
Ok(value) => Ok(Some(value)),
Err(e) => {
if e.raw_os_error() == Some(c::ERROR_ENVVAR_NOT_FOUND as i32) {
Ok(None)
} else {
Err(e)
}
}
}
}
pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
let k = to_u16s(k)?;
let v = to_u16s(v)?;
cvt(unsafe {
c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr())
}).map(|_| ())
}
pub fn unsetenv(n: &OsStr) -> io::Result<()> {
let v = to_u16s(n)?;
cvt(unsafe {
c::SetEnvironmentVariableW(v.as_ptr(), ptr::null())
}).map(|_| ())
}
pub fn temp_dir() -> PathBuf {
super::fill_utf16_buf(|buf, sz| unsafe {
c::GetTempPathW(sz, buf)
}, super::os2path).unwrap()
}
pub fn home_dir() -> Option<PathBuf> {
::env::var_os("HOME").or_else(|| {
::env::var_os("USERPROFILE")
}).map(PathBuf::from).or_else(|| unsafe {
let me = c::GetCurrentProcess();
let mut token = ptr::null_mut();
if c::OpenProcessToken(me, c::TOKEN_READ, &mut token) == 0 {
return None
}
let _handle = Handle::new(token);
super::fill_utf16_buf(|buf, mut sz| {
match c::GetUserProfileDirectoryW(token, buf, &mut sz) {
0 if c::GetLastError()!= c::ERROR_INSUFFICIENT_BUFFER => 0,
0 => sz,
_ => sz - 1, // sz includes the null terminator
}
}, super::os2path).ok()
})
}
pub fn exit(code: i32) ->! {
unsafe { c::ExitProcess(code as c::UINT) }
}
pub fn getpid() -> u32 {
unsafe { c::GetCurrentProcessId() as u32 }
}
#[cfg(test)]
mod tests {
use io::Error;
use sys::c;
// tests `error_string` above
#[test]
fn ntstatus_error() {
const STATUS_UNSUCCESSFUL: u32 = 0xc000_0001;
assert!(!Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FACILITY_NT_BIT) as _)
.to_string().contains("FormatMessageW() returned error"));
}
}
| {
loop {
unsafe {
if *self.cur == 0 { return None }
let p = &*self.cur as *const u16;
let mut len = 0;
while *p.offset(len) != 0 {
len += 1;
}
let s = slice::from_raw_parts(p, len as usize);
self.cur = self.cur.offset(len + 1);
// Windows allows environment variables to start with an equals
// symbol (in any other position, this is the separator between
// variable name and value). Since`s` has at least length 1 at
// this point (because the empty string terminates the array of
// environment variables), we can safely slice.
let pos = match s[1..].iter().position(|&u| u == b'=' as u16).map(|p| p + 1) {
Some(p) => p,
None => continue, | identifier_body |
os.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.
//! Implementation of `std::os` functionality for Windows
#![allow(nonstandard_style)]
use os::windows::prelude::*;
use error::Error as StdError;
use ffi::{OsString, OsStr};
use fmt;
use io;
use os::windows::ffi::EncodeWide;
use path::{self, PathBuf};
use ptr;
use slice;
use sys::{c, cvt};
use sys::handle::Handle;
use super::to_u16s;
pub fn errno() -> i32 {
unsafe { c::GetLastError() as i32 }
}
/// Gets a detailed string description for the given error number.
pub fn error_string(mut errnum: i32) -> String {
// This value is calculated from the macro
// MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
let langId = 0x0800 as c::DWORD;
let mut buf = [0 as c::WCHAR; 2048];
unsafe {
let mut module = ptr::null_mut();
let mut flags = 0;
// NTSTATUS errors may be encoded as HRESULT, which may returned from
// GetLastError. For more information about Windows error codes, see
// `[MS-ERREF]`: https://msdn.microsoft.com/en-us/library/cc231198.aspx
if (errnum & c::FACILITY_NT_BIT as i32)!= 0 {
// format according to https://support.microsoft.com/en-us/help/259693
const NTDLL_DLL: &[u16] = &['N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _,
'.' as _, 'D' as _, 'L' as _, 'L' as _, 0];
module = c::GetModuleHandleW(NTDLL_DLL.as_ptr());
if module!= ptr::null_mut() {
errnum ^= c::FACILITY_NT_BIT as i32;
flags = c::FORMAT_MESSAGE_FROM_HMODULE;
}
}
let res = c::FormatMessageW(flags | c::FORMAT_MESSAGE_FROM_SYSTEM |
c::FORMAT_MESSAGE_IGNORE_INSERTS,
module,
errnum as c::DWORD,
langId,
buf.as_mut_ptr(),
buf.len() as c::DWORD,
ptr::null()) as usize;
if res == 0 {
// Sometimes FormatMessageW can fail e.g., system doesn't like langId,
let fm_err = errno();
return format!("OS Error {} (FormatMessageW() returned error {})",
errnum, fm_err);
}
match String::from_utf16(&buf[..res]) {
Ok(mut msg) => {
// Trim trailing CRLF inserted by FormatMessageW
let len = msg.trim_end().len();
msg.truncate(len);
msg
},
Err(..) => format!("OS Error {} (FormatMessageW() returned \
invalid UTF-16)", errnum),
}
}
}
pub struct Env {
base: c::LPWCH,
cur: c::LPWCH,
}
impl Iterator for Env {
type Item = (OsString, OsString);
fn next(&mut self) -> Option<(OsString, OsString)> {
loop {
unsafe {
if *self.cur == 0 { return None }
let p = &*self.cur as *const u16;
let mut len = 0;
while *p.offset(len)!= 0 {
len += 1;
}
let s = slice::from_raw_parts(p, len as usize);
self.cur = self.cur.offset(len + 1);
// Windows allows environment variables to start with an equals
// symbol (in any other position, this is the separator between
// variable name and value). Since`s` has at least length 1 at
// this point (because the empty string terminates the array of
// environment variables), we can safely slice.
let pos = match s[1..].iter().position(|&u| u == b'=' as u16).map(|p| p + 1) {
Some(p) => p,
None => continue,
};
return Some((
OsStringExt::from_wide(&s[..pos]),
OsStringExt::from_wide(&s[pos+1..]),
))
}
}
}
}
impl Drop for Env {
fn drop(&mut self) {
unsafe { c::FreeEnvironmentStringsW(self.base); }
}
}
pub fn env() -> Env {
unsafe {
let ch = c::GetEnvironmentStringsW();
if ch as usize == 0 {
panic!("failure getting env string from OS: {}",
io::Error::last_os_error());
}
Env { base: ch, cur: ch }
}
}
pub struct SplitPaths<'a> {
data: EncodeWide<'a>,
must_yield: bool,
}
pub fn split_paths(unparsed: &OsStr) -> SplitPaths {
SplitPaths {
data: unparsed.encode_wide(),
must_yield: true,
}
}
impl<'a> Iterator for SplitPaths<'a> {
type Item = PathBuf;
fn next(&mut self) -> Option<PathBuf> {
// On Windows, the PATH environment variable is semicolon separated.
// Double quotes are used as a way of introducing literal semicolons
// (since c:\some;dir is a valid Windows path). Double quotes are not
// themselves permitted in path names, so there is no way to escape a
// double quote. Quoted regions can appear in arbitrary locations, so
//
// c:\foo;c:\som"e;di"r;c:\bar
//
// Should parse as [c:\foo, c:\some;dir, c:\bar].
//
// (The above is based on testing; there is no clear reference available
// for the grammar.)
let must_yield = self.must_yield;
self.must_yield = false;
let mut in_progress = Vec::new();
let mut in_quote = false;
for b in self.data.by_ref() {
if b == '"' as u16 {
in_quote =!in_quote;
} else if b == ';' as u16 &&!in_quote {
self.must_yield = true;
break |
if!must_yield && in_progress.is_empty() {
None
} else {
Some(super::os2path(&in_progress))
}
}
}
#[derive(Debug)]
pub struct JoinPathsError;
pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
where I: Iterator<Item=T>, T: AsRef<OsStr>
{
let mut joined = Vec::new();
let sep = b';' as u16;
for (i, path) in paths.enumerate() {
let path = path.as_ref();
if i > 0 { joined.push(sep) }
let v = path.encode_wide().collect::<Vec<u16>>();
if v.contains(&(b'"' as u16)) {
return Err(JoinPathsError)
} else if v.contains(&sep) {
joined.push(b'"' as u16);
joined.extend_from_slice(&v[..]);
joined.push(b'"' as u16);
} else {
joined.extend_from_slice(&v[..]);
}
}
Ok(OsStringExt::from_wide(&joined[..]))
}
impl fmt::Display for JoinPathsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"path segment contains `\"`".fmt(f)
}
}
impl StdError for JoinPathsError {
fn description(&self) -> &str { "failed to join paths" }
}
pub fn current_exe() -> io::Result<PathBuf> {
super::fill_utf16_buf(|buf, sz| unsafe {
c::GetModuleFileNameW(ptr::null_mut(), buf, sz)
}, super::os2path)
}
pub fn getcwd() -> io::Result<PathBuf> {
super::fill_utf16_buf(|buf, sz| unsafe {
c::GetCurrentDirectoryW(sz, buf)
}, super::os2path)
}
pub fn chdir(p: &path::Path) -> io::Result<()> {
let p: &OsStr = p.as_ref();
let mut p = p.encode_wide().collect::<Vec<_>>();
p.push(0);
cvt(unsafe {
c::SetCurrentDirectoryW(p.as_ptr())
}).map(|_| ())
}
pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
let k = to_u16s(k)?;
let res = super::fill_utf16_buf(|buf, sz| unsafe {
c::GetEnvironmentVariableW(k.as_ptr(), buf, sz)
}, |buf| {
OsStringExt::from_wide(buf)
});
match res {
Ok(value) => Ok(Some(value)),
Err(e) => {
if e.raw_os_error() == Some(c::ERROR_ENVVAR_NOT_FOUND as i32) {
Ok(None)
} else {
Err(e)
}
}
}
}
pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
let k = to_u16s(k)?;
let v = to_u16s(v)?;
cvt(unsafe {
c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr())
}).map(|_| ())
}
pub fn unsetenv(n: &OsStr) -> io::Result<()> {
let v = to_u16s(n)?;
cvt(unsafe {
c::SetEnvironmentVariableW(v.as_ptr(), ptr::null())
}).map(|_| ())
}
pub fn temp_dir() -> PathBuf {
super::fill_utf16_buf(|buf, sz| unsafe {
c::GetTempPathW(sz, buf)
}, super::os2path).unwrap()
}
pub fn home_dir() -> Option<PathBuf> {
::env::var_os("HOME").or_else(|| {
::env::var_os("USERPROFILE")
}).map(PathBuf::from).or_else(|| unsafe {
let me = c::GetCurrentProcess();
let mut token = ptr::null_mut();
if c::OpenProcessToken(me, c::TOKEN_READ, &mut token) == 0 {
return None
}
let _handle = Handle::new(token);
super::fill_utf16_buf(|buf, mut sz| {
match c::GetUserProfileDirectoryW(token, buf, &mut sz) {
0 if c::GetLastError()!= c::ERROR_INSUFFICIENT_BUFFER => 0,
0 => sz,
_ => sz - 1, // sz includes the null terminator
}
}, super::os2path).ok()
})
}
pub fn exit(code: i32) ->! {
unsafe { c::ExitProcess(code as c::UINT) }
}
pub fn getpid() -> u32 {
unsafe { c::GetCurrentProcessId() as u32 }
}
#[cfg(test)]
mod tests {
use io::Error;
use sys::c;
// tests `error_string` above
#[test]
fn ntstatus_error() {
const STATUS_UNSUCCESSFUL: u32 = 0xc000_0001;
assert!(!Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FACILITY_NT_BIT) as _)
.to_string().contains("FormatMessageW() returned error"));
}
} | } else {
in_progress.push(b)
}
} | random_line_split |
base_props.rs | use crate::core::{Directedness, Graph};
use num_traits::{One, PrimInt, Unsigned, Zero};
use std::borrow::Borrow;
/// A graph where new vertices can be added
pub trait NewVertex: Graph
{
/// Adds a new vertex with the given weight to the graph.
/// Returns the id of the new vertex.
fn new_vertex_weighted(&mut self, w: Self::VertexWeight) -> Result<Self::Vertex, ()>;
// Optional methods
/// Adds a new vertex to the graph.
/// Returns the id of the new vertex.
/// The weight of the vertex is the default.
fn new_vertex(&mut self) -> Result<Self::Vertex, ()>
where
Self::VertexWeight: Default,
{
self.new_vertex_weighted(Self::VertexWeight::default())
}
}
/// A graph where vertices can be removed.
///
/// Removing a vertex may invalidate existing vertices.
pub trait RemoveVertex: Graph
{
/// Removes the given vertex from the graph, returning its weight.
/// If the vertex still has edges incident on it, they are also removed,
/// dropping their weights.
fn remove_vertex(&mut self, v: impl Borrow<Self::Vertex>) -> Result<Self::VertexWeight, ()>;
}
pub trait AddEdge: Graph
{
/// Adds a copy of the given edge to the graph
fn add_edge_weighted(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
weight: Self::EdgeWeight,
) -> Result<(), ()>;
// Optional methods
/// Adds the given edge to the graph, regardless of whether there are
/// existing, identical edges in the graph.
/// The vertices the new edge is incident on must exist in the graph and the
/// id must be valid.
///
/// ###Returns
/// - `Ok` if the edge is valid and was added to the graph.
/// - `Err` if the edge is invalid or the graph was otherwise unable to
/// store it.
///
/// ###`Ok` properties:
///
/// - Only the given edge is added to the graph.
/// - Existing edges are unchanged.
/// - No vertices are introduced or removed.
///
/// ###`Err` properties:
///
/// - The graph is unchanged.
fn add_edge(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
) -> Result<(), ()>
where
Self::EdgeWeight: Default,
{
self.add_edge_weighted(source, sink, Self::EdgeWeight::default())
}
}
pub trait RemoveEdge: Graph
{
fn remove_edge_where_weight<F>(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
f: F,
) -> Result<Self::EdgeWeight, ()>
where
F: Fn(&Self::EdgeWeight) -> bool;
// Optional methods
/// Removes an edge source in v1 and sinked in v2.
///
/// ###Returns
/// - `Ok` if the edge was present before the call and was removed.
/// - `Err` if the edge was not found in the graph or it was otherwise
/// unable to remove it.
///
/// ###`Ok` properties:
///
/// - One edge identical to the given edge is removed.
/// - No new edges are introduced.
/// - No edges are changed.
/// - No new vertices are introduced or removed.
///
/// ###`Err` properties:
///
/// - The graph is unchanged.
fn remove_edge(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
) -> Result<Self::EdgeWeight, ()>
{
self.remove_edge_where_weight(source, sink, |_| true)
}
}
/// A graph with a finite number of vertices that can be counted.
pub trait VertexCount: Graph
{
type Count: PrimInt + Unsigned;
/// Returns the number of vertices in the graph.
fn vertex_count(&self) -> Self::Count
{
let mut count = Self::Count::zero();
let mut verts = self.all_vertices();
while let Some(_) = verts.next()
{
count = count + Self::Count::one();
}
count
}
}
/// A graph with a finite number of edges that can be counted.
pub trait EdgeCount: Graph
{
type Count: PrimInt + Unsigned;
/// Returns the number of vertices in the graph.
fn edge_count(&self) -> Self::Count
{
let mut count = Self::Count::zero();
let mut inc = || count = count + Self::Count::one();
let verts: Vec<_> = self.all_vertices().collect();
let mut iter = verts.iter();
let mut rest_iter = iter.clone();
while let Some(v) = iter.next()
{
for v2 in rest_iter
{
self.edges_between(v.borrow(), v2.borrow())
.for_each(|_| inc());
if Self::Directedness::directed()
|
}
rest_iter = iter.clone();
}
count
}
}
| {
self.edges_between(v2.borrow(), v.borrow())
.for_each(|_| inc());
} | conditional_block |
base_props.rs | use crate::core::{Directedness, Graph};
use num_traits::{One, PrimInt, Unsigned, Zero};
use std::borrow::Borrow;
/// A graph where new vertices can be added
pub trait NewVertex: Graph
{
/// Adds a new vertex with the given weight to the graph.
/// Returns the id of the new vertex.
fn new_vertex_weighted(&mut self, w: Self::VertexWeight) -> Result<Self::Vertex, ()>;
// Optional methods
/// Adds a new vertex to the graph.
/// Returns the id of the new vertex.
/// The weight of the vertex is the default.
fn new_vertex(&mut self) -> Result<Self::Vertex, ()>
where
Self::VertexWeight: Default,
{
self.new_vertex_weighted(Self::VertexWeight::default())
}
}
/// A graph where vertices can be removed.
///
/// Removing a vertex may invalidate existing vertices.
pub trait RemoveVertex: Graph
{
/// Removes the given vertex from the graph, returning its weight.
/// If the vertex still has edges incident on it, they are also removed,
/// dropping their weights.
fn remove_vertex(&mut self, v: impl Borrow<Self::Vertex>) -> Result<Self::VertexWeight, ()>;
}
pub trait AddEdge: Graph
{
/// Adds a copy of the given edge to the graph
fn add_edge_weighted(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
weight: Self::EdgeWeight,
) -> Result<(), ()>;
// Optional methods
/// Adds the given edge to the graph, regardless of whether there are
/// existing, identical edges in the graph.
/// The vertices the new edge is incident on must exist in the graph and the
/// id must be valid.
///
/// ###Returns
/// - `Ok` if the edge is valid and was added to the graph.
/// - `Err` if the edge is invalid or the graph was otherwise unable to
/// store it.
///
/// ###`Ok` properties:
/// | /// - No vertices are introduced or removed.
///
/// ###`Err` properties:
///
/// - The graph is unchanged.
fn add_edge(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
) -> Result<(), ()>
where
Self::EdgeWeight: Default,
{
self.add_edge_weighted(source, sink, Self::EdgeWeight::default())
}
}
pub trait RemoveEdge: Graph
{
fn remove_edge_where_weight<F>(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
f: F,
) -> Result<Self::EdgeWeight, ()>
where
F: Fn(&Self::EdgeWeight) -> bool;
// Optional methods
/// Removes an edge source in v1 and sinked in v2.
///
/// ###Returns
/// - `Ok` if the edge was present before the call and was removed.
/// - `Err` if the edge was not found in the graph or it was otherwise
/// unable to remove it.
///
/// ###`Ok` properties:
///
/// - One edge identical to the given edge is removed.
/// - No new edges are introduced.
/// - No edges are changed.
/// - No new vertices are introduced or removed.
///
/// ###`Err` properties:
///
/// - The graph is unchanged.
fn remove_edge(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
) -> Result<Self::EdgeWeight, ()>
{
self.remove_edge_where_weight(source, sink, |_| true)
}
}
/// A graph with a finite number of vertices that can be counted.
pub trait VertexCount: Graph
{
type Count: PrimInt + Unsigned;
/// Returns the number of vertices in the graph.
fn vertex_count(&self) -> Self::Count
{
let mut count = Self::Count::zero();
let mut verts = self.all_vertices();
while let Some(_) = verts.next()
{
count = count + Self::Count::one();
}
count
}
}
/// A graph with a finite number of edges that can be counted.
pub trait EdgeCount: Graph
{
type Count: PrimInt + Unsigned;
/// Returns the number of vertices in the graph.
fn edge_count(&self) -> Self::Count
{
let mut count = Self::Count::zero();
let mut inc = || count = count + Self::Count::one();
let verts: Vec<_> = self.all_vertices().collect();
let mut iter = verts.iter();
let mut rest_iter = iter.clone();
while let Some(v) = iter.next()
{
for v2 in rest_iter
{
self.edges_between(v.borrow(), v2.borrow())
.for_each(|_| inc());
if Self::Directedness::directed()
{
self.edges_between(v2.borrow(), v.borrow())
.for_each(|_| inc());
}
}
rest_iter = iter.clone();
}
count
}
} | /// - Only the given edge is added to the graph.
/// - Existing edges are unchanged. | random_line_split |
base_props.rs | use crate::core::{Directedness, Graph};
use num_traits::{One, PrimInt, Unsigned, Zero};
use std::borrow::Borrow;
/// A graph where new vertices can be added
pub trait NewVertex: Graph
{
/// Adds a new vertex with the given weight to the graph.
/// Returns the id of the new vertex.
fn new_vertex_weighted(&mut self, w: Self::VertexWeight) -> Result<Self::Vertex, ()>;
// Optional methods
/// Adds a new vertex to the graph.
/// Returns the id of the new vertex.
/// The weight of the vertex is the default.
fn new_vertex(&mut self) -> Result<Self::Vertex, ()>
where
Self::VertexWeight: Default,
|
}
/// A graph where vertices can be removed.
///
/// Removing a vertex may invalidate existing vertices.
pub trait RemoveVertex: Graph
{
/// Removes the given vertex from the graph, returning its weight.
/// If the vertex still has edges incident on it, they are also removed,
/// dropping their weights.
fn remove_vertex(&mut self, v: impl Borrow<Self::Vertex>) -> Result<Self::VertexWeight, ()>;
}
pub trait AddEdge: Graph
{
/// Adds a copy of the given edge to the graph
fn add_edge_weighted(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
weight: Self::EdgeWeight,
) -> Result<(), ()>;
// Optional methods
/// Adds the given edge to the graph, regardless of whether there are
/// existing, identical edges in the graph.
/// The vertices the new edge is incident on must exist in the graph and the
/// id must be valid.
///
/// ###Returns
/// - `Ok` if the edge is valid and was added to the graph.
/// - `Err` if the edge is invalid or the graph was otherwise unable to
/// store it.
///
/// ###`Ok` properties:
///
/// - Only the given edge is added to the graph.
/// - Existing edges are unchanged.
/// - No vertices are introduced or removed.
///
/// ###`Err` properties:
///
/// - The graph is unchanged.
fn add_edge(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
) -> Result<(), ()>
where
Self::EdgeWeight: Default,
{
self.add_edge_weighted(source, sink, Self::EdgeWeight::default())
}
}
pub trait RemoveEdge: Graph
{
fn remove_edge_where_weight<F>(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
f: F,
) -> Result<Self::EdgeWeight, ()>
where
F: Fn(&Self::EdgeWeight) -> bool;
// Optional methods
/// Removes an edge source in v1 and sinked in v2.
///
/// ###Returns
/// - `Ok` if the edge was present before the call and was removed.
/// - `Err` if the edge was not found in the graph or it was otherwise
/// unable to remove it.
///
/// ###`Ok` properties:
///
/// - One edge identical to the given edge is removed.
/// - No new edges are introduced.
/// - No edges are changed.
/// - No new vertices are introduced or removed.
///
/// ###`Err` properties:
///
/// - The graph is unchanged.
fn remove_edge(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
) -> Result<Self::EdgeWeight, ()>
{
self.remove_edge_where_weight(source, sink, |_| true)
}
}
/// A graph with a finite number of vertices that can be counted.
pub trait VertexCount: Graph
{
type Count: PrimInt + Unsigned;
/// Returns the number of vertices in the graph.
fn vertex_count(&self) -> Self::Count
{
let mut count = Self::Count::zero();
let mut verts = self.all_vertices();
while let Some(_) = verts.next()
{
count = count + Self::Count::one();
}
count
}
}
/// A graph with a finite number of edges that can be counted.
pub trait EdgeCount: Graph
{
type Count: PrimInt + Unsigned;
/// Returns the number of vertices in the graph.
fn edge_count(&self) -> Self::Count
{
let mut count = Self::Count::zero();
let mut inc = || count = count + Self::Count::one();
let verts: Vec<_> = self.all_vertices().collect();
let mut iter = verts.iter();
let mut rest_iter = iter.clone();
while let Some(v) = iter.next()
{
for v2 in rest_iter
{
self.edges_between(v.borrow(), v2.borrow())
.for_each(|_| inc());
if Self::Directedness::directed()
{
self.edges_between(v2.borrow(), v.borrow())
.for_each(|_| inc());
}
}
rest_iter = iter.clone();
}
count
}
}
| {
self.new_vertex_weighted(Self::VertexWeight::default())
} | identifier_body |
base_props.rs | use crate::core::{Directedness, Graph};
use num_traits::{One, PrimInt, Unsigned, Zero};
use std::borrow::Borrow;
/// A graph where new vertices can be added
pub trait NewVertex: Graph
{
/// Adds a new vertex with the given weight to the graph.
/// Returns the id of the new vertex.
fn new_vertex_weighted(&mut self, w: Self::VertexWeight) -> Result<Self::Vertex, ()>;
// Optional methods
/// Adds a new vertex to the graph.
/// Returns the id of the new vertex.
/// The weight of the vertex is the default.
fn new_vertex(&mut self) -> Result<Self::Vertex, ()>
where
Self::VertexWeight: Default,
{
self.new_vertex_weighted(Self::VertexWeight::default())
}
}
/// A graph where vertices can be removed.
///
/// Removing a vertex may invalidate existing vertices.
pub trait RemoveVertex: Graph
{
/// Removes the given vertex from the graph, returning its weight.
/// If the vertex still has edges incident on it, they are also removed,
/// dropping their weights.
fn remove_vertex(&mut self, v: impl Borrow<Self::Vertex>) -> Result<Self::VertexWeight, ()>;
}
pub trait AddEdge: Graph
{
/// Adds a copy of the given edge to the graph
fn add_edge_weighted(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
weight: Self::EdgeWeight,
) -> Result<(), ()>;
// Optional methods
/// Adds the given edge to the graph, regardless of whether there are
/// existing, identical edges in the graph.
/// The vertices the new edge is incident on must exist in the graph and the
/// id must be valid.
///
/// ###Returns
/// - `Ok` if the edge is valid and was added to the graph.
/// - `Err` if the edge is invalid or the graph was otherwise unable to
/// store it.
///
/// ###`Ok` properties:
///
/// - Only the given edge is added to the graph.
/// - Existing edges are unchanged.
/// - No vertices are introduced or removed.
///
/// ###`Err` properties:
///
/// - The graph is unchanged.
fn | (
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
) -> Result<(), ()>
where
Self::EdgeWeight: Default,
{
self.add_edge_weighted(source, sink, Self::EdgeWeight::default())
}
}
pub trait RemoveEdge: Graph
{
fn remove_edge_where_weight<F>(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
f: F,
) -> Result<Self::EdgeWeight, ()>
where
F: Fn(&Self::EdgeWeight) -> bool;
// Optional methods
/// Removes an edge source in v1 and sinked in v2.
///
/// ###Returns
/// - `Ok` if the edge was present before the call and was removed.
/// - `Err` if the edge was not found in the graph or it was otherwise
/// unable to remove it.
///
/// ###`Ok` properties:
///
/// - One edge identical to the given edge is removed.
/// - No new edges are introduced.
/// - No edges are changed.
/// - No new vertices are introduced or removed.
///
/// ###`Err` properties:
///
/// - The graph is unchanged.
fn remove_edge(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
) -> Result<Self::EdgeWeight, ()>
{
self.remove_edge_where_weight(source, sink, |_| true)
}
}
/// A graph with a finite number of vertices that can be counted.
pub trait VertexCount: Graph
{
type Count: PrimInt + Unsigned;
/// Returns the number of vertices in the graph.
fn vertex_count(&self) -> Self::Count
{
let mut count = Self::Count::zero();
let mut verts = self.all_vertices();
while let Some(_) = verts.next()
{
count = count + Self::Count::one();
}
count
}
}
/// A graph with a finite number of edges that can be counted.
pub trait EdgeCount: Graph
{
type Count: PrimInt + Unsigned;
/// Returns the number of vertices in the graph.
fn edge_count(&self) -> Self::Count
{
let mut count = Self::Count::zero();
let mut inc = || count = count + Self::Count::one();
let verts: Vec<_> = self.all_vertices().collect();
let mut iter = verts.iter();
let mut rest_iter = iter.clone();
while let Some(v) = iter.next()
{
for v2 in rest_iter
{
self.edges_between(v.borrow(), v2.borrow())
.for_each(|_| inc());
if Self::Directedness::directed()
{
self.edges_between(v2.borrow(), v.borrow())
.for_each(|_| inc());
}
}
rest_iter = iter.clone();
}
count
}
}
| add_edge | identifier_name |
signal-exit-status.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.
// copyright 2013-2014 the rust project developers. see the copyright
// file at the top-level directory of this distribution and at
// http://rust-lang.org/copyright.
//
// licensed under the apache license, version 2.0 <license-apache or
// http://www.apache.org/licenses/license-2.0> or the mit license
// <license-mit or http://opensource.org/licenses/mit>, at your
// option. this file may not be copied, modified, or distributed
// except according to those terms.
// ignore-win32
use std::os;
use std::io::process::{Process, ExitSignal, ExitStatus};
pub fn main() | {
let args = os::args();
let args = args.as_slice();
if args.len() >= 2 && args[1] == "signal".to_owned() {
// Raise a segfault.
unsafe { *(0 as *mut int) = 0; }
} else {
let status = Process::status(args[0], ["signal".to_owned()]).unwrap();
// Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK).
match status {
ExitSignal(_) if cfg!(unix) => {},
ExitStatus(0xC0000028) if cfg!(windows) => {},
_ => fail!("invalid termination (was not signalled): {:?}", status)
}
}
} | identifier_body |
|
signal-exit-status.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT | // 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.
// copyright 2013-2014 the rust project developers. see the copyright
// file at the top-level directory of this distribution and at
// http://rust-lang.org/copyright.
//
// licensed under the apache license, version 2.0 <license-apache or
// http://www.apache.org/licenses/license-2.0> or the mit license
// <license-mit or http://opensource.org/licenses/mit>, at your
// option. this file may not be copied, modified, or distributed
// except according to those terms.
// ignore-win32
use std::os;
use std::io::process::{Process, ExitSignal, ExitStatus};
pub fn main() {
let args = os::args();
let args = args.as_slice();
if args.len() >= 2 && args[1] == "signal".to_owned() {
// Raise a segfault.
unsafe { *(0 as *mut int) = 0; }
} else {
let status = Process::status(args[0], ["signal".to_owned()]).unwrap();
// Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK).
match status {
ExitSignal(_) if cfg!(unix) => {},
ExitStatus(0xC0000028) if cfg!(windows) => {},
_ => fail!("invalid termination (was not signalled): {:?}", status)
}
}
} | // 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 | random_line_split |
signal-exit-status.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.
// copyright 2013-2014 the rust project developers. see the copyright
// file at the top-level directory of this distribution and at
// http://rust-lang.org/copyright.
//
// licensed under the apache license, version 2.0 <license-apache or
// http://www.apache.org/licenses/license-2.0> or the mit license
// <license-mit or http://opensource.org/licenses/mit>, at your
// option. this file may not be copied, modified, or distributed
// except according to those terms.
// ignore-win32
use std::os;
use std::io::process::{Process, ExitSignal, ExitStatus};
pub fn main() {
let args = os::args();
let args = args.as_slice();
if args.len() >= 2 && args[1] == "signal".to_owned() {
// Raise a segfault.
unsafe { *(0 as *mut int) = 0; }
} else |
}
| {
let status = Process::status(args[0], ["signal".to_owned()]).unwrap();
// Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK).
match status {
ExitSignal(_) if cfg!(unix) => {},
ExitStatus(0xC0000028) if cfg!(windows) => {},
_ => fail!("invalid termination (was not signalled): {:?}", status)
}
} | conditional_block |
signal-exit-status.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.
// copyright 2013-2014 the rust project developers. see the copyright
// file at the top-level directory of this distribution and at
// http://rust-lang.org/copyright.
//
// licensed under the apache license, version 2.0 <license-apache or
// http://www.apache.org/licenses/license-2.0> or the mit license
// <license-mit or http://opensource.org/licenses/mit>, at your
// option. this file may not be copied, modified, or distributed
// except according to those terms.
// ignore-win32
use std::os;
use std::io::process::{Process, ExitSignal, ExitStatus};
pub fn | () {
let args = os::args();
let args = args.as_slice();
if args.len() >= 2 && args[1] == "signal".to_owned() {
// Raise a segfault.
unsafe { *(0 as *mut int) = 0; }
} else {
let status = Process::status(args[0], ["signal".to_owned()]).unwrap();
// Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK).
match status {
ExitSignal(_) if cfg!(unix) => {},
ExitStatus(0xC0000028) if cfg!(windows) => {},
_ => fail!("invalid termination (was not signalled): {:?}", status)
}
}
}
| main | identifier_name |
macros.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.
//! Standard library macros
//!
//! This modules contains a set of macros which are exported from the standard
//! library. Each macro is available for use when linking against the standard
//! library.
/// The entry point for panic of Rust threads.
///
/// This macro is used to inject panic into a Rust thread, causing the thread to
/// unwind and panic entirely. Each thread's panic can be reaped as the
/// `Box<Any>` type, and the single-argument form of the `panic!` macro will be
/// the value which is transmitted.
///
/// The multi-argument form of this macro panics with a string and has the
/// `format!` syntax for building a string.
///
/// # Examples
///
/// ```should_panic
/// # #![allow(unreachable_code)]
/// panic!();
/// panic!("this is a terrible mistake!");
/// panic!(4); // panic with the value of 4 to be collected elsewhere
/// panic!("this is a {} {message}", "fancy", message = "message");
/// ```
#[macro_export]
#[allow_internal_unstable]
macro_rules! panic {
() => ({
panic!("explicit panic")
});
($msg:expr) => ({
$crate::rt::begin_unwind($msg, {
// static requires less code at runtime, more constant data
static _FILE_LINE: (&'static str, u32) = (file!(), line!());
&_FILE_LINE
})
});
($fmt:expr, $($arg:tt)+) => ({
$crate::rt::begin_unwind_fmt(format_args!($fmt, $($arg)+), {
// The leading _'s are to avoid dead code warnings if this is
// used inside a dead function. Just `#[allow(dead_code)]` is
// insufficient, since the user may have
// `#[forbid(dead_code)]` and which cannot be overridden.
static _FILE_LINE: (&'static str, u32) = (file!(), line!());
&_FILE_LINE
})
});
}
/// Macro for printing to the standard output.
///
/// Equivalent to the `println!` macro except that a newline is not printed at
/// the end of the message.
///
/// Note that stdout is frequently line-buffered by default so it may be
/// necessary to use `io::stdout().flush()` to ensure the output is emitted
/// immediately.
///
/// # Panics
///
/// Panics if writing to `io::stdout()` fails.
///
/// # Examples
///
/// ```
/// use std::io::{self, Write};
///
/// print!("this ");
/// print!("will ");
/// print!("be ");
/// print!("on ");
/// print!("the ");
/// print!("same ");
/// print!("line ");
///
/// io::stdout().flush().unwrap();
///
/// print!("this string has a newline, why not choose println! instead?\n");
///
/// io::stdout().flush().unwrap();
/// ```
#[macro_export]
#[allow_internal_unstable]
macro_rules! print {
($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*)));
}
/// Macro for printing to the standard output, with a newline.
///
/// Use the `format!` syntax to write data to the standard output.
/// See `std::fmt` for more information.
///
/// # Panics
///
/// Panics if writing to `io::stdout()` fails.
///
/// # Examples
///
/// ```
/// println!("hello there!");
/// println!("format {} arguments", "some");
/// ```
#[macro_export]
macro_rules! println {
($fmt:expr) => (print!(concat!($fmt, "\n")));
($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
}
/// Helper macro for unwrapping `Result` values while returning early with an
/// error if the value of the expression is `Err`. Can only be used in
/// functions that return `Result` because of the early return of `Err` that
/// it provides.
///
/// # Examples
///
/// ```
/// use std::io;
/// use std::fs::File;
/// use std::io::prelude::*;
///
/// fn write_to_file_using_try() -> Result<(), io::Error> {
/// let mut file = try!(File::create("my_best_friends.txt"));
/// try!(file.write_all(b"This is a list of my best friends."));
/// println!("I wrote to the file");
/// Ok(())
/// }
/// // This is equivalent to:
/// fn write_to_file_using_match() -> Result<(), io::Error> {
/// let mut file = try!(File::create("my_best_friends.txt"));
/// match file.write_all(b"This is a list of my best friends.") {
/// Ok(_) => (),
/// Err(e) => return Err(e),
/// }
/// println!("I wrote to the file");
/// Ok(())
/// }
/// ```
#[macro_export]
macro_rules! try {
($expr:expr) => (match $expr {
$crate::result::Result::Ok(val) => val,
$crate::result::Result::Err(err) => {
return $crate::result::Result::Err($crate::convert::From::from(err))
}
})
}
/// A macro to select an event from a number of receivers.
///
/// This macro is used to wait for the first event to occur on a number of
/// receivers. It places no restrictions on the types of receivers given to
/// this macro, this can be viewed as a heterogeneous select.
///
/// # Examples
///
/// ```
/// #![feature(mpsc_select)]
///
/// use std::thread;
/// use std::sync::mpsc;
///
/// // two placeholder functions for now
/// fn long_running_thread() {}
/// fn calculate_the_answer() -> u32 { 42 }
///
/// let (tx1, rx1) = mpsc::channel();
/// let (tx2, rx2) = mpsc::channel();
///
/// thread::spawn(move|| { long_running_thread(); tx1.send(()).unwrap(); });
/// thread::spawn(move|| { tx2.send(calculate_the_answer()).unwrap(); });
///
/// select! {
/// _ = rx1.recv() => println!("the long running thread finished first"),
/// answer = rx2.recv() => {
/// println!("the answer was: {}", answer.unwrap());
/// }
/// }
/// # drop(rx1.recv());
/// # drop(rx2.recv());
/// ```
///
/// For more information about select, see the `std::sync::mpsc::Select` structure.
#[macro_export]
macro_rules! select {
(
$($name:pat = $rx:ident.$meth:ident() => $code:expr),+
) => ({
use $crate::sync::mpsc::Select;
let sel = Select::new();
$( let mut $rx = sel.handle(&$rx); )+
unsafe {
$( $rx.add(); )+
}
let ret = sel.wait();
$( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
{ unreachable!() }
})
}
// When testing the standard library, we link to the liblog crate to get the
// logging macros. In doing so, the liblog crate was linked against the real
// version of libstd, and uses a different std::fmt module than the test crate
// uses. To get around this difference, we redefine the log!() macro here to be
// just a dumb version of what it should be. | #[cfg(test)]
macro_rules! log {
($lvl:expr, $($args:tt)*) => (
if log_enabled!($lvl) { println!($($args)*) }
)
}
#[cfg(test)]
macro_rules! assert_approx_eq {
($a:expr, $b:expr) => ({
let (a, b) = (&$a, &$b);
assert!((*a - *b).abs() < 1.0e-6,
"{} is not approximately equal to {}", *a, *b);
})
}
/// Built-in macros to the compiler itself.
///
/// These macros do not have any corresponding definition with a `macro_rules!`
/// macro, but are documented here. Their implementations can be found hardcoded
/// into libsyntax itself.
#[cfg(dox)]
pub mod builtin {
/// The core macro for formatted string creation & output.
///
/// This macro produces a value of type `fmt::Arguments`. This value can be
/// passed to the functions in `std::fmt` for performing useful functions.
/// All other formatting macros (`format!`, `write!`, `println!`, etc) are
/// proxied through this one.
///
/// For more information, see the documentation in `std::fmt`.
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// let s = fmt::format(format_args!("hello {}", "world"));
/// assert_eq!(s, format!("hello {}", "world"));
///
/// ```
#[macro_export]
macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({
/* compiler built-in */
}) }
/// Inspect an environment variable at compile time.
///
/// This macro will expand to the value of the named environment variable at
/// compile time, yielding an expression of type `&'static str`.
///
/// If the environment variable is not defined, then a compilation error
/// will be emitted. To not emit a compile error, use the `option_env!`
/// macro instead.
///
/// # Examples
///
/// ```
/// let path: &'static str = env!("PATH");
/// println!("the $PATH variable at the time of compiling was: {}", path);
/// ```
#[macro_export]
macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
/// Optionally inspect an environment variable at compile time.
///
/// If the named environment variable is present at compile time, this will
/// expand into an expression of type `Option<&'static str>` whose value is
/// `Some` of the value of the environment variable. If the environment
/// variable is not present, then this will expand to `None`.
///
/// A compile time error is never emitted when using this macro regardless
/// of whether the environment variable is present or not.
///
/// # Examples
///
/// ```
/// let key: Option<&'static str> = option_env!("SECRET_KEY");
/// println!("the secret key might be: {:?}", key);
/// ```
#[macro_export]
macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
/// Concatenate identifiers into one identifier.
///
/// This macro takes any number of comma-separated identifiers, and
/// concatenates them all into one, yielding an expression which is a new
/// identifier. Note that hygiene makes it such that this macro cannot
/// capture local variables, and macros are only allowed in item,
/// statement or expression position, meaning this macro may be difficult to
/// use in some situations.
///
/// # Examples
///
/// ```
/// #![feature(concat_idents)]
///
/// # fn main() {
/// fn foobar() -> u32 { 23 }
///
/// let f = concat_idents!(foo, bar);
/// println!("{}", f());
/// # }
/// ```
#[macro_export]
macro_rules! concat_idents {
($($e:ident),*) => ({ /* compiler built-in */ })
}
/// Concatenates literals into a static string slice.
///
/// This macro takes any number of comma-separated literals, yielding an
/// expression of type `&'static str` which represents all of the literals
/// concatenated left-to-right.
///
/// Integer and floating point literals are stringified in order to be
/// concatenated.
///
/// # Examples
///
/// ```
/// let s = concat!("test", 10, 'b', true);
/// assert_eq!(s, "test10btrue");
/// ```
#[macro_export]
macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
/// A macro which expands to the line number on which it was invoked.
///
/// The expanded expression has type `u32`, and the returned line is not
/// the invocation of the `line!()` macro itself, but rather the first macro
/// invocation leading up to the invocation of the `line!()` macro.
///
/// # Examples
///
/// ```
/// let current_line = line!();
/// println!("defined on line: {}", current_line);
/// ```
#[macro_export]
macro_rules! line { () => ({ /* compiler built-in */ }) }
/// A macro which expands to the column number on which it was invoked.
///
/// The expanded expression has type `u32`, and the returned column is not
/// the invocation of the `column!()` macro itself, but rather the first macro
/// invocation leading up to the invocation of the `column!()` macro.
///
/// # Examples
///
/// ```
/// let current_col = column!();
/// println!("defined on column: {}", current_col);
/// ```
#[macro_export]
macro_rules! column { () => ({ /* compiler built-in */ }) }
/// A macro which expands to the file name from which it was invoked.
///
/// The expanded expression has type `&'static str`, and the returned file
/// is not the invocation of the `file!()` macro itself, but rather the
/// first macro invocation leading up to the invocation of the `file!()`
/// macro.
///
/// # Examples
///
/// ```
/// let this_file = file!();
/// println!("defined in file: {}", this_file);
/// ```
#[macro_export]
macro_rules! file { () => ({ /* compiler built-in */ }) }
/// A macro which stringifies its argument.
///
/// This macro will yield an expression of type `&'static str` which is the
/// stringification of all the tokens passed to the macro. No restrictions
/// are placed on the syntax of the macro invocation itself.
///
/// # Examples
///
/// ```
/// let one_plus_one = stringify!(1 + 1);
/// assert_eq!(one_plus_one, "1 + 1");
/// ```
#[macro_export]
macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
/// Includes a utf8-encoded file as a string.
///
/// This macro will yield an expression of type `&'static str` which is the
/// contents of the filename specified. The file is located relative to the
/// current file (similarly to how modules are found),
///
/// # Examples
///
/// ```rust,ignore
/// let secret_key = include_str!("secret-key.ascii");
/// ```
#[macro_export]
macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
/// Includes a file as a reference to a byte array.
///
/// This macro will yield an expression of type `&'static [u8; N]` which is
/// the contents of the filename specified. The file is located relative to
/// the current file (similarly to how modules are found),
///
/// # Examples
///
/// ```rust,ignore
/// let secret_key = include_bytes!("secret-key.bin");
/// ```
#[macro_export]
macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
/// Expands to a string that represents the current module path.
///
/// The current module path can be thought of as the hierarchy of modules
/// leading back up to the crate root. The first component of the path
/// returned is the name of the crate currently being compiled.
///
/// # Examples
///
/// ```
/// mod test {
/// pub fn foo() {
/// assert!(module_path!().ends_with("test"));
/// }
/// }
///
/// test::foo();
/// ```
#[macro_export]
macro_rules! module_path { () => ({ /* compiler built-in */ }) }
/// Boolean evaluation of configuration flags.
///
/// In addition to the `#[cfg]` attribute, this macro is provided to allow
/// boolean expression evaluation of configuration flags. This frequently
/// leads to less duplicated code.
///
/// The syntax given to this macro is the same syntax as the `cfg`
/// attribute.
///
/// # Examples
///
/// ```
/// let my_directory = if cfg!(windows) {
/// "windows-specific-directory"
/// } else {
/// "unix-directory"
/// };
/// ```
#[macro_export]
macro_rules! cfg { ($cfg:tt) => ({ /* compiler built-in */ }) }
/// Parse the current given file as an expression.
///
/// This is generally a bad idea, because it's going to behave unhygienically.
///
/// # Examples
///
/// ```ignore
/// fn foo() {
/// include!("/path/to/a/file")
/// }
/// ```
#[macro_export]
macro_rules! include { ($cfg:tt) => ({ /* compiler built-in */ }) }
} | random_line_split |
|
metrics.rs | use std::fmt;
use std::time::Duration;
use tic::Receiver;
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum Metric {
Request,
Processed,
}
impl fmt::Display for Metric {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
pub fn init(listen: Option<String>) -> Receiver<Metric> {
let mut config = Receiver::<Metric>::configure()
.batch_size(1)
.capacity(4096)
.poll_delay(Some(Duration::new(0, 1_000_000)))
.service(true);
if let Some(addr) = listen {
info!("listening STATS {}", addr);
config = config.http_listen(addr);
}
config.build()
}
| {
match *self {
Metric::Request => write!(f, "request"),
Metric::Processed => write!(f, "processed"),
}
} | identifier_body |
metrics.rs | use std::fmt;
use std::time::Duration;
use tic::Receiver;
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum Metric {
Request,
Processed,
}
impl fmt::Display for Metric {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Metric::Request => write!(f, "request"),
Metric::Processed => write!(f, "processed"),
}
}
}
pub fn init(listen: Option<String>) -> Receiver<Metric> {
let mut config = Receiver::<Metric>::configure()
.batch_size(1)
.capacity(4096)
.poll_delay(Some(Duration::new(0, 1_000_000)))
.service(true);
if let Some(addr) = listen {
info!("listening STATS {}", addr);
config = config.http_listen(addr);
}
config.build()
}
| fmt | identifier_name |
metrics.rs | use std::fmt;
use std::time::Duration;
use tic::Receiver;
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum Metric {
Request,
Processed,
}
impl fmt::Display for Metric {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { | }
}
}
pub fn init(listen: Option<String>) -> Receiver<Metric> {
let mut config = Receiver::<Metric>::configure()
.batch_size(1)
.capacity(4096)
.poll_delay(Some(Duration::new(0, 1_000_000)))
.service(true);
if let Some(addr) = listen {
info!("listening STATS {}", addr);
config = config.http_listen(addr);
}
config.build()
} | Metric::Request => write!(f, "request"),
Metric::Processed => write!(f, "processed"), | random_line_split |
permissionstatus.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::PermissionStatusBinding::{self, PermissionDescriptor, PermissionName};
use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionState;
use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionStatusMethods;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use std::cell::Cell;
use std::fmt::{self, Display, Formatter};
// https://w3c.github.io/permissions/#permissionstatus
#[dom_struct]
pub struct PermissionStatus {
eventtarget: EventTarget,
state: Cell<PermissionState>,
query: Cell<PermissionName>,
}
impl PermissionStatus {
pub fn new_inherited(query: PermissionName) -> PermissionStatus {
PermissionStatus {
eventtarget: EventTarget::new_inherited(),
state: Cell::new(PermissionState::Denied),
query: Cell::new(query),
}
}
pub fn new(global: &GlobalScope, query: &PermissionDescriptor) -> DomRoot<PermissionStatus> {
reflect_dom_object(Box::new(PermissionStatus::new_inherited(query.name)),
global,
PermissionStatusBinding::Wrap)
}
pub fn set_state(&self, state: PermissionState) {
self.state.set(state);
}
pub fn get_query(&self) -> PermissionName {
self.query.get()
}
}
impl PermissionStatusMethods for PermissionStatus {
// https://w3c.github.io/permissions/#dom-permissionstatus-state
fn State(&self) -> PermissionState {
self.state.get()
}
// https://w3c.github.io/permissions/#dom-permissionstatus-onchange
event_handler!(onchange, GetOnchange, SetOnchange); |
impl Display for PermissionName {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
} | } | random_line_split |
permissionstatus.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::PermissionStatusBinding::{self, PermissionDescriptor, PermissionName};
use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionState;
use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionStatusMethods;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use std::cell::Cell;
use std::fmt::{self, Display, Formatter};
// https://w3c.github.io/permissions/#permissionstatus
#[dom_struct]
pub struct PermissionStatus {
eventtarget: EventTarget,
state: Cell<PermissionState>,
query: Cell<PermissionName>,
}
impl PermissionStatus {
pub fn new_inherited(query: PermissionName) -> PermissionStatus {
PermissionStatus {
eventtarget: EventTarget::new_inherited(),
state: Cell::new(PermissionState::Denied),
query: Cell::new(query),
}
}
pub fn new(global: &GlobalScope, query: &PermissionDescriptor) -> DomRoot<PermissionStatus> {
reflect_dom_object(Box::new(PermissionStatus::new_inherited(query.name)),
global,
PermissionStatusBinding::Wrap)
}
pub fn set_state(&self, state: PermissionState) {
self.state.set(state);
}
pub fn get_query(&self) -> PermissionName {
self.query.get()
}
}
impl PermissionStatusMethods for PermissionStatus {
// https://w3c.github.io/permissions/#dom-permissionstatus-state
fn State(&self) -> PermissionState {
self.state.get()
}
// https://w3c.github.io/permissions/#dom-permissionstatus-onchange
event_handler!(onchange, GetOnchange, SetOnchange);
}
impl Display for PermissionName {
fn fmt(&self, f: &mut Formatter) -> fmt::Result |
}
| {
write!(f, "{}", self.as_str())
} | identifier_body |
permissionstatus.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::PermissionStatusBinding::{self, PermissionDescriptor, PermissionName};
use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionState;
use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionStatusMethods;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use std::cell::Cell;
use std::fmt::{self, Display, Formatter};
// https://w3c.github.io/permissions/#permissionstatus
#[dom_struct]
pub struct PermissionStatus {
eventtarget: EventTarget,
state: Cell<PermissionState>,
query: Cell<PermissionName>,
}
impl PermissionStatus {
pub fn new_inherited(query: PermissionName) -> PermissionStatus {
PermissionStatus {
eventtarget: EventTarget::new_inherited(),
state: Cell::new(PermissionState::Denied),
query: Cell::new(query),
}
}
pub fn | (global: &GlobalScope, query: &PermissionDescriptor) -> DomRoot<PermissionStatus> {
reflect_dom_object(Box::new(PermissionStatus::new_inherited(query.name)),
global,
PermissionStatusBinding::Wrap)
}
pub fn set_state(&self, state: PermissionState) {
self.state.set(state);
}
pub fn get_query(&self) -> PermissionName {
self.query.get()
}
}
impl PermissionStatusMethods for PermissionStatus {
// https://w3c.github.io/permissions/#dom-permissionstatus-state
fn State(&self) -> PermissionState {
self.state.get()
}
// https://w3c.github.io/permissions/#dom-permissionstatus-onchange
event_handler!(onchange, GetOnchange, SetOnchange);
}
impl Display for PermissionName {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
| new | identifier_name |
unused-macro.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(decl_macro)]
#![deny(unused_macros)]
// Most simple case
macro unused { //~ ERROR: unused macro definition
() => {}
}
#[allow(unused_macros)]
mod bar {
// Test that putting the #[deny] close to the macro's definition
// works.
#[deny(unused_macros)]
macro unused { //~ ERROR: unused macro definition
() => {}
}
}
mod boo {
pub(crate) macro unused { //~ ERROR: unused macro definition
() => {}
}
}
fn main() | {} | identifier_body |
|
unused-macro.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(decl_macro)]
#![deny(unused_macros)]
// Most simple case
macro unused { //~ ERROR: unused macro definition
() => {}
}
#[allow(unused_macros)]
mod bar {
// Test that putting the #[deny] close to the macro's definition
// works.
#[deny(unused_macros)]
macro unused { //~ ERROR: unused macro definition
() => {}
}
}
mod boo {
pub(crate) macro unused { //~ ERROR: unused macro definition
() => {}
}
}
fn | () {}
| main | identifier_name |
unused-macro.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(decl_macro)]
#![deny(unused_macros)]
// Most simple case
macro unused { //~ ERROR: unused macro definition
() => {}
}
#[allow(unused_macros)] | // Test that putting the #[deny] close to the macro's definition
// works.
#[deny(unused_macros)]
macro unused { //~ ERROR: unused macro definition
() => {}
}
}
mod boo {
pub(crate) macro unused { //~ ERROR: unused macro definition
() => {}
}
}
fn main() {} | mod bar { | random_line_split |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot::RwLockUpgradableReadGuard;
use crate::CacheStats;
use crate::IoTimeSeries;
use crate::ProgressBar;
/// Data needed to render render multi-line progress.
///
/// There are 2 kinds of data:
/// - I/O time series. (ex. "Network [▁▂▄█▇▅▃▆] 3MB/s")
/// - Ordinary progress bars with "position" and "total".
/// (ex. "fetching files 123/456")
#[derive(Default, Clone, Debug)]
pub struct Registry {
render_cond: Arc<(Mutex<bool>, Condvar)>,
inner: Arc<RwLock<Inner>>,
}
macro_rules! impl_model {
{
$( $field:ident: $type:ty, )*
} => {
paste::paste! {
#[derive(Default, Debug)]
struct Inner {
$( $field: Vec<Arc<$type>>, )*
}
impl Registry {
$(
/// Register a model.
pub fn [< register_ $field >](&self, model: &Arc<$type>) {
tracing::debug!("registering {} {}", stringify!($type), model.topic());
let mut inner = self.inner.write();
inner.$field.push(model.clone());
}
/// List models registered.
pub fn [< list_ $field >](&self) -> Vec<Arc<$type>> {
self.inner.read().$field.clone()
}
/// Remove models that were dropped externally.
pub fn [< remove_orphan_ $field >](&self) -> usize {
let inner = self.inner.upgradable_read();
let orphan_count = inner
.$field
.iter()
.filter(|b| Arc::strong_count(b) == 1)
.count();
if orphan_count > 0 {
tracing::debug!(
"removing {} orphan {}",
orphan_count,
stringify!($type)
);
let mut inner = RwLockUpgradableReadGuard::upgrade(inner);
inner.$field = inner
.$field
.drain(..)
.filter(|b| Arc::strong_count(b) > 1)
.collect();
}
orphan_count
}
)*
/// Remove all registered models that are dropped externally.
pub fn remove_orphan_models(&self) {
$( self.[< remove_orphan_ $field >](); )*
}
}
}
};
}
impl_model! {
cache_stats: CacheStats,
io_time_series: IoTimeSeries,
progress_bar: ProgressBar,
}
impl Registry {
/// The "main" progress registry in this process.
pub fn main() -> &'static Self {
static REGISTRY: Lazy<Registry> = Lazy::new(|| {
tracing::debug!("main progress Registry initialized");
Registry {
render_cond: Arc::new((Mutex::new(false), Condvar::new())),
..Default::default()
}
});
®ISTRY
}
/// step/wait provide a mechanism for tests to step through
/// rendering/handling of the registry in a controlled manner. The
/// test calls step() which unblocks the wait()er. Then step()
/// waits for the next wait() call, ensuring that the registry
/// processing loop finished its iteration.
pub fn step(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
*ready = true;
var.notify_one();
// Wait for wait() to notify us that it completed an iteration.
var.wait(&mut ready);
}
/// See step().
pub fn wait(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
if *ready {
// | for next step() call.
var.wait(&mut ready);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_register_bar() {
let registry = Registry::default();
let topic = "fetching files";
// Add 2 progress bars.
let bar1 = {
let bar = ProgressBar::new(topic.to_string(), 100, "files");
bar.set_position(50);
registry.register_progress_bar(&bar);
bar
};
let bar2 = {
let bar = ProgressBar::new(topic.to_string(), 200, "bytes");
bar.increase_position(100);
bar.set_message("a.txt".to_string());
registry.register_progress_bar(&bar);
bar
};
assert_eq!(registry.remove_orphan_progress_bar(), 0);
assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 50/100 files, [fetching files 100/200 bytes a.txt]"
);
// Dropping a bar marks it as "completed" and affects aggregated_bars.
drop(bar1);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 100/200 bytes a.txt]"
);
drop(bar2);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(format!("{:?}", registry.list_progress_bar()), "[]");
}
#[test]
fn test_time_series() {
let registry = Registry::default();
let series1 = IoTimeSeries::new("Net", "requests");
registry.register_io_time_series(&series1);
let series2 = IoTimeSeries::new("Disk", "files");
series2.populate_test_samples(1, 1, 1);
registry.register_io_time_series(&series2);
assert_eq!(
format!("{:?}", registry.list_io_time_series()),
"[Net [0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0], Disk [0|0|0, 5000|300|1, 20000|1200|2, 45000|2700|3, 80000|4800|4, 125000|7500|5, 180000|10800|6, 245000|14700|7, 320000|19200|8, 405000|24300|9, 500000|30000|10, 605000|36300|11, 720000|43200|12, 845000|50700|13, 980000|58800|14, 1125000|67500|15]]"
);
drop(series1);
drop(series2);
assert_eq!(registry.remove_orphan_io_time_series(), 2);
assert_eq!(format!("{:?}", registry.list_io_time_series()), "[]");
}
}
| We've come around to the next iteration's wait() call -
// notify step() that we finished an iteration.
*ready = false;
var.notify_one();
}
// Wait | conditional_block |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot::RwLockUpgradableReadGuard;
use crate::CacheStats;
use crate::IoTimeSeries;
use crate::ProgressBar;
/// Data needed to render render multi-line progress.
///
/// There are 2 kinds of data:
/// - I/O time series. (ex. "Network [▁▂▄█▇▅▃▆] 3MB/s")
/// - Ordinary progress bars with "position" and "total".
/// (ex. "fetching files 123/456")
#[derive(Default, Clone, Debug)]
pub struct Registry {
render_cond: Arc<(Mutex<bool>, Condvar)>,
inner: Arc<RwLock<Inner>>,
}
macro_rules! impl_model {
{
$( $field:ident: $type:ty, )*
} => {
paste::paste! {
#[derive(Default, Debug)]
struct Inner {
$( $field: Vec<Arc<$type>>, )*
}
impl Registry {
$(
/// Register a model.
pub fn [< register_ $field >](&self, model: &Arc<$type>) {
tracing::debug!("registering {} {}", stringify!($type), model.topic());
let mut inner = self.inner.write();
inner.$field.push(model.clone());
}
/// List models registered.
pub fn [< list_ $field >](&self) -> Vec<Arc<$type>> {
self.inner.read().$field.clone()
}
/// Remove models that were dropped externally.
pub fn [< remove_orphan_ $field >](&self) -> usize {
let inner = self.inner.upgradable_read();
let orphan_count = inner
.$field
.iter()
.filter(|b| Arc::strong_count(b) == 1)
.count();
if orphan_count > 0 {
tracing::debug!(
"removing {} orphan {}",
orphan_count,
stringify!($type)
);
let mut inner = RwLockUpgradableReadGuard::upgrade(inner);
inner.$field = inner
.$field
.drain(..)
.filter(|b| Arc::strong_count(b) > 1)
.collect();
}
orphan_count
}
)*
| }
}
}
};
}
impl_model! {
cache_stats: CacheStats,
io_time_series: IoTimeSeries,
progress_bar: ProgressBar,
}
impl Registry {
/// The "main" progress registry in this process.
pub fn main() -> &'static Self {
static REGISTRY: Lazy<Registry> = Lazy::new(|| {
tracing::debug!("main progress Registry initialized");
Registry {
render_cond: Arc::new((Mutex::new(false), Condvar::new())),
..Default::default()
}
});
®ISTRY
}
/// step/wait provide a mechanism for tests to step through
/// rendering/handling of the registry in a controlled manner. The
/// test calls step() which unblocks the wait()er. Then step()
/// waits for the next wait() call, ensuring that the registry
/// processing loop finished its iteration.
pub fn step(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
*ready = true;
var.notify_one();
// Wait for wait() to notify us that it completed an iteration.
var.wait(&mut ready);
}
/// See step().
pub fn wait(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
if *ready {
// We've come around to the next iteration's wait() call -
// notify step() that we finished an iteration.
*ready = false;
var.notify_one();
}
// Wait for next step() call.
var.wait(&mut ready);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_register_bar() {
let registry = Registry::default();
let topic = "fetching files";
// Add 2 progress bars.
let bar1 = {
let bar = ProgressBar::new(topic.to_string(), 100, "files");
bar.set_position(50);
registry.register_progress_bar(&bar);
bar
};
let bar2 = {
let bar = ProgressBar::new(topic.to_string(), 200, "bytes");
bar.increase_position(100);
bar.set_message("a.txt".to_string());
registry.register_progress_bar(&bar);
bar
};
assert_eq!(registry.remove_orphan_progress_bar(), 0);
assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 50/100 files, [fetching files 100/200 bytes a.txt]"
);
// Dropping a bar marks it as "completed" and affects aggregated_bars.
drop(bar1);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 100/200 bytes a.txt]"
);
drop(bar2);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(format!("{:?}", registry.list_progress_bar()), "[]");
}
#[test]
fn test_time_series() {
let registry = Registry::default();
let series1 = IoTimeSeries::new("Net", "requests");
registry.register_io_time_series(&series1);
let series2 = IoTimeSeries::new("Disk", "files");
series2.populate_test_samples(1, 1, 1);
registry.register_io_time_series(&series2);
assert_eq!(
format!("{:?}", registry.list_io_time_series()),
"[Net [0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0], Disk [0|0|0, 5000|300|1, 20000|1200|2, 45000|2700|3, 80000|4800|4, 125000|7500|5, 180000|10800|6, 245000|14700|7, 320000|19200|8, 405000|24300|9, 500000|30000|10, 605000|36300|11, 720000|43200|12, 845000|50700|13, 980000|58800|14, 1125000|67500|15]]"
);
drop(series1);
drop(series2);
assert_eq!(registry.remove_orphan_io_time_series(), 2);
assert_eq!(format!("{:?}", registry.list_io_time_series()), "[]");
}
} | /// Remove all registered models that are dropped externally.
pub fn remove_orphan_models(&self) {
$( self.[< remove_orphan_ $field >](); )* | random_line_split |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot::RwLockUpgradableReadGuard;
use crate::CacheStats;
use crate::IoTimeSeries;
use crate::ProgressBar;
/// Data needed to render render multi-line progress.
///
/// There are 2 kinds of data:
/// - I/O time series. (ex. "Network [▁▂▄█▇▅▃▆] 3MB/s")
/// - Ordinary progress bars with "position" and "total".
/// (ex. "fetching files 123/456")
#[derive(Default, Clone, Debug)]
pub struct Registry {
render_cond: Arc<(Mutex<bool>, Condvar)>,
inner: Arc<RwLock<Inner>>,
}
macro_rules! impl_model {
{
$( $field:ident: $type:ty, )*
} => {
paste::paste! {
#[derive(Default, Debug)]
struct Inner {
$( $field: Vec<Arc<$type>>, )*
}
impl Registry {
$(
/// Register a model.
pub fn [< register_ $field >](&self, model: &Arc<$type>) {
tracing::debug!("registering {} {}", stringify!($type), model.topic());
let mut inner = self.inner.write();
inner.$field.push(model.clone());
}
/// List models registered.
pub fn [< list_ $field >](&self) -> Vec<Arc<$type>> {
self.inner.read().$field.clone()
}
/// Remove models that were dropped externally.
pub fn [< remove_orphan_ $field >](&self) -> usize {
let inner = self.inner.upgradable_read();
let orphan_count = inner
.$field
.iter()
.filter(|b| Arc::strong_count(b) == 1)
.count();
if orphan_count > 0 {
tracing::debug!(
"removing {} orphan {}",
orphan_count,
stringify!($type)
);
let mut inner = RwLockUpgradableReadGuard::upgrade(inner);
inner.$field = inner
.$field
.drain(..)
.filter(|b| Arc::strong_count(b) > 1)
.collect();
}
orphan_count
}
)*
/// Remove all registered models that are dropped externally.
pub fn remove_orphan_models(&self) {
$( self.[< remove_orphan_ $field >](); )*
}
}
}
};
}
impl_model! {
cache_stats: CacheStats,
io_time_series: IoTimeSeries,
progress_bar: ProgressBar,
}
impl Registry {
/// The "main" progress registry in this process.
pub fn main() -> &'static Self {
static REGISTRY: Lazy<Registry> = Lazy::new(|| {
tracing::debug!("main progress Registry initialized");
Registry {
render_cond: Arc::new((Mutex::new(false), Condvar::new())),
..Default::default()
}
});
®ISTRY
}
/// step/wait provide a mechanism for tests to step through
/// rendering/handling of the registry in a controlled manner. The
/// test calls step() which unblocks the wait()er. Then step()
/// waits for the next wait() call, ensuring that the registry
/// processing loop finished its iteration.
pub fn step(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
*ready = true;
var.notify_one();
// Wait for wait() to notify us that it completed an iteration.
var.wait(&mut ready);
}
/// See step().
pub fn wait(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
if *ready {
// We've come around to the next iteration's wait() call -
// notify step() that we finished an iteration.
*ready = false;
var.notify_one();
}
// Wait for next step() call.
var.wait(&mut ready);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_register_bar() {
let re | assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 50/100 files, [fetching files 100/200 bytes a.txt]"
);
// Dropping a bar marks it as "completed" and affects aggregated_bars.
drop(bar1);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 100/200 bytes a.txt]"
);
drop(bar2);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(format!("{:?}", registry.list_progress_bar()), "[]");
}
#[test]
fn test_time_series() {
let registry = Registry::default();
let series1 = IoTimeSeries::new("Net", "requests");
registry.register_io_time_series(&series1);
let series2 = IoTimeSeries::new("Disk", "files");
series2.populate_test_samples(1, 1, 1);
registry.register_io_time_series(&series2);
assert_eq!(
format!("{:?}", registry.list_io_time_series()),
"[Net [0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0], Disk [0|0|0, 5000|300|1, 20000|1200|2, 45000|2700|3, 80000|4800|4, 125000|7500|5, 180000|10800|6, 245000|14700|7, 320000|19200|8, 405000|24300|9, 500000|30000|10, 605000|36300|11, 720000|43200|12, 845000|50700|13, 980000|58800|14, 1125000|67500|15]]"
);
drop(series1);
drop(series2);
assert_eq!(registry.remove_orphan_io_time_series(), 2);
assert_eq!(format!("{:?}", registry.list_io_time_series()), "[]");
}
}
| gistry = Registry::default();
let topic = "fetching files";
// Add 2 progress bars.
let bar1 = {
let bar = ProgressBar::new(topic.to_string(), 100, "files");
bar.set_position(50);
registry.register_progress_bar(&bar);
bar
};
let bar2 = {
let bar = ProgressBar::new(topic.to_string(), 200, "bytes");
bar.increase_position(100);
bar.set_message("a.txt".to_string());
registry.register_progress_bar(&bar);
bar
};
assert_eq!(registry.remove_orphan_progress_bar(), 0); | identifier_body |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot::RwLockUpgradableReadGuard;
use crate::CacheStats;
use crate::IoTimeSeries;
use crate::ProgressBar;
/// Data needed to render render multi-line progress.
///
/// There are 2 kinds of data:
/// - I/O time series. (ex. "Network [▁▂▄█▇▅▃▆] 3MB/s")
/// - Ordinary progress bars with "position" and "total".
/// (ex. "fetching files 123/456")
#[derive(Default, Clone, Debug)]
pub struct Registry {
render_cond: Arc<(Mutex<bool>, Condvar)>,
inner: Arc<RwLock<Inner>>,
}
macro_rules! impl_model {
{
$( $field:ident: $type:ty, )*
} => {
paste::paste! {
#[derive(Default, Debug)]
struct Inner {
$( $field: Vec<Arc<$type>>, )*
}
impl Registry {
$(
/// Register a model.
pub fn [< register_ $field >](&self, model: &Arc<$type>) {
tracing::debug!("registering {} {}", stringify!($type), model.topic());
let mut inner = self.inner.write();
inner.$field.push(model.clone());
}
/// List models registered.
pub fn [< list_ $field >](&self) -> Vec<Arc<$type>> {
self.inner.read().$field.clone()
}
/// Remove models that were dropped externally.
pub fn [< remove_orphan_ $field >](&self) -> usize {
let inner = self.inner.upgradable_read();
let orphan_count = inner
.$field
.iter()
.filter(|b| Arc::strong_count(b) == 1)
.count();
if orphan_count > 0 {
tracing::debug!(
"removing {} orphan {}",
orphan_count,
stringify!($type)
);
let mut inner = RwLockUpgradableReadGuard::upgrade(inner);
inner.$field = inner
.$field
.drain(..)
.filter(|b| Arc::strong_count(b) > 1)
.collect();
}
orphan_count
}
)*
/// Remove all registered models that are dropped externally.
pub fn remove_orphan_models(&self) {
$( self.[< remove_orphan_ $field >](); )*
}
}
}
};
}
impl_model! {
cache_stats: CacheStats,
io_time_series: IoTimeSeries,
progress_bar: ProgressBar,
}
impl Registry {
/// The "main" progress registry in this process.
pub fn main() -> &'static Self {
static REGISTRY: Lazy<Registry> = Lazy::new(|| {
tracing::debug!("main progress Registry initialized");
Registry {
render_cond: Arc::new((Mutex::new(false), Condvar::new())),
..Default::default()
}
});
®ISTRY
}
/// step/wait provide a mechanism for tests to step through
/// rendering/handling of the registry in a controlled manner. The
/// test calls step() which unblocks the wait()er. Then step()
/// waits for the next wait() call, ensuring that the registry
/// processing loop finished its iteration.
pub fn step(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
*ready = true;
var.notify_one();
// Wait for wait() to notify us that it completed an iteration.
var.wait(&mut ready);
}
/// See step().
pub fn wait(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
if *ready {
// We've come around to the next iteration's wait() call -
// notify step() that we finished an iteration.
*ready = false;
var.notify_one();
}
// Wait for next step() call.
var.wait(&mut ready);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_register_bar() {
let registry = Registry::default();
let topic = "fetching files";
// Add 2 progress bars.
let bar1 = {
let bar = ProgressBar::new(topic.to_string(), 100, "files");
bar.set_position(50);
registry.register_progress_bar(&bar);
bar
};
let bar2 = {
let bar = ProgressBar::new(topic.to_string(), 200, "bytes");
bar.increase_position(100);
bar.set_message("a.txt".to_string());
registry.register_progress_bar(&bar);
bar
};
assert_eq!(registry.remove_orphan_progress_bar(), 0);
assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 50/100 files, [fetching files 100/200 bytes a.txt]"
);
// Dropping a bar marks it as "completed" and affects aggregated_bars.
drop(bar1);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 100/200 bytes a.txt]"
);
drop(bar2);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(format!("{:?}", registry.list_progress_bar()), "[]");
}
#[test]
fn test_time_series | registry = Registry::default();
let series1 = IoTimeSeries::new("Net", "requests");
registry.register_io_time_series(&series1);
let series2 = IoTimeSeries::new("Disk", "files");
series2.populate_test_samples(1, 1, 1);
registry.register_io_time_series(&series2);
assert_eq!(
format!("{:?}", registry.list_io_time_series()),
"[Net [0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0], Disk [0|0|0, 5000|300|1, 20000|1200|2, 45000|2700|3, 80000|4800|4, 125000|7500|5, 180000|10800|6, 245000|14700|7, 320000|19200|8, 405000|24300|9, 500000|30000|10, 605000|36300|11, 720000|43200|12, 845000|50700|13, 980000|58800|14, 1125000|67500|15]]"
);
drop(series1);
drop(series2);
assert_eq!(registry.remove_orphan_io_time_series(), 2);
assert_eq!(format!("{:?}", registry.list_io_time_series()), "[]");
}
}
| () {
let | identifier_name |
where-clauses-cross-crate.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.
// aux-build:where_clauses_xc.rs
extern crate where_clauses_xc;
use where_clauses_xc::{Equal, equal}; | println!("{}", equal(&1, &1));
println!("{}", "hello".equal(&"hello"));
println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar"));
} |
fn main() {
println!("{}", equal(&1, &2)); | random_line_split |
where-clauses-cross-crate.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.
// aux-build:where_clauses_xc.rs
extern crate where_clauses_xc;
use where_clauses_xc::{Equal, equal};
fn | () {
println!("{}", equal(&1, &2));
println!("{}", equal(&1, &1));
println!("{}", "hello".equal(&"hello"));
println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar"));
}
| main | identifier_name |
where-clauses-cross-crate.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.
// aux-build:where_clauses_xc.rs
extern crate where_clauses_xc;
use where_clauses_xc::{Equal, equal};
fn main() | {
println!("{}", equal(&1, &2));
println!("{}", equal(&1, &1));
println!("{}", "hello".equal(&"hello"));
println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar"));
} | identifier_body |
|
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Intern {
Intern { vec: Vec::new() }
}
pub fn add(&mut self, string: &CStr) -> *const c_char {
fn e | s1: &CStr, s2: &CStr) -> bool {
s1 == s2
}
for s in &self.vec {
if eq(s, string) {
return s.as_ptr();
}
}
self.vec.push(string.to_owned());
self.vec.last().unwrap().as_ptr()
}
}
#[cfg(test)]
mod tests {
use super::Intern;
use std::ffi::CStr;
#[test]
fn intern() {
fn cstr(str: &[u8]) -> &CStr {
CStr::from_bytes_with_nul(str).unwrap()
}
let mut intern = Intern::new();
let foo_ptr = intern.add(cstr(b"foo\0"));
let bar_ptr = intern.add(cstr(b"bar\0"));
assert!(!foo_ptr.is_null());
assert!(!bar_ptr.is_null());
assert!(foo_ptr!= bar_ptr);
assert!(foo_ptr == intern.add(cstr(b"foo\0")));
assert!(foo_ptr!= intern.add(cstr(b"fo\0")));
assert!(foo_ptr!= intern.add(cstr(b"fool\0")));
assert!(foo_ptr!= intern.add(cstr(b"not foo\0")));
}
}
| q( | identifier_name |
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Intern {
Intern { vec: Vec::new() }
}
pub fn add(&mut self, string: &CStr) -> *const c_char {
fn eq(s1: &CStr, s2: &CStr) -> bool { | for s in &self.vec {
if eq(s, string) {
return s.as_ptr();
}
}
self.vec.push(string.to_owned());
self.vec.last().unwrap().as_ptr()
}
}
#[cfg(test)]
mod tests {
use super::Intern;
use std::ffi::CStr;
#[test]
fn intern() {
fn cstr(str: &[u8]) -> &CStr {
CStr::from_bytes_with_nul(str).unwrap()
}
let mut intern = Intern::new();
let foo_ptr = intern.add(cstr(b"foo\0"));
let bar_ptr = intern.add(cstr(b"bar\0"));
assert!(!foo_ptr.is_null());
assert!(!bar_ptr.is_null());
assert!(foo_ptr!= bar_ptr);
assert!(foo_ptr == intern.add(cstr(b"foo\0")));
assert!(foo_ptr!= intern.add(cstr(b"fo\0")));
assert!(foo_ptr!= intern.add(cstr(b"fool\0")));
assert!(foo_ptr!= intern.add(cstr(b"not foo\0")));
}
}
|
s1 == s2
}
| identifier_body |
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Intern {
Intern { vec: Vec::new() }
}
pub fn add(&mut self, string: &CStr) -> *const c_char {
fn eq(s1: &CStr, s2: &CStr) -> bool {
s1 == s2
}
for s in &self.vec {
if eq(s, string) { | }
self.vec.push(string.to_owned());
self.vec.last().unwrap().as_ptr()
}
}
#[cfg(test)]
mod tests {
use super::Intern;
use std::ffi::CStr;
#[test]
fn intern() {
fn cstr(str: &[u8]) -> &CStr {
CStr::from_bytes_with_nul(str).unwrap()
}
let mut intern = Intern::new();
let foo_ptr = intern.add(cstr(b"foo\0"));
let bar_ptr = intern.add(cstr(b"bar\0"));
assert!(!foo_ptr.is_null());
assert!(!bar_ptr.is_null());
assert!(foo_ptr!= bar_ptr);
assert!(foo_ptr == intern.add(cstr(b"foo\0")));
assert!(foo_ptr!= intern.add(cstr(b"fo\0")));
assert!(foo_ptr!= intern.add(cstr(b"fool\0")));
assert!(foo_ptr!= intern.add(cstr(b"not foo\0")));
}
}
|
return s.as_ptr();
}
| conditional_block |
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Intern {
Intern { vec: Vec::new() }
}
pub fn add(&mut self, string: &CStr) -> *const c_char {
fn eq(s1: &CStr, s2: &CStr) -> bool {
s1 == s2
}
for s in &self.vec {
if eq(s, string) {
return s.as_ptr();
}
}
self.vec.push(string.to_owned());
self.vec.last().unwrap().as_ptr()
}
}
#[cfg(test)]
mod tests {
use super::Intern;
use std::ffi::CStr;
#[test]
fn intern() {
fn cstr(str: &[u8]) -> &CStr {
CStr::from_bytes_with_nul(str).unwrap()
}
let mut intern = Intern::new(); | assert!(!bar_ptr.is_null());
assert!(foo_ptr!= bar_ptr);
assert!(foo_ptr == intern.add(cstr(b"foo\0")));
assert!(foo_ptr!= intern.add(cstr(b"fo\0")));
assert!(foo_ptr!= intern.add(cstr(b"fool\0")));
assert!(foo_ptr!= intern.add(cstr(b"not foo\0")));
}
} |
let foo_ptr = intern.add(cstr(b"foo\0"));
let bar_ptr = intern.add(cstr(b"bar\0"));
assert!(!foo_ptr.is_null()); | random_line_split |
main.rs | #![feature(associated_consts)]
#![feature(slice_patterns)]
#![feature(const_fn)]
//#![deny(missing_docs)]
//#![deny(warnings)]
extern crate sdl2;
extern crate nuklear_rust as nk;
use nk::*;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Difficulty {
Easy,
Hard
}
#[derive(Debug, Default, Copy, Clone, PartialEq)]
#[repr(C, packed)]
struct GuiVertex {
position: [f32; 2],
uv: [f32; 2],
color: [u8; 4]
}
use std::mem::size_of;
impl GuiVertex {
const OFFSETOF_POSITION: usize = 0;
const OFFSETOF_UV: usize = 8;
const OFFSETOF_COLOR: usize = 16;
}
const MAX_VERTEX_BUFFER: usize = 512 * 1024;
const MAX_ELEMENT_BUFFER: usize = 128 * 1024;
struct App<'a> {
sdl2: sdl2::Sdl,
rdr: sdl2::render::Renderer<'a>,
nk: nk::NkContext,
property: i32,
op: Difficulty,
aa: NkAntiAliasing,
}
enum AppEventHandling {
Quit,
Unhandled,
}
trait IntoNkKey {
fn to_nk_key(&self) -> NkKey;
}
use sdl2::keyboard::Keycode;
use sdl2::keyboard::Keycode::*;
use NkKey::*;
impl IntoNkKey for Keycode {
fn to_nk_key(&self) -> NkKey {
match self {
&Up => NK_KEY_UP,
_ => NK_KEY_NONE,
}
}
}
impl<'a> App<'a> {
fn new() -> Self {
let sdl2 = sdl2::init().expect("Could not initialize SDL2");
let sdl2_video = sdl2.video().expect("Could not initialize video subsystem");
let window = sdl2_video.window("Foo", 800, 600).build().unwrap();
let rdr =
window.renderer().accelerated().present_vsync().build().unwrap();
use std::fs::File;
use std::io::Read;
let mut buf = Vec::<u8>::new();
let mut file = File::open("/home/yoon/.local/share/fonts/basis33.ttf").unwrap();
file.read_to_end(&mut buf).unwrap();
drop(file);
let mut atlas = NkFontAtlas::new(&mut NkAllocator::new_vec());
atlas.begin();
let mut font = atlas.add_font_with_bytes(&buf, 16f32).unwrap();
let _ = atlas.bake(NkFontAtlasFormat::NK_FONT_ATLAS_RGBA32);
atlas.end(NkHandle::from_ptr(std::ptr::null_mut()), None);
let mut nk = NkContext::new(&mut NkAllocator::new_vec(), &font.handle());
nk.style_set_font(&font.handle());
App {
sdl2, rdr, nk, property: 0, op: Difficulty::Easy, aa: NkAntiAliasing::NK_ANTI_ALIASING_OFF
}
}
fn handle_event(&mut self, e: &sdl2::event::Event) -> Result<(), AppEventHandling> {
use sdl2::event::Event;
self.nk.input_begin();
let out = match e {
&Event::MouseMotion { x, y,.. } => {
println!("Mouse at {:?}", (x, y));
Ok(())
},
&Event::KeyDown { keycode,.. } => {
self.nk.input_key(keycode.unwrap().to_nk_key(), true);
println!("Key {:?} is down", keycode);
Ok(())
},
&Event::KeyUp { keycode,.. } => {
self.nk.input_key(keycode.unwrap().to_nk_key(), false);
println!("Key {:?} is up", keycode);
Ok(())
},
&Event::TextInput {..} => Ok(()),
&Event::MouseButtonDown { mouse_btn,.. } => {
println!("Mouse {:?} is down", mouse_btn);
Ok(())
},
&Event::MouseButtonUp { mouse_btn,.. } => {
println!("Mouse {:?} is up", mouse_btn);
Ok(())
},
&Event::MouseWheel { direction, y,.. } => {
println!("Mouse scroll: {} ({:?})", y, direction);
Ok(())
},
&Event::Window {..} => Ok(()),
&Event::Quit {..} => Err(AppEventHandling::Quit),
_ => Err(AppEventHandling::Unhandled),
};
self.nk.input_end();
out
}
fn gui(&mut self) {
let nk = &mut self.nk;
let title = NkString::from("Foo");
let rect = NkRect {x:20f32, y:30f32, w:200f32, h:200f32};
use NkPanelFlags::*;
let flags = NK_WINDOW_MOVABLE as u32
| NK_WINDOW_SCALABLE as u32
| NK_WINDOW_CLOSABLE as u32
| NK_WINDOW_MINIMIZABLE as u32
| NK_WINDOW_TITLE as u32;
if nk.begin(title, rect, flags) {
use NkTextAlignment::*;
nk.menubar_begin();
nk.layout_row_begin(NkLayoutFormat::NK_STATIC, 25f32, 2);
nk.layout_row_push(45f32);
if nk.menu_begin_label(NkString::from("FILE"), NK_TEXT_LEFT as u32, NkVec2 { x:120f32, y:200f32 }) {
nk.layout_row_dynamic(30f32, 1);
nk.menu_item_label(NkString::from("OPEN"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("CLOSE"), NK_TEXT_LEFT as u32);
nk.menu_end();
}
nk.layout_row_push(45f32);
if nk.menu_begin_label(NkString::from("EDIT"), NK_TEXT_LEFT as u32, NkVec2 { x:120f32, y:200f32 }) {
nk.layout_row_dynamic(30f32, 1);
nk.menu_item_label(NkString::from("CUT"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("COPY"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("CLOSE"), NK_TEXT_LEFT as u32);
nk.menu_end();
}
nk.layout_row_end();
nk.menubar_end();
nk.layout_row_static(30f32, 80, 1);
if nk.button_label(NkString::from("button")) {
println!("Button pressed!");
}
use Difficulty::*;
nk.layout_row_dynamic(30f32, 2);
if nk.option_label(NkString::from("Easy"), self.op == Easy) {
self.op = Easy;
}
if nk.option_label(NkString::from("Hard"), self.op == Hard) {
self.op = Hard;
}
nk.layout_row_dynamic(25f32, 1);
nk.property_int(NkString::from("Compression:"), 0, &mut self.property, 100, 10, 1f32);
}
nk.end();
}
fn render_gui(&mut self) {
let nk = &mut self.nk;
const MAX_CMDS_BUFFER: usize = MAX_VERTEX_BUFFER;
let mut cmd_mem = [0u8; MAX_CMDS_BUFFER];
let mut cmds = NkBuffer::with_fixed(&mut cmd_mem);
use NkDrawVertexLayoutFormat::*;
use NkDrawVertexLayoutAttribute::*;
let vlayout = NkDrawVertexLayoutElements::new(&[
(NK_VERTEX_POSITION, NK_FORMAT_FLOAT, GuiVertex::OFFSETOF_POSITION as u32),
(NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, GuiVertex::OFFSETOF_UV as u32),
(NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, GuiVertex::OFFSETOF_COLOR as u32),
// è_é
(NK_VERTEX_ATTRIBUTE_COUNT, NK_FORMAT_COUNT, 0),
]);
let mut config = NkConvertConfig::default();
config.set_vertex_layout(&vlayout);
config.set_vertex_size(size_of::<GuiVertex>());
config.set_null(NkDrawNullTexture::default());
config.set_circle_segment_count(22);
config.set_curve_segment_count(22);
config.set_arc_segment_count(22);
config.set_global_alpha(1f32);
config.set_shape_aa(self.aa);
config.set_line_aa(self.aa);
/*
use std::slice::from_raw_parts_mut as frpm;
let mut vmem = [0u8; MAX_VERTEX_BUFFER];
let mut emem = [0u8; MAX_ELEMENT_BUFFER];
let vertices = unsafe { frpm(vmem.as_mut_ptr() as *mut GuiVertex, MAX_VERTEX_BUFFER/size_of::<GuiVertex>()) };
let elements = unsafe { frpm(emem.as_mut_ptr() as *mut u16, MAX_ELEMENT_BUFFER/size_of::<u16>()) };
let mut vbuf = NkBuffer::with_fixed(&mut vmem);
let mut ebuf = NkBuffer::with_fixed(&mut emem);
nk.convert(&mut cmds, &mut ebuf, &mut vbuf, &config);
let mut offset = 0;
for cmd in nk.draw_command_iterator(&cmds) {
let elem_count = cmd.elem_count();
if elem_count <= 0 {
continue;
}
for i in offset..(offset+elem_count) {
let e = elements[i as usize] as usize;
println!("i: {}", e);
let v = vertices[e];
let [x,y] = v.position;
let [r,g,b,a] = v.color;
let (w,h) = self.rdr.window().unwrap().size();
let x = (w as f32*(x+1f32)/2f32) as i32;
let y = -(h as f32*(y+1f32)/2f32) as i32;
self.rdr.set_draw_color(sdl2::pixels::Color::RGBA(r,g,b,a));
self.rdr.draw_point(sdl2::rect::Point::new(x,y)).unwrap();
}
offset += elem_count;
}
*/
for cmd in nk.command_iterator() {
println!("cmd: {:?}", cmd);
}
nk.clear();
}
}
fn ma | {
std::env::set_var("RUST_BACKTRACE", "1");
let mut app = App::new();
let mut event_pump = app.sdl2.event_pump().unwrap();
'running: loop {
for e in event_pump.poll_iter() {
use AppEventHandling::*;
match app.handle_event(&e) {
Ok(_) => (),
Err(Quit) => break 'running,
Err(Unhandled) => println!("Unhandled event: {:?}", &e),
};
}
use sdl2::pixels::Color::*;
use sdl2::rect::Rect;
app.rdr.set_draw_color(RGB(255, 255, 0));
app.rdr.clear();
app.rdr.set_draw_color(RGB(0, 255, 255));
app.rdr.draw_rect(Rect::new(20, 20, 50, 50)).unwrap();
app.gui();
app.render_gui();
app.rdr.present();
}
}
| in() | identifier_name |
main.rs | #![feature(associated_consts)]
#![feature(slice_patterns)]
#![feature(const_fn)]
//#![deny(missing_docs)]
//#![deny(warnings)]
extern crate sdl2;
extern crate nuklear_rust as nk;
use nk::*;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Difficulty {
Easy,
Hard
}
#[derive(Debug, Default, Copy, Clone, PartialEq)]
#[repr(C, packed)]
struct GuiVertex {
position: [f32; 2],
uv: [f32; 2],
color: [u8; 4]
}
use std::mem::size_of;
impl GuiVertex {
const OFFSETOF_POSITION: usize = 0;
const OFFSETOF_UV: usize = 8;
const OFFSETOF_COLOR: usize = 16;
}
const MAX_VERTEX_BUFFER: usize = 512 * 1024;
const MAX_ELEMENT_BUFFER: usize = 128 * 1024;
struct App<'a> {
sdl2: sdl2::Sdl,
rdr: sdl2::render::Renderer<'a>,
nk: nk::NkContext,
property: i32,
op: Difficulty,
aa: NkAntiAliasing,
}
enum AppEventHandling {
Quit,
Unhandled,
}
trait IntoNkKey {
fn to_nk_key(&self) -> NkKey;
}
use sdl2::keyboard::Keycode;
use sdl2::keyboard::Keycode::*;
use NkKey::*;
impl IntoNkKey for Keycode {
fn to_nk_key(&self) -> NkKey {
match self {
&Up => NK_KEY_UP,
_ => NK_KEY_NONE,
}
}
}
impl<'a> App<'a> {
fn new() -> Self {
let sdl2 = sdl2::init().expect("Could not initialize SDL2");
let sdl2_video = sdl2.video().expect("Could not initialize video subsystem");
let window = sdl2_video.window("Foo", 800, 600).build().unwrap();
let rdr =
window.renderer().accelerated().present_vsync().build().unwrap();
use std::fs::File;
use std::io::Read;
let mut buf = Vec::<u8>::new();
let mut file = File::open("/home/yoon/.local/share/fonts/basis33.ttf").unwrap();
file.read_to_end(&mut buf).unwrap();
drop(file);
let mut atlas = NkFontAtlas::new(&mut NkAllocator::new_vec());
atlas.begin();
let mut font = atlas.add_font_with_bytes(&buf, 16f32).unwrap();
let _ = atlas.bake(NkFontAtlasFormat::NK_FONT_ATLAS_RGBA32);
atlas.end(NkHandle::from_ptr(std::ptr::null_mut()), None);
let mut nk = NkContext::new(&mut NkAllocator::new_vec(), &font.handle());
nk.style_set_font(&font.handle());
App {
sdl2, rdr, nk, property: 0, op: Difficulty::Easy, aa: NkAntiAliasing::NK_ANTI_ALIASING_OFF
}
}
fn handle_event(&mut self, e: &sdl2::event::Event) -> Result<(), AppEventHandling> {
use sdl2::event::Event;
self.nk.input_begin();
let out = match e {
&Event::MouseMotion { x, y,.. } => {
println!("Mouse at {:?}", (x, y));
Ok(())
},
&Event::KeyDown { keycode,.. } => {
self.nk.input_key(keycode.unwrap().to_nk_key(), true);
println!("Key {:?} is down", keycode);
Ok(())
},
&Event::KeyUp { keycode,.. } => {
self.nk.input_key(keycode.unwrap().to_nk_key(), false);
println!("Key {:?} is up", keycode);
Ok(())
},
&Event::TextInput {..} => Ok(()),
&Event::MouseButtonDown { mouse_btn,.. } => {
println!("Mouse {:?} is down", mouse_btn);
Ok(())
},
&Event::MouseButtonUp { mouse_btn,.. } => {
println!("Mouse {:?} is up", mouse_btn);
Ok(())
},
&Event::MouseWheel { direction, y,.. } => {
println!("Mouse scroll: {} ({:?})", y, direction);
Ok(())
},
&Event::Window {..} => Ok(()),
&Event::Quit {..} => Err(AppEventHandling::Quit),
_ => Err(AppEventHandling::Unhandled),
};
self.nk.input_end();
out
}
fn gui(&mut self) {
let nk = &mut self.nk;
let title = NkString::from("Foo");
let rect = NkRect {x:20f32, y:30f32, w:200f32, h:200f32};
use NkPanelFlags::*;
let flags = NK_WINDOW_MOVABLE as u32
| NK_WINDOW_SCALABLE as u32
| NK_WINDOW_CLOSABLE as u32
| NK_WINDOW_MINIMIZABLE as u32
| NK_WINDOW_TITLE as u32;
if nk.begin(title, rect, flags) {
use NkTextAlignment::*;
nk.menubar_begin();
nk.layout_row_begin(NkLayoutFormat::NK_STATIC, 25f32, 2);
nk.layout_row_push(45f32);
if nk.menu_begin_label(NkString::from("FILE"), NK_TEXT_LEFT as u32, NkVec2 { x:120f32, y:200f32 }) {
nk.layout_row_dynamic(30f32, 1);
nk.menu_item_label(NkString::from("OPEN"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("CLOSE"), NK_TEXT_LEFT as u32);
nk.menu_end();
}
nk.layout_row_push(45f32);
if nk.menu_begin_label(NkString::from("EDIT"), NK_TEXT_LEFT as u32, NkVec2 { x:120f32, y:200f32 }) {
nk.layout_row_dynamic(30f32, 1);
nk.menu_item_label(NkString::from("CUT"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("COPY"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("CLOSE"), NK_TEXT_LEFT as u32);
nk.menu_end();
}
nk.layout_row_end();
nk.menubar_end();
nk.layout_row_static(30f32, 80, 1);
if nk.button_label(NkString::from("button")) {
println!("Button pressed!");
}
use Difficulty::*;
nk.layout_row_dynamic(30f32, 2);
if nk.option_label(NkString::from("Easy"), self.op == Easy) {
self.op = Easy;
}
if nk.option_label(NkString::from("Hard"), self.op == Hard) {
self.op = Hard;
}
nk.layout_row_dynamic(25f32, 1);
nk.property_int(NkString::from("Compression:"), 0, &mut self.property, 100, 10, 1f32);
}
nk.end();
}
fn render_gui(&mut self) {
let nk = &mut self.nk;
const MAX_CMDS_BUFFER: usize = MAX_VERTEX_BUFFER;
let mut cmd_mem = [0u8; MAX_CMDS_BUFFER];
let mut cmds = NkBuffer::with_fixed(&mut cmd_mem);
use NkDrawVertexLayoutFormat::*;
use NkDrawVertexLayoutAttribute::*;
let vlayout = NkDrawVertexLayoutElements::new(&[
(NK_VERTEX_POSITION, NK_FORMAT_FLOAT, GuiVertex::OFFSETOF_POSITION as u32),
(NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, GuiVertex::OFFSETOF_UV as u32),
(NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, GuiVertex::OFFSETOF_COLOR as u32),
// è_é
(NK_VERTEX_ATTRIBUTE_COUNT, NK_FORMAT_COUNT, 0),
]);
let mut config = NkConvertConfig::default();
config.set_vertex_layout(&vlayout);
config.set_vertex_size(size_of::<GuiVertex>());
config.set_null(NkDrawNullTexture::default());
config.set_circle_segment_count(22);
config.set_curve_segment_count(22);
config.set_arc_segment_count(22);
config.set_global_alpha(1f32);
config.set_shape_aa(self.aa);
config.set_line_aa(self.aa);
/*
use std::slice::from_raw_parts_mut as frpm;
let mut vmem = [0u8; MAX_VERTEX_BUFFER];
let mut emem = [0u8; MAX_ELEMENT_BUFFER];
let vertices = unsafe { frpm(vmem.as_mut_ptr() as *mut GuiVertex, MAX_VERTEX_BUFFER/size_of::<GuiVertex>()) };
let elements = unsafe { frpm(emem.as_mut_ptr() as *mut u16, MAX_ELEMENT_BUFFER/size_of::<u16>()) };
let mut vbuf = NkBuffer::with_fixed(&mut vmem);
let mut ebuf = NkBuffer::with_fixed(&mut emem);
nk.convert(&mut cmds, &mut ebuf, &mut vbuf, &config);
let mut offset = 0;
for cmd in nk.draw_command_iterator(&cmds) {
let elem_count = cmd.elem_count();
if elem_count <= 0 {
continue;
}
for i in offset..(offset+elem_count) {
let e = elements[i as usize] as usize;
println!("i: {}", e);
let v = vertices[e];
let [x,y] = v.position;
let [r,g,b,a] = v.color;
let (w,h) = self.rdr.window().unwrap().size(); | self.rdr.set_draw_color(sdl2::pixels::Color::RGBA(r,g,b,a));
self.rdr.draw_point(sdl2::rect::Point::new(x,y)).unwrap();
}
offset += elem_count;
}
*/
for cmd in nk.command_iterator() {
println!("cmd: {:?}", cmd);
}
nk.clear();
}
}
fn main() {
std::env::set_var("RUST_BACKTRACE", "1");
let mut app = App::new();
let mut event_pump = app.sdl2.event_pump().unwrap();
'running: loop {
for e in event_pump.poll_iter() {
use AppEventHandling::*;
match app.handle_event(&e) {
Ok(_) => (),
Err(Quit) => break 'running,
Err(Unhandled) => println!("Unhandled event: {:?}", &e),
};
}
use sdl2::pixels::Color::*;
use sdl2::rect::Rect;
app.rdr.set_draw_color(RGB(255, 255, 0));
app.rdr.clear();
app.rdr.set_draw_color(RGB(0, 255, 255));
app.rdr.draw_rect(Rect::new(20, 20, 50, 50)).unwrap();
app.gui();
app.render_gui();
app.rdr.present();
}
} | let x = (w as f32*(x+1f32)/2f32) as i32;
let y = -(h as f32*(y+1f32)/2f32) as i32; | random_line_split |
main.rs | #![feature(associated_consts)]
#![feature(slice_patterns)]
#![feature(const_fn)]
//#![deny(missing_docs)]
//#![deny(warnings)]
extern crate sdl2;
extern crate nuklear_rust as nk;
use nk::*;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Difficulty {
Easy,
Hard
}
#[derive(Debug, Default, Copy, Clone, PartialEq)]
#[repr(C, packed)]
struct GuiVertex {
position: [f32; 2],
uv: [f32; 2],
color: [u8; 4]
}
use std::mem::size_of;
impl GuiVertex {
const OFFSETOF_POSITION: usize = 0;
const OFFSETOF_UV: usize = 8;
const OFFSETOF_COLOR: usize = 16;
}
const MAX_VERTEX_BUFFER: usize = 512 * 1024;
const MAX_ELEMENT_BUFFER: usize = 128 * 1024;
struct App<'a> {
sdl2: sdl2::Sdl,
rdr: sdl2::render::Renderer<'a>,
nk: nk::NkContext,
property: i32,
op: Difficulty,
aa: NkAntiAliasing,
}
enum AppEventHandling {
Quit,
Unhandled,
}
trait IntoNkKey {
fn to_nk_key(&self) -> NkKey;
}
use sdl2::keyboard::Keycode;
use sdl2::keyboard::Keycode::*;
use NkKey::*;
impl IntoNkKey for Keycode {
fn to_nk_key(&self) -> NkKey {
match self {
&Up => NK_KEY_UP,
_ => NK_KEY_NONE,
}
}
}
impl<'a> App<'a> {
fn new() -> Self {
let sdl2 = sdl2::init().expect("Could not initialize SDL2");
let sdl2_video = sdl2.video().expect("Could not initialize video subsystem");
let window = sdl2_video.window("Foo", 800, 600).build().unwrap();
let rdr =
window.renderer().accelerated().present_vsync().build().unwrap();
use std::fs::File;
use std::io::Read;
let mut buf = Vec::<u8>::new();
let mut file = File::open("/home/yoon/.local/share/fonts/basis33.ttf").unwrap();
file.read_to_end(&mut buf).unwrap();
drop(file);
let mut atlas = NkFontAtlas::new(&mut NkAllocator::new_vec());
atlas.begin();
let mut font = atlas.add_font_with_bytes(&buf, 16f32).unwrap();
let _ = atlas.bake(NkFontAtlasFormat::NK_FONT_ATLAS_RGBA32);
atlas.end(NkHandle::from_ptr(std::ptr::null_mut()), None);
let mut nk = NkContext::new(&mut NkAllocator::new_vec(), &font.handle());
nk.style_set_font(&font.handle());
App {
sdl2, rdr, nk, property: 0, op: Difficulty::Easy, aa: NkAntiAliasing::NK_ANTI_ALIASING_OFF
}
}
fn handle_event(&mut self, e: &sdl2::event::Event) -> Result<(), AppEventHandling> {
use sdl2::event::Event;
self.nk.input_begin();
let out = match e {
&Event::MouseMotion { x, y,.. } => {
println!("Mouse at {:?}", (x, y));
Ok(())
},
&Event::KeyDown { keycode,.. } => {
self.nk.input_key(keycode.unwrap().to_nk_key(), true);
println!("Key {:?} is down", keycode);
Ok(())
},
&Event::KeyUp { keycode,.. } => {
self.nk.input_key(keycode.unwrap().to_nk_key(), false);
println!("Key {:?} is up", keycode);
Ok(())
},
&Event::TextInput {..} => Ok(()),
&Event::MouseButtonDown { mouse_btn,.. } => {
println!("Mouse {:?} is down", mouse_btn);
Ok(())
},
&Event::MouseButtonUp { mouse_btn,.. } => | ,
&Event::MouseWheel { direction, y,.. } => {
println!("Mouse scroll: {} ({:?})", y, direction);
Ok(())
},
&Event::Window {..} => Ok(()),
&Event::Quit {..} => Err(AppEventHandling::Quit),
_ => Err(AppEventHandling::Unhandled),
};
self.nk.input_end();
out
}
fn gui(&mut self) {
let nk = &mut self.nk;
let title = NkString::from("Foo");
let rect = NkRect {x:20f32, y:30f32, w:200f32, h:200f32};
use NkPanelFlags::*;
let flags = NK_WINDOW_MOVABLE as u32
| NK_WINDOW_SCALABLE as u32
| NK_WINDOW_CLOSABLE as u32
| NK_WINDOW_MINIMIZABLE as u32
| NK_WINDOW_TITLE as u32;
if nk.begin(title, rect, flags) {
use NkTextAlignment::*;
nk.menubar_begin();
nk.layout_row_begin(NkLayoutFormat::NK_STATIC, 25f32, 2);
nk.layout_row_push(45f32);
if nk.menu_begin_label(NkString::from("FILE"), NK_TEXT_LEFT as u32, NkVec2 { x:120f32, y:200f32 }) {
nk.layout_row_dynamic(30f32, 1);
nk.menu_item_label(NkString::from("OPEN"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("CLOSE"), NK_TEXT_LEFT as u32);
nk.menu_end();
}
nk.layout_row_push(45f32);
if nk.menu_begin_label(NkString::from("EDIT"), NK_TEXT_LEFT as u32, NkVec2 { x:120f32, y:200f32 }) {
nk.layout_row_dynamic(30f32, 1);
nk.menu_item_label(NkString::from("CUT"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("COPY"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("CLOSE"), NK_TEXT_LEFT as u32);
nk.menu_end();
}
nk.layout_row_end();
nk.menubar_end();
nk.layout_row_static(30f32, 80, 1);
if nk.button_label(NkString::from("button")) {
println!("Button pressed!");
}
use Difficulty::*;
nk.layout_row_dynamic(30f32, 2);
if nk.option_label(NkString::from("Easy"), self.op == Easy) {
self.op = Easy;
}
if nk.option_label(NkString::from("Hard"), self.op == Hard) {
self.op = Hard;
}
nk.layout_row_dynamic(25f32, 1);
nk.property_int(NkString::from("Compression:"), 0, &mut self.property, 100, 10, 1f32);
}
nk.end();
}
fn render_gui(&mut self) {
let nk = &mut self.nk;
const MAX_CMDS_BUFFER: usize = MAX_VERTEX_BUFFER;
let mut cmd_mem = [0u8; MAX_CMDS_BUFFER];
let mut cmds = NkBuffer::with_fixed(&mut cmd_mem);
use NkDrawVertexLayoutFormat::*;
use NkDrawVertexLayoutAttribute::*;
let vlayout = NkDrawVertexLayoutElements::new(&[
(NK_VERTEX_POSITION, NK_FORMAT_FLOAT, GuiVertex::OFFSETOF_POSITION as u32),
(NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, GuiVertex::OFFSETOF_UV as u32),
(NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, GuiVertex::OFFSETOF_COLOR as u32),
// è_é
(NK_VERTEX_ATTRIBUTE_COUNT, NK_FORMAT_COUNT, 0),
]);
let mut config = NkConvertConfig::default();
config.set_vertex_layout(&vlayout);
config.set_vertex_size(size_of::<GuiVertex>());
config.set_null(NkDrawNullTexture::default());
config.set_circle_segment_count(22);
config.set_curve_segment_count(22);
config.set_arc_segment_count(22);
config.set_global_alpha(1f32);
config.set_shape_aa(self.aa);
config.set_line_aa(self.aa);
/*
use std::slice::from_raw_parts_mut as frpm;
let mut vmem = [0u8; MAX_VERTEX_BUFFER];
let mut emem = [0u8; MAX_ELEMENT_BUFFER];
let vertices = unsafe { frpm(vmem.as_mut_ptr() as *mut GuiVertex, MAX_VERTEX_BUFFER/size_of::<GuiVertex>()) };
let elements = unsafe { frpm(emem.as_mut_ptr() as *mut u16, MAX_ELEMENT_BUFFER/size_of::<u16>()) };
let mut vbuf = NkBuffer::with_fixed(&mut vmem);
let mut ebuf = NkBuffer::with_fixed(&mut emem);
nk.convert(&mut cmds, &mut ebuf, &mut vbuf, &config);
let mut offset = 0;
for cmd in nk.draw_command_iterator(&cmds) {
let elem_count = cmd.elem_count();
if elem_count <= 0 {
continue;
}
for i in offset..(offset+elem_count) {
let e = elements[i as usize] as usize;
println!("i: {}", e);
let v = vertices[e];
let [x,y] = v.position;
let [r,g,b,a] = v.color;
let (w,h) = self.rdr.window().unwrap().size();
let x = (w as f32*(x+1f32)/2f32) as i32;
let y = -(h as f32*(y+1f32)/2f32) as i32;
self.rdr.set_draw_color(sdl2::pixels::Color::RGBA(r,g,b,a));
self.rdr.draw_point(sdl2::rect::Point::new(x,y)).unwrap();
}
offset += elem_count;
}
*/
for cmd in nk.command_iterator() {
println!("cmd: {:?}", cmd);
}
nk.clear();
}
}
fn main() {
std::env::set_var("RUST_BACKTRACE", "1");
let mut app = App::new();
let mut event_pump = app.sdl2.event_pump().unwrap();
'running: loop {
for e in event_pump.poll_iter() {
use AppEventHandling::*;
match app.handle_event(&e) {
Ok(_) => (),
Err(Quit) => break 'running,
Err(Unhandled) => println!("Unhandled event: {:?}", &e),
};
}
use sdl2::pixels::Color::*;
use sdl2::rect::Rect;
app.rdr.set_draw_color(RGB(255, 255, 0));
app.rdr.clear();
app.rdr.set_draw_color(RGB(0, 255, 255));
app.rdr.draw_rect(Rect::new(20, 20, 50, 50)).unwrap();
app.gui();
app.render_gui();
app.rdr.present();
}
}
| {
println!("Mouse {:?} is up", mouse_btn);
Ok(())
} | conditional_block |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn new() -> App {
App {
id: 0,
layout: Layout::fill(),
}
}
}
impl Widget for App {
fn layout(&self) -> Option<&Layout> { | fn layout_mut(&mut self) -> Option<&mut Layout> {
Some(&mut self.layout)
}
fn reduce(&mut self, id: NodeId, action: &Box<Any>, scene: &mut Scene) {
if let Some(payload) = action.downcast_ref::<WidgetAdded>() {
if payload.0!= id {
return;
}
scene.add_child(
id,
Panel::new(Layout {
left: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
right: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
height: Some(15),
left: Some(15),
right: Some(15),
valign: Align::Center,
..Default::default()
}),
);
}
}
}
fn main() {
let mut term = Terminal::new();
let mut scene = Scene::empty();
scene.add(App::new());
term.set_scene(scene);
while term.running() {
term.poll();
term.draw();
thread::sleep(Duration::from_millis(1000 / 30));
}
} | Some(&self.layout)
}
| random_line_split |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn | () -> App {
App {
id: 0,
layout: Layout::fill(),
}
}
}
impl Widget for App {
fn layout(&self) -> Option<&Layout> {
Some(&self.layout)
}
fn layout_mut(&mut self) -> Option<&mut Layout> {
Some(&mut self.layout)
}
fn reduce(&mut self, id: NodeId, action: &Box<Any>, scene: &mut Scene) {
if let Some(payload) = action.downcast_ref::<WidgetAdded>() {
if payload.0!= id {
return;
}
scene.add_child(
id,
Panel::new(Layout {
left: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
right: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
height: Some(15),
left: Some(15),
right: Some(15),
valign: Align::Center,
..Default::default()
}),
);
}
}
}
fn main() {
let mut term = Terminal::new();
let mut scene = Scene::empty();
scene.add(App::new());
term.set_scene(scene);
while term.running() {
term.poll();
term.draw();
thread::sleep(Duration::from_millis(1000 / 30));
}
}
| new | identifier_name |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn new() -> App {
App {
id: 0,
layout: Layout::fill(),
}
}
}
impl Widget for App {
fn layout(&self) -> Option<&Layout> {
Some(&self.layout)
}
fn layout_mut(&mut self) -> Option<&mut Layout> {
Some(&mut self.layout)
}
fn reduce(&mut self, id: NodeId, action: &Box<Any>, scene: &mut Scene) {
if let Some(payload) = action.downcast_ref::<WidgetAdded>() | right: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
height: Some(15),
left: Some(15),
right: Some(15),
valign: Align::Center,
..Default::default()
}),
);
}
}
}
fn main() {
let mut term = Terminal::new();
let mut scene = Scene::empty();
scene.add(App::new());
term.set_scene(scene);
while term.running() {
term.poll();
term.draw();
thread::sleep(Duration::from_millis(1000 / 30));
}
}
| {
if payload.0 != id {
return;
}
scene.add_child(
id,
Panel::new(Layout {
left: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout { | conditional_block |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn new() -> App {
App {
id: 0,
layout: Layout::fill(),
}
}
}
impl Widget for App {
fn layout(&self) -> Option<&Layout> {
Some(&self.layout)
}
fn layout_mut(&mut self) -> Option<&mut Layout> {
Some(&mut self.layout)
}
fn reduce(&mut self, id: NodeId, action: &Box<Any>, scene: &mut Scene) | Panel::new(Layout {
right: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
height: Some(15),
left: Some(15),
right: Some(15),
valign: Align::Center,
..Default::default()
}),
);
}
}
}
fn main() {
let mut term = Terminal::new();
let mut scene = Scene::empty();
scene.add(App::new());
term.set_scene(scene);
while term.running() {
term.poll();
term.draw();
thread::sleep(Duration::from_millis(1000 / 30));
}
}
| {
if let Some(payload) = action.downcast_ref::<WidgetAdded>() {
if payload.0 != id {
return;
}
scene.add_child(
id,
Panel::new(Layout {
left: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id, | identifier_body |
gdk_x11.rs | //! Glue code between gdk and x11, allowing some `gdk_x11_*` functions.
//!
//! This is not a complete binding, but just provides what we need in a
//! reasonable way.
use gdk;
use gdk_sys::GdkDisplay;
use glib::translate::*;
use x11::xlib::{Display, Window};
// https://developer.gnome.org/gdk3/stable/gdk3-X-Window-System-Interaction.html
mod ffi {
use gdk_sys::{GdkDisplay, GdkWindow};
use x11::xlib::{Display, Window};
extern "C" {
pub fn gdk_x11_get_default_xdisplay() -> *mut Display;
pub fn gdk_x11_get_default_root_xwindow() -> Window;
pub fn gdk_x11_window_foreign_new_for_display(
display: *mut GdkDisplay,
window: Window,
) -> *mut GdkWindow;
}
}
/// Gets the default GTK+ display.
///
/// # Returns
///
/// the Xlib Display* for the display specified in the `--display`
/// command line option or the `DISPLAY` environment variable.
pub fn gdk_x11_get_default_xdisplay() -> *mut Display {
unsafe {
return ffi::gdk_x11_get_default_xdisplay();
}
}
/// Gets the root window of the default screen (see `gdk_x11_get_default_screen()`).
///
/// # Returns
///
/// an Xlib Window.
pub fn gdk_x11_get_default_root_xwindow() -> Window |
/// Wraps a native window in a GdkWindow. The function will try to look up the
/// window using `gdk_x11_window_lookup_for_display()` first. If it does not find
/// it there, it will create a new window.
///
/// This may fail if the window has been destroyed. If the window was already
/// known to GDK, a new reference to the existing GdkWindow is returned.
/// ## `display`
/// the GdkDisplay where the window handle comes from.
/// ## ` window`
/// an Xlib Window
///
/// # Returns
///
/// a GdkWindow wrapper for the native window, or `None` if the window has been
/// destroyed. The wrapper will be newly created, if one doesn’t exist already.
pub fn gdk_x11_window_foreign_new_for_display(
gdk_display: &mut gdk::Display,
xwindow: Window,
) -> Option<gdk::Window> {
unsafe {
let display: *mut GdkDisplay =
mut_override(gdk_display.to_glib_none().0);
return from_glib_full(ffi::gdk_x11_window_foreign_new_for_display(
display,
xwindow,
));
}
}
| {
unsafe {
return ffi::gdk_x11_get_default_root_xwindow();
}
} | identifier_body |
gdk_x11.rs | //! Glue code between gdk and x11, allowing some `gdk_x11_*` functions.
//!
//! This is not a complete binding, but just provides what we need in a
//! reasonable way.
use gdk;
use gdk_sys::GdkDisplay;
use glib::translate::*;
use x11::xlib::{Display, Window};
// https://developer.gnome.org/gdk3/stable/gdk3-X-Window-System-Interaction.html
mod ffi {
use gdk_sys::{GdkDisplay, GdkWindow};
use x11::xlib::{Display, Window};
extern "C" {
pub fn gdk_x11_get_default_xdisplay() -> *mut Display;
pub fn gdk_x11_get_default_root_xwindow() -> Window;
pub fn gdk_x11_window_foreign_new_for_display(
display: *mut GdkDisplay,
window: Window,
) -> *mut GdkWindow;
}
}
/// Gets the default GTK+ display.
///
/// # Returns
///
/// the Xlib Display* for the display specified in the `--display`
/// command line option or the `DISPLAY` environment variable.
pub fn gdk_x11_get_default_xdisplay() -> *mut Display {
unsafe {
return ffi::gdk_x11_get_default_xdisplay();
}
}
/// Gets the root window of the default screen (see `gdk_x11_get_default_screen()`).
///
/// # Returns
///
/// an Xlib Window.
pub fn gdk_x11_get_default_root_xwindow() -> Window {
unsafe {
return ffi::gdk_x11_get_default_root_xwindow();
}
}
/// Wraps a native window in a GdkWindow. The function will try to look up the
/// window using `gdk_x11_window_lookup_for_display()` first. If it does not find
/// it there, it will create a new window.
///
/// This may fail if the window has been destroyed. If the window was already
/// known to GDK, a new reference to the existing GdkWindow is returned.
/// ## `display`
/// the GdkDisplay where the window handle comes from.
/// ## ` window`
/// an Xlib Window
///
/// # Returns
///
/// a GdkWindow wrapper for the native window, or `None` if the window has been
/// destroyed. The wrapper will be newly created, if one doesn’t exist already.
pub fn gd | gdk_display: &mut gdk::Display,
xwindow: Window,
) -> Option<gdk::Window> {
unsafe {
let display: *mut GdkDisplay =
mut_override(gdk_display.to_glib_none().0);
return from_glib_full(ffi::gdk_x11_window_foreign_new_for_display(
display,
xwindow,
));
}
}
| k_x11_window_foreign_new_for_display(
| identifier_name |
gdk_x11.rs | //! Glue code between gdk and x11, allowing some `gdk_x11_*` functions.
//!
//! This is not a complete binding, but just provides what we need in a
//! reasonable way.
use gdk;
use gdk_sys::GdkDisplay;
use glib::translate::*;
use x11::xlib::{Display, Window};
// https://developer.gnome.org/gdk3/stable/gdk3-X-Window-System-Interaction.html
mod ffi {
use gdk_sys::{GdkDisplay, GdkWindow};
use x11::xlib::{Display, Window};
extern "C" {
pub fn gdk_x11_get_default_xdisplay() -> *mut Display;
pub fn gdk_x11_get_default_root_xwindow() -> Window;
pub fn gdk_x11_window_foreign_new_for_display(
display: *mut GdkDisplay,
window: Window,
) -> *mut GdkWindow;
}
} |
/// Gets the default GTK+ display.
///
/// # Returns
///
/// the Xlib Display* for the display specified in the `--display`
/// command line option or the `DISPLAY` environment variable.
pub fn gdk_x11_get_default_xdisplay() -> *mut Display {
unsafe {
return ffi::gdk_x11_get_default_xdisplay();
}
}
/// Gets the root window of the default screen (see `gdk_x11_get_default_screen()`).
///
/// # Returns
///
/// an Xlib Window.
pub fn gdk_x11_get_default_root_xwindow() -> Window {
unsafe {
return ffi::gdk_x11_get_default_root_xwindow();
}
}
/// Wraps a native window in a GdkWindow. The function will try to look up the
/// window using `gdk_x11_window_lookup_for_display()` first. If it does not find
/// it there, it will create a new window.
///
/// This may fail if the window has been destroyed. If the window was already
/// known to GDK, a new reference to the existing GdkWindow is returned.
/// ## `display`
/// the GdkDisplay where the window handle comes from.
/// ## ` window`
/// an Xlib Window
///
/// # Returns
///
/// a GdkWindow wrapper for the native window, or `None` if the window has been
/// destroyed. The wrapper will be newly created, if one doesn’t exist already.
pub fn gdk_x11_window_foreign_new_for_display(
gdk_display: &mut gdk::Display,
xwindow: Window,
) -> Option<gdk::Window> {
unsafe {
let display: *mut GdkDisplay =
mut_override(gdk_display.to_glib_none().0);
return from_glib_full(ffi::gdk_x11_window_foreign_new_for_display(
display,
xwindow,
));
}
} | random_line_split |
|
access.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.
/// An exclusive access primitive
///
/// This primitive is used to gain exclusive access to read() and write() in uv.
/// It is assumed that all invocations of this struct happen on the same thread
/// (the uv event loop).
use std::cell::UnsafeCell;
use std::mem;
use std::rt::local::Local;
use std::rt::task::{BlockedTask, Task};
use std::sync::Arc;
use homing::HomingMissile;
pub struct Access<T> {
inner: Arc<UnsafeCell<Inner<T>>>,
}
pub struct Guard<'a, T: 'a> {
access: &'a mut Access<T>,
missile: Option<HomingMissile>,
}
struct Inner<T> {
queue: Vec<(BlockedTask, uint)>,
held: bool,
closed: bool,
data: T,
}
impl<T: Send> Access<T> {
pub fn new(data: T) -> Access<T> {
Access {
inner: Arc::new(UnsafeCell::new(Inner {
queue: vec![],
held: false,
closed: false,
data: data,
}))
}
}
pub fn grant<'a>(&'a mut self, token: uint,
missile: HomingMissile) -> Guard<'a, T> {
// This unsafety is actually OK because the homing missile argument
// guarantees that we're on the same event loop as all the other objects
// attempting to get access granted.
let inner = unsafe { &mut *self.inner.get() };
if inner.held {
let t: Box<Task> = Local::take();
t.deschedule(1, |task| {
inner.queue.push((task, token));
Ok(())
});
assert!(inner.held);
} else {
inner.held = true;
}
Guard { access: self, missile: Some(missile) }
}
pub fn unsafe_get(&self) -> *mut T {
unsafe { &mut (*self.inner.get()).data as *mut _ }
}
// Safe version which requires proof that you are on the home scheduler.
pub fn get_mut<'a>(&'a mut self, _missile: &HomingMissile) -> &'a mut T {
unsafe { &mut *self.unsafe_get() }
}
pub fn close(&self, _missile: &HomingMissile) {
// This unsafety is OK because with a homing missile we're guaranteed to
// be the only task looking at the `closed` flag (and are therefore
// allowed to modify it). Additionally, no atomics are necessary because
// everyone's running on the same thread and has already done the
// necessary synchronization to be running on this thread.
unsafe { (*self.inner.get()).closed = true; }
}
// Dequeue a blocked task with a specified token. This is unsafe because it
// is only safe to invoke while on the home event loop, and there is no
// guarantee that this i being invoked on the home event loop.
pub unsafe fn dequeue(&mut self, token: uint) -> Option<BlockedTask> {
let inner = &mut *self.inner.get();
match inner.queue.iter().position(|&(_, t)| t == token) {
Some(i) => Some(inner.queue.remove(i).unwrap().val0()),
None => None,
}
}
/// Test whether this access is closed, using a homing missile to prove
/// that it's safe
pub fn is_closed(&self, _missile: &HomingMissile) -> bool {
unsafe { (*self.inner.get()).closed }
}
}
impl<T: Send> Clone for Access<T> {
fn clone(&self) -> Access<T> {
Access { inner: self.inner.clone() }
}
}
impl<'a, T: Send> Guard<'a, T> {
pub fn | (&self) -> bool {
// See above for why this unsafety is ok, it just applies to the read
// instead of the write.
unsafe { (*self.access.inner.get()).closed }
}
}
impl<'a, T: Send> Deref<T> for Guard<'a, T> {
fn deref<'a>(&'a self) -> &'a T {
// A guard represents exclusive access to a piece of data, so it's safe
// to hand out shared and mutable references
unsafe { &(*self.access.inner.get()).data }
}
}
impl<'a, T: Send> DerefMut<T> for Guard<'a, T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut (*self.access.inner.get()).data }
}
}
#[unsafe_destructor]
impl<'a, T: Send> Drop for Guard<'a, T> {
fn drop(&mut self) {
// This guard's homing missile is still armed, so we're guaranteed to be
// on the same I/O event loop, so this unsafety should be ok.
assert!(self.missile.is_some());
let inner: &mut Inner<T> = unsafe {
mem::transmute(self.access.inner.get())
};
match inner.queue.remove(0) {
// Here we have found a task that was waiting for access, and we
// current have the "access lock" we need to relinquish access to
// this sleeping task.
//
// To do so, we first drop out homing missile and we then reawaken
// the task. In reawakening the task, it will be immediately
// scheduled on this scheduler. Because we might be woken up on some
// other scheduler, we drop our homing missile before we reawaken
// the task.
Some((task, _)) => {
drop(self.missile.take());
task.reawaken();
}
None => { inner.held = false; }
}
}
}
#[unsafe_destructor]
impl<T> Drop for Inner<T> {
fn drop(&mut self) {
assert!(!self.held);
assert_eq!(self.queue.len(), 0);
}
}
| is_closed | identifier_name |
access.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.
/// An exclusive access primitive
///
/// This primitive is used to gain exclusive access to read() and write() in uv.
/// It is assumed that all invocations of this struct happen on the same thread | use std::cell::UnsafeCell;
use std::mem;
use std::rt::local::Local;
use std::rt::task::{BlockedTask, Task};
use std::sync::Arc;
use homing::HomingMissile;
pub struct Access<T> {
inner: Arc<UnsafeCell<Inner<T>>>,
}
pub struct Guard<'a, T: 'a> {
access: &'a mut Access<T>,
missile: Option<HomingMissile>,
}
struct Inner<T> {
queue: Vec<(BlockedTask, uint)>,
held: bool,
closed: bool,
data: T,
}
impl<T: Send> Access<T> {
pub fn new(data: T) -> Access<T> {
Access {
inner: Arc::new(UnsafeCell::new(Inner {
queue: vec![],
held: false,
closed: false,
data: data,
}))
}
}
pub fn grant<'a>(&'a mut self, token: uint,
missile: HomingMissile) -> Guard<'a, T> {
// This unsafety is actually OK because the homing missile argument
// guarantees that we're on the same event loop as all the other objects
// attempting to get access granted.
let inner = unsafe { &mut *self.inner.get() };
if inner.held {
let t: Box<Task> = Local::take();
t.deschedule(1, |task| {
inner.queue.push((task, token));
Ok(())
});
assert!(inner.held);
} else {
inner.held = true;
}
Guard { access: self, missile: Some(missile) }
}
pub fn unsafe_get(&self) -> *mut T {
unsafe { &mut (*self.inner.get()).data as *mut _ }
}
// Safe version which requires proof that you are on the home scheduler.
pub fn get_mut<'a>(&'a mut self, _missile: &HomingMissile) -> &'a mut T {
unsafe { &mut *self.unsafe_get() }
}
pub fn close(&self, _missile: &HomingMissile) {
// This unsafety is OK because with a homing missile we're guaranteed to
// be the only task looking at the `closed` flag (and are therefore
// allowed to modify it). Additionally, no atomics are necessary because
// everyone's running on the same thread and has already done the
// necessary synchronization to be running on this thread.
unsafe { (*self.inner.get()).closed = true; }
}
// Dequeue a blocked task with a specified token. This is unsafe because it
// is only safe to invoke while on the home event loop, and there is no
// guarantee that this i being invoked on the home event loop.
pub unsafe fn dequeue(&mut self, token: uint) -> Option<BlockedTask> {
let inner = &mut *self.inner.get();
match inner.queue.iter().position(|&(_, t)| t == token) {
Some(i) => Some(inner.queue.remove(i).unwrap().val0()),
None => None,
}
}
/// Test whether this access is closed, using a homing missile to prove
/// that it's safe
pub fn is_closed(&self, _missile: &HomingMissile) -> bool {
unsafe { (*self.inner.get()).closed }
}
}
impl<T: Send> Clone for Access<T> {
fn clone(&self) -> Access<T> {
Access { inner: self.inner.clone() }
}
}
impl<'a, T: Send> Guard<'a, T> {
pub fn is_closed(&self) -> bool {
// See above for why this unsafety is ok, it just applies to the read
// instead of the write.
unsafe { (*self.access.inner.get()).closed }
}
}
impl<'a, T: Send> Deref<T> for Guard<'a, T> {
fn deref<'a>(&'a self) -> &'a T {
// A guard represents exclusive access to a piece of data, so it's safe
// to hand out shared and mutable references
unsafe { &(*self.access.inner.get()).data }
}
}
impl<'a, T: Send> DerefMut<T> for Guard<'a, T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut (*self.access.inner.get()).data }
}
}
#[unsafe_destructor]
impl<'a, T: Send> Drop for Guard<'a, T> {
fn drop(&mut self) {
// This guard's homing missile is still armed, so we're guaranteed to be
// on the same I/O event loop, so this unsafety should be ok.
assert!(self.missile.is_some());
let inner: &mut Inner<T> = unsafe {
mem::transmute(self.access.inner.get())
};
match inner.queue.remove(0) {
// Here we have found a task that was waiting for access, and we
// current have the "access lock" we need to relinquish access to
// this sleeping task.
//
// To do so, we first drop out homing missile and we then reawaken
// the task. In reawakening the task, it will be immediately
// scheduled on this scheduler. Because we might be woken up on some
// other scheduler, we drop our homing missile before we reawaken
// the task.
Some((task, _)) => {
drop(self.missile.take());
task.reawaken();
}
None => { inner.held = false; }
}
}
}
#[unsafe_destructor]
impl<T> Drop for Inner<T> {
fn drop(&mut self) {
assert!(!self.held);
assert_eq!(self.queue.len(), 0);
}
} | /// (the uv event loop).
| random_line_split |
overloaded-index-autoderef.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test overloaded indexing combined with autoderef.
#![allow(unknown_features)]
#![feature(box_syntax)]
use std::ops::{Index, IndexMut};
struct Foo {
x: int,
y: int,
}
impl Index<int> for Foo {
type Output = int;
fn index(&self, z: &int) -> &int {
if *z == 0 {
&self.x
} else {
&self.y
} |
impl IndexMut<int> for Foo {
fn index_mut(&mut self, z: &int) -> &mut int {
if *z == 0 {
&mut self.x
} else {
&mut self.y
}
}
}
trait Int {
fn get(self) -> int;
fn get_from_ref(&self) -> int;
fn inc(&mut self);
}
impl Int for int {
fn get(self) -> int { self }
fn get_from_ref(&self) -> int { *self }
fn inc(&mut self) { *self += 1; }
}
fn main() {
let mut f: Box<_> = box Foo {
x: 1,
y: 2,
};
assert_eq!(f[1], 2);
f[0] = 3;
assert_eq!(f[0], 3);
// Test explicit IndexMut where `f` must be autoderef:
{
let p = &mut f[1];
*p = 4;
}
// Test explicit Index where `f` must be autoderef:
{
let p = &f[1];
assert_eq!(*p, 4);
}
// Test calling methods with `&mut self`, `self, and `&self` receivers:
f[1].inc();
assert_eq!(f[1].get(), 5);
assert_eq!(f[1].get_from_ref(), 5);
} | }
} | random_line_split |
overloaded-index-autoderef.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test overloaded indexing combined with autoderef.
#![allow(unknown_features)]
#![feature(box_syntax)]
use std::ops::{Index, IndexMut};
struct Foo {
x: int,
y: int,
}
impl Index<int> for Foo {
type Output = int;
fn index(&self, z: &int) -> &int {
if *z == 0 | else {
&self.y
}
}
}
impl IndexMut<int> for Foo {
fn index_mut(&mut self, z: &int) -> &mut int {
if *z == 0 {
&mut self.x
} else {
&mut self.y
}
}
}
trait Int {
fn get(self) -> int;
fn get_from_ref(&self) -> int;
fn inc(&mut self);
}
impl Int for int {
fn get(self) -> int { self }
fn get_from_ref(&self) -> int { *self }
fn inc(&mut self) { *self += 1; }
}
fn main() {
let mut f: Box<_> = box Foo {
x: 1,
y: 2,
};
assert_eq!(f[1], 2);
f[0] = 3;
assert_eq!(f[0], 3);
// Test explicit IndexMut where `f` must be autoderef:
{
let p = &mut f[1];
*p = 4;
}
// Test explicit Index where `f` must be autoderef:
{
let p = &f[1];
assert_eq!(*p, 4);
}
// Test calling methods with `&mut self`, `self, and `&self` receivers:
f[1].inc();
assert_eq!(f[1].get(), 5);
assert_eq!(f[1].get_from_ref(), 5);
}
| {
&self.x
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.