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
polygon.rs
//! Draw polygon use types::Color; use {types, triangulation, Graphics, DrawState}; use math::{Matrix2d, Scalar}; /// A polygon #[derive(Copy, Clone)] pub struct Polygon { /// The color of the polygon pub color: Color, } impl Polygon { /// Creates new polygon pub fn new(color: Color) -> Polygon { Polygon { color: color } } /// Sets color. pub fn
(mut self, color: Color) -> Self { self.color = color; self } /// Draws polygon using the default method. #[inline(always)] pub fn draw<G>(&self, polygon: types::Polygon, draw_state: &DrawState, transform: Matrix2d, g: &mut G) where G: Graphics { g.polygon(self, polygon, draw_state, transform); } /// Draws polygon using triangulation. pub fn draw_tri<G>(&self, polygon: types::Polygon, draw_state: &DrawState, transform: Matrix2d, g: &mut G) where G: Graphics { g.tri_list(draw_state, &self.color, |f| { triangulation::with_polygon_tri_list(transform, polygon, |vertices| f(vertices)) }); } /// Draws tweened polygon with linear interpolation, using default method. #[inline(always)] pub fn draw_tween_lerp<G>(&self, polygons: types::Polygons, tween_factor: Scalar, draw_state: &DrawState, transform: Matrix2d, g: &mut G) where G: Graphics { g.polygon_tween_lerp(self, polygons, tween_factor, draw_state, transform); } /// Draws tweened polygon with linear interpolation, using triangulation. pub fn draw_tween_lerp_tri<G>(&self, polygons: types::Polygons, tween_factor: Scalar, draw_state: &DrawState, transform: Matrix2d, g: &mut G) where G: Graphics { if self.color[3] == 0.0 { return; } g.tri_list(draw_state, &self.color, |f| { triangulation::with_lerp_polygons_tri_list(transform, polygons, tween_factor, |vertices| f(vertices)) }); } } #[cfg(test)] mod test { use super::*; #[test] fn test_polygon() { let _polygon = Polygon::new([1.0; 4]).color([0.0; 4]); } }
color
identifier_name
polygon.rs
//! Draw polygon use types::Color; use {types, triangulation, Graphics, DrawState}; use math::{Matrix2d, Scalar}; /// A polygon #[derive(Copy, Clone)] pub struct Polygon { /// The color of the polygon pub color: Color, } impl Polygon { /// Creates new polygon pub fn new(color: Color) -> Polygon { Polygon { color: color } } /// Sets color. pub fn color(mut self, color: Color) -> Self { self.color = color; self } /// Draws polygon using the default method. #[inline(always)] pub fn draw<G>(&self, polygon: types::Polygon, draw_state: &DrawState, transform: Matrix2d, g: &mut G) where G: Graphics { g.polygon(self, polygon, draw_state, transform); } /// Draws polygon using triangulation. pub fn draw_tri<G>(&self, polygon: types::Polygon, draw_state: &DrawState, transform: Matrix2d, g: &mut G) where G: Graphics { g.tri_list(draw_state, &self.color, |f| { triangulation::with_polygon_tri_list(transform, polygon, |vertices| f(vertices)) }); } /// Draws tweened polygon with linear interpolation, using default method.
transform: Matrix2d, g: &mut G) where G: Graphics { g.polygon_tween_lerp(self, polygons, tween_factor, draw_state, transform); } /// Draws tweened polygon with linear interpolation, using triangulation. pub fn draw_tween_lerp_tri<G>(&self, polygons: types::Polygons, tween_factor: Scalar, draw_state: &DrawState, transform: Matrix2d, g: &mut G) where G: Graphics { if self.color[3] == 0.0 { return; } g.tri_list(draw_state, &self.color, |f| { triangulation::with_lerp_polygons_tri_list(transform, polygons, tween_factor, |vertices| f(vertices)) }); } } #[cfg(test)] mod test { use super::*; #[test] fn test_polygon() { let _polygon = Polygon::new([1.0; 4]).color([0.0; 4]); } }
#[inline(always)] pub fn draw_tween_lerp<G>(&self, polygons: types::Polygons, tween_factor: Scalar, draw_state: &DrawState,
random_line_split
bench.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use rand::{Rng, task_rng}; use stdtest::Bencher; use std::str; use regex::{Regex, NoExpand}; fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) { b.iter(|| if!re.is_match(text) { fail!("no match") }); } #[bench] fn no_exponential(b: &mut Bencher) { let n = 100; let re = Regex::new("a?".repeat(n) + "a".repeat(n)).unwrap(); let text = "a".repeat(n); bench_assert_match(b, re, text); } #[bench] fn literal(b: &mut Bencher) { let re = regex!("y"); let text = "x".repeat(50) + "y"; bench_assert_match(b, re, text); } #[bench] fn not_literal(b: &mut Bencher) { let re = regex!(".y"); let text = "x".repeat(50) + "y"; bench_assert_match(b, re, text); } #[bench] fn match_class(b: &mut Bencher) { let re = regex!("[abcdw]"); let text = "xxxx".repeat(20) + "w"; bench_assert_match(b, re, text); } #[bench] fn match_class_in_range(b: &mut Bencher) { // 'b' is between 'a' and 'c', so the class range checking doesn't help. let re = regex!("[ac]"); let text = "bbbb".repeat(20) + "c"; bench_assert_match(b, re, text); } #[bench] fn replace_all(b: &mut Bencher) { let re = regex!("[cjrw]"); let text = "abcdefghijklmnopqrstuvwxyz"; // FIXME: This isn't using the $name expand stuff. // It's possible RE2/Go is using it, but currently, the expand in this // crate is actually compiling a regex, so it's incredibly slow. b.iter(|| re.replace_all(text, NoExpand(""))); } #[bench] fn anchored_literal_short_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_short_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_a(b: &mut Bencher) { let re = regex!("^.bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_a_not(b: &mut Bencher) { let re = regex!(".bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_b(b: &mut Bencher) { let re = regex!("^.bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_b_not(b: &mut Bencher) { let re = regex!(".bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix(b: &mut Bencher) { let re = regex!("^abcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix_not(b: &mut Bencher) { let re = regex!("^.bcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } macro_rules! throughput( ($name:ident, $regex:expr, $size:expr) => ( #[bench] fn $name(b: &mut Bencher) { let text = gen_text($size); b.bytes = $size; b.iter(|| if $regex.is_match(text.as_slice()) { fail!("match") }); } ); ) fn easy0() -> Regex { regex!("ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn easy1() -> Regex { regex!("A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$") } fn medium() -> Regex { regex!("[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } #[allow(deprecated_owned_vector)] fn gen_text(n: uint) -> StrBuf { let mut rng = task_rng(); let mut bytes = rng.gen_ascii_str(n).into_bytes(); for (i, b) in bytes.mut_iter().enumerate() { if i % 20 == 0
} str::from_utf8(bytes.as_slice()).unwrap().to_strbuf() } throughput!(easy0_32, easy0(), 32) throughput!(easy0_1K, easy0(), 1<<10) throughput!(easy0_32K, easy0(), 32<<10) throughput!(easy1_32, easy1(), 32) throughput!(easy1_1K, easy1(), 1<<10) throughput!(easy1_32K, easy1(), 32<<10) throughput!(medium_32, medium(), 32) throughput!(medium_1K, medium(), 1<<10) throughput!(medium_32K,medium(), 32<<10) throughput!(hard_32, hard(), 32) throughput!(hard_1K, hard(), 1<<10) throughput!(hard_32K,hard(), 32<<10)
{ *b = '\n' as u8 }
conditional_block
bench.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use rand::{Rng, task_rng}; use stdtest::Bencher; use std::str; use regex::{Regex, NoExpand}; fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) { b.iter(|| if!re.is_match(text) { fail!("no match") }); } #[bench] fn no_exponential(b: &mut Bencher) { let n = 100; let re = Regex::new("a?".repeat(n) + "a".repeat(n)).unwrap(); let text = "a".repeat(n); bench_assert_match(b, re, text); } #[bench] fn literal(b: &mut Bencher) { let re = regex!("y"); let text = "x".repeat(50) + "y"; bench_assert_match(b, re, text); } #[bench] fn not_literal(b: &mut Bencher) { let re = regex!(".y"); let text = "x".repeat(50) + "y"; bench_assert_match(b, re, text); } #[bench] fn match_class(b: &mut Bencher) { let re = regex!("[abcdw]"); let text = "xxxx".repeat(20) + "w"; bench_assert_match(b, re, text); } #[bench] fn match_class_in_range(b: &mut Bencher) { // 'b' is between 'a' and 'c', so the class range checking doesn't help. let re = regex!("[ac]"); let text = "bbbb".repeat(20) + "c"; bench_assert_match(b, re, text); } #[bench] fn replace_all(b: &mut Bencher) { let re = regex!("[cjrw]"); let text = "abcdefghijklmnopqrstuvwxyz"; // FIXME: This isn't using the $name expand stuff. // It's possible RE2/Go is using it, but currently, the expand in this // crate is actually compiling a regex, so it's incredibly slow. b.iter(|| re.replace_all(text, NoExpand(""))); } #[bench] fn anchored_literal_short_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_short_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_a(b: &mut Bencher) { let re = regex!("^.bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_a_not(b: &mut Bencher) { let re = regex!(".bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_b(b: &mut Bencher) { let re = regex!("^.bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_b_not(b: &mut Bencher) { let re = regex!(".bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix(b: &mut Bencher) { let re = regex!("^abcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix_not(b: &mut Bencher) { let re = regex!("^.bcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } macro_rules! throughput( ($name:ident, $regex:expr, $size:expr) => ( #[bench] fn $name(b: &mut Bencher) { let text = gen_text($size);
) fn easy0() -> Regex { regex!("ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn easy1() -> Regex { regex!("A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$") } fn medium() -> Regex { regex!("[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } #[allow(deprecated_owned_vector)] fn gen_text(n: uint) -> StrBuf { let mut rng = task_rng(); let mut bytes = rng.gen_ascii_str(n).into_bytes(); for (i, b) in bytes.mut_iter().enumerate() { if i % 20 == 0 { *b = '\n' as u8 } } str::from_utf8(bytes.as_slice()).unwrap().to_strbuf() } throughput!(easy0_32, easy0(), 32) throughput!(easy0_1K, easy0(), 1<<10) throughput!(easy0_32K, easy0(), 32<<10) throughput!(easy1_32, easy1(), 32) throughput!(easy1_1K, easy1(), 1<<10) throughput!(easy1_32K, easy1(), 32<<10) throughput!(medium_32, medium(), 32) throughput!(medium_1K, medium(), 1<<10) throughput!(medium_32K,medium(), 32<<10) throughput!(hard_32, hard(), 32) throughput!(hard_1K, hard(), 1<<10) throughput!(hard_32K,hard(), 32<<10)
b.bytes = $size; b.iter(|| if $regex.is_match(text.as_slice()) { fail!("match") }); } );
random_line_split
bench.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use rand::{Rng, task_rng}; use stdtest::Bencher; use std::str; use regex::{Regex, NoExpand}; fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str)
#[bench] fn no_exponential(b: &mut Bencher) { let n = 100; let re = Regex::new("a?".repeat(n) + "a".repeat(n)).unwrap(); let text = "a".repeat(n); bench_assert_match(b, re, text); } #[bench] fn literal(b: &mut Bencher) { let re = regex!("y"); let text = "x".repeat(50) + "y"; bench_assert_match(b, re, text); } #[bench] fn not_literal(b: &mut Bencher) { let re = regex!(".y"); let text = "x".repeat(50) + "y"; bench_assert_match(b, re, text); } #[bench] fn match_class(b: &mut Bencher) { let re = regex!("[abcdw]"); let text = "xxxx".repeat(20) + "w"; bench_assert_match(b, re, text); } #[bench] fn match_class_in_range(b: &mut Bencher) { // 'b' is between 'a' and 'c', so the class range checking doesn't help. let re = regex!("[ac]"); let text = "bbbb".repeat(20) + "c"; bench_assert_match(b, re, text); } #[bench] fn replace_all(b: &mut Bencher) { let re = regex!("[cjrw]"); let text = "abcdefghijklmnopqrstuvwxyz"; // FIXME: This isn't using the $name expand stuff. // It's possible RE2/Go is using it, but currently, the expand in this // crate is actually compiling a regex, so it's incredibly slow. b.iter(|| re.replace_all(text, NoExpand(""))); } #[bench] fn anchored_literal_short_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_short_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_a(b: &mut Bencher) { let re = regex!("^.bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_a_not(b: &mut Bencher) { let re = regex!(".bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_b(b: &mut Bencher) { let re = regex!("^.bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_b_not(b: &mut Bencher) { let re = regex!(".bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix(b: &mut Bencher) { let re = regex!("^abcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix_not(b: &mut Bencher) { let re = regex!("^.bcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } macro_rules! throughput( ($name:ident, $regex:expr, $size:expr) => ( #[bench] fn $name(b: &mut Bencher) { let text = gen_text($size); b.bytes = $size; b.iter(|| if $regex.is_match(text.as_slice()) { fail!("match") }); } ); ) fn easy0() -> Regex { regex!("ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn easy1() -> Regex { regex!("A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$") } fn medium() -> Regex { regex!("[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } #[allow(deprecated_owned_vector)] fn gen_text(n: uint) -> StrBuf { let mut rng = task_rng(); let mut bytes = rng.gen_ascii_str(n).into_bytes(); for (i, b) in bytes.mut_iter().enumerate() { if i % 20 == 0 { *b = '\n' as u8 } } str::from_utf8(bytes.as_slice()).unwrap().to_strbuf() } throughput!(easy0_32, easy0(), 32) throughput!(easy0_1K, easy0(), 1<<10) throughput!(easy0_32K, easy0(), 32<<10) throughput!(easy1_32, easy1(), 32) throughput!(easy1_1K, easy1(), 1<<10) throughput!(easy1_32K, easy1(), 32<<10) throughput!(medium_32, medium(), 32) throughput!(medium_1K, medium(), 1<<10) throughput!(medium_32K,medium(), 32<<10) throughput!(hard_32, hard(), 32) throughput!(hard_1K, hard(), 1<<10) throughput!(hard_32K,hard(), 32<<10)
{ b.iter(|| if !re.is_match(text) { fail!("no match") }); }
identifier_body
bench.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use rand::{Rng, task_rng}; use stdtest::Bencher; use std::str; use regex::{Regex, NoExpand}; fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) { b.iter(|| if!re.is_match(text) { fail!("no match") }); } #[bench] fn no_exponential(b: &mut Bencher) { let n = 100; let re = Regex::new("a?".repeat(n) + "a".repeat(n)).unwrap(); let text = "a".repeat(n); bench_assert_match(b, re, text); } #[bench] fn
(b: &mut Bencher) { let re = regex!("y"); let text = "x".repeat(50) + "y"; bench_assert_match(b, re, text); } #[bench] fn not_literal(b: &mut Bencher) { let re = regex!(".y"); let text = "x".repeat(50) + "y"; bench_assert_match(b, re, text); } #[bench] fn match_class(b: &mut Bencher) { let re = regex!("[abcdw]"); let text = "xxxx".repeat(20) + "w"; bench_assert_match(b, re, text); } #[bench] fn match_class_in_range(b: &mut Bencher) { // 'b' is between 'a' and 'c', so the class range checking doesn't help. let re = regex!("[ac]"); let text = "bbbb".repeat(20) + "c"; bench_assert_match(b, re, text); } #[bench] fn replace_all(b: &mut Bencher) { let re = regex!("[cjrw]"); let text = "abcdefghijklmnopqrstuvwxyz"; // FIXME: This isn't using the $name expand stuff. // It's possible RE2/Go is using it, but currently, the expand in this // crate is actually compiling a regex, so it's incredibly slow. b.iter(|| re.replace_all(text, NoExpand(""))); } #[bench] fn anchored_literal_short_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_short_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_a(b: &mut Bencher) { let re = regex!("^.bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_a_not(b: &mut Bencher) { let re = regex!(".bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_b(b: &mut Bencher) { let re = regex!("^.bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_b_not(b: &mut Bencher) { let re = regex!(".bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix(b: &mut Bencher) { let re = regex!("^abcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix_not(b: &mut Bencher) { let re = regex!("^.bcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } macro_rules! throughput( ($name:ident, $regex:expr, $size:expr) => ( #[bench] fn $name(b: &mut Bencher) { let text = gen_text($size); b.bytes = $size; b.iter(|| if $regex.is_match(text.as_slice()) { fail!("match") }); } ); ) fn easy0() -> Regex { regex!("ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn easy1() -> Regex { regex!("A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$") } fn medium() -> Regex { regex!("[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } #[allow(deprecated_owned_vector)] fn gen_text(n: uint) -> StrBuf { let mut rng = task_rng(); let mut bytes = rng.gen_ascii_str(n).into_bytes(); for (i, b) in bytes.mut_iter().enumerate() { if i % 20 == 0 { *b = '\n' as u8 } } str::from_utf8(bytes.as_slice()).unwrap().to_strbuf() } throughput!(easy0_32, easy0(), 32) throughput!(easy0_1K, easy0(), 1<<10) throughput!(easy0_32K, easy0(), 32<<10) throughput!(easy1_32, easy1(), 32) throughput!(easy1_1K, easy1(), 1<<10) throughput!(easy1_32K, easy1(), 32<<10) throughput!(medium_32, medium(), 32) throughput!(medium_1K, medium(), 1<<10) throughput!(medium_32K,medium(), 32<<10) throughput!(hard_32, hard(), 32) throughput!(hard_1K, hard(), 1<<10) throughput!(hard_32K,hard(), 32<<10)
literal
identifier_name
client.rs
use abox = sodiumoxide::crypto::asymmetricbox; use capnp; use capnp::message::{MessageReader, MessageBuilder, ReaderOptions}; use capnp::serialize_packed; use std::io; use std::str; use std::time::duration::Duration; use nanomsg::{NanoSocket}; use nanomsg::{AF_SP,NN_PAIR}; use schema::request_capnp; use schema::reply_capnp; pub fn
() { info!("Connecting to {}", ::client_addr); let sock = NanoSocket::new(AF_SP, NN_PAIR).unwrap(); sock.connect(::client_addr).unwrap(); let (pub_key, sec_key) = abox::gen_keypair(); let mut req_i = 0u32; loop { let req_str = format!("Request {}", req_i); debug!("Sending: {}", req_str); let mut message = capnp::message::MallocMessageBuilder::new_default(); { let rep = message.init_root::<request_capnp::Request::Builder>(); rep.set_data(req_str.as_bytes()); rep.set_key({let abox::PublicKey(b) = pub_key; b}); } let mut writer = io::MemWriter::new(); serialize_packed::write_packed_message_unbuffered(&mut writer, &message).unwrap(); sock.send(writer.unwrap().as_slice()).unwrap(); let rep = sock.recv().unwrap(); let mut reader = io::MemReader::new(rep); let reader = serialize_packed::new_reader_unbuffered(&mut reader, ReaderOptions::new()).unwrap(); let rep = reader.get_root::<reply_capnp::Reply::Reader>(); let rep_nonce = abox::Nonce::from_slice_by_ref(rep.get_nonce()).unwrap(); let rep_key = abox::PublicKey::from_slice_by_ref(rep.get_key()).unwrap(); match abox::open(rep.get_data(), rep_nonce, rep_key, &sec_key) { Some(data) => match str::from_utf8(data.as_slice()) { Some(s) => debug!("Received: {}", s), None => debug!("Received: some binary data"), }, None => debug!("Received garbage"), }; req_i += 1; io::timer::sleep(Duration::seconds(10)); } }
client
identifier_name
client.rs
use abox = sodiumoxide::crypto::asymmetricbox; use capnp; use capnp::message::{MessageReader, MessageBuilder, ReaderOptions}; use capnp::serialize_packed; use std::io; use std::str; use std::time::duration::Duration; use nanomsg::{NanoSocket}; use nanomsg::{AF_SP,NN_PAIR}; use schema::request_capnp; use schema::reply_capnp; pub fn client()
} let mut writer = io::MemWriter::new(); serialize_packed::write_packed_message_unbuffered(&mut writer, &message).unwrap(); sock.send(writer.unwrap().as_slice()).unwrap(); let rep = sock.recv().unwrap(); let mut reader = io::MemReader::new(rep); let reader = serialize_packed::new_reader_unbuffered(&mut reader, ReaderOptions::new()).unwrap(); let rep = reader.get_root::<reply_capnp::Reply::Reader>(); let rep_nonce = abox::Nonce::from_slice_by_ref(rep.get_nonce()).unwrap(); let rep_key = abox::PublicKey::from_slice_by_ref(rep.get_key()).unwrap(); match abox::open(rep.get_data(), rep_nonce, rep_key, &sec_key) { Some(data) => match str::from_utf8(data.as_slice()) { Some(s) => debug!("Received: {}", s), None => debug!("Received: some binary data"), }, None => debug!("Received garbage"), }; req_i += 1; io::timer::sleep(Duration::seconds(10)); } }
{ info!("Connecting to {}", ::client_addr); let sock = NanoSocket::new(AF_SP, NN_PAIR).unwrap(); sock.connect(::client_addr).unwrap(); let (pub_key, sec_key) = abox::gen_keypair(); let mut req_i = 0u32; loop { let req_str = format!("Request {}", req_i); debug!("Sending: {}", req_str); let mut message = capnp::message::MallocMessageBuilder::new_default(); { let rep = message.init_root::<request_capnp::Request::Builder>(); rep.set_data(req_str.as_bytes()); rep.set_key({let abox::PublicKey(b) = pub_key; b});
identifier_body
client.rs
use abox = sodiumoxide::crypto::asymmetricbox; use capnp; use capnp::message::{MessageReader, MessageBuilder, ReaderOptions}; use capnp::serialize_packed; use std::io; use std::str; use std::time::duration::Duration; use nanomsg::{NanoSocket}; use nanomsg::{AF_SP,NN_PAIR}; use schema::request_capnp; use schema::reply_capnp; pub fn client() { info!("Connecting to {}", ::client_addr); let sock = NanoSocket::new(AF_SP, NN_PAIR).unwrap(); sock.connect(::client_addr).unwrap(); let (pub_key, sec_key) = abox::gen_keypair(); let mut req_i = 0u32; loop { let req_str = format!("Request {}", req_i); debug!("Sending: {}", req_str); let mut message = capnp::message::MallocMessageBuilder::new_default(); { let rep = message.init_root::<request_capnp::Request::Builder>(); rep.set_data(req_str.as_bytes()); rep.set_key({let abox::PublicKey(b) = pub_key; b}); } let mut writer = io::MemWriter::new(); serialize_packed::write_packed_message_unbuffered(&mut writer, &message).unwrap(); sock.send(writer.unwrap().as_slice()).unwrap();
let rep_nonce = abox::Nonce::from_slice_by_ref(rep.get_nonce()).unwrap(); let rep_key = abox::PublicKey::from_slice_by_ref(rep.get_key()).unwrap(); match abox::open(rep.get_data(), rep_nonce, rep_key, &sec_key) { Some(data) => match str::from_utf8(data.as_slice()) { Some(s) => debug!("Received: {}", s), None => debug!("Received: some binary data"), }, None => debug!("Received garbage"), }; req_i += 1; io::timer::sleep(Duration::seconds(10)); } }
let rep = sock.recv().unwrap(); let mut reader = io::MemReader::new(rep); let reader = serialize_packed::new_reader_unbuffered(&mut reader, ReaderOptions::new()).unwrap(); let rep = reader.get_root::<reply_capnp::Reply::Reader>();
random_line_split
main.rs
extern crate roman_army; use roman_army::ComponentUnit; use roman_army::primitives::{ Archer, Infantryman, Horseman }; use roman_army::composite::CompositeUnit; fn main() { let mut army = CompositeUnit::new(); for _ in 0..4 { let legion = create_legion(); army.add_unit(Box::new(legion)); } { let legions = army.get_units(); println!("Roman army damaging strength is {}", army.get_strength()); println!("Roman army has {} legions\n", legions.len()); } { let legion = army.get_unit(0); println!("Roman legion damaging strength is {}", legion.get_strength()); println!("Roman legion has {} units\n", legion.get_units().len()); } army.remove(0); let legions = army.get_units(); println!("Roman army damaging strength is {}", army.get_strength()); println!("Roman army has {} legions", legions.len()); } fn
() -> CompositeUnit { let mut composite_legion = CompositeUnit::new(); for _ in 0..3000 { composite_legion.add_unit(Box::new(Infantryman)); } for _ in 0..1200 { composite_legion.add_unit(Box::new(Archer)); } for _ in 0..300 { composite_legion.add_unit(Box::new(Horseman)); } composite_legion }
create_legion
identifier_name
main.rs
extern crate roman_army; use roman_army::ComponentUnit; use roman_army::primitives::{ Archer, Infantryman, Horseman }; use roman_army::composite::CompositeUnit; fn main()
army.remove(0); let legions = army.get_units(); println!("Roman army damaging strength is {}", army.get_strength()); println!("Roman army has {} legions", legions.len()); } fn create_legion() -> CompositeUnit { let mut composite_legion = CompositeUnit::new(); for _ in 0..3000 { composite_legion.add_unit(Box::new(Infantryman)); } for _ in 0..1200 { composite_legion.add_unit(Box::new(Archer)); } for _ in 0..300 { composite_legion.add_unit(Box::new(Horseman)); } composite_legion }
{ let mut army = CompositeUnit::new(); for _ in 0..4 { let legion = create_legion(); army.add_unit(Box::new(legion)); } { let legions = army.get_units(); println!("Roman army damaging strength is {}", army.get_strength()); println!("Roman army has {} legions\n", legions.len()); } { let legion = army.get_unit(0); println!("Roman legion damaging strength is {}", legion.get_strength()); println!("Roman legion has {} units\n", legion.get_units().len()); }
identifier_body
main.rs
extern crate roman_army; use roman_army::ComponentUnit; use roman_army::primitives::{ Archer, Infantryman, Horseman }; use roman_army::composite::CompositeUnit; fn main() { let mut army = CompositeUnit::new(); for _ in 0..4 { let legion = create_legion(); army.add_unit(Box::new(legion)); } { let legions = army.get_units(); println!("Roman army damaging strength is {}", army.get_strength()); println!("Roman army has {} legions\n", legions.len()); }
{ let legion = army.get_unit(0); println!("Roman legion damaging strength is {}", legion.get_strength()); println!("Roman legion has {} units\n", legion.get_units().len()); } army.remove(0); let legions = army.get_units(); println!("Roman army damaging strength is {}", army.get_strength()); println!("Roman army has {} legions", legions.len()); } fn create_legion() -> CompositeUnit { let mut composite_legion = CompositeUnit::new(); for _ in 0..3000 { composite_legion.add_unit(Box::new(Infantryman)); } for _ in 0..1200 { composite_legion.add_unit(Box::new(Archer)); } for _ in 0..300 { composite_legion.add_unit(Box::new(Horseman)); } composite_legion }
random_line_split
area.rs
// Copyright (c) 2017-2021 Linaro LTD // Copyright (c) 2018-2019 JUUL Labs // Copyright (c) 2019 Arm Limited // // SPDX-License-Identifier: Apache-2.0 //! Describe flash areas. use simflash::{Flash, SimFlash, Sector}; use std::ptr; use std::collections::HashMap; /// Structure to build up the boot area table. #[derive(Debug, Default, Clone)] pub struct AreaDesc { areas: Vec<Vec<FlashArea>>, whole: Vec<FlashArea>, sectors: HashMap<u8, Vec<Sector>>, } impl AreaDesc { pub fn new() -> AreaDesc { AreaDesc { areas: vec![], whole: vec![], sectors: HashMap::new(), } } pub fn add_flash_sectors(&mut self, id: u8, flash: &SimFlash) { self.sectors.insert(id, flash.sector_iter().collect()); } /// Add a slot to the image. The slot must align with erasable units in the flash device. /// Panics if the description is not valid. There are also bootloader assumptions that the /// slots are PRIMARY_SLOT, SECONDARY_SLOT, and SCRATCH in that order. pub fn add_image(&mut self, base: usize, len: usize, id: FlashId, dev_id: u8) { let nid = id as usize; let orig_base = base; let orig_len = len; let mut base = base; let mut len = len; while nid > self.areas.len() { self.areas.push(vec![]); self.whole.push(Default::default()); } if nid!= self.areas.len()
let mut area = vec![]; for sector in &self.sectors[&dev_id] { if len == 0 { break; }; if base > sector.base + sector.size - 1 { continue; } if sector.base!= base { panic!("Image does not start on a sector boundary"); } area.push(FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: sector.base as u32, size: sector.size as u32, }); base += sector.size; len -= sector.size; } if len!= 0 { panic!("Image goes past end of device"); } self.areas.push(area); self.whole.push(FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: orig_base as u32, size: orig_len as u32, }); } // Add a simple slot to the image. This ignores the device layout, and just adds the area as a // single unit. It assumes that the image lines up with image boundaries. This tests // configurations where the partition table uses larger sectors than the underlying flash // device. pub fn add_simple_image(&mut self, base: usize, len: usize, id: FlashId, dev_id: u8) { let area = vec![FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: base as u32, size: len as u32, }]; self.areas.push(area); self.whole.push(FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: base as u32, size: len as u32, }); } // Look for the image with the given ID, and return its offset, size and // device id. Returns None if the area is not present. pub fn find(&self, id: FlashId) -> Option<(usize, usize, u8)> { for area in &self.whole { // FIXME: should we ensure id is not duplicated over multiple devices? if area.flash_id == id { return Some((area.off as usize, area.size as usize, area.device_id)); } } None } pub fn get_c(&self) -> CAreaDesc { let mut areas: CAreaDesc = Default::default(); assert_eq!(self.areas.len(), self.whole.len()); for (i, area) in self.areas.iter().enumerate() { if!area.is_empty() { areas.slots[i].areas = &area[0]; areas.slots[i].whole = self.whole[i].clone(); areas.slots[i].num_areas = area.len() as u32; areas.slots[i].id = area[0].flash_id; } } areas.num_slots = self.areas.len() as u32; areas } /// Return an iterator over all `FlashArea`s present. pub fn iter_areas(&self) -> impl Iterator<Item = &FlashArea> { self.whole.iter() } } /// The area descriptor, C format. #[repr(C)] #[derive(Debug, Default)] pub struct CAreaDesc { slots: [CArea; 16], num_slots: u32, } #[repr(C)] #[derive(Debug)] pub struct CArea { whole: FlashArea, areas: *const FlashArea, num_areas: u32, // FIXME: is this not already available on whole/areas? id: FlashId, } impl Default for CArea { fn default() -> CArea { CArea { areas: ptr::null(), whole: Default::default(), id: FlashId::BootLoader, num_areas: 0, } } } /// Flash area map. #[repr(u8)] #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[allow(dead_code)] pub enum FlashId { BootLoader = 0, Image0 = 1, Image1 = 2, ImageScratch = 3, Image2 = 4, Image3 = 5, } impl Default for FlashId { fn default() -> FlashId { FlashId::BootLoader } } #[repr(C)] #[derive(Debug, Clone, Default)] pub struct FlashArea { pub flash_id: FlashId, pub device_id: u8, pad16: u16, pub off: u32, pub size: u32, }
{ panic!("Flash areas not added in order"); }
conditional_block
area.rs
// Copyright (c) 2017-2021 Linaro LTD // Copyright (c) 2018-2019 JUUL Labs // Copyright (c) 2019 Arm Limited // // SPDX-License-Identifier: Apache-2.0 //! Describe flash areas. use simflash::{Flash, SimFlash, Sector}; use std::ptr; use std::collections::HashMap; /// Structure to build up the boot area table. #[derive(Debug, Default, Clone)] pub struct AreaDesc { areas: Vec<Vec<FlashArea>>, whole: Vec<FlashArea>, sectors: HashMap<u8, Vec<Sector>>, } impl AreaDesc { pub fn new() -> AreaDesc { AreaDesc { areas: vec![], whole: vec![], sectors: HashMap::new(), } } pub fn add_flash_sectors(&mut self, id: u8, flash: &SimFlash) { self.sectors.insert(id, flash.sector_iter().collect()); } /// Add a slot to the image. The slot must align with erasable units in the flash device. /// Panics if the description is not valid. There are also bootloader assumptions that the /// slots are PRIMARY_SLOT, SECONDARY_SLOT, and SCRATCH in that order. pub fn add_image(&mut self, base: usize, len: usize, id: FlashId, dev_id: u8) { let nid = id as usize; let orig_base = base; let orig_len = len; let mut base = base; let mut len = len; while nid > self.areas.len() { self.areas.push(vec![]); self.whole.push(Default::default()); } if nid!= self.areas.len() { panic!("Flash areas not added in order"); } let mut area = vec![]; for sector in &self.sectors[&dev_id] { if len == 0 { break; }; if base > sector.base + sector.size - 1 { continue; } if sector.base!= base { panic!("Image does not start on a sector boundary"); } area.push(FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: sector.base as u32, size: sector.size as u32, }); base += sector.size; len -= sector.size; } if len!= 0 { panic!("Image goes past end of device"); } self.areas.push(area); self.whole.push(FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: orig_base as u32, size: orig_len as u32, }); } // Add a simple slot to the image. This ignores the device layout, and just adds the area as a // single unit. It assumes that the image lines up with image boundaries. This tests // configurations where the partition table uses larger sectors than the underlying flash // device. pub fn add_simple_image(&mut self, base: usize, len: usize, id: FlashId, dev_id: u8) { let area = vec![FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: base as u32, size: len as u32, }]; self.areas.push(area); self.whole.push(FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: base as u32, size: len as u32, }); } // Look for the image with the given ID, and return its offset, size and // device id. Returns None if the area is not present. pub fn find(&self, id: FlashId) -> Option<(usize, usize, u8)> { for area in &self.whole { // FIXME: should we ensure id is not duplicated over multiple devices? if area.flash_id == id { return Some((area.off as usize, area.size as usize, area.device_id)); } } None } pub fn get_c(&self) -> CAreaDesc { let mut areas: CAreaDesc = Default::default(); assert_eq!(self.areas.len(), self.whole.len()); for (i, area) in self.areas.iter().enumerate() { if!area.is_empty() { areas.slots[i].areas = &area[0]; areas.slots[i].whole = self.whole[i].clone(); areas.slots[i].num_areas = area.len() as u32; areas.slots[i].id = area[0].flash_id; } } areas.num_slots = self.areas.len() as u32; areas } /// Return an iterator over all `FlashArea`s present. pub fn iter_areas(&self) -> impl Iterator<Item = &FlashArea> { self.whole.iter() } } /// The area descriptor, C format. #[repr(C)] #[derive(Debug, Default)] pub struct CAreaDesc { slots: [CArea; 16], num_slots: u32, } #[repr(C)] #[derive(Debug)] pub struct CArea { whole: FlashArea, areas: *const FlashArea,
impl Default for CArea { fn default() -> CArea { CArea { areas: ptr::null(), whole: Default::default(), id: FlashId::BootLoader, num_areas: 0, } } } /// Flash area map. #[repr(u8)] #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[allow(dead_code)] pub enum FlashId { BootLoader = 0, Image0 = 1, Image1 = 2, ImageScratch = 3, Image2 = 4, Image3 = 5, } impl Default for FlashId { fn default() -> FlashId { FlashId::BootLoader } } #[repr(C)] #[derive(Debug, Clone, Default)] pub struct FlashArea { pub flash_id: FlashId, pub device_id: u8, pad16: u16, pub off: u32, pub size: u32, }
num_areas: u32, // FIXME: is this not already available on whole/areas? id: FlashId, }
random_line_split
area.rs
// Copyright (c) 2017-2021 Linaro LTD // Copyright (c) 2018-2019 JUUL Labs // Copyright (c) 2019 Arm Limited // // SPDX-License-Identifier: Apache-2.0 //! Describe flash areas. use simflash::{Flash, SimFlash, Sector}; use std::ptr; use std::collections::HashMap; /// Structure to build up the boot area table. #[derive(Debug, Default, Clone)] pub struct AreaDesc { areas: Vec<Vec<FlashArea>>, whole: Vec<FlashArea>, sectors: HashMap<u8, Vec<Sector>>, } impl AreaDesc { pub fn new() -> AreaDesc { AreaDesc { areas: vec![], whole: vec![], sectors: HashMap::new(), } } pub fn add_flash_sectors(&mut self, id: u8, flash: &SimFlash)
/// Add a slot to the image. The slot must align with erasable units in the flash device. /// Panics if the description is not valid. There are also bootloader assumptions that the /// slots are PRIMARY_SLOT, SECONDARY_SLOT, and SCRATCH in that order. pub fn add_image(&mut self, base: usize, len: usize, id: FlashId, dev_id: u8) { let nid = id as usize; let orig_base = base; let orig_len = len; let mut base = base; let mut len = len; while nid > self.areas.len() { self.areas.push(vec![]); self.whole.push(Default::default()); } if nid!= self.areas.len() { panic!("Flash areas not added in order"); } let mut area = vec![]; for sector in &self.sectors[&dev_id] { if len == 0 { break; }; if base > sector.base + sector.size - 1 { continue; } if sector.base!= base { panic!("Image does not start on a sector boundary"); } area.push(FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: sector.base as u32, size: sector.size as u32, }); base += sector.size; len -= sector.size; } if len!= 0 { panic!("Image goes past end of device"); } self.areas.push(area); self.whole.push(FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: orig_base as u32, size: orig_len as u32, }); } // Add a simple slot to the image. This ignores the device layout, and just adds the area as a // single unit. It assumes that the image lines up with image boundaries. This tests // configurations where the partition table uses larger sectors than the underlying flash // device. pub fn add_simple_image(&mut self, base: usize, len: usize, id: FlashId, dev_id: u8) { let area = vec![FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: base as u32, size: len as u32, }]; self.areas.push(area); self.whole.push(FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: base as u32, size: len as u32, }); } // Look for the image with the given ID, and return its offset, size and // device id. Returns None if the area is not present. pub fn find(&self, id: FlashId) -> Option<(usize, usize, u8)> { for area in &self.whole { // FIXME: should we ensure id is not duplicated over multiple devices? if area.flash_id == id { return Some((area.off as usize, area.size as usize, area.device_id)); } } None } pub fn get_c(&self) -> CAreaDesc { let mut areas: CAreaDesc = Default::default(); assert_eq!(self.areas.len(), self.whole.len()); for (i, area) in self.areas.iter().enumerate() { if!area.is_empty() { areas.slots[i].areas = &area[0]; areas.slots[i].whole = self.whole[i].clone(); areas.slots[i].num_areas = area.len() as u32; areas.slots[i].id = area[0].flash_id; } } areas.num_slots = self.areas.len() as u32; areas } /// Return an iterator over all `FlashArea`s present. pub fn iter_areas(&self) -> impl Iterator<Item = &FlashArea> { self.whole.iter() } } /// The area descriptor, C format. #[repr(C)] #[derive(Debug, Default)] pub struct CAreaDesc { slots: [CArea; 16], num_slots: u32, } #[repr(C)] #[derive(Debug)] pub struct CArea { whole: FlashArea, areas: *const FlashArea, num_areas: u32, // FIXME: is this not already available on whole/areas? id: FlashId, } impl Default for CArea { fn default() -> CArea { CArea { areas: ptr::null(), whole: Default::default(), id: FlashId::BootLoader, num_areas: 0, } } } /// Flash area map. #[repr(u8)] #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[allow(dead_code)] pub enum FlashId { BootLoader = 0, Image0 = 1, Image1 = 2, ImageScratch = 3, Image2 = 4, Image3 = 5, } impl Default for FlashId { fn default() -> FlashId { FlashId::BootLoader } } #[repr(C)] #[derive(Debug, Clone, Default)] pub struct FlashArea { pub flash_id: FlashId, pub device_id: u8, pad16: u16, pub off: u32, pub size: u32, }
{ self.sectors.insert(id, flash.sector_iter().collect()); }
identifier_body
area.rs
// Copyright (c) 2017-2021 Linaro LTD // Copyright (c) 2018-2019 JUUL Labs // Copyright (c) 2019 Arm Limited // // SPDX-License-Identifier: Apache-2.0 //! Describe flash areas. use simflash::{Flash, SimFlash, Sector}; use std::ptr; use std::collections::HashMap; /// Structure to build up the boot area table. #[derive(Debug, Default, Clone)] pub struct AreaDesc { areas: Vec<Vec<FlashArea>>, whole: Vec<FlashArea>, sectors: HashMap<u8, Vec<Sector>>, } impl AreaDesc { pub fn
() -> AreaDesc { AreaDesc { areas: vec![], whole: vec![], sectors: HashMap::new(), } } pub fn add_flash_sectors(&mut self, id: u8, flash: &SimFlash) { self.sectors.insert(id, flash.sector_iter().collect()); } /// Add a slot to the image. The slot must align with erasable units in the flash device. /// Panics if the description is not valid. There are also bootloader assumptions that the /// slots are PRIMARY_SLOT, SECONDARY_SLOT, and SCRATCH in that order. pub fn add_image(&mut self, base: usize, len: usize, id: FlashId, dev_id: u8) { let nid = id as usize; let orig_base = base; let orig_len = len; let mut base = base; let mut len = len; while nid > self.areas.len() { self.areas.push(vec![]); self.whole.push(Default::default()); } if nid!= self.areas.len() { panic!("Flash areas not added in order"); } let mut area = vec![]; for sector in &self.sectors[&dev_id] { if len == 0 { break; }; if base > sector.base + sector.size - 1 { continue; } if sector.base!= base { panic!("Image does not start on a sector boundary"); } area.push(FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: sector.base as u32, size: sector.size as u32, }); base += sector.size; len -= sector.size; } if len!= 0 { panic!("Image goes past end of device"); } self.areas.push(area); self.whole.push(FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: orig_base as u32, size: orig_len as u32, }); } // Add a simple slot to the image. This ignores the device layout, and just adds the area as a // single unit. It assumes that the image lines up with image boundaries. This tests // configurations where the partition table uses larger sectors than the underlying flash // device. pub fn add_simple_image(&mut self, base: usize, len: usize, id: FlashId, dev_id: u8) { let area = vec![FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: base as u32, size: len as u32, }]; self.areas.push(area); self.whole.push(FlashArea { flash_id: id, device_id: dev_id, pad16: 0, off: base as u32, size: len as u32, }); } // Look for the image with the given ID, and return its offset, size and // device id. Returns None if the area is not present. pub fn find(&self, id: FlashId) -> Option<(usize, usize, u8)> { for area in &self.whole { // FIXME: should we ensure id is not duplicated over multiple devices? if area.flash_id == id { return Some((area.off as usize, area.size as usize, area.device_id)); } } None } pub fn get_c(&self) -> CAreaDesc { let mut areas: CAreaDesc = Default::default(); assert_eq!(self.areas.len(), self.whole.len()); for (i, area) in self.areas.iter().enumerate() { if!area.is_empty() { areas.slots[i].areas = &area[0]; areas.slots[i].whole = self.whole[i].clone(); areas.slots[i].num_areas = area.len() as u32; areas.slots[i].id = area[0].flash_id; } } areas.num_slots = self.areas.len() as u32; areas } /// Return an iterator over all `FlashArea`s present. pub fn iter_areas(&self) -> impl Iterator<Item = &FlashArea> { self.whole.iter() } } /// The area descriptor, C format. #[repr(C)] #[derive(Debug, Default)] pub struct CAreaDesc { slots: [CArea; 16], num_slots: u32, } #[repr(C)] #[derive(Debug)] pub struct CArea { whole: FlashArea, areas: *const FlashArea, num_areas: u32, // FIXME: is this not already available on whole/areas? id: FlashId, } impl Default for CArea { fn default() -> CArea { CArea { areas: ptr::null(), whole: Default::default(), id: FlashId::BootLoader, num_areas: 0, } } } /// Flash area map. #[repr(u8)] #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[allow(dead_code)] pub enum FlashId { BootLoader = 0, Image0 = 1, Image1 = 2, ImageScratch = 3, Image2 = 4, Image3 = 5, } impl Default for FlashId { fn default() -> FlashId { FlashId::BootLoader } } #[repr(C)] #[derive(Debug, Clone, Default)] pub struct FlashArea { pub flash_id: FlashId, pub device_id: u8, pad16: u16, pub off: u32, pub size: u32, }
new
identifier_name
build.rs
extern crate amq_protocol; use amq_protocol::codegen::*; use std::collections::BTreeMap; use std::env; use std::fs::File; use std::io::{Read, Write}; use std::path::Path; fn main() { let out_dir = env::var("OUT_DIR").expect("OUT_DIR is not defined"); let dest_path = Path::new(&out_dir).join("generated.rs"); let dest_path2 = Path::new(&out_dir).join("api.rs");
let mut full_tpl = String::new(); let mut api_tpl = String::new(); std::fs::File::open("templates/main.rs").expect("Failed to open main template").read_to_string(&mut full_tpl).expect("Failed to read main template"); std::fs::File::open("templates/api.rs").expect("Failed to open main template").read_to_string(&mut api_tpl).expect("Failed to read main template"); let mut handlebars = CodeGenerator::new().register_amqp_helpers(); let mut data = BTreeMap::new(); handlebars.register_template_string("full", full_tpl).expect("Failed to register full template"); handlebars.register_template_string("api", api_tpl).expect("Failed to register api template"); let specs = AMQProtocolDefinition::load(); data.insert("specs".to_string(), specs); writeln!(f, "{}", handlebars.render("full", &data).expect("Failed to render full template")).expect("Failed to write generated.rs"); writeln!(f2, "{}", handlebars.render("api", &data).expect("Failed to render api template")).expect("Failed to write api.rs"); }
let mut f = File::create(&dest_path).expect("Failed to create generated.rs"); let mut f2 = File::create(&dest_path2).expect("Failed to create api.rs");
random_line_split
build.rs
extern crate amq_protocol; use amq_protocol::codegen::*; use std::collections::BTreeMap; use std::env; use std::fs::File; use std::io::{Read, Write}; use std::path::Path; fn main()
writeln!(f2, "{}", handlebars.render("api", &data).expect("Failed to render api template")).expect("Failed to write api.rs"); }
{ let out_dir = env::var("OUT_DIR").expect("OUT_DIR is not defined"); let dest_path = Path::new(&out_dir).join("generated.rs"); let dest_path2 = Path::new(&out_dir).join("api.rs"); let mut f = File::create(&dest_path).expect("Failed to create generated.rs"); let mut f2 = File::create(&dest_path2).expect("Failed to create api.rs"); let mut full_tpl = String::new(); let mut api_tpl = String::new(); std::fs::File::open("templates/main.rs").expect("Failed to open main template").read_to_string(&mut full_tpl).expect("Failed to read main template"); std::fs::File::open("templates/api.rs").expect("Failed to open main template").read_to_string(&mut api_tpl).expect("Failed to read main template"); let mut handlebars = CodeGenerator::new().register_amqp_helpers(); let mut data = BTreeMap::new(); handlebars.register_template_string("full", full_tpl).expect("Failed to register full template"); handlebars.register_template_string("api", api_tpl).expect("Failed to register api template"); let specs = AMQProtocolDefinition::load(); data.insert("specs".to_string(), specs); writeln!(f, "{}", handlebars.render("full", &data).expect("Failed to render full template")).expect("Failed to write generated.rs");
identifier_body
build.rs
extern crate amq_protocol; use amq_protocol::codegen::*; use std::collections::BTreeMap; use std::env; use std::fs::File; use std::io::{Read, Write}; use std::path::Path; fn
() { let out_dir = env::var("OUT_DIR").expect("OUT_DIR is not defined"); let dest_path = Path::new(&out_dir).join("generated.rs"); let dest_path2 = Path::new(&out_dir).join("api.rs"); let mut f = File::create(&dest_path).expect("Failed to create generated.rs"); let mut f2 = File::create(&dest_path2).expect("Failed to create api.rs"); let mut full_tpl = String::new(); let mut api_tpl = String::new(); std::fs::File::open("templates/main.rs").expect("Failed to open main template").read_to_string(&mut full_tpl).expect("Failed to read main template"); std::fs::File::open("templates/api.rs").expect("Failed to open main template").read_to_string(&mut api_tpl).expect("Failed to read main template"); let mut handlebars = CodeGenerator::new().register_amqp_helpers(); let mut data = BTreeMap::new(); handlebars.register_template_string("full", full_tpl).expect("Failed to register full template"); handlebars.register_template_string("api", api_tpl).expect("Failed to register api template"); let specs = AMQProtocolDefinition::load(); data.insert("specs".to_string(), specs); writeln!(f, "{}", handlebars.render("full", &data).expect("Failed to render full template")).expect("Failed to write generated.rs"); writeln!(f2, "{}", handlebars.render("api", &data).expect("Failed to render api template")).expect("Failed to write api.rs"); }
main
identifier_name
cli.rs
use clap::{crate_version, App, AppSettings, Arg}; pub fn build_cli() -> App<'static,'static>
) .arg( Arg::with_name("test") .required(false) .long("test") .short("t") .help("Test to see if conversion is required") .takes_value(false), ) .arg( Arg::with_name("file") .required(true) .index(1) .multiple(true) .takes_value(true) .help("The files to convert"), ) }
{ App::new("chromecastise") .version(crate_version!()) .author("Stuart Moss <[email protected]>") .setting(AppSettings::ArgRequiredElseHelp) .arg( Arg::with_name("mp4") .long("mp4") .short("a") .help("Use mp4 as the output container format") .conflicts_with("mkv") .takes_value(false), ) .arg( Arg::with_name("mkv") .long("mkv") .short("b") .help("Use mkv as the output container format") .conflicts_with("mp4") .takes_value(false),
identifier_body
cli.rs
use clap::{crate_version, App, AppSettings, Arg}; pub fn build_cli() -> App<'static,'static> { App::new("chromecastise") .version(crate_version!()) .author("Stuart Moss <[email protected]>") .setting(AppSettings::ArgRequiredElseHelp) .arg( Arg::with_name("mp4") .long("mp4") .short("a")
.help("Use mp4 as the output container format") .conflicts_with("mkv") .takes_value(false), ) .arg( Arg::with_name("mkv") .long("mkv") .short("b") .help("Use mkv as the output container format") .conflicts_with("mp4") .takes_value(false), ) .arg( Arg::with_name("test") .required(false) .long("test") .short("t") .help("Test to see if conversion is required") .takes_value(false), ) .arg( Arg::with_name("file") .required(true) .index(1) .multiple(true) .takes_value(true) .help("The files to convert"), ) }
random_line_split
cli.rs
use clap::{crate_version, App, AppSettings, Arg}; pub fn
() -> App<'static,'static> { App::new("chromecastise") .version(crate_version!()) .author("Stuart Moss <[email protected]>") .setting(AppSettings::ArgRequiredElseHelp) .arg( Arg::with_name("mp4") .long("mp4") .short("a") .help("Use mp4 as the output container format") .conflicts_with("mkv") .takes_value(false), ) .arg( Arg::with_name("mkv") .long("mkv") .short("b") .help("Use mkv as the output container format") .conflicts_with("mp4") .takes_value(false), ) .arg( Arg::with_name("test") .required(false) .long("test") .short("t") .help("Test to see if conversion is required") .takes_value(false), ) .arg( Arg::with_name("file") .required(true) .index(1) .multiple(true) .takes_value(true) .help("The files to convert"), ) }
build_cli
identifier_name
mod.rs
use system::OS; mod manager; pub mod scoped; // #[macro_use]mod local; // pub use self::local::{LocalKey, LocalKeyState}; /// Cooperatively gives up a timeslice to the OS scheduler. pub fn yield_now() { OS::yield_thread() } /// Blocks unless or until the current thread's token is made available. /// /// Every thread is equipped with some basic low-level blocking support, via /// the `park()` function and the [`unpark()`][unpark] method. These can be /// used as a more CPU-efficient implementation of a spinlock. ///
/// being acquired). /// /// A call to `park` does not guarantee that the thread will remain parked /// forever, and callers should be prepared for this possibility. /// /// See the [module documentation][thread] for more detail. /// /// [thread]: index.html // The implementation currently uses the trivial strategy of a Mutex+Condvar // with wakeup flag, which does not actually allow spurious wakeups. In the // future, this will be implemented in a more efficient way, perhaps along the lines of // http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp // or futuxes, and in either case may allow spurious wakeups. pub fn park() { OS::suspend_thread(OS::get_current_thread()); } pub use self::manager::{collect, current, JoinHandle, Thread, spawn};
/// [unpark]: struct.Thread.html#method.unpark /// /// The API is typically used by acquiring a handle to the current thread, /// placing that handle in a shared data structure so that other threads can /// find it, and then parking (in a loop with a check for the token actually
random_line_split
mod.rs
use system::OS; mod manager; pub mod scoped; // #[macro_use]mod local; // pub use self::local::{LocalKey, LocalKeyState}; /// Cooperatively gives up a timeslice to the OS scheduler. pub fn yield_now() { OS::yield_thread() } /// Blocks unless or until the current thread's token is made available. /// /// Every thread is equipped with some basic low-level blocking support, via /// the `park()` function and the [`unpark()`][unpark] method. These can be /// used as a more CPU-efficient implementation of a spinlock. /// /// [unpark]: struct.Thread.html#method.unpark /// /// The API is typically used by acquiring a handle to the current thread, /// placing that handle in a shared data structure so that other threads can /// find it, and then parking (in a loop with a check for the token actually /// being acquired). /// /// A call to `park` does not guarantee that the thread will remain parked /// forever, and callers should be prepared for this possibility. /// /// See the [module documentation][thread] for more detail. /// /// [thread]: index.html // The implementation currently uses the trivial strategy of a Mutex+Condvar // with wakeup flag, which does not actually allow spurious wakeups. In the // future, this will be implemented in a more efficient way, perhaps along the lines of // http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp // or futuxes, and in either case may allow spurious wakeups. pub fn park()
pub use self::manager::{collect, current, JoinHandle, Thread, spawn};
{ OS::suspend_thread(OS::get_current_thread()); }
identifier_body
mod.rs
use system::OS; mod manager; pub mod scoped; // #[macro_use]mod local; // pub use self::local::{LocalKey, LocalKeyState}; /// Cooperatively gives up a timeslice to the OS scheduler. pub fn
() { OS::yield_thread() } /// Blocks unless or until the current thread's token is made available. /// /// Every thread is equipped with some basic low-level blocking support, via /// the `park()` function and the [`unpark()`][unpark] method. These can be /// used as a more CPU-efficient implementation of a spinlock. /// /// [unpark]: struct.Thread.html#method.unpark /// /// The API is typically used by acquiring a handle to the current thread, /// placing that handle in a shared data structure so that other threads can /// find it, and then parking (in a loop with a check for the token actually /// being acquired). /// /// A call to `park` does not guarantee that the thread will remain parked /// forever, and callers should be prepared for this possibility. /// /// See the [module documentation][thread] for more detail. /// /// [thread]: index.html // The implementation currently uses the trivial strategy of a Mutex+Condvar // with wakeup flag, which does not actually allow spurious wakeups. In the // future, this will be implemented in a more efficient way, perhaps along the lines of // http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp // or futuxes, and in either case may allow spurious wakeups. pub fn park() { OS::suspend_thread(OS::get_current_thread()); } pub use self::manager::{collect, current, JoinHandle, Thread, spawn};
yield_now
identifier_name
tests.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. #![feature(plugin)] #![plugin(hexfloat)] #[test] fn main()
{ let a = hexfloat!("0x1.999999999999ap-4"); assert_eq!(a, 0.1f64); let b = hexfloat!("-0x1.fffp-4", f32); assert_eq!(b, -0.12498474_f32); let c = hexfloat!("0x.12345p5", f64); let d = hexfloat!("0x0.12345p5", f64); assert_eq!(c,d); let f = hexfloat!("0x10.p4", f32); let g = hexfloat!("0x10.0p4", f32); assert_eq!(f,g); }
identifier_body
tests.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. #![feature(plugin)] #![plugin(hexfloat)] #[test] fn
() { let a = hexfloat!("0x1.999999999999ap-4"); assert_eq!(a, 0.1f64); let b = hexfloat!("-0x1.fffp-4", f32); assert_eq!(b, -0.12498474_f32); let c = hexfloat!("0x.12345p5", f64); let d = hexfloat!("0x0.12345p5", f64); assert_eq!(c,d); let f = hexfloat!("0x10.p4", f32); let g = hexfloat!("0x10.0p4", f32); assert_eq!(f,g); }
main
identifier_name
tests.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. #![feature(plugin)] #![plugin(hexfloat)] #[test] fn main() { let a = hexfloat!("0x1.999999999999ap-4"); assert_eq!(a, 0.1f64); let b = hexfloat!("-0x1.fffp-4", f32); assert_eq!(b, -0.12498474_f32); let c = hexfloat!("0x.12345p5", f64); let d = hexfloat!("0x0.12345p5", f64); assert_eq!(c,d); let f = hexfloat!("0x10.p4", f32); let g = hexfloat!("0x10.0p4", f32);
assert_eq!(f,g); }
random_line_split
text.rs
/// Divide a string into the longest slice that fits within maximum line /// length and the rest of the string. /// /// Place the split before a whitespace or after a hyphen if possible. Any /// whitespace between the two segments is trimmed. Newlines will cause a /// segment split when encountered. pub fn split_line<'a, F>(text: &'a str, char_width: &F, max_len: f32) -> (&'a str, &'a str) where F: Fn(char) -> f32 { assert!(max_len >= 0.0); if text.len() == 0 { return (text, text); } // Init the split position to 1 because we always want to return at least // 1 character in the head partition. let mut head_end = 1; let mut tail_start = 1; // Is the iteration currently consuming whitespace inside a possible // break. let mut eat_whitespace = false; let mut length = 0.0; for (i, c) in text.chars().enumerate() { length = length + char_width(c); // Invariant: head_end and tail_start describe a valid, but possibly // suboptimal return value at this point. assert!(text[..head_end].len() > 0); assert!(head_end <= tail_start); if eat_whitespace { if c.is_whitespace() { tail_start = i + 1; if c == '\n' { return (&text[..head_end], &text[tail_start..]); } continue; } else { eat_whitespace = false; }
assert!(!eat_whitespace); // Invariant: The length of the string processed up to this point is // still short enough to return. // Encounter the first whitespace, set head_end marker. if c.is_whitespace() { head_end = i; tail_start = i + 1; if c == '\n' { return (&text[..head_end], &text[tail_start..]); } eat_whitespace = true; continue; } assert!(!c.is_whitespace()); // Went over the allowed length. if length > max_len { if i > 1 && head_end == 1 && tail_start == 1 { // Didn't encounter any better cut points, so just place cut // in the middle of the word where we're at. head_end = i; tail_start = i; } // Use the last good result. return (&text[..head_end], &text[tail_start..]); } // Hyphens are a possible cut point. if c == '-' { head_end = i + 1; tail_start = i + 1; } } (&text, &""[..]) } /// Wrap a text into multiple lines separated by newlines. pub fn wrap_lines<F>(mut text: &str, char_width: &F, max_len: f32) -> String where F: Fn(char) -> f32 { let mut result = String::new(); loop { let (head, tail) = split_line(text, char_width, max_len); if head.len() == 0 && tail.len() == 0 { break; } assert!(head.len() > 0, "Line splitter caught in infinite loop"); assert!(tail.len() < text.len(), "Line splitter not shrinking string"); result = result + head; // Must preserve a hard newline at the end if the input string had // one. The else branch checks for the very last char being a newline, // this would be clipped off otherwise. if tail.len()!= 0 { result = result + "\n"; } else if text.chars().last() == Some('\n') { result = result + "\n"; } text = tail; } result } pub struct Map2DIterator<T> { /// Input iterator iter: T, x: i32, y: i32, } impl<T: Iterator<Item=char>> Iterator for Map2DIterator<T> { type Item = (char, i32, i32); fn next(&mut self) -> Option<(char, i32, i32)> { loop { match self.iter.next() { None => { return None } Some(c) if c == '\n' => { self.y += 1; self.x = 0; } Some(c) if (c as u32) < 32 => { } Some(c) => { self.x += 1; return Some((c, self.x - 1, self.y)) } } } } } pub trait Map2DUtil: Sized { /// Convert an input value into a sequence of 2D coordinates associated /// with a subvalue. /// /// Used for converting a string of ASCII art into characters and their /// coordinates. fn map2d(self) -> Map2DIterator<Self>; } impl<T: Iterator<Item=char>> Map2DUtil for T { fn map2d(self) -> Map2DIterator<T> { Map2DIterator{ iter: self, x: 0, y: 0 } } } #[cfg(test)] mod test { #[test] fn test_split_line() { use super::split_line; assert_eq!(("", ""), split_line("", &|_| 1.0, 12.0)); assert_eq!(("a", ""), split_line("a", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the cat", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the cat", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the \t cat", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the \ncat", &|_| 1.0, 32.0)); assert_eq!(("the", " cat"), split_line("the \n cat", &|_| 1.0, 32.0)); assert_eq!(("the cat", ""), split_line("the cat", &|_| 1.0, 32.0)); assert_eq!(("the", "cat sat"), split_line("the cat sat", &|_| 1.0, 6.0)); assert_eq!(("the cat", "sat"), split_line("the cat sat", &|_| 1.0, 7.0)); assert_eq!(("a", "bc"), split_line("abc", &|_| 1.0, 0.01)); assert_eq!(("dead", "beef"), split_line("deadbeef", &|_| 1.0, 4.0)); assert_eq!(("the-", "cat"), split_line("the-cat", &|_| 1.0, 5.0)); } }
} // We're either just encountering the first whitespace after a block // of text, or over non-whitespace text.
random_line_split
text.rs
/// Divide a string into the longest slice that fits within maximum line /// length and the rest of the string. /// /// Place the split before a whitespace or after a hyphen if possible. Any /// whitespace between the two segments is trimmed. Newlines will cause a /// segment split when encountered. pub fn split_line<'a, F>(text: &'a str, char_width: &F, max_len: f32) -> (&'a str, &'a str) where F: Fn(char) -> f32 { assert!(max_len >= 0.0); if text.len() == 0 { return (text, text); } // Init the split position to 1 because we always want to return at least // 1 character in the head partition. let mut head_end = 1; let mut tail_start = 1; // Is the iteration currently consuming whitespace inside a possible // break. let mut eat_whitespace = false; let mut length = 0.0; for (i, c) in text.chars().enumerate() { length = length + char_width(c); // Invariant: head_end and tail_start describe a valid, but possibly // suboptimal return value at this point. assert!(text[..head_end].len() > 0); assert!(head_end <= tail_start); if eat_whitespace { if c.is_whitespace() { tail_start = i + 1; if c == '\n' { return (&text[..head_end], &text[tail_start..]); } continue; } else { eat_whitespace = false; } } // We're either just encountering the first whitespace after a block // of text, or over non-whitespace text. assert!(!eat_whitespace); // Invariant: The length of the string processed up to this point is // still short enough to return. // Encounter the first whitespace, set head_end marker. if c.is_whitespace() { head_end = i; tail_start = i + 1; if c == '\n' { return (&text[..head_end], &text[tail_start..]); } eat_whitespace = true; continue; } assert!(!c.is_whitespace()); // Went over the allowed length. if length > max_len { if i > 1 && head_end == 1 && tail_start == 1 { // Didn't encounter any better cut points, so just place cut // in the middle of the word where we're at. head_end = i; tail_start = i; } // Use the last good result. return (&text[..head_end], &text[tail_start..]); } // Hyphens are a possible cut point. if c == '-' { head_end = i + 1; tail_start = i + 1; } } (&text, &""[..]) } /// Wrap a text into multiple lines separated by newlines. pub fn wrap_lines<F>(mut text: &str, char_width: &F, max_len: f32) -> String where F: Fn(char) -> f32 { let mut result = String::new(); loop { let (head, tail) = split_line(text, char_width, max_len); if head.len() == 0 && tail.len() == 0
assert!(head.len() > 0, "Line splitter caught in infinite loop"); assert!(tail.len() < text.len(), "Line splitter not shrinking string"); result = result + head; // Must preserve a hard newline at the end if the input string had // one. The else branch checks for the very last char being a newline, // this would be clipped off otherwise. if tail.len()!= 0 { result = result + "\n"; } else if text.chars().last() == Some('\n') { result = result + "\n"; } text = tail; } result } pub struct Map2DIterator<T> { /// Input iterator iter: T, x: i32, y: i32, } impl<T: Iterator<Item=char>> Iterator for Map2DIterator<T> { type Item = (char, i32, i32); fn next(&mut self) -> Option<(char, i32, i32)> { loop { match self.iter.next() { None => { return None } Some(c) if c == '\n' => { self.y += 1; self.x = 0; } Some(c) if (c as u32) < 32 => { } Some(c) => { self.x += 1; return Some((c, self.x - 1, self.y)) } } } } } pub trait Map2DUtil: Sized { /// Convert an input value into a sequence of 2D coordinates associated /// with a subvalue. /// /// Used for converting a string of ASCII art into characters and their /// coordinates. fn map2d(self) -> Map2DIterator<Self>; } impl<T: Iterator<Item=char>> Map2DUtil for T { fn map2d(self) -> Map2DIterator<T> { Map2DIterator{ iter: self, x: 0, y: 0 } } } #[cfg(test)] mod test { #[test] fn test_split_line() { use super::split_line; assert_eq!(("", ""), split_line("", &|_| 1.0, 12.0)); assert_eq!(("a", ""), split_line("a", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the cat", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the cat", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the \t cat", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the \ncat", &|_| 1.0, 32.0)); assert_eq!(("the", " cat"), split_line("the \n cat", &|_| 1.0, 32.0)); assert_eq!(("the cat", ""), split_line("the cat", &|_| 1.0, 32.0)); assert_eq!(("the", "cat sat"), split_line("the cat sat", &|_| 1.0, 6.0)); assert_eq!(("the cat", "sat"), split_line("the cat sat", &|_| 1.0, 7.0)); assert_eq!(("a", "bc"), split_line("abc", &|_| 1.0, 0.01)); assert_eq!(("dead", "beef"), split_line("deadbeef", &|_| 1.0, 4.0)); assert_eq!(("the-", "cat"), split_line("the-cat", &|_| 1.0, 5.0)); } }
{ break; }
conditional_block
text.rs
/// Divide a string into the longest slice that fits within maximum line /// length and the rest of the string. /// /// Place the split before a whitespace or after a hyphen if possible. Any /// whitespace between the two segments is trimmed. Newlines will cause a /// segment split when encountered. pub fn split_line<'a, F>(text: &'a str, char_width: &F, max_len: f32) -> (&'a str, &'a str) where F: Fn(char) -> f32 { assert!(max_len >= 0.0); if text.len() == 0 { return (text, text); } // Init the split position to 1 because we always want to return at least // 1 character in the head partition. let mut head_end = 1; let mut tail_start = 1; // Is the iteration currently consuming whitespace inside a possible // break. let mut eat_whitespace = false; let mut length = 0.0; for (i, c) in text.chars().enumerate() { length = length + char_width(c); // Invariant: head_end and tail_start describe a valid, but possibly // suboptimal return value at this point. assert!(text[..head_end].len() > 0); assert!(head_end <= tail_start); if eat_whitespace { if c.is_whitespace() { tail_start = i + 1; if c == '\n' { return (&text[..head_end], &text[tail_start..]); } continue; } else { eat_whitespace = false; } } // We're either just encountering the first whitespace after a block // of text, or over non-whitespace text. assert!(!eat_whitespace); // Invariant: The length of the string processed up to this point is // still short enough to return. // Encounter the first whitespace, set head_end marker. if c.is_whitespace() { head_end = i; tail_start = i + 1; if c == '\n' { return (&text[..head_end], &text[tail_start..]); } eat_whitespace = true; continue; } assert!(!c.is_whitespace()); // Went over the allowed length. if length > max_len { if i > 1 && head_end == 1 && tail_start == 1 { // Didn't encounter any better cut points, so just place cut // in the middle of the word where we're at. head_end = i; tail_start = i; } // Use the last good result. return (&text[..head_end], &text[tail_start..]); } // Hyphens are a possible cut point. if c == '-' { head_end = i + 1; tail_start = i + 1; } } (&text, &""[..]) } /// Wrap a text into multiple lines separated by newlines. pub fn wrap_lines<F>(mut text: &str, char_width: &F, max_len: f32) -> String where F: Fn(char) -> f32 { let mut result = String::new(); loop { let (head, tail) = split_line(text, char_width, max_len); if head.len() == 0 && tail.len() == 0 { break; } assert!(head.len() > 0, "Line splitter caught in infinite loop"); assert!(tail.len() < text.len(), "Line splitter not shrinking string"); result = result + head; // Must preserve a hard newline at the end if the input string had // one. The else branch checks for the very last char being a newline, // this would be clipped off otherwise. if tail.len()!= 0 { result = result + "\n"; } else if text.chars().last() == Some('\n') { result = result + "\n"; } text = tail; } result } pub struct Map2DIterator<T> { /// Input iterator iter: T, x: i32, y: i32, } impl<T: Iterator<Item=char>> Iterator for Map2DIterator<T> { type Item = (char, i32, i32); fn
(&mut self) -> Option<(char, i32, i32)> { loop { match self.iter.next() { None => { return None } Some(c) if c == '\n' => { self.y += 1; self.x = 0; } Some(c) if (c as u32) < 32 => { } Some(c) => { self.x += 1; return Some((c, self.x - 1, self.y)) } } } } } pub trait Map2DUtil: Sized { /// Convert an input value into a sequence of 2D coordinates associated /// with a subvalue. /// /// Used for converting a string of ASCII art into characters and their /// coordinates. fn map2d(self) -> Map2DIterator<Self>; } impl<T: Iterator<Item=char>> Map2DUtil for T { fn map2d(self) -> Map2DIterator<T> { Map2DIterator{ iter: self, x: 0, y: 0 } } } #[cfg(test)] mod test { #[test] fn test_split_line() { use super::split_line; assert_eq!(("", ""), split_line("", &|_| 1.0, 12.0)); assert_eq!(("a", ""), split_line("a", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the cat", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the cat", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the \t cat", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the \ncat", &|_| 1.0, 32.0)); assert_eq!(("the", " cat"), split_line("the \n cat", &|_| 1.0, 32.0)); assert_eq!(("the cat", ""), split_line("the cat", &|_| 1.0, 32.0)); assert_eq!(("the", "cat sat"), split_line("the cat sat", &|_| 1.0, 6.0)); assert_eq!(("the cat", "sat"), split_line("the cat sat", &|_| 1.0, 7.0)); assert_eq!(("a", "bc"), split_line("abc", &|_| 1.0, 0.01)); assert_eq!(("dead", "beef"), split_line("deadbeef", &|_| 1.0, 4.0)); assert_eq!(("the-", "cat"), split_line("the-cat", &|_| 1.0, 5.0)); } }
next
identifier_name
text.rs
/// Divide a string into the longest slice that fits within maximum line /// length and the rest of the string. /// /// Place the split before a whitespace or after a hyphen if possible. Any /// whitespace between the two segments is trimmed. Newlines will cause a /// segment split when encountered. pub fn split_line<'a, F>(text: &'a str, char_width: &F, max_len: f32) -> (&'a str, &'a str) where F: Fn(char) -> f32 { assert!(max_len >= 0.0); if text.len() == 0 { return (text, text); } // Init the split position to 1 because we always want to return at least // 1 character in the head partition. let mut head_end = 1; let mut tail_start = 1; // Is the iteration currently consuming whitespace inside a possible // break. let mut eat_whitespace = false; let mut length = 0.0; for (i, c) in text.chars().enumerate() { length = length + char_width(c); // Invariant: head_end and tail_start describe a valid, but possibly // suboptimal return value at this point. assert!(text[..head_end].len() > 0); assert!(head_end <= tail_start); if eat_whitespace { if c.is_whitespace() { tail_start = i + 1; if c == '\n' { return (&text[..head_end], &text[tail_start..]); } continue; } else { eat_whitespace = false; } } // We're either just encountering the first whitespace after a block // of text, or over non-whitespace text. assert!(!eat_whitespace); // Invariant: The length of the string processed up to this point is // still short enough to return. // Encounter the first whitespace, set head_end marker. if c.is_whitespace() { head_end = i; tail_start = i + 1; if c == '\n' { return (&text[..head_end], &text[tail_start..]); } eat_whitespace = true; continue; } assert!(!c.is_whitespace()); // Went over the allowed length. if length > max_len { if i > 1 && head_end == 1 && tail_start == 1 { // Didn't encounter any better cut points, so just place cut // in the middle of the word where we're at. head_end = i; tail_start = i; } // Use the last good result. return (&text[..head_end], &text[tail_start..]); } // Hyphens are a possible cut point. if c == '-' { head_end = i + 1; tail_start = i + 1; } } (&text, &""[..]) } /// Wrap a text into multiple lines separated by newlines. pub fn wrap_lines<F>(mut text: &str, char_width: &F, max_len: f32) -> String where F: Fn(char) -> f32
pub struct Map2DIterator<T> { /// Input iterator iter: T, x: i32, y: i32, } impl<T: Iterator<Item=char>> Iterator for Map2DIterator<T> { type Item = (char, i32, i32); fn next(&mut self) -> Option<(char, i32, i32)> { loop { match self.iter.next() { None => { return None } Some(c) if c == '\n' => { self.y += 1; self.x = 0; } Some(c) if (c as u32) < 32 => { } Some(c) => { self.x += 1; return Some((c, self.x - 1, self.y)) } } } } } pub trait Map2DUtil: Sized { /// Convert an input value into a sequence of 2D coordinates associated /// with a subvalue. /// /// Used for converting a string of ASCII art into characters and their /// coordinates. fn map2d(self) -> Map2DIterator<Self>; } impl<T: Iterator<Item=char>> Map2DUtil for T { fn map2d(self) -> Map2DIterator<T> { Map2DIterator{ iter: self, x: 0, y: 0 } } } #[cfg(test)] mod test { #[test] fn test_split_line() { use super::split_line; assert_eq!(("", ""), split_line("", &|_| 1.0, 12.0)); assert_eq!(("a", ""), split_line("a", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the cat", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the cat", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the \t cat", &|_| 1.0, 5.0)); assert_eq!(("the", "cat"), split_line("the \ncat", &|_| 1.0, 32.0)); assert_eq!(("the", " cat"), split_line("the \n cat", &|_| 1.0, 32.0)); assert_eq!(("the cat", ""), split_line("the cat", &|_| 1.0, 32.0)); assert_eq!(("the", "cat sat"), split_line("the cat sat", &|_| 1.0, 6.0)); assert_eq!(("the cat", "sat"), split_line("the cat sat", &|_| 1.0, 7.0)); assert_eq!(("a", "bc"), split_line("abc", &|_| 1.0, 0.01)); assert_eq!(("dead", "beef"), split_line("deadbeef", &|_| 1.0, 4.0)); assert_eq!(("the-", "cat"), split_line("the-cat", &|_| 1.0, 5.0)); } }
{ let mut result = String::new(); loop { let (head, tail) = split_line(text, char_width, max_len); if head.len() == 0 && tail.len() == 0 { break; } assert!(head.len() > 0, "Line splitter caught in infinite loop"); assert!(tail.len() < text.len(), "Line splitter not shrinking string"); result = result + head; // Must preserve a hard newline at the end if the input string had // one. The else branch checks for the very last char being a newline, // this would be clipped off otherwise. if tail.len() != 0 { result = result + "\n"; } else if text.chars().last() == Some('\n') { result = result + "\n"; } text = tail; } result }
identifier_body
components.rs
use std::convert::{Into}; use std::collections::HashSet; use calx::{Rgba}; use location::Location; use location_set::LocationSet; use {Biome}; use item::{ItemType}; use ability::Ability; use stats::Stats; /// Dummy component to mark prototype objects #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)] pub struct IsPrototype; /// Entity name and appearance. #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Desc { pub name: String, pub icon: usize, pub color: Rgba, } impl Desc { pub fn new<C: Into<Rgba>>(name: &str, icon: usize, color: C) -> Desc { // XXX: Not idiomatic to set this to be called with a non-owned // &str instead of a String, I just want to get away from typing //.to_string() everywhere with the calls that mostly use string // literals. Desc { name: name.to_string(), icon: icon, color: color.into(), } } } /// Map field-of-view and remembered terrain. #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct MapMemory { pub seen: LocationSet, pub remembered: LocationSet, } impl MapMemory { pub fn new() -> MapMemory { MapMemory { seen: LocationSet::new(), remembered: LocationSet::new(), } } } /// Spawning properties for prototype objects. #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Spawn { /// Types of areas where this entity can spawn. pub biome: Biome, /// Weight of this entity in the random sampling distribution. pub commonness: u32, /// Minimum depth where the entity will show up. More powerful entities /// only start showing up in large depths. pub min_depth: i32, pub category: Category, } impl Spawn { pub fn new(category: Category) -> Spawn { Spawn { biome: Biome::Overland, commonness: 1000, min_depth: 1, category: category, } } /// Set the biome(s) where this entity can be spawned. By default entities /// can spawn anywhere. pub fn
(mut self, biome: Biome) -> Spawn { self.biome = biome; self } /// Set the minimum depth where the entity can spawn. More powerful /// entities should only spawn in greater depths. By default this is 1. pub fn depth(mut self, min_depth: i32) -> Spawn { self.min_depth = min_depth; self } /// Set the probability for this entity to spawn. Twice as large is twice /// as common. The default is 1000. pub fn commonness(mut self, commonness: u32) -> Spawn { assert!(commonness > 0); self.commonness = commonness; self } } #[derive(Copy, Clone, Eq, PartialEq, Debug, RustcEncodable, RustcDecodable)] pub enum Category { Mob = 0b1, Consumable = 0b10, Equipment = 0b100, Item = 0b110, Anything = -1, } #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Brain { pub state: BrainState, pub alignment: Alignment } /// Mob behavior state. #[derive(Copy, Clone, Eq, PartialEq, Debug, RustcEncodable, RustcDecodable)] pub enum BrainState { /// AI mob is inactive, but can be startled into action by noise or /// motion. Asleep, /// AI mob is looking for a fight. Hunting, /// AI mob is wandering around. Roaming, /// Mob is under player control. PlayerControl, } /// Used to determine who tries to fight whom. #[derive(Copy, Clone, Eq, PartialEq, Debug, RustcEncodable, RustcDecodable)] pub enum Alignment { Berserk, Phage, Indigenous, Colonist, } /// Damage state component. The default state is undamaged and unarmored. #[derive(Copy, Clone, Debug, Default, RustcEncodable, RustcDecodable)] pub struct Health { /// The more wounds you have, the more hurt you are. How much damage you /// can take before dying depends on entity power level, not described by /// Wounds component. Probably in MobStat or something. pub wounds: i32, /// Armor points get eaten away before you start getting wounds. pub armor: i32, } /// Items can be picked up and carried and they do stuff. #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Item { pub item_type: ItemType, pub ability: Ability, } /// Stats cache is a transient component made from adding up a mob's intrinsic /// stats and the stat bonuses of its equipment and whatever spell effects may /// apply. pub type StatsCache = Option<Stats>; /// Belong to a zone. #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Colonist { pub home_base: String, } impl Colonist { // Bases will be assigned when the unit is deployed. pub fn new() -> Colonist { Colonist { home_base: String::new() } } }
biome
identifier_name
components.rs
use std::convert::{Into}; use std::collections::HashSet; use calx::{Rgba}; use location::Location; use location_set::LocationSet; use {Biome}; use item::{ItemType}; use ability::Ability; use stats::Stats; /// Dummy component to mark prototype objects #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)] pub struct IsPrototype; /// Entity name and appearance. #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Desc { pub name: String, pub icon: usize, pub color: Rgba, } impl Desc { pub fn new<C: Into<Rgba>>(name: &str, icon: usize, color: C) -> Desc { // XXX: Not idiomatic to set this to be called with a non-owned // &str instead of a String, I just want to get away from typing //.to_string() everywhere with the calls that mostly use string // literals. Desc { name: name.to_string(), icon: icon, color: color.into(), } } } /// Map field-of-view and remembered terrain. #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct MapMemory { pub seen: LocationSet, pub remembered: LocationSet, } impl MapMemory { pub fn new() -> MapMemory { MapMemory { seen: LocationSet::new(), remembered: LocationSet::new(), } } } /// Spawning properties for prototype objects. #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Spawn { /// Types of areas where this entity can spawn. pub biome: Biome, /// Weight of this entity in the random sampling distribution. pub commonness: u32, /// Minimum depth where the entity will show up. More powerful entities /// only start showing up in large depths. pub min_depth: i32, pub category: Category, } impl Spawn { pub fn new(category: Category) -> Spawn { Spawn { biome: Biome::Overland, commonness: 1000, min_depth: 1, category: category, } } /// Set the biome(s) where this entity can be spawned. By default entities /// can spawn anywhere. pub fn biome(mut self, biome: Biome) -> Spawn { self.biome = biome; self } /// Set the minimum depth where the entity can spawn. More powerful /// entities should only spawn in greater depths. By default this is 1. pub fn depth(mut self, min_depth: i32) -> Spawn { self.min_depth = min_depth; self } /// Set the probability for this entity to spawn. Twice as large is twice /// as common. The default is 1000. pub fn commonness(mut self, commonness: u32) -> Spawn { assert!(commonness > 0); self.commonness = commonness; self } } #[derive(Copy, Clone, Eq, PartialEq, Debug, RustcEncodable, RustcDecodable)] pub enum Category { Mob = 0b1, Consumable = 0b10, Equipment = 0b100, Item = 0b110, Anything = -1, } #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Brain { pub state: BrainState, pub alignment: Alignment } /// Mob behavior state. #[derive(Copy, Clone, Eq, PartialEq, Debug, RustcEncodable, RustcDecodable)] pub enum BrainState { /// AI mob is inactive, but can be startled into action by noise or /// motion. Asleep, /// AI mob is looking for a fight. Hunting, /// AI mob is wandering around. Roaming, /// Mob is under player control. PlayerControl, } /// Used to determine who tries to fight whom. #[derive(Copy, Clone, Eq, PartialEq, Debug, RustcEncodable, RustcDecodable)] pub enum Alignment { Berserk, Phage, Indigenous, Colonist, } /// Damage state component. The default state is undamaged and unarmored. #[derive(Copy, Clone, Debug, Default, RustcEncodable, RustcDecodable)] pub struct Health { /// The more wounds you have, the more hurt you are. How much damage you /// can take before dying depends on entity power level, not described by /// Wounds component. Probably in MobStat or something. pub wounds: i32, /// Armor points get eaten away before you start getting wounds. pub armor: i32, } /// Items can be picked up and carried and they do stuff.
} /// Stats cache is a transient component made from adding up a mob's intrinsic /// stats and the stat bonuses of its equipment and whatever spell effects may /// apply. pub type StatsCache = Option<Stats>; /// Belong to a zone. #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Colonist { pub home_base: String, } impl Colonist { // Bases will be assigned when the unit is deployed. pub fn new() -> Colonist { Colonist { home_base: String::new() } } }
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Item { pub item_type: ItemType, pub ability: Ability,
random_line_split
components.rs
use std::convert::{Into}; use std::collections::HashSet; use calx::{Rgba}; use location::Location; use location_set::LocationSet; use {Biome}; use item::{ItemType}; use ability::Ability; use stats::Stats; /// Dummy component to mark prototype objects #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)] pub struct IsPrototype; /// Entity name and appearance. #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Desc { pub name: String, pub icon: usize, pub color: Rgba, } impl Desc { pub fn new<C: Into<Rgba>>(name: &str, icon: usize, color: C) -> Desc { // XXX: Not idiomatic to set this to be called with a non-owned // &str instead of a String, I just want to get away from typing //.to_string() everywhere with the calls that mostly use string // literals. Desc { name: name.to_string(), icon: icon, color: color.into(), } } } /// Map field-of-view and remembered terrain. #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct MapMemory { pub seen: LocationSet, pub remembered: LocationSet, } impl MapMemory { pub fn new() -> MapMemory { MapMemory { seen: LocationSet::new(), remembered: LocationSet::new(), } } } /// Spawning properties for prototype objects. #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Spawn { /// Types of areas where this entity can spawn. pub biome: Biome, /// Weight of this entity in the random sampling distribution. pub commonness: u32, /// Minimum depth where the entity will show up. More powerful entities /// only start showing up in large depths. pub min_depth: i32, pub category: Category, } impl Spawn { pub fn new(category: Category) -> Spawn { Spawn { biome: Biome::Overland, commonness: 1000, min_depth: 1, category: category, } } /// Set the biome(s) where this entity can be spawned. By default entities /// can spawn anywhere. pub fn biome(mut self, biome: Biome) -> Spawn { self.biome = biome; self } /// Set the minimum depth where the entity can spawn. More powerful /// entities should only spawn in greater depths. By default this is 1. pub fn depth(mut self, min_depth: i32) -> Spawn
/// Set the probability for this entity to spawn. Twice as large is twice /// as common. The default is 1000. pub fn commonness(mut self, commonness: u32) -> Spawn { assert!(commonness > 0); self.commonness = commonness; self } } #[derive(Copy, Clone, Eq, PartialEq, Debug, RustcEncodable, RustcDecodable)] pub enum Category { Mob = 0b1, Consumable = 0b10, Equipment = 0b100, Item = 0b110, Anything = -1, } #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Brain { pub state: BrainState, pub alignment: Alignment } /// Mob behavior state. #[derive(Copy, Clone, Eq, PartialEq, Debug, RustcEncodable, RustcDecodable)] pub enum BrainState { /// AI mob is inactive, but can be startled into action by noise or /// motion. Asleep, /// AI mob is looking for a fight. Hunting, /// AI mob is wandering around. Roaming, /// Mob is under player control. PlayerControl, } /// Used to determine who tries to fight whom. #[derive(Copy, Clone, Eq, PartialEq, Debug, RustcEncodable, RustcDecodable)] pub enum Alignment { Berserk, Phage, Indigenous, Colonist, } /// Damage state component. The default state is undamaged and unarmored. #[derive(Copy, Clone, Debug, Default, RustcEncodable, RustcDecodable)] pub struct Health { /// The more wounds you have, the more hurt you are. How much damage you /// can take before dying depends on entity power level, not described by /// Wounds component. Probably in MobStat or something. pub wounds: i32, /// Armor points get eaten away before you start getting wounds. pub armor: i32, } /// Items can be picked up and carried and they do stuff. #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Item { pub item_type: ItemType, pub ability: Ability, } /// Stats cache is a transient component made from adding up a mob's intrinsic /// stats and the stat bonuses of its equipment and whatever spell effects may /// apply. pub type StatsCache = Option<Stats>; /// Belong to a zone. #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Colonist { pub home_base: String, } impl Colonist { // Bases will be assigned when the unit is deployed. pub fn new() -> Colonist { Colonist { home_base: String::new() } } }
{ self.min_depth = min_depth; self }
identifier_body
issue13359.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
fn main() { foo(1*(1 as int)); //~^ ERROR: mismatched types: expected `i16`, found `int` (expected `i16`, found `int`) bar(1*(1 as uint)); //~^ ERROR: mismatched types: expected `u32`, found `uint` (expected `u32`, found `uint`) }
// except according to those terms. fn foo(_s: i16) { } fn bar(_s: u32) { }
random_line_split
issue13359.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. fn foo(_s: i16) { } fn bar(_s: u32)
fn main() { foo(1*(1 as int)); //~^ ERROR: mismatched types: expected `i16`, found `int` (expected `i16`, found `int`) bar(1*(1 as uint)); //~^ ERROR: mismatched types: expected `u32`, found `uint` (expected `u32`, found `uint`) }
{ }
identifier_body
issue13359.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. fn
(_s: i16) { } fn bar(_s: u32) { } fn main() { foo(1*(1 as int)); //~^ ERROR: mismatched types: expected `i16`, found `int` (expected `i16`, found `int`) bar(1*(1 as uint)); //~^ ERROR: mismatched types: expected `u32`, found `uint` (expected `u32`, found `uint`) }
foo
identifier_name
test_code_in_readme.rs
use std::{ fs, fs::File, io::{Read, Write}, path::Path, }; use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag}; use flapigen::{CppConfig, Generator, JavaConfig, LanguageConfig}; use tempfile::tempdir; #[test] fn test_code_in_readme() { let _ = env_logger::try_init(); let tests = parse_readme(); let tmp_dir = tempdir().expect("Can not create tmp dir"); println!("{}: tmp_dir {}", file!(), tmp_dir.path().display()); for test in &tests { if test.text.contains("foreigner_class!") { println!("{} with such code:\n{}", test.name, test.text); fs::create_dir_all(&tmp_dir.path().join(&test.name)).unwrap(); let rust_path_src = tmp_dir.path().join(&test.name).join("test.rs.in"); let mut src = File::create(&rust_path_src).expect("can not create test.rs.in"); src.write_all(test.text.as_bytes()).unwrap(); let rust_path_dst = tmp_dir.path().join(&test.name).join("test.rs"); { let java_path = tmp_dir.path().join(&test.name).join("java"); fs::create_dir_all(&java_path).unwrap(); let swig_gen = Generator::new(LanguageConfig::JavaConfig(JavaConfig::new( java_path, "com.example".into(), ))) .with_pointer_target_width(64); swig_gen.expand("flapigen_test_jni", &rust_path_src, &rust_path_dst); } { let cpp_path = tmp_dir.path().join(&test.name).join("c++"); fs::create_dir_all(&cpp_path).unwrap(); let swig_gen = Generator::new(LanguageConfig::CppConfig(CppConfig::new( cpp_path, "com_example".into(), ))) .with_pointer_target_width(64); swig_gen.expand("flapigen_test_c++", &rust_path_src, &rust_path_dst); } } } } struct CodeBlockInfo { is_rust: bool, should_panic: bool, ignore: bool, no_run: bool, is_old_template: bool, template: Option<String>, } #[derive(Debug)] struct Test { name: String, text: String, ignore: bool, no_run: bool, should_panic: bool, template: Option<String>, } fn parse_readme() -> Vec<Test> { let mut file = File::open(Path::new("../README.md")).expect("Can not open README"); let mut cnt = String::new(); file.read_to_string(&mut cnt).unwrap(); let parser = Parser::new(&cnt); let mut test_number = 1; let mut code_buffer = None; let mut tests = Vec::new(); for event in parser { match event { Event::Start(Tag::CodeBlock(ref info)) => { let code_block_info = parse_code_block_info(info); if code_block_info.is_rust { code_buffer = Some(Vec::new()); } } Event::Text(text) => { if let Some(ref mut buf) = code_buffer { buf.push(text.to_string()); } } Event::End(Tag::CodeBlock(ref info)) => { let code_block_info = parse_code_block_info(info); if let Some(buf) = code_buffer.take() { tests.push(Test { name: format!("test_{}", test_number), text: buf.iter().fold(String::new(), |acc, x| acc + x.as_str()), ignore: code_block_info.ignore, no_run: code_block_info.no_run, should_panic: code_block_info.should_panic, template: code_block_info.template, }); test_number += 1; } } _ => (), } } tests } fn parse_code_block_info(info: &CodeBlockKind) -> CodeBlockInfo
match token { "" => {} "rust" => { info.is_rust = true; seen_rust_tags = true } "should_panic" => { info.should_panic = true; seen_rust_tags = true } "ignore" => { info.ignore = true; seen_rust_tags = true } "no_run" => { info.no_run = true; seen_rust_tags = true; } "skeptic-template" => { info.is_old_template = true; seen_rust_tags = true } _ if token.starts_with("skt-") => { info.template = Some(token[4..].to_string()); seen_rust_tags = true; } _ => seen_other_tags = true, } } info.is_rust &=!seen_other_tags || seen_rust_tags; info }
{ // Same as rustdoc let info: &str = match info { CodeBlockKind::Indented => "", CodeBlockKind::Fenced(x) => x.as_ref(), }; let tokens = info.split(|c: char| !(c == '_' || c == '-' || c.is_alphanumeric())); let mut seen_rust_tags = false; let mut seen_other_tags = false; let mut info = CodeBlockInfo { is_rust: false, should_panic: false, ignore: false, no_run: false, is_old_template: false, template: None, }; for token in tokens {
identifier_body
test_code_in_readme.rs
use std::{ fs, fs::File, io::{Read, Write}, path::Path, }; use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag}; use flapigen::{CppConfig, Generator, JavaConfig, LanguageConfig}; use tempfile::tempdir; #[test] fn test_code_in_readme() { let _ = env_logger::try_init(); let tests = parse_readme(); let tmp_dir = tempdir().expect("Can not create tmp dir"); println!("{}: tmp_dir {}", file!(), tmp_dir.path().display()); for test in &tests { if test.text.contains("foreigner_class!") { println!("{} with such code:\n{}", test.name, test.text); fs::create_dir_all(&tmp_dir.path().join(&test.name)).unwrap(); let rust_path_src = tmp_dir.path().join(&test.name).join("test.rs.in"); let mut src = File::create(&rust_path_src).expect("can not create test.rs.in"); src.write_all(test.text.as_bytes()).unwrap(); let rust_path_dst = tmp_dir.path().join(&test.name).join("test.rs"); { let java_path = tmp_dir.path().join(&test.name).join("java"); fs::create_dir_all(&java_path).unwrap(); let swig_gen = Generator::new(LanguageConfig::JavaConfig(JavaConfig::new( java_path, "com.example".into(), ))) .with_pointer_target_width(64); swig_gen.expand("flapigen_test_jni", &rust_path_src, &rust_path_dst); } { let cpp_path = tmp_dir.path().join(&test.name).join("c++"); fs::create_dir_all(&cpp_path).unwrap(); let swig_gen = Generator::new(LanguageConfig::CppConfig(CppConfig::new( cpp_path, "com_example".into(), ))) .with_pointer_target_width(64); swig_gen.expand("flapigen_test_c++", &rust_path_src, &rust_path_dst); } } } } struct CodeBlockInfo { is_rust: bool, should_panic: bool, ignore: bool, no_run: bool, is_old_template: bool, template: Option<String>, } #[derive(Debug)] struct Test { name: String, text: String, ignore: bool, no_run: bool, should_panic: bool, template: Option<String>, } fn parse_readme() -> Vec<Test> { let mut file = File::open(Path::new("../README.md")).expect("Can not open README"); let mut cnt = String::new(); file.read_to_string(&mut cnt).unwrap(); let parser = Parser::new(&cnt); let mut test_number = 1; let mut code_buffer = None; let mut tests = Vec::new(); for event in parser { match event { Event::Start(Tag::CodeBlock(ref info)) => { let code_block_info = parse_code_block_info(info); if code_block_info.is_rust { code_buffer = Some(Vec::new()); } } Event::Text(text) => { if let Some(ref mut buf) = code_buffer { buf.push(text.to_string()); } } Event::End(Tag::CodeBlock(ref info)) => { let code_block_info = parse_code_block_info(info); if let Some(buf) = code_buffer.take() { tests.push(Test { name: format!("test_{}", test_number), text: buf.iter().fold(String::new(), |acc, x| acc + x.as_str()), ignore: code_block_info.ignore, no_run: code_block_info.no_run, should_panic: code_block_info.should_panic, template: code_block_info.template, }); test_number += 1; } } _ => (), } } tests } fn
(info: &CodeBlockKind) -> CodeBlockInfo { // Same as rustdoc let info: &str = match info { CodeBlockKind::Indented => "", CodeBlockKind::Fenced(x) => x.as_ref(), }; let tokens = info.split(|c: char|!(c == '_' || c == '-' || c.is_alphanumeric())); let mut seen_rust_tags = false; let mut seen_other_tags = false; let mut info = CodeBlockInfo { is_rust: false, should_panic: false, ignore: false, no_run: false, is_old_template: false, template: None, }; for token in tokens { match token { "" => {} "rust" => { info.is_rust = true; seen_rust_tags = true } "should_panic" => { info.should_panic = true; seen_rust_tags = true } "ignore" => { info.ignore = true; seen_rust_tags = true } "no_run" => { info.no_run = true; seen_rust_tags = true; } "skeptic-template" => { info.is_old_template = true; seen_rust_tags = true } _ if token.starts_with("skt-") => { info.template = Some(token[4..].to_string()); seen_rust_tags = true; } _ => seen_other_tags = true, } } info.is_rust &=!seen_other_tags || seen_rust_tags; info }
parse_code_block_info
identifier_name
test_code_in_readme.rs
use std::{ fs, fs::File, io::{Read, Write}, path::Path, }; use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag}; use flapigen::{CppConfig, Generator, JavaConfig, LanguageConfig}; use tempfile::tempdir; #[test] fn test_code_in_readme() { let _ = env_logger::try_init(); let tests = parse_readme(); let tmp_dir = tempdir().expect("Can not create tmp dir"); println!("{}: tmp_dir {}", file!(), tmp_dir.path().display()); for test in &tests { if test.text.contains("foreigner_class!") { println!("{} with such code:\n{}", test.name, test.text); fs::create_dir_all(&tmp_dir.path().join(&test.name)).unwrap(); let rust_path_src = tmp_dir.path().join(&test.name).join("test.rs.in"); let mut src = File::create(&rust_path_src).expect("can not create test.rs.in"); src.write_all(test.text.as_bytes()).unwrap(); let rust_path_dst = tmp_dir.path().join(&test.name).join("test.rs"); { let java_path = tmp_dir.path().join(&test.name).join("java"); fs::create_dir_all(&java_path).unwrap(); let swig_gen = Generator::new(LanguageConfig::JavaConfig(JavaConfig::new( java_path, "com.example".into(), ))) .with_pointer_target_width(64); swig_gen.expand("flapigen_test_jni", &rust_path_src, &rust_path_dst); } { let cpp_path = tmp_dir.path().join(&test.name).join("c++"); fs::create_dir_all(&cpp_path).unwrap(); let swig_gen = Generator::new(LanguageConfig::CppConfig(CppConfig::new( cpp_path, "com_example".into(), ))) .with_pointer_target_width(64); swig_gen.expand("flapigen_test_c++", &rust_path_src, &rust_path_dst); } } } } struct CodeBlockInfo { is_rust: bool, should_panic: bool, ignore: bool, no_run: bool, is_old_template: bool, template: Option<String>, } #[derive(Debug)] struct Test { name: String, text: String, ignore: bool, no_run: bool, should_panic: bool, template: Option<String>, } fn parse_readme() -> Vec<Test> { let mut file = File::open(Path::new("../README.md")).expect("Can not open README"); let mut cnt = String::new(); file.read_to_string(&mut cnt).unwrap(); let parser = Parser::new(&cnt); let mut test_number = 1; let mut code_buffer = None;
let mut tests = Vec::new(); for event in parser { match event { Event::Start(Tag::CodeBlock(ref info)) => { let code_block_info = parse_code_block_info(info); if code_block_info.is_rust { code_buffer = Some(Vec::new()); } } Event::Text(text) => { if let Some(ref mut buf) = code_buffer { buf.push(text.to_string()); } } Event::End(Tag::CodeBlock(ref info)) => { let code_block_info = parse_code_block_info(info); if let Some(buf) = code_buffer.take() { tests.push(Test { name: format!("test_{}", test_number), text: buf.iter().fold(String::new(), |acc, x| acc + x.as_str()), ignore: code_block_info.ignore, no_run: code_block_info.no_run, should_panic: code_block_info.should_panic, template: code_block_info.template, }); test_number += 1; } } _ => (), } } tests } fn parse_code_block_info(info: &CodeBlockKind) -> CodeBlockInfo { // Same as rustdoc let info: &str = match info { CodeBlockKind::Indented => "", CodeBlockKind::Fenced(x) => x.as_ref(), }; let tokens = info.split(|c: char|!(c == '_' || c == '-' || c.is_alphanumeric())); let mut seen_rust_tags = false; let mut seen_other_tags = false; let mut info = CodeBlockInfo { is_rust: false, should_panic: false, ignore: false, no_run: false, is_old_template: false, template: None, }; for token in tokens { match token { "" => {} "rust" => { info.is_rust = true; seen_rust_tags = true } "should_panic" => { info.should_panic = true; seen_rust_tags = true } "ignore" => { info.ignore = true; seen_rust_tags = true } "no_run" => { info.no_run = true; seen_rust_tags = true; } "skeptic-template" => { info.is_old_template = true; seen_rust_tags = true } _ if token.starts_with("skt-") => { info.template = Some(token[4..].to_string()); seen_rust_tags = true; } _ => seen_other_tags = true, } } info.is_rust &=!seen_other_tags || seen_rust_tags; info }
random_line_split
frame.rs
use std::collections::HashMap; use std::rc::Rc; use std::cell::RefCell; use super::super::varstack::VectorVarStack; use super::super::objects::{ObjectRef, Code}; use super::instructions::{Instruction, InstructionDecoder}; #[derive(Debug)] pub enum Block { Loop(usize, usize), // begin, end TryExcept(usize, usize), // begin, end ExceptPopGoto(ObjectRef, usize, usize), // If an exception matchs the first arg matches, pop n elements from the stack and set the PC to the second arg } #[derive(Debug)] pub struct Frame { pub object: ObjectRef, pub var_stack: VectorVarStack<ObjectRef>, pub block_stack: Vec<Block>, pub locals: Rc<RefCell<HashMap<String, ObjectRef>>>, pub instructions: Vec<Instruction>, pub code: Code, pub program_counter: usize, } impl Frame { pub fn
(object: ObjectRef, code: Code, locals: Rc<RefCell<HashMap<String, ObjectRef>>>) -> Frame { let instructions: Vec<Instruction> = InstructionDecoder::new(code.code.iter()).into_iter().collect(); Frame { object: object, var_stack: VectorVarStack::new(), block_stack: Vec::new(), locals: locals, instructions: instructions, code: code, program_counter: 0, } } }
new
identifier_name
frame.rs
use std::collections::HashMap; use std::rc::Rc; use std::cell::RefCell; use super::super::varstack::VectorVarStack; use super::super::objects::{ObjectRef, Code}; use super::instructions::{Instruction, InstructionDecoder}; #[derive(Debug)] pub enum Block { Loop(usize, usize), // begin, end TryExcept(usize, usize), // begin, end ExceptPopGoto(ObjectRef, usize, usize), // If an exception matchs the first arg matches, pop n elements from the stack and set the PC to the second arg } #[derive(Debug)] pub struct Frame { pub object: ObjectRef, pub var_stack: VectorVarStack<ObjectRef>,
} impl Frame { pub fn new(object: ObjectRef, code: Code, locals: Rc<RefCell<HashMap<String, ObjectRef>>>) -> Frame { let instructions: Vec<Instruction> = InstructionDecoder::new(code.code.iter()).into_iter().collect(); Frame { object: object, var_stack: VectorVarStack::new(), block_stack: Vec::new(), locals: locals, instructions: instructions, code: code, program_counter: 0, } } }
pub block_stack: Vec<Block>, pub locals: Rc<RefCell<HashMap<String, ObjectRef>>>, pub instructions: Vec<Instruction>, pub code: Code, pub program_counter: usize,
random_line_split
frame.rs
use std::collections::HashMap; use std::rc::Rc; use std::cell::RefCell; use super::super::varstack::VectorVarStack; use super::super::objects::{ObjectRef, Code}; use super::instructions::{Instruction, InstructionDecoder}; #[derive(Debug)] pub enum Block { Loop(usize, usize), // begin, end TryExcept(usize, usize), // begin, end ExceptPopGoto(ObjectRef, usize, usize), // If an exception matchs the first arg matches, pop n elements from the stack and set the PC to the second arg } #[derive(Debug)] pub struct Frame { pub object: ObjectRef, pub var_stack: VectorVarStack<ObjectRef>, pub block_stack: Vec<Block>, pub locals: Rc<RefCell<HashMap<String, ObjectRef>>>, pub instructions: Vec<Instruction>, pub code: Code, pub program_counter: usize, } impl Frame { pub fn new(object: ObjectRef, code: Code, locals: Rc<RefCell<HashMap<String, ObjectRef>>>) -> Frame
}
{ let instructions: Vec<Instruction> = InstructionDecoder::new(code.code.iter()).into_iter().collect(); Frame { object: object, var_stack: VectorVarStack::new(), block_stack: Vec::new(), locals: locals, instructions: instructions, code: code, program_counter: 0, } }
identifier_body
main.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(std_misc)] use std::dynamic_lib::DynamicLibrary; use std::path::Path; pub fn main()
{ unsafe { let path = Path::new("libdylib.so"); let a = DynamicLibrary::open(Some(&path)).unwrap(); assert!(a.symbol::<isize>("fun1").is_ok()); assert!(a.symbol::<isize>("fun2").is_err()); assert!(a.symbol::<isize>("fun3").is_err()); assert!(a.symbol::<isize>("fun4").is_ok()); assert!(a.symbol::<isize>("fun5").is_ok()); } }
identifier_body
main.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(std_misc)] use std::dynamic_lib::DynamicLibrary; use std::path::Path; pub fn main() { unsafe { let path = Path::new("libdylib.so"); let a = DynamicLibrary::open(Some(&path)).unwrap(); assert!(a.symbol::<isize>("fun1").is_ok()); assert!(a.symbol::<isize>("fun2").is_err()); assert!(a.symbol::<isize>("fun3").is_err()); assert!(a.symbol::<isize>("fun4").is_ok()); assert!(a.symbol::<isize>("fun5").is_ok());
}
}
random_line_split
main.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(std_misc)] use std::dynamic_lib::DynamicLibrary; use std::path::Path; pub fn
() { unsafe { let path = Path::new("libdylib.so"); let a = DynamicLibrary::open(Some(&path)).unwrap(); assert!(a.symbol::<isize>("fun1").is_ok()); assert!(a.symbol::<isize>("fun2").is_err()); assert!(a.symbol::<isize>("fun3").is_err()); assert!(a.symbol::<isize>("fun4").is_ok()); assert!(a.symbol::<isize>("fun5").is_ok()); } }
main
identifier_name
cache.rs
use consumer::forced_string; use std::{fs, path, process}; #[derive(Clone)] pub struct Cache { build: path::PathBuf, cache: path::PathBuf, folders: Vec<String>, } impl Cache { pub fn new(build: path::PathBuf, cache: path::PathBuf) -> Cache { let folders = vec![ "target/debug", "target/release", "target/aarch64-unknown-linux-gnu", "target/arm-unknown-linux-gnueabi", "target/arm-unknown-linux-gnueabihf", "target/armv7-unknown-linux-gnueabihf", "target/i686-unknown-linux-gnu", "target/i686-unknown-linux-musl", "target/x86_64-unknown-linux-gnu", "target/x86_64-unknwon-linux-musl", "target/benchcmp/target", "fuzz/target", "fuzz/corpus", ]; let folders = folders.iter().map(|&x| x.to_owned()).collect(); Cache { build: build, cache: cache, folders: folders, } } pub fn save(&self) -> Result<(), ()> { save(self.build.as_path(), self.cache.as_path(), &self.folders) } pub fn load(&self) -> Result<(), ()> { load(self.build.as_path(), self.cache.as_path(), &self.folders) } pub fn set_cache(&mut self, path: path::PathBuf) { self.cache = path; } } // save the cache directories fn save(build: &path::Path, cache: &path::Path, folders: &[String]) -> Result<(), ()> { info!("cache save: start"); for folder in folders { let _ = rsync(folder, build, cache); } info!("cache save: complete"); Ok(()) } // load the cache into the build dir fn load(build: &path::Path, cache: &path::Path, folders: &[String]) -> Result<(), ()> { info!("cache load: start"); for folder in folders { let _ = rsync(folder, cache, build); } info!("cache load: complete"); Ok(()) } // call rsync for subfolder path fn
(path: &str, source: &path::Path, destination: &path::Path) -> Result<(), &'static str> { let mut dst = destination.to_path_buf(); dst.push(path); let _ = fs::create_dir_all(dst.as_path()); dst.pop(); let output = process::Command::new("rsync") .arg("-aPc") .arg("--delete") .arg(path) .arg(dst.as_path().to_str().unwrap()) .current_dir(source) .output() .map_err(|_| "could not execute rsync")?; trace!("stdout:\n{}", forced_string(output.stdout)); trace!("stderr:\n{}", forced_string(output.stderr)); if output.status.success() { debug!("rsync {}: ok", path); Ok(()) } else { debug!("rsync {}: fail", path); Err("rsync failed") } }
rsync
identifier_name
cache.rs
use consumer::forced_string; use std::{fs, path, process}; #[derive(Clone)] pub struct Cache { build: path::PathBuf, cache: path::PathBuf, folders: Vec<String>, } impl Cache { pub fn new(build: path::PathBuf, cache: path::PathBuf) -> Cache { let folders = vec![ "target/debug", "target/release", "target/aarch64-unknown-linux-gnu", "target/arm-unknown-linux-gnueabi", "target/arm-unknown-linux-gnueabihf", "target/armv7-unknown-linux-gnueabihf", "target/i686-unknown-linux-gnu", "target/i686-unknown-linux-musl", "target/x86_64-unknown-linux-gnu", "target/x86_64-unknwon-linux-musl", "target/benchcmp/target", "fuzz/target", "fuzz/corpus", ]; let folders = folders.iter().map(|&x| x.to_owned()).collect(); Cache { build: build, cache: cache, folders: folders, } } pub fn save(&self) -> Result<(), ()> { save(self.build.as_path(), self.cache.as_path(), &self.folders) } pub fn load(&self) -> Result<(), ()> { load(self.build.as_path(), self.cache.as_path(), &self.folders) } pub fn set_cache(&mut self, path: path::PathBuf) { self.cache = path; } } // save the cache directories fn save(build: &path::Path, cache: &path::Path, folders: &[String]) -> Result<(), ()> { info!("cache save: start"); for folder in folders { let _ = rsync(folder, build, cache); } info!("cache save: complete"); Ok(()) } // load the cache into the build dir fn load(build: &path::Path, cache: &path::Path, folders: &[String]) -> Result<(), ()> { info!("cache load: start"); for folder in folders { let _ = rsync(folder, cache, build); } info!("cache load: complete"); Ok(()) } // call rsync for subfolder path fn rsync(path: &str, source: &path::Path, destination: &path::Path) -> Result<(), &'static str> { let mut dst = destination.to_path_buf(); dst.push(path); let _ = fs::create_dir_all(dst.as_path()); dst.pop(); let output = process::Command::new("rsync") .arg("-aPc") .arg("--delete") .arg(path) .arg(dst.as_path().to_str().unwrap()) .current_dir(source) .output() .map_err(|_| "could not execute rsync")?; trace!("stdout:\n{}", forced_string(output.stdout)); trace!("stderr:\n{}", forced_string(output.stderr)); if output.status.success() { debug!("rsync {}: ok", path); Ok(()) } else
}
{ debug!("rsync {}: fail", path); Err("rsync failed") }
conditional_block
cache.rs
use consumer::forced_string; use std::{fs, path, process}; #[derive(Clone)] pub struct Cache { build: path::PathBuf, cache: path::PathBuf, folders: Vec<String>, } impl Cache { pub fn new(build: path::PathBuf, cache: path::PathBuf) -> Cache { let folders = vec![ "target/debug", "target/release", "target/aarch64-unknown-linux-gnu", "target/arm-unknown-linux-gnueabi", "target/arm-unknown-linux-gnueabihf", "target/armv7-unknown-linux-gnueabihf", "target/i686-unknown-linux-gnu", "target/i686-unknown-linux-musl", "target/x86_64-unknown-linux-gnu", "target/x86_64-unknwon-linux-musl", "target/benchcmp/target", "fuzz/target", "fuzz/corpus", ]; let folders = folders.iter().map(|&x| x.to_owned()).collect(); Cache { build: build, cache: cache, folders: folders, } } pub fn save(&self) -> Result<(), ()> { save(self.build.as_path(), self.cache.as_path(), &self.folders) } pub fn load(&self) -> Result<(), ()> { load(self.build.as_path(), self.cache.as_path(), &self.folders) } pub fn set_cache(&mut self, path: path::PathBuf) { self.cache = path; } } // save the cache directories fn save(build: &path::Path, cache: &path::Path, folders: &[String]) -> Result<(), ()> { info!("cache save: start"); for folder in folders { let _ = rsync(folder, build, cache); } info!("cache save: complete"); Ok(()) } // load the cache into the build dir fn load(build: &path::Path, cache: &path::Path, folders: &[String]) -> Result<(), ()> { info!("cache load: start"); for folder in folders { let _ = rsync(folder, cache, build); } info!("cache load: complete"); Ok(()) } // call rsync for subfolder path fn rsync(path: &str, source: &path::Path, destination: &path::Path) -> Result<(), &'static str> { let mut dst = destination.to_path_buf(); dst.push(path); let _ = fs::create_dir_all(dst.as_path()); dst.pop(); let output = process::Command::new("rsync") .arg("-aPc") .arg("--delete") .arg(path) .arg(dst.as_path().to_str().unwrap()) .current_dir(source) .output() .map_err(|_| "could not execute rsync")?; trace!("stdout:\n{}", forced_string(output.stdout)); trace!("stderr:\n{}", forced_string(output.stderr));
Ok(()) } else { debug!("rsync {}: fail", path); Err("rsync failed") } }
if output.status.success() { debug!("rsync {}: ok", path);
random_line_split
kindck-impl-type-params.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Issue #14061: tests the interaction between generic implementation // parameter bounds and trait objects. #![feature(box_syntax)] use std::marker; struct S<T>(marker::PhantomData<T>); trait Gettable<T> { fn get(&self) -> T { panic!() } } impl<T: Send + Copy +'static> Gettable<T> for S<T> {} fn f<T>(val: T) { let t: S<T> = S(marker::PhantomData); let a = &t as &Gettable<T>; //~^ ERROR the trait `core::marker::Send` is not implemented //~^^ ERROR the trait `core::marker::Copy` is not implemented //~^^^ ERROR the parameter type `T` may not live long enough } fn g<T>(val: T) { let t: S<T> = S(marker::PhantomData); let a: &Gettable<T> = &t; //~^ ERROR the trait `core::marker::Send` is not implemented //~^^ ERROR the trait `core::marker::Copy` is not implemented } fn foo<'a>() { let t: S<&'a isize> = S(marker::PhantomData); let a = &t as &Gettable<&'a isize>; //~^ ERROR does not fulfill } fn foo2<'a>() { let t: Box<S<String>> = box S(marker::PhantomData); let a = t as Box<Gettable<String>>; //~^ ERROR the trait `core::marker::Copy` is not implemented } fn foo3<'a>()
fn main() { }
{ let t: Box<S<String>> = box S(marker::PhantomData); let a: Box<Gettable<String>> = t; //~^ ERROR the trait `core::marker::Copy` is not implemented }
identifier_body
kindck-impl-type-params.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Issue #14061: tests the interaction between generic implementation // parameter bounds and trait objects. #![feature(box_syntax)] use std::marker; struct S<T>(marker::PhantomData<T>); trait Gettable<T> { fn
(&self) -> T { panic!() } } impl<T: Send + Copy +'static> Gettable<T> for S<T> {} fn f<T>(val: T) { let t: S<T> = S(marker::PhantomData); let a = &t as &Gettable<T>; //~^ ERROR the trait `core::marker::Send` is not implemented //~^^ ERROR the trait `core::marker::Copy` is not implemented //~^^^ ERROR the parameter type `T` may not live long enough } fn g<T>(val: T) { let t: S<T> = S(marker::PhantomData); let a: &Gettable<T> = &t; //~^ ERROR the trait `core::marker::Send` is not implemented //~^^ ERROR the trait `core::marker::Copy` is not implemented } fn foo<'a>() { let t: S<&'a isize> = S(marker::PhantomData); let a = &t as &Gettable<&'a isize>; //~^ ERROR does not fulfill } fn foo2<'a>() { let t: Box<S<String>> = box S(marker::PhantomData); let a = t as Box<Gettable<String>>; //~^ ERROR the trait `core::marker::Copy` is not implemented } fn foo3<'a>() { let t: Box<S<String>> = box S(marker::PhantomData); let a: Box<Gettable<String>> = t; //~^ ERROR the trait `core::marker::Copy` is not implemented } fn main() { }
get
identifier_name
kindck-impl-type-params.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Issue #14061: tests the interaction between generic implementation // parameter bounds and trait objects. #![feature(box_syntax)] use std::marker; struct S<T>(marker::PhantomData<T>); trait Gettable<T> { fn get(&self) -> T { panic!() } } impl<T: Send + Copy +'static> Gettable<T> for S<T> {} fn f<T>(val: T) { let t: S<T> = S(marker::PhantomData); let a = &t as &Gettable<T>; //~^ ERROR the trait `core::marker::Send` is not implemented //~^^ ERROR the trait `core::marker::Copy` is not implemented //~^^^ ERROR the parameter type `T` may not live long enough } fn g<T>(val: T) { let t: S<T> = S(marker::PhantomData); let a: &Gettable<T> = &t; //~^ ERROR the trait `core::marker::Send` is not implemented
fn foo<'a>() { let t: S<&'a isize> = S(marker::PhantomData); let a = &t as &Gettable<&'a isize>; //~^ ERROR does not fulfill } fn foo2<'a>() { let t: Box<S<String>> = box S(marker::PhantomData); let a = t as Box<Gettable<String>>; //~^ ERROR the trait `core::marker::Copy` is not implemented } fn foo3<'a>() { let t: Box<S<String>> = box S(marker::PhantomData); let a: Box<Gettable<String>> = t; //~^ ERROR the trait `core::marker::Copy` is not implemented } fn main() { }
//~^^ ERROR the trait `core::marker::Copy` is not implemented }
random_line_split
negative_literal_mover.rs
//! This module literals in a GDL description such that all variables in a negative literal (i.e. a //! `distinct` or `not` literal) have been seen in positive literals occurring before that //! `negative` literal. The resulting GDL should be semantically equivalent. To see why this is //! necessary, see section 13.6 [here](http://logic.stanford.edu/ggp/chapters/chapter_13.html). For //! an example test case of where this makes a difference, see the `test_beginning_distinct` test //! case in this file. use std::collections::HashSet; use prover::deorer; use gdl::{Description, Rule, Variable, Literal, Term}; use gdl::Clause::RuleClause; use gdl::Literal::{OrLit, NotLit, DistinctLit, RelLit}; use gdl::Term::{VarTerm, FuncTerm}; /// Reorders a game description such that all negative literals occur after all their variables /// have been seen in a positive literal pub fn reorder(desc: Description) -> Description { let desc = deorer::deor(desc); let mut new_clauses = Vec::new(); for clause in desc.clauses { match clause { RuleClause(r) => { new_clauses.push(reorder_rule(r).into()); } _ => new_clauses.push(clause) } } Description::new(new_clauses) } fn reorder_rule(mut r: Rule) -> Rule {
let body = &mut *r.body; body.swap(index, swap_index); } None => break } } r } fn find_neg_lit_index(body: &[Literal]) -> Option<usize> { let mut seen_vars = HashSet::new(); for (i, lit) in body.iter().enumerate() { match lit { l @ &DistinctLit(_) | l @ &NotLit(_) => { if!seen_all_vars(&seen_vars, l) { return Some(i); } } l @ &RelLit(_) => { seen_vars.extend(get_vars(l)); } &OrLit(_) => panic!("Or literals were removed"), _ => () } } None } fn find_candidate_index(body: &[Literal], neg_lit: &Literal) -> Option<usize> { let mut seen_vars = HashSet::new(); for (i, lit) in body.iter().enumerate() { match lit { l @ &RelLit(_) => { seen_vars.extend(get_vars(l)); if seen_all_vars(&seen_vars, neg_lit) { return Some(i) } }, &OrLit(_) => panic!("Or literals were removed"), _ => () } } None } fn get_vars(l: &Literal) -> Vec<Variable> { let mut res = Vec::new(); match l { &RelLit(ref r) => { for term in r.args.iter() { res.extend(get_vars_from_term(term)); } res }, &NotLit(ref not) => get_vars(&not.lit), &DistinctLit(ref distinct) => { res.extend(get_vars_from_term(&distinct.term1)); res.extend(get_vars_from_term(&distinct.term2)); res }, &OrLit(_) => panic!("Or literals were removed"), _ => res } } fn get_vars_from_term(t: &Term) -> Vec<Variable> { match t { &VarTerm(ref v) => vec![(*v).clone()], &FuncTerm(ref f) => { let mut res = Vec::new(); for t in f.args.iter() { res.extend(get_vars_from_term(t)); } res } _ => Vec::new() } } fn seen_all_vars(seen_vars: &HashSet<Variable>, l: &Literal) -> bool { let vars = get_vars(l); for var in vars { if!seen_vars.contains(&var) { return false; } } true } #[cfg(test)] mod test { use {gdl, State, Role}; use super::reorder; use prover::Prover; use prover::query_builder; #[test] fn test_distinct() { let desc = gdl::parse("(<= p (distinct?a?b) (q?a?b))"); let expected = gdl::parse("(<= p (q?a?b) (distinct?a?b))"); assert_eq!(reorder(desc), expected); } #[test] fn test_not_function() { let desc = gdl::parse("(<= p (not (foo (bar?a))) (q?a))"); let expected = gdl::parse("(<= p (q?a) (not (foo (bar?a))))"); assert_eq!(reorder(desc), expected); } #[test] fn test_not() { let desc = gdl::parse("(<= p (not (foo?a)) (q?a))"); let expected = gdl::parse("(<= p (q?a) (not (foo?a)))"); assert_eq!(reorder(desc), expected); } #[test] fn test_multiple_swap() { let desc = gdl::parse("(<= p (not (bar?a)) (not (foo?a?b)) (q?a) (distinct?a?b) \ (q?b) (q?c))"); let expected = gdl::parse("(<= p (q?a) (q?b) (not (bar?a)) (distinct?a?b) \ (not (foo?a?b)) (q?c))"); assert_eq!(reorder(desc), expected); } #[test] fn test_no_move() { let desc = gdl::parse("(<= p (q?a) (not (foo?a)))"); assert_eq!(reorder(desc.clone()), desc); let desc = gdl::parse("(<= p (q?a) (distinct?a))"); assert_eq!(reorder(desc.clone()), desc); } #[test] fn test_beginning_distinct() { let gdl = "(role you) \ (<= (foo?a?b) \ (distinct?a?b) \ (p?a) \ (q?b)) \ (p a) \ (p b) \ (q a) \ (q b) \ (<= (legal you (do?a?b)) \ (foo?a?b)) \ (next win) \ (<= terminal \ (true win)) \ (goal you 100)"; let desc = gdl::parse(gdl); let prover = Prover::new(desc); let moves = prover.ask(query_builder::legal_query(&Role::new("you")), &State::new()).into_moves(); // Without the reordering, there are four legal moves, which is incorrect assert_eq!(moves.len(), 2); } }
loop { match find_neg_lit_index(&*r.body) { Some(index) => { let swap_index = find_candidate_index(&*r.body, &r.body[index]) .expect("No candidate index found");
random_line_split
negative_literal_mover.rs
//! This module literals in a GDL description such that all variables in a negative literal (i.e. a //! `distinct` or `not` literal) have been seen in positive literals occurring before that //! `negative` literal. The resulting GDL should be semantically equivalent. To see why this is //! necessary, see section 13.6 [here](http://logic.stanford.edu/ggp/chapters/chapter_13.html). For //! an example test case of where this makes a difference, see the `test_beginning_distinct` test //! case in this file. use std::collections::HashSet; use prover::deorer; use gdl::{Description, Rule, Variable, Literal, Term}; use gdl::Clause::RuleClause; use gdl::Literal::{OrLit, NotLit, DistinctLit, RelLit}; use gdl::Term::{VarTerm, FuncTerm}; /// Reorders a game description such that all negative literals occur after all their variables /// have been seen in a positive literal pub fn reorder(desc: Description) -> Description { let desc = deorer::deor(desc); let mut new_clauses = Vec::new(); for clause in desc.clauses { match clause { RuleClause(r) =>
_ => new_clauses.push(clause) } } Description::new(new_clauses) } fn reorder_rule(mut r: Rule) -> Rule { loop { match find_neg_lit_index(&*r.body) { Some(index) => { let swap_index = find_candidate_index(&*r.body, &r.body[index]) .expect("No candidate index found"); let body = &mut *r.body; body.swap(index, swap_index); } None => break } } r } fn find_neg_lit_index(body: &[Literal]) -> Option<usize> { let mut seen_vars = HashSet::new(); for (i, lit) in body.iter().enumerate() { match lit { l @ &DistinctLit(_) | l @ &NotLit(_) => { if!seen_all_vars(&seen_vars, l) { return Some(i); } } l @ &RelLit(_) => { seen_vars.extend(get_vars(l)); } &OrLit(_) => panic!("Or literals were removed"), _ => () } } None } fn find_candidate_index(body: &[Literal], neg_lit: &Literal) -> Option<usize> { let mut seen_vars = HashSet::new(); for (i, lit) in body.iter().enumerate() { match lit { l @ &RelLit(_) => { seen_vars.extend(get_vars(l)); if seen_all_vars(&seen_vars, neg_lit) { return Some(i) } }, &OrLit(_) => panic!("Or literals were removed"), _ => () } } None } fn get_vars(l: &Literal) -> Vec<Variable> { let mut res = Vec::new(); match l { &RelLit(ref r) => { for term in r.args.iter() { res.extend(get_vars_from_term(term)); } res }, &NotLit(ref not) => get_vars(&not.lit), &DistinctLit(ref distinct) => { res.extend(get_vars_from_term(&distinct.term1)); res.extend(get_vars_from_term(&distinct.term2)); res }, &OrLit(_) => panic!("Or literals were removed"), _ => res } } fn get_vars_from_term(t: &Term) -> Vec<Variable> { match t { &VarTerm(ref v) => vec![(*v).clone()], &FuncTerm(ref f) => { let mut res = Vec::new(); for t in f.args.iter() { res.extend(get_vars_from_term(t)); } res } _ => Vec::new() } } fn seen_all_vars(seen_vars: &HashSet<Variable>, l: &Literal) -> bool { let vars = get_vars(l); for var in vars { if!seen_vars.contains(&var) { return false; } } true } #[cfg(test)] mod test { use {gdl, State, Role}; use super::reorder; use prover::Prover; use prover::query_builder; #[test] fn test_distinct() { let desc = gdl::parse("(<= p (distinct?a?b) (q?a?b))"); let expected = gdl::parse("(<= p (q?a?b) (distinct?a?b))"); assert_eq!(reorder(desc), expected); } #[test] fn test_not_function() { let desc = gdl::parse("(<= p (not (foo (bar?a))) (q?a))"); let expected = gdl::parse("(<= p (q?a) (not (foo (bar?a))))"); assert_eq!(reorder(desc), expected); } #[test] fn test_not() { let desc = gdl::parse("(<= p (not (foo?a)) (q?a))"); let expected = gdl::parse("(<= p (q?a) (not (foo?a)))"); assert_eq!(reorder(desc), expected); } #[test] fn test_multiple_swap() { let desc = gdl::parse("(<= p (not (bar?a)) (not (foo?a?b)) (q?a) (distinct?a?b) \ (q?b) (q?c))"); let expected = gdl::parse("(<= p (q?a) (q?b) (not (bar?a)) (distinct?a?b) \ (not (foo?a?b)) (q?c))"); assert_eq!(reorder(desc), expected); } #[test] fn test_no_move() { let desc = gdl::parse("(<= p (q?a) (not (foo?a)))"); assert_eq!(reorder(desc.clone()), desc); let desc = gdl::parse("(<= p (q?a) (distinct?a))"); assert_eq!(reorder(desc.clone()), desc); } #[test] fn test_beginning_distinct() { let gdl = "(role you) \ (<= (foo?a?b) \ (distinct?a?b) \ (p?a) \ (q?b)) \ (p a) \ (p b) \ (q a) \ (q b) \ (<= (legal you (do?a?b)) \ (foo?a?b)) \ (next win) \ (<= terminal \ (true win)) \ (goal you 100)"; let desc = gdl::parse(gdl); let prover = Prover::new(desc); let moves = prover.ask(query_builder::legal_query(&Role::new("you")), &State::new()).into_moves(); // Without the reordering, there are four legal moves, which is incorrect assert_eq!(moves.len(), 2); } }
{ new_clauses.push(reorder_rule(r).into()); }
conditional_block
negative_literal_mover.rs
//! This module literals in a GDL description such that all variables in a negative literal (i.e. a //! `distinct` or `not` literal) have been seen in positive literals occurring before that //! `negative` literal. The resulting GDL should be semantically equivalent. To see why this is //! necessary, see section 13.6 [here](http://logic.stanford.edu/ggp/chapters/chapter_13.html). For //! an example test case of where this makes a difference, see the `test_beginning_distinct` test //! case in this file. use std::collections::HashSet; use prover::deorer; use gdl::{Description, Rule, Variable, Literal, Term}; use gdl::Clause::RuleClause; use gdl::Literal::{OrLit, NotLit, DistinctLit, RelLit}; use gdl::Term::{VarTerm, FuncTerm}; /// Reorders a game description such that all negative literals occur after all their variables /// have been seen in a positive literal pub fn reorder(desc: Description) -> Description { let desc = deorer::deor(desc); let mut new_clauses = Vec::new(); for clause in desc.clauses { match clause { RuleClause(r) => { new_clauses.push(reorder_rule(r).into()); } _ => new_clauses.push(clause) } } Description::new(new_clauses) } fn reorder_rule(mut r: Rule) -> Rule { loop { match find_neg_lit_index(&*r.body) { Some(index) => { let swap_index = find_candidate_index(&*r.body, &r.body[index]) .expect("No candidate index found"); let body = &mut *r.body; body.swap(index, swap_index); } None => break } } r } fn find_neg_lit_index(body: &[Literal]) -> Option<usize> { let mut seen_vars = HashSet::new(); for (i, lit) in body.iter().enumerate() { match lit { l @ &DistinctLit(_) | l @ &NotLit(_) => { if!seen_all_vars(&seen_vars, l) { return Some(i); } } l @ &RelLit(_) => { seen_vars.extend(get_vars(l)); } &OrLit(_) => panic!("Or literals were removed"), _ => () } } None } fn find_candidate_index(body: &[Literal], neg_lit: &Literal) -> Option<usize> { let mut seen_vars = HashSet::new(); for (i, lit) in body.iter().enumerate() { match lit { l @ &RelLit(_) => { seen_vars.extend(get_vars(l)); if seen_all_vars(&seen_vars, neg_lit) { return Some(i) } }, &OrLit(_) => panic!("Or literals were removed"), _ => () } } None } fn get_vars(l: &Literal) -> Vec<Variable> { let mut res = Vec::new(); match l { &RelLit(ref r) => { for term in r.args.iter() { res.extend(get_vars_from_term(term)); } res }, &NotLit(ref not) => get_vars(&not.lit), &DistinctLit(ref distinct) => { res.extend(get_vars_from_term(&distinct.term1)); res.extend(get_vars_from_term(&distinct.term2)); res }, &OrLit(_) => panic!("Or literals were removed"), _ => res } } fn get_vars_from_term(t: &Term) -> Vec<Variable> { match t { &VarTerm(ref v) => vec![(*v).clone()], &FuncTerm(ref f) => { let mut res = Vec::new(); for t in f.args.iter() { res.extend(get_vars_from_term(t)); } res } _ => Vec::new() } } fn seen_all_vars(seen_vars: &HashSet<Variable>, l: &Literal) -> bool { let vars = get_vars(l); for var in vars { if!seen_vars.contains(&var) { return false; } } true } #[cfg(test)] mod test { use {gdl, State, Role}; use super::reorder; use prover::Prover; use prover::query_builder; #[test] fn test_distinct() { let desc = gdl::parse("(<= p (distinct?a?b) (q?a?b))"); let expected = gdl::parse("(<= p (q?a?b) (distinct?a?b))"); assert_eq!(reorder(desc), expected); } #[test] fn test_not_function() { let desc = gdl::parse("(<= p (not (foo (bar?a))) (q?a))"); let expected = gdl::parse("(<= p (q?a) (not (foo (bar?a))))"); assert_eq!(reorder(desc), expected); } #[test] fn test_not() { let desc = gdl::parse("(<= p (not (foo?a)) (q?a))"); let expected = gdl::parse("(<= p (q?a) (not (foo?a)))"); assert_eq!(reorder(desc), expected); } #[test] fn test_multiple_swap() { let desc = gdl::parse("(<= p (not (bar?a)) (not (foo?a?b)) (q?a) (distinct?a?b) \ (q?b) (q?c))"); let expected = gdl::parse("(<= p (q?a) (q?b) (not (bar?a)) (distinct?a?b) \ (not (foo?a?b)) (q?c))"); assert_eq!(reorder(desc), expected); } #[test] fn test_no_move()
#[test] fn test_beginning_distinct() { let gdl = "(role you) \ (<= (foo?a?b) \ (distinct?a?b) \ (p?a) \ (q?b)) \ (p a) \ (p b) \ (q a) \ (q b) \ (<= (legal you (do?a?b)) \ (foo?a?b)) \ (next win) \ (<= terminal \ (true win)) \ (goal you 100)"; let desc = gdl::parse(gdl); let prover = Prover::new(desc); let moves = prover.ask(query_builder::legal_query(&Role::new("you")), &State::new()).into_moves(); // Without the reordering, there are four legal moves, which is incorrect assert_eq!(moves.len(), 2); } }
{ let desc = gdl::parse("(<= p (q ?a) (not (foo ?a)))"); assert_eq!(reorder(desc.clone()), desc); let desc = gdl::parse("(<= p (q ?a) (distinct ?a))"); assert_eq!(reorder(desc.clone()), desc); }
identifier_body
negative_literal_mover.rs
//! This module literals in a GDL description such that all variables in a negative literal (i.e. a //! `distinct` or `not` literal) have been seen in positive literals occurring before that //! `negative` literal. The resulting GDL should be semantically equivalent. To see why this is //! necessary, see section 13.6 [here](http://logic.stanford.edu/ggp/chapters/chapter_13.html). For //! an example test case of where this makes a difference, see the `test_beginning_distinct` test //! case in this file. use std::collections::HashSet; use prover::deorer; use gdl::{Description, Rule, Variable, Literal, Term}; use gdl::Clause::RuleClause; use gdl::Literal::{OrLit, NotLit, DistinctLit, RelLit}; use gdl::Term::{VarTerm, FuncTerm}; /// Reorders a game description such that all negative literals occur after all their variables /// have been seen in a positive literal pub fn reorder(desc: Description) -> Description { let desc = deorer::deor(desc); let mut new_clauses = Vec::new(); for clause in desc.clauses { match clause { RuleClause(r) => { new_clauses.push(reorder_rule(r).into()); } _ => new_clauses.push(clause) } } Description::new(new_clauses) } fn reorder_rule(mut r: Rule) -> Rule { loop { match find_neg_lit_index(&*r.body) { Some(index) => { let swap_index = find_candidate_index(&*r.body, &r.body[index]) .expect("No candidate index found"); let body = &mut *r.body; body.swap(index, swap_index); } None => break } } r } fn find_neg_lit_index(body: &[Literal]) -> Option<usize> { let mut seen_vars = HashSet::new(); for (i, lit) in body.iter().enumerate() { match lit { l @ &DistinctLit(_) | l @ &NotLit(_) => { if!seen_all_vars(&seen_vars, l) { return Some(i); } } l @ &RelLit(_) => { seen_vars.extend(get_vars(l)); } &OrLit(_) => panic!("Or literals were removed"), _ => () } } None } fn find_candidate_index(body: &[Literal], neg_lit: &Literal) -> Option<usize> { let mut seen_vars = HashSet::new(); for (i, lit) in body.iter().enumerate() { match lit { l @ &RelLit(_) => { seen_vars.extend(get_vars(l)); if seen_all_vars(&seen_vars, neg_lit) { return Some(i) } }, &OrLit(_) => panic!("Or literals were removed"), _ => () } } None } fn get_vars(l: &Literal) -> Vec<Variable> { let mut res = Vec::new(); match l { &RelLit(ref r) => { for term in r.args.iter() { res.extend(get_vars_from_term(term)); } res }, &NotLit(ref not) => get_vars(&not.lit), &DistinctLit(ref distinct) => { res.extend(get_vars_from_term(&distinct.term1)); res.extend(get_vars_from_term(&distinct.term2)); res }, &OrLit(_) => panic!("Or literals were removed"), _ => res } } fn
(t: &Term) -> Vec<Variable> { match t { &VarTerm(ref v) => vec![(*v).clone()], &FuncTerm(ref f) => { let mut res = Vec::new(); for t in f.args.iter() { res.extend(get_vars_from_term(t)); } res } _ => Vec::new() } } fn seen_all_vars(seen_vars: &HashSet<Variable>, l: &Literal) -> bool { let vars = get_vars(l); for var in vars { if!seen_vars.contains(&var) { return false; } } true } #[cfg(test)] mod test { use {gdl, State, Role}; use super::reorder; use prover::Prover; use prover::query_builder; #[test] fn test_distinct() { let desc = gdl::parse("(<= p (distinct?a?b) (q?a?b))"); let expected = gdl::parse("(<= p (q?a?b) (distinct?a?b))"); assert_eq!(reorder(desc), expected); } #[test] fn test_not_function() { let desc = gdl::parse("(<= p (not (foo (bar?a))) (q?a))"); let expected = gdl::parse("(<= p (q?a) (not (foo (bar?a))))"); assert_eq!(reorder(desc), expected); } #[test] fn test_not() { let desc = gdl::parse("(<= p (not (foo?a)) (q?a))"); let expected = gdl::parse("(<= p (q?a) (not (foo?a)))"); assert_eq!(reorder(desc), expected); } #[test] fn test_multiple_swap() { let desc = gdl::parse("(<= p (not (bar?a)) (not (foo?a?b)) (q?a) (distinct?a?b) \ (q?b) (q?c))"); let expected = gdl::parse("(<= p (q?a) (q?b) (not (bar?a)) (distinct?a?b) \ (not (foo?a?b)) (q?c))"); assert_eq!(reorder(desc), expected); } #[test] fn test_no_move() { let desc = gdl::parse("(<= p (q?a) (not (foo?a)))"); assert_eq!(reorder(desc.clone()), desc); let desc = gdl::parse("(<= p (q?a) (distinct?a))"); assert_eq!(reorder(desc.clone()), desc); } #[test] fn test_beginning_distinct() { let gdl = "(role you) \ (<= (foo?a?b) \ (distinct?a?b) \ (p?a) \ (q?b)) \ (p a) \ (p b) \ (q a) \ (q b) \ (<= (legal you (do?a?b)) \ (foo?a?b)) \ (next win) \ (<= terminal \ (true win)) \ (goal you 100)"; let desc = gdl::parse(gdl); let prover = Prover::new(desc); let moves = prover.ask(query_builder::legal_query(&Role::new("you")), &State::new()).into_moves(); // Without the reordering, there are four legal moves, which is incorrect assert_eq!(moves.len(), 2); } }
get_vars_from_term
identifier_name
TestNextafter.rs
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 *
*/ // Don't edit this file! It is auto-generated by frameworks/rs/api/generate.sh. #pragma version(1) #pragma rs java_package_name(android.renderscript.cts) rs_allocation gAllocInTarget; float __attribute__((kernel)) testNextafterFloatFloatFloat(float inV, unsigned int x) { float inTarget = rsGetElementAt_float(gAllocInTarget, x); return nextafter(inV, inTarget); } float2 __attribute__((kernel)) testNextafterFloat2Float2Float2(float2 inV, unsigned int x) { float2 inTarget = rsGetElementAt_float2(gAllocInTarget, x); return nextafter(inV, inTarget); } float3 __attribute__((kernel)) testNextafterFloat3Float3Float3(float3 inV, unsigned int x) { float3 inTarget = rsGetElementAt_float3(gAllocInTarget, x); return nextafter(inV, inTarget); } float4 __attribute__((kernel)) testNextafterFloat4Float4Float4(float4 inV, unsigned int x) { float4 inTarget = rsGetElementAt_float4(gAllocInTarget, x); return nextafter(inV, inTarget); }
* 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.
random_line_split
timer.rs
use super::*; use time; use time::Tm; /// A timer metric for tracking elapsed time /// /// Internally uses a `Metric<i64>` with `Semantics::Instant` and `1` time dimension pub struct Timer { metric: Metric<i64>, time_scale: Time, start_time: Option<Tm> } /// Error encountered while starting or stopping a timer #[derive(Debug)] pub enum Error { /// IO error Io(io::Error), /// Timer was already started TimerAlreadyStarted, /// Timer wasn't previously started TimerNotStarted, } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) } } impl Timer { /// Creates a new timer metric with given time scale pub fn
(name: &str, time_scale: Time, shorthelp_text: &str, longhelp_text: &str) -> Result<Self, String> { let metric = Metric::new( name, 0, Semantics::Instant, Unit::new().time(time_scale, 1)?, shorthelp_text, longhelp_text )?; Ok(Timer { metric: metric, time_scale: time_scale, start_time: None }) } /// Starts the timer. Returns an error if the timer is /// already started. pub fn start(&mut self) -> Result<(), Error> { if self.start_time.is_some() { return Err(Error::TimerAlreadyStarted) } self.start_time = Some(time::now()); Ok(()) } /// Stops the timer, updates the internal metric, and /// returns the time elapsed since the last `start`. If /// the timer was stopped too early or too late such that /// the internal nanosecond, microsecond or millisecond value /// over/under-flows, then elapsed time isn't updated. /// /// Returns `0` if the timer wasn't started before. pub fn stop(&mut self) -> Result<i64, Error> { match self.start_time { Some(start_time) => { let duration = time::now() - start_time; let elapsed = match self.time_scale { Time::NSec => duration.num_nanoseconds().unwrap_or(0), Time::USec => duration.num_microseconds().unwrap_or(0), Time::MSec => duration.num_microseconds().unwrap_or(0), Time::Sec => duration.num_seconds(), Time::Min => duration.num_minutes(), Time::Hour => duration.num_hours() }; let val = self.metric.val(); self.metric.set_val(val + elapsed)?; self.start_time = None; Ok(elapsed) }, None => Err(Error::TimerNotStarted) } } /// Returns the cumulative time elapsed between every /// `start` and `stop` pair. pub fn elapsed(&mut self) -> i64 { self.metric.val() } } impl MMVWriter for Timer { private_impl!{} fn write(&mut self, ws: &mut MMVWriterState, c: &mut Cursor<&mut [u8]>, mmv_ver: Version) -> io::Result<()> { self.metric.write(ws, c, mmv_ver) } fn register(&self, ws: &mut MMVWriterState, mmv_ver: Version) { self.metric.register(ws, mmv_ver) } fn has_mmv2_string(&self) -> bool { self.metric.has_mmv2_string() } } #[test] pub fn test() { use super::super::Client; use std::thread; use std::time::Duration; let mut timer = Timer::new("timer", Time::MSec, "", "").unwrap(); assert_eq!(timer.elapsed(), 0); Client::new("timer_test").unwrap() .export(&mut [&mut timer]).unwrap(); assert!(timer.stop().is_err()); let sleep_time = 2; // seconds timer.start().unwrap(); assert!(timer.start().is_err()); thread::sleep(Duration::from_secs(sleep_time)); let elapsed1 = timer.stop().unwrap(); assert_eq!(timer.elapsed(), elapsed1); timer.start().unwrap(); thread::sleep(Duration::from_secs(sleep_time)); let elapsed2 = timer.stop().unwrap(); assert_eq!(timer.elapsed(), elapsed1 + elapsed2); }
new
identifier_name
timer.rs
use super::*; use time; use time::Tm; /// A timer metric for tracking elapsed time /// /// Internally uses a `Metric<i64>` with `Semantics::Instant` and `1` time dimension pub struct Timer { metric: Metric<i64>, time_scale: Time, start_time: Option<Tm> } /// Error encountered while starting or stopping a timer #[derive(Debug)] pub enum Error { /// IO error Io(io::Error), /// Timer was already started TimerAlreadyStarted, /// Timer wasn't previously started TimerNotStarted, } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) } } impl Timer { /// Creates a new timer metric with given time scale pub fn new(name: &str, time_scale: Time, shorthelp_text: &str, longhelp_text: &str) -> Result<Self, String> { let metric = Metric::new( name, 0, Semantics::Instant, Unit::new().time(time_scale, 1)?, shorthelp_text, longhelp_text )?; Ok(Timer { metric: metric, time_scale: time_scale, start_time: None }) } /// Starts the timer. Returns an error if the timer is /// already started. pub fn start(&mut self) -> Result<(), Error> { if self.start_time.is_some() { return Err(Error::TimerAlreadyStarted) } self.start_time = Some(time::now()); Ok(()) } /// Stops the timer, updates the internal metric, and /// returns the time elapsed since the last `start`. If /// the timer was stopped too early or too late such that /// the internal nanosecond, microsecond or millisecond value /// over/under-flows, then elapsed time isn't updated. /// /// Returns `0` if the timer wasn't started before. pub fn stop(&mut self) -> Result<i64, Error> { match self.start_time { Some(start_time) => { let duration = time::now() - start_time; let elapsed = match self.time_scale { Time::NSec => duration.num_nanoseconds().unwrap_or(0), Time::USec => duration.num_microseconds().unwrap_or(0), Time::MSec => duration.num_microseconds().unwrap_or(0), Time::Sec => duration.num_seconds(), Time::Min => duration.num_minutes(), Time::Hour => duration.num_hours() }; let val = self.metric.val(); self.metric.set_val(val + elapsed)?; self.start_time = None; Ok(elapsed) }, None => Err(Error::TimerNotStarted) } } /// Returns the cumulative time elapsed between every /// `start` and `stop` pair. pub fn elapsed(&mut self) -> i64 { self.metric.val() } } impl MMVWriter for Timer { private_impl!{} fn write(&mut self, ws: &mut MMVWriterState, c: &mut Cursor<&mut [u8]>, mmv_ver: Version) -> io::Result<()> { self.metric.write(ws, c, mmv_ver) } fn register(&self, ws: &mut MMVWriterState, mmv_ver: Version) { self.metric.register(ws, mmv_ver) } fn has_mmv2_string(&self) -> bool { self.metric.has_mmv2_string() } } #[test] pub fn test()
timer.start().unwrap(); thread::sleep(Duration::from_secs(sleep_time)); let elapsed2 = timer.stop().unwrap(); assert_eq!(timer.elapsed(), elapsed1 + elapsed2); }
{ use super::super::Client; use std::thread; use std::time::Duration; let mut timer = Timer::new("timer", Time::MSec, "", "").unwrap(); assert_eq!(timer.elapsed(), 0); Client::new("timer_test").unwrap() .export(&mut [&mut timer]).unwrap(); assert!(timer.stop().is_err()); let sleep_time = 2; // seconds timer.start().unwrap(); assert!(timer.start().is_err()); thread::sleep(Duration::from_secs(sleep_time)); let elapsed1 = timer.stop().unwrap(); assert_eq!(timer.elapsed(), elapsed1);
identifier_body
timer.rs
use super::*; use time; use time::Tm; /// A timer metric for tracking elapsed time /// /// Internally uses a `Metric<i64>` with `Semantics::Instant` and `1` time dimension pub struct Timer { metric: Metric<i64>, time_scale: Time, start_time: Option<Tm> } /// Error encountered while starting or stopping a timer #[derive(Debug)] pub enum Error { /// IO error Io(io::Error), /// Timer was already started TimerAlreadyStarted, /// Timer wasn't previously started TimerNotStarted, } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) } } impl Timer { /// Creates a new timer metric with given time scale pub fn new(name: &str, time_scale: Time, shorthelp_text: &str, longhelp_text: &str) -> Result<Self, String> { let metric = Metric::new( name, 0, Semantics::Instant, Unit::new().time(time_scale, 1)?, shorthelp_text, longhelp_text )?; Ok(Timer { metric: metric, time_scale: time_scale, start_time: None }) } /// Starts the timer. Returns an error if the timer is /// already started. pub fn start(&mut self) -> Result<(), Error> { if self.start_time.is_some() { return Err(Error::TimerAlreadyStarted) } self.start_time = Some(time::now()); Ok(()) } /// Stops the timer, updates the internal metric, and /// returns the time elapsed since the last `start`. If /// the timer was stopped too early or too late such that /// the internal nanosecond, microsecond or millisecond value /// over/under-flows, then elapsed time isn't updated. /// /// Returns `0` if the timer wasn't started before. pub fn stop(&mut self) -> Result<i64, Error> { match self.start_time { Some(start_time) => { let duration = time::now() - start_time; let elapsed = match self.time_scale { Time::NSec => duration.num_nanoseconds().unwrap_or(0), Time::USec => duration.num_microseconds().unwrap_or(0), Time::MSec => duration.num_microseconds().unwrap_or(0), Time::Sec => duration.num_seconds(), Time::Min => duration.num_minutes(), Time::Hour => duration.num_hours() }; let val = self.metric.val(); self.metric.set_val(val + elapsed)?; self.start_time = None; Ok(elapsed) }, None => Err(Error::TimerNotStarted) } } /// Returns the cumulative time elapsed between every /// `start` and `stop` pair. pub fn elapsed(&mut self) -> i64 { self.metric.val() } } impl MMVWriter for Timer { private_impl!{} fn write(&mut self, ws: &mut MMVWriterState, c: &mut Cursor<&mut [u8]>, mmv_ver: Version) -> io::Result<()> { self.metric.write(ws, c, mmv_ver) } fn register(&self, ws: &mut MMVWriterState, mmv_ver: Version) { self.metric.register(ws, mmv_ver) } fn has_mmv2_string(&self) -> bool { self.metric.has_mmv2_string() } }
use std::thread; use std::time::Duration; let mut timer = Timer::new("timer", Time::MSec, "", "").unwrap(); assert_eq!(timer.elapsed(), 0); Client::new("timer_test").unwrap() .export(&mut [&mut timer]).unwrap(); assert!(timer.stop().is_err()); let sleep_time = 2; // seconds timer.start().unwrap(); assert!(timer.start().is_err()); thread::sleep(Duration::from_secs(sleep_time)); let elapsed1 = timer.stop().unwrap(); assert_eq!(timer.elapsed(), elapsed1); timer.start().unwrap(); thread::sleep(Duration::from_secs(sleep_time)); let elapsed2 = timer.stop().unwrap(); assert_eq!(timer.elapsed(), elapsed1 + elapsed2); }
#[test] pub fn test() { use super::super::Client;
random_line_split
nullable-pointer-iotareduction.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. #![feature(macro_rules)] use std::{option, cast}; // Iota-reduction is a rule in the Calculus of (Co-)Inductive Constructions, // which "says that a destructor applied to an object built from a constructor // behaves as expected". -- http://coq.inria.fr/doc/Reference-Manual006.html // // It's a little more complicated here, because of pointers and regions and // trying to get assert failure messages that at least identify which case // failed. enum E<T> { Thing(int, T), Nothing((), ((), ()), [i8,..0]) } impl<T> E<T> { fn is_none(&self) -> bool { match *self { Thing(..) => false, Nothing(..) => true } } fn get_ref<'r>(&'r self) -> (int, &'r T) { match *self { Nothing(..) => fail!("E::get_ref(Nothing::<{}>)", stringify!(T)), Thing(x, ref y) => (x, y) } } } macro_rules! check_option { ($e:expr: $T:ty) => {{ check_option!($e: $T, |ptr| assert!(*ptr == $e)); }}; ($e:expr: $T:ty, |$v:ident| $chk:expr) => {{ assert!(option::None::<$T>.is_none()); let e = $e; let s_ = option::Some::<$T>(e); let $v = s_.get_ref(); $chk }} } macro_rules! check_fancy { ($e:expr: $T:ty) => {{ check_fancy!($e: $T, |ptr| assert!(*ptr == $e)); }}; ($e:expr: $T:ty, |$v:ident| $chk:expr) => {{ assert!(Nothing::<$T>((), ((), ()), [23i8,..0]).is_none()); let e = $e; let t_ = Thing::<$T>(23, e); match t_.get_ref() { (23, $v) => { $chk } _ => fail!("Thing::<{}>(23, {}).get_ref()!= (23, _)",
} macro_rules! check_type { ($($a:tt)*) => {{ check_option!($($a)*); check_fancy!($($a)*); }} } pub fn main() { check_type!(&17: &int); check_type!(box 18: Box<int>); check_type!(@19: @int); check_type!("foo".to_owned(): ~str); check_type!(vec!(20, 22): Vec<int> ); let mint: uint = unsafe { cast::transmute(main) }; check_type!(main: fn(), |pthing| { assert!(mint == unsafe { cast::transmute(*pthing) }) }); }
stringify!($T), stringify!($e)) } }}
random_line_split
nullable-pointer-iotareduction.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. #![feature(macro_rules)] use std::{option, cast}; // Iota-reduction is a rule in the Calculus of (Co-)Inductive Constructions, // which "says that a destructor applied to an object built from a constructor // behaves as expected". -- http://coq.inria.fr/doc/Reference-Manual006.html // // It's a little more complicated here, because of pointers and regions and // trying to get assert failure messages that at least identify which case // failed. enum E<T> { Thing(int, T), Nothing((), ((), ()), [i8,..0]) } impl<T> E<T> { fn is_none(&self) -> bool { match *self { Thing(..) => false, Nothing(..) => true } } fn get_ref<'r>(&'r self) -> (int, &'r T) { match *self { Nothing(..) => fail!("E::get_ref(Nothing::<{}>)", stringify!(T)), Thing(x, ref y) => (x, y) } } } macro_rules! check_option { ($e:expr: $T:ty) => {{ check_option!($e: $T, |ptr| assert!(*ptr == $e)); }}; ($e:expr: $T:ty, |$v:ident| $chk:expr) => {{ assert!(option::None::<$T>.is_none()); let e = $e; let s_ = option::Some::<$T>(e); let $v = s_.get_ref(); $chk }} } macro_rules! check_fancy { ($e:expr: $T:ty) => {{ check_fancy!($e: $T, |ptr| assert!(*ptr == $e)); }}; ($e:expr: $T:ty, |$v:ident| $chk:expr) => {{ assert!(Nothing::<$T>((), ((), ()), [23i8,..0]).is_none()); let e = $e; let t_ = Thing::<$T>(23, e); match t_.get_ref() { (23, $v) => { $chk } _ => fail!("Thing::<{}>(23, {}).get_ref()!= (23, _)", stringify!($T), stringify!($e)) } }} } macro_rules! check_type { ($($a:tt)*) => {{ check_option!($($a)*); check_fancy!($($a)*); }} } pub fn main()
{ check_type!(&17: &int); check_type!(box 18: Box<int>); check_type!(@19: @int); check_type!("foo".to_owned(): ~str); check_type!(vec!(20, 22): Vec<int> ); let mint: uint = unsafe { cast::transmute(main) }; check_type!(main: fn(), |pthing| { assert!(mint == unsafe { cast::transmute(*pthing) }) }); }
identifier_body
nullable-pointer-iotareduction.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. #![feature(macro_rules)] use std::{option, cast}; // Iota-reduction is a rule in the Calculus of (Co-)Inductive Constructions, // which "says that a destructor applied to an object built from a constructor // behaves as expected". -- http://coq.inria.fr/doc/Reference-Manual006.html // // It's a little more complicated here, because of pointers and regions and // trying to get assert failure messages that at least identify which case // failed. enum E<T> { Thing(int, T), Nothing((), ((), ()), [i8,..0]) } impl<T> E<T> { fn is_none(&self) -> bool { match *self { Thing(..) => false, Nothing(..) => true } } fn
<'r>(&'r self) -> (int, &'r T) { match *self { Nothing(..) => fail!("E::get_ref(Nothing::<{}>)", stringify!(T)), Thing(x, ref y) => (x, y) } } } macro_rules! check_option { ($e:expr: $T:ty) => {{ check_option!($e: $T, |ptr| assert!(*ptr == $e)); }}; ($e:expr: $T:ty, |$v:ident| $chk:expr) => {{ assert!(option::None::<$T>.is_none()); let e = $e; let s_ = option::Some::<$T>(e); let $v = s_.get_ref(); $chk }} } macro_rules! check_fancy { ($e:expr: $T:ty) => {{ check_fancy!($e: $T, |ptr| assert!(*ptr == $e)); }}; ($e:expr: $T:ty, |$v:ident| $chk:expr) => {{ assert!(Nothing::<$T>((), ((), ()), [23i8,..0]).is_none()); let e = $e; let t_ = Thing::<$T>(23, e); match t_.get_ref() { (23, $v) => { $chk } _ => fail!("Thing::<{}>(23, {}).get_ref()!= (23, _)", stringify!($T), stringify!($e)) } }} } macro_rules! check_type { ($($a:tt)*) => {{ check_option!($($a)*); check_fancy!($($a)*); }} } pub fn main() { check_type!(&17: &int); check_type!(box 18: Box<int>); check_type!(@19: @int); check_type!("foo".to_owned(): ~str); check_type!(vec!(20, 22): Vec<int> ); let mint: uint = unsafe { cast::transmute(main) }; check_type!(main: fn(), |pthing| { assert!(mint == unsafe { cast::transmute(*pthing) }) }); }
get_ref
identifier_name
tile.rs
use ndarray::{ArrayBase, DataMut, NdIndex, IntoDimension}; #[derive(Copy, Clone, Debug)] #[cfg_attr( feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate") )] pub struct Tile<D: ndarray::Dimension, I: NdIndex<D>> { dim: D, active: Option<(I, f64)>, } impl<D: ndarray::Dimension, I: NdIndex<D>> Tile<D, I> { pub fn new<T: IntoDimension<Dim = D>>(dim: T, active: Option<(I, f64)>) -> Self { Tile { dim: dim.into_dimension(), active, } } } impl<D: ndarray::Dimension, I: NdIndex<D> + Clone> crate::params::Buffer for Tile<D, I> { type Dim = D; fn raw_dim(&self) -> D { self.dim.clone() } fn addto<E: DataMut<Elem = f64>>(&self, arr: &mut ArrayBase<E, Self::Dim>)
fn scaled_addto<E: DataMut<Elem = f64>>(&self, alpha: f64, arr: &mut ArrayBase<E, Self::Dim>) { if let Some((idx, activation)) = &self.active { arr[idx.clone()] += alpha * activation; } } } impl<D, I> crate::params::BufferMut for Tile<D, I> where D: ndarray::Dimension, I: NdIndex<D> + PartialEq + Clone, { fn zeros<T: IntoDimension<Dim = D>>(dim: T) -> Self { Tile::new(dim, None) } fn map(&self, f: impl Fn(f64) -> f64) -> Self { self.clone().map_into(f) } fn map_into(self, f: impl Fn(f64) -> f64) -> Self { Tile { dim: self.dim, active: self.active.map(|(idx, a)| (idx, f(a))), } } fn map_inplace(&mut self, f: impl Fn(f64) -> f64) { if let Some((_, x)) = &mut self.active { *x = f(*x); } } fn merge(&self, other: &Self, f: impl Fn(f64, f64) -> f64) -> Self { self.clone().merge_into(other, f) } fn merge_into(mut self, other: &Self, f: impl Fn(f64, f64) -> f64) -> Self { self.merge_inplace(other, f); self } fn merge_inplace(&mut self, other: &Self, f: impl Fn(f64, f64) -> f64) { if self.dim!= other.dim { panic!("Incompatible buffers shapes.") } match (&mut self.active, &other.active) { (Some((i, x)), Some((j, y))) if i == j => *x = f(*x, *y), _ => panic!("Incompatible buffer indices."), } } }
{ if let Some((idx, activation)) = &self.active { arr[idx.clone()] += activation; } }
identifier_body
tile.rs
use ndarray::{ArrayBase, DataMut, NdIndex, IntoDimension}; #[derive(Copy, Clone, Debug)] #[cfg_attr( feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate") )] pub struct Tile<D: ndarray::Dimension, I: NdIndex<D>> { dim: D, active: Option<(I, f64)>, } impl<D: ndarray::Dimension, I: NdIndex<D>> Tile<D, I> { pub fn new<T: IntoDimension<Dim = D>>(dim: T, active: Option<(I, f64)>) -> Self { Tile { dim: dim.into_dimension(), active, } } } impl<D: ndarray::Dimension, I: NdIndex<D> + Clone> crate::params::Buffer for Tile<D, I> { type Dim = D; fn raw_dim(&self) -> D { self.dim.clone() } fn addto<E: DataMut<Elem = f64>>(&self, arr: &mut ArrayBase<E, Self::Dim>) { if let Some((idx, activation)) = &self.active {
fn scaled_addto<E: DataMut<Elem = f64>>(&self, alpha: f64, arr: &mut ArrayBase<E, Self::Dim>) { if let Some((idx, activation)) = &self.active { arr[idx.clone()] += alpha * activation; } } } impl<D, I> crate::params::BufferMut for Tile<D, I> where D: ndarray::Dimension, I: NdIndex<D> + PartialEq + Clone, { fn zeros<T: IntoDimension<Dim = D>>(dim: T) -> Self { Tile::new(dim, None) } fn map(&self, f: impl Fn(f64) -> f64) -> Self { self.clone().map_into(f) } fn map_into(self, f: impl Fn(f64) -> f64) -> Self { Tile { dim: self.dim, active: self.active.map(|(idx, a)| (idx, f(a))), } } fn map_inplace(&mut self, f: impl Fn(f64) -> f64) { if let Some((_, x)) = &mut self.active { *x = f(*x); } } fn merge(&self, other: &Self, f: impl Fn(f64, f64) -> f64) -> Self { self.clone().merge_into(other, f) } fn merge_into(mut self, other: &Self, f: impl Fn(f64, f64) -> f64) -> Self { self.merge_inplace(other, f); self } fn merge_inplace(&mut self, other: &Self, f: impl Fn(f64, f64) -> f64) { if self.dim!= other.dim { panic!("Incompatible buffers shapes.") } match (&mut self.active, &other.active) { (Some((i, x)), Some((j, y))) if i == j => *x = f(*x, *y), _ => panic!("Incompatible buffer indices."), } } }
arr[idx.clone()] += activation; } }
random_line_split
tile.rs
use ndarray::{ArrayBase, DataMut, NdIndex, IntoDimension}; #[derive(Copy, Clone, Debug)] #[cfg_attr( feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate") )] pub struct Tile<D: ndarray::Dimension, I: NdIndex<D>> { dim: D, active: Option<(I, f64)>, } impl<D: ndarray::Dimension, I: NdIndex<D>> Tile<D, I> { pub fn new<T: IntoDimension<Dim = D>>(dim: T, active: Option<(I, f64)>) -> Self { Tile { dim: dim.into_dimension(), active, } } } impl<D: ndarray::Dimension, I: NdIndex<D> + Clone> crate::params::Buffer for Tile<D, I> { type Dim = D; fn raw_dim(&self) -> D { self.dim.clone() } fn addto<E: DataMut<Elem = f64>>(&self, arr: &mut ArrayBase<E, Self::Dim>) { if let Some((idx, activation)) = &self.active { arr[idx.clone()] += activation; } } fn scaled_addto<E: DataMut<Elem = f64>>(&self, alpha: f64, arr: &mut ArrayBase<E, Self::Dim>) { if let Some((idx, activation)) = &self.active { arr[idx.clone()] += alpha * activation; } } } impl<D, I> crate::params::BufferMut for Tile<D, I> where D: ndarray::Dimension, I: NdIndex<D> + PartialEq + Clone, { fn zeros<T: IntoDimension<Dim = D>>(dim: T) -> Self { Tile::new(dim, None) } fn map(&self, f: impl Fn(f64) -> f64) -> Self { self.clone().map_into(f) } fn map_into(self, f: impl Fn(f64) -> f64) -> Self { Tile { dim: self.dim, active: self.active.map(|(idx, a)| (idx, f(a))), } } fn map_inplace(&mut self, f: impl Fn(f64) -> f64) { if let Some((_, x)) = &mut self.active { *x = f(*x); } } fn merge(&self, other: &Self, f: impl Fn(f64, f64) -> f64) -> Self { self.clone().merge_into(other, f) } fn merge_into(mut self, other: &Self, f: impl Fn(f64, f64) -> f64) -> Self { self.merge_inplace(other, f); self } fn
(&mut self, other: &Self, f: impl Fn(f64, f64) -> f64) { if self.dim!= other.dim { panic!("Incompatible buffers shapes.") } match (&mut self.active, &other.active) { (Some((i, x)), Some((j, y))) if i == j => *x = f(*x, *y), _ => panic!("Incompatible buffer indices."), } } }
merge_inplace
identifier_name
htmllegendelement.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::HTMLLegendElementBinding; use dom::bindings::codegen::Bindings::HTMLLegendElementBinding::HTMLLegendElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::document::Document; use dom::element::Element; use dom::htmlelement::HTMLElement; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlformelement::{HTMLFormElement, FormControl}; use dom::node::{Node, UnbindContext}; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLLegendElement { htmlelement: HTMLElement, form_owner: MutNullableDom<HTMLFormElement>, } impl HTMLLegendElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLLegendElement { HTMLLegendElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), form_owner: Default::default(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLLegendElement> { Node::reflect_node(Box::new(HTMLLegendElement::new_inherited(local_name, prefix, document)), document, HTMLLegendElementBinding::Wrap) } } impl VirtualMethods for HTMLLegendElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>())
else { el.check_disabled_attribute(); } } } impl HTMLLegendElementMethods for HTMLLegendElement { // https://html.spec.whatwg.org/multipage/#dom-legend-form fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> { let parent = self.upcast::<Node>().GetParentElement()?; if parent.is::<HTMLFieldSetElement>() { return self.form_owner(); } None } } impl FormControl for HTMLLegendElement { fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> { self.form_owner.get() } fn set_form_owner(&self, form: Option<&HTMLFormElement>) { self.form_owner.set(form); } fn to_element<'a>(&'a self) -> &'a Element { self.upcast::<Element>() } }
{ el.check_ancestors_disabled_state_for_form_control(); }
conditional_block
htmllegendelement.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::HTMLLegendElementBinding; use dom::bindings::codegen::Bindings::HTMLLegendElementBinding::HTMLLegendElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::document::Document; use dom::element::Element; use dom::htmlelement::HTMLElement; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlformelement::{HTMLFormElement, FormControl}; use dom::node::{Node, UnbindContext}; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLLegendElement { htmlelement: HTMLElement, form_owner: MutNullableDom<HTMLFormElement>, } impl HTMLLegendElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLLegendElement { HTMLLegendElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), form_owner: Default::default(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLLegendElement> { Node::reflect_node(Box::new(HTMLLegendElement::new_inherited(local_name, prefix, document)), document, HTMLLegendElementBinding::Wrap) } } impl VirtualMethods for HTMLLegendElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); } } } impl HTMLLegendElementMethods for HTMLLegendElement { // https://html.spec.whatwg.org/multipage/#dom-legend-form fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> { let parent = self.upcast::<Node>().GetParentElement()?; if parent.is::<HTMLFieldSetElement>() { return self.form_owner(); } None } } impl FormControl for HTMLLegendElement { fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> { self.form_owner.get() } fn
(&self, form: Option<&HTMLFormElement>) { self.form_owner.set(form); } fn to_element<'a>(&'a self) -> &'a Element { self.upcast::<Element>() } }
set_form_owner
identifier_name
htmllegendelement.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::HTMLLegendElementBinding; use dom::bindings::codegen::Bindings::HTMLLegendElementBinding::HTMLLegendElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable;
use dom::element::Element; use dom::htmlelement::HTMLElement; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlformelement::{HTMLFormElement, FormControl}; use dom::node::{Node, UnbindContext}; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLLegendElement { htmlelement: HTMLElement, form_owner: MutNullableDom<HTMLFormElement>, } impl HTMLLegendElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLLegendElement { HTMLLegendElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), form_owner: Default::default(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLLegendElement> { Node::reflect_node(Box::new(HTMLLegendElement::new_inherited(local_name, prefix, document)), document, HTMLLegendElementBinding::Wrap) } } impl VirtualMethods for HTMLLegendElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); } } } impl HTMLLegendElementMethods for HTMLLegendElement { // https://html.spec.whatwg.org/multipage/#dom-legend-form fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> { let parent = self.upcast::<Node>().GetParentElement()?; if parent.is::<HTMLFieldSetElement>() { return self.form_owner(); } None } } impl FormControl for HTMLLegendElement { fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> { self.form_owner.get() } fn set_form_owner(&self, form: Option<&HTMLFormElement>) { self.form_owner.set(form); } fn to_element<'a>(&'a self) -> &'a Element { self.upcast::<Element>() } }
use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::document::Document;
random_line_split
htmllegendelement.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::HTMLLegendElementBinding; use dom::bindings::codegen::Bindings::HTMLLegendElementBinding::HTMLLegendElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::document::Document; use dom::element::Element; use dom::htmlelement::HTMLElement; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlformelement::{HTMLFormElement, FormControl}; use dom::node::{Node, UnbindContext}; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLLegendElement { htmlelement: HTMLElement, form_owner: MutNullableDom<HTMLFormElement>, } impl HTMLLegendElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLLegendElement { HTMLLegendElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), form_owner: Default::default(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLLegendElement> { Node::reflect_node(Box::new(HTMLLegendElement::new_inherited(local_name, prefix, document)), document, HTMLLegendElementBinding::Wrap) } } impl VirtualMethods for HTMLLegendElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext)
} impl HTMLLegendElementMethods for HTMLLegendElement { // https://html.spec.whatwg.org/multipage/#dom-legend-form fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> { let parent = self.upcast::<Node>().GetParentElement()?; if parent.is::<HTMLFieldSetElement>() { return self.form_owner(); } None } } impl FormControl for HTMLLegendElement { fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> { self.form_owner.get() } fn set_form_owner(&self, form: Option<&HTMLFormElement>) { self.form_owner.set(form); } fn to_element<'a>(&'a self) -> &'a Element { self.upcast::<Element>() } }
{ self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); } }
identifier_body
context.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/. */ //! The context within which style is calculated. use animation::Animation; use app_units::Au; use dom::OpaqueNode; use error_reporting::ParseErrorReporter; use euclid::Size2D; use matching::StyleSharingCandidateCache; use parking_lot::RwLock; use selector_matching::Stylist; use std::cell::RefCell; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::sync::mpsc::Sender; use timer::Timer; /// This structure is used to create a local style context from a shared one. pub struct LocalStyleContextCreationInfo { new_animations_sender: Sender<Animation>, } impl LocalStyleContextCreationInfo { pub fn new(animations_sender: Sender<Animation>) -> Self { LocalStyleContextCreationInfo { new_animations_sender: animations_sender, } } } pub struct SharedStyleContext { /// The current viewport size. pub viewport_size: Size2D<Au>,
/// Screen sized changed? pub screen_size_changed: bool, /// The CSS selector stylist. pub stylist: Arc<Stylist>, /// Starts at zero, and increased by one every time a layout completes. /// This can be used to easily check for invalid stale data. pub generation: u32, /// Why is this reflow occurring pub goal: ReflowGoal, /// The animations that are currently running. pub running_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired since the last style recalculation. pub expired_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, ///The CSS error reporter for all CSS loaded in this layout thread pub error_reporter: Box<ParseErrorReporter + Sync>, /// Data needed to create the local style context from the shared one. pub local_context_creation_data: Mutex<LocalStyleContextCreationInfo>, /// The current timer for transitions and animations. This is needed to test /// them. pub timer: Timer, } pub struct LocalStyleContext { pub style_sharing_candidate_cache: RefCell<StyleSharingCandidateCache>, /// A channel on which new animations that have been triggered by style /// recalculation can be sent. pub new_animations_sender: Sender<Animation>, } impl LocalStyleContext { pub fn new(local_context_creation_data: &LocalStyleContextCreationInfo) -> Self { LocalStyleContext { style_sharing_candidate_cache: RefCell::new(StyleSharingCandidateCache::new()), new_animations_sender: local_context_creation_data.new_animations_sender.clone(), } } } pub trait StyleContext<'a> { fn shared_context(&self) -> &'a SharedStyleContext; fn local_context(&self) -> &LocalStyleContext; } /// Why we're doing reflow. #[derive(PartialEq, Copy, Clone, Debug)] pub enum ReflowGoal { /// We're reflowing in order to send a display list to the screen. ForDisplay, /// We're reflowing in order to satisfy a script query. No display list will be created. ForScriptQuery, }
random_line_split
context.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/. */ //! The context within which style is calculated. use animation::Animation; use app_units::Au; use dom::OpaqueNode; use error_reporting::ParseErrorReporter; use euclid::Size2D; use matching::StyleSharingCandidateCache; use parking_lot::RwLock; use selector_matching::Stylist; use std::cell::RefCell; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::sync::mpsc::Sender; use timer::Timer; /// This structure is used to create a local style context from a shared one. pub struct LocalStyleContextCreationInfo { new_animations_sender: Sender<Animation>, } impl LocalStyleContextCreationInfo { pub fn new(animations_sender: Sender<Animation>) -> Self { LocalStyleContextCreationInfo { new_animations_sender: animations_sender, } } } pub struct SharedStyleContext { /// The current viewport size. pub viewport_size: Size2D<Au>, /// Screen sized changed? pub screen_size_changed: bool, /// The CSS selector stylist. pub stylist: Arc<Stylist>, /// Starts at zero, and increased by one every time a layout completes. /// This can be used to easily check for invalid stale data. pub generation: u32, /// Why is this reflow occurring pub goal: ReflowGoal, /// The animations that are currently running. pub running_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired since the last style recalculation. pub expired_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, ///The CSS error reporter for all CSS loaded in this layout thread pub error_reporter: Box<ParseErrorReporter + Sync>, /// Data needed to create the local style context from the shared one. pub local_context_creation_data: Mutex<LocalStyleContextCreationInfo>, /// The current timer for transitions and animations. This is needed to test /// them. pub timer: Timer, } pub struct LocalStyleContext { pub style_sharing_candidate_cache: RefCell<StyleSharingCandidateCache>, /// A channel on which new animations that have been triggered by style /// recalculation can be sent. pub new_animations_sender: Sender<Animation>, } impl LocalStyleContext { pub fn new(local_context_creation_data: &LocalStyleContextCreationInfo) -> Self { LocalStyleContext { style_sharing_candidate_cache: RefCell::new(StyleSharingCandidateCache::new()), new_animations_sender: local_context_creation_data.new_animations_sender.clone(), } } } pub trait StyleContext<'a> { fn shared_context(&self) -> &'a SharedStyleContext; fn local_context(&self) -> &LocalStyleContext; } /// Why we're doing reflow. #[derive(PartialEq, Copy, Clone, Debug)] pub enum
{ /// We're reflowing in order to send a display list to the screen. ForDisplay, /// We're reflowing in order to satisfy a script query. No display list will be created. ForScriptQuery, }
ReflowGoal
identifier_name
core.rs
// Core types. // Copyright (c) 2015 by Shipeng Feng. // Licensed under the BSD License, see LICENSE for more details. use std::os; use std::path::Path; use std::slice::SliceConcatExt; use getopts; use types::{Params, CommandCallback}; use types::{Options, Argument}; use formatting::HelpFormatter; /// The command is the basic type of command line applications in cli. This /// handles command line parsing. pub struct Command { name: String, // The name of the command to use callback: CommandCallback, // The callback to execute options: Vec<Options>, // The options to register with this command arguments: Vec<Argument>, // The arguments to register with this command help: String, // The help message to use for this command epilog: String, // Printed at the end of the help page short_help: String, // The short help to use for this command, this is shown on the command listing of the parent command } impl Command { pub fn new(name: &str, callback: CommandCallback) -> Command { Command { name: name.to_string(), callback: callback, options: Vec::new(), arguments: Vec::new(), help: String::new(), epilog: String::new(), short_help: String::new(), } } /// Attaches an option to the command. pub fn option(&mut self, short_name: &'static str, long_name: &'static str, help: &'static str, is_flag: bool, is_bool_flag: bool, multiple: bool, required: bool, default: Option<&'static str>) { let option = Options::new(short_name, long_name, help, is_flag, is_bool_flag, multiple, required, default); self.options.push(option); } /// Attaches an argument to the command. pub fn argument(&mut self, name: &'static str, required: bool, default: Option<&'static str>) { let argument = Argument::new(name, required, default); self.arguments.push(argument); } fn make_formatter(&self) -> HelpFormatter { HelpFormatter::new(80, 2) } fn format_usage(&self, formatter: &mut HelpFormatter) { let mut pieces: Vec<String> = Vec::new(); pieces.push("[OPTIONS]".to_string()); for argument in self.arguments.iter() { pieces.push(argument.get_usage_piece()); } formatter.write_usage(self.name.as_slice(), pieces.concat(), "Usage: ") } pub fn get_usage(&self) -> String { let mut formatter = self.make_formatter(); self.format_usage(&mut formatter); formatter.getvalue() } fn format_help_text(&self, formatter: &mut HelpFormatter) { if!self.help.is_empty() { formatter.write_paragraph(); formatter.indent(); formatter.write_text(self.help.clone()); formatter.dedent(); } } fn format_options(&self, formatter: &mut HelpFormatter) { let mut opts: Vec<(String, String)> = Vec::new(); for option in self.get_options().iter() { opts.push(option.get_help_record()); } if!opts.is_empty() { formatter.enter_section("Options"); formatter.write_dl(opts); formatter.exit_section(); } } fn format_epilog(&self, formatter: &mut HelpFormatter) { if!self.epilog.is_empty() { formatter.write_paragraph(); formatter.indent(); formatter.write_text(self.epilog.clone()); formatter.dedent(); } } fn format_help(&self, formatter: &mut HelpFormatter)
pub fn get_help(&self) -> String { let mut formatter = self.make_formatter(); self.format_help(&mut formatter); formatter.getvalue() } /// Returns the help option. fn get_help_option(&self) -> Options { let help_option_names = vec!["h", "help"]; let show_help = |params: Params| { print!("{}", self.get_help()); }; return Options::new(help_option_names[0], help_option_names[1], "Show this message and exit.", true, true, false, false, None); } /// This invokes the command with given arguments. pub fn invoke(&self, pragram_name: String, args: Vec<String>) { let args = self.parse_args(args); let callback = self.callback; callback(args); } /// Get all options plus help option. fn get_options(&self) -> Vec<Options> { let mut options: Vec<Options> = Vec::new(); for option in self.options.iter() { options.push(option.clone()); } let help_option = self.get_help_option(); options.push(help_option); return options; } /// Creates the underlying option parser for this command. fn make_parser(&self) -> getopts::Options { let mut parser = getopts::Options::new(); for option in self.get_options().iter() { option.add_to_parser(&mut parser); } return parser; } /// Create the parser and parses the arguments. fn parse_args(&self, args: Vec<String>) -> Vec<String> { args } /// This is the way to run one command application. pub fn run(&self) { let mut args = os::args(); let program = args.remove(0); let program_path = Path::new(program.as_slice()); let program_name = program_path.file_name().unwrap().to_str().unwrap(); // Hook for the Bash completion. // bashcomplete(self, program_name); self.invoke(program_name.to_string(), args); } }
{ self.format_usage(formatter); self.format_help_text(formatter); self.format_options(formatter); self.format_epilog(formatter); }
identifier_body
core.rs
// Core types. // Copyright (c) 2015 by Shipeng Feng. // Licensed under the BSD License, see LICENSE for more details. use std::os; use std::path::Path; use std::slice::SliceConcatExt; use getopts; use types::{Params, CommandCallback}; use types::{Options, Argument}; use formatting::HelpFormatter; /// The command is the basic type of command line applications in cli. This /// handles command line parsing. pub struct Command { name: String, // The name of the command to use callback: CommandCallback, // The callback to execute options: Vec<Options>, // The options to register with this command arguments: Vec<Argument>, // The arguments to register with this command help: String, // The help message to use for this command epilog: String, // Printed at the end of the help page short_help: String, // The short help to use for this command, this is shown on the command listing of the parent command } impl Command { pub fn new(name: &str, callback: CommandCallback) -> Command { Command { name: name.to_string(), callback: callback, options: Vec::new(), arguments: Vec::new(), help: String::new(), epilog: String::new(), short_help: String::new(), } } /// Attaches an option to the command. pub fn option(&mut self, short_name: &'static str, long_name: &'static str, help: &'static str, is_flag: bool, is_bool_flag: bool, multiple: bool, required: bool, default: Option<&'static str>) { let option = Options::new(short_name, long_name, help, is_flag, is_bool_flag, multiple, required, default); self.options.push(option); } /// Attaches an argument to the command. pub fn argument(&mut self, name: &'static str, required: bool, default: Option<&'static str>) { let argument = Argument::new(name, required, default); self.arguments.push(argument); } fn make_formatter(&self) -> HelpFormatter { HelpFormatter::new(80, 2) } fn format_usage(&self, formatter: &mut HelpFormatter) { let mut pieces: Vec<String> = Vec::new(); pieces.push("[OPTIONS]".to_string()); for argument in self.arguments.iter() { pieces.push(argument.get_usage_piece()); } formatter.write_usage(self.name.as_slice(), pieces.concat(), "Usage: ") } pub fn get_usage(&self) -> String { let mut formatter = self.make_formatter(); self.format_usage(&mut formatter); formatter.getvalue() } fn format_help_text(&self, formatter: &mut HelpFormatter) { if!self.help.is_empty() { formatter.write_paragraph(); formatter.indent(); formatter.write_text(self.help.clone()); formatter.dedent(); } } fn format_options(&self, formatter: &mut HelpFormatter) { let mut opts: Vec<(String, String)> = Vec::new(); for option in self.get_options().iter() { opts.push(option.get_help_record()); } if!opts.is_empty() { formatter.enter_section("Options"); formatter.write_dl(opts); formatter.exit_section(); } } fn format_epilog(&self, formatter: &mut HelpFormatter) { if!self.epilog.is_empty() { formatter.write_paragraph(); formatter.indent(); formatter.write_text(self.epilog.clone()); formatter.dedent(); } } fn format_help(&self, formatter: &mut HelpFormatter) { self.format_usage(formatter); self.format_help_text(formatter); self.format_options(formatter); self.format_epilog(formatter); } pub fn get_help(&self) -> String { let mut formatter = self.make_formatter(); self.format_help(&mut formatter); formatter.getvalue() } /// Returns the help option. fn get_help_option(&self) -> Options { let help_option_names = vec!["h", "help"]; let show_help = |params: Params| { print!("{}", self.get_help()); }; return Options::new(help_option_names[0], help_option_names[1], "Show this message and exit.", true, true, false, false, None); } /// This invokes the command with given arguments. pub fn invoke(&self, pragram_name: String, args: Vec<String>) { let args = self.parse_args(args); let callback = self.callback; callback(args); } /// Get all options plus help option. fn get_options(&self) -> Vec<Options> { let mut options: Vec<Options> = Vec::new(); for option in self.options.iter() { options.push(option.clone()); } let help_option = self.get_help_option(); options.push(help_option); return options; } /// Creates the underlying option parser for this command. fn
(&self) -> getopts::Options { let mut parser = getopts::Options::new(); for option in self.get_options().iter() { option.add_to_parser(&mut parser); } return parser; } /// Create the parser and parses the arguments. fn parse_args(&self, args: Vec<String>) -> Vec<String> { args } /// This is the way to run one command application. pub fn run(&self) { let mut args = os::args(); let program = args.remove(0); let program_path = Path::new(program.as_slice()); let program_name = program_path.file_name().unwrap().to_str().unwrap(); // Hook for the Bash completion. // bashcomplete(self, program_name); self.invoke(program_name.to_string(), args); } }
make_parser
identifier_name
core.rs
// Core types. // Copyright (c) 2015 by Shipeng Feng. // Licensed under the BSD License, see LICENSE for more details. use std::os; use std::path::Path; use std::slice::SliceConcatExt; use getopts; use types::{Params, CommandCallback}; use types::{Options, Argument}; use formatting::HelpFormatter; /// The command is the basic type of command line applications in cli. This /// handles command line parsing. pub struct Command { name: String, // The name of the command to use callback: CommandCallback, // The callback to execute options: Vec<Options>, // The options to register with this command arguments: Vec<Argument>, // The arguments to register with this command help: String, // The help message to use for this command epilog: String, // Printed at the end of the help page short_help: String, // The short help to use for this command, this is shown on the command listing of the parent command } impl Command { pub fn new(name: &str, callback: CommandCallback) -> Command { Command { name: name.to_string(), callback: callback, options: Vec::new(), arguments: Vec::new(), help: String::new(), epilog: String::new(), short_help: String::new(), } } /// Attaches an option to the command. pub fn option(&mut self, short_name: &'static str, long_name: &'static str, help: &'static str, is_flag: bool, is_bool_flag: bool, multiple: bool, required: bool, default: Option<&'static str>) { let option = Options::new(short_name, long_name, help, is_flag, is_bool_flag, multiple, required, default); self.options.push(option); } /// Attaches an argument to the command. pub fn argument(&mut self, name: &'static str, required: bool, default: Option<&'static str>) { let argument = Argument::new(name, required, default); self.arguments.push(argument); } fn make_formatter(&self) -> HelpFormatter { HelpFormatter::new(80, 2) } fn format_usage(&self, formatter: &mut HelpFormatter) { let mut pieces: Vec<String> = Vec::new(); pieces.push("[OPTIONS]".to_string()); for argument in self.arguments.iter() { pieces.push(argument.get_usage_piece()); } formatter.write_usage(self.name.as_slice(), pieces.concat(), "Usage: ") } pub fn get_usage(&self) -> String { let mut formatter = self.make_formatter(); self.format_usage(&mut formatter); formatter.getvalue() } fn format_help_text(&self, formatter: &mut HelpFormatter) {
formatter.dedent(); } } fn format_options(&self, formatter: &mut HelpFormatter) { let mut opts: Vec<(String, String)> = Vec::new(); for option in self.get_options().iter() { opts.push(option.get_help_record()); } if!opts.is_empty() { formatter.enter_section("Options"); formatter.write_dl(opts); formatter.exit_section(); } } fn format_epilog(&self, formatter: &mut HelpFormatter) { if!self.epilog.is_empty() { formatter.write_paragraph(); formatter.indent(); formatter.write_text(self.epilog.clone()); formatter.dedent(); } } fn format_help(&self, formatter: &mut HelpFormatter) { self.format_usage(formatter); self.format_help_text(formatter); self.format_options(formatter); self.format_epilog(formatter); } pub fn get_help(&self) -> String { let mut formatter = self.make_formatter(); self.format_help(&mut formatter); formatter.getvalue() } /// Returns the help option. fn get_help_option(&self) -> Options { let help_option_names = vec!["h", "help"]; let show_help = |params: Params| { print!("{}", self.get_help()); }; return Options::new(help_option_names[0], help_option_names[1], "Show this message and exit.", true, true, false, false, None); } /// This invokes the command with given arguments. pub fn invoke(&self, pragram_name: String, args: Vec<String>) { let args = self.parse_args(args); let callback = self.callback; callback(args); } /// Get all options plus help option. fn get_options(&self) -> Vec<Options> { let mut options: Vec<Options> = Vec::new(); for option in self.options.iter() { options.push(option.clone()); } let help_option = self.get_help_option(); options.push(help_option); return options; } /// Creates the underlying option parser for this command. fn make_parser(&self) -> getopts::Options { let mut parser = getopts::Options::new(); for option in self.get_options().iter() { option.add_to_parser(&mut parser); } return parser; } /// Create the parser and parses the arguments. fn parse_args(&self, args: Vec<String>) -> Vec<String> { args } /// This is the way to run one command application. pub fn run(&self) { let mut args = os::args(); let program = args.remove(0); let program_path = Path::new(program.as_slice()); let program_name = program_path.file_name().unwrap().to_str().unwrap(); // Hook for the Bash completion. // bashcomplete(self, program_name); self.invoke(program_name.to_string(), args); } }
if !self.help.is_empty() { formatter.write_paragraph(); formatter.indent(); formatter.write_text(self.help.clone());
random_line_split
core.rs
// Core types. // Copyright (c) 2015 by Shipeng Feng. // Licensed under the BSD License, see LICENSE for more details. use std::os; use std::path::Path; use std::slice::SliceConcatExt; use getopts; use types::{Params, CommandCallback}; use types::{Options, Argument}; use formatting::HelpFormatter; /// The command is the basic type of command line applications in cli. This /// handles command line parsing. pub struct Command { name: String, // The name of the command to use callback: CommandCallback, // The callback to execute options: Vec<Options>, // The options to register with this command arguments: Vec<Argument>, // The arguments to register with this command help: String, // The help message to use for this command epilog: String, // Printed at the end of the help page short_help: String, // The short help to use for this command, this is shown on the command listing of the parent command } impl Command { pub fn new(name: &str, callback: CommandCallback) -> Command { Command { name: name.to_string(), callback: callback, options: Vec::new(), arguments: Vec::new(), help: String::new(), epilog: String::new(), short_help: String::new(), } } /// Attaches an option to the command. pub fn option(&mut self, short_name: &'static str, long_name: &'static str, help: &'static str, is_flag: bool, is_bool_flag: bool, multiple: bool, required: bool, default: Option<&'static str>) { let option = Options::new(short_name, long_name, help, is_flag, is_bool_flag, multiple, required, default); self.options.push(option); } /// Attaches an argument to the command. pub fn argument(&mut self, name: &'static str, required: bool, default: Option<&'static str>) { let argument = Argument::new(name, required, default); self.arguments.push(argument); } fn make_formatter(&self) -> HelpFormatter { HelpFormatter::new(80, 2) } fn format_usage(&self, formatter: &mut HelpFormatter) { let mut pieces: Vec<String> = Vec::new(); pieces.push("[OPTIONS]".to_string()); for argument in self.arguments.iter() { pieces.push(argument.get_usage_piece()); } formatter.write_usage(self.name.as_slice(), pieces.concat(), "Usage: ") } pub fn get_usage(&self) -> String { let mut formatter = self.make_formatter(); self.format_usage(&mut formatter); formatter.getvalue() } fn format_help_text(&self, formatter: &mut HelpFormatter) { if!self.help.is_empty() { formatter.write_paragraph(); formatter.indent(); formatter.write_text(self.help.clone()); formatter.dedent(); } } fn format_options(&self, formatter: &mut HelpFormatter) { let mut opts: Vec<(String, String)> = Vec::new(); for option in self.get_options().iter() { opts.push(option.get_help_record()); } if!opts.is_empty()
} fn format_epilog(&self, formatter: &mut HelpFormatter) { if!self.epilog.is_empty() { formatter.write_paragraph(); formatter.indent(); formatter.write_text(self.epilog.clone()); formatter.dedent(); } } fn format_help(&self, formatter: &mut HelpFormatter) { self.format_usage(formatter); self.format_help_text(formatter); self.format_options(formatter); self.format_epilog(formatter); } pub fn get_help(&self) -> String { let mut formatter = self.make_formatter(); self.format_help(&mut formatter); formatter.getvalue() } /// Returns the help option. fn get_help_option(&self) -> Options { let help_option_names = vec!["h", "help"]; let show_help = |params: Params| { print!("{}", self.get_help()); }; return Options::new(help_option_names[0], help_option_names[1], "Show this message and exit.", true, true, false, false, None); } /// This invokes the command with given arguments. pub fn invoke(&self, pragram_name: String, args: Vec<String>) { let args = self.parse_args(args); let callback = self.callback; callback(args); } /// Get all options plus help option. fn get_options(&self) -> Vec<Options> { let mut options: Vec<Options> = Vec::new(); for option in self.options.iter() { options.push(option.clone()); } let help_option = self.get_help_option(); options.push(help_option); return options; } /// Creates the underlying option parser for this command. fn make_parser(&self) -> getopts::Options { let mut parser = getopts::Options::new(); for option in self.get_options().iter() { option.add_to_parser(&mut parser); } return parser; } /// Create the parser and parses the arguments. fn parse_args(&self, args: Vec<String>) -> Vec<String> { args } /// This is the way to run one command application. pub fn run(&self) { let mut args = os::args(); let program = args.remove(0); let program_path = Path::new(program.as_slice()); let program_name = program_path.file_name().unwrap().to_str().unwrap(); // Hook for the Bash completion. // bashcomplete(self, program_name); self.invoke(program_name.to_string(), args); } }
{ formatter.enter_section("Options"); formatter.write_dl(opts); formatter.exit_section(); }
conditional_block
bluetoothadvertisingdata.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::BluetoothAdvertisingDataBinding; use dom::bindings::codegen::Bindings::BluetoothAdvertisingDataBinding::BluetoothAdvertisingDataMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; // https://webbluetoothcg.github.io/web-bluetooth/#bluetoothadvertisingdata #[dom_struct] pub struct BluetoothAdvertisingData { reflector_: Reflector, appearance: u16, txPower: i8, rssi: i8, } impl BluetoothAdvertisingData { pub fn new_inherited(appearance: u16, txPower: i8, rssi: i8) -> BluetoothAdvertisingData
pub fn new(global: GlobalRef, appearance: u16, txPower: i8, rssi: i8) -> Root<BluetoothAdvertisingData> { reflect_dom_object(box BluetoothAdvertisingData::new_inherited(appearance, txPower, rssi), global, BluetoothAdvertisingDataBinding::Wrap) } } impl BluetoothAdvertisingDataMethods for BluetoothAdvertisingData { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingdata-appearance fn GetAppearance(&self) -> Option<u16> { Some(self.appearance) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingdata-txpower fn GetTxPower(&self) -> Option<i8> { Some(self.txPower) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingdata-rssi fn GetRssi(&self) -> Option<i8> { Some(self.rssi) } }
{ BluetoothAdvertisingData { reflector_: Reflector::new(), appearance: appearance, txPower: txPower, rssi: rssi, } }
identifier_body
bluetoothadvertisingdata.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::BluetoothAdvertisingDataBinding; use dom::bindings::codegen::Bindings::BluetoothAdvertisingDataBinding::BluetoothAdvertisingDataMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; // https://webbluetoothcg.github.io/web-bluetooth/#bluetoothadvertisingdata #[dom_struct] pub struct BluetoothAdvertisingData { reflector_: Reflector, appearance: u16, txPower: i8, rssi: i8, } impl BluetoothAdvertisingData { pub fn new_inherited(appearance: u16, txPower: i8, rssi: i8) -> BluetoothAdvertisingData { BluetoothAdvertisingData { reflector_: Reflector::new(), appearance: appearance, txPower: txPower, rssi: rssi, } } pub fn new(global: GlobalRef, appearance: u16, txPower: i8, rssi: i8) -> Root<BluetoothAdvertisingData> { reflect_dom_object(box BluetoothAdvertisingData::new_inherited(appearance, txPower, rssi), global, BluetoothAdvertisingDataBinding::Wrap) } } impl BluetoothAdvertisingDataMethods for BluetoothAdvertisingData { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingdata-appearance fn GetAppearance(&self) -> Option<u16> { Some(self.appearance) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingdata-txpower fn GetTxPower(&self) -> Option<i8> { Some(self.txPower) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingdata-rssi fn GetRssi(&self) -> Option<i8> { Some(self.rssi)
} }
random_line_split
bluetoothadvertisingdata.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::BluetoothAdvertisingDataBinding; use dom::bindings::codegen::Bindings::BluetoothAdvertisingDataBinding::BluetoothAdvertisingDataMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; // https://webbluetoothcg.github.io/web-bluetooth/#bluetoothadvertisingdata #[dom_struct] pub struct BluetoothAdvertisingData { reflector_: Reflector, appearance: u16, txPower: i8, rssi: i8, } impl BluetoothAdvertisingData { pub fn
(appearance: u16, txPower: i8, rssi: i8) -> BluetoothAdvertisingData { BluetoothAdvertisingData { reflector_: Reflector::new(), appearance: appearance, txPower: txPower, rssi: rssi, } } pub fn new(global: GlobalRef, appearance: u16, txPower: i8, rssi: i8) -> Root<BluetoothAdvertisingData> { reflect_dom_object(box BluetoothAdvertisingData::new_inherited(appearance, txPower, rssi), global, BluetoothAdvertisingDataBinding::Wrap) } } impl BluetoothAdvertisingDataMethods for BluetoothAdvertisingData { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingdata-appearance fn GetAppearance(&self) -> Option<u16> { Some(self.appearance) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingdata-txpower fn GetTxPower(&self) -> Option<i8> { Some(self.txPower) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingdata-rssi fn GetRssi(&self) -> Option<i8> { Some(self.rssi) } }
new_inherited
identifier_name
number.rs
// Copyright 2017 ThetaSinner // // This file is part of Osmium. // Osmium is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Osmium is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Osmium. If not, see <http://www.gnu.org/licenses/>. // std use std::slice::Iter; use std::iter::Peekable; /// Representation for an encoded number as defined by hpack section 5.1 #[derive(Debug)] pub struct EncodedNumber { pub prefix: u8, pub rest: Option<Vec<u8>> } #[derive(Debug)] pub struct DecodedNumber { pub num: u32, pub octets_read: usize } // TODO is u32 the right type to use? probably want to allow number to get as big as they can before they're capped. // maybe use usize instead? // see above, usize is pointer sized (32 bits in x86 and 64 bits on x86_64) which would mean the server adapts to the system it runs on? // and the server can use the max sizes provided by rust to decide which values are too large to decode at runtime. // n here is N in the hpack encoding instructions. // n must lie between 1 and 8 inclusive pub fn encode(num: u32, n: u8) -> EncodedNumber { if num < (1 << n) - 1 { return EncodedNumber { prefix: num as u8, rest: None } } let two_pow_n_minus_one = (1 << n) - 1; let mut rest = Vec::new(); let mut _num = num - two_pow_n_minus_one; while _num >= 128 { rest.push(((_num % 128) + 128) as u8); _num = _num / 128; } rest.push(_num as u8); EncodedNumber { prefix: two_pow_n_minus_one as u8, rest: Some(rest) } } // TODO must reject encodings which overflow integer on decode. // octets must have length at least 1 // n must be between 1 and 8 inclusive pub fn decode(octets: &mut Peekable<Iter<u8>>, n: u8) -> DecodedNumber { // turn off bits which should not be checked. let mut num = (*octets.next().unwrap() & (255 >> (8 - n))) as u32; if num < (1 << n) - 1 { return DecodedNumber { num: num, octets_read: 1 }; } // We have read the prefix already, now count how many octets are in the rest list. let mut octets_read = 1; let mut m = 0; while let Some(&octet) = octets.peek() { num = num + (octet & 127) as u32 * (1 << m); m = m + 7; octets_read += 1; octets.next(); if octet & 128!= 128
} DecodedNumber { num: num, octets_read: octets_read } } #[cfg(test)] mod tests { use super::{encode, decode}; // slightly clumsy function to print the bits of a u8. // it's useful even if it's bad :) #[allow(unused)] pub fn print_binary(octet: u8) { let mut bits = [0, 0, 0, 0, 0, 0, 0, 0]; for i in 0..8 { let filter = 2i32.pow(i as u32) as u8; bits[7 - i] = (octet & filter == filter) as u8; } println!("{:?}", bits); } // See example C.1.1 of hpack instructions. #[test] fn encdode_in_prefix() { let en = encode(10, 5); assert_eq!(10, en.prefix); assert!(en.rest.is_none()); } #[test] fn decode_prefix_only() { let en = encode(10, 5); let octets = vec!(en.prefix); let dn = decode(&mut octets.iter().peekable(), 5); assert_eq!(1, dn.octets_read); assert_eq!(10, dn.num); } // See example C.1.2 of hpack instructions. #[test] fn encode_using_rest() { let en = encode(1337, 5); assert_eq!(31, en.prefix); assert!(en.rest.is_some()); let rest = en.rest.unwrap(); assert_eq!(154, rest[0]); assert_eq!(10, rest[1]); } #[test] fn decode_using_rest() { let en = encode(1337, 5); let mut octets = vec!(en.prefix); octets.extend(en.rest.unwrap()); let de = decode(&mut octets.iter().peekable(), 5); assert_eq!(3, de.octets_read); assert_eq!(1337, de.num); } // See example C.1.3 of hpack instructions. #[test] fn encode_starting_at_octet_boundary() { let en = encode(42, 8); assert_eq!(42, en.prefix); assert!(en.rest.is_none()); } #[test] fn decode_starting_at_octet_boundary() { let en = encode(42, 8); let octets = vec!(en.prefix); let dn = decode(&mut octets.iter().peekable(), 8); assert_eq!(1, dn.octets_read); assert_eq!(42, dn.num); } }
{break;}
conditional_block
number.rs
// Copyright 2017 ThetaSinner // // This file is part of Osmium. // Osmium is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Osmium is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Osmium. If not, see <http://www.gnu.org/licenses/>. // std use std::slice::Iter; use std::iter::Peekable; /// Representation for an encoded number as defined by hpack section 5.1 #[derive(Debug)] pub struct EncodedNumber { pub prefix: u8, pub rest: Option<Vec<u8>> } #[derive(Debug)] pub struct DecodedNumber { pub num: u32, pub octets_read: usize } // TODO is u32 the right type to use? probably want to allow number to get as big as they can before they're capped. // maybe use usize instead? // see above, usize is pointer sized (32 bits in x86 and 64 bits on x86_64) which would mean the server adapts to the system it runs on? // and the server can use the max sizes provided by rust to decide which values are too large to decode at runtime. // n here is N in the hpack encoding instructions. // n must lie between 1 and 8 inclusive pub fn encode(num: u32, n: u8) -> EncodedNumber { if num < (1 << n) - 1 { return EncodedNumber { prefix: num as u8, rest: None } } let two_pow_n_minus_one = (1 << n) - 1; let mut rest = Vec::new(); let mut _num = num - two_pow_n_minus_one; while _num >= 128 { rest.push(((_num % 128) + 128) as u8); _num = _num / 128; } rest.push(_num as u8); EncodedNumber { prefix: two_pow_n_minus_one as u8, rest: Some(rest) } } // TODO must reject encodings which overflow integer on decode.
if num < (1 << n) - 1 { return DecodedNumber { num: num, octets_read: 1 }; } // We have read the prefix already, now count how many octets are in the rest list. let mut octets_read = 1; let mut m = 0; while let Some(&octet) = octets.peek() { num = num + (octet & 127) as u32 * (1 << m); m = m + 7; octets_read += 1; octets.next(); if octet & 128!= 128 {break;} } DecodedNumber { num: num, octets_read: octets_read } } #[cfg(test)] mod tests { use super::{encode, decode}; // slightly clumsy function to print the bits of a u8. // it's useful even if it's bad :) #[allow(unused)] pub fn print_binary(octet: u8) { let mut bits = [0, 0, 0, 0, 0, 0, 0, 0]; for i in 0..8 { let filter = 2i32.pow(i as u32) as u8; bits[7 - i] = (octet & filter == filter) as u8; } println!("{:?}", bits); } // See example C.1.1 of hpack instructions. #[test] fn encdode_in_prefix() { let en = encode(10, 5); assert_eq!(10, en.prefix); assert!(en.rest.is_none()); } #[test] fn decode_prefix_only() { let en = encode(10, 5); let octets = vec!(en.prefix); let dn = decode(&mut octets.iter().peekable(), 5); assert_eq!(1, dn.octets_read); assert_eq!(10, dn.num); } // See example C.1.2 of hpack instructions. #[test] fn encode_using_rest() { let en = encode(1337, 5); assert_eq!(31, en.prefix); assert!(en.rest.is_some()); let rest = en.rest.unwrap(); assert_eq!(154, rest[0]); assert_eq!(10, rest[1]); } #[test] fn decode_using_rest() { let en = encode(1337, 5); let mut octets = vec!(en.prefix); octets.extend(en.rest.unwrap()); let de = decode(&mut octets.iter().peekable(), 5); assert_eq!(3, de.octets_read); assert_eq!(1337, de.num); } // See example C.1.3 of hpack instructions. #[test] fn encode_starting_at_octet_boundary() { let en = encode(42, 8); assert_eq!(42, en.prefix); assert!(en.rest.is_none()); } #[test] fn decode_starting_at_octet_boundary() { let en = encode(42, 8); let octets = vec!(en.prefix); let dn = decode(&mut octets.iter().peekable(), 8); assert_eq!(1, dn.octets_read); assert_eq!(42, dn.num); } }
// octets must have length at least 1 // n must be between 1 and 8 inclusive pub fn decode(octets: &mut Peekable<Iter<u8>>, n: u8) -> DecodedNumber { // turn off bits which should not be checked. let mut num = (*octets.next().unwrap() & (255 >> (8 - n))) as u32;
random_line_split
number.rs
// Copyright 2017 ThetaSinner // // This file is part of Osmium. // Osmium is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Osmium is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Osmium. If not, see <http://www.gnu.org/licenses/>. // std use std::slice::Iter; use std::iter::Peekable; /// Representation for an encoded number as defined by hpack section 5.1 #[derive(Debug)] pub struct EncodedNumber { pub prefix: u8, pub rest: Option<Vec<u8>> } #[derive(Debug)] pub struct DecodedNumber { pub num: u32, pub octets_read: usize } // TODO is u32 the right type to use? probably want to allow number to get as big as they can before they're capped. // maybe use usize instead? // see above, usize is pointer sized (32 bits in x86 and 64 bits on x86_64) which would mean the server adapts to the system it runs on? // and the server can use the max sizes provided by rust to decide which values are too large to decode at runtime. // n here is N in the hpack encoding instructions. // n must lie between 1 and 8 inclusive pub fn encode(num: u32, n: u8) -> EncodedNumber { if num < (1 << n) - 1 { return EncodedNumber { prefix: num as u8, rest: None } } let two_pow_n_minus_one = (1 << n) - 1; let mut rest = Vec::new(); let mut _num = num - two_pow_n_minus_one; while _num >= 128 { rest.push(((_num % 128) + 128) as u8); _num = _num / 128; } rest.push(_num as u8); EncodedNumber { prefix: two_pow_n_minus_one as u8, rest: Some(rest) } } // TODO must reject encodings which overflow integer on decode. // octets must have length at least 1 // n must be between 1 and 8 inclusive pub fn decode(octets: &mut Peekable<Iter<u8>>, n: u8) -> DecodedNumber { // turn off bits which should not be checked. let mut num = (*octets.next().unwrap() & (255 >> (8 - n))) as u32; if num < (1 << n) - 1 { return DecodedNumber { num: num, octets_read: 1 }; } // We have read the prefix already, now count how many octets are in the rest list. let mut octets_read = 1; let mut m = 0; while let Some(&octet) = octets.peek() { num = num + (octet & 127) as u32 * (1 << m); m = m + 7; octets_read += 1; octets.next(); if octet & 128!= 128 {break;} } DecodedNumber { num: num, octets_read: octets_read } } #[cfg(test)] mod tests { use super::{encode, decode}; // slightly clumsy function to print the bits of a u8. // it's useful even if it's bad :) #[allow(unused)] pub fn print_binary(octet: u8) { let mut bits = [0, 0, 0, 0, 0, 0, 0, 0]; for i in 0..8 { let filter = 2i32.pow(i as u32) as u8; bits[7 - i] = (octet & filter == filter) as u8; } println!("{:?}", bits); } // See example C.1.1 of hpack instructions. #[test] fn encdode_in_prefix() { let en = encode(10, 5); assert_eq!(10, en.prefix); assert!(en.rest.is_none()); } #[test] fn decode_prefix_only() { let en = encode(10, 5); let octets = vec!(en.prefix); let dn = decode(&mut octets.iter().peekable(), 5); assert_eq!(1, dn.octets_read); assert_eq!(10, dn.num); } // See example C.1.2 of hpack instructions. #[test] fn encode_using_rest() { let en = encode(1337, 5); assert_eq!(31, en.prefix); assert!(en.rest.is_some()); let rest = en.rest.unwrap(); assert_eq!(154, rest[0]); assert_eq!(10, rest[1]); } #[test] fn decode_using_rest() { let en = encode(1337, 5); let mut octets = vec!(en.prefix); octets.extend(en.rest.unwrap()); let de = decode(&mut octets.iter().peekable(), 5); assert_eq!(3, de.octets_read); assert_eq!(1337, de.num); } // See example C.1.3 of hpack instructions. #[test] fn
() { let en = encode(42, 8); assert_eq!(42, en.prefix); assert!(en.rest.is_none()); } #[test] fn decode_starting_at_octet_boundary() { let en = encode(42, 8); let octets = vec!(en.prefix); let dn = decode(&mut octets.iter().peekable(), 8); assert_eq!(1, dn.octets_read); assert_eq!(42, dn.num); } }
encode_starting_at_octet_boundary
identifier_name
entry.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use toml_query::insert::TomlValueInsertExt; use toml_query::read::TomlValueReadExt; use toml_query::read::TomlValueReadTypeExt; use toml::Value; use libimagstore::store::Entry; use libimagentrylink::linkable::Linkable; use anyhow::Result; use anyhow::Context; use anyhow::Error; use crate::store::CategoryStore; pub trait EntryCategory { fn set_category(&mut self, s: &str) -> Result<()>; fn set_category_checked(&mut self, register: &dyn CategoryStore, s: &str) -> Result<()>; fn get_category(&self) -> Result<String>; fn has_category(&self) -> Result<bool>; fn remove_category(&mut self) -> Result<()>; } impl EntryCategory for Entry { fn set_category(&mut self, s: &str) -> Result<()> { trace!("Setting category '{}' UNCHECKED", s); self.get_header_mut() .insert(&String::from("category.value"), Value::String(s.to_string())) .context(anyhow!("Failed to insert header at 'category.value' of '{}'", self.get_location())) .map_err(Error::from) .map(|_| ()) } /// Check whether a category exists before setting it. /// /// This function should be used by default over EntryCategory::set_category()! fn set_category_checked(&mut self, register: &dyn CategoryStore, s: &str) -> Result<()> { trace!("Setting category '{}' checked", s); let mut category = register .get_category_by_name(s)? .ok_or_else(|| anyhow!("Category does not exist"))?; self.set_category(s)?; self.add_link(&mut category)?; Ok(()) } fn get_category(&self) -> Result<String> { trace!("Getting category from '{}'", self.get_location()); self.get_header() .read_string("category.value")? .ok_or_else(|| anyhow!("Category name missing")) } fn
(&self) -> Result<bool> { trace!("Has category? '{}'", self.get_location()); self.get_header() .read("category.value") .context(anyhow!("Failed to read header at 'category.value' of '{}'", self.get_location())) .map_err(Error::from) .map(|x| x.is_some()) } /// Remove the category setting /// /// # Warning /// /// This does _only_ remove the category setting in the header. This does _not_ remove the /// internal link to the category entry, nor does it remove the category from the store. fn remove_category(&mut self) -> Result<()> { use toml_query::delete::TomlValueDeleteExt; self.get_header_mut() .delete("category.value") .context(anyhow!("Failed to delete header at 'category.value' of '{}'", self.get_location())) .map_err(Error::from) .map(|_| ()) } }
has_category
identifier_name
entry.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use toml_query::insert::TomlValueInsertExt; use toml_query::read::TomlValueReadExt; use toml_query::read::TomlValueReadTypeExt; use toml::Value; use libimagstore::store::Entry; use libimagentrylink::linkable::Linkable; use anyhow::Result; use anyhow::Context; use anyhow::Error; use crate::store::CategoryStore; pub trait EntryCategory { fn set_category(&mut self, s: &str) -> Result<()>; fn set_category_checked(&mut self, register: &dyn CategoryStore, s: &str) -> Result<()>; fn get_category(&self) -> Result<String>; fn has_category(&self) -> Result<bool>; fn remove_category(&mut self) -> Result<()>; } impl EntryCategory for Entry { fn set_category(&mut self, s: &str) -> Result<()> { trace!("Setting category '{}' UNCHECKED", s); self.get_header_mut() .insert(&String::from("category.value"), Value::String(s.to_string())) .context(anyhow!("Failed to insert header at 'category.value' of '{}'", self.get_location())) .map_err(Error::from) .map(|_| ()) } /// Check whether a category exists before setting it. /// /// This function should be used by default over EntryCategory::set_category()! fn set_category_checked(&mut self, register: &dyn CategoryStore, s: &str) -> Result<()> { trace!("Setting category '{}' checked", s);
let mut category = register .get_category_by_name(s)? .ok_or_else(|| anyhow!("Category does not exist"))?; self.set_category(s)?; self.add_link(&mut category)?; Ok(()) } fn get_category(&self) -> Result<String> { trace!("Getting category from '{}'", self.get_location()); self.get_header() .read_string("category.value")? .ok_or_else(|| anyhow!("Category name missing")) } fn has_category(&self) -> Result<bool> { trace!("Has category? '{}'", self.get_location()); self.get_header() .read("category.value") .context(anyhow!("Failed to read header at 'category.value' of '{}'", self.get_location())) .map_err(Error::from) .map(|x| x.is_some()) } /// Remove the category setting /// /// # Warning /// /// This does _only_ remove the category setting in the header. This does _not_ remove the /// internal link to the category entry, nor does it remove the category from the store. fn remove_category(&mut self) -> Result<()> { use toml_query::delete::TomlValueDeleteExt; self.get_header_mut() .delete("category.value") .context(anyhow!("Failed to delete header at 'category.value' of '{}'", self.get_location())) .map_err(Error::from) .map(|_| ()) } }
random_line_split
entry.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use toml_query::insert::TomlValueInsertExt; use toml_query::read::TomlValueReadExt; use toml_query::read::TomlValueReadTypeExt; use toml::Value; use libimagstore::store::Entry; use libimagentrylink::linkable::Linkable; use anyhow::Result; use anyhow::Context; use anyhow::Error; use crate::store::CategoryStore; pub trait EntryCategory { fn set_category(&mut self, s: &str) -> Result<()>; fn set_category_checked(&mut self, register: &dyn CategoryStore, s: &str) -> Result<()>; fn get_category(&self) -> Result<String>; fn has_category(&self) -> Result<bool>; fn remove_category(&mut self) -> Result<()>; } impl EntryCategory for Entry { fn set_category(&mut self, s: &str) -> Result<()> { trace!("Setting category '{}' UNCHECKED", s); self.get_header_mut() .insert(&String::from("category.value"), Value::String(s.to_string())) .context(anyhow!("Failed to insert header at 'category.value' of '{}'", self.get_location())) .map_err(Error::from) .map(|_| ()) } /// Check whether a category exists before setting it. /// /// This function should be used by default over EntryCategory::set_category()! fn set_category_checked(&mut self, register: &dyn CategoryStore, s: &str) -> Result<()> { trace!("Setting category '{}' checked", s); let mut category = register .get_category_by_name(s)? .ok_or_else(|| anyhow!("Category does not exist"))?; self.set_category(s)?; self.add_link(&mut category)?; Ok(()) } fn get_category(&self) -> Result<String>
fn has_category(&self) -> Result<bool> { trace!("Has category? '{}'", self.get_location()); self.get_header() .read("category.value") .context(anyhow!("Failed to read header at 'category.value' of '{}'", self.get_location())) .map_err(Error::from) .map(|x| x.is_some()) } /// Remove the category setting /// /// # Warning /// /// This does _only_ remove the category setting in the header. This does _not_ remove the /// internal link to the category entry, nor does it remove the category from the store. fn remove_category(&mut self) -> Result<()> { use toml_query::delete::TomlValueDeleteExt; self.get_header_mut() .delete("category.value") .context(anyhow!("Failed to delete header at 'category.value' of '{}'", self.get_location())) .map_err(Error::from) .map(|_| ()) } }
{ trace!("Getting category from '{}'", self.get_location()); self.get_header() .read_string("category.value")? .ok_or_else(|| anyhow!("Category name missing")) }
identifier_body
font_cache_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::SourceLocation; use gfx::font_cache_thread::FontCacheThread; use ipc_channel::ipc; use style::computed_values::font_family::{FamilyName, FamilyNameSyntax}; use style::font_face::{FontFaceRuleData, Source}; #[test] fn
() { let (inp_chan, _) = ipc::channel().unwrap(); let (out_chan, out_receiver) = ipc::channel().unwrap(); let font_cache_thread = FontCacheThread::new(inp_chan, None); let family_name = FamilyName { name: From::from("test family"), syntax: FamilyNameSyntax::Quoted, }; let variant_name = FamilyName { name: From::from("test font face"), syntax: FamilyNameSyntax::Quoted, }; let font_face_rule = FontFaceRuleData { family: Some(family_name.clone()), sources: Some(vec![Source::Local(variant_name)]), source_location: SourceLocation { line: 0, column: 0, }, }; font_cache_thread.add_web_font( family_name, font_face_rule.font_face().unwrap().effective_sources(), out_chan); assert_eq!(out_receiver.recv().unwrap(), ()); }
test_local_web_font
identifier_name
font_cache_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::SourceLocation; use gfx::font_cache_thread::FontCacheThread;
#[test] fn test_local_web_font() { let (inp_chan, _) = ipc::channel().unwrap(); let (out_chan, out_receiver) = ipc::channel().unwrap(); let font_cache_thread = FontCacheThread::new(inp_chan, None); let family_name = FamilyName { name: From::from("test family"), syntax: FamilyNameSyntax::Quoted, }; let variant_name = FamilyName { name: From::from("test font face"), syntax: FamilyNameSyntax::Quoted, }; let font_face_rule = FontFaceRuleData { family: Some(family_name.clone()), sources: Some(vec![Source::Local(variant_name)]), source_location: SourceLocation { line: 0, column: 0, }, }; font_cache_thread.add_web_font( family_name, font_face_rule.font_face().unwrap().effective_sources(), out_chan); assert_eq!(out_receiver.recv().unwrap(), ()); }
use ipc_channel::ipc; use style::computed_values::font_family::{FamilyName, FamilyNameSyntax}; use style::font_face::{FontFaceRuleData, Source};
random_line_split
font_cache_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::SourceLocation; use gfx::font_cache_thread::FontCacheThread; use ipc_channel::ipc; use style::computed_values::font_family::{FamilyName, FamilyNameSyntax}; use style::font_face::{FontFaceRuleData, Source}; #[test] fn test_local_web_font()
font_cache_thread.add_web_font( family_name, font_face_rule.font_face().unwrap().effective_sources(), out_chan); assert_eq!(out_receiver.recv().unwrap(), ()); }
{ let (inp_chan, _) = ipc::channel().unwrap(); let (out_chan, out_receiver) = ipc::channel().unwrap(); let font_cache_thread = FontCacheThread::new(inp_chan, None); let family_name = FamilyName { name: From::from("test family"), syntax: FamilyNameSyntax::Quoted, }; let variant_name = FamilyName { name: From::from("test font face"), syntax: FamilyNameSyntax::Quoted, }; let font_face_rule = FontFaceRuleData { family: Some(family_name.clone()), sources: Some(vec![Source::Local(variant_name)]), source_location: SourceLocation { line: 0, column: 0, }, };
identifier_body
x86_64.rs
#[repr(C)] #[derive(Copy)] pub struct lconv { pub decimal_point: *mut ::char_t, pub thousands_sep: *mut ::char_t, pub grouping: *mut ::char_t, pub int_curr_symbol: *mut ::char_t, pub currency_symbol: *mut ::char_t, pub mon_decimal_point: *mut ::char_t, pub mon_thousands_sep: *mut ::char_t, pub mon_grouping: *mut ::char_t, pub positive_sign: *mut ::char_t, pub negative_sign: *mut ::char_t, pub int_frac_digits: ::char_t, pub frac_digits: ::char_t, pub p_cs_precedes: ::char_t, pub p_sep_by_space: ::char_t, pub n_cs_precedes: ::char_t, pub n_sep_by_space: ::char_t, pub p_sign_posn: ::char_t, pub n_sign_posn: ::char_t, pub int_p_cs_precedes: ::char_t, pub int_p_sep_by_space: ::char_t, pub int_n_cs_precedes: ::char_t, pub int_n_sep_by_space: ::char_t, pub int_p_sign_posn: ::char_t, pub int_n_sign_posn: ::char_t, } new!(lconv); pub type locale_t = *mut ::void_t; pub const LC_ALL: ::int_t = 6; pub const LC_COLLATE: ::int_t = 3; pub const LC_CTYPE: ::int_t = 0; pub const LC_MESSAGES: ::int_t = 5; pub const LC_MONETARY: ::int_t = 4; pub const LC_NUMERIC: ::int_t = 1; pub const LC_TIME: ::int_t = 2; pub const LC_COLLATE_MASK: ::int_t = 8; pub const LC_CTYPE_MASK: ::int_t = 1; pub const LC_MESSAGES_MASK: ::int_t = 32; pub const LC_MONETARY_MASK: ::int_t = 16; pub const LC_NUMERIC_MASK: ::int_t = 2; pub const LC_TIME_MASK: ::int_t = 4;
pub const LC_GLOBAL_LOCALE: locale_t = -1i64 as locale_t;
pub const LC_ALL_MASK: ::int_t = 8127;
random_line_split
x86_64.rs
#[repr(C)] #[derive(Copy)] pub struct
{ pub decimal_point: *mut ::char_t, pub thousands_sep: *mut ::char_t, pub grouping: *mut ::char_t, pub int_curr_symbol: *mut ::char_t, pub currency_symbol: *mut ::char_t, pub mon_decimal_point: *mut ::char_t, pub mon_thousands_sep: *mut ::char_t, pub mon_grouping: *mut ::char_t, pub positive_sign: *mut ::char_t, pub negative_sign: *mut ::char_t, pub int_frac_digits: ::char_t, pub frac_digits: ::char_t, pub p_cs_precedes: ::char_t, pub p_sep_by_space: ::char_t, pub n_cs_precedes: ::char_t, pub n_sep_by_space: ::char_t, pub p_sign_posn: ::char_t, pub n_sign_posn: ::char_t, pub int_p_cs_precedes: ::char_t, pub int_p_sep_by_space: ::char_t, pub int_n_cs_precedes: ::char_t, pub int_n_sep_by_space: ::char_t, pub int_p_sign_posn: ::char_t, pub int_n_sign_posn: ::char_t, } new!(lconv); pub type locale_t = *mut ::void_t; pub const LC_ALL: ::int_t = 6; pub const LC_COLLATE: ::int_t = 3; pub const LC_CTYPE: ::int_t = 0; pub const LC_MESSAGES: ::int_t = 5; pub const LC_MONETARY: ::int_t = 4; pub const LC_NUMERIC: ::int_t = 1; pub const LC_TIME: ::int_t = 2; pub const LC_COLLATE_MASK: ::int_t = 8; pub const LC_CTYPE_MASK: ::int_t = 1; pub const LC_MESSAGES_MASK: ::int_t = 32; pub const LC_MONETARY_MASK: ::int_t = 16; pub const LC_NUMERIC_MASK: ::int_t = 2; pub const LC_TIME_MASK: ::int_t = 4; pub const LC_ALL_MASK: ::int_t = 8127; pub const LC_GLOBAL_LOCALE: locale_t = -1i64 as locale_t;
lconv
identifier_name
pointer.rs
use super::{AllocId, InterpResult}; use rustc_macros::HashStable; use rustc_target::abi::{HasDataLayout, Size}; use std::convert::TryFrom; use std::fmt; //////////////////////////////////////////////////////////////////////////////// // Pointer arithmetic //////////////////////////////////////////////////////////////////////////////// pub trait PointerArithmetic: HasDataLayout { // These are not supposed to be overridden. #[inline(always)] fn pointer_size(&self) -> Size { self.data_layout().pointer_size } #[inline] fn machine_usize_max(&self) -> u64 { let max_usize_plus_1 = 1u128 << self.pointer_size().bits(); u64::try_from(max_usize_plus_1 - 1).unwrap() } #[inline] fn machine_isize_min(&self) -> i64 { let max_isize_plus_1 = 1i128 << (self.pointer_size().bits() - 1); i64::try_from(-max_isize_plus_1).unwrap() } #[inline] fn machine_isize_max(&self) -> i64 { let max_isize_plus_1 = 1u128 << (self.pointer_size().bits() - 1); i64::try_from(max_isize_plus_1 - 1).unwrap() } #[inline] fn machine_usize_to_isize(&self, val: u64) -> i64 { let val = val as i64; // Now clamp into the machine_isize range. if val > self.machine_isize_max() { // This can only happen the the ptr size is < 64, so we know max_usize_plus_1 fits into // i64. let max_usize_plus_1 = 1u128 << self.pointer_size().bits(); val - i64::try_from(max_usize_plus_1).unwrap() } else { val } } /// Helper function: truncate given value-"overflowed flag" pair to pointer size and /// update "overflowed flag" if there was an overflow. /// This should be called by all the other methods before returning! #[inline] fn truncate_to_ptr(&self, (val, over): (u64, bool)) -> (u64, bool) { let val = u128::from(val); let max_ptr_plus_1 = 1u128 << self.pointer_size().bits(); (u64::try_from(val % max_ptr_plus_1).unwrap(), over || val >= max_ptr_plus_1) } #[inline] fn overflowing_offset(&self, val: u64, i: u64) -> (u64, bool) { // We do not need to check if i fits in a machine usize. If it doesn't, // either the wrapping_add will wrap or res will not fit in a pointer. let res = val.overflowing_add(i); self.truncate_to_ptr(res) } #[inline] fn overflowing_signed_offset(&self, val: u64, i: i64) -> (u64, bool) { // We need to make sure that i fits in a machine isize. let n = i.unsigned_abs(); if i >= 0 { let (val, over) = self.overflowing_offset(val, n); (val, over || i > self.machine_isize_max()) } else { let res = val.overflowing_sub(n); let (val, over) = self.truncate_to_ptr(res); (val, over || i < self.machine_isize_min()) } } #[inline] fn offset<'tcx>(&self, val: u64, i: u64) -> InterpResult<'tcx, u64> { let (res, over) = self.overflowing_offset(val, i); if over { throw_ub!(PointerArithOverflow) } else { Ok(res) } } #[inline] fn
<'tcx>(&self, val: u64, i: i64) -> InterpResult<'tcx, u64> { let (res, over) = self.overflowing_signed_offset(val, i); if over { throw_ub!(PointerArithOverflow) } else { Ok(res) } } } impl<T: HasDataLayout> PointerArithmetic for T {} /// This trait abstracts over the kind of provenance that is associated with a `Pointer`. It is /// mostly opaque; the `Machine` trait extends it with some more operations that also have access to /// some global state. /// We don't actually care about this `Debug` bound (we use `Provenance::fmt` to format the entire /// pointer), but `derive` adds some unecessary bounds. pub trait Provenance: Copy + fmt::Debug { /// Says whether the `offset` field of `Pointer`s with this provenance is the actual physical address. /// If `true, ptr-to-int casts work by simply discarding the provenance. /// If `false`, ptr-to-int casts are not supported. The offset *must* be relative in that case. const OFFSET_IS_ADDR: bool; /// We also use this trait to control whether to abort execution when a pointer is being partially overwritten /// (this avoids a separate trait in `allocation.rs` just for this purpose). const ERR_ON_PARTIAL_PTR_OVERWRITE: bool; /// Determines how a pointer should be printed. fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result where Self: Sized; /// Provenance must always be able to identify the allocation this ptr points to. /// (Identifying the offset in that allocation, however, is harder -- use `Memory::ptr_get_alloc` for that.) fn get_alloc_id(self) -> AllocId; } impl Provenance for AllocId { // With the `AllocId` as provenance, the `offset` is interpreted *relative to the allocation*, // so ptr-to-int casts are not possible (since we do not know the global physical offset). const OFFSET_IS_ADDR: bool = false; // For now, do not allow this, so that we keep our options open. const ERR_ON_PARTIAL_PTR_OVERWRITE: bool = true; fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Forward `alternate` flag to `alloc_id` printing. if f.alternate() { write!(f, "{:#?}", ptr.provenance)?; } else { write!(f, "{:?}", ptr.provenance)?; } // Print offset only if it is non-zero. if ptr.offset.bytes() > 0 { write!(f, "+0x{:x}", ptr.offset.bytes())?; } Ok(()) } fn get_alloc_id(self) -> AllocId { self } } /// Represents a pointer in the Miri engine. /// /// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to. #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, TyEncodable, TyDecodable, Hash)] #[derive(HashStable)] pub struct Pointer<Tag = AllocId> { pub(super) offset: Size, // kept private to avoid accidental misinterpretation (meaning depends on `Tag` type) pub provenance: Tag, } static_assert_size!(Pointer, 16); // We want the `Debug` output to be readable as it is used by `derive(Debug)` for // all the Miri types. impl<Tag: Provenance> fmt::Debug for Pointer<Tag> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Provenance::fmt(self, f) } } impl<Tag: Provenance> fmt::Debug for Pointer<Option<Tag>> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.provenance { Some(tag) => Provenance::fmt(&Pointer::new(tag, self.offset), f), None => write!(f, "0x{:x}", self.offset.bytes()), } } } /// Produces a `Pointer` that points to the beginning of the `Allocation`. impl From<AllocId> for Pointer { #[inline(always)] fn from(alloc_id: AllocId) -> Self { Pointer::new(alloc_id, Size::ZERO) } } impl<Tag> From<Pointer<Tag>> for Pointer<Option<Tag>> { #[inline(always)] fn from(ptr: Pointer<Tag>) -> Self { let (tag, offset) = ptr.into_parts(); Pointer::new(Some(tag), offset) } } impl<Tag> Pointer<Option<Tag>> { pub fn into_pointer_or_addr(self) -> Result<Pointer<Tag>, Size> { match self.provenance { Some(tag) => Ok(Pointer::new(tag, self.offset)), None => Err(self.offset), } } } impl<Tag> Pointer<Option<Tag>> { #[inline(always)] pub fn null() -> Self { Pointer { provenance: None, offset: Size::ZERO } } } impl<'tcx, Tag> Pointer<Tag> { #[inline(always)] pub fn new(provenance: Tag, offset: Size) -> Self { Pointer { provenance, offset } } /// Obtain the constituents of this pointer. Not that the meaning of the offset depends on the type `Tag`! /// This function must only be used in the implementation of `Machine::ptr_get_alloc`, /// and when a `Pointer` is taken apart to be stored efficiently in an `Allocation`. #[inline(always)] pub fn into_parts(self) -> (Tag, Size) { (self.provenance, self.offset) } pub fn map_provenance(self, f: impl FnOnce(Tag) -> Tag) -> Self { Pointer { provenance: f(self.provenance),..self } } #[inline] pub fn offset(self, i: Size, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> { Ok(Pointer { offset: Size::from_bytes(cx.data_layout().offset(self.offset.bytes(), i.bytes())?), ..self }) } #[inline] pub fn overflowing_offset(self, i: Size, cx: &impl HasDataLayout) -> (Self, bool) { let (res, over) = cx.data_layout().overflowing_offset(self.offset.bytes(), i.bytes()); let ptr = Pointer { offset: Size::from_bytes(res),..self }; (ptr, over) } #[inline(always)] pub fn wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self { self.overflowing_offset(i, cx).0 } #[inline] pub fn signed_offset(self, i: i64, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> { Ok(Pointer { offset: Size::from_bytes(cx.data_layout().signed_offset(self.offset.bytes(), i)?), ..self }) } #[inline] pub fn overflowing_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> (Self, bool) { let (res, over) = cx.data_layout().overflowing_signed_offset(self.offset.bytes(), i); let ptr = Pointer { offset: Size::from_bytes(res),..self }; (ptr, over) } #[inline(always)] pub fn wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self { self.overflowing_signed_offset(i, cx).0 } }
signed_offset
identifier_name
pointer.rs
use super::{AllocId, InterpResult}; use rustc_macros::HashStable; use rustc_target::abi::{HasDataLayout, Size}; use std::convert::TryFrom; use std::fmt; //////////////////////////////////////////////////////////////////////////////// // Pointer arithmetic //////////////////////////////////////////////////////////////////////////////// pub trait PointerArithmetic: HasDataLayout { // These are not supposed to be overridden. #[inline(always)] fn pointer_size(&self) -> Size { self.data_layout().pointer_size } #[inline] fn machine_usize_max(&self) -> u64 { let max_usize_plus_1 = 1u128 << self.pointer_size().bits(); u64::try_from(max_usize_plus_1 - 1).unwrap() } #[inline] fn machine_isize_min(&self) -> i64 { let max_isize_plus_1 = 1i128 << (self.pointer_size().bits() - 1); i64::try_from(-max_isize_plus_1).unwrap() } #[inline] fn machine_isize_max(&self) -> i64 { let max_isize_plus_1 = 1u128 << (self.pointer_size().bits() - 1); i64::try_from(max_isize_plus_1 - 1).unwrap() } #[inline] fn machine_usize_to_isize(&self, val: u64) -> i64 { let val = val as i64; // Now clamp into the machine_isize range. if val > self.machine_isize_max() { // This can only happen the the ptr size is < 64, so we know max_usize_plus_1 fits into // i64. let max_usize_plus_1 = 1u128 << self.pointer_size().bits(); val - i64::try_from(max_usize_plus_1).unwrap() } else { val } } /// Helper function: truncate given value-"overflowed flag" pair to pointer size and /// update "overflowed flag" if there was an overflow. /// This should be called by all the other methods before returning! #[inline] fn truncate_to_ptr(&self, (val, over): (u64, bool)) -> (u64, bool) { let val = u128::from(val); let max_ptr_plus_1 = 1u128 << self.pointer_size().bits(); (u64::try_from(val % max_ptr_plus_1).unwrap(), over || val >= max_ptr_plus_1) } #[inline] fn overflowing_offset(&self, val: u64, i: u64) -> (u64, bool) { // We do not need to check if i fits in a machine usize. If it doesn't, // either the wrapping_add will wrap or res will not fit in a pointer. let res = val.overflowing_add(i); self.truncate_to_ptr(res) } #[inline] fn overflowing_signed_offset(&self, val: u64, i: i64) -> (u64, bool) { // We need to make sure that i fits in a machine isize. let n = i.unsigned_abs(); if i >= 0 { let (val, over) = self.overflowing_offset(val, n); (val, over || i > self.machine_isize_max()) } else { let res = val.overflowing_sub(n); let (val, over) = self.truncate_to_ptr(res); (val, over || i < self.machine_isize_min()) } } #[inline] fn offset<'tcx>(&self, val: u64, i: u64) -> InterpResult<'tcx, u64> { let (res, over) = self.overflowing_offset(val, i); if over { throw_ub!(PointerArithOverflow) } else { Ok(res) } } #[inline] fn signed_offset<'tcx>(&self, val: u64, i: i64) -> InterpResult<'tcx, u64> { let (res, over) = self.overflowing_signed_offset(val, i); if over { throw_ub!(PointerArithOverflow) } else { Ok(res) } } } impl<T: HasDataLayout> PointerArithmetic for T {} /// This trait abstracts over the kind of provenance that is associated with a `Pointer`. It is /// mostly opaque; the `Machine` trait extends it with some more operations that also have access to /// some global state. /// We don't actually care about this `Debug` bound (we use `Provenance::fmt` to format the entire /// pointer), but `derive` adds some unecessary bounds. pub trait Provenance: Copy + fmt::Debug { /// Says whether the `offset` field of `Pointer`s with this provenance is the actual physical address. /// If `true, ptr-to-int casts work by simply discarding the provenance. /// If `false`, ptr-to-int casts are not supported. The offset *must* be relative in that case. const OFFSET_IS_ADDR: bool; /// We also use this trait to control whether to abort execution when a pointer is being partially overwritten /// (this avoids a separate trait in `allocation.rs` just for this purpose). const ERR_ON_PARTIAL_PTR_OVERWRITE: bool; /// Determines how a pointer should be printed. fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result where Self: Sized; /// Provenance must always be able to identify the allocation this ptr points to. /// (Identifying the offset in that allocation, however, is harder -- use `Memory::ptr_get_alloc` for that.) fn get_alloc_id(self) -> AllocId; } impl Provenance for AllocId { // With the `AllocId` as provenance, the `offset` is interpreted *relative to the allocation*, // so ptr-to-int casts are not possible (since we do not know the global physical offset). const OFFSET_IS_ADDR: bool = false; // For now, do not allow this, so that we keep our options open. const ERR_ON_PARTIAL_PTR_OVERWRITE: bool = true; fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result
fn get_alloc_id(self) -> AllocId { self } } /// Represents a pointer in the Miri engine. /// /// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to. #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, TyEncodable, TyDecodable, Hash)] #[derive(HashStable)] pub struct Pointer<Tag = AllocId> { pub(super) offset: Size, // kept private to avoid accidental misinterpretation (meaning depends on `Tag` type) pub provenance: Tag, } static_assert_size!(Pointer, 16); // We want the `Debug` output to be readable as it is used by `derive(Debug)` for // all the Miri types. impl<Tag: Provenance> fmt::Debug for Pointer<Tag> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Provenance::fmt(self, f) } } impl<Tag: Provenance> fmt::Debug for Pointer<Option<Tag>> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.provenance { Some(tag) => Provenance::fmt(&Pointer::new(tag, self.offset), f), None => write!(f, "0x{:x}", self.offset.bytes()), } } } /// Produces a `Pointer` that points to the beginning of the `Allocation`. impl From<AllocId> for Pointer { #[inline(always)] fn from(alloc_id: AllocId) -> Self { Pointer::new(alloc_id, Size::ZERO) } } impl<Tag> From<Pointer<Tag>> for Pointer<Option<Tag>> { #[inline(always)] fn from(ptr: Pointer<Tag>) -> Self { let (tag, offset) = ptr.into_parts(); Pointer::new(Some(tag), offset) } } impl<Tag> Pointer<Option<Tag>> { pub fn into_pointer_or_addr(self) -> Result<Pointer<Tag>, Size> { match self.provenance { Some(tag) => Ok(Pointer::new(tag, self.offset)), None => Err(self.offset), } } } impl<Tag> Pointer<Option<Tag>> { #[inline(always)] pub fn null() -> Self { Pointer { provenance: None, offset: Size::ZERO } } } impl<'tcx, Tag> Pointer<Tag> { #[inline(always)] pub fn new(provenance: Tag, offset: Size) -> Self { Pointer { provenance, offset } } /// Obtain the constituents of this pointer. Not that the meaning of the offset depends on the type `Tag`! /// This function must only be used in the implementation of `Machine::ptr_get_alloc`, /// and when a `Pointer` is taken apart to be stored efficiently in an `Allocation`. #[inline(always)] pub fn into_parts(self) -> (Tag, Size) { (self.provenance, self.offset) } pub fn map_provenance(self, f: impl FnOnce(Tag) -> Tag) -> Self { Pointer { provenance: f(self.provenance),..self } } #[inline] pub fn offset(self, i: Size, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> { Ok(Pointer { offset: Size::from_bytes(cx.data_layout().offset(self.offset.bytes(), i.bytes())?), ..self }) } #[inline] pub fn overflowing_offset(self, i: Size, cx: &impl HasDataLayout) -> (Self, bool) { let (res, over) = cx.data_layout().overflowing_offset(self.offset.bytes(), i.bytes()); let ptr = Pointer { offset: Size::from_bytes(res),..self }; (ptr, over) } #[inline(always)] pub fn wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self { self.overflowing_offset(i, cx).0 } #[inline] pub fn signed_offset(self, i: i64, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> { Ok(Pointer { offset: Size::from_bytes(cx.data_layout().signed_offset(self.offset.bytes(), i)?), ..self }) } #[inline] pub fn overflowing_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> (Self, bool) { let (res, over) = cx.data_layout().overflowing_signed_offset(self.offset.bytes(), i); let ptr = Pointer { offset: Size::from_bytes(res),..self }; (ptr, over) } #[inline(always)] pub fn wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self { self.overflowing_signed_offset(i, cx).0 } }
{ // Forward `alternate` flag to `alloc_id` printing. if f.alternate() { write!(f, "{:#?}", ptr.provenance)?; } else { write!(f, "{:?}", ptr.provenance)?; } // Print offset only if it is non-zero. if ptr.offset.bytes() > 0 { write!(f, "+0x{:x}", ptr.offset.bytes())?; } Ok(()) }
identifier_body
pointer.rs
use super::{AllocId, InterpResult}; use rustc_macros::HashStable; use rustc_target::abi::{HasDataLayout, Size}; use std::convert::TryFrom; use std::fmt; //////////////////////////////////////////////////////////////////////////////// // Pointer arithmetic //////////////////////////////////////////////////////////////////////////////// pub trait PointerArithmetic: HasDataLayout { // These are not supposed to be overridden. #[inline(always)] fn pointer_size(&self) -> Size { self.data_layout().pointer_size } #[inline] fn machine_usize_max(&self) -> u64 { let max_usize_plus_1 = 1u128 << self.pointer_size().bits(); u64::try_from(max_usize_plus_1 - 1).unwrap() } #[inline] fn machine_isize_min(&self) -> i64 { let max_isize_plus_1 = 1i128 << (self.pointer_size().bits() - 1); i64::try_from(-max_isize_plus_1).unwrap() } #[inline] fn machine_isize_max(&self) -> i64 { let max_isize_plus_1 = 1u128 << (self.pointer_size().bits() - 1); i64::try_from(max_isize_plus_1 - 1).unwrap() } #[inline] fn machine_usize_to_isize(&self, val: u64) -> i64 { let val = val as i64; // Now clamp into the machine_isize range. if val > self.machine_isize_max() { // This can only happen the the ptr size is < 64, so we know max_usize_plus_1 fits into // i64. let max_usize_plus_1 = 1u128 << self.pointer_size().bits(); val - i64::try_from(max_usize_plus_1).unwrap() } else { val } } /// Helper function: truncate given value-"overflowed flag" pair to pointer size and /// update "overflowed flag" if there was an overflow. /// This should be called by all the other methods before returning! #[inline] fn truncate_to_ptr(&self, (val, over): (u64, bool)) -> (u64, bool) { let val = u128::from(val); let max_ptr_plus_1 = 1u128 << self.pointer_size().bits(); (u64::try_from(val % max_ptr_plus_1).unwrap(), over || val >= max_ptr_plus_1) } #[inline] fn overflowing_offset(&self, val: u64, i: u64) -> (u64, bool) { // We do not need to check if i fits in a machine usize. If it doesn't, // either the wrapping_add will wrap or res will not fit in a pointer. let res = val.overflowing_add(i); self.truncate_to_ptr(res) } #[inline] fn overflowing_signed_offset(&self, val: u64, i: i64) -> (u64, bool) { // We need to make sure that i fits in a machine isize. let n = i.unsigned_abs(); if i >= 0 { let (val, over) = self.overflowing_offset(val, n); (val, over || i > self.machine_isize_max()) } else { let res = val.overflowing_sub(n); let (val, over) = self.truncate_to_ptr(res); (val, over || i < self.machine_isize_min()) } } #[inline] fn offset<'tcx>(&self, val: u64, i: u64) -> InterpResult<'tcx, u64> { let (res, over) = self.overflowing_offset(val, i); if over { throw_ub!(PointerArithOverflow) } else { Ok(res) } } #[inline] fn signed_offset<'tcx>(&self, val: u64, i: i64) -> InterpResult<'tcx, u64> { let (res, over) = self.overflowing_signed_offset(val, i); if over { throw_ub!(PointerArithOverflow) } else { Ok(res) } } } impl<T: HasDataLayout> PointerArithmetic for T {} /// This trait abstracts over the kind of provenance that is associated with a `Pointer`. It is /// mostly opaque; the `Machine` trait extends it with some more operations that also have access to /// some global state. /// We don't actually care about this `Debug` bound (we use `Provenance::fmt` to format the entire /// pointer), but `derive` adds some unecessary bounds. pub trait Provenance: Copy + fmt::Debug { /// Says whether the `offset` field of `Pointer`s with this provenance is the actual physical address. /// If `true, ptr-to-int casts work by simply discarding the provenance. /// If `false`, ptr-to-int casts are not supported. The offset *must* be relative in that case. const OFFSET_IS_ADDR: bool; /// We also use this trait to control whether to abort execution when a pointer is being partially overwritten /// (this avoids a separate trait in `allocation.rs` just for this purpose). const ERR_ON_PARTIAL_PTR_OVERWRITE: bool; /// Determines how a pointer should be printed. fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result where Self: Sized; /// Provenance must always be able to identify the allocation this ptr points to. /// (Identifying the offset in that allocation, however, is harder -- use `Memory::ptr_get_alloc` for that.) fn get_alloc_id(self) -> AllocId; } impl Provenance for AllocId { // With the `AllocId` as provenance, the `offset` is interpreted *relative to the allocation*, // so ptr-to-int casts are not possible (since we do not know the global physical offset). const OFFSET_IS_ADDR: bool = false; // For now, do not allow this, so that we keep our options open. const ERR_ON_PARTIAL_PTR_OVERWRITE: bool = true; fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Forward `alternate` flag to `alloc_id` printing. if f.alternate() { write!(f, "{:#?}", ptr.provenance)?; } else { write!(f, "{:?}", ptr.provenance)?; } // Print offset only if it is non-zero. if ptr.offset.bytes() > 0 { write!(f, "+0x{:x}", ptr.offset.bytes())?; } Ok(()) } fn get_alloc_id(self) -> AllocId { self } } /// Represents a pointer in the Miri engine. /// /// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to. #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, TyEncodable, TyDecodable, Hash)] #[derive(HashStable)] pub struct Pointer<Tag = AllocId> { pub(super) offset: Size, // kept private to avoid accidental misinterpretation (meaning depends on `Tag` type) pub provenance: Tag, } static_assert_size!(Pointer, 16); // We want the `Debug` output to be readable as it is used by `derive(Debug)` for // all the Miri types. impl<Tag: Provenance> fmt::Debug for Pointer<Tag> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Provenance::fmt(self, f) } } impl<Tag: Provenance> fmt::Debug for Pointer<Option<Tag>> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
None => write!(f, "0x{:x}", self.offset.bytes()), } } } /// Produces a `Pointer` that points to the beginning of the `Allocation`. impl From<AllocId> for Pointer { #[inline(always)] fn from(alloc_id: AllocId) -> Self { Pointer::new(alloc_id, Size::ZERO) } } impl<Tag> From<Pointer<Tag>> for Pointer<Option<Tag>> { #[inline(always)] fn from(ptr: Pointer<Tag>) -> Self { let (tag, offset) = ptr.into_parts(); Pointer::new(Some(tag), offset) } } impl<Tag> Pointer<Option<Tag>> { pub fn into_pointer_or_addr(self) -> Result<Pointer<Tag>, Size> { match self.provenance { Some(tag) => Ok(Pointer::new(tag, self.offset)), None => Err(self.offset), } } } impl<Tag> Pointer<Option<Tag>> { #[inline(always)] pub fn null() -> Self { Pointer { provenance: None, offset: Size::ZERO } } } impl<'tcx, Tag> Pointer<Tag> { #[inline(always)] pub fn new(provenance: Tag, offset: Size) -> Self { Pointer { provenance, offset } } /// Obtain the constituents of this pointer. Not that the meaning of the offset depends on the type `Tag`! /// This function must only be used in the implementation of `Machine::ptr_get_alloc`, /// and when a `Pointer` is taken apart to be stored efficiently in an `Allocation`. #[inline(always)] pub fn into_parts(self) -> (Tag, Size) { (self.provenance, self.offset) } pub fn map_provenance(self, f: impl FnOnce(Tag) -> Tag) -> Self { Pointer { provenance: f(self.provenance),..self } } #[inline] pub fn offset(self, i: Size, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> { Ok(Pointer { offset: Size::from_bytes(cx.data_layout().offset(self.offset.bytes(), i.bytes())?), ..self }) } #[inline] pub fn overflowing_offset(self, i: Size, cx: &impl HasDataLayout) -> (Self, bool) { let (res, over) = cx.data_layout().overflowing_offset(self.offset.bytes(), i.bytes()); let ptr = Pointer { offset: Size::from_bytes(res),..self }; (ptr, over) } #[inline(always)] pub fn wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self { self.overflowing_offset(i, cx).0 } #[inline] pub fn signed_offset(self, i: i64, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> { Ok(Pointer { offset: Size::from_bytes(cx.data_layout().signed_offset(self.offset.bytes(), i)?), ..self }) } #[inline] pub fn overflowing_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> (Self, bool) { let (res, over) = cx.data_layout().overflowing_signed_offset(self.offset.bytes(), i); let ptr = Pointer { offset: Size::from_bytes(res),..self }; (ptr, over) } #[inline(always)] pub fn wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self { self.overflowing_signed_offset(i, cx).0 } }
match self.provenance { Some(tag) => Provenance::fmt(&Pointer::new(tag, self.offset), f),
random_line_split
pointer.rs
use super::{AllocId, InterpResult}; use rustc_macros::HashStable; use rustc_target::abi::{HasDataLayout, Size}; use std::convert::TryFrom; use std::fmt; //////////////////////////////////////////////////////////////////////////////// // Pointer arithmetic //////////////////////////////////////////////////////////////////////////////// pub trait PointerArithmetic: HasDataLayout { // These are not supposed to be overridden. #[inline(always)] fn pointer_size(&self) -> Size { self.data_layout().pointer_size } #[inline] fn machine_usize_max(&self) -> u64 { let max_usize_plus_1 = 1u128 << self.pointer_size().bits(); u64::try_from(max_usize_plus_1 - 1).unwrap() } #[inline] fn machine_isize_min(&self) -> i64 { let max_isize_plus_1 = 1i128 << (self.pointer_size().bits() - 1); i64::try_from(-max_isize_plus_1).unwrap() } #[inline] fn machine_isize_max(&self) -> i64 { let max_isize_plus_1 = 1u128 << (self.pointer_size().bits() - 1); i64::try_from(max_isize_plus_1 - 1).unwrap() } #[inline] fn machine_usize_to_isize(&self, val: u64) -> i64 { let val = val as i64; // Now clamp into the machine_isize range. if val > self.machine_isize_max() { // This can only happen the the ptr size is < 64, so we know max_usize_plus_1 fits into // i64. let max_usize_plus_1 = 1u128 << self.pointer_size().bits(); val - i64::try_from(max_usize_plus_1).unwrap() } else { val } } /// Helper function: truncate given value-"overflowed flag" pair to pointer size and /// update "overflowed flag" if there was an overflow. /// This should be called by all the other methods before returning! #[inline] fn truncate_to_ptr(&self, (val, over): (u64, bool)) -> (u64, bool) { let val = u128::from(val); let max_ptr_plus_1 = 1u128 << self.pointer_size().bits(); (u64::try_from(val % max_ptr_plus_1).unwrap(), over || val >= max_ptr_plus_1) } #[inline] fn overflowing_offset(&self, val: u64, i: u64) -> (u64, bool) { // We do not need to check if i fits in a machine usize. If it doesn't, // either the wrapping_add will wrap or res will not fit in a pointer. let res = val.overflowing_add(i); self.truncate_to_ptr(res) } #[inline] fn overflowing_signed_offset(&self, val: u64, i: i64) -> (u64, bool) { // We need to make sure that i fits in a machine isize. let n = i.unsigned_abs(); if i >= 0
else { let res = val.overflowing_sub(n); let (val, over) = self.truncate_to_ptr(res); (val, over || i < self.machine_isize_min()) } } #[inline] fn offset<'tcx>(&self, val: u64, i: u64) -> InterpResult<'tcx, u64> { let (res, over) = self.overflowing_offset(val, i); if over { throw_ub!(PointerArithOverflow) } else { Ok(res) } } #[inline] fn signed_offset<'tcx>(&self, val: u64, i: i64) -> InterpResult<'tcx, u64> { let (res, over) = self.overflowing_signed_offset(val, i); if over { throw_ub!(PointerArithOverflow) } else { Ok(res) } } } impl<T: HasDataLayout> PointerArithmetic for T {} /// This trait abstracts over the kind of provenance that is associated with a `Pointer`. It is /// mostly opaque; the `Machine` trait extends it with some more operations that also have access to /// some global state. /// We don't actually care about this `Debug` bound (we use `Provenance::fmt` to format the entire /// pointer), but `derive` adds some unecessary bounds. pub trait Provenance: Copy + fmt::Debug { /// Says whether the `offset` field of `Pointer`s with this provenance is the actual physical address. /// If `true, ptr-to-int casts work by simply discarding the provenance. /// If `false`, ptr-to-int casts are not supported. The offset *must* be relative in that case. const OFFSET_IS_ADDR: bool; /// We also use this trait to control whether to abort execution when a pointer is being partially overwritten /// (this avoids a separate trait in `allocation.rs` just for this purpose). const ERR_ON_PARTIAL_PTR_OVERWRITE: bool; /// Determines how a pointer should be printed. fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result where Self: Sized; /// Provenance must always be able to identify the allocation this ptr points to. /// (Identifying the offset in that allocation, however, is harder -- use `Memory::ptr_get_alloc` for that.) fn get_alloc_id(self) -> AllocId; } impl Provenance for AllocId { // With the `AllocId` as provenance, the `offset` is interpreted *relative to the allocation*, // so ptr-to-int casts are not possible (since we do not know the global physical offset). const OFFSET_IS_ADDR: bool = false; // For now, do not allow this, so that we keep our options open. const ERR_ON_PARTIAL_PTR_OVERWRITE: bool = true; fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Forward `alternate` flag to `alloc_id` printing. if f.alternate() { write!(f, "{:#?}", ptr.provenance)?; } else { write!(f, "{:?}", ptr.provenance)?; } // Print offset only if it is non-zero. if ptr.offset.bytes() > 0 { write!(f, "+0x{:x}", ptr.offset.bytes())?; } Ok(()) } fn get_alloc_id(self) -> AllocId { self } } /// Represents a pointer in the Miri engine. /// /// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to. #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, TyEncodable, TyDecodable, Hash)] #[derive(HashStable)] pub struct Pointer<Tag = AllocId> { pub(super) offset: Size, // kept private to avoid accidental misinterpretation (meaning depends on `Tag` type) pub provenance: Tag, } static_assert_size!(Pointer, 16); // We want the `Debug` output to be readable as it is used by `derive(Debug)` for // all the Miri types. impl<Tag: Provenance> fmt::Debug for Pointer<Tag> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Provenance::fmt(self, f) } } impl<Tag: Provenance> fmt::Debug for Pointer<Option<Tag>> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.provenance { Some(tag) => Provenance::fmt(&Pointer::new(tag, self.offset), f), None => write!(f, "0x{:x}", self.offset.bytes()), } } } /// Produces a `Pointer` that points to the beginning of the `Allocation`. impl From<AllocId> for Pointer { #[inline(always)] fn from(alloc_id: AllocId) -> Self { Pointer::new(alloc_id, Size::ZERO) } } impl<Tag> From<Pointer<Tag>> for Pointer<Option<Tag>> { #[inline(always)] fn from(ptr: Pointer<Tag>) -> Self { let (tag, offset) = ptr.into_parts(); Pointer::new(Some(tag), offset) } } impl<Tag> Pointer<Option<Tag>> { pub fn into_pointer_or_addr(self) -> Result<Pointer<Tag>, Size> { match self.provenance { Some(tag) => Ok(Pointer::new(tag, self.offset)), None => Err(self.offset), } } } impl<Tag> Pointer<Option<Tag>> { #[inline(always)] pub fn null() -> Self { Pointer { provenance: None, offset: Size::ZERO } } } impl<'tcx, Tag> Pointer<Tag> { #[inline(always)] pub fn new(provenance: Tag, offset: Size) -> Self { Pointer { provenance, offset } } /// Obtain the constituents of this pointer. Not that the meaning of the offset depends on the type `Tag`! /// This function must only be used in the implementation of `Machine::ptr_get_alloc`, /// and when a `Pointer` is taken apart to be stored efficiently in an `Allocation`. #[inline(always)] pub fn into_parts(self) -> (Tag, Size) { (self.provenance, self.offset) } pub fn map_provenance(self, f: impl FnOnce(Tag) -> Tag) -> Self { Pointer { provenance: f(self.provenance),..self } } #[inline] pub fn offset(self, i: Size, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> { Ok(Pointer { offset: Size::from_bytes(cx.data_layout().offset(self.offset.bytes(), i.bytes())?), ..self }) } #[inline] pub fn overflowing_offset(self, i: Size, cx: &impl HasDataLayout) -> (Self, bool) { let (res, over) = cx.data_layout().overflowing_offset(self.offset.bytes(), i.bytes()); let ptr = Pointer { offset: Size::from_bytes(res),..self }; (ptr, over) } #[inline(always)] pub fn wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self { self.overflowing_offset(i, cx).0 } #[inline] pub fn signed_offset(self, i: i64, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> { Ok(Pointer { offset: Size::from_bytes(cx.data_layout().signed_offset(self.offset.bytes(), i)?), ..self }) } #[inline] pub fn overflowing_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> (Self, bool) { let (res, over) = cx.data_layout().overflowing_signed_offset(self.offset.bytes(), i); let ptr = Pointer { offset: Size::from_bytes(res),..self }; (ptr, over) } #[inline(always)] pub fn wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self { self.overflowing_signed_offset(i, cx).0 } }
{ let (val, over) = self.overflowing_offset(val, n); (val, over || i > self.machine_isize_max()) }
conditional_block
mod.rs
mod test_signal; // NOTE: DragonFly lacks a kernel-level implementation of Posix AIO as of // this writing. There is an user-level implementation, but whether aio // works or not heavily depends on which pthread implementation is chosen // by the user at link time. For this reason we do not want to run aio test
target_os = "netbsd"))] mod test_aio; #[cfg(target_os = "linux")] mod test_signalfd; mod test_socket; mod test_sockopt; mod test_select; #[cfg(any(target_os = "android", target_os = "linux"))] mod test_sysinfo; mod test_termios; mod test_ioctl; mod test_wait; mod test_uio; #[cfg(target_os = "linux")] mod test_epoll; mod test_pthread; #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux", target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] mod test_ptrace;
// cases on DragonFly. #[cfg(any(target_os = "freebsd", target_os = "ios", target_os = "linux", target_os = "macos",
random_line_split
mod.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Networking I/O use old_io::{IoError, IoResult, InvalidInput}; use ops::FnMut; use option::Option::None; use result::Result::{Ok, Err}; use self::ip::{SocketAddr, ToSocketAddr}; pub use self::addrinfo::get_host_addresses; pub mod addrinfo; pub mod tcp; pub mod udp; pub mod ip; pub mod pipe; fn
<A, T, F>(addr: A, mut action: F) -> IoResult<T> where A: ToSocketAddr, F: FnMut(SocketAddr) -> IoResult<T>, { const DEFAULT_ERROR: IoError = IoError { kind: InvalidInput, desc: "no addresses found for hostname", detail: None }; let addresses = try!(addr.to_socket_addr_all()); let mut err = DEFAULT_ERROR; for addr in addresses { match action(addr) { Ok(r) => return Ok(r), Err(e) => err = e } } Err(err) }
with_addresses
identifier_name
mod.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Networking I/O use old_io::{IoError, IoResult, InvalidInput}; use ops::FnMut; use option::Option::None; use result::Result::{Ok, Err}; use self::ip::{SocketAddr, ToSocketAddr}; pub use self::addrinfo::get_host_addresses; pub mod addrinfo; pub mod tcp; pub mod udp; pub mod ip; pub mod pipe; fn with_addresses<A, T, F>(addr: A, mut action: F) -> IoResult<T> where A: ToSocketAddr, F: FnMut(SocketAddr) -> IoResult<T>,
{ const DEFAULT_ERROR: IoError = IoError { kind: InvalidInput, desc: "no addresses found for hostname", detail: None }; let addresses = try!(addr.to_socket_addr_all()); let mut err = DEFAULT_ERROR; for addr in addresses { match action(addr) { Ok(r) => return Ok(r), Err(e) => err = e } } Err(err) }
identifier_body
mod.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Networking I/O use old_io::{IoError, IoResult, InvalidInput}; use ops::FnMut; use option::Option::None; use result::Result::{Ok, Err}; use self::ip::{SocketAddr, ToSocketAddr}; pub use self::addrinfo::get_host_addresses; pub mod addrinfo; pub mod tcp; pub mod udp; pub mod ip; pub mod pipe; fn with_addresses<A, T, F>(addr: A, mut action: F) -> IoResult<T> where A: ToSocketAddr, F: FnMut(SocketAddr) -> IoResult<T>, { const DEFAULT_ERROR: IoError = IoError {
detail: None }; let addresses = try!(addr.to_socket_addr_all()); let mut err = DEFAULT_ERROR; for addr in addresses { match action(addr) { Ok(r) => return Ok(r), Err(e) => err = e } } Err(err) }
kind: InvalidInput, desc: "no addresses found for hostname",
random_line_split
mod.rs
sockaddr_in, sockaddr_in6, sockaddr_un, sa_family_t, }; pub use self::multicast::{ ip_mreq, ipv6_mreq, }; pub use self::consts::*; pub use libc::sockaddr_storage; #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[repr(i32)] pub enum SockType { Stream = consts::SOCK_STREAM, Datagram = consts::SOCK_DGRAM, SeqPacket = consts::SOCK_SEQPACKET, Raw = consts::SOCK_RAW, Rdm = consts::SOCK_RDM, } // Extra flags - Supported by Linux 2.6.27, normalized on other platforms bitflags!( pub struct SockFlag: c_int { const SOCK_NONBLOCK = 0o0004000; const SOCK_CLOEXEC = 0o2000000; } ); /// Copy the in-memory representation of src into the byte slice dst, /// updating the slice to point to the remainder of dst only. Unsafe /// because it exposes all bytes in src, which may be UB if some of them /// are uninitialized (including padding). unsafe fn copy_bytes<'a, 'b, T:?Sized>(src: &T, dst: &'a mut &'b mut [u8]) { let srclen = mem::size_of_val(src); let mut tmpdst = &mut [][..]; mem::swap(&mut tmpdst, dst); let (target, mut remainder) = tmpdst.split_at_mut(srclen); // Safe because the mutable borrow of dst guarantees that src does not alias it. ptr::copy_nonoverlapping(src as *const T as *const u8, target.as_mut_ptr(), srclen); mem::swap(dst, &mut remainder); } use self::ffi::{cmsghdr, msghdr, type_of_cmsg_len, type_of_cmsg_data}; /// A structure used to make room in a cmsghdr passed to recvmsg. The /// size and alignment match that of a cmsghdr followed by a T, but the /// fields are not accessible, as the actual types will change on a call /// to recvmsg. /// /// To make room for multiple messages, nest the type parameter with /// tuples, e.g. /// `let cmsg: CmsgSpace<([RawFd; 3], CmsgSpace<[RawFd; 2]>)> = CmsgSpace::new();` pub struct CmsgSpace<T> { _hdr: cmsghdr, _data: T, } impl<T> CmsgSpace<T> { /// Create a CmsgSpace<T>. The structure is used only for space, so /// the fields are uninitialized. pub fn new() -> Self { // Safe because the fields themselves aren't accessible. unsafe { mem::uninitialized() } } } pub struct RecvMsg<'a> { // The number of bytes received. pub bytes: usize, cmsg_buffer: &'a [u8], pub address: Option<SockAddr>, pub flags: MsgFlags, } impl<'a> RecvMsg<'a> { /// Iterate over the valid control messages pointed to by this /// msghdr. pub fn cmsgs(&self) -> CmsgIterator { CmsgIterator(self.cmsg_buffer) } } pub struct
<'a>(&'a [u8]); impl<'a> Iterator for CmsgIterator<'a> { type Item = ControlMessage<'a>; // The implementation loosely follows CMSG_FIRSTHDR / CMSG_NXTHDR, // although we handle the invariants in slightly different places to // get a better iterator interface. fn next(&mut self) -> Option<ControlMessage<'a>> { let buf = self.0; let sizeof_cmsghdr = mem::size_of::<cmsghdr>(); if buf.len() < sizeof_cmsghdr { return None; } let cmsg: &cmsghdr = unsafe { mem::transmute(buf.as_ptr()) }; // This check is only in the glibc implementation of CMSG_NXTHDR // (although it claims the kernel header checks this), but such // a structure is clearly invalid, either way. let cmsg_len = cmsg.cmsg_len as usize; if cmsg_len < sizeof_cmsghdr { return None; } let len = cmsg_len - sizeof_cmsghdr; // Advance our internal pointer. if cmsg_align(cmsg_len) > buf.len() { return None; } self.0 = &buf[cmsg_align(cmsg_len)..]; match (cmsg.cmsg_level, cmsg.cmsg_type) { (SOL_SOCKET, SCM_RIGHTS) => unsafe { Some(ControlMessage::ScmRights( slice::from_raw_parts( &cmsg.cmsg_data as *const _ as *const _, 1))) }, (_, _) => unsafe { Some(ControlMessage::Unknown(UnknownCmsg( &cmsg, slice::from_raw_parts( &cmsg.cmsg_data as *const _ as *const _, len)))) } } } } /// A type-safe wrapper around a single control message. More types may /// be added to this enum; do not exhaustively pattern-match it. /// [Further reading](http://man7.org/linux/man-pages/man3/cmsg.3.html) pub enum ControlMessage<'a> { /// A message of type SCM_RIGHTS, containing an array of file /// descriptors passed between processes. See the description in the /// "Ancillary messages" section of the /// [unix(7) man page](http://man7.org/linux/man-pages/man7/unix.7.html). ScmRights(&'a [RawFd]), #[doc(hidden)] Unknown(UnknownCmsg<'a>), } // An opaque structure used to prevent cmsghdr from being a public type #[doc(hidden)] pub struct UnknownCmsg<'a>(&'a cmsghdr, &'a [u8]); fn cmsg_align(len: usize) -> usize { let align_bytes = mem::size_of::<type_of_cmsg_data>() - 1; (len + align_bytes) &!align_bytes } impl<'a> ControlMessage<'a> { /// The value of CMSG_SPACE on this message. fn space(&self) -> usize { cmsg_align(self.len()) } /// The value of CMSG_LEN on this message. fn len(&self) -> usize { cmsg_align(mem::size_of::<cmsghdr>()) + match *self { ControlMessage::ScmRights(fds) => { mem::size_of_val(fds) }, ControlMessage::Unknown(UnknownCmsg(_, bytes)) => { mem::size_of_val(bytes) } } } // Unsafe: start and end of buffer must be size_t-aligned (that is, // cmsg_align'd). Updates the provided slice; panics if the buffer // is too small. unsafe fn encode_into<'b>(&self, buf: &mut &'b mut [u8]) { match *self { ControlMessage::ScmRights(fds) => { let cmsg = cmsghdr { cmsg_len: self.len() as type_of_cmsg_len, cmsg_level: SOL_SOCKET, cmsg_type: SCM_RIGHTS, cmsg_data: [], }; copy_bytes(&cmsg, buf); let padlen = cmsg_align(mem::size_of_val(&cmsg)) - mem::size_of_val(&cmsg); let mut tmpbuf = &mut [][..]; mem::swap(&mut tmpbuf, buf); let (_padding, mut remainder) = tmpbuf.split_at_mut(padlen); mem::swap(buf, &mut remainder); copy_bytes(fds, buf); }, ControlMessage::Unknown(UnknownCmsg(orig_cmsg, bytes)) => { copy_bytes(orig_cmsg, buf); copy_bytes(bytes, buf); } } } } /// Send data in scatter-gather vectors to a socket, possibly accompanied /// by ancillary data. Optionally direct the message at the given address, /// as with sendto. /// /// Allocates if cmsgs is nonempty. pub fn sendmsg<'a>(fd: RawFd, iov: &[IoVec<&'a [u8]>], cmsgs: &[ControlMessage<'a>], flags: MsgFlags, addr: Option<&'a SockAddr>) -> Result<usize> { let mut len = 0; let mut capacity = 0; for cmsg in cmsgs { len += cmsg.len(); capacity += cmsg.space(); } // Note that the resulting vector claims to have length == capacity, // so it's presently uninitialized. let mut cmsg_buffer = unsafe { let mut vec = Vec::<u8>::with_capacity(len); vec.set_len(len); vec }; { let mut ptr = &mut cmsg_buffer[..]; for cmsg in cmsgs { unsafe { cmsg.encode_into(&mut ptr) }; } } let (name, namelen) = match addr { Some(addr) => { let (x, y) = unsafe { addr.as_ffi_pair() }; (x as *const _, y) } None => (0 as *const _, 0), }; let cmsg_ptr = if capacity > 0 { cmsg_buffer.as_ptr() as *const c_void } else { ptr::null() }; let mhdr = msghdr { msg_name: name as *const c_void, msg_namelen: namelen, msg_iov: iov.as_ptr(), msg_iovlen: iov.len() as size_t, msg_control: cmsg_ptr, msg_controllen: capacity as size_t, msg_flags: 0, }; let ret = unsafe { ffi::sendmsg(fd, &mhdr, flags.bits()) }; Errno::result(ret).map(|r| r as usize) } /// Receive message in scatter-gather vectors from a socket, and /// optionally receive ancillary data into the provided buffer. /// If no ancillary data is desired, use () as the type parameter. pub fn recvmsg<'a, T>(fd: RawFd, iov: &[IoVec<&mut [u8]>], cmsg_buffer: Option<&'a mut CmsgSpace<T>>, flags: MsgFlags) -> Result<RecvMsg<'a>> { let mut address: sockaddr_storage = unsafe { mem::uninitialized() }; let (msg_control, msg_controllen) = match cmsg_buffer { Some(cmsg_buffer) => (cmsg_buffer as *mut _, mem::size_of_val(cmsg_buffer)), None => (0 as *mut _, 0), }; let mut mhdr = msghdr { msg_name: &mut address as *const _ as *const c_void, msg_namelen: mem::size_of::<sockaddr_storage>() as socklen_t, msg_iov: iov.as_ptr() as *const IoVec<&[u8]>, // safe cast to add const-ness msg_iovlen: iov.len() as size_t, msg_control: msg_control as *const c_void, msg_controllen: msg_controllen as size_t, msg_flags: 0, }; let ret = unsafe { ffi::recvmsg(fd, &mut mhdr, flags.bits()) }; Ok(unsafe { RecvMsg { bytes: try!(Errno::result(ret)) as usize, cmsg_buffer: slice::from_raw_parts(mhdr.msg_control as *const u8, mhdr.msg_controllen as usize), address: sockaddr_storage_to_addr(&address, mhdr.msg_namelen as usize).ok(), flags: MsgFlags::from_bits_truncate(mhdr.msg_flags), } }) } /// Create an endpoint for communication /// /// [Further reading](http://man7.org/linux/man-pages/man2/socket.2.html) pub fn socket(domain: AddressFamily, ty: SockType, flags: SockFlag, protocol: c_int) -> Result<RawFd> { let mut ty = ty as c_int; let feat_atomic = features::socket_atomic_cloexec(); if feat_atomic { ty = ty | flags.bits(); } // TODO: Check the kernel version let res = try!(Errno::result(unsafe { ffi::socket(domain as c_int, ty, protocol) })); if!feat_atomic { if flags.contains(SOCK_CLOEXEC) { try!(fcntl(res, F_SETFD(FD_CLOEXEC))); } if flags.contains(SOCK_NONBLOCK) { try!(fcntl(res, F_SETFL(O_NONBLOCK))); } } Ok(res) } /// Create a pair of connected sockets /// /// [Further reading](http://man7.org/linux/man-pages/man2/socketpair.2.html) pub fn socketpair(domain: AddressFamily, ty: SockType, protocol: c_int, flags: SockFlag) -> Result<(RawFd, RawFd)> { let mut ty = ty as c_int; let feat_atomic = features::socket_atomic_cloexec(); if feat_atomic { ty = ty | flags.bits(); } let mut fds = [-1, -1]; let res = unsafe { ffi::socketpair(domain as c_int, ty, protocol, fds.as_mut_ptr()) }; try!(Errno::result(res)); if!feat_atomic { if flags.contains(SOCK_CLOEXEC) { try!(fcntl(fds[0], F_SETFD(FD_CLOEXEC))); try!(fcntl(fds[1], F_SETFD(FD_CLOEXEC))); } if flags.contains(SOCK_NONBLOCK) { try!(fcntl(fds[0], F_SETFL(O_NONBLOCK))); try!(fcntl(fds[1], F_SETFL(O_NONBLOCK))); } } Ok((fds[0], fds[1])) } /// Listen for connections on a socket /// /// [Further reading](http://man7.org/linux/man-pages/man2/listen.2.html) pub fn listen(sockfd: RawFd, backlog: usize) -> Result<()> { let res = unsafe { ffi::listen(sockfd, backlog as c_int) }; Errno::result(res).map(drop) } /// Bind a name to a socket /// /// [Further reading](http://man7.org/linux/man-pages/man2/bind.2.html) #[cfg(not(all(target_os="android", target_pointer_width="64")))] pub fn bind(fd: RawFd, addr: &SockAddr) -> Result<()> { let res = unsafe { let (ptr, len) = addr.as_ffi_pair(); ffi::bind(fd, ptr, len) }; Errno::result(res).map(drop) } /// Bind a name to a socket /// /// [Further reading](http://man7.org/linux/man-pages/man2/bind.2.html) // Android has some weirdness. Its 64-bit bind takes a c_int instead of a // socklen_t #[cfg(all(target_os="android", target_pointer_width="64"))] pub fn bind(fd: RawFd, addr: &SockAddr) -> Result<()> { let res = unsafe { let (ptr, len) = addr.as_ffi_pair(); ffi::bind(fd, ptr, len as c_int) }; Errno::result(res).map(drop) } /// Accept a connection on a socket /// /// [Further reading](http://man7.org/linux/man-pages/man2/accept.2.html) pub fn accept(sockfd: RawFd) -> Result<RawFd> { let res = unsafe { ffi::accept(sockfd, ptr::null_mut(), ptr::null_mut()) }; Errno::result(res) } /// Accept a connection on a socket /// /// [Further reading](http://man7.org/linux/man-pages/man2/accept.2.html) pub fn accept4(sockfd: RawFd, flags: SockFlag) -> Result<RawFd> { accept4_polyfill(sockfd, flags) } #[inline] fn accept4_polyfill(sockfd: RawFd, flags: SockFlag) -> Result<RawFd> { let res = try!(Errno::result(unsafe { ffi::accept(sockfd, ptr::null_mut(), ptr::null_mut()) })); if flags.contains(SOCK_CLOEXEC) { try!(fcntl(res, F_SETFD(FD_CLOEXEC))); } if flags.contains(SOCK_NONBLOCK) { try!(fcntl(res, F_SETFL(O_NONBLOCK))); } Ok(res) } /// Initiate a connection on a socket /// /// [Further reading](http://man7.org/linux/man-pages/man2/connect.2.html) pub fn connect(fd: RawFd, addr: &SockAddr) -> Result<()> { let res = unsafe { let (ptr, len) = addr.as_ffi_pair(); ffi::connect(fd, ptr, len) }; Errno::result(res).map(drop) } /// Receive data from a connection-oriented socket. Returns the number of /// bytes read /// /// [Further reading](http://man7.org/linux/man-pages/man2/recv.2.html) pub fn recv(sockfd: RawFd, buf: &mut [u8], flags: MsgFlags) -> Result<usize> { unsafe { let ret = ffi::recv( sockfd, buf.as_ptr() as *mut c_void, buf.len() as size_t, flags.bits()); Errno::result(ret).map(|r| r as usize) } } /// Receive data from a connectionless or connection-oriented socket. Returns /// the number of bytes read and the socket address of the sender. /// /// [Further reading](http://man7.org/linux/man-pages/man2/recvmsg.2.html) pub fn recvfrom(sockfd: RawFd, buf: &mut [u8]) -> Result<(usize, SockAddr)> { unsafe { let addr: sockaddr_storage = mem::zeroed(); let mut len = mem::size_of::<sockaddr_storage>() as socklen_t; let ret = try!(Errno::result(ffi::recvfrom( sockfd, buf.as_ptr() as *mut c_void, buf.len() as size_t, 0, mem::transmute(&addr), &mut len as *mut socklen_t))); sockaddr_storage_to_addr(&addr, len as usize) .map(|addr| (ret as usize, addr)) } } pub fn sendto(fd: RawFd, buf: &[u8], addr: &SockAddr, flags: MsgFlags) -> Result<usize> { let ret = unsafe { let (ptr, len) = addr.as_ffi_pair(); ffi::sendto(fd, buf.as_ptr() as *const c_void, buf.len() as size_t, flags.bits(), ptr, len) }; Errno::result(ret).map(|r| r as usize) } /// Send data to a connection-oriented socket. Returns the number of bytes read /// /// [Further reading](http://man7.org/linux/man-pages/man2/send.2.html) pub fn send(fd: RawFd, buf: &[u8], flags: MsgFlags) -> Result<usize> { let ret = unsafe { ffi::send(fd, buf.as_ptr() as *const c_void, buf.len() as size_t, flags.bits()) }; Errno::result(ret).map(|r| r as usize) } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct linger { pub l_onoff: c_int, pub l_linger: c_int } #[repr(C)] #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct ucred { pid: pid_t, uid: uid_t, gid: gid_t, } /* * * ===== Socket Options ===== * */ /// The protocol level at which to get / set socket options. Used as an /// argument to `getsockopt` and `setsockopt`. /// /// [Further reading](http://man7.org/linux/man-pages/man2/setsockopt.2.html) #[repr(i32)] pub enum SockLevel { Socket = SOL_SOCKET, Tcp = IPPROTO_TCP, Ip = IPPROTO_IP, Ipv6 = IPPROTO_IPV6, Udp = IPPROTO_UDP, #[cfg(any(target_os = "linux", target_os = "android"))] Netlink = SOL_NETLINK, } /// Represents a socket option that can be accessed or set. Used as an argument /// to `getsockopt` pub trait GetSockOpt : Copy { type Val; #[doc(hidden)] fn get(&self, fd: RawFd) -> Result<Self::Val>; } /// Represents a socket option that can be accessed or set. Used as an argument /// to `setsockopt` pub trait SetSockOpt : Copy { type Val; #[doc(hidden)] fn set(&self, fd: RawFd, val: &Self::Val) -> Result<()>; } /// Get the current value for the requested socket option /// /// [Further reading](http://man7.org/linux/man-pages/man2/getsockopt.2.html) pub fn getsockopt<O: GetSockOpt>(fd: RawFd, opt: O) -> Result<O::Val> { opt.get(fd) } /// Sets the value for the requested socket option /// /// [Further reading](http://man7.org/linux/man-pages/man2/setsockopt.2.html) pub fn setsockopt<O: SetSockOpt>(fd: RawFd, opt: O, val: &O::Val) -> Result<()> { opt.set(fd, val) } /// Get the address of the peer connected to the socket `fd`. /// /// [Further reading](http://man7.org/linux/man-pages/man2/getpeername.2.html) pub fn getpeername(fd: RawFd) -> Result<SockAddr> { unsafe { let addr: sockaddr_storage = mem::uninitialized(); let mut len = mem::size_of::<sockaddr_storage>() as socklen_t; let ret = ffi::getpeername(fd, mem::transmute(&addr), &mut len); try!(Errno::result(ret)); sockaddr_storage_to_addr(&addr, len as usize) } } /// Get the current address to which the socket `fd` is bound. /// /// [Further reading](http://man7.org/linux/man-pages/man2/getsockname.2.html) pub fn getsockname(fd: RawFd) -> Result<SockAddr> { unsafe { let addr: sockaddr_storage = mem::uninitialized(); let mut len = mem::size_of::<sockaddr_storage>() as socklen_t; let ret = ffi::getsockname(fd, mem::transmute(&addr), &mut len); try!(Errno::result(ret)); sockaddr_storage_to_addr(&addr, len as usize) } } /// Return the appropriate SockAddr type from a `sockaddr_storage` of a certain /// size. In C this would usually be done by casting. The `len` argument /// should be the number of bytes in the sockaddr_storage that are actually /// allocated and valid. It must be at least as large as all the useful parts /// of the structure. Note that in the case of a `sockaddr_un`, `len` need not /// include the terminating null. pub unsafe fn sockaddr_storage_to_addr( addr: &sockaddr_storage, len: usize) -> Result<SockAddr> { if len < mem::size_of_val(&addr.ss_family) { return Err(Error::Sys(Errno::ENOTCONN)); } match addr.ss_family as c_int { consts::AF_INET => { assert!(len as usize == mem::size_of::<sockaddr_in>());
CmsgIterator
identifier_name