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
free.rs
#![deny(warnings)] extern crate coreutils; extern crate extra; #[cfg(target_os = "redox")] extern crate syscall; #[cfg(target_os = "redox")] fn free(parser: &coreutils::ArgParser) -> ::std::io::Result<()> { use coreutils::to_human_readable_string; use std::io::Error; use syscall::data::StatVfs; let mut stat = StatVfs::default(); { let fd = syscall::open("memory:", syscall::O_STAT).map_err(|err| Error::from_raw_os_error(err.errno))?; syscall::fstatvfs(fd, &mut stat).map_err(|err| Error::from_raw_os_error(err.errno))?; let _ = syscall::close(fd); } let size = stat.f_blocks * stat.f_bsize as u64; let used = (stat.f_blocks - stat.f_bfree) * stat.f_bsize as u64; let free = stat.f_bavail * stat.f_bsize as u64; if parser.found("human-readable") { println!("{:<8}{:>10}{:>10}{:>10}", "Mem:", to_human_readable_string(size), to_human_readable_string(used), to_human_readable_string(free)); } else { println!("{:<8}{:>10}{:>10}{:>10}", "Mem:", (size + 1023)/1024, (used + 1023)/1024, (free + 1023)/1024); } Ok(()) } #[cfg(target_os = "redox")] fn main() { use std::env; use std::io::{stdout, stderr, Write}; use std::process::exit; use coreutils::ArgParser; use extra::option::OptionalExt; const MAN_PAGE: &'static str = /* @MANSTART{free} */ r#" NAME free - view memory usage SYNOPSIS free [ -h | --help ] DESCRIPTION free displays the current memory usage of the system OPTIONS -h --human-readable human readable output --help display this help and exit "#; /* @MANEND */ let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(1) .add_flag(&["h", "human-readable"]) .add_flag(&["help"]); parser.parse(env::args()); if parser.found("help")
println!("{:<8}{:>10}{:>10}{:>10}", "", "total", "used", "free"); free(&parser).try(&mut stderr); } #[cfg(not(target_os = "redox"))] fn main() { use std::io::{stderr, Write}; use std::process::exit; let mut stderr = stderr(); stderr.write(b"error: unimplemented outside redox").unwrap(); exit(1); }
{ stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().try(&mut stderr); exit(0); }
conditional_block
float2.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. pub fn main() { let a = 1.5e6; let b = 1.5E6; let c = 1e6; let d = 1E6; let e = 3.0f32; let f = 5.9f64; let g = 1e6f32; let h = 1.0e7f64; let i = 1.0E7f64; let j = 3.1e+9; let k = 3.2e-10; assert!((a == b)); assert!((c < b)); assert!((c == d)); assert!((e < g)); assert!((f < h)); assert!((g == 1000000.0f32)); assert!((h == i)); assert!((j > k)); assert!((k < a));
}
random_line_split
float2.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. pub fn
() { let a = 1.5e6; let b = 1.5E6; let c = 1e6; let d = 1E6; let e = 3.0f32; let f = 5.9f64; let g = 1e6f32; let h = 1.0e7f64; let i = 1.0E7f64; let j = 3.1e+9; let k = 3.2e-10; assert!((a == b)); assert!((c < b)); assert!((c == d)); assert!((e < g)); assert!((f < h)); assert!((g == 1000000.0f32)); assert!((h == i)); assert!((j > k)); assert!((k < a)); }
main
identifier_name
float2.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. pub fn main()
assert!((k < a)); }
{ let a = 1.5e6; let b = 1.5E6; let c = 1e6; let d = 1E6; let e = 3.0f32; let f = 5.9f64; let g = 1e6f32; let h = 1.0e7f64; let i = 1.0E7f64; let j = 3.1e+9; let k = 3.2e-10; assert!((a == b)); assert!((c < b)); assert!((c == d)); assert!((e < g)); assert!((f < h)); assert!((g == 1000000.0f32)); assert!((h == i)); assert!((j > k));
identifier_body
cleanup-shortcircuit.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that cleanups for the RHS of shortcircuiting operators work. // pretty-expanded FIXME #23616 use std::env; pub fn main() { let args: Vec<String> = env::args().collect(); // Here, the rvalue `"signal".to_string()` requires cleanup. Older versions // of the code had a problem that the cleanup scope for this // expression was the end of the `if`, and as the `"signal".to_string()` // expression was never evaluated, we wound up trying to clean // uninitialized memory. if args.len() >= 2 && args[1] == "signal"
}
{ // Raise a segfault. unsafe { *(0 as *mut isize) = 0; } }
conditional_block
cleanup-shortcircuit.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that cleanups for the RHS of shortcircuiting operators work. // pretty-expanded FIXME #23616 use std::env; pub fn main()
{ let args: Vec<String> = env::args().collect(); // Here, the rvalue `"signal".to_string()` requires cleanup. Older versions // of the code had a problem that the cleanup scope for this // expression was the end of the `if`, and as the `"signal".to_string()` // expression was never evaluated, we wound up trying to clean // uninitialized memory. if args.len() >= 2 && args[1] == "signal" { // Raise a segfault. unsafe { *(0 as *mut isize) = 0; } } }
identifier_body
cleanup-shortcircuit.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that cleanups for the RHS of shortcircuiting operators work. // pretty-expanded FIXME #23616 use std::env; pub fn
() { let args: Vec<String> = env::args().collect(); // Here, the rvalue `"signal".to_string()` requires cleanup. Older versions // of the code had a problem that the cleanup scope for this // expression was the end of the `if`, and as the `"signal".to_string()` // expression was never evaluated, we wound up trying to clean // uninitialized memory. if args.len() >= 2 && args[1] == "signal" { // Raise a segfault. unsafe { *(0 as *mut isize) = 0; } } }
main
identifier_name
cleanup-shortcircuit.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that cleanups for the RHS of shortcircuiting operators work. // pretty-expanded FIXME #23616 use std::env; pub fn main() { let args: Vec<String> = env::args().collect(); // Here, the rvalue `"signal".to_string()` requires cleanup. Older versions // of the code had a problem that the cleanup scope for this // expression was the end of the `if`, and as the `"signal".to_string()` // expression was never evaluated, we wound up trying to clean // uninitialized memory. if args.len() >= 2 && args[1] == "signal" { // Raise a segfault. unsafe { *(0 as *mut isize) = 0; }
}
}
random_line_split
heuristics.rs
use super::{Dimension, PackInput}; use std::fmt::{Debug, Result, Formatter}; use std::cmp::{Ordering, PartialOrd, max}; pub const ALL: [&(SortHeuristic + Sync); 7] = [ &AreaSort, &PerimeterSort, &SideSort, &WidthSort, &HeightSort, &SquarenessByAreaSort, &SquarenessByPerimeterSort, ]; pub struct AreaSort; pub struct PerimeterSort; pub struct SideSort; pub struct WidthSort; pub struct HeightSort; pub struct SquarenessByAreaSort; pub struct SquarenessByPerimeterSort; pub trait SortHeuristic: Sync { fn name(&self) -> &'static str; fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering; } impl SortHeuristic for AreaSort { fn name(&self) -> &'static str { "area" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| d.w * d.h) } } impl SortHeuristic for PerimeterSort { fn name(&self) -> &'static str { "perimeter" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| d.w + d.h) } } impl SortHeuristic for SideSort { fn name(&self) -> &'static str { "side" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| max(d.w, d.h)) } } impl SortHeuristic for WidthSort { fn name(&self) -> &'static str { "width" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| d.w) } } impl SortHeuristic for HeightSort { fn name(&self) -> &'static str { "height" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| d.h) } } impl SortHeuristic for SquarenessByAreaSort { fn name(&self) -> &'static str { "squareness_area" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| sqa(d)) } } impl SortHeuristic for SquarenessByPerimeterSort { fn name(&self) -> &'static str { "squareness_perimeter" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| sqp(d)) } } fn squareness(d: &Dimension) -> f32 { if d.w < d.h
else { d.h as f32 / d.w as f32 } } fn sqa(d: &Dimension) -> f32 { squareness(d) * (d.w * d.h) as f32 } fn sqp(d: &Dimension) -> f32 { squareness(d) * (d.w + d.h) as f32 } fn cmp_by_key<F, T: PartialOrd>(l: &PackInput, r: &PackInput, key: F) -> Ordering where F: Fn(&Dimension) -> T { key(&r.dim).partial_cmp(&key(&l.dim)).unwrap_or(Ordering::Equal) } impl Debug for SortHeuristic { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{}", self.name()) } }
{ d.w as f32 / d.h as f32 }
conditional_block
heuristics.rs
use super::{Dimension, PackInput}; use std::fmt::{Debug, Result, Formatter}; use std::cmp::{Ordering, PartialOrd, max}; pub const ALL: [&(SortHeuristic + Sync); 7] = [ &AreaSort, &PerimeterSort, &SideSort, &WidthSort, &HeightSort, &SquarenessByAreaSort, &SquarenessByPerimeterSort,
pub struct PerimeterSort; pub struct SideSort; pub struct WidthSort; pub struct HeightSort; pub struct SquarenessByAreaSort; pub struct SquarenessByPerimeterSort; pub trait SortHeuristic: Sync { fn name(&self) -> &'static str; fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering; } impl SortHeuristic for AreaSort { fn name(&self) -> &'static str { "area" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| d.w * d.h) } } impl SortHeuristic for PerimeterSort { fn name(&self) -> &'static str { "perimeter" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| d.w + d.h) } } impl SortHeuristic for SideSort { fn name(&self) -> &'static str { "side" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| max(d.w, d.h)) } } impl SortHeuristic for WidthSort { fn name(&self) -> &'static str { "width" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| d.w) } } impl SortHeuristic for HeightSort { fn name(&self) -> &'static str { "height" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| d.h) } } impl SortHeuristic for SquarenessByAreaSort { fn name(&self) -> &'static str { "squareness_area" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| sqa(d)) } } impl SortHeuristic for SquarenessByPerimeterSort { fn name(&self) -> &'static str { "squareness_perimeter" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| sqp(d)) } } fn squareness(d: &Dimension) -> f32 { if d.w < d.h { d.w as f32 / d.h as f32 } else { d.h as f32 / d.w as f32 } } fn sqa(d: &Dimension) -> f32 { squareness(d) * (d.w * d.h) as f32 } fn sqp(d: &Dimension) -> f32 { squareness(d) * (d.w + d.h) as f32 } fn cmp_by_key<F, T: PartialOrd>(l: &PackInput, r: &PackInput, key: F) -> Ordering where F: Fn(&Dimension) -> T { key(&r.dim).partial_cmp(&key(&l.dim)).unwrap_or(Ordering::Equal) } impl Debug for SortHeuristic { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{}", self.name()) } }
]; pub struct AreaSort;
random_line_split
heuristics.rs
use super::{Dimension, PackInput}; use std::fmt::{Debug, Result, Formatter}; use std::cmp::{Ordering, PartialOrd, max}; pub const ALL: [&(SortHeuristic + Sync); 7] = [ &AreaSort, &PerimeterSort, &SideSort, &WidthSort, &HeightSort, &SquarenessByAreaSort, &SquarenessByPerimeterSort, ]; pub struct AreaSort; pub struct PerimeterSort; pub struct SideSort; pub struct WidthSort; pub struct HeightSort; pub struct SquarenessByAreaSort; pub struct SquarenessByPerimeterSort; pub trait SortHeuristic: Sync { fn name(&self) -> &'static str; fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering; } impl SortHeuristic for AreaSort { fn name(&self) -> &'static str { "area" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| d.w * d.h) } } impl SortHeuristic for PerimeterSort { fn name(&self) -> &'static str { "perimeter" } fn
(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| d.w + d.h) } } impl SortHeuristic for SideSort { fn name(&self) -> &'static str { "side" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| max(d.w, d.h)) } } impl SortHeuristic for WidthSort { fn name(&self) -> &'static str { "width" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| d.w) } } impl SortHeuristic for HeightSort { fn name(&self) -> &'static str { "height" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| d.h) } } impl SortHeuristic for SquarenessByAreaSort { fn name(&self) -> &'static str { "squareness_area" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| sqa(d)) } } impl SortHeuristic for SquarenessByPerimeterSort { fn name(&self) -> &'static str { "squareness_perimeter" } fn cmp(&self, l: &PackInput, r: &PackInput) -> Ordering { cmp_by_key(l, r, |d| sqp(d)) } } fn squareness(d: &Dimension) -> f32 { if d.w < d.h { d.w as f32 / d.h as f32 } else { d.h as f32 / d.w as f32 } } fn sqa(d: &Dimension) -> f32 { squareness(d) * (d.w * d.h) as f32 } fn sqp(d: &Dimension) -> f32 { squareness(d) * (d.w + d.h) as f32 } fn cmp_by_key<F, T: PartialOrd>(l: &PackInput, r: &PackInput, key: F) -> Ordering where F: Fn(&Dimension) -> T { key(&r.dim).partial_cmp(&key(&l.dim)).unwrap_or(Ordering::Equal) } impl Debug for SortHeuristic { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{}", self.name()) } }
cmp
identifier_name
day_3.rs
use self::Number::{One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero}; #[derive(PartialEq, Debug)] pub enum Number { One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero } impl From<char> for Number { fn from(c: char) -> Number { match c { '1' => One, '2' => Two, '3' => Three, '4' => Four, '5' => Five, '6' => Six, '7' => Seven, '8' => Eight, '9' => Nine, '0' => Zero, _ => unreachable!("It is a bug!"), } } } #[derive(Default)] pub struct Display { input: Option<&'static str> } impl Display { pub fn new() -> Display
pub fn output(&self) -> Option<Vec<Number>> { match self.input { Some(data) => Some(data.chars().map(Number::from).collect::<Vec<Number>>()), None => Some(vec![]), } } pub fn input(&mut self, data: &'static str) { self.input = Some(data); } }
{ Display { input: None } }
identifier_body
day_3.rs
use self::Number::{One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero}; #[derive(PartialEq, Debug)] pub enum
{ One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero } impl From<char> for Number { fn from(c: char) -> Number { match c { '1' => One, '2' => Two, '3' => Three, '4' => Four, '5' => Five, '6' => Six, '7' => Seven, '8' => Eight, '9' => Nine, '0' => Zero, _ => unreachable!("It is a bug!"), } } } #[derive(Default)] pub struct Display { input: Option<&'static str> } impl Display { pub fn new() -> Display { Display { input: None } } pub fn output(&self) -> Option<Vec<Number>> { match self.input { Some(data) => Some(data.chars().map(Number::from).collect::<Vec<Number>>()), None => Some(vec![]), } } pub fn input(&mut self, data: &'static str) { self.input = Some(data); } }
Number
identifier_name
day_3.rs
use self::Number::{One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero}; #[derive(PartialEq, Debug)] pub enum Number { One, Two, Three, Four, Five, Six, Seven, Eight, Nine,
impl From<char> for Number { fn from(c: char) -> Number { match c { '1' => One, '2' => Two, '3' => Three, '4' => Four, '5' => Five, '6' => Six, '7' => Seven, '8' => Eight, '9' => Nine, '0' => Zero, _ => unreachable!("It is a bug!"), } } } #[derive(Default)] pub struct Display { input: Option<&'static str> } impl Display { pub fn new() -> Display { Display { input: None } } pub fn output(&self) -> Option<Vec<Number>> { match self.input { Some(data) => Some(data.chars().map(Number::from).collect::<Vec<Number>>()), None => Some(vec![]), } } pub fn input(&mut self, data: &'static str) { self.input = Some(data); } }
Zero }
random_line_split
update_json.rs
use toyunda_player::VideoMeta; use subtitles::*; use clap::ArgMatches; use std::path::PathBuf; use std::fs::File; extern crate serde_json; extern crate serde_yaml; /// true on success /// false on failure pub fn update_json(args: &ArgMatches) -> bool { if let Some(path) = args.value_of("JSON_FILE") { let json_path = PathBuf::from(path); let yaml_path = json_path.with_extension("yaml"); if (json_path.is_file() && yaml_path.is_file()) { let json_file = File::open(&json_path); let yaml_file = File::open(&yaml_path); match (json_file, yaml_file) { (Ok(json_file), Ok(yaml_file)) => { let video_meta: Result<VideoMeta, _> = serde_yaml::from_reader(&yaml_file); let subs: Result<Subtitles, _> = serde_json::from_reader(&json_file); match (video_meta, subs) { (Ok(video_meta), Ok(mut subs)) => { subs.song_info = video_meta.song_info.clone(); let mut json_file = File::create(&json_path) .expect("Can't open json file for writing"); if let Err(e) = serde_json::to_writer_pretty(&mut json_file, &subs) { println!("Some error occured while generating new subtitles : \ {:?}", e); false } else { true } } (Err(err), _) => { println!("error while parsing video_meta : {:?}", err); false } (_, Err(err)) => { println!("error while parsing subtitles : {:?}", err); false } } }
println!("file `{}` couldn't be opened : {:?}", json_path.display(), e); false } (_, Err(e)) => { println!("file `{}` couldn't be opened : {:?}", yaml_path.display(), e); false } } } else { if json_path.is_file() { println!("file `{}` not found", yaml_path.display()); } else { println!("file `{}` not found", json_path.display()); }; false } } else { println!("A file is required for the subcommand 'update'"); // clap shouldn't let this case happen but never too sure false } }
(Err(e), _) => {
random_line_split
update_json.rs
use toyunda_player::VideoMeta; use subtitles::*; use clap::ArgMatches; use std::path::PathBuf; use std::fs::File; extern crate serde_json; extern crate serde_yaml; /// true on success /// false on failure pub fn update_json(args: &ArgMatches) -> bool { if let Some(path) = args.value_of("JSON_FILE") { let json_path = PathBuf::from(path); let yaml_path = json_path.with_extension("yaml"); if (json_path.is_file() && yaml_path.is_file()) { let json_file = File::open(&json_path); let yaml_file = File::open(&yaml_path); match (json_file, yaml_file) { (Ok(json_file), Ok(yaml_file)) => { let video_meta: Result<VideoMeta, _> = serde_yaml::from_reader(&yaml_file); let subs: Result<Subtitles, _> = serde_json::from_reader(&json_file); match (video_meta, subs) { (Ok(video_meta), Ok(mut subs)) => { subs.song_info = video_meta.song_info.clone(); let mut json_file = File::create(&json_path) .expect("Can't open json file for writing"); if let Err(e) = serde_json::to_writer_pretty(&mut json_file, &subs) { println!("Some error occured while generating new subtitles : \ {:?}", e); false } else { true } } (Err(err), _) => { println!("error while parsing video_meta : {:?}", err); false } (_, Err(err)) => { println!("error while parsing subtitles : {:?}", err); false } } } (Err(e), _) => { println!("file `{}` couldn't be opened : {:?}", json_path.display(), e); false } (_, Err(e)) => { println!("file `{}` couldn't be opened : {:?}", yaml_path.display(), e); false } } } else
} else { println!("A file is required for the subcommand 'update'"); // clap shouldn't let this case happen but never too sure false } }
{ if json_path.is_file() { println!("file `{}` not found", yaml_path.display()); } else { println!("file `{}` not found", json_path.display()); }; false }
conditional_block
update_json.rs
use toyunda_player::VideoMeta; use subtitles::*; use clap::ArgMatches; use std::path::PathBuf; use std::fs::File; extern crate serde_json; extern crate serde_yaml; /// true on success /// false on failure pub fn update_json(args: &ArgMatches) -> bool
false } else { true } } (Err(err), _) => { println!("error while parsing video_meta : {:?}", err); false } (_, Err(err)) => { println!("error while parsing subtitles : {:?}", err); false } } } (Err(e), _) => { println!("file `{}` couldn't be opened : {:?}", json_path.display(), e); false } (_, Err(e)) => { println!("file `{}` couldn't be opened : {:?}", yaml_path.display(), e); false } } } else { if json_path.is_file() { println!("file `{}` not found", yaml_path.display()); } else { println!("file `{}` not found", json_path.display()); }; false } } else { println!("A file is required for the subcommand 'update'"); // clap shouldn't let this case happen but never too sure false } }
{ if let Some(path) = args.value_of("JSON_FILE") { let json_path = PathBuf::from(path); let yaml_path = json_path.with_extension("yaml"); if (json_path.is_file() && yaml_path.is_file()) { let json_file = File::open(&json_path); let yaml_file = File::open(&yaml_path); match (json_file, yaml_file) { (Ok(json_file), Ok(yaml_file)) => { let video_meta: Result<VideoMeta, _> = serde_yaml::from_reader(&yaml_file); let subs: Result<Subtitles, _> = serde_json::from_reader(&json_file); match (video_meta, subs) { (Ok(video_meta), Ok(mut subs)) => { subs.song_info = video_meta.song_info.clone(); let mut json_file = File::create(&json_path) .expect("Can't open json file for writing"); if let Err(e) = serde_json::to_writer_pretty(&mut json_file, &subs) { println!("Some error occured while generating new subtitles : \ {:?}", e);
identifier_body
update_json.rs
use toyunda_player::VideoMeta; use subtitles::*; use clap::ArgMatches; use std::path::PathBuf; use std::fs::File; extern crate serde_json; extern crate serde_yaml; /// true on success /// false on failure pub fn
(args: &ArgMatches) -> bool { if let Some(path) = args.value_of("JSON_FILE") { let json_path = PathBuf::from(path); let yaml_path = json_path.with_extension("yaml"); if (json_path.is_file() && yaml_path.is_file()) { let json_file = File::open(&json_path); let yaml_file = File::open(&yaml_path); match (json_file, yaml_file) { (Ok(json_file), Ok(yaml_file)) => { let video_meta: Result<VideoMeta, _> = serde_yaml::from_reader(&yaml_file); let subs: Result<Subtitles, _> = serde_json::from_reader(&json_file); match (video_meta, subs) { (Ok(video_meta), Ok(mut subs)) => { subs.song_info = video_meta.song_info.clone(); let mut json_file = File::create(&json_path) .expect("Can't open json file for writing"); if let Err(e) = serde_json::to_writer_pretty(&mut json_file, &subs) { println!("Some error occured while generating new subtitles : \ {:?}", e); false } else { true } } (Err(err), _) => { println!("error while parsing video_meta : {:?}", err); false } (_, Err(err)) => { println!("error while parsing subtitles : {:?}", err); false } } } (Err(e), _) => { println!("file `{}` couldn't be opened : {:?}", json_path.display(), e); false } (_, Err(e)) => { println!("file `{}` couldn't be opened : {:?}", yaml_path.display(), e); false } } } else { if json_path.is_file() { println!("file `{}` not found", yaml_path.display()); } else { println!("file `{}` not found", json_path.display()); }; false } } else { println!("A file is required for the subcommand 'update'"); // clap shouldn't let this case happen but never too sure false } }
update_json
identifier_name
let.rs
// // Copyright 2015 Joshua R. Rodgers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #[macro_use] extern crate query_rs; #[allow(unused_variables)] #[test] fn let_clause_should_introduce_new_context() { let result = query! { from x => (0..10).zip(0..10), let (a, b) = x, select a*b }; let expected = vec! [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]; for (i, x) in result.enumerate() { assert_eq!(x, expected[i]); } } #[allow(unused_variables)] #[test] fn
() { let multiplier = 2; let result = query! { from x => (0..5), let a = x * multiplier, select a }; let expected = vec! [0, 2, 4, 6, 8]; for (i, x) in result.enumerate() { assert_eq!(x, expected[i]); } }
let_clause_should_be_able_to_take_closure
identifier_name
let.rs
// // Copyright 2015 Joshua R. Rodgers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //
#[allow(unused_variables)] #[test] fn let_clause_should_introduce_new_context() { let result = query! { from x => (0..10).zip(0..10), let (a, b) = x, select a*b }; let expected = vec! [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]; for (i, x) in result.enumerate() { assert_eq!(x, expected[i]); } } #[allow(unused_variables)] #[test] fn let_clause_should_be_able_to_take_closure() { let multiplier = 2; let result = query! { from x => (0..5), let a = x * multiplier, select a }; let expected = vec! [0, 2, 4, 6, 8]; for (i, x) in result.enumerate() { assert_eq!(x, expected[i]); } }
#[macro_use] extern crate query_rs;
random_line_split
let.rs
// // Copyright 2015 Joshua R. Rodgers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #[macro_use] extern crate query_rs; #[allow(unused_variables)] #[test] fn let_clause_should_introduce_new_context()
#[allow(unused_variables)] #[test] fn let_clause_should_be_able_to_take_closure() { let multiplier = 2; let result = query! { from x => (0..5), let a = x * multiplier, select a }; let expected = vec! [0, 2, 4, 6, 8]; for (i, x) in result.enumerate() { assert_eq!(x, expected[i]); } }
{ let result = query! { from x => (0..10).zip(0..10), let (a, b) = x, select a*b }; let expected = vec! [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]; for (i, x) in result.enumerate() { assert_eq!(x, expected[i]); } }
identifier_body
mod.rs
// OpenAOE: An open source reimplementation of Age of Empires (1997) // Copyright (c) 2016 Kevin Fuller // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pub mod unit;
random_line_split
lib.rs
pub trait Summary { fn summarize(&self) -> String; } pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String, } impl Summary for NewsArticle { fn summarize(&self) -> String { format!("{}, by {} ({})", self.headline, self.author, self.location) } } pub struct Tweet { pub username: String, pub content: String, pub reply: bool, pub retweet: bool, } impl Summary for Tweet { fn summarize(&self) -> String { format!("{}: {}", self.username, self.content) } } // ANCHOR: here fn returns_summarizable(switch: bool) -> impl Summary { if switch { NewsArticle { headline: String::from( "Penguins win the Stanley Cup Championship!", ), location: String::from("Pittsburgh, PA, USA"), author: String::from("Iceburgh"), content: String::from( "The Pittsburgh Penguins once again are the best \ hockey team in the NHL.", ), } } else
} // ANCHOR_END: here
{ Tweet { username: String::from("horse_ebooks"), content: String::from( "of course, as you probably already know, people", ), reply: false, retweet: false, } }
conditional_block
lib.rs
pub trait Summary { fn summarize(&self) -> String; } pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String, } impl Summary for NewsArticle { fn summarize(&self) -> String { format!("{}, by {} ({})", self.headline, self.author, self.location) } } pub struct Tweet { pub username: String, pub content: String, pub reply: bool, pub retweet: bool, } impl Summary for Tweet { fn summarize(&self) -> String { format!("{}: {}", self.username, self.content) } } // ANCHOR: here fn returns_summarizable(switch: bool) -> impl Summary { if switch { NewsArticle { headline: String::from( "Penguins win the Stanley Cup Championship!", ), location: String::from("Pittsburgh, PA, USA"), author: String::from("Iceburgh"), content: String::from( "The Pittsburgh Penguins once again are the best \ hockey team in the NHL.", ), } } else { Tweet { username: String::from("horse_ebooks"), content: String::from( "of course, as you probably already know, people", ), reply: false, retweet: false, } } }
// ANCHOR_END: here
random_line_split
lib.rs
pub trait Summary { fn summarize(&self) -> String; } pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String, } impl Summary for NewsArticle { fn summarize(&self) -> String { format!("{}, by {} ({})", self.headline, self.author, self.location) } } pub struct
{ pub username: String, pub content: String, pub reply: bool, pub retweet: bool, } impl Summary for Tweet { fn summarize(&self) -> String { format!("{}: {}", self.username, self.content) } } // ANCHOR: here fn returns_summarizable(switch: bool) -> impl Summary { if switch { NewsArticle { headline: String::from( "Penguins win the Stanley Cup Championship!", ), location: String::from("Pittsburgh, PA, USA"), author: String::from("Iceburgh"), content: String::from( "The Pittsburgh Penguins once again are the best \ hockey team in the NHL.", ), } } else { Tweet { username: String::from("horse_ebooks"), content: String::from( "of course, as you probably already know, people", ), reply: false, retweet: false, } } } // ANCHOR_END: here
Tweet
identifier_name
htmltablecellelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use dom::bindings::codegen::Bindings::HTMLTableCellElementBinding::HTMLTableCellElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::LayoutJS; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::{Element, RawLayoutElementHelpers}; use dom::htmlelement::HTMLElement; use dom::htmltablerowelement::HTMLTableRowElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use html5ever_atoms::LocalName; use style::attr::{AttrValue, LengthOrPercentageOrAuto}; const DEFAULT_COLSPAN: u32 = 1; #[dom_struct] pub struct HTMLTableCellElement { htmlelement: HTMLElement, } impl HTMLTableCellElement { pub fn new_inherited(tag_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLTableCellElement { HTMLTableCellElement { htmlelement: HTMLElement::new_inherited(tag_name, prefix, document), } } #[inline] pub fn htmlelement(&self) -> &HTMLElement { &self.htmlelement } } impl HTMLTableCellElementMethods for HTMLTableCellElement { // https://html.spec.whatwg.org/multipage/#dom-tdth-colspan make_uint_getter!(ColSpan, "colspan", DEFAULT_COLSPAN); // https://html.spec.whatwg.org/multipage/#dom-tdth-colspan make_uint_setter!(SetColSpan, "colspan", DEFAULT_COLSPAN); // https://html.spec.whatwg.org/multipage/#dom-tdth-bgcolor make_getter!(BgColor, "bgcolor"); // https://html.spec.whatwg.org/multipage/#dom-tdth-bgcolor make_legacy_color_setter!(SetBgColor, "bgcolor"); // https://html.spec.whatwg.org/multipage/#dom-tdth-width make_getter!(Width, "width"); // https://html.spec.whatwg.org/multipage/#dom-tdth-width make_nonzero_dimension_setter!(SetWidth, "width"); // https://html.spec.whatwg.org/multipage/#dom-tdth-cellindex fn CellIndex(&self) -> i32 { let self_node = self.upcast::<Node>(); let parent_children = match self_node.GetParentNode() { Some(ref parent_node) if parent_node.is::<HTMLTableRowElement>() => { parent_node.children() }, _ => return -1, }; parent_children.filter(|c| c.is::<HTMLTableCellElement>()) .position(|c| &*c == self_node) .map_or(-1, |p| p as i32) } } pub trait HTMLTableCellElementLayoutHelpers { fn get_background_color(&self) -> Option<RGBA>; fn get_colspan(&self) -> Option<u32>; fn get_width(&self) -> LengthOrPercentageOrAuto; } #[allow(unsafe_code)] impl HTMLTableCellElementLayoutHelpers for LayoutJS<HTMLTableCellElement> { fn get_background_color(&self) -> Option<RGBA> { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("bgcolor")) .and_then(AttrValue::as_color) .cloned() } } fn get_colspan(&self) -> Option<u32> { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("colspan")) .map(AttrValue::as_uint) } } fn
(&self) -> LengthOrPercentageOrAuto { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("width")) .map(AttrValue::as_dimension) .cloned() .unwrap_or(LengthOrPercentageOrAuto::Auto) } } } impl VirtualMethods for HTMLTableCellElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue { match *local_name { local_name!("colspan") => AttrValue::from_u32(value.into(), DEFAULT_COLSPAN), local_name!("bgcolor") => AttrValue::from_legacy_color(value.into()), local_name!("width") => AttrValue::from_nonzero_dimension(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), } } }
get_width
identifier_name
htmltablecellelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use dom::bindings::codegen::Bindings::HTMLTableCellElementBinding::HTMLTableCellElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::LayoutJS; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::{Element, RawLayoutElementHelpers}; use dom::htmlelement::HTMLElement; use dom::htmltablerowelement::HTMLTableRowElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use html5ever_atoms::LocalName; use style::attr::{AttrValue, LengthOrPercentageOrAuto}; const DEFAULT_COLSPAN: u32 = 1; #[dom_struct] pub struct HTMLTableCellElement { htmlelement: HTMLElement, } impl HTMLTableCellElement { pub fn new_inherited(tag_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLTableCellElement { HTMLTableCellElement { htmlelement: HTMLElement::new_inherited(tag_name, prefix, document), } } #[inline] pub fn htmlelement(&self) -> &HTMLElement { &self.htmlelement } } impl HTMLTableCellElementMethods for HTMLTableCellElement { // https://html.spec.whatwg.org/multipage/#dom-tdth-colspan make_uint_getter!(ColSpan, "colspan", DEFAULT_COLSPAN); // https://html.spec.whatwg.org/multipage/#dom-tdth-colspan make_uint_setter!(SetColSpan, "colspan", DEFAULT_COLSPAN); // https://html.spec.whatwg.org/multipage/#dom-tdth-bgcolor make_getter!(BgColor, "bgcolor"); // https://html.spec.whatwg.org/multipage/#dom-tdth-bgcolor make_legacy_color_setter!(SetBgColor, "bgcolor"); // https://html.spec.whatwg.org/multipage/#dom-tdth-width make_getter!(Width, "width"); // https://html.spec.whatwg.org/multipage/#dom-tdth-width make_nonzero_dimension_setter!(SetWidth, "width"); // https://html.spec.whatwg.org/multipage/#dom-tdth-cellindex fn CellIndex(&self) -> i32 { let self_node = self.upcast::<Node>(); let parent_children = match self_node.GetParentNode() { Some(ref parent_node) if parent_node.is::<HTMLTableRowElement>() => { parent_node.children() }, _ => return -1, }; parent_children.filter(|c| c.is::<HTMLTableCellElement>()) .position(|c| &*c == self_node) .map_or(-1, |p| p as i32) } } pub trait HTMLTableCellElementLayoutHelpers { fn get_background_color(&self) -> Option<RGBA>; fn get_colspan(&self) -> Option<u32>; fn get_width(&self) -> LengthOrPercentageOrAuto; } #[allow(unsafe_code)] impl HTMLTableCellElementLayoutHelpers for LayoutJS<HTMLTableCellElement> { fn get_background_color(&self) -> Option<RGBA> { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("bgcolor"))
fn get_colspan(&self) -> Option<u32> { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("colspan")) .map(AttrValue::as_uint) } } fn get_width(&self) -> LengthOrPercentageOrAuto { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("width")) .map(AttrValue::as_dimension) .cloned() .unwrap_or(LengthOrPercentageOrAuto::Auto) } } } impl VirtualMethods for HTMLTableCellElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue { match *local_name { local_name!("colspan") => AttrValue::from_u32(value.into(), DEFAULT_COLSPAN), local_name!("bgcolor") => AttrValue::from_legacy_color(value.into()), local_name!("width") => AttrValue::from_nonzero_dimension(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), } } }
.and_then(AttrValue::as_color) .cloned() } }
random_line_split
htmltablecellelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use dom::bindings::codegen::Bindings::HTMLTableCellElementBinding::HTMLTableCellElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::LayoutJS; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::{Element, RawLayoutElementHelpers}; use dom::htmlelement::HTMLElement; use dom::htmltablerowelement::HTMLTableRowElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use html5ever_atoms::LocalName; use style::attr::{AttrValue, LengthOrPercentageOrAuto}; const DEFAULT_COLSPAN: u32 = 1; #[dom_struct] pub struct HTMLTableCellElement { htmlelement: HTMLElement, } impl HTMLTableCellElement { pub fn new_inherited(tag_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLTableCellElement { HTMLTableCellElement { htmlelement: HTMLElement::new_inherited(tag_name, prefix, document), } } #[inline] pub fn htmlelement(&self) -> &HTMLElement { &self.htmlelement } } impl HTMLTableCellElementMethods for HTMLTableCellElement { // https://html.spec.whatwg.org/multipage/#dom-tdth-colspan make_uint_getter!(ColSpan, "colspan", DEFAULT_COLSPAN); // https://html.spec.whatwg.org/multipage/#dom-tdth-colspan make_uint_setter!(SetColSpan, "colspan", DEFAULT_COLSPAN); // https://html.spec.whatwg.org/multipage/#dom-tdth-bgcolor make_getter!(BgColor, "bgcolor"); // https://html.spec.whatwg.org/multipage/#dom-tdth-bgcolor make_legacy_color_setter!(SetBgColor, "bgcolor"); // https://html.spec.whatwg.org/multipage/#dom-tdth-width make_getter!(Width, "width"); // https://html.spec.whatwg.org/multipage/#dom-tdth-width make_nonzero_dimension_setter!(SetWidth, "width"); // https://html.spec.whatwg.org/multipage/#dom-tdth-cellindex fn CellIndex(&self) -> i32 { let self_node = self.upcast::<Node>(); let parent_children = match self_node.GetParentNode() { Some(ref parent_node) if parent_node.is::<HTMLTableRowElement>() => { parent_node.children() }, _ => return -1, }; parent_children.filter(|c| c.is::<HTMLTableCellElement>()) .position(|c| &*c == self_node) .map_or(-1, |p| p as i32) } } pub trait HTMLTableCellElementLayoutHelpers { fn get_background_color(&self) -> Option<RGBA>; fn get_colspan(&self) -> Option<u32>; fn get_width(&self) -> LengthOrPercentageOrAuto; } #[allow(unsafe_code)] impl HTMLTableCellElementLayoutHelpers for LayoutJS<HTMLTableCellElement> { fn get_background_color(&self) -> Option<RGBA>
fn get_colspan(&self) -> Option<u32> { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("colspan")) .map(AttrValue::as_uint) } } fn get_width(&self) -> LengthOrPercentageOrAuto { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("width")) .map(AttrValue::as_dimension) .cloned() .unwrap_or(LengthOrPercentageOrAuto::Auto) } } } impl VirtualMethods for HTMLTableCellElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue { match *local_name { local_name!("colspan") => AttrValue::from_u32(value.into(), DEFAULT_COLSPAN), local_name!("bgcolor") => AttrValue::from_legacy_color(value.into()), local_name!("width") => AttrValue::from_nonzero_dimension(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), } } }
{ unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("bgcolor")) .and_then(AttrValue::as_color) .cloned() } }
identifier_body
enums.rs
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors // GENERATOR-BEGIN: LegacyHandlerFlags // ⚠️This was generated by GENERATOR!🦹‍♂️ pub(crate) struct LegacyHandler
d_code)] impl LegacyHandlerFlags { pub(crate) const HANDLER_REG: u32 = 0x0000_0001; pub(crate) const HANDLER_MEM: u32 = 0x0000_0002; pub(crate) const HANDLER_66_REG: u32 = 0x0000_0004; pub(crate) const HANDLER_66_MEM: u32 = 0x0000_0008; pub(crate) const HANDLER_F3_REG: u32 = 0x0000_0010; pub(crate) const HANDLER_F3_MEM: u32 = 0x0000_0020; pub(crate) const HANDLER_F2_REG: u32 = 0x0000_0040; pub(crate) const HANDLER_F2_MEM: u32 = 0x0000_0080; } // GENERATOR-END: LegacyHandlerFlags
Flags; #[allow(dea
identifier_name
enums.rs
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors // GENERATOR-BEGIN: LegacyHandlerFlags // ⚠️This was generated by GENERATOR!🦹‍♂️ pub(crate) struct LegacyHandlerFlags; #[allow(dead_code)] impl LegacyHandlerFlags { pub(crate) const HANDLER_REG: u32 = 0x0000_0001; pub(crate) const HANDLER_MEM: u32 = 0x0000_0002; pub(crate) const HANDLER_66_REG: u32 = 0x0000_0004; pub(crate) const HANDLER_66_MEM: u32 = 0x0000_0008; pub(crate) const HANDLER_F3_REG: u32 = 0x0000_0010; pub(crate) const HANDLER_F3_MEM: u32 = 0x0000_0020;
} // GENERATOR-END: LegacyHandlerFlags
pub(crate) const HANDLER_F2_REG: u32 = 0x0000_0040; pub(crate) const HANDLER_F2_MEM: u32 = 0x0000_0080;
random_line_split
mutate.rs
use malachite_base::rational_sequences::RationalSequence; use malachite_base_test_util::generators::large_type_gen_var_22; #[test] pub fn test_mutate() { fn test( non_repeating: &[u8], repeating: &[u8], index: usize, new_value: u8, out: u8, non_repeating_out: &[u8], repeating_out: &[u8], ) { let mut xs = RationalSequence::from_slices(non_repeating, repeating); assert_eq!( xs.mutate(index, |x| { *x = new_value; out }), out ); assert_eq!( xs, RationalSequence::from_slices(non_repeating_out, repeating_out) ); } test(&[1, 2, 3], &[], 0, 5, 6, &[5, 2, 3], &[]); test(&[1, 2, 3], &[], 1, 5, 6, &[1, 5, 3], &[]); test(&[1, 2, 3], &[], 2, 5, 6, &[1, 2, 5], &[]); test( &[1, 2, 3], &[4, 5, 6], 3, 100, 6, &[1, 2, 3, 100], &[5, 6, 4], ); test( &[1, 2, 3], &[4, 5, 6], 10, 100, 6, &[1, 2, 3, 4, 5, 6, 4, 5, 6, 4, 100], &[6, 4, 5], ); } #[test] #[should_panic] fn mutate_fail_1()
#[test] #[should_panic] fn mutate_fail_2() { RationalSequence::from_vec(vec![1, 2, 3]).mutate(3, |_| {}) } #[test] fn mutate_properties() { large_type_gen_var_22::<u8>().test_properties(|(mut xs, index, y, z)| { let xs_old = xs.clone(); let x_old = xs[index]; assert_eq!( xs.mutate(index, |x| { *x = y; z }), z ); assert_eq!(xs[index], y); xs.mutate(index, |x| { *x = x_old; }); assert_eq!(xs, xs_old); }); }
{ RationalSequence::<u8>::from_vec(vec![]).mutate(0, |_| {}); }
identifier_body
mutate.rs
use malachite_base::rational_sequences::RationalSequence; use malachite_base_test_util::generators::large_type_gen_var_22; #[test] pub fn test_mutate() { fn test( non_repeating: &[u8], repeating: &[u8], index: usize, new_value: u8, out: u8, non_repeating_out: &[u8], repeating_out: &[u8], ) { let mut xs = RationalSequence::from_slices(non_repeating, repeating); assert_eq!( xs.mutate(index, |x| { *x = new_value; out }), out ); assert_eq!( xs, RationalSequence::from_slices(non_repeating_out, repeating_out) ); } test(&[1, 2, 3], &[], 0, 5, 6, &[5, 2, 3], &[]); test(&[1, 2, 3], &[], 1, 5, 6, &[1, 5, 3], &[]); test(&[1, 2, 3], &[], 2, 5, 6, &[1, 2, 5], &[]); test( &[1, 2, 3], &[4, 5, 6], 3, 100, 6,
); test( &[1, 2, 3], &[4, 5, 6], 10, 100, 6, &[1, 2, 3, 4, 5, 6, 4, 5, 6, 4, 100], &[6, 4, 5], ); } #[test] #[should_panic] fn mutate_fail_1() { RationalSequence::<u8>::from_vec(vec![]).mutate(0, |_| {}); } #[test] #[should_panic] fn mutate_fail_2() { RationalSequence::from_vec(vec![1, 2, 3]).mutate(3, |_| {}) } #[test] fn mutate_properties() { large_type_gen_var_22::<u8>().test_properties(|(mut xs, index, y, z)| { let xs_old = xs.clone(); let x_old = xs[index]; assert_eq!( xs.mutate(index, |x| { *x = y; z }), z ); assert_eq!(xs[index], y); xs.mutate(index, |x| { *x = x_old; }); assert_eq!(xs, xs_old); }); }
&[1, 2, 3, 100], &[5, 6, 4],
random_line_split
mutate.rs
use malachite_base::rational_sequences::RationalSequence; use malachite_base_test_util::generators::large_type_gen_var_22; #[test] pub fn test_mutate() { fn test( non_repeating: &[u8], repeating: &[u8], index: usize, new_value: u8, out: u8, non_repeating_out: &[u8], repeating_out: &[u8], ) { let mut xs = RationalSequence::from_slices(non_repeating, repeating); assert_eq!( xs.mutate(index, |x| { *x = new_value; out }), out ); assert_eq!( xs, RationalSequence::from_slices(non_repeating_out, repeating_out) ); } test(&[1, 2, 3], &[], 0, 5, 6, &[5, 2, 3], &[]); test(&[1, 2, 3], &[], 1, 5, 6, &[1, 5, 3], &[]); test(&[1, 2, 3], &[], 2, 5, 6, &[1, 2, 5], &[]); test( &[1, 2, 3], &[4, 5, 6], 3, 100, 6, &[1, 2, 3, 100], &[5, 6, 4], ); test( &[1, 2, 3], &[4, 5, 6], 10, 100, 6, &[1, 2, 3, 4, 5, 6, 4, 5, 6, 4, 100], &[6, 4, 5], ); } #[test] #[should_panic] fn mutate_fail_1() { RationalSequence::<u8>::from_vec(vec![]).mutate(0, |_| {}); } #[test] #[should_panic] fn
() { RationalSequence::from_vec(vec![1, 2, 3]).mutate(3, |_| {}) } #[test] fn mutate_properties() { large_type_gen_var_22::<u8>().test_properties(|(mut xs, index, y, z)| { let xs_old = xs.clone(); let x_old = xs[index]; assert_eq!( xs.mutate(index, |x| { *x = y; z }), z ); assert_eq!(xs[index], y); xs.mutate(index, |x| { *x = x_old; }); assert_eq!(xs, xs_old); }); }
mutate_fail_2
identifier_name
util.rs
extern crate time; use std::env; use std::fs; use std::path; use std::time::{SystemTime, UNIX_EPOCH}; use core::io::BinaryComponent; use core::sig; pub fn load_user_keypair() -> Option<sig::Keypair>
} pub fn timestamp() -> i64 { let dur = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); ((dur.as_secs() * 1000) + ((dur.subsec_nanos() / 1000000) as u64)) as i64 }
{ let kpp = match env::home_dir() { Some(mut p) => { p.push(".jiyunet"); p.push("keypair.bin"); p }, None => path::PathBuf::from(".") }; let mut f = match fs::File::open(kpp) { Ok(o) => o, Err(_) => return None }; match sig::Keypair::from_reader(&mut f) { Ok(kp) => Some(kp), Err(_) => None }
identifier_body
util.rs
extern crate time; use std::env; use std::fs; use std::path; use std::time::{SystemTime, UNIX_EPOCH}; use core::io::BinaryComponent; use core::sig; pub fn load_user_keypair() -> Option<sig::Keypair> { let kpp = match env::home_dir() { Some(mut p) => { p.push(".jiyunet"); p.push("keypair.bin"); p },
}; let mut f = match fs::File::open(kpp) { Ok(o) => o, Err(_) => return None }; match sig::Keypair::from_reader(&mut f) { Ok(kp) => Some(kp), Err(_) => None } } pub fn timestamp() -> i64 { let dur = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); ((dur.as_secs() * 1000) + ((dur.subsec_nanos() / 1000000) as u64)) as i64 }
None => path::PathBuf::from(".")
random_line_split
util.rs
extern crate time; use std::env; use std::fs; use std::path; use std::time::{SystemTime, UNIX_EPOCH}; use core::io::BinaryComponent; use core::sig; pub fn
() -> Option<sig::Keypair> { let kpp = match env::home_dir() { Some(mut p) => { p.push(".jiyunet"); p.push("keypair.bin"); p }, None => path::PathBuf::from(".") }; let mut f = match fs::File::open(kpp) { Ok(o) => o, Err(_) => return None }; match sig::Keypair::from_reader(&mut f) { Ok(kp) => Some(kp), Err(_) => None } } pub fn timestamp() -> i64 { let dur = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); ((dur.as_secs() * 1000) + ((dur.subsec_nanos() / 1000000) as u64)) as i64 }
load_user_keypair
identifier_name
error.rs
//! Error types for corepack. // // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at https://mozilla.org/MPL/2.0/. use std::fmt::Display; #[cfg(feature = "alloc")] use alloc::string::String; #[cfg(feature = "alloc")] use alloc::string::ToString; use std::str::Utf8Error; use std::fmt; /// Reasons that parsing or encoding might fail in corepack. #[derive(Debug)] pub enum Error { /// Container or sequence was too big to serialize. TooBig, /// Reached end of a stream. EndOfStream, /// Invalid type encountered. BadType, /// Invalid length encountered. BadLength, /// Error decoding UTF8 string. Utf8Error(Utf8Error), /// Some other error that does not fit into the above. Other(String), } impl Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str(self.description()) } } impl Error { fn description(&self) -> &str { match self { &Error::TooBig => "Overflowing value", &Error::EndOfStream => "End of stream", &Error::BadType => "Invalid type", &Error::BadLength => "Invalid length", &Error::Utf8Error(_) => "UTF8 Error", &Error::Other(ref message) => &message, } }
Error::Utf8Error(cause) } } #[cfg(feature = "std")] impl ::std::error::Error for Error { fn description(&self) -> &str { Error::description(self) } fn cause(&self) -> Option<&::std::error::Error> { match self { &Error::Utf8Error(ref cause) => Some(cause), _ => None, } } } impl ::serde::ser::Error for Error { fn custom<T: Display>(msg: T) -> Error { Error::Other(msg.to_string()) } } impl ::serde::de::Error for Error { fn custom<T: Display>(msg: T) -> Error { ::serde::ser::Error::custom(msg) } }
} impl From<Utf8Error> for Error { fn from(cause: Utf8Error) -> Error {
random_line_split
error.rs
//! Error types for corepack. // // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at https://mozilla.org/MPL/2.0/. use std::fmt::Display; #[cfg(feature = "alloc")] use alloc::string::String; #[cfg(feature = "alloc")] use alloc::string::ToString; use std::str::Utf8Error; use std::fmt; /// Reasons that parsing or encoding might fail in corepack. #[derive(Debug)] pub enum Error { /// Container or sequence was too big to serialize. TooBig, /// Reached end of a stream. EndOfStream, /// Invalid type encountered. BadType, /// Invalid length encountered. BadLength, /// Error decoding UTF8 string. Utf8Error(Utf8Error), /// Some other error that does not fit into the above. Other(String), } impl Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result
} impl Error { fn description(&self) -> &str { match self { &Error::TooBig => "Overflowing value", &Error::EndOfStream => "End of stream", &Error::BadType => "Invalid type", &Error::BadLength => "Invalid length", &Error::Utf8Error(_) => "UTF8 Error", &Error::Other(ref message) => &message, } } } impl From<Utf8Error> for Error { fn from(cause: Utf8Error) -> Error { Error::Utf8Error(cause) } } #[cfg(feature = "std")] impl ::std::error::Error for Error { fn description(&self) -> &str { Error::description(self) } fn cause(&self) -> Option<&::std::error::Error> { match self { &Error::Utf8Error(ref cause) => Some(cause), _ => None, } } } impl ::serde::ser::Error for Error { fn custom<T: Display>(msg: T) -> Error { Error::Other(msg.to_string()) } } impl ::serde::de::Error for Error { fn custom<T: Display>(msg: T) -> Error { ::serde::ser::Error::custom(msg) } }
{ fmt.write_str(self.description()) }
identifier_body
error.rs
//! Error types for corepack. // // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at https://mozilla.org/MPL/2.0/. use std::fmt::Display; #[cfg(feature = "alloc")] use alloc::string::String; #[cfg(feature = "alloc")] use alloc::string::ToString; use std::str::Utf8Error; use std::fmt; /// Reasons that parsing or encoding might fail in corepack. #[derive(Debug)] pub enum Error { /// Container or sequence was too big to serialize. TooBig, /// Reached end of a stream. EndOfStream, /// Invalid type encountered. BadType, /// Invalid length encountered. BadLength, /// Error decoding UTF8 string. Utf8Error(Utf8Error), /// Some other error that does not fit into the above. Other(String), } impl Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str(self.description()) } } impl Error { fn
(&self) -> &str { match self { &Error::TooBig => "Overflowing value", &Error::EndOfStream => "End of stream", &Error::BadType => "Invalid type", &Error::BadLength => "Invalid length", &Error::Utf8Error(_) => "UTF8 Error", &Error::Other(ref message) => &message, } } } impl From<Utf8Error> for Error { fn from(cause: Utf8Error) -> Error { Error::Utf8Error(cause) } } #[cfg(feature = "std")] impl ::std::error::Error for Error { fn description(&self) -> &str { Error::description(self) } fn cause(&self) -> Option<&::std::error::Error> { match self { &Error::Utf8Error(ref cause) => Some(cause), _ => None, } } } impl ::serde::ser::Error for Error { fn custom<T: Display>(msg: T) -> Error { Error::Other(msg.to_string()) } } impl ::serde::de::Error for Error { fn custom<T: Display>(msg: T) -> Error { ::serde::ser::Error::custom(msg) } }
description
identifier_name
lang_items.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. // Detecting language items. // // Language items are items that represent concepts intrinsic to the language // itself. Examples are: // // * Traits that specify "kinds"; e.g. "Sync", "Send". // // * Traits that represent operators; e.g. "Add", "Sub", "Index". // // * Functions called by the compiler itself. pub use self::LangItem::*; use session::Session; use metadata::csearch::each_lang_item; use middle::ty; use middle::weak_lang_items; use util::nodemap::FnvHashMap; use syntax::ast; use syntax::ast_util::local_def; use syntax::attr::AttrMetaMethods; use syntax::codemap::{DUMMY_SP, Span}; use syntax::parse::token::InternedString; use syntax::visit::Visitor; use syntax::visit; use std::iter::Enumerate; use std::slice; // The actual lang items defined come at the end of this file in one handy table. // So you probably just want to nip down to the end. macro_rules! lets_do_this { ( $( $variant:ident, $name:expr, $method:ident; )* ) => { enum_from_u32! { #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub enum LangItem { $($variant,)* } } pub struct LanguageItems { pub items: Vec<Option<ast::DefId>>, pub missing: Vec<LangItem>, } impl LanguageItems { pub fn new() -> LanguageItems { fn foo(_: LangItem) -> Option<ast::DefId> { None } LanguageItems { items: vec!($(foo($variant)),*), missing: Vec::new(), } } pub fn items<'a>(&'a self) -> Enumerate<slice::Iter<'a, Option<ast::DefId>>> { self.items.iter().enumerate() } pub fn item_name(index: usize) -> &'static str { let item: Option<LangItem> = LangItem::from_u32(index as u32); match item { $( Some($variant) => $name, )* None => "???" } } pub fn require(&self, it: LangItem) -> Result<ast::DefId, String> { match self.items[it as usize] { Some(id) => Ok(id), None => { Err(format!("requires `{}` lang_item", LanguageItems::item_name(it as usize))) } } } pub fn require_owned_box(&self) -> Result<ast::DefId, String> { self.require(OwnedBoxLangItem) } pub fn from_builtin_kind(&self, bound: ty::BuiltinBound) -> Result<ast::DefId, String> { match bound { ty::BoundSend => self.require(SendTraitLangItem), ty::BoundSized => self.require(SizedTraitLangItem), ty::BoundCopy => self.require(CopyTraitLangItem), ty::BoundSync => self.require(SyncTraitLangItem), } } pub fn to_builtin_kind(&self, id: ast::DefId) -> Option<ty::BuiltinBound> { if Some(id) == self.send_trait() { Some(ty::BoundSend) } else if Some(id) == self.sized_trait() { Some(ty::BoundSized) } else if Some(id) == self.copy_trait() { Some(ty::BoundCopy) } else if Some(id) == self.sync_trait() { Some(ty::BoundSync) } else { None } } pub fn fn_trait_kind(&self, id: ast::DefId) -> Option<ty::ClosureKind> { let def_id_kinds = [ (self.fn_trait(), ty::FnClosureKind), (self.fn_mut_trait(), ty::FnMutClosureKind), (self.fn_once_trait(), ty::FnOnceClosureKind), ]; for &(opt_def_id, kind) in &def_id_kinds { if Some(id) == opt_def_id { return Some(kind); } } None } $( #[allow(dead_code)] pub fn $method(&self) -> Option<ast::DefId> { self.items[$variant as usize] } )* } struct LanguageItemCollector<'a> { items: LanguageItems, session: &'a Session, item_refs: FnvHashMap<&'static str, usize>, } impl<'a, 'v> Visitor<'v> for LanguageItemCollector<'a> { fn visit_item(&mut self, item: &ast::Item) { if let Some(value) = extract(&item.attrs) {
} visit::walk_item(self, item); } } impl<'a> LanguageItemCollector<'a> { pub fn new(session: &'a Session) -> LanguageItemCollector<'a> { let mut item_refs = FnvHashMap(); $( item_refs.insert($name, $variant as usize); )* LanguageItemCollector { session: session, items: LanguageItems::new(), item_refs: item_refs } } pub fn collect_item(&mut self, item_index: usize, item_def_id: ast::DefId, span: Span) { // Check for duplicates. match self.items.items[item_index] { Some(original_def_id) if original_def_id!= item_def_id => { span_err!(self.session, span, E0152, "duplicate entry for `{}`", LanguageItems::item_name(item_index)); } Some(_) | None => { // OK. } } // Matched. self.items.items[item_index] = Some(item_def_id); } pub fn collect_local_language_items(&mut self, krate: &ast::Crate) { visit::walk_crate(self, krate); } pub fn collect_external_language_items(&mut self) { let crate_store = &self.session.cstore; crate_store.iter_crate_data(|crate_number, _crate_metadata| { each_lang_item(crate_store, crate_number, |node_id, item_index| { let def_id = ast::DefId { krate: crate_number, node: node_id }; self.collect_item(item_index, def_id, DUMMY_SP); true }); }) } pub fn collect(&mut self, krate: &ast::Crate) { self.collect_local_language_items(krate); self.collect_external_language_items(); } } pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> { for attribute in attrs { match attribute.value_str() { Some(ref value) if attribute.check_name("lang") => { return Some(value.clone()); } _ => {} } } return None; } pub fn collect_language_items(krate: &ast::Crate, session: &Session) -> LanguageItems { let mut collector = LanguageItemCollector::new(session); collector.collect(krate); let LanguageItemCollector { mut items,.. } = collector; weak_lang_items::check_crate(krate, session, &mut items); session.abort_if_errors(); items } // End of the macro } } lets_do_this! { // Variant name, Name, Method name; CharImplItem, "char", char_impl; StrImplItem, "str", str_impl; SliceImplItem, "slice", slice_impl; ConstPtrImplItem, "const_ptr", const_ptr_impl; MutPtrImplItem, "mut_ptr", mut_ptr_impl; I8ImplItem, "i8", i8_impl; I16ImplItem, "i16", i16_impl; I32ImplItem, "i32", i32_impl; I64ImplItem, "i64", i64_impl; IsizeImplItem, "isize", isize_impl; U8ImplItem, "u8", u8_impl; U16ImplItem, "u16", u16_impl; U32ImplItem, "u32", u32_impl; U64ImplItem, "u64", u64_impl; UsizeImplItem, "usize", usize_impl; F32ImplItem, "f32", f32_impl; F64ImplItem, "f64", f64_impl; SendTraitLangItem, "send", send_trait; SizedTraitLangItem, "sized", sized_trait; UnsizeTraitLangItem, "unsize", unsize_trait; CopyTraitLangItem, "copy", copy_trait; SyncTraitLangItem, "sync", sync_trait; DropTraitLangItem, "drop", drop_trait; CoerceUnsizedTraitLangItem, "coerce_unsized", coerce_unsized_trait; AddTraitLangItem, "add", add_trait; SubTraitLangItem, "sub", sub_trait; MulTraitLangItem, "mul", mul_trait; DivTraitLangItem, "div", div_trait; RemTraitLangItem, "rem", rem_trait; NegTraitLangItem, "neg", neg_trait; NotTraitLangItem, "not", not_trait; BitXorTraitLangItem, "bitxor", bitxor_trait; BitAndTraitLangItem, "bitand", bitand_trait; BitOrTraitLangItem, "bitor", bitor_trait; ShlTraitLangItem, "shl", shl_trait; ShrTraitLangItem, "shr", shr_trait; IndexTraitLangItem, "index", index_trait; IndexMutTraitLangItem, "index_mut", index_mut_trait; RangeStructLangItem, "range", range_struct; RangeFromStructLangItem, "range_from", range_from_struct; RangeToStructLangItem, "range_to", range_to_struct; RangeFullStructLangItem, "range_full", range_full_struct; UnsafeCellTypeLangItem, "unsafe_cell", unsafe_cell_type; DerefTraitLangItem, "deref", deref_trait; DerefMutTraitLangItem, "deref_mut", deref_mut_trait; FnTraitLangItem, "fn", fn_trait; FnMutTraitLangItem, "fn_mut", fn_mut_trait; FnOnceTraitLangItem, "fn_once", fn_once_trait; EqTraitLangItem, "eq", eq_trait; OrdTraitLangItem, "ord", ord_trait; StrEqFnLangItem, "str_eq", str_eq_fn; // A number of panic-related lang items. The `panic` item corresponds to // divide-by-zero and various panic cases with `match`. The // `panic_bounds_check` item is for indexing arrays. // // The `begin_unwind` lang item has a predefined symbol name and is sort of // a "weak lang item" in the sense that a crate is not required to have it // defined to use it, but a final product is required to define it // somewhere. Additionally, there are restrictions on crates that use a weak // lang item, but do not have it defined. PanicFnLangItem, "panic", panic_fn; PanicBoundsCheckFnLangItem, "panic_bounds_check", panic_bounds_check_fn; PanicFmtLangItem, "panic_fmt", panic_fmt; ExchangeMallocFnLangItem, "exchange_malloc", exchange_malloc_fn; ExchangeFreeFnLangItem, "exchange_free", exchange_free_fn; StrDupUniqFnLangItem, "strdup_uniq", strdup_uniq_fn; StartFnLangItem, "start", start_fn; EhPersonalityLangItem, "eh_personality", eh_personality; EhPersonalityCatchLangItem, "eh_personality_catch", eh_personality_catch; EhUnwindResumeLangItem, "eh_unwind_resume", eh_unwind_resume; MSVCTryFilterLangItem, "msvc_try_filter", msvc_try_filter; ExchangeHeapLangItem, "exchange_heap", exchange_heap; OwnedBoxLangItem, "owned_box", owned_box; PhantomDataItem, "phantom_data", phantom_data; // Deprecated: CovariantTypeItem, "covariant_type", covariant_type; ContravariantTypeItem, "contravariant_type", contravariant_type; InvariantTypeItem, "invariant_type", invariant_type; CovariantLifetimeItem, "covariant_lifetime", covariant_lifetime; ContravariantLifetimeItem, "contravariant_lifetime", contravariant_lifetime; InvariantLifetimeItem, "invariant_lifetime", invariant_lifetime; NoCopyItem, "no_copy_bound", no_copy_bound; NonZeroItem, "non_zero", non_zero; StackExhaustedLangItem, "stack_exhausted", stack_exhausted; DebugTraitLangItem, "debug_trait", debug_trait; }
let item_index = self.item_refs.get(&value[..]).cloned(); if let Some(item_index) = item_index { self.collect_item(item_index, local_def(item.id), item.span) }
random_line_split
js.rs
use crate::{CharEncoder, Named}; pub struct Js; impl CharEncoder for Js { fn encode(iter: &mut dyn Iterator<Item = char>) -> Option<String> { iter.next().map(|ch| { let i = ch as u32; if i <= 0xFFFF { format!("\\u{:01$X}", i, 4) } else
}) } fn wrap_in_quotes() -> bool { true } } impl Named for Js { fn name() -> &'static str { "javascript" } } #[cfg(test)] mod tests { use super::Js; use crate::{CharEncoder, Named}; use std::iter::{empty, once}; #[test] fn empty_iterator() { assert_eq!(Js::encode(&mut empty()), None); } #[test] fn values() { let expected1 = Some(r"\u0000".to_string()); assert_eq!(Js::encode(&mut "\u{0}".chars()), expected1); let expected2 = Some(r"\u005E".to_string()); assert_eq!(Js::encode(&mut once('^')), expected2); let expected3 = Some(r"\u210B".to_string()); assert_eq!(Js::encode(&mut once('ℋ')), expected3); // "𝔄" is a single code pointer greater than FFFF let expected4 = Some(r"\u{1D504}".to_string()); assert_eq!(Js::encode(&mut once('𝔄')), expected4); } #[test] fn loop_without_crashing() { let v = vec!['a', 'b', 'c']; let mut iter = v.into_iter(); while let Some(_) = Js::encode(&mut iter) {} } #[test] fn quotes() { assert!(Js::wrap_in_quotes()); } #[test] fn name() { assert_eq!(Js::name(), "javascript"); } }
{ format!("\\u{{{:X}}}", i) }
conditional_block
js.rs
use crate::{CharEncoder, Named}; pub struct Js; impl CharEncoder for Js { fn
(iter: &mut dyn Iterator<Item = char>) -> Option<String> { iter.next().map(|ch| { let i = ch as u32; if i <= 0xFFFF { format!("\\u{:01$X}", i, 4) } else { format!("\\u{{{:X}}}", i) } }) } fn wrap_in_quotes() -> bool { true } } impl Named for Js { fn name() -> &'static str { "javascript" } } #[cfg(test)] mod tests { use super::Js; use crate::{CharEncoder, Named}; use std::iter::{empty, once}; #[test] fn empty_iterator() { assert_eq!(Js::encode(&mut empty()), None); } #[test] fn values() { let expected1 = Some(r"\u0000".to_string()); assert_eq!(Js::encode(&mut "\u{0}".chars()), expected1); let expected2 = Some(r"\u005E".to_string()); assert_eq!(Js::encode(&mut once('^')), expected2); let expected3 = Some(r"\u210B".to_string()); assert_eq!(Js::encode(&mut once('ℋ')), expected3); // "𝔄" is a single code pointer greater than FFFF let expected4 = Some(r"\u{1D504}".to_string()); assert_eq!(Js::encode(&mut once('𝔄')), expected4); } #[test] fn loop_without_crashing() { let v = vec!['a', 'b', 'c']; let mut iter = v.into_iter(); while let Some(_) = Js::encode(&mut iter) {} } #[test] fn quotes() { assert!(Js::wrap_in_quotes()); } #[test] fn name() { assert_eq!(Js::name(), "javascript"); } }
encode
identifier_name
js.rs
use crate::{CharEncoder, Named}; pub struct Js; impl CharEncoder for Js { fn encode(iter: &mut dyn Iterator<Item = char>) -> Option<String> { iter.next().map(|ch| { let i = ch as u32; if i <= 0xFFFF { format!("\\u{:01$X}", i, 4) } else { format!("\\u{{{:X}}}", i) } }) } fn wrap_in_quotes() -> bool { true } } impl Named for Js { fn name() -> &'static str { "javascript" } } #[cfg(test)] mod tests { use super::Js; use crate::{CharEncoder, Named}; use std::iter::{empty, once}; #[test] fn empty_iterator() { assert_eq!(Js::encode(&mut empty()), None); } #[test] fn values() { let expected1 = Some(r"\u0000".to_string()); assert_eq!(Js::encode(&mut "\u{0}".chars()), expected1); let expected2 = Some(r"\u005E".to_string()); assert_eq!(Js::encode(&mut once('^')), expected2); let expected3 = Some(r"\u210B".to_string()); assert_eq!(Js::encode(&mut once('ℋ')), expected3); // "𝔄" is a single code pointer greater than FFFF let expected4 = Some(r"\u{1D504}".to_string()); assert_eq!(Js::encode(&mut once('𝔄')), expected4); } #[test] fn loop_without_crashing() { let v = vec!['a', 'b', 'c']; let mut iter = v.into_iter(); while let Some(_) = Js::encode(&mut iter) {} } #[test] fn quotes() { assert!(Js::wrap_in_quotes()); } #[test] fn name() {
assert_eq!(Js::name(), "javascript"); } }
identifier_body
js.rs
use crate::{CharEncoder, Named}; pub struct Js; impl CharEncoder for Js { fn encode(iter: &mut dyn Iterator<Item = char>) -> Option<String> { iter.next().map(|ch| { let i = ch as u32; if i <= 0xFFFF { format!("\\u{:01$X}", i, 4) } else { format!("\\u{{{:X}}}", i) } }) } fn wrap_in_quotes() -> bool { true } } impl Named for Js { fn name() -> &'static str { "javascript" } } #[cfg(test)] mod tests { use super::Js; use crate::{CharEncoder, Named}; use std::iter::{empty, once}; #[test] fn empty_iterator() { assert_eq!(Js::encode(&mut empty()), None); } #[test] fn values() { let expected1 = Some(r"\u0000".to_string()); assert_eq!(Js::encode(&mut "\u{0}".chars()), expected1); let expected2 = Some(r"\u005E".to_string()); assert_eq!(Js::encode(&mut once('^')), expected2); let expected3 = Some(r"\u210B".to_string()); assert_eq!(Js::encode(&mut once('ℋ')), expected3); // "𝔄" is a single code pointer greater than FFFF let expected4 = Some(r"\u{1D504}".to_string()); assert_eq!(Js::encode(&mut once('𝔄')), expected4); } #[test] fn loop_without_crashing() { let v = vec!['a', 'b', 'c']; let mut iter = v.into_iter(); while let Some(_) = Js::encode(&mut iter) {}
assert!(Js::wrap_in_quotes()); } #[test] fn name() { assert_eq!(Js::name(), "javascript"); } }
} #[test] fn quotes() {
random_line_split
macro-only-syntax.rs
// force-host // no-prefer-dynamic // These are tests for syntax that is accepted by the Rust parser but // unconditionally rejected semantically after macro expansion. Attribute macros // are permitted to accept such syntax as long as they replace it with something // that makes sense to Rust. // // We also inspect some of the spans to verify the syntax is not triggering the // lossy string reparse hack (https://github.com/rust-lang/rust/issues/43081). #![crate_type = "proc-macro"] #![feature(proc_macro_span)] extern crate proc_macro; use proc_macro::{token_stream, Delimiter, TokenStream, TokenTree}; use std::path::Component; // unsafe mod m { // pub unsafe mod inner; // } #[proc_macro_attribute] pub fn expect_unsafe_mod(_attrs: TokenStream, input: TokenStream) -> TokenStream { let tokens = &mut input.into_iter(); expect(tokens, "unsafe"); expect(tokens, "mod"); expect(tokens, "m"); let tokens = &mut expect_brace(tokens); expect(tokens, "pub"); expect(tokens, "unsafe"); expect(tokens, "mod"); let ident = expect(tokens, "inner"); expect(tokens, ";"); check_useful_span(ident, "unsafe-mod.rs"); TokenStream::new() } // unsafe extern { // type T; // } #[proc_macro_attribute] pub fn expect_unsafe_foreign_mod(_attrs: TokenStream, input: TokenStream) -> TokenStream { let tokens = &mut input.into_iter(); expect(tokens, "unsafe"); expect(tokens, "extern"); let tokens = &mut expect_brace(tokens); expect(tokens, "type"); let ident = expect(tokens, "T"); expect(tokens, ";"); check_useful_span(ident, "unsafe-foreign-mod.rs"); TokenStream::new() } // unsafe extern "C++" {} #[proc_macro_attribute] pub fn expect_unsafe_extern_cpp_mod(_attrs: TokenStream, input: TokenStream) -> TokenStream { let tokens = &mut input.into_iter(); expect(tokens, "unsafe"); expect(tokens, "extern"); let abi = expect(tokens, "\"C++\""); expect_brace(tokens); check_useful_span(abi, "unsafe-foreign-mod.rs"); TokenStream::new() } fn expect(tokens: &mut token_stream::IntoIter, expected: &str) -> TokenTree
fn expect_brace(tokens: &mut token_stream::IntoIter) -> token_stream::IntoIter { match tokens.next() { Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Brace => { group.stream().into_iter() } wrong => panic!("unexpected token: {:?}, expected `{{`", wrong), } } fn check_useful_span(token: TokenTree, expected_filename: &str) { let span = token.span(); assert!(span.start().column < span.end().column); let source_path = span.source_file().path(); let filename = source_path.components().last().unwrap(); assert_eq!(filename, Component::Normal(expected_filename.as_ref())); }
{ match tokens.next() { Some(token) if token.to_string() == expected => token, wrong => panic!("unexpected token: {:?}, expected `{}`", wrong, expected), } }
identifier_body
macro-only-syntax.rs
// force-host // no-prefer-dynamic // These are tests for syntax that is accepted by the Rust parser but // unconditionally rejected semantically after macro expansion. Attribute macros // are permitted to accept such syntax as long as they replace it with something // that makes sense to Rust. // // We also inspect some of the spans to verify the syntax is not triggering the // lossy string reparse hack (https://github.com/rust-lang/rust/issues/43081). #![crate_type = "proc-macro"] #![feature(proc_macro_span)] extern crate proc_macro; use proc_macro::{token_stream, Delimiter, TokenStream, TokenTree}; use std::path::Component; // unsafe mod m { // pub unsafe mod inner; // } #[proc_macro_attribute] pub fn
(_attrs: TokenStream, input: TokenStream) -> TokenStream { let tokens = &mut input.into_iter(); expect(tokens, "unsafe"); expect(tokens, "mod"); expect(tokens, "m"); let tokens = &mut expect_brace(tokens); expect(tokens, "pub"); expect(tokens, "unsafe"); expect(tokens, "mod"); let ident = expect(tokens, "inner"); expect(tokens, ";"); check_useful_span(ident, "unsafe-mod.rs"); TokenStream::new() } // unsafe extern { // type T; // } #[proc_macro_attribute] pub fn expect_unsafe_foreign_mod(_attrs: TokenStream, input: TokenStream) -> TokenStream { let tokens = &mut input.into_iter(); expect(tokens, "unsafe"); expect(tokens, "extern"); let tokens = &mut expect_brace(tokens); expect(tokens, "type"); let ident = expect(tokens, "T"); expect(tokens, ";"); check_useful_span(ident, "unsafe-foreign-mod.rs"); TokenStream::new() } // unsafe extern "C++" {} #[proc_macro_attribute] pub fn expect_unsafe_extern_cpp_mod(_attrs: TokenStream, input: TokenStream) -> TokenStream { let tokens = &mut input.into_iter(); expect(tokens, "unsafe"); expect(tokens, "extern"); let abi = expect(tokens, "\"C++\""); expect_brace(tokens); check_useful_span(abi, "unsafe-foreign-mod.rs"); TokenStream::new() } fn expect(tokens: &mut token_stream::IntoIter, expected: &str) -> TokenTree { match tokens.next() { Some(token) if token.to_string() == expected => token, wrong => panic!("unexpected token: {:?}, expected `{}`", wrong, expected), } } fn expect_brace(tokens: &mut token_stream::IntoIter) -> token_stream::IntoIter { match tokens.next() { Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Brace => { group.stream().into_iter() } wrong => panic!("unexpected token: {:?}, expected `{{`", wrong), } } fn check_useful_span(token: TokenTree, expected_filename: &str) { let span = token.span(); assert!(span.start().column < span.end().column); let source_path = span.source_file().path(); let filename = source_path.components().last().unwrap(); assert_eq!(filename, Component::Normal(expected_filename.as_ref())); }
expect_unsafe_mod
identifier_name
macro-only-syntax.rs
// force-host // no-prefer-dynamic // These are tests for syntax that is accepted by the Rust parser but // unconditionally rejected semantically after macro expansion. Attribute macros // are permitted to accept such syntax as long as they replace it with something // that makes sense to Rust. // // We also inspect some of the spans to verify the syntax is not triggering the // lossy string reparse hack (https://github.com/rust-lang/rust/issues/43081).
#![crate_type = "proc-macro"] #![feature(proc_macro_span)] extern crate proc_macro; use proc_macro::{token_stream, Delimiter, TokenStream, TokenTree}; use std::path::Component; // unsafe mod m { // pub unsafe mod inner; // } #[proc_macro_attribute] pub fn expect_unsafe_mod(_attrs: TokenStream, input: TokenStream) -> TokenStream { let tokens = &mut input.into_iter(); expect(tokens, "unsafe"); expect(tokens, "mod"); expect(tokens, "m"); let tokens = &mut expect_brace(tokens); expect(tokens, "pub"); expect(tokens, "unsafe"); expect(tokens, "mod"); let ident = expect(tokens, "inner"); expect(tokens, ";"); check_useful_span(ident, "unsafe-mod.rs"); TokenStream::new() } // unsafe extern { // type T; // } #[proc_macro_attribute] pub fn expect_unsafe_foreign_mod(_attrs: TokenStream, input: TokenStream) -> TokenStream { let tokens = &mut input.into_iter(); expect(tokens, "unsafe"); expect(tokens, "extern"); let tokens = &mut expect_brace(tokens); expect(tokens, "type"); let ident = expect(tokens, "T"); expect(tokens, ";"); check_useful_span(ident, "unsafe-foreign-mod.rs"); TokenStream::new() } // unsafe extern "C++" {} #[proc_macro_attribute] pub fn expect_unsafe_extern_cpp_mod(_attrs: TokenStream, input: TokenStream) -> TokenStream { let tokens = &mut input.into_iter(); expect(tokens, "unsafe"); expect(tokens, "extern"); let abi = expect(tokens, "\"C++\""); expect_brace(tokens); check_useful_span(abi, "unsafe-foreign-mod.rs"); TokenStream::new() } fn expect(tokens: &mut token_stream::IntoIter, expected: &str) -> TokenTree { match tokens.next() { Some(token) if token.to_string() == expected => token, wrong => panic!("unexpected token: {:?}, expected `{}`", wrong, expected), } } fn expect_brace(tokens: &mut token_stream::IntoIter) -> token_stream::IntoIter { match tokens.next() { Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Brace => { group.stream().into_iter() } wrong => panic!("unexpected token: {:?}, expected `{{`", wrong), } } fn check_useful_span(token: TokenTree, expected_filename: &str) { let span = token.span(); assert!(span.start().column < span.end().column); let source_path = span.source_file().path(); let filename = source_path.components().last().unwrap(); assert_eq!(filename, Component::Normal(expected_filename.as_ref())); }
random_line_split
android.rs
use regex::Regex; use crate::file::{get_path, get_content, set_content}; use crate::git::list_changes_main; use crate::version::Version;
fn path_error_logs() -> String { get_path(vec!["..", "android", "ErrorLogs", "build.gradle"]) } pub fn update_android(version: &Version) { let changes = list_changes_main(); let changed_general = general_changed(&changes); let updated_main = update_main(version); if!updated_main { return } if changed_general || changed("App", &changes) { change_code(path_app(), "(2011\\d{6})"); } if changed_general || changed("ErrorLogs", &changes) { change_code(path_error_logs(), "(\\d+)"); } } fn general_changed(list: &Vec<String>) -> bool { let checks = vec![ "Lib", "TestUtils", "build.gradle", "gradle.properties", "settings.gradle" ]; for check in checks { if changed(check, list) { return true; } } return false; } fn changed(name: &str, list: &Vec<String>) -> bool { let path = format!("android/{}", name); for item in list { if item.starts_with(&path) { return true; } } return false; } fn update_main(version: &Version) -> bool { let mut content = get_content(path_main()); if!content.contains(&version.prev) { return false; } let old_name = version_name(&version.prev); let new_name = version_name(&version.code); content = content.replace(&old_name, &new_name); set_content(path_main(), content); return true } fn version_name(version: &str) -> String { format!(r#"ext.dfm_version = "{}""#, version) } fn change_code(path: String, pattern: &str) { let mut content = get_content(path.clone()); let pattern = version_code(&pattern); let regex = Regex::new(&pattern).unwrap(); let old_number = regex .captures(&content) .unwrap() .get(1) .unwrap() .as_str() .parse::<i32>() .unwrap(); let new_number = old_number + 1; let old_code = version_code(&old_number.to_string()); let new_code = version_code(&new_number.to_string()); content = content.replace(&old_code, &new_code); set_content(path, content); } fn version_code(version: &str) -> String { format!("versionCode {}", version) }
fn path_main() -> String { get_path(vec!["..", "android", "build.gradle"]) } fn path_app() -> String { get_path(vec!["..", "android", "App", "build.gradle"]) }
random_line_split
android.rs
use regex::Regex; use crate::file::{get_path, get_content, set_content}; use crate::git::list_changes_main; use crate::version::Version; fn path_main() -> String { get_path(vec!["..", "android", "build.gradle"]) } fn path_app() -> String { get_path(vec!["..", "android", "App", "build.gradle"]) } fn path_error_logs() -> String { get_path(vec!["..", "android", "ErrorLogs", "build.gradle"]) } pub fn update_android(version: &Version) { let changes = list_changes_main(); let changed_general = general_changed(&changes); let updated_main = update_main(version); if!updated_main { return } if changed_general || changed("App", &changes) { change_code(path_app(), "(2011\\d{6})"); } if changed_general || changed("ErrorLogs", &changes) { change_code(path_error_logs(), "(\\d+)"); } } fn general_changed(list: &Vec<String>) -> bool { let checks = vec![ "Lib", "TestUtils", "build.gradle", "gradle.properties", "settings.gradle" ]; for check in checks { if changed(check, list) { return true; } } return false; } fn changed(name: &str, list: &Vec<String>) -> bool { let path = format!("android/{}", name); for item in list { if item.starts_with(&path) { return true; } } return false; } fn update_main(version: &Version) -> bool { let mut content = get_content(path_main()); if!content.contains(&version.prev) { return false; } let old_name = version_name(&version.prev); let new_name = version_name(&version.code); content = content.replace(&old_name, &new_name); set_content(path_main(), content); return true } fn
(version: &str) -> String { format!(r#"ext.dfm_version = "{}""#, version) } fn change_code(path: String, pattern: &str) { let mut content = get_content(path.clone()); let pattern = version_code(&pattern); let regex = Regex::new(&pattern).unwrap(); let old_number = regex .captures(&content) .unwrap() .get(1) .unwrap() .as_str() .parse::<i32>() .unwrap(); let new_number = old_number + 1; let old_code = version_code(&old_number.to_string()); let new_code = version_code(&new_number.to_string()); content = content.replace(&old_code, &new_code); set_content(path, content); } fn version_code(version: &str) -> String { format!("versionCode {}", version) }
version_name
identifier_name
android.rs
use regex::Regex; use crate::file::{get_path, get_content, set_content}; use crate::git::list_changes_main; use crate::version::Version; fn path_main() -> String { get_path(vec!["..", "android", "build.gradle"]) } fn path_app() -> String { get_path(vec!["..", "android", "App", "build.gradle"]) } fn path_error_logs() -> String { get_path(vec!["..", "android", "ErrorLogs", "build.gradle"]) } pub fn update_android(version: &Version) { let changes = list_changes_main(); let changed_general = general_changed(&changes); let updated_main = update_main(version); if!updated_main { return } if changed_general || changed("App", &changes) { change_code(path_app(), "(2011\\d{6})"); } if changed_general || changed("ErrorLogs", &changes) { change_code(path_error_logs(), "(\\d+)"); } } fn general_changed(list: &Vec<String>) -> bool { let checks = vec![ "Lib", "TestUtils", "build.gradle", "gradle.properties", "settings.gradle" ]; for check in checks { if changed(check, list) { return true; } } return false; } fn changed(name: &str, list: &Vec<String>) -> bool { let path = format!("android/{}", name); for item in list { if item.starts_with(&path)
} return false; } fn update_main(version: &Version) -> bool { let mut content = get_content(path_main()); if!content.contains(&version.prev) { return false; } let old_name = version_name(&version.prev); let new_name = version_name(&version.code); content = content.replace(&old_name, &new_name); set_content(path_main(), content); return true } fn version_name(version: &str) -> String { format!(r#"ext.dfm_version = "{}""#, version) } fn change_code(path: String, pattern: &str) { let mut content = get_content(path.clone()); let pattern = version_code(&pattern); let regex = Regex::new(&pattern).unwrap(); let old_number = regex .captures(&content) .unwrap() .get(1) .unwrap() .as_str() .parse::<i32>() .unwrap(); let new_number = old_number + 1; let old_code = version_code(&old_number.to_string()); let new_code = version_code(&new_number.to_string()); content = content.replace(&old_code, &new_code); set_content(path, content); } fn version_code(version: &str) -> String { format!("versionCode {}", version) }
{ return true; }
conditional_block
android.rs
use regex::Regex; use crate::file::{get_path, get_content, set_content}; use crate::git::list_changes_main; use crate::version::Version; fn path_main() -> String { get_path(vec!["..", "android", "build.gradle"]) } fn path_app() -> String { get_path(vec!["..", "android", "App", "build.gradle"]) } fn path_error_logs() -> String { get_path(vec!["..", "android", "ErrorLogs", "build.gradle"]) } pub fn update_android(version: &Version)
fn general_changed(list: &Vec<String>) -> bool { let checks = vec![ "Lib", "TestUtils", "build.gradle", "gradle.properties", "settings.gradle" ]; for check in checks { if changed(check, list) { return true; } } return false; } fn changed(name: &str, list: &Vec<String>) -> bool { let path = format!("android/{}", name); for item in list { if item.starts_with(&path) { return true; } } return false; } fn update_main(version: &Version) -> bool { let mut content = get_content(path_main()); if!content.contains(&version.prev) { return false; } let old_name = version_name(&version.prev); let new_name = version_name(&version.code); content = content.replace(&old_name, &new_name); set_content(path_main(), content); return true } fn version_name(version: &str) -> String { format!(r#"ext.dfm_version = "{}""#, version) } fn change_code(path: String, pattern: &str) { let mut content = get_content(path.clone()); let pattern = version_code(&pattern); let regex = Regex::new(&pattern).unwrap(); let old_number = regex .captures(&content) .unwrap() .get(1) .unwrap() .as_str() .parse::<i32>() .unwrap(); let new_number = old_number + 1; let old_code = version_code(&old_number.to_string()); let new_code = version_code(&new_number.to_string()); content = content.replace(&old_code, &new_code); set_content(path, content); } fn version_code(version: &str) -> String { format!("versionCode {}", version) }
{ let changes = list_changes_main(); let changed_general = general_changed(&changes); let updated_main = update_main(version); if !updated_main { return } if changed_general || changed("App", &changes) { change_code(path_app(), "(2011\\d{6})"); } if changed_general || changed("ErrorLogs", &changes) { change_code(path_error_logs(), "(\\d+)"); } }
identifier_body
arc.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 thread::Mutex; use mem::{replace, transmute}; use kinds::{Freeze, Send, marker}; use clone::{Clone, DeepClone}; use ops::Drop; use cmp::{Eq, Ord}; use atomic::{atomic_fence_acq, atomic_xadd_relaxed, atomic_xsub_rel}; struct ArcBox<T> { value: T, count: int } #[unsafe_no_drop_flag] pub struct Arc<T> { ptr: *mut ArcBox<T> } impl<T: Send + Freeze> Arc<T> { #[inline(always)] pub fn new(value: T) -> Arc<T> { unsafe { Arc::new_unchecked(value) } } } impl<T> Arc<T> { pub unsafe fn new_unchecked(value: T) -> Arc<T> { Arc{ptr: transmute(~ArcBox{value: value, count: 1})} } } impl<T> Arc<T> { #[inline(always)] pub fn borrow<'a>(&'a self) -> &'a T { unsafe { &(*self.ptr).value } } } // Reasoning behind the atomic memory ordering: // http://www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html #[unsafe_destructor] impl<T> Drop for Arc<T> { fn drop(&mut self) { if self.ptr!= 0 as *mut ArcBox<T> { unsafe { if atomic_xsub_rel(&mut (*self.ptr).count, 1) == 1 { atomic_fence_acq(); let _: ~ArcBox<T> = transmute(self.ptr); } } } } } impl<T> Clone for Arc<T> { fn clone(&self) -> Arc<T> { unsafe { atomic_xadd_relaxed(&mut (*self.ptr).count, 1); Arc { ptr: self.ptr } } } } impl<T: DeepClone> DeepClone for Arc<T> { fn deep_clone(&self) -> Arc<T> { unsafe { Arc::new_unchecked(self.borrow().deep_clone()) } } } impl<T: Eq> Eq for Arc<T> { #[inline(always)] fn eq(&self, other: &Arc<T>) -> bool { *self.borrow() == *other.borrow() } #[inline(always)] fn ne(&self, other: &Arc<T>) -> bool { *self.borrow()!= *other.borrow() } } impl<T: Ord> Ord for Arc<T> { #[inline(always)] fn lt(&self, other: &Arc<T>) -> bool { *self.borrow() < *other.borrow() } #[inline(always)] fn le(&self, other: &Arc<T>) -> bool { *self.borrow() <= *other.borrow() } #[inline(always)] fn gt(&self, other: &Arc<T>) -> bool { *self.borrow() > *other.borrow() } #[inline(always)] fn ge(&self, other: &Arc<T>) -> bool
} struct MutexArcBox<T> { mutex: Mutex, value: T, no_freeze: marker::NoFreeze } pub struct MutexArc<T> { ptr: Arc<MutexArcBox<T>> } impl<T: Send> MutexArc<T> { pub fn new(value: T) -> MutexArc<T> { let b = MutexArcBox { mutex: Mutex::new(), value: value, no_freeze: marker::NoFreeze }; unsafe { MutexArc { ptr: Arc::new_unchecked(b) } } } pub fn swap(&self, value: T) -> T { unsafe { let ptr: &mut MutexArcBox<T> = transmute(self.ptr.borrow()); let _guard = ptr.mutex.lock_guard(); replace(&mut ptr.value, value) } } } impl<T> Clone for MutexArc<T> { #[inline(always)] fn clone(&self) -> MutexArc<T> { MutexArc { ptr: self.ptr.clone() } } }
{ *self.borrow() >= *other.borrow() }
identifier_body
arc.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 thread::Mutex; use mem::{replace, transmute}; use kinds::{Freeze, Send, marker}; use clone::{Clone, DeepClone}; use ops::Drop; use cmp::{Eq, Ord}; use atomic::{atomic_fence_acq, atomic_xadd_relaxed, atomic_xsub_rel}; struct ArcBox<T> { value: T, count: int } #[unsafe_no_drop_flag] pub struct Arc<T> { ptr: *mut ArcBox<T> } impl<T: Send + Freeze> Arc<T> { #[inline(always)] pub fn new(value: T) -> Arc<T> { unsafe { Arc::new_unchecked(value) } } } impl<T> Arc<T> { pub unsafe fn new_unchecked(value: T) -> Arc<T> { Arc{ptr: transmute(~ArcBox{value: value, count: 1})} } } impl<T> Arc<T> { #[inline(always)] pub fn borrow<'a>(&'a self) -> &'a T { unsafe { &(*self.ptr).value } } } // Reasoning behind the atomic memory ordering: // http://www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html #[unsafe_destructor] impl<T> Drop for Arc<T> { fn drop(&mut self) { if self.ptr!= 0 as *mut ArcBox<T> { unsafe { if atomic_xsub_rel(&mut (*self.ptr).count, 1) == 1 { atomic_fence_acq(); let _: ~ArcBox<T> = transmute(self.ptr); } } } } } impl<T> Clone for Arc<T> { fn clone(&self) -> Arc<T> { unsafe { atomic_xadd_relaxed(&mut (*self.ptr).count, 1); Arc { ptr: self.ptr } } } } impl<T: DeepClone> DeepClone for Arc<T> { fn deep_clone(&self) -> Arc<T> { unsafe { Arc::new_unchecked(self.borrow().deep_clone()) } } } impl<T: Eq> Eq for Arc<T> { #[inline(always)] fn eq(&self, other: &Arc<T>) -> bool { *self.borrow() == *other.borrow() } #[inline(always)] fn ne(&self, other: &Arc<T>) -> bool { *self.borrow()!= *other.borrow() } } impl<T: Ord> Ord for Arc<T> { #[inline(always)] fn lt(&self, other: &Arc<T>) -> bool { *self.borrow() < *other.borrow() } #[inline(always)] fn le(&self, other: &Arc<T>) -> bool { *self.borrow() <= *other.borrow() } #[inline(always)] fn gt(&self, other: &Arc<T>) -> bool { *self.borrow() > *other.borrow() } #[inline(always)] fn ge(&self, other: &Arc<T>) -> bool { *self.borrow() >= *other.borrow() } } struct MutexArcBox<T> { mutex: Mutex, value: T, no_freeze: marker::NoFreeze } pub struct MutexArc<T> { ptr: Arc<MutexArcBox<T>> } impl<T: Send> MutexArc<T> { pub fn new(value: T) -> MutexArc<T> { let b = MutexArcBox { mutex: Mutex::new(), value: value, no_freeze: marker::NoFreeze }; unsafe { MutexArc { ptr: Arc::new_unchecked(b) } } } pub fn swap(&self, value: T) -> T { unsafe { let ptr: &mut MutexArcBox<T> = transmute(self.ptr.borrow()); let _guard = ptr.mutex.lock_guard(); replace(&mut ptr.value, value) } } } impl<T> Clone for MutexArc<T> { #[inline(always)] fn clone(&self) -> MutexArc<T> { MutexArc { ptr: self.ptr.clone() }
} }
random_line_split
arc.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 thread::Mutex; use mem::{replace, transmute}; use kinds::{Freeze, Send, marker}; use clone::{Clone, DeepClone}; use ops::Drop; use cmp::{Eq, Ord}; use atomic::{atomic_fence_acq, atomic_xadd_relaxed, atomic_xsub_rel}; struct ArcBox<T> { value: T, count: int } #[unsafe_no_drop_flag] pub struct Arc<T> { ptr: *mut ArcBox<T> } impl<T: Send + Freeze> Arc<T> { #[inline(always)] pub fn new(value: T) -> Arc<T> { unsafe { Arc::new_unchecked(value) } } } impl<T> Arc<T> { pub unsafe fn new_unchecked(value: T) -> Arc<T> { Arc{ptr: transmute(~ArcBox{value: value, count: 1})} } } impl<T> Arc<T> { #[inline(always)] pub fn borrow<'a>(&'a self) -> &'a T { unsafe { &(*self.ptr).value } } } // Reasoning behind the atomic memory ordering: // http://www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html #[unsafe_destructor] impl<T> Drop for Arc<T> { fn drop(&mut self) { if self.ptr!= 0 as *mut ArcBox<T>
} } impl<T> Clone for Arc<T> { fn clone(&self) -> Arc<T> { unsafe { atomic_xadd_relaxed(&mut (*self.ptr).count, 1); Arc { ptr: self.ptr } } } } impl<T: DeepClone> DeepClone for Arc<T> { fn deep_clone(&self) -> Arc<T> { unsafe { Arc::new_unchecked(self.borrow().deep_clone()) } } } impl<T: Eq> Eq for Arc<T> { #[inline(always)] fn eq(&self, other: &Arc<T>) -> bool { *self.borrow() == *other.borrow() } #[inline(always)] fn ne(&self, other: &Arc<T>) -> bool { *self.borrow()!= *other.borrow() } } impl<T: Ord> Ord for Arc<T> { #[inline(always)] fn lt(&self, other: &Arc<T>) -> bool { *self.borrow() < *other.borrow() } #[inline(always)] fn le(&self, other: &Arc<T>) -> bool { *self.borrow() <= *other.borrow() } #[inline(always)] fn gt(&self, other: &Arc<T>) -> bool { *self.borrow() > *other.borrow() } #[inline(always)] fn ge(&self, other: &Arc<T>) -> bool { *self.borrow() >= *other.borrow() } } struct MutexArcBox<T> { mutex: Mutex, value: T, no_freeze: marker::NoFreeze } pub struct MutexArc<T> { ptr: Arc<MutexArcBox<T>> } impl<T: Send> MutexArc<T> { pub fn new(value: T) -> MutexArc<T> { let b = MutexArcBox { mutex: Mutex::new(), value: value, no_freeze: marker::NoFreeze }; unsafe { MutexArc { ptr: Arc::new_unchecked(b) } } } pub fn swap(&self, value: T) -> T { unsafe { let ptr: &mut MutexArcBox<T> = transmute(self.ptr.borrow()); let _guard = ptr.mutex.lock_guard(); replace(&mut ptr.value, value) } } } impl<T> Clone for MutexArc<T> { #[inline(always)] fn clone(&self) -> MutexArc<T> { MutexArc { ptr: self.ptr.clone() } } }
{ unsafe { if atomic_xsub_rel(&mut (*self.ptr).count, 1) == 1 { atomic_fence_acq(); let _: ~ArcBox<T> = transmute(self.ptr); } } }
conditional_block
arc.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 thread::Mutex; use mem::{replace, transmute}; use kinds::{Freeze, Send, marker}; use clone::{Clone, DeepClone}; use ops::Drop; use cmp::{Eq, Ord}; use atomic::{atomic_fence_acq, atomic_xadd_relaxed, atomic_xsub_rel}; struct ArcBox<T> { value: T, count: int } #[unsafe_no_drop_flag] pub struct Arc<T> { ptr: *mut ArcBox<T> } impl<T: Send + Freeze> Arc<T> { #[inline(always)] pub fn new(value: T) -> Arc<T> { unsafe { Arc::new_unchecked(value) } } } impl<T> Arc<T> { pub unsafe fn new_unchecked(value: T) -> Arc<T> { Arc{ptr: transmute(~ArcBox{value: value, count: 1})} } } impl<T> Arc<T> { #[inline(always)] pub fn borrow<'a>(&'a self) -> &'a T { unsafe { &(*self.ptr).value } } } // Reasoning behind the atomic memory ordering: // http://www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html #[unsafe_destructor] impl<T> Drop for Arc<T> { fn drop(&mut self) { if self.ptr!= 0 as *mut ArcBox<T> { unsafe { if atomic_xsub_rel(&mut (*self.ptr).count, 1) == 1 { atomic_fence_acq(); let _: ~ArcBox<T> = transmute(self.ptr); } } } } } impl<T> Clone for Arc<T> { fn clone(&self) -> Arc<T> { unsafe { atomic_xadd_relaxed(&mut (*self.ptr).count, 1); Arc { ptr: self.ptr } } } } impl<T: DeepClone> DeepClone for Arc<T> { fn deep_clone(&self) -> Arc<T> { unsafe { Arc::new_unchecked(self.borrow().deep_clone()) } } } impl<T: Eq> Eq for Arc<T> { #[inline(always)] fn eq(&self, other: &Arc<T>) -> bool { *self.borrow() == *other.borrow() } #[inline(always)] fn ne(&self, other: &Arc<T>) -> bool { *self.borrow()!= *other.borrow() } } impl<T: Ord> Ord for Arc<T> { #[inline(always)] fn
(&self, other: &Arc<T>) -> bool { *self.borrow() < *other.borrow() } #[inline(always)] fn le(&self, other: &Arc<T>) -> bool { *self.borrow() <= *other.borrow() } #[inline(always)] fn gt(&self, other: &Arc<T>) -> bool { *self.borrow() > *other.borrow() } #[inline(always)] fn ge(&self, other: &Arc<T>) -> bool { *self.borrow() >= *other.borrow() } } struct MutexArcBox<T> { mutex: Mutex, value: T, no_freeze: marker::NoFreeze } pub struct MutexArc<T> { ptr: Arc<MutexArcBox<T>> } impl<T: Send> MutexArc<T> { pub fn new(value: T) -> MutexArc<T> { let b = MutexArcBox { mutex: Mutex::new(), value: value, no_freeze: marker::NoFreeze }; unsafe { MutexArc { ptr: Arc::new_unchecked(b) } } } pub fn swap(&self, value: T) -> T { unsafe { let ptr: &mut MutexArcBox<T> = transmute(self.ptr.borrow()); let _guard = ptr.mutex.lock_guard(); replace(&mut ptr.value, value) } } } impl<T> Clone for MutexArc<T> { #[inline(always)] fn clone(&self) -> MutexArc<T> { MutexArc { ptr: self.ptr.clone() } } }
lt
identifier_name
p104.rs
//! [Problem 104](https://projecteuler.net/problem=104) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use num_integer::Integer; fn is_pandigit(n: u64) -> bool { let mut hist = [false; 10]; let mut cnt = 0; let mut itr = n; while itr > 0 { let (d, r) = itr.div_rem(&10); if r == 0 || hist[r as usize] { return false; } hist[r as usize] = true; itr = d; cnt += 1; } cnt == 9 } struct FibFirst { base: u64, phi: f64, curr: u64, cnt: usize, } impl FibFirst { fn new(len: u32) -> FibFirst { assert!(len > 0); FibFirst { base: 10u64.pow(len), phi: (1.0 + (5.0f64).sqrt()) / 2.0, curr: 1, cnt: 1, } } } impl Iterator for FibFirst { type Item = u64; fn next(&mut self) -> Option<u64> {
let next = match self.cnt { 0 => 1, 1 => 1, 2 => 2, 3 => 3, 4 => 5, _ => { let mut f = ((self.curr as f64) * self.phi + 0.5) as u64; while f > self.base * self.base { f /= 10; } f } }; let mut curr = self.curr; self.curr = next; self.cnt += 1; while curr > self.base { curr /= 10; } Some(curr) } } struct FibLast { base: u64, curr: u64, next: u64, } impl FibLast { fn new(len: u32) -> FibLast { assert!(len > 0); FibLast { base: 10u64.pow(len), curr: 1, next: 1, } } } impl Iterator for FibLast { type Item = u64; fn next(&mut self) -> Option<u64> { let next = (self.curr + self.next) % self.base; let curr = self.curr; self.curr = self.next; self.next = next; Some(curr) } } fn solve() -> String { let len = 9; let first = FibFirst::new(len); let last = FibLast::new(len); let (k, _) = first .zip(last) .enumerate() .find(|&(_, (f, l))| is_pandigit(f) && is_pandigit(l)) .unwrap(); (k + 1).to_string() } common::problem!("329468", solve); #[cfg(test)] mod tests { use super::{FibFirst, FibLast}; use num_bigint::BigUint; use seq::Fibonacci; #[test] fn fib() { let len = 9; let it = Fibonacci::<BigUint>::new() .zip(FibFirst::new(len as u32).zip(FibLast::new(len as u32))); for (bu, (fst, lst)) in it.take(100) { let bus = bu.to_string(); if bus.len() < len { assert_eq!(bus, fst.to_string()); assert_eq!(bus, lst.to_string()); } else { assert_eq!(bus[..len].parse::<u64>().unwrap(), fst); assert_eq!(bus[bus.len() - len..].parse::<u64>().unwrap(), lst); } } } }
random_line_split
p104.rs
//! [Problem 104](https://projecteuler.net/problem=104) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use num_integer::Integer; fn is_pandigit(n: u64) -> bool { let mut hist = [false; 10]; let mut cnt = 0; let mut itr = n; while itr > 0 { let (d, r) = itr.div_rem(&10); if r == 0 || hist[r as usize] { return false; } hist[r as usize] = true; itr = d; cnt += 1; } cnt == 9 } struct FibFirst { base: u64, phi: f64, curr: u64, cnt: usize, } impl FibFirst { fn new(len: u32) -> FibFirst { assert!(len > 0); FibFirst { base: 10u64.pow(len), phi: (1.0 + (5.0f64).sqrt()) / 2.0, curr: 1, cnt: 1, } } } impl Iterator for FibFirst { type Item = u64; fn next(&mut self) -> Option<u64> { let next = match self.cnt { 0 => 1, 1 => 1, 2 => 2, 3 => 3, 4 => 5, _ => { let mut f = ((self.curr as f64) * self.phi + 0.5) as u64; while f > self.base * self.base { f /= 10; } f } }; let mut curr = self.curr; self.curr = next; self.cnt += 1; while curr > self.base { curr /= 10; } Some(curr) } } struct FibLast { base: u64, curr: u64, next: u64, } impl FibLast { fn new(len: u32) -> FibLast { assert!(len > 0); FibLast { base: 10u64.pow(len), curr: 1, next: 1, } } } impl Iterator for FibLast { type Item = u64; fn next(&mut self) -> Option<u64> { let next = (self.curr + self.next) % self.base; let curr = self.curr; self.curr = self.next; self.next = next; Some(curr) } } fn solve() -> String { let len = 9; let first = FibFirst::new(len); let last = FibLast::new(len); let (k, _) = first .zip(last) .enumerate() .find(|&(_, (f, l))| is_pandigit(f) && is_pandigit(l)) .unwrap(); (k + 1).to_string() } common::problem!("329468", solve); #[cfg(test)] mod tests { use super::{FibFirst, FibLast}; use num_bigint::BigUint; use seq::Fibonacci; #[test] fn fib() { let len = 9; let it = Fibonacci::<BigUint>::new() .zip(FibFirst::new(len as u32).zip(FibLast::new(len as u32))); for (bu, (fst, lst)) in it.take(100) { let bus = bu.to_string(); if bus.len() < len
else { assert_eq!(bus[..len].parse::<u64>().unwrap(), fst); assert_eq!(bus[bus.len() - len..].parse::<u64>().unwrap(), lst); } } } }
{ assert_eq!(bus, fst.to_string()); assert_eq!(bus, lst.to_string()); }
conditional_block
p104.rs
//! [Problem 104](https://projecteuler.net/problem=104) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use num_integer::Integer; fn is_pandigit(n: u64) -> bool { let mut hist = [false; 10]; let mut cnt = 0; let mut itr = n; while itr > 0 { let (d, r) = itr.div_rem(&10); if r == 0 || hist[r as usize] { return false; } hist[r as usize] = true; itr = d; cnt += 1; } cnt == 9 } struct
{ base: u64, phi: f64, curr: u64, cnt: usize, } impl FibFirst { fn new(len: u32) -> FibFirst { assert!(len > 0); FibFirst { base: 10u64.pow(len), phi: (1.0 + (5.0f64).sqrt()) / 2.0, curr: 1, cnt: 1, } } } impl Iterator for FibFirst { type Item = u64; fn next(&mut self) -> Option<u64> { let next = match self.cnt { 0 => 1, 1 => 1, 2 => 2, 3 => 3, 4 => 5, _ => { let mut f = ((self.curr as f64) * self.phi + 0.5) as u64; while f > self.base * self.base { f /= 10; } f } }; let mut curr = self.curr; self.curr = next; self.cnt += 1; while curr > self.base { curr /= 10; } Some(curr) } } struct FibLast { base: u64, curr: u64, next: u64, } impl FibLast { fn new(len: u32) -> FibLast { assert!(len > 0); FibLast { base: 10u64.pow(len), curr: 1, next: 1, } } } impl Iterator for FibLast { type Item = u64; fn next(&mut self) -> Option<u64> { let next = (self.curr + self.next) % self.base; let curr = self.curr; self.curr = self.next; self.next = next; Some(curr) } } fn solve() -> String { let len = 9; let first = FibFirst::new(len); let last = FibLast::new(len); let (k, _) = first .zip(last) .enumerate() .find(|&(_, (f, l))| is_pandigit(f) && is_pandigit(l)) .unwrap(); (k + 1).to_string() } common::problem!("329468", solve); #[cfg(test)] mod tests { use super::{FibFirst, FibLast}; use num_bigint::BigUint; use seq::Fibonacci; #[test] fn fib() { let len = 9; let it = Fibonacci::<BigUint>::new() .zip(FibFirst::new(len as u32).zip(FibLast::new(len as u32))); for (bu, (fst, lst)) in it.take(100) { let bus = bu.to_string(); if bus.len() < len { assert_eq!(bus, fst.to_string()); assert_eq!(bus, lst.to_string()); } else { assert_eq!(bus[..len].parse::<u64>().unwrap(), fst); assert_eq!(bus[bus.len() - len..].parse::<u64>().unwrap(), lst); } } } }
FibFirst
identifier_name
p104.rs
//! [Problem 104](https://projecteuler.net/problem=104) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use num_integer::Integer; fn is_pandigit(n: u64) -> bool { let mut hist = [false; 10]; let mut cnt = 0; let mut itr = n; while itr > 0 { let (d, r) = itr.div_rem(&10); if r == 0 || hist[r as usize] { return false; } hist[r as usize] = true; itr = d; cnt += 1; } cnt == 9 } struct FibFirst { base: u64, phi: f64, curr: u64, cnt: usize, } impl FibFirst { fn new(len: u32) -> FibFirst
} impl Iterator for FibFirst { type Item = u64; fn next(&mut self) -> Option<u64> { let next = match self.cnt { 0 => 1, 1 => 1, 2 => 2, 3 => 3, 4 => 5, _ => { let mut f = ((self.curr as f64) * self.phi + 0.5) as u64; while f > self.base * self.base { f /= 10; } f } }; let mut curr = self.curr; self.curr = next; self.cnt += 1; while curr > self.base { curr /= 10; } Some(curr) } } struct FibLast { base: u64, curr: u64, next: u64, } impl FibLast { fn new(len: u32) -> FibLast { assert!(len > 0); FibLast { base: 10u64.pow(len), curr: 1, next: 1, } } } impl Iterator for FibLast { type Item = u64; fn next(&mut self) -> Option<u64> { let next = (self.curr + self.next) % self.base; let curr = self.curr; self.curr = self.next; self.next = next; Some(curr) } } fn solve() -> String { let len = 9; let first = FibFirst::new(len); let last = FibLast::new(len); let (k, _) = first .zip(last) .enumerate() .find(|&(_, (f, l))| is_pandigit(f) && is_pandigit(l)) .unwrap(); (k + 1).to_string() } common::problem!("329468", solve); #[cfg(test)] mod tests { use super::{FibFirst, FibLast}; use num_bigint::BigUint; use seq::Fibonacci; #[test] fn fib() { let len = 9; let it = Fibonacci::<BigUint>::new() .zip(FibFirst::new(len as u32).zip(FibLast::new(len as u32))); for (bu, (fst, lst)) in it.take(100) { let bus = bu.to_string(); if bus.len() < len { assert_eq!(bus, fst.to_string()); assert_eq!(bus, lst.to_string()); } else { assert_eq!(bus[..len].parse::<u64>().unwrap(), fst); assert_eq!(bus[bus.len() - len..].parse::<u64>().unwrap(), lst); } } } }
{ assert!(len > 0); FibFirst { base: 10u64.pow(len), phi: (1.0 + (5.0f64).sqrt()) / 2.0, curr: 1, cnt: 1, } }
identifier_body
imports_granularity_crate.rs
// rustfmt-imports_granularity: Crate use a::{c,d,b}; use a::{d, e, b, a, f}; use a::{f, g, c}; #[doc(hidden)]
use a::d; use a::{c, d, e}; #[doc(hidden)] use a::b; use a::d; pub use foo::bar; use foo::{a, b, c}; pub use foo::foobar; use a::{b::{c::*}}; use a::{b::{c::{}}}; use a::{b::{c::d}}; use a::{b::{c::{xxx, yyy, zzz}}}; // https://github.com/rust-lang/rustfmt/issues/3808 use d::{self}; use e::{self as foo}; use f::{self, b}; use g::a; use g::{self, b}; use h::{a}; use i::a::{self}; use j::{a::{self}}; use {k::{a, b}, l::{a, b}}; use {k::{c, d}, l::{c, d}};
use a::b; use a::c;
random_line_split
protocol.rs
pub enum Token { Symbol(String), Ident(String), Lifetime(String), String(String), ByteString(Vec<u8>), Char(char), Unsigned(u128, u8), Signed(i128, u8), Float(f64, u8), } pub struct Reader<R> { inner: R, } impl<R: ::std::io::Read> Reader<R> { pub fn new(r: R) -> Reader<R> { Reader { inner: r, } } } impl<R: ::std::io::Read> Reader<R> { pub fn read_ent(&mut self) -> Option<Token> { let hdr_b = match self.getb() { Some(b) => b, None => return None, }; // TODO: leading span Some(match hdr_b { 0 => Token::Symbol(self.get_string()), 1 => Token::Ident(self.get_string()), 2 => Token::Lifetime(self.get_string()), 3 => Token::String(self.get_string()), 4 => Token::ByteString(self.get_byte_vec()), 5 => Token::Char(::std::char::from_u32(self.get_i128v() as u32).expect("char lit")), 6 => { let ty = self.getb().expect("getb int ty"); let val = self.get_u128v(); Token::Unsigned(val, ty) }, 7 => { let ty = self.getb().expect("getb int ty"); let val = self.get_i128v(); Token::Signed(val, ty) }, 8 => { let ty = self.getb().expect("getb int ty"); let val = self.get_f64(); Token::Float(val, ty) }, _ => panic!("Unknown tag byte: {:#x}", hdr_b), }) } fn getb(&mut self) -> Option<u8> { let mut b = [0]; match self.inner.read(&mut b) { Ok(1) => Some(b[0]), Ok(0) => None, Ok(_) => panic!("Bad byte count"), Err(e) => panic!("Error reading from stdin - {}", e), } } fn get_u128v(&mut self) -> u128 { let mut ofs = 0; let mut raw_rv = 0u128; loop { let b = self.getb().unwrap(); raw_rv |= ((b & 0x7F) as u128) << ofs; if b < 128 { break; } assert!(ofs < 18*7); // at most 18 bytes needed for a i128 ofs += 7; } raw_rv } fn get_i128v(&mut self) -> i128 { let raw_rv = self.get_u128v(); // Zig-zag encoding (0 = 0, 1 = -1, 2 = 1,...) if raw_rv & 1!= 0 { -( (raw_rv >> 1) as i128 + 1 ) } else { (raw_rv >> 1) as i128 } } fn get_byte_vec(&mut self) -> Vec<u8> { let size = self.get_u128v(); assert!(size < (1<<30)); let size = size as usize; let mut buf = vec![0u8; size]; match self.inner.read_exact(&mut buf) { Ok(_) => {}, Err(e) => panic!("Error reading from stdin get_byte_vec({}) - {}", size, e), } buf } fn get_string(&mut self) -> String { let raw = self.get_byte_vec(); String::from_utf8(raw).expect("Invalid UTF-8 passed from compiler") } fn get_f64(&mut self) -> f64 { let mut buf = [0u8; 8]; match self.inner.read_exact(&mut buf) { Ok(_) => {}, Err(e) => panic!("Error reading from stdin - {}", e), } unsafe { ::std::mem::transmute(buf) } }
} impl<T: ::std::io::Write> Writer<T> { pub fn new(w: T) -> Writer<T> { Writer { inner: w, } } pub fn write_ent(&mut self, t: Token) { match t { Token::Symbol(v) => { self.putb(0); self.put_bytes(v.as_bytes()); }, Token::Ident(v) => { self.putb(1); self.put_bytes(v.as_bytes()); }, Token::Lifetime(v) => { self.putb(2); self.put_bytes(v.as_bytes()); }, Token::String(v) => { self.putb(3); self.put_bytes(v.as_bytes()); }, Token::ByteString(v) => { self.putb(4); self.put_bytes(&v[..]); }, Token::Char(v) => { self.putb(5); self.put_u128v(v as u32 as u128); }, Token::Unsigned(v, sz) => { self.putb(6); self.putb(sz); self.put_u128v(v); }, Token::Signed(v, sz) => { self.putb(7); self.putb(sz); self.put_i128v(v); }, Token::Float(v, sz) => { self.putb(8); self.putb(sz); self.put_f64(v); }, } } pub fn write_sym(&mut self, v: &[u8]) { self.putb(0); // "Symbol" self.put_bytes(v); } pub fn write_sym_1(&mut self, ch: char) { self.putb(0); // "Symbol" self.putb(1); // Length self.putb(ch as u8); } fn putb(&mut self, v: u8) { let buf = [v]; self.inner.write(&buf).expect(""); } fn put_u128v(&mut self, mut v: u128) { while v >= 128 { self.putb( (v & 0x7F) as u8 | 0x80 ); v >>= 7; } self.putb( (v & 0x7F) as u8 ); } fn put_i128v(&mut self, v: i128) { if v < 0 { self.put_u128v( (((v + 1) as u128) << 1) | 1 ); } else { self.put_u128v( (v as u128) << 1 ); } } fn put_bytes(&mut self, v: &[u8]) { self.put_u128v(v.len() as u128); self.inner.write(v).expect(""); } fn put_f64(&mut self, v: f64) { let buf: [u8; 8] = unsafe { ::std::mem::transmute(v) }; self.inner.write(&buf).expect(""); } }
} pub struct Writer<T> { inner: T,
random_line_split
protocol.rs
pub enum Token { Symbol(String), Ident(String), Lifetime(String), String(String), ByteString(Vec<u8>), Char(char), Unsigned(u128, u8), Signed(i128, u8), Float(f64, u8), } pub struct Reader<R> { inner: R, } impl<R: ::std::io::Read> Reader<R> { pub fn new(r: R) -> Reader<R> { Reader { inner: r, } } } impl<R: ::std::io::Read> Reader<R> { pub fn read_ent(&mut self) -> Option<Token> { let hdr_b = match self.getb() { Some(b) => b, None => return None, }; // TODO: leading span Some(match hdr_b { 0 => Token::Symbol(self.get_string()), 1 => Token::Ident(self.get_string()), 2 => Token::Lifetime(self.get_string()), 3 => Token::String(self.get_string()), 4 => Token::ByteString(self.get_byte_vec()), 5 => Token::Char(::std::char::from_u32(self.get_i128v() as u32).expect("char lit")), 6 => { let ty = self.getb().expect("getb int ty"); let val = self.get_u128v(); Token::Unsigned(val, ty) }, 7 => { let ty = self.getb().expect("getb int ty"); let val = self.get_i128v(); Token::Signed(val, ty) }, 8 => { let ty = self.getb().expect("getb int ty"); let val = self.get_f64(); Token::Float(val, ty) }, _ => panic!("Unknown tag byte: {:#x}", hdr_b), }) } fn getb(&mut self) -> Option<u8> { let mut b = [0]; match self.inner.read(&mut b) { Ok(1) => Some(b[0]), Ok(0) => None, Ok(_) => panic!("Bad byte count"), Err(e) => panic!("Error reading from stdin - {}", e), } } fn get_u128v(&mut self) -> u128 { let mut ofs = 0; let mut raw_rv = 0u128; loop { let b = self.getb().unwrap(); raw_rv |= ((b & 0x7F) as u128) << ofs; if b < 128 { break; } assert!(ofs < 18*7); // at most 18 bytes needed for a i128 ofs += 7; } raw_rv } fn get_i128v(&mut self) -> i128 { let raw_rv = self.get_u128v(); // Zig-zag encoding (0 = 0, 1 = -1, 2 = 1,...) if raw_rv & 1!= 0 { -( (raw_rv >> 1) as i128 + 1 ) } else { (raw_rv >> 1) as i128 } } fn get_byte_vec(&mut self) -> Vec<u8> { let size = self.get_u128v(); assert!(size < (1<<30)); let size = size as usize; let mut buf = vec![0u8; size]; match self.inner.read_exact(&mut buf) { Ok(_) => {}, Err(e) => panic!("Error reading from stdin get_byte_vec({}) - {}", size, e), } buf } fn get_string(&mut self) -> String { let raw = self.get_byte_vec(); String::from_utf8(raw).expect("Invalid UTF-8 passed from compiler") } fn get_f64(&mut self) -> f64 { let mut buf = [0u8; 8]; match self.inner.read_exact(&mut buf) { Ok(_) => {}, Err(e) => panic!("Error reading from stdin - {}", e), } unsafe { ::std::mem::transmute(buf) } } } pub struct Writer<T> { inner: T, } impl<T: ::std::io::Write> Writer<T> { pub fn new(w: T) -> Writer<T> { Writer { inner: w, } } pub fn write_ent(&mut self, t: Token) { match t { Token::Symbol(v) => { self.putb(0); self.put_bytes(v.as_bytes()); }, Token::Ident(v) => { self.putb(1); self.put_bytes(v.as_bytes()); }, Token::Lifetime(v) => { self.putb(2); self.put_bytes(v.as_bytes()); }, Token::String(v) => { self.putb(3); self.put_bytes(v.as_bytes()); }, Token::ByteString(v) => { self.putb(4); self.put_bytes(&v[..]); }, Token::Char(v) => { self.putb(5); self.put_u128v(v as u32 as u128); }, Token::Unsigned(v, sz) => { self.putb(6); self.putb(sz); self.put_u128v(v); }, Token::Signed(v, sz) => { self.putb(7); self.putb(sz); self.put_i128v(v); }, Token::Float(v, sz) => { self.putb(8); self.putb(sz); self.put_f64(v); }, } } pub fn write_sym(&mut self, v: &[u8]) { self.putb(0); // "Symbol" self.put_bytes(v); } pub fn write_sym_1(&mut self, ch: char) { self.putb(0); // "Symbol" self.putb(1); // Length self.putb(ch as u8); } fn putb(&mut self, v: u8) { let buf = [v]; self.inner.write(&buf).expect(""); } fn
(&mut self, mut v: u128) { while v >= 128 { self.putb( (v & 0x7F) as u8 | 0x80 ); v >>= 7; } self.putb( (v & 0x7F) as u8 ); } fn put_i128v(&mut self, v: i128) { if v < 0 { self.put_u128v( (((v + 1) as u128) << 1) | 1 ); } else { self.put_u128v( (v as u128) << 1 ); } } fn put_bytes(&mut self, v: &[u8]) { self.put_u128v(v.len() as u128); self.inner.write(v).expect(""); } fn put_f64(&mut self, v: f64) { let buf: [u8; 8] = unsafe { ::std::mem::transmute(v) }; self.inner.write(&buf).expect(""); } }
put_u128v
identifier_name
protocol.rs
pub enum Token { Symbol(String), Ident(String), Lifetime(String), String(String), ByteString(Vec<u8>), Char(char), Unsigned(u128, u8), Signed(i128, u8), Float(f64, u8), } pub struct Reader<R> { inner: R, } impl<R: ::std::io::Read> Reader<R> { pub fn new(r: R) -> Reader<R> { Reader { inner: r, } } } impl<R: ::std::io::Read> Reader<R> { pub fn read_ent(&mut self) -> Option<Token> { let hdr_b = match self.getb() { Some(b) => b, None => return None, }; // TODO: leading span Some(match hdr_b { 0 => Token::Symbol(self.get_string()), 1 => Token::Ident(self.get_string()), 2 => Token::Lifetime(self.get_string()), 3 => Token::String(self.get_string()), 4 => Token::ByteString(self.get_byte_vec()), 5 => Token::Char(::std::char::from_u32(self.get_i128v() as u32).expect("char lit")), 6 => { let ty = self.getb().expect("getb int ty"); let val = self.get_u128v(); Token::Unsigned(val, ty) }, 7 => { let ty = self.getb().expect("getb int ty"); let val = self.get_i128v(); Token::Signed(val, ty) }, 8 => { let ty = self.getb().expect("getb int ty"); let val = self.get_f64(); Token::Float(val, ty) }, _ => panic!("Unknown tag byte: {:#x}", hdr_b), }) } fn getb(&mut self) -> Option<u8> { let mut b = [0]; match self.inner.read(&mut b) { Ok(1) => Some(b[0]), Ok(0) => None, Ok(_) => panic!("Bad byte count"), Err(e) => panic!("Error reading from stdin - {}", e), } } fn get_u128v(&mut self) -> u128 { let mut ofs = 0; let mut raw_rv = 0u128; loop { let b = self.getb().unwrap(); raw_rv |= ((b & 0x7F) as u128) << ofs; if b < 128 { break; } assert!(ofs < 18*7); // at most 18 bytes needed for a i128 ofs += 7; } raw_rv } fn get_i128v(&mut self) -> i128 { let raw_rv = self.get_u128v(); // Zig-zag encoding (0 = 0, 1 = -1, 2 = 1,...) if raw_rv & 1!= 0 { -( (raw_rv >> 1) as i128 + 1 ) } else { (raw_rv >> 1) as i128 } } fn get_byte_vec(&mut self) -> Vec<u8> { let size = self.get_u128v(); assert!(size < (1<<30)); let size = size as usize; let mut buf = vec![0u8; size]; match self.inner.read_exact(&mut buf) { Ok(_) => {}, Err(e) => panic!("Error reading from stdin get_byte_vec({}) - {}", size, e), } buf } fn get_string(&mut self) -> String { let raw = self.get_byte_vec(); String::from_utf8(raw).expect("Invalid UTF-8 passed from compiler") } fn get_f64(&mut self) -> f64 { let mut buf = [0u8; 8]; match self.inner.read_exact(&mut buf) { Ok(_) => {}, Err(e) => panic!("Error reading from stdin - {}", e), } unsafe { ::std::mem::transmute(buf) } } } pub struct Writer<T> { inner: T, } impl<T: ::std::io::Write> Writer<T> { pub fn new(w: T) -> Writer<T> { Writer { inner: w, } } pub fn write_ent(&mut self, t: Token) { match t { Token::Symbol(v) => { self.putb(0); self.put_bytes(v.as_bytes()); }, Token::Ident(v) => { self.putb(1); self.put_bytes(v.as_bytes()); }, Token::Lifetime(v) => { self.putb(2); self.put_bytes(v.as_bytes()); }, Token::String(v) => { self.putb(3); self.put_bytes(v.as_bytes()); }, Token::ByteString(v) => { self.putb(4); self.put_bytes(&v[..]); }, Token::Char(v) => { self.putb(5); self.put_u128v(v as u32 as u128); }, Token::Unsigned(v, sz) => { self.putb(6); self.putb(sz); self.put_u128v(v); }, Token::Signed(v, sz) => { self.putb(7); self.putb(sz); self.put_i128v(v); }, Token::Float(v, sz) => { self.putb(8); self.putb(sz); self.put_f64(v); }, } } pub fn write_sym(&mut self, v: &[u8]) { self.putb(0); // "Symbol" self.put_bytes(v); } pub fn write_sym_1(&mut self, ch: char) { self.putb(0); // "Symbol" self.putb(1); // Length self.putb(ch as u8); } fn putb(&mut self, v: u8)
fn put_u128v(&mut self, mut v: u128) { while v >= 128 { self.putb( (v & 0x7F) as u8 | 0x80 ); v >>= 7; } self.putb( (v & 0x7F) as u8 ); } fn put_i128v(&mut self, v: i128) { if v < 0 { self.put_u128v( (((v + 1) as u128) << 1) | 1 ); } else { self.put_u128v( (v as u128) << 1 ); } } fn put_bytes(&mut self, v: &[u8]) { self.put_u128v(v.len() as u128); self.inner.write(v).expect(""); } fn put_f64(&mut self, v: f64) { let buf: [u8; 8] = unsafe { ::std::mem::transmute(v) }; self.inner.write(&buf).expect(""); } }
{ let buf = [v]; self.inner.write(&buf).expect(""); }
identifier_body
protocol.rs
pub enum Token { Symbol(String), Ident(String), Lifetime(String), String(String), ByteString(Vec<u8>), Char(char), Unsigned(u128, u8), Signed(i128, u8), Float(f64, u8), } pub struct Reader<R> { inner: R, } impl<R: ::std::io::Read> Reader<R> { pub fn new(r: R) -> Reader<R> { Reader { inner: r, } } } impl<R: ::std::io::Read> Reader<R> { pub fn read_ent(&mut self) -> Option<Token> { let hdr_b = match self.getb() { Some(b) => b, None => return None, }; // TODO: leading span Some(match hdr_b { 0 => Token::Symbol(self.get_string()), 1 => Token::Ident(self.get_string()), 2 => Token::Lifetime(self.get_string()), 3 => Token::String(self.get_string()), 4 => Token::ByteString(self.get_byte_vec()), 5 => Token::Char(::std::char::from_u32(self.get_i128v() as u32).expect("char lit")), 6 => { let ty = self.getb().expect("getb int ty"); let val = self.get_u128v(); Token::Unsigned(val, ty) }, 7 => { let ty = self.getb().expect("getb int ty"); let val = self.get_i128v(); Token::Signed(val, ty) }, 8 => { let ty = self.getb().expect("getb int ty"); let val = self.get_f64(); Token::Float(val, ty) }, _ => panic!("Unknown tag byte: {:#x}", hdr_b), }) } fn getb(&mut self) -> Option<u8> { let mut b = [0]; match self.inner.read(&mut b) { Ok(1) => Some(b[0]), Ok(0) => None, Ok(_) => panic!("Bad byte count"), Err(e) => panic!("Error reading from stdin - {}", e), } } fn get_u128v(&mut self) -> u128 { let mut ofs = 0; let mut raw_rv = 0u128; loop { let b = self.getb().unwrap(); raw_rv |= ((b & 0x7F) as u128) << ofs; if b < 128 { break; } assert!(ofs < 18*7); // at most 18 bytes needed for a i128 ofs += 7; } raw_rv } fn get_i128v(&mut self) -> i128 { let raw_rv = self.get_u128v(); // Zig-zag encoding (0 = 0, 1 = -1, 2 = 1,...) if raw_rv & 1!= 0 { -( (raw_rv >> 1) as i128 + 1 ) } else { (raw_rv >> 1) as i128 } } fn get_byte_vec(&mut self) -> Vec<u8> { let size = self.get_u128v(); assert!(size < (1<<30)); let size = size as usize; let mut buf = vec![0u8; size]; match self.inner.read_exact(&mut buf) { Ok(_) => {}, Err(e) => panic!("Error reading from stdin get_byte_vec({}) - {}", size, e), } buf } fn get_string(&mut self) -> String { let raw = self.get_byte_vec(); String::from_utf8(raw).expect("Invalid UTF-8 passed from compiler") } fn get_f64(&mut self) -> f64 { let mut buf = [0u8; 8]; match self.inner.read_exact(&mut buf) { Ok(_) => {}, Err(e) => panic!("Error reading from stdin - {}", e), } unsafe { ::std::mem::transmute(buf) } } } pub struct Writer<T> { inner: T, } impl<T: ::std::io::Write> Writer<T> { pub fn new(w: T) -> Writer<T> { Writer { inner: w, } } pub fn write_ent(&mut self, t: Token) { match t { Token::Symbol(v) => { self.putb(0); self.put_bytes(v.as_bytes()); }, Token::Ident(v) => { self.putb(1); self.put_bytes(v.as_bytes()); }, Token::Lifetime(v) =>
, Token::String(v) => { self.putb(3); self.put_bytes(v.as_bytes()); }, Token::ByteString(v) => { self.putb(4); self.put_bytes(&v[..]); }, Token::Char(v) => { self.putb(5); self.put_u128v(v as u32 as u128); }, Token::Unsigned(v, sz) => { self.putb(6); self.putb(sz); self.put_u128v(v); }, Token::Signed(v, sz) => { self.putb(7); self.putb(sz); self.put_i128v(v); }, Token::Float(v, sz) => { self.putb(8); self.putb(sz); self.put_f64(v); }, } } pub fn write_sym(&mut self, v: &[u8]) { self.putb(0); // "Symbol" self.put_bytes(v); } pub fn write_sym_1(&mut self, ch: char) { self.putb(0); // "Symbol" self.putb(1); // Length self.putb(ch as u8); } fn putb(&mut self, v: u8) { let buf = [v]; self.inner.write(&buf).expect(""); } fn put_u128v(&mut self, mut v: u128) { while v >= 128 { self.putb( (v & 0x7F) as u8 | 0x80 ); v >>= 7; } self.putb( (v & 0x7F) as u8 ); } fn put_i128v(&mut self, v: i128) { if v < 0 { self.put_u128v( (((v + 1) as u128) << 1) | 1 ); } else { self.put_u128v( (v as u128) << 1 ); } } fn put_bytes(&mut self, v: &[u8]) { self.put_u128v(v.len() as u128); self.inner.write(v).expect(""); } fn put_f64(&mut self, v: f64) { let buf: [u8; 8] = unsafe { ::std::mem::transmute(v) }; self.inner.write(&buf).expect(""); } }
{ self.putb(2); self.put_bytes(v.as_bytes()); }
conditional_block
sprite.rs
// Copyright 2013-2014 Jeffery Olson // // Licensed under the 3-Clause BSD License, see LICENSE.txt // at the top-level of this repository. // This file may not be copied, modified, or distributed // except according to those terms. #[deriving(Clone, Encodable, Decodable)] pub struct SpriteSheet { pub path: String, pub name: String } #[deriving(Encodable, Decodable)] pub struct SpriteTile { pub sheet: String, pub coords: (uint, uint), pub size: (uint, uint) } impl Clone for SpriteTile { fn clone(&self) -> SpriteTile { SpriteTile { sheet: self.sheet.clone(), coords: (self.coords), size: (self.size) } } } impl SpriteTile { pub fn
() -> SpriteTile { SpriteTile { sheet: "".to_string(), coords: (0,0), size:(0,0) } } }
stub
identifier_name
sprite.rs
// Copyright 2013-2014 Jeffery Olson // // Licensed under the 3-Clause BSD License, see LICENSE.txt // at the top-level of this repository. // This file may not be copied, modified, or distributed // except according to those terms. #[deriving(Clone, Encodable, Decodable)] pub struct SpriteSheet { pub path: String, pub name: String } #[deriving(Encodable, Decodable)] pub struct SpriteTile { pub sheet: String, pub coords: (uint, uint), pub size: (uint, uint) } impl Clone for SpriteTile { fn clone(&self) -> SpriteTile
} impl SpriteTile { pub fn stub() -> SpriteTile { SpriteTile { sheet: "".to_string(), coords: (0,0), size:(0,0) } } }
{ SpriteTile { sheet: self.sheet.clone(), coords: (self.coords), size: (self.size) } }
identifier_body
sprite.rs
// Copyright 2013-2014 Jeffery Olson // // Licensed under the 3-Clause BSD License, see LICENSE.txt // at the top-level of this repository. // This file may not be copied, modified, or distributed // except according to those terms.
} #[deriving(Encodable, Decodable)] pub struct SpriteTile { pub sheet: String, pub coords: (uint, uint), pub size: (uint, uint) } impl Clone for SpriteTile { fn clone(&self) -> SpriteTile { SpriteTile { sheet: self.sheet.clone(), coords: (self.coords), size: (self.size) } } } impl SpriteTile { pub fn stub() -> SpriteTile { SpriteTile { sheet: "".to_string(), coords: (0,0), size:(0,0) } } }
#[deriving(Clone, Encodable, Decodable)] pub struct SpriteSheet { pub path: String, pub name: String
random_line_split
path.rs
use std::io::fs::PathExtensions; fn main()
} // `stat` returns an IoResult<FileStat> === Result<FileStat, IoError> let stat = match path.stat() { Err(why) => fail!("{}", why.desc), Ok(stat) => stat, }; println!("{} size is {} bytes", display, stat.size); // `join` merges a path with a byte container using the OS specific // separator, and returns the new path let new_path = path.join("a").join("b"); // Convert the path into a string slice match new_path.as_str() { None => fail!("new path is not a valid UTF-8 sequence"), Some(s) => println!("new path is {}", s), } }
{ // Create a `Path` from an `&'static str` let path = Path::new("."); // The `display` method returns a `Show`able structure let display = path.display(); // Check if the path exists if path.exists() { println!("{} exists", display); } // Check if the path is a file if path.is_file() { println!("{} is a file", display); } // Check if the path is a directory if path.is_dir() { println!("{} is a directory", display);
identifier_body
path.rs
use std::io::fs::PathExtensions; fn main() { // Create a `Path` from an `&'static str` let path = Path::new("."); // The `display` method returns a `Show`able structure let display = path.display(); // Check if the path exists if path.exists() { println!("{} exists", display); } // Check if the path is a file if path.is_file() { println!("{} is a file", display); }
} // `stat` returns an IoResult<FileStat> === Result<FileStat, IoError> let stat = match path.stat() { Err(why) => fail!("{}", why.desc), Ok(stat) => stat, }; println!("{} size is {} bytes", display, stat.size); // `join` merges a path with a byte container using the OS specific // separator, and returns the new path let new_path = path.join("a").join("b"); // Convert the path into a string slice match new_path.as_str() { None => fail!("new path is not a valid UTF-8 sequence"), Some(s) => println!("new path is {}", s), } }
// Check if the path is a directory if path.is_dir() { println!("{} is a directory", display);
random_line_split
path.rs
use std::io::fs::PathExtensions; fn
() { // Create a `Path` from an `&'static str` let path = Path::new("."); // The `display` method returns a `Show`able structure let display = path.display(); // Check if the path exists if path.exists() { println!("{} exists", display); } // Check if the path is a file if path.is_file() { println!("{} is a file", display); } // Check if the path is a directory if path.is_dir() { println!("{} is a directory", display); } // `stat` returns an IoResult<FileStat> === Result<FileStat, IoError> let stat = match path.stat() { Err(why) => fail!("{}", why.desc), Ok(stat) => stat, }; println!("{} size is {} bytes", display, stat.size); // `join` merges a path with a byte container using the OS specific // separator, and returns the new path let new_path = path.join("a").join("b"); // Convert the path into a string slice match new_path.as_str() { None => fail!("new path is not a valid UTF-8 sequence"), Some(s) => println!("new path is {}", s), } }
main
identifier_name
x86_64_unknown_freebsd.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 target::Target; pub fn target() -> Target {
Target { data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\ f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\ s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(), llvm_target: "x86_64-unknown-freebsd".to_string(), target_endian: "little".to_string(), target_pointer_width: "64".to_string(), arch: "x86_64".to_string(), target_os: "freebsd".to_string(), options: base, } }
let mut base = super::freebsd_base::opts(); base.pre_link_args.push("-m64".to_string());
random_line_split
x86_64_unknown_freebsd.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 target::Target; pub fn
() -> Target { let mut base = super::freebsd_base::opts(); base.pre_link_args.push("-m64".to_string()); Target { data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\ f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\ s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(), llvm_target: "x86_64-unknown-freebsd".to_string(), target_endian: "little".to_string(), target_pointer_width: "64".to_string(), arch: "x86_64".to_string(), target_os: "freebsd".to_string(), options: base, } }
target
identifier_name
x86_64_unknown_freebsd.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 target::Target; pub fn target() -> Target
{ let mut base = super::freebsd_base::opts(); base.pre_link_args.push("-m64".to_string()); Target { data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\ f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\ s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(), llvm_target: "x86_64-unknown-freebsd".to_string(), target_endian: "little".to_string(), target_pointer_width: "64".to_string(), arch: "x86_64".to_string(), target_os: "freebsd".to_string(), options: base, } }
identifier_body
vcs.rs
use std::path::Path; use git2; use util::{CargoResult, process}; pub struct
; pub struct GitRepo; impl GitRepo { pub fn init(path: &Path, _: &Path) -> CargoResult<GitRepo> { git2::Repository::init(path)?; Ok(GitRepo) } pub fn discover(path: &Path, _: &Path) -> Result<git2::Repository,git2::Error> { git2::Repository::discover(path) } } impl HgRepo { pub fn init(path: &Path, cwd: &Path) -> CargoResult<HgRepo> { process("hg").cwd(cwd).arg("init").arg(path).exec()?; Ok(HgRepo) } pub fn discover(path: &Path, cwd: &Path) -> CargoResult<HgRepo> { process("hg").cwd(cwd).arg("root").cwd(path).exec_with_output()?; Ok(HgRepo) } }
HgRepo
identifier_name
vcs.rs
use std::path::Path; use git2; use util::{CargoResult, process}; pub struct HgRepo; pub struct GitRepo; impl GitRepo { pub fn init(path: &Path, _: &Path) -> CargoResult<GitRepo> { git2::Repository::init(path)?; Ok(GitRepo) } pub fn discover(path: &Path, _: &Path) -> Result<git2::Repository,git2::Error> { git2::Repository::discover(path) } } impl HgRepo { pub fn init(path: &Path, cwd: &Path) -> CargoResult<HgRepo> { process("hg").cwd(cwd).arg("init").arg(path).exec()?; Ok(HgRepo)
}
} pub fn discover(path: &Path, cwd: &Path) -> CargoResult<HgRepo> { process("hg").cwd(cwd).arg("root").cwd(path).exec_with_output()?; Ok(HgRepo) }
random_line_split
channel.rs
extern crate futures; use std::sync::atomic::*; use futures::{Future, Stream, Sink}; use futures::future::result; use futures::sync::mpsc; mod support; use support::*; #[test] fn
() { let (tx, mut rx) = mpsc::channel(1); sassert_empty(&mut rx); sassert_empty(&mut rx); let amt = 20; send(amt, tx).forget(); let mut rx = rx.wait(); for i in (1..amt + 1).rev() { assert_eq!(rx.next(), Some(Ok(i))); } assert_eq!(rx.next(), None); fn send(n: u32, sender: mpsc::Sender<u32>) -> Box<Future<Item=(), Error=()> + Send> { if n == 0 { return result(Ok(())).boxed() } sender.send(n).map_err(|_| ()).and_then(move |sender| { send(n - 1, sender) }).boxed() } } #[test] fn drop_sender() { let (tx, mut rx) = mpsc::channel::<u32>(1); drop(tx); sassert_done(&mut rx); } #[test] fn drop_rx() { let (tx, rx) = mpsc::channel::<u32>(1); let tx = tx.send(1).wait().ok().unwrap(); drop(rx); assert!(tx.send(1).wait().is_err()); } #[test] fn drop_order() { static DROPS: AtomicUsize = ATOMIC_USIZE_INIT; let (tx, rx) = mpsc::channel(1); struct A; impl Drop for A { fn drop(&mut self) { DROPS.fetch_add(1, Ordering::SeqCst); } } let tx = tx.send(A).wait().unwrap(); assert_eq!(DROPS.load(Ordering::SeqCst), 0); drop(rx); assert_eq!(DROPS.load(Ordering::SeqCst), 1); assert!(tx.send(A).wait().is_err()); assert_eq!(DROPS.load(Ordering::SeqCst), 2); }
sequence
identifier_name
channel.rs
extern crate futures; use std::sync::atomic::*; use futures::{Future, Stream, Sink}; use futures::future::result; use futures::sync::mpsc; mod support; use support::*; #[test] fn sequence() { let (tx, mut rx) = mpsc::channel(1); sassert_empty(&mut rx); sassert_empty(&mut rx); let amt = 20; send(amt, tx).forget(); let mut rx = rx.wait(); for i in (1..amt + 1).rev() { assert_eq!(rx.next(), Some(Ok(i))); } assert_eq!(rx.next(), None); fn send(n: u32, sender: mpsc::Sender<u32>) -> Box<Future<Item=(), Error=()> + Send> { if n == 0
sender.send(n).map_err(|_| ()).and_then(move |sender| { send(n - 1, sender) }).boxed() } } #[test] fn drop_sender() { let (tx, mut rx) = mpsc::channel::<u32>(1); drop(tx); sassert_done(&mut rx); } #[test] fn drop_rx() { let (tx, rx) = mpsc::channel::<u32>(1); let tx = tx.send(1).wait().ok().unwrap(); drop(rx); assert!(tx.send(1).wait().is_err()); } #[test] fn drop_order() { static DROPS: AtomicUsize = ATOMIC_USIZE_INIT; let (tx, rx) = mpsc::channel(1); struct A; impl Drop for A { fn drop(&mut self) { DROPS.fetch_add(1, Ordering::SeqCst); } } let tx = tx.send(A).wait().unwrap(); assert_eq!(DROPS.load(Ordering::SeqCst), 0); drop(rx); assert_eq!(DROPS.load(Ordering::SeqCst), 1); assert!(tx.send(A).wait().is_err()); assert_eq!(DROPS.load(Ordering::SeqCst), 2); }
{ return result(Ok(())).boxed() }
conditional_block
channel.rs
use std::sync::atomic::*; use futures::{Future, Stream, Sink}; use futures::future::result; use futures::sync::mpsc; mod support; use support::*; #[test] fn sequence() { let (tx, mut rx) = mpsc::channel(1); sassert_empty(&mut rx); sassert_empty(&mut rx); let amt = 20; send(amt, tx).forget(); let mut rx = rx.wait(); for i in (1..amt + 1).rev() { assert_eq!(rx.next(), Some(Ok(i))); } assert_eq!(rx.next(), None); fn send(n: u32, sender: mpsc::Sender<u32>) -> Box<Future<Item=(), Error=()> + Send> { if n == 0 { return result(Ok(())).boxed() } sender.send(n).map_err(|_| ()).and_then(move |sender| { send(n - 1, sender) }).boxed() } } #[test] fn drop_sender() { let (tx, mut rx) = mpsc::channel::<u32>(1); drop(tx); sassert_done(&mut rx); } #[test] fn drop_rx() { let (tx, rx) = mpsc::channel::<u32>(1); let tx = tx.send(1).wait().ok().unwrap(); drop(rx); assert!(tx.send(1).wait().is_err()); } #[test] fn drop_order() { static DROPS: AtomicUsize = ATOMIC_USIZE_INIT; let (tx, rx) = mpsc::channel(1); struct A; impl Drop for A { fn drop(&mut self) { DROPS.fetch_add(1, Ordering::SeqCst); } } let tx = tx.send(A).wait().unwrap(); assert_eq!(DROPS.load(Ordering::SeqCst), 0); drop(rx); assert_eq!(DROPS.load(Ordering::SeqCst), 1); assert!(tx.send(A).wait().is_err()); assert_eq!(DROPS.load(Ordering::SeqCst), 2); }
extern crate futures;
random_line_split
file_reading.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::domexception::DOMErrorName; use crate::dom::filereader::{FileReader, GenerationId, ReadMetaData, TrustedFileReader}; use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptThreadEventCategory}; use crate::task::{TaskCanceller, TaskOnce}; use crate::task_source::{TaskSource, TaskSourceName}; use msg::constellation_msg::PipelineId; #[derive(JSTraceable)] pub struct FileReadingTaskSource(pub Box<dyn ScriptChan + Send +'static>, pub PipelineId); impl Clone for FileReadingTaskSource { fn clone(&self) -> FileReadingTaskSource { FileReadingTaskSource(self.0.clone(), self.1.clone()) } } impl TaskSource for FileReadingTaskSource { const NAME: TaskSourceName = TaskSourceName::FileReading; fn queue_with_canceller<T>(&self, task: T, canceller: &TaskCanceller) -> Result<(), ()> where T: TaskOnce +'static, { self.0.send(CommonScriptMsg::Task( ScriptThreadEventCategory::FileRead, Box::new(canceller.wrap_task(task)), Some(self.1), FileReadingTaskSource::NAME, )) } } impl TaskOnce for FileReadingTask { fn run_once(self) { self.handle_task(); } } #[allow(dead_code)] pub enum FileReadingTask { ProcessRead(TrustedFileReader, GenerationId), ProcessReadData(TrustedFileReader, GenerationId), ProcessReadError(TrustedFileReader, GenerationId, DOMErrorName), ProcessReadEOF(TrustedFileReader, GenerationId, ReadMetaData, Vec<u8>), } impl FileReadingTask { pub fn handle_task(self) { use self::FileReadingTask::*; match self { ProcessRead(reader, gen_id) => FileReader::process_read(reader, gen_id), ProcessReadData(reader, gen_id) => FileReader::process_read_data(reader, gen_id), ProcessReadError(reader, gen_id, error) => { FileReader::process_read_error(reader, gen_id, error) }, ProcessReadEOF(reader, gen_id, metadata, blob_contents) => { FileReader::process_read_eof(reader, gen_id, metadata, blob_contents) }, }
} }
random_line_split
file_reading.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::domexception::DOMErrorName; use crate::dom::filereader::{FileReader, GenerationId, ReadMetaData, TrustedFileReader}; use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptThreadEventCategory}; use crate::task::{TaskCanceller, TaskOnce}; use crate::task_source::{TaskSource, TaskSourceName}; use msg::constellation_msg::PipelineId; #[derive(JSTraceable)] pub struct FileReadingTaskSource(pub Box<dyn ScriptChan + Send +'static>, pub PipelineId); impl Clone for FileReadingTaskSource { fn clone(&self) -> FileReadingTaskSource { FileReadingTaskSource(self.0.clone(), self.1.clone()) } } impl TaskSource for FileReadingTaskSource { const NAME: TaskSourceName = TaskSourceName::FileReading; fn queue_with_canceller<T>(&self, task: T, canceller: &TaskCanceller) -> Result<(), ()> where T: TaskOnce +'static, { self.0.send(CommonScriptMsg::Task( ScriptThreadEventCategory::FileRead, Box::new(canceller.wrap_task(task)), Some(self.1), FileReadingTaskSource::NAME, )) } } impl TaskOnce for FileReadingTask { fn run_once(self) { self.handle_task(); } } #[allow(dead_code)] pub enum
{ ProcessRead(TrustedFileReader, GenerationId), ProcessReadData(TrustedFileReader, GenerationId), ProcessReadError(TrustedFileReader, GenerationId, DOMErrorName), ProcessReadEOF(TrustedFileReader, GenerationId, ReadMetaData, Vec<u8>), } impl FileReadingTask { pub fn handle_task(self) { use self::FileReadingTask::*; match self { ProcessRead(reader, gen_id) => FileReader::process_read(reader, gen_id), ProcessReadData(reader, gen_id) => FileReader::process_read_data(reader, gen_id), ProcessReadError(reader, gen_id, error) => { FileReader::process_read_error(reader, gen_id, error) }, ProcessReadEOF(reader, gen_id, metadata, blob_contents) => { FileReader::process_read_eof(reader, gen_id, metadata, blob_contents) }, } } }
FileReadingTask
identifier_name
file_reading.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::domexception::DOMErrorName; use crate::dom::filereader::{FileReader, GenerationId, ReadMetaData, TrustedFileReader}; use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptThreadEventCategory}; use crate::task::{TaskCanceller, TaskOnce}; use crate::task_source::{TaskSource, TaskSourceName}; use msg::constellation_msg::PipelineId; #[derive(JSTraceable)] pub struct FileReadingTaskSource(pub Box<dyn ScriptChan + Send +'static>, pub PipelineId); impl Clone for FileReadingTaskSource { fn clone(&self) -> FileReadingTaskSource
} impl TaskSource for FileReadingTaskSource { const NAME: TaskSourceName = TaskSourceName::FileReading; fn queue_with_canceller<T>(&self, task: T, canceller: &TaskCanceller) -> Result<(), ()> where T: TaskOnce +'static, { self.0.send(CommonScriptMsg::Task( ScriptThreadEventCategory::FileRead, Box::new(canceller.wrap_task(task)), Some(self.1), FileReadingTaskSource::NAME, )) } } impl TaskOnce for FileReadingTask { fn run_once(self) { self.handle_task(); } } #[allow(dead_code)] pub enum FileReadingTask { ProcessRead(TrustedFileReader, GenerationId), ProcessReadData(TrustedFileReader, GenerationId), ProcessReadError(TrustedFileReader, GenerationId, DOMErrorName), ProcessReadEOF(TrustedFileReader, GenerationId, ReadMetaData, Vec<u8>), } impl FileReadingTask { pub fn handle_task(self) { use self::FileReadingTask::*; match self { ProcessRead(reader, gen_id) => FileReader::process_read(reader, gen_id), ProcessReadData(reader, gen_id) => FileReader::process_read_data(reader, gen_id), ProcessReadError(reader, gen_id, error) => { FileReader::process_read_error(reader, gen_id, error) }, ProcessReadEOF(reader, gen_id, metadata, blob_contents) => { FileReader::process_read_eof(reader, gen_id, metadata, blob_contents) }, } } }
{ FileReadingTaskSource(self.0.clone(), self.1.clone()) }
identifier_body
main.rs
use std::ops::{Add}; fn main() { println!(); // ARRAYS let one = [1,2,3]; let two: [u8; 3] = [1,2,3]; let blank1 = [0; 3]; let blank2: [u8; 3] = [0; 3]; let arrays = [one, two, blank1, blank2]; for a in &arrays { print!("{:?}: ", a); for n in a.iter() { print!("\t{} + 10 = {}", n, n+10); } let mut sum = 0; for i in 0..a.len() { sum += a[i]; } print!("\t(Σ{:?} = {})", a, sum); println!(); } println!(); // GREP-LITE let search_term = "picture"; let quote = "Every face, every shop, bedroom window, public-house, and dark square is a picture feverishly turned--in search of what? It is the same with books. What do we seek through millions of pages?"; for (idx, line) in quote.lines().enumerate() { if line.contains(search_term) { let line_num = idx + 1; println!("{}: {}", line_num, line); } } println!(); // NUMBERS AND GENERIC FUNCTION let (a, b) = (1.2, 3.4); let (x, y) = (10, 20); let c = add(a,b); let z = add(x, y); println!("{} + {} = {}", a, b, c); println!("{} + {} = {}", x, y, z); println!(); // SIMPLE FINDER let haystack = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862]; for reference in haystack.iter() { let item = *reference; let result = match item { 42 | 132 => "hit!", _ => "miss", }; if result == "hit!" { println!("{}: {}", item, result); } } println!(); // NUMBERS AND BASE SYSTEMS let three = 0b11; let thirty = 0o36; let three_hundred = 0x12C; println!("{} {} {}", three, thirty, three_hundred); println!("{:b} {:b} {:b}", three, thirty, three_hundred); println!("{:o} {:o} {:o}", three, thirty, three_hundred); println!("{:x} {:x} {:x}", three, thirty, three_hundred); println!(); // NUMBERS AND TYPES let twenty = 20; let twenty_one: i32 = twenty + 1; let floats_okay = 21.0; let one_million = 1_000_000; println!("{}; {}; {}; {}", twenty, twenty_one, floats_okay, one_million); println!(); let a = 10; let b: i32 = 20; let c = add(a, b); println!("a + b = {}", c); } //GENERIC FUNCTION fn a
T: Add<Output = T>>(i: T, j: T) -> T { i + j }
dd<
identifier_name
main.rs
use std::ops::{Add}; fn main() { println!(); // ARRAYS let one = [1,2,3]; let two: [u8; 3] = [1,2,3]; let blank1 = [0; 3]; let blank2: [u8; 3] = [0; 3]; let arrays = [one, two, blank1, blank2]; for a in &arrays { print!("{:?}: ", a); for n in a.iter() { print!("\t{} + 10 = {}", n, n+10); }
print!("\t(Σ{:?} = {})", a, sum); println!(); } println!(); // GREP-LITE let search_term = "picture"; let quote = "Every face, every shop, bedroom window, public-house, and dark square is a picture feverishly turned--in search of what? It is the same with books. What do we seek through millions of pages?"; for (idx, line) in quote.lines().enumerate() { if line.contains(search_term) { let line_num = idx + 1; println!("{}: {}", line_num, line); } } println!(); // NUMBERS AND GENERIC FUNCTION let (a, b) = (1.2, 3.4); let (x, y) = (10, 20); let c = add(a,b); let z = add(x, y); println!("{} + {} = {}", a, b, c); println!("{} + {} = {}", x, y, z); println!(); // SIMPLE FINDER let haystack = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862]; for reference in haystack.iter() { let item = *reference; let result = match item { 42 | 132 => "hit!", _ => "miss", }; if result == "hit!" { println!("{}: {}", item, result); } } println!(); // NUMBERS AND BASE SYSTEMS let three = 0b11; let thirty = 0o36; let three_hundred = 0x12C; println!("{} {} {}", three, thirty, three_hundred); println!("{:b} {:b} {:b}", three, thirty, three_hundred); println!("{:o} {:o} {:o}", three, thirty, three_hundred); println!("{:x} {:x} {:x}", three, thirty, three_hundred); println!(); // NUMBERS AND TYPES let twenty = 20; let twenty_one: i32 = twenty + 1; let floats_okay = 21.0; let one_million = 1_000_000; println!("{}; {}; {}; {}", twenty, twenty_one, floats_okay, one_million); println!(); let a = 10; let b: i32 = 20; let c = add(a, b); println!("a + b = {}", c); } //GENERIC FUNCTION fn add<T: Add<Output = T>>(i: T, j: T) -> T { i + j }
let mut sum = 0; for i in 0..a.len() { sum += a[i]; }
random_line_split
main.rs
use std::ops::{Add}; fn main() { println!(); // ARRAYS let one = [1,2,3]; let two: [u8; 3] = [1,2,3]; let blank1 = [0; 3]; let blank2: [u8; 3] = [0; 3]; let arrays = [one, two, blank1, blank2]; for a in &arrays { print!("{:?}: ", a); for n in a.iter() { print!("\t{} + 10 = {}", n, n+10); } let mut sum = 0; for i in 0..a.len() { sum += a[i]; } print!("\t(Σ{:?} = {})", a, sum); println!(); } println!(); // GREP-LITE let search_term = "picture"; let quote = "Every face, every shop, bedroom window, public-house, and dark square is a picture feverishly turned--in search of what? It is the same with books. What do we seek through millions of pages?"; for (idx, line) in quote.lines().enumerate() { if line.contains(search_term) { let line_num = idx + 1; println!("{}: {}", line_num, line); } } println!(); // NUMBERS AND GENERIC FUNCTION let (a, b) = (1.2, 3.4); let (x, y) = (10, 20); let c = add(a,b); let z = add(x, y); println!("{} + {} = {}", a, b, c); println!("{} + {} = {}", x, y, z); println!(); // SIMPLE FINDER let haystack = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862]; for reference in haystack.iter() { let item = *reference; let result = match item { 42 | 132 => "hit!", _ => "miss", }; if result == "hit!" { println!("{}: {}", item, result); } } println!(); // NUMBERS AND BASE SYSTEMS let three = 0b11; let thirty = 0o36; let three_hundred = 0x12C; println!("{} {} {}", three, thirty, three_hundred); println!("{:b} {:b} {:b}", three, thirty, three_hundred); println!("{:o} {:o} {:o}", three, thirty, three_hundred); println!("{:x} {:x} {:x}", three, thirty, three_hundred); println!(); // NUMBERS AND TYPES let twenty = 20; let twenty_one: i32 = twenty + 1; let floats_okay = 21.0; let one_million = 1_000_000; println!("{}; {}; {}; {}", twenty, twenty_one, floats_okay, one_million); println!(); let a = 10; let b: i32 = 20; let c = add(a, b); println!("a + b = {}", c); } //GENERIC FUNCTION fn add<T: Add<Output = T>>(i: T, j: T) -> T {
i + j }
identifier_body
test_multicast.rs
// TODO: This doesn't pass on android 64bit CI... // Figure out why! #![cfg(not(target_os = "android"))] use mio::{Events, Poll, PollOpt, Ready, Token}; use mio::net::UdpSocket; use bytes::{Buf, MutBuf, RingBuf, SliceBuf}; use std::str; use std::net::IpAddr; use localhost; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str,
impl UdpHandler { fn new(tx: UdpSocket, rx: UdpSocket, msg: &'static str) -> UdpHandler { let sock = UdpSocket::bind(&"127.0.0.1:12345".parse().unwrap()).unwrap(); UdpHandler { tx: tx, rx: rx, msg: msg, buf: SliceBuf::wrap(msg.as_bytes()), rx_buf: RingBuf::new(1024), localhost: sock.local_addr().unwrap().ip(), shutdown: false, } } fn handle_read(&mut self, _: &mut Poll, token: Token, _: Ready) { match token { LISTENER => { debug!("We are receiving a datagram now..."); match unsafe { self.rx.recv_from(self.rx_buf.mut_bytes()) } { Ok((cnt, addr)) => { unsafe { MutBuf::advance(&mut self.rx_buf, cnt); } assert_eq!(addr.ip(), self.localhost); } res => panic!("unexpected result: {:?}", res), } assert!(str::from_utf8(self.rx_buf.bytes()).unwrap() == self.msg); self.shutdown = true; }, _ => () } } fn handle_write(&mut self, _: &mut Poll, token: Token, _: Ready) { match token { SENDER => { let addr = self.rx.local_addr().unwrap(); let cnt = self.tx.send_to(self.buf.bytes(), &addr).unwrap(); self.buf.advance(cnt); }, _ => () } } } #[test] pub fn test_multicast() { drop(::env_logger::init()); debug!("Starting TEST_UDP_CONNECTIONLESS"); let mut poll = Poll::new().unwrap(); let addr = localhost(); let any = "0.0.0.0:0".parse().unwrap(); let tx = UdpSocket::bind(&any).unwrap(); let rx = UdpSocket::bind(&addr).unwrap(); info!("Joining group 227.1.1.100"); let any = "0.0.0.0".parse().unwrap(); rx.join_multicast_v4(&"227.1.1.100".parse().unwrap(), &any).unwrap(); info!("Joining group 227.1.1.101"); rx.join_multicast_v4(&"227.1.1.101".parse().unwrap(), &any).unwrap(); info!("Registering SENDER"); poll.register(&tx, SENDER, Ready::writable(), PollOpt::edge()).unwrap(); info!("Registering LISTENER"); poll.register(&rx, LISTENER, Ready::readable(), PollOpt::edge()).unwrap(); let mut events = Events::with_capacity(1024); let mut handler = UdpHandler::new(tx, rx, "hello world"); info!("Starting event loop to test with..."); while!handler.shutdown { poll.poll(&mut events, None).unwrap(); for event in &events { if event.readiness().is_readable() { handler.handle_read(&mut poll, event.token(), event.readiness()); } if event.readiness().is_writable() { handler.handle_write(&mut poll, event.token(), event.readiness()); } } } }
buf: SliceBuf<'static>, rx_buf: RingBuf, localhost: IpAddr, shutdown: bool, }
random_line_split
test_multicast.rs
// TODO: This doesn't pass on android 64bit CI... // Figure out why! #![cfg(not(target_os = "android"))] use mio::{Events, Poll, PollOpt, Ready, Token}; use mio::net::UdpSocket; use bytes::{Buf, MutBuf, RingBuf, SliceBuf}; use std::str; use std::net::IpAddr; use localhost; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str, buf: SliceBuf<'static>, rx_buf: RingBuf, localhost: IpAddr, shutdown: bool, } impl UdpHandler { fn new(tx: UdpSocket, rx: UdpSocket, msg: &'static str) -> UdpHandler { let sock = UdpSocket::bind(&"127.0.0.1:12345".parse().unwrap()).unwrap(); UdpHandler { tx: tx, rx: rx, msg: msg, buf: SliceBuf::wrap(msg.as_bytes()), rx_buf: RingBuf::new(1024), localhost: sock.local_addr().unwrap().ip(), shutdown: false, } } fn handle_read(&mut self, _: &mut Poll, token: Token, _: Ready) { match token { LISTENER => { debug!("We are receiving a datagram now..."); match unsafe { self.rx.recv_from(self.rx_buf.mut_bytes()) } { Ok((cnt, addr)) => { unsafe { MutBuf::advance(&mut self.rx_buf, cnt); } assert_eq!(addr.ip(), self.localhost); } res => panic!("unexpected result: {:?}", res), } assert!(str::from_utf8(self.rx_buf.bytes()).unwrap() == self.msg); self.shutdown = true; }, _ => () } } fn handle_write(&mut self, _: &mut Poll, token: Token, _: Ready)
} #[test] pub fn test_multicast() { drop(::env_logger::init()); debug!("Starting TEST_UDP_CONNECTIONLESS"); let mut poll = Poll::new().unwrap(); let addr = localhost(); let any = "0.0.0.0:0".parse().unwrap(); let tx = UdpSocket::bind(&any).unwrap(); let rx = UdpSocket::bind(&addr).unwrap(); info!("Joining group 227.1.1.100"); let any = "0.0.0.0".parse().unwrap(); rx.join_multicast_v4(&"227.1.1.100".parse().unwrap(), &any).unwrap(); info!("Joining group 227.1.1.101"); rx.join_multicast_v4(&"227.1.1.101".parse().unwrap(), &any).unwrap(); info!("Registering SENDER"); poll.register(&tx, SENDER, Ready::writable(), PollOpt::edge()).unwrap(); info!("Registering LISTENER"); poll.register(&rx, LISTENER, Ready::readable(), PollOpt::edge()).unwrap(); let mut events = Events::with_capacity(1024); let mut handler = UdpHandler::new(tx, rx, "hello world"); info!("Starting event loop to test with..."); while!handler.shutdown { poll.poll(&mut events, None).unwrap(); for event in &events { if event.readiness().is_readable() { handler.handle_read(&mut poll, event.token(), event.readiness()); } if event.readiness().is_writable() { handler.handle_write(&mut poll, event.token(), event.readiness()); } } } }
{ match token { SENDER => { let addr = self.rx.local_addr().unwrap(); let cnt = self.tx.send_to(self.buf.bytes(), &addr).unwrap(); self.buf.advance(cnt); }, _ => () } }
identifier_body
test_multicast.rs
// TODO: This doesn't pass on android 64bit CI... // Figure out why! #![cfg(not(target_os = "android"))] use mio::{Events, Poll, PollOpt, Ready, Token}; use mio::net::UdpSocket; use bytes::{Buf, MutBuf, RingBuf, SliceBuf}; use std::str; use std::net::IpAddr; use localhost; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str, buf: SliceBuf<'static>, rx_buf: RingBuf, localhost: IpAddr, shutdown: bool, } impl UdpHandler { fn new(tx: UdpSocket, rx: UdpSocket, msg: &'static str) -> UdpHandler { let sock = UdpSocket::bind(&"127.0.0.1:12345".parse().unwrap()).unwrap(); UdpHandler { tx: tx, rx: rx, msg: msg, buf: SliceBuf::wrap(msg.as_bytes()), rx_buf: RingBuf::new(1024), localhost: sock.local_addr().unwrap().ip(), shutdown: false, } } fn handle_read(&mut self, _: &mut Poll, token: Token, _: Ready) { match token { LISTENER => { debug!("We are receiving a datagram now..."); match unsafe { self.rx.recv_from(self.rx_buf.mut_bytes()) } { Ok((cnt, addr)) => { unsafe { MutBuf::advance(&mut self.rx_buf, cnt); } assert_eq!(addr.ip(), self.localhost); } res => panic!("unexpected result: {:?}", res), } assert!(str::from_utf8(self.rx_buf.bytes()).unwrap() == self.msg); self.shutdown = true; }, _ => () } } fn handle_write(&mut self, _: &mut Poll, token: Token, _: Ready) { match token { SENDER =>
, _ => () } } } #[test] pub fn test_multicast() { drop(::env_logger::init()); debug!("Starting TEST_UDP_CONNECTIONLESS"); let mut poll = Poll::new().unwrap(); let addr = localhost(); let any = "0.0.0.0:0".parse().unwrap(); let tx = UdpSocket::bind(&any).unwrap(); let rx = UdpSocket::bind(&addr).unwrap(); info!("Joining group 227.1.1.100"); let any = "0.0.0.0".parse().unwrap(); rx.join_multicast_v4(&"227.1.1.100".parse().unwrap(), &any).unwrap(); info!("Joining group 227.1.1.101"); rx.join_multicast_v4(&"227.1.1.101".parse().unwrap(), &any).unwrap(); info!("Registering SENDER"); poll.register(&tx, SENDER, Ready::writable(), PollOpt::edge()).unwrap(); info!("Registering LISTENER"); poll.register(&rx, LISTENER, Ready::readable(), PollOpt::edge()).unwrap(); let mut events = Events::with_capacity(1024); let mut handler = UdpHandler::new(tx, rx, "hello world"); info!("Starting event loop to test with..."); while!handler.shutdown { poll.poll(&mut events, None).unwrap(); for event in &events { if event.readiness().is_readable() { handler.handle_read(&mut poll, event.token(), event.readiness()); } if event.readiness().is_writable() { handler.handle_write(&mut poll, event.token(), event.readiness()); } } } }
{ let addr = self.rx.local_addr().unwrap(); let cnt = self.tx.send_to(self.buf.bytes(), &addr).unwrap(); self.buf.advance(cnt); }
conditional_block
test_multicast.rs
// TODO: This doesn't pass on android 64bit CI... // Figure out why! #![cfg(not(target_os = "android"))] use mio::{Events, Poll, PollOpt, Ready, Token}; use mio::net::UdpSocket; use bytes::{Buf, MutBuf, RingBuf, SliceBuf}; use std::str; use std::net::IpAddr; use localhost; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str, buf: SliceBuf<'static>, rx_buf: RingBuf, localhost: IpAddr, shutdown: bool, } impl UdpHandler { fn
(tx: UdpSocket, rx: UdpSocket, msg: &'static str) -> UdpHandler { let sock = UdpSocket::bind(&"127.0.0.1:12345".parse().unwrap()).unwrap(); UdpHandler { tx: tx, rx: rx, msg: msg, buf: SliceBuf::wrap(msg.as_bytes()), rx_buf: RingBuf::new(1024), localhost: sock.local_addr().unwrap().ip(), shutdown: false, } } fn handle_read(&mut self, _: &mut Poll, token: Token, _: Ready) { match token { LISTENER => { debug!("We are receiving a datagram now..."); match unsafe { self.rx.recv_from(self.rx_buf.mut_bytes()) } { Ok((cnt, addr)) => { unsafe { MutBuf::advance(&mut self.rx_buf, cnt); } assert_eq!(addr.ip(), self.localhost); } res => panic!("unexpected result: {:?}", res), } assert!(str::from_utf8(self.rx_buf.bytes()).unwrap() == self.msg); self.shutdown = true; }, _ => () } } fn handle_write(&mut self, _: &mut Poll, token: Token, _: Ready) { match token { SENDER => { let addr = self.rx.local_addr().unwrap(); let cnt = self.tx.send_to(self.buf.bytes(), &addr).unwrap(); self.buf.advance(cnt); }, _ => () } } } #[test] pub fn test_multicast() { drop(::env_logger::init()); debug!("Starting TEST_UDP_CONNECTIONLESS"); let mut poll = Poll::new().unwrap(); let addr = localhost(); let any = "0.0.0.0:0".parse().unwrap(); let tx = UdpSocket::bind(&any).unwrap(); let rx = UdpSocket::bind(&addr).unwrap(); info!("Joining group 227.1.1.100"); let any = "0.0.0.0".parse().unwrap(); rx.join_multicast_v4(&"227.1.1.100".parse().unwrap(), &any).unwrap(); info!("Joining group 227.1.1.101"); rx.join_multicast_v4(&"227.1.1.101".parse().unwrap(), &any).unwrap(); info!("Registering SENDER"); poll.register(&tx, SENDER, Ready::writable(), PollOpt::edge()).unwrap(); info!("Registering LISTENER"); poll.register(&rx, LISTENER, Ready::readable(), PollOpt::edge()).unwrap(); let mut events = Events::with_capacity(1024); let mut handler = UdpHandler::new(tx, rx, "hello world"); info!("Starting event loop to test with..."); while!handler.shutdown { poll.poll(&mut events, None).unwrap(); for event in &events { if event.readiness().is_readable() { handler.handle_read(&mut poll, event.token(), event.readiness()); } if event.readiness().is_writable() { handler.handle_write(&mut poll, event.token(), event.readiness()); } } } }
new
identifier_name
attachment.rs
// notty is a new kind of terminal emulator. // Copyright (C) 2015 without boats // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use base64; pub struct Attachments { data: Vec<String>, } impl Default for Attachments { fn default() -> Attachments { Attachments { data: vec![String::new()] } } } impl Attachments { pub fn clear(&mut self) { self.data.truncate(1); self.data.last_mut().unwrap().clear(); } pub fn iter(&self) -> AttachmentIter { self.into_iter() } pub fn append(&mut self, ch: char) -> Option<bool> { match ch { '0'...'9' | 'A'...'Z' | 'a'...'z' | '+' | '/' | '=' =>
'#' => { self.data.push(String::new()); None } '\u{9c}' => Some(true), _ => Some(false), } } } impl<'a> IntoIterator for &'a Attachments { type Item = Vec<u8>; type IntoIter = AttachmentIter<'a>; fn into_iter(self) -> AttachmentIter<'a> { AttachmentIter { attachments: self.data.iter(), } } } pub struct AttachmentIter<'a>{ attachments: <&'a Vec<String> as IntoIterator>::IntoIter, } impl<'a> Iterator for AttachmentIter<'a> { type Item = Vec<u8>; fn next(&mut self) -> Option<Vec<u8>> { self.attachments.next().and_then(|data| base64::u8de(data.as_bytes()).ok()) } } #[cfg(test)] mod tests { use base64; use super::*; static BLOCKS: &'static [&'static str] = &[ "YELLOW SUBMARINE", "Hello, world!", "History is a nightmare from which I am trying to awaken.", "#", "Happy familie are all alike; every unhappy family is unhappy in its own way.", "--A little more test data.--" ]; #[test] fn iterates() { let attachments = Attachments { data: BLOCKS.iter().map(|s| base64::encode(s).unwrap()).collect() }; for (attachment, block) in (&attachments).into_iter().zip(BLOCKS) { assert_eq!(attachment, block.as_bytes()); } } #[test] fn appends() { let mut attachments = Attachments::default(); for data in BLOCKS.iter().map(|s| base64::encode(s).unwrap()) { for ch in data.chars() { assert_eq!(attachments.append(ch), None); } assert_eq!(attachments.append('#'), None); } assert_eq!(attachments.append('\u{9c}'), Some(true)); for (attachment, block) in (&attachments).into_iter().zip(BLOCKS) { assert_eq!(attachment, block.as_bytes()); } } #[test] fn wont_append_invalid_chars() { let mut attachments = Attachments::default(); assert_eq!(attachments.append('~'), Some(false)); assert_eq!(attachments.data.last().unwrap().len(), 0); } }
{ self.data.last_mut().unwrap().push(ch); None }
conditional_block
attachment.rs
// notty is a new kind of terminal emulator. // Copyright (C) 2015 without boats // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use base64; pub struct
{ data: Vec<String>, } impl Default for Attachments { fn default() -> Attachments { Attachments { data: vec![String::new()] } } } impl Attachments { pub fn clear(&mut self) { self.data.truncate(1); self.data.last_mut().unwrap().clear(); } pub fn iter(&self) -> AttachmentIter { self.into_iter() } pub fn append(&mut self, ch: char) -> Option<bool> { match ch { '0'...'9' | 'A'...'Z' | 'a'...'z' | '+' | '/' | '=' => { self.data.last_mut().unwrap().push(ch); None } '#' => { self.data.push(String::new()); None } '\u{9c}' => Some(true), _ => Some(false), } } } impl<'a> IntoIterator for &'a Attachments { type Item = Vec<u8>; type IntoIter = AttachmentIter<'a>; fn into_iter(self) -> AttachmentIter<'a> { AttachmentIter { attachments: self.data.iter(), } } } pub struct AttachmentIter<'a>{ attachments: <&'a Vec<String> as IntoIterator>::IntoIter, } impl<'a> Iterator for AttachmentIter<'a> { type Item = Vec<u8>; fn next(&mut self) -> Option<Vec<u8>> { self.attachments.next().and_then(|data| base64::u8de(data.as_bytes()).ok()) } } #[cfg(test)] mod tests { use base64; use super::*; static BLOCKS: &'static [&'static str] = &[ "YELLOW SUBMARINE", "Hello, world!", "History is a nightmare from which I am trying to awaken.", "#", "Happy familie are all alike; every unhappy family is unhappy in its own way.", "--A little more test data.--" ]; #[test] fn iterates() { let attachments = Attachments { data: BLOCKS.iter().map(|s| base64::encode(s).unwrap()).collect() }; for (attachment, block) in (&attachments).into_iter().zip(BLOCKS) { assert_eq!(attachment, block.as_bytes()); } } #[test] fn appends() { let mut attachments = Attachments::default(); for data in BLOCKS.iter().map(|s| base64::encode(s).unwrap()) { for ch in data.chars() { assert_eq!(attachments.append(ch), None); } assert_eq!(attachments.append('#'), None); } assert_eq!(attachments.append('\u{9c}'), Some(true)); for (attachment, block) in (&attachments).into_iter().zip(BLOCKS) { assert_eq!(attachment, block.as_bytes()); } } #[test] fn wont_append_invalid_chars() { let mut attachments = Attachments::default(); assert_eq!(attachments.append('~'), Some(false)); assert_eq!(attachments.data.last().unwrap().len(), 0); } }
Attachments
identifier_name
attachment.rs
// notty is a new kind of terminal emulator. // Copyright (C) 2015 without boats // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use base64; pub struct Attachments { data: Vec<String>, } impl Default for Attachments { fn default() -> Attachments { Attachments { data: vec![String::new()] } } } impl Attachments { pub fn clear(&mut self) { self.data.truncate(1); self.data.last_mut().unwrap().clear(); } pub fn iter(&self) -> AttachmentIter { self.into_iter() } pub fn append(&mut self, ch: char) -> Option<bool> { match ch { '0'...'9' | 'A'...'Z' | 'a'...'z' | '+' | '/' | '=' => { self.data.last_mut().unwrap().push(ch); None } '#' => { self.data.push(String::new()); None } '\u{9c}' => Some(true), _ => Some(false), } } } impl<'a> IntoIterator for &'a Attachments { type Item = Vec<u8>; type IntoIter = AttachmentIter<'a>; fn into_iter(self) -> AttachmentIter<'a> { AttachmentIter { attachments: self.data.iter(), } } } pub struct AttachmentIter<'a>{ attachments: <&'a Vec<String> as IntoIterator>::IntoIter, } impl<'a> Iterator for AttachmentIter<'a> { type Item = Vec<u8>; fn next(&mut self) -> Option<Vec<u8>> { self.attachments.next().and_then(|data| base64::u8de(data.as_bytes()).ok()) } } #[cfg(test)] mod tests { use base64; use super::*; static BLOCKS: &'static [&'static str] = &[ "YELLOW SUBMARINE", "Hello, world!", "History is a nightmare from which I am trying to awaken.",
"Happy familie are all alike; every unhappy family is unhappy in its own way.", "--A little more test data.--" ]; #[test] fn iterates() { let attachments = Attachments { data: BLOCKS.iter().map(|s| base64::encode(s).unwrap()).collect() }; for (attachment, block) in (&attachments).into_iter().zip(BLOCKS) { assert_eq!(attachment, block.as_bytes()); } } #[test] fn appends() { let mut attachments = Attachments::default(); for data in BLOCKS.iter().map(|s| base64::encode(s).unwrap()) { for ch in data.chars() { assert_eq!(attachments.append(ch), None); } assert_eq!(attachments.append('#'), None); } assert_eq!(attachments.append('\u{9c}'), Some(true)); for (attachment, block) in (&attachments).into_iter().zip(BLOCKS) { assert_eq!(attachment, block.as_bytes()); } } #[test] fn wont_append_invalid_chars() { let mut attachments = Attachments::default(); assert_eq!(attachments.append('~'), Some(false)); assert_eq!(attachments.data.last().unwrap().len(), 0); } }
"#",
random_line_split
geometry.rs
use byteorder::{ReadBytesExt, LittleEndian}; use super::{Section, Struct, Result, Error, ReadExt, Stream}; use super::{Vec3, Uv, Sphere, Rgba}; use super::{Material, MaterialList, Extension}; use std::rc::Rc; /// Holds a list of `Geometry`s to be passed around. #[derive(Debug)] pub struct GeometryList(pub Vec<Rc<Geometry>>); /// Primary container object for dynamic model data. /// /// The data itself is stored as lists of `Triangle`s stored in a `MorphTarget`. Each such Triangle /// object also contains a reference to a `Material` object, which defines that triangle's appearance. /// /// During scene generation process, `Geometry` data will be used to generate `Mesh` data for /// rendering. Most of the time the pre-calculated `Mesh`es are already pre-calculated on the /// Clump RenderWare Stream in the form of `MeshHeader`. /// /// A Geometry object cannot be directly liked to a Frame as there is no storage for these. /// Instead, you should create an Atomic with a reference the Geometry, then link that Atomic to a Frame. #[derive(Debug)] pub struct Geometry { /// Render as triangle strips. pub is_tri_strip: bool, /// Pre-light colors. /// /// One element for each vertex. pub colors: Option<Vec<Rgba>>, /// Texture coordinate sets. /// /// One element for each coordinate set (uv0, uv1,...), and then one element for each vertex. pub uv_sets: Vec<Vec<Uv>>, /// List of triangles related to this geometry. /// /// Each triangle point to a vertex index on the current morph target and the a material index. pub faces: Vec<Triangle>, /// Defines vertex positions and normals. pub targets: Vec<MorphTarget>, /// Defines triangle's appearance. pub matlist: MaterialList, /// List of meshes to be rendered. /// /// Notice the cached meshes have a different indexing propery of the underlying Geometry, /// that is the `is_tri_strip` of the `Geometry` must be ignored in favor of the one in the /// `MeshHeader`. pub meshlist: MeshHeader, } /// Meshes are a caching system designed to speed up rendering. /// /// To make efficient use of hardware acceleration, model geometry is grouped into Meshes when the /// Geometry object is loaded and/or unlocked. /// /// Meshes are generated by sorting the model geometry by Material to reduce repeated uploads of /// the same texture data and Tristripping is also performed at the this level. #[derive(Debug)] pub struct Mesh { // TODO priv data? /// Material associated with this mesh triangles. pub material: Rc<Material>, /// Indices of triangles making the mesh. pub indices: Vec<u16>, } /// Header for all meshes that constitute a single `Geometry`. #[derive(Debug)] pub struct MeshHeader { /// Render as triangle strips. pub is_tri_strip: bool, /// Total triangle index count in all meshes. pub total_indices: u32, /// List of meshes. pub meshes: Vec<Mesh>, } /// Represents a triangle in a geometry. /// /// This is specified by three indices into the geometry's vertex list together with an index in to /// the geometry's material list. #[derive(Debug, Copy, Clone)] pub struct Triangle { // `Triangle`s are necessary only to calculate `Mesh`es, though those meshes are mostly like // already precalculated inside our clump streams (dff). /// Y vertex index. pub y_id: u16, /// X vertex index. pub x_id: u16, /// Index into material list pub mat_id: u16, /// Z vertex index. pub z_id: u16, } /// Keyframe points for interpolation in animations. A single keyframe means a non-keyframe geometry. #[derive(Debug)] pub struct MorphTarget { // Grand Theft Auto does not use keyframe animations, and as such there's always only a // single morph target in Geometry. /// Bounding sphere of the vertices. pub sphere: Sphere, pub unk1: u32, unk2: u32, /// Keyframe / Geometry vertex positions. pub verts: Option<Vec<Vec3>>, /// Keyframe / Geometry normals. pub normals: Option<Vec<Vec3>>, } impl Section for GeometryList { fn section_id() -> u32 { 0x001A } } impl Section for Geometry { fn section_id() -> u32 { 0x000F } } impl Section for MeshHeader { fn section_id() -> u32 { 0x050E } // Bin Mesh PLG } impl GeometryList { /// Gets the geometry at the specified index or `None` if out of range. pub fn get(&self, index: usize) -> Option<Rc<Geometry>> { self.0.get(index).map(|rcgeo| rcgeo.clone()) } /// Reads a Geometry List off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>) -> Result<GeometryList> { let _header = try!(Self::read_header(rws)); let numgeo = try!(Struct::read_up(rws, |rws| { Ok(try!(rws.read_u32::<LittleEndian>())) })); let mut geolist = Vec::with_capacity(numgeo as usize); for _ in (0..numgeo) { geolist.push( Rc::new(try!(Geometry::read(rws))) ); } Ok(GeometryList(geolist)) } } impl Geometry { /// Reads a Geometry off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>) -> Result<Geometry> { let header = try!(Self::read_header(rws)); let (flags, colors, uv_sets, faces, targets) = try!(Struct::read_up(rws, |rws| { let flags = try!(rws.read_u16::<LittleEndian>()); let num_uv = try!(rws.read_u8()); let _natflags = try!(rws.read_u8()); // TODO what is this? let num_tris = try!(rws.read_u32::<LittleEndian>()); let num_verts = try!(rws.read_u32::<LittleEndian>()); let num_morphs = try!(rws.read_u32::<LittleEndian>()); // On 3.4.0.3 and below there are some additional information let _amb_difu_spec = { if header.version <= 0x1003FFFF { Some(( try!(rws.read_f32::<LittleEndian>()), try!(rws.read_f32::<LittleEndian>()), try!(rws.read_f32::<LittleEndian>()), )) } else { None } }; // This geometry has pre-light colors? let colors = { if (flags & 8)!= 0 { let mut v = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) { v.push(try!(Rgba::read(rws))); } Some(v) } else { None } }; // Texture coordinates sets. let uv_sets = { let mut sets = Vec::with_capacity(num_uv as usize); for _ in (0..num_uv) { let mut v = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) { v.push(try!(Uv::read(rws))); } sets.push(v) } sets }; // Triangles that make up the model. let faces = { let mut v = Vec::with_capacity(num_tris as usize); for _ in (0..num_tris) { v.push(Triangle { y_id: try!(rws.read_u16::<LittleEndian>()), x_id: try!(rws.read_u16::<LittleEndian>()), mat_id: try!(rws.read_u16::<LittleEndian>()), z_id: try!(rws.read_u16::<LittleEndian>()), }); } v }; // Morph targets. let targets = { let mut v = Vec::with_capacity(num_morphs as usize); for _ in (0..num_morphs) { v.push(MorphTarget { sphere: try!(Sphere::read(rws)), unk1: try!(rws.read_u32::<LittleEndian>()), unk2: try!(rws.read_u32::<LittleEndian>()), verts: { // This geometry has positions? if (flags & 2)!= 0 { let mut verts = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) { verts.push(try!(Vec3::read(rws))); } Some(verts) } else { None } }, normals: { // This geometry has vertex normals? if (flags & 16)!= 0 { let mut normz = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) { normz.push(try!(Vec3::read(rws))); } Some(normz) } else { None } }, }); } v }; Ok((flags, colors, uv_sets, faces, targets)) })); let matlist = try!(MaterialList::read(rws)); let meshlist = try!(Extension::read_for(rws, |rws| MeshHeader::read(rws, &matlist))); Ok(Geometry { is_tri_strip: (flags & 1)!= 0, colors: colors, uv_sets: uv_sets, faces: faces, targets: targets, matlist: matlist, meshlist: meshlist.unwrap_or_else(|| { unimplemented!() // TODO calculate meshlist ourselves }), }) } } impl MeshHeader { /// Reads a Bin Mesh PLG off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>, matlist: &MaterialList) -> Result<MeshHeader>
} impl Mesh { /// Reads a single Mesh (from a Bin Mesh PLG) off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>, matlist: &MaterialList) -> Result<Mesh> { let nidx = try!(rws.read_u32::<LittleEndian>()) as usize; let matid = try!(rws.read_u32::<LittleEndian>()) as usize; Ok(Mesh { material: try!(matlist.get(matid) .ok_or(Error::Other("Invalid 'Mesh' material id".into()))), indices: { let mut v = Vec::with_capacity(nidx); for _ in (0..nidx) { v.push(try!(rws.read_u32::<LittleEndian>().map(|x| x as u16))); } v }, }) } }
{ let _header = try!(Self::read_header(rws)); let flags = try!(rws.read_u32::<LittleEndian>()); let num_mesh = try!(rws.read_u32::<LittleEndian>()); let total_idx = try!(rws.read_u32::<LittleEndian>()); Ok(MeshHeader { is_tri_strip: (flags & 1) != 0, // TODO better analyze? total_indices: total_idx, meshes: try!((0..num_mesh).map(|_| Mesh::read(rws, matlist)).collect()), }) }
identifier_body
geometry.rs
use byteorder::{ReadBytesExt, LittleEndian}; use super::{Section, Struct, Result, Error, ReadExt, Stream}; use super::{Vec3, Uv, Sphere, Rgba}; use super::{Material, MaterialList, Extension}; use std::rc::Rc; /// Holds a list of `Geometry`s to be passed around. #[derive(Debug)] pub struct GeometryList(pub Vec<Rc<Geometry>>); /// Primary container object for dynamic model data. /// /// The data itself is stored as lists of `Triangle`s stored in a `MorphTarget`. Each such Triangle /// object also contains a reference to a `Material` object, which defines that triangle's appearance. /// /// During scene generation process, `Geometry` data will be used to generate `Mesh` data for /// rendering. Most of the time the pre-calculated `Mesh`es are already pre-calculated on the /// Clump RenderWare Stream in the form of `MeshHeader`. /// /// A Geometry object cannot be directly liked to a Frame as there is no storage for these. /// Instead, you should create an Atomic with a reference the Geometry, then link that Atomic to a Frame. #[derive(Debug)] pub struct Geometry { /// Render as triangle strips. pub is_tri_strip: bool, /// Pre-light colors. /// /// One element for each vertex. pub colors: Option<Vec<Rgba>>, /// Texture coordinate sets. /// /// One element for each coordinate set (uv0, uv1,...), and then one element for each vertex. pub uv_sets: Vec<Vec<Uv>>, /// List of triangles related to this geometry. /// /// Each triangle point to a vertex index on the current morph target and the a material index. pub faces: Vec<Triangle>, /// Defines vertex positions and normals. pub targets: Vec<MorphTarget>, /// Defines triangle's appearance. pub matlist: MaterialList, /// List of meshes to be rendered. /// /// Notice the cached meshes have a different indexing propery of the underlying Geometry, /// that is the `is_tri_strip` of the `Geometry` must be ignored in favor of the one in the /// `MeshHeader`. pub meshlist: MeshHeader, } /// Meshes are a caching system designed to speed up rendering. /// /// To make efficient use of hardware acceleration, model geometry is grouped into Meshes when the /// Geometry object is loaded and/or unlocked. /// /// Meshes are generated by sorting the model geometry by Material to reduce repeated uploads of /// the same texture data and Tristripping is also performed at the this level. #[derive(Debug)] pub struct Mesh { // TODO priv data? /// Material associated with this mesh triangles. pub material: Rc<Material>, /// Indices of triangles making the mesh. pub indices: Vec<u16>, } /// Header for all meshes that constitute a single `Geometry`. #[derive(Debug)] pub struct MeshHeader { /// Render as triangle strips. pub is_tri_strip: bool, /// Total triangle index count in all meshes. pub total_indices: u32, /// List of meshes. pub meshes: Vec<Mesh>, } /// Represents a triangle in a geometry. /// /// This is specified by three indices into the geometry's vertex list together with an index in to /// the geometry's material list. #[derive(Debug, Copy, Clone)] pub struct Triangle { // `Triangle`s are necessary only to calculate `Mesh`es, though those meshes are mostly like // already precalculated inside our clump streams (dff). /// Y vertex index. pub y_id: u16, /// X vertex index. pub x_id: u16, /// Index into material list pub mat_id: u16, /// Z vertex index. pub z_id: u16, } /// Keyframe points for interpolation in animations. A single keyframe means a non-keyframe geometry. #[derive(Debug)] pub struct MorphTarget { // Grand Theft Auto does not use keyframe animations, and as such there's always only a // single morph target in Geometry. /// Bounding sphere of the vertices. pub sphere: Sphere, pub unk1: u32, unk2: u32, /// Keyframe / Geometry vertex positions. pub verts: Option<Vec<Vec3>>, /// Keyframe / Geometry normals. pub normals: Option<Vec<Vec3>>, } impl Section for GeometryList { fn section_id() -> u32 { 0x001A } } impl Section for Geometry { fn section_id() -> u32 { 0x000F } } impl Section for MeshHeader { fn section_id() -> u32 { 0x050E } // Bin Mesh PLG } impl GeometryList { /// Gets the geometry at the specified index or `None` if out of range. pub fn get(&self, index: usize) -> Option<Rc<Geometry>> { self.0.get(index).map(|rcgeo| rcgeo.clone()) } /// Reads a Geometry List off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>) -> Result<GeometryList> { let _header = try!(Self::read_header(rws)); let numgeo = try!(Struct::read_up(rws, |rws| { Ok(try!(rws.read_u32::<LittleEndian>())) })); let mut geolist = Vec::with_capacity(numgeo as usize); for _ in (0..numgeo) { geolist.push( Rc::new(try!(Geometry::read(rws))) ); } Ok(GeometryList(geolist)) } } impl Geometry { /// Reads a Geometry off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>) -> Result<Geometry> { let header = try!(Self::read_header(rws)); let (flags, colors, uv_sets, faces, targets) = try!(Struct::read_up(rws, |rws| { let flags = try!(rws.read_u16::<LittleEndian>()); let num_uv = try!(rws.read_u8()); let _natflags = try!(rws.read_u8()); // TODO what is this? let num_tris = try!(rws.read_u32::<LittleEndian>()); let num_verts = try!(rws.read_u32::<LittleEndian>()); let num_morphs = try!(rws.read_u32::<LittleEndian>()); // On 3.4.0.3 and below there are some additional information let _amb_difu_spec = { if header.version <= 0x1003FFFF { Some(( try!(rws.read_f32::<LittleEndian>()), try!(rws.read_f32::<LittleEndian>()), try!(rws.read_f32::<LittleEndian>()), )) } else { None } }; // This geometry has pre-light colors? let colors = { if (flags & 8)!= 0 { let mut v = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) { v.push(try!(Rgba::read(rws))); } Some(v) } else { None } }; // Texture coordinates sets. let uv_sets = { let mut sets = Vec::with_capacity(num_uv as usize); for _ in (0..num_uv) { let mut v = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) { v.push(try!(Uv::read(rws))); } sets.push(v) } sets }; // Triangles that make up the model. let faces = { let mut v = Vec::with_capacity(num_tris as usize); for _ in (0..num_tris) { v.push(Triangle { y_id: try!(rws.read_u16::<LittleEndian>()), x_id: try!(rws.read_u16::<LittleEndian>()), mat_id: try!(rws.read_u16::<LittleEndian>()), z_id: try!(rws.read_u16::<LittleEndian>()), }); } v }; // Morph targets. let targets = { let mut v = Vec::with_capacity(num_morphs as usize); for _ in (0..num_morphs) { v.push(MorphTarget { sphere: try!(Sphere::read(rws)), unk1: try!(rws.read_u32::<LittleEndian>()), unk2: try!(rws.read_u32::<LittleEndian>()), verts: { // This geometry has positions? if (flags & 2)!= 0 { let mut verts = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) { verts.push(try!(Vec3::read(rws))); } Some(verts) } else
}, normals: { // This geometry has vertex normals? if (flags & 16)!= 0 { let mut normz = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) { normz.push(try!(Vec3::read(rws))); } Some(normz) } else { None } }, }); } v }; Ok((flags, colors, uv_sets, faces, targets)) })); let matlist = try!(MaterialList::read(rws)); let meshlist = try!(Extension::read_for(rws, |rws| MeshHeader::read(rws, &matlist))); Ok(Geometry { is_tri_strip: (flags & 1)!= 0, colors: colors, uv_sets: uv_sets, faces: faces, targets: targets, matlist: matlist, meshlist: meshlist.unwrap_or_else(|| { unimplemented!() // TODO calculate meshlist ourselves }), }) } } impl MeshHeader { /// Reads a Bin Mesh PLG off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>, matlist: &MaterialList) -> Result<MeshHeader> { let _header = try!(Self::read_header(rws)); let flags = try!(rws.read_u32::<LittleEndian>()); let num_mesh = try!(rws.read_u32::<LittleEndian>()); let total_idx = try!(rws.read_u32::<LittleEndian>()); Ok(MeshHeader { is_tri_strip: (flags & 1)!= 0, // TODO better analyze? total_indices: total_idx, meshes: try!((0..num_mesh).map(|_| Mesh::read(rws, matlist)).collect()), }) } } impl Mesh { /// Reads a single Mesh (from a Bin Mesh PLG) off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>, matlist: &MaterialList) -> Result<Mesh> { let nidx = try!(rws.read_u32::<LittleEndian>()) as usize; let matid = try!(rws.read_u32::<LittleEndian>()) as usize; Ok(Mesh { material: try!(matlist.get(matid) .ok_or(Error::Other("Invalid 'Mesh' material id".into()))), indices: { let mut v = Vec::with_capacity(nidx); for _ in (0..nidx) { v.push(try!(rws.read_u32::<LittleEndian>().map(|x| x as u16))); } v }, }) } }
{ None }
conditional_block
geometry.rs
use byteorder::{ReadBytesExt, LittleEndian}; use super::{Section, Struct, Result, Error, ReadExt, Stream}; use super::{Vec3, Uv, Sphere, Rgba}; use super::{Material, MaterialList, Extension}; use std::rc::Rc; /// Holds a list of `Geometry`s to be passed around. #[derive(Debug)] pub struct GeometryList(pub Vec<Rc<Geometry>>); /// Primary container object for dynamic model data. /// /// The data itself is stored as lists of `Triangle`s stored in a `MorphTarget`. Each such Triangle /// object also contains a reference to a `Material` object, which defines that triangle's appearance. /// /// During scene generation process, `Geometry` data will be used to generate `Mesh` data for /// rendering. Most of the time the pre-calculated `Mesh`es are already pre-calculated on the /// Clump RenderWare Stream in the form of `MeshHeader`. /// /// A Geometry object cannot be directly liked to a Frame as there is no storage for these. /// Instead, you should create an Atomic with a reference the Geometry, then link that Atomic to a Frame. #[derive(Debug)] pub struct Geometry { /// Render as triangle strips. pub is_tri_strip: bool, /// Pre-light colors. /// /// One element for each vertex. pub colors: Option<Vec<Rgba>>, /// Texture coordinate sets. /// /// One element for each coordinate set (uv0, uv1,...), and then one element for each vertex. pub uv_sets: Vec<Vec<Uv>>, /// List of triangles related to this geometry. /// /// Each triangle point to a vertex index on the current morph target and the a material index. pub faces: Vec<Triangle>, /// Defines vertex positions and normals. pub targets: Vec<MorphTarget>, /// Defines triangle's appearance. pub matlist: MaterialList, /// List of meshes to be rendered. /// /// Notice the cached meshes have a different indexing propery of the underlying Geometry, /// that is the `is_tri_strip` of the `Geometry` must be ignored in favor of the one in the /// `MeshHeader`. pub meshlist: MeshHeader, } /// Meshes are a caching system designed to speed up rendering. /// /// To make efficient use of hardware acceleration, model geometry is grouped into Meshes when the /// Geometry object is loaded and/or unlocked. /// /// Meshes are generated by sorting the model geometry by Material to reduce repeated uploads of /// the same texture data and Tristripping is also performed at the this level. #[derive(Debug)] pub struct Mesh { // TODO priv data? /// Material associated with this mesh triangles. pub material: Rc<Material>, /// Indices of triangles making the mesh. pub indices: Vec<u16>, } /// Header for all meshes that constitute a single `Geometry`. #[derive(Debug)] pub struct
{ /// Render as triangle strips. pub is_tri_strip: bool, /// Total triangle index count in all meshes. pub total_indices: u32, /// List of meshes. pub meshes: Vec<Mesh>, } /// Represents a triangle in a geometry. /// /// This is specified by three indices into the geometry's vertex list together with an index in to /// the geometry's material list. #[derive(Debug, Copy, Clone)] pub struct Triangle { // `Triangle`s are necessary only to calculate `Mesh`es, though those meshes are mostly like // already precalculated inside our clump streams (dff). /// Y vertex index. pub y_id: u16, /// X vertex index. pub x_id: u16, /// Index into material list pub mat_id: u16, /// Z vertex index. pub z_id: u16, } /// Keyframe points for interpolation in animations. A single keyframe means a non-keyframe geometry. #[derive(Debug)] pub struct MorphTarget { // Grand Theft Auto does not use keyframe animations, and as such there's always only a // single morph target in Geometry. /// Bounding sphere of the vertices. pub sphere: Sphere, pub unk1: u32, unk2: u32, /// Keyframe / Geometry vertex positions. pub verts: Option<Vec<Vec3>>, /// Keyframe / Geometry normals. pub normals: Option<Vec<Vec3>>, } impl Section for GeometryList { fn section_id() -> u32 { 0x001A } } impl Section for Geometry { fn section_id() -> u32 { 0x000F } } impl Section for MeshHeader { fn section_id() -> u32 { 0x050E } // Bin Mesh PLG } impl GeometryList { /// Gets the geometry at the specified index or `None` if out of range. pub fn get(&self, index: usize) -> Option<Rc<Geometry>> { self.0.get(index).map(|rcgeo| rcgeo.clone()) } /// Reads a Geometry List off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>) -> Result<GeometryList> { let _header = try!(Self::read_header(rws)); let numgeo = try!(Struct::read_up(rws, |rws| { Ok(try!(rws.read_u32::<LittleEndian>())) })); let mut geolist = Vec::with_capacity(numgeo as usize); for _ in (0..numgeo) { geolist.push( Rc::new(try!(Geometry::read(rws))) ); } Ok(GeometryList(geolist)) } } impl Geometry { /// Reads a Geometry off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>) -> Result<Geometry> { let header = try!(Self::read_header(rws)); let (flags, colors, uv_sets, faces, targets) = try!(Struct::read_up(rws, |rws| { let flags = try!(rws.read_u16::<LittleEndian>()); let num_uv = try!(rws.read_u8()); let _natflags = try!(rws.read_u8()); // TODO what is this? let num_tris = try!(rws.read_u32::<LittleEndian>()); let num_verts = try!(rws.read_u32::<LittleEndian>()); let num_morphs = try!(rws.read_u32::<LittleEndian>()); // On 3.4.0.3 and below there are some additional information let _amb_difu_spec = { if header.version <= 0x1003FFFF { Some(( try!(rws.read_f32::<LittleEndian>()), try!(rws.read_f32::<LittleEndian>()), try!(rws.read_f32::<LittleEndian>()), )) } else { None } }; // This geometry has pre-light colors? let colors = { if (flags & 8)!= 0 { let mut v = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) { v.push(try!(Rgba::read(rws))); } Some(v) } else { None } }; // Texture coordinates sets. let uv_sets = { let mut sets = Vec::with_capacity(num_uv as usize); for _ in (0..num_uv) { let mut v = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) { v.push(try!(Uv::read(rws))); } sets.push(v) } sets }; // Triangles that make up the model. let faces = { let mut v = Vec::with_capacity(num_tris as usize); for _ in (0..num_tris) { v.push(Triangle { y_id: try!(rws.read_u16::<LittleEndian>()), x_id: try!(rws.read_u16::<LittleEndian>()), mat_id: try!(rws.read_u16::<LittleEndian>()), z_id: try!(rws.read_u16::<LittleEndian>()), }); } v }; // Morph targets. let targets = { let mut v = Vec::with_capacity(num_morphs as usize); for _ in (0..num_morphs) { v.push(MorphTarget { sphere: try!(Sphere::read(rws)), unk1: try!(rws.read_u32::<LittleEndian>()), unk2: try!(rws.read_u32::<LittleEndian>()), verts: { // This geometry has positions? if (flags & 2)!= 0 { let mut verts = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) { verts.push(try!(Vec3::read(rws))); } Some(verts) } else { None } }, normals: { // This geometry has vertex normals? if (flags & 16)!= 0 { let mut normz = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) { normz.push(try!(Vec3::read(rws))); } Some(normz) } else { None } }, }); } v }; Ok((flags, colors, uv_sets, faces, targets)) })); let matlist = try!(MaterialList::read(rws)); let meshlist = try!(Extension::read_for(rws, |rws| MeshHeader::read(rws, &matlist))); Ok(Geometry { is_tri_strip: (flags & 1)!= 0, colors: colors, uv_sets: uv_sets, faces: faces, targets: targets, matlist: matlist, meshlist: meshlist.unwrap_or_else(|| { unimplemented!() // TODO calculate meshlist ourselves }), }) } } impl MeshHeader { /// Reads a Bin Mesh PLG off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>, matlist: &MaterialList) -> Result<MeshHeader> { let _header = try!(Self::read_header(rws)); let flags = try!(rws.read_u32::<LittleEndian>()); let num_mesh = try!(rws.read_u32::<LittleEndian>()); let total_idx = try!(rws.read_u32::<LittleEndian>()); Ok(MeshHeader { is_tri_strip: (flags & 1)!= 0, // TODO better analyze? total_indices: total_idx, meshes: try!((0..num_mesh).map(|_| Mesh::read(rws, matlist)).collect()), }) } } impl Mesh { /// Reads a single Mesh (from a Bin Mesh PLG) off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>, matlist: &MaterialList) -> Result<Mesh> { let nidx = try!(rws.read_u32::<LittleEndian>()) as usize; let matid = try!(rws.read_u32::<LittleEndian>()) as usize; Ok(Mesh { material: try!(matlist.get(matid) .ok_or(Error::Other("Invalid 'Mesh' material id".into()))), indices: { let mut v = Vec::with_capacity(nidx); for _ in (0..nidx) { v.push(try!(rws.read_u32::<LittleEndian>().map(|x| x as u16))); } v }, }) } }
MeshHeader
identifier_name
geometry.rs
use byteorder::{ReadBytesExt, LittleEndian}; use super::{Section, Struct, Result, Error, ReadExt, Stream}; use super::{Vec3, Uv, Sphere, Rgba}; use super::{Material, MaterialList, Extension}; use std::rc::Rc; /// Holds a list of `Geometry`s to be passed around. #[derive(Debug)] pub struct GeometryList(pub Vec<Rc<Geometry>>); /// Primary container object for dynamic model data. /// /// The data itself is stored as lists of `Triangle`s stored in a `MorphTarget`. Each such Triangle /// object also contains a reference to a `Material` object, which defines that triangle's appearance. /// /// During scene generation process, `Geometry` data will be used to generate `Mesh` data for /// rendering. Most of the time the pre-calculated `Mesh`es are already pre-calculated on the /// Clump RenderWare Stream in the form of `MeshHeader`. /// /// A Geometry object cannot be directly liked to a Frame as there is no storage for these. /// Instead, you should create an Atomic with a reference the Geometry, then link that Atomic to a Frame. #[derive(Debug)] pub struct Geometry { /// Render as triangle strips. pub is_tri_strip: bool, /// Pre-light colors. /// /// One element for each vertex. pub colors: Option<Vec<Rgba>>, /// Texture coordinate sets. /// /// One element for each coordinate set (uv0, uv1,...), and then one element for each vertex. pub uv_sets: Vec<Vec<Uv>>, /// List of triangles related to this geometry. /// /// Each triangle point to a vertex index on the current morph target and the a material index. pub faces: Vec<Triangle>, /// Defines vertex positions and normals. pub targets: Vec<MorphTarget>, /// Defines triangle's appearance. pub matlist: MaterialList, /// List of meshes to be rendered. /// /// Notice the cached meshes have a different indexing propery of the underlying Geometry, /// that is the `is_tri_strip` of the `Geometry` must be ignored in favor of the one in the /// `MeshHeader`. pub meshlist: MeshHeader, } /// Meshes are a caching system designed to speed up rendering. /// /// To make efficient use of hardware acceleration, model geometry is grouped into Meshes when the /// Geometry object is loaded and/or unlocked. /// /// Meshes are generated by sorting the model geometry by Material to reduce repeated uploads of /// the same texture data and Tristripping is also performed at the this level. #[derive(Debug)] pub struct Mesh { // TODO priv data? /// Material associated with this mesh triangles. pub material: Rc<Material>, /// Indices of triangles making the mesh. pub indices: Vec<u16>, } /// Header for all meshes that constitute a single `Geometry`. #[derive(Debug)] pub struct MeshHeader { /// Render as triangle strips. pub is_tri_strip: bool, /// Total triangle index count in all meshes. pub total_indices: u32, /// List of meshes. pub meshes: Vec<Mesh>, } /// Represents a triangle in a geometry. /// /// This is specified by three indices into the geometry's vertex list together with an index in to /// the geometry's material list. #[derive(Debug, Copy, Clone)] pub struct Triangle { // `Triangle`s are necessary only to calculate `Mesh`es, though those meshes are mostly like // already precalculated inside our clump streams (dff). /// Y vertex index. pub y_id: u16, /// X vertex index. pub x_id: u16, /// Index into material list pub mat_id: u16, /// Z vertex index. pub z_id: u16, } /// Keyframe points for interpolation in animations. A single keyframe means a non-keyframe geometry. #[derive(Debug)] pub struct MorphTarget { // Grand Theft Auto does not use keyframe animations, and as such there's always only a // single morph target in Geometry. /// Bounding sphere of the vertices. pub sphere: Sphere, pub unk1: u32, unk2: u32, /// Keyframe / Geometry vertex positions. pub verts: Option<Vec<Vec3>>, /// Keyframe / Geometry normals. pub normals: Option<Vec<Vec3>>, } impl Section for GeometryList { fn section_id() -> u32 { 0x001A } } impl Section for Geometry { fn section_id() -> u32 { 0x000F } } impl Section for MeshHeader { fn section_id() -> u32 { 0x050E } // Bin Mesh PLG } impl GeometryList { /// Gets the geometry at the specified index or `None` if out of range. pub fn get(&self, index: usize) -> Option<Rc<Geometry>> { self.0.get(index).map(|rcgeo| rcgeo.clone()) } /// Reads a Geometry List off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>) -> Result<GeometryList> { let _header = try!(Self::read_header(rws)); let numgeo = try!(Struct::read_up(rws, |rws| { Ok(try!(rws.read_u32::<LittleEndian>())) })); let mut geolist = Vec::with_capacity(numgeo as usize); for _ in (0..numgeo) { geolist.push( Rc::new(try!(Geometry::read(rws))) ); } Ok(GeometryList(geolist)) } } impl Geometry { /// Reads a Geometry off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>) -> Result<Geometry> { let header = try!(Self::read_header(rws)); let (flags, colors, uv_sets, faces, targets) = try!(Struct::read_up(rws, |rws| { let flags = try!(rws.read_u16::<LittleEndian>()); let num_uv = try!(rws.read_u8()); let _natflags = try!(rws.read_u8()); // TODO what is this? let num_tris = try!(rws.read_u32::<LittleEndian>()); let num_verts = try!(rws.read_u32::<LittleEndian>()); let num_morphs = try!(rws.read_u32::<LittleEndian>()); // On 3.4.0.3 and below there are some additional information let _amb_difu_spec = { if header.version <= 0x1003FFFF { Some(( try!(rws.read_f32::<LittleEndian>()), try!(rws.read_f32::<LittleEndian>()), try!(rws.read_f32::<LittleEndian>()), )) } else { None } }; // This geometry has pre-light colors? let colors = { if (flags & 8)!= 0 { let mut v = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) { v.push(try!(Rgba::read(rws))); } Some(v) } else { None } }; // Texture coordinates sets. let uv_sets = { let mut sets = Vec::with_capacity(num_uv as usize); for _ in (0..num_uv) { let mut v = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) { v.push(try!(Uv::read(rws))); } sets.push(v) } sets }; // Triangles that make up the model. let faces = { let mut v = Vec::with_capacity(num_tris as usize); for _ in (0..num_tris) { v.push(Triangle { y_id: try!(rws.read_u16::<LittleEndian>()), x_id: try!(rws.read_u16::<LittleEndian>()), mat_id: try!(rws.read_u16::<LittleEndian>()), z_id: try!(rws.read_u16::<LittleEndian>()), }); } v }; // Morph targets. let targets = { let mut v = Vec::with_capacity(num_morphs as usize); for _ in (0..num_morphs) { v.push(MorphTarget { sphere: try!(Sphere::read(rws)), unk1: try!(rws.read_u32::<LittleEndian>()), unk2: try!(rws.read_u32::<LittleEndian>()), verts: { // This geometry has positions? if (flags & 2)!= 0 { let mut verts = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) {
verts.push(try!(Vec3::read(rws))); } Some(verts) } else { None } }, normals: { // This geometry has vertex normals? if (flags & 16)!= 0 { let mut normz = Vec::with_capacity(num_verts as usize); for _ in (0..num_verts) { normz.push(try!(Vec3::read(rws))); } Some(normz) } else { None } }, }); } v }; Ok((flags, colors, uv_sets, faces, targets)) })); let matlist = try!(MaterialList::read(rws)); let meshlist = try!(Extension::read_for(rws, |rws| MeshHeader::read(rws, &matlist))); Ok(Geometry { is_tri_strip: (flags & 1)!= 0, colors: colors, uv_sets: uv_sets, faces: faces, targets: targets, matlist: matlist, meshlist: meshlist.unwrap_or_else(|| { unimplemented!() // TODO calculate meshlist ourselves }), }) } } impl MeshHeader { /// Reads a Bin Mesh PLG off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>, matlist: &MaterialList) -> Result<MeshHeader> { let _header = try!(Self::read_header(rws)); let flags = try!(rws.read_u32::<LittleEndian>()); let num_mesh = try!(rws.read_u32::<LittleEndian>()); let total_idx = try!(rws.read_u32::<LittleEndian>()); Ok(MeshHeader { is_tri_strip: (flags & 1)!= 0, // TODO better analyze? total_indices: total_idx, meshes: try!((0..num_mesh).map(|_| Mesh::read(rws, matlist)).collect()), }) } } impl Mesh { /// Reads a single Mesh (from a Bin Mesh PLG) off the RenderWare Stream. pub fn read<R: ReadExt>(rws: &mut Stream<R>, matlist: &MaterialList) -> Result<Mesh> { let nidx = try!(rws.read_u32::<LittleEndian>()) as usize; let matid = try!(rws.read_u32::<LittleEndian>()) as usize; Ok(Mesh { material: try!(matlist.get(matid) .ok_or(Error::Other("Invalid 'Mesh' material id".into()))), indices: { let mut v = Vec::with_capacity(nidx); for _ in (0..nidx) { v.push(try!(rws.read_u32::<LittleEndian>().map(|x| x as u16))); } v }, }) } }
random_line_split
lossy_float_literal.rs
// run-rustfix #![warn(clippy::lossy_float_literal)] fn
() { // Lossy whole-number float literals let _: f32 = 16_777_217.0; let _: f32 = 16_777_219.0; let _: f32 = 16_777_219.; let _: f32 = 16_777_219.000; let _ = 16_777_219f32; let _: f32 = -16_777_219.0; let _: f64 = 9_007_199_254_740_993.0; let _: f64 = 9_007_199_254_740_993.; let _: f64 = 9_007_199_254_740_993.00; let _ = 9_007_199_254_740_993f64; let _: f64 = -9_007_199_254_740_993.0; // Lossless whole number float literals let _: f32 = 16_777_216.0; let _: f32 = 16_777_218.0; let _: f32 = 16_777_220.0; let _: f32 = -16_777_216.0; let _: f32 = -16_777_220.0; let _: f64 = 16_777_217.0; let _: f64 = -16_777_217.0; let _: f64 = 9_007_199_254_740_992.0; let _: f64 = -9_007_199_254_740_992.0; // Ignored whole number float literals let _: f32 = 1e25; let _: f32 = 1E25; let _: f64 = 1e99; let _: f64 = 1E99; let _: f32 = 0.1; }
main
identifier_name
lossy_float_literal.rs
// run-rustfix #![warn(clippy::lossy_float_literal)] fn main() { // Lossy whole-number float literals let _: f32 = 16_777_217.0; let _: f32 = 16_777_219.0; let _: f32 = 16_777_219.; let _: f32 = 16_777_219.000; let _ = 16_777_219f32; let _: f32 = -16_777_219.0; let _: f64 = 9_007_199_254_740_993.0; let _: f64 = 9_007_199_254_740_993.; let _: f64 = 9_007_199_254_740_993.00; let _ = 9_007_199_254_740_993f64; let _: f64 = -9_007_199_254_740_993.0; // Lossless whole number float literals let _: f32 = 16_777_216.0; let _: f32 = 16_777_218.0; let _: f32 = 16_777_220.0; let _: f32 = -16_777_216.0; let _: f32 = -16_777_220.0; let _: f64 = 16_777_217.0; let _: f64 = -16_777_217.0; let _: f64 = 9_007_199_254_740_992.0; let _: f64 = -9_007_199_254_740_992.0;
let _: f64 = 1E99; let _: f32 = 0.1; }
// Ignored whole number float literals let _: f32 = 1e25; let _: f32 = 1E25; let _: f64 = 1e99;
random_line_split
lossy_float_literal.rs
// run-rustfix #![warn(clippy::lossy_float_literal)] fn main()
let _: f64 = 16_777_217.0; let _: f64 = -16_777_217.0; let _: f64 = 9_007_199_254_740_992.0; let _: f64 = -9_007_199_254_740_992.0; // Ignored whole number float literals let _: f32 = 1e25; let _: f32 = 1E25; let _: f64 = 1e99; let _: f64 = 1E99; let _: f32 = 0.1; }
{ // Lossy whole-number float literals let _: f32 = 16_777_217.0; let _: f32 = 16_777_219.0; let _: f32 = 16_777_219.; let _: f32 = 16_777_219.000; let _ = 16_777_219f32; let _: f32 = -16_777_219.0; let _: f64 = 9_007_199_254_740_993.0; let _: f64 = 9_007_199_254_740_993.; let _: f64 = 9_007_199_254_740_993.00; let _ = 9_007_199_254_740_993f64; let _: f64 = -9_007_199_254_740_993.0; // Lossless whole number float literals let _: f32 = 16_777_216.0; let _: f32 = 16_777_218.0; let _: f32 = 16_777_220.0; let _: f32 = -16_777_216.0; let _: f32 = -16_777_220.0;
identifier_body
syscall_tests.rs
// TODO: Write a bunch more syscall-y tests to test that each syscall for each file/directory type // acts as we expect. use super::mount; use super::tests::digest_to_filepath; use crate::tests::make_dirs; use libc; use std::ffi::CString; use std::path::Path; use store::Store; use testutil::data::TestData; #[test] fn read_file_by_digest_exact_bytes() { let (store_dir, mount_dir) = make_dirs(); let runtime = task_executor::Executor::new(); let store = Store::local_only(runtime.clone(), store_dir.path()).expect("Error creating local store"); let test_bytes = TestData::roland(); runtime .block_on(store.store_file_bytes(test_bytes.bytes(), false)) .expect("Storing bytes"); let _fs = mount(mount_dir.path(), store, runtime).expect("Mounting"); let path = mount_dir .path() .join("digest") .join(digest_to_filepath(&test_bytes.digest())); let mut buf = make_buffer(test_bytes.len()); unsafe { let fd = libc::open(path_to_cstring(&path).as_ptr(), 0); assert!(fd > 0, "Bad fd {}", fd); let read_bytes = libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len()); assert_eq!(test_bytes.len() as isize, read_bytes); assert_eq!(0, libc::close(fd)); } assert_eq!(test_bytes.string(), String::from_utf8(buf).unwrap()); } fn path_to_cstring(path: &Path) -> CString { CString::new(path.to_string_lossy().as_bytes().to_owned()).unwrap() } fn make_buffer(size: usize) -> Vec<u8>
{ let mut buf: Vec<u8> = Vec::new(); buf.resize(size, 0); buf }
identifier_body
syscall_tests.rs
// TODO: Write a bunch more syscall-y tests to test that each syscall for each file/directory type // acts as we expect. use super::mount; use super::tests::digest_to_filepath; use crate::tests::make_dirs; use libc; use std::ffi::CString; use std::path::Path; use store::Store; use testutil::data::TestData; #[test] fn
() { let (store_dir, mount_dir) = make_dirs(); let runtime = task_executor::Executor::new(); let store = Store::local_only(runtime.clone(), store_dir.path()).expect("Error creating local store"); let test_bytes = TestData::roland(); runtime .block_on(store.store_file_bytes(test_bytes.bytes(), false)) .expect("Storing bytes"); let _fs = mount(mount_dir.path(), store, runtime).expect("Mounting"); let path = mount_dir .path() .join("digest") .join(digest_to_filepath(&test_bytes.digest())); let mut buf = make_buffer(test_bytes.len()); unsafe { let fd = libc::open(path_to_cstring(&path).as_ptr(), 0); assert!(fd > 0, "Bad fd {}", fd); let read_bytes = libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len()); assert_eq!(test_bytes.len() as isize, read_bytes); assert_eq!(0, libc::close(fd)); } assert_eq!(test_bytes.string(), String::from_utf8(buf).unwrap()); } fn path_to_cstring(path: &Path) -> CString { CString::new(path.to_string_lossy().as_bytes().to_owned()).unwrap() } fn make_buffer(size: usize) -> Vec<u8> { let mut buf: Vec<u8> = Vec::new(); buf.resize(size, 0); buf }
read_file_by_digest_exact_bytes
identifier_name