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
main.rs
const ASCII_A: u8 = b'A'; fn main() { let msg = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; let key = "VIGENERECIPHER"; let enc = vigenere(msg, key, true); let dec = vigenere(&enc, key, false); println!("msg: {}", msg); println!("key: {}", key); println!("enc: {}", enc); println!("dec: {}", dec); } fn vigenere(plaintext: &str, key: &str, encrypt: bool) -> String { let plaintext_bytes = to_sanitized_bytes(plaintext); let key_bytes = to_sanitized_bytes(key); let key_len = key_bytes.len(); let mut output = String::with_capacity(plaintext_bytes.len()); for (i, byte) in plaintext_bytes.iter().enumerate() { let c = *byte; let b = key_bytes[i % key_len]; let output_byte = if encrypt
else { dec_byte(c, b) }; output.push(output_byte as char); } output } fn to_sanitized_bytes(string: &str) -> Vec<u8> { string .chars() .filter(|&c| c.is_alphabetic()) .map(|c| c.to_ascii_uppercase() as u8) .collect::<Vec<u8>>() } fn enc_byte(m: u8, k: u8) -> u8 { ASCII_A + (m.wrapping_add(k).wrapping_sub(2 * (ASCII_A))) % 26 } fn dec_byte(c: u8, k: u8) -> u8 { ASCII_A + (c.wrapping_sub(k).wrapping_add(26)) % 26 } #[test] fn test_enc_dec() { let plaintext = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; let key = "VIGENERECIPHER"; let enc = vigenere(plaintext, key, true); assert_eq!( "WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY", enc ); let dec = vigenere(&enc, key, false); assert_eq!( "BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH", dec ); } #[test] fn test_equal_len_key_and_plaintext() { let plaintext = "VIGENERECIPHER"; let key = "REHPICERENEGIV"; // to be sure nobody breaks this test assert_eq!(plaintext.len(), key.len()); let enc = vigenere(plaintext, key, true); assert_eq!("MMNTVGVVGVTNMM", enc); let dec = vigenere(&enc, key, false); assert_eq!(plaintext, dec); } #[test] fn test_empty_string_enc_dec() { let enc = vigenere("", "", true); assert_eq!("", enc); let dec = vigenere("", "", false); assert_eq!("", dec); }
{ enc_byte(c, b) }
conditional_block
stat.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io::fs::PathExtensions; use std::io::{File, TempDir}; pub fn
() { let dir = TempDir::new_in(&Path::new("."), "").unwrap(); let path = dir.path().join("file"); { match File::create(&path) { Err(..) => unreachable!(), Ok(f) => { let mut f = f; for _ in range(0u, 1000) { f.write(&[0]); } } } } assert!(path.exists()); assert_eq!(path.stat().unwrap().size, 1000); }
main
identifier_name
stat.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io::fs::PathExtensions; use std::io::{File, TempDir}; pub fn main() { let dir = TempDir::new_in(&Path::new("."), "").unwrap(); let path = dir.path().join("file"); { match File::create(&path) { Err(..) => unreachable!(), Ok(f) =>
} } assert!(path.exists()); assert_eq!(path.stat().unwrap().size, 1000); }
{ let mut f = f; for _ in range(0u, 1000) { f.write(&[0]); } }
conditional_block
stat.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io::fs::PathExtensions; use std::io::{File, TempDir}; pub fn main() { let dir = TempDir::new_in(&Path::new("."), "").unwrap(); let path = dir.path().join("file"); { match File::create(&path) { Err(..) => unreachable!(), Ok(f) => { let mut f = f; for _ in range(0u, 1000) { f.write(&[0]); }
assert!(path.exists()); assert_eq!(path.stat().unwrap().size, 1000); }
} } }
random_line_split
stat.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io::fs::PathExtensions; use std::io::{File, TempDir}; pub fn main()
{ let dir = TempDir::new_in(&Path::new("."), "").unwrap(); let path = dir.path().join("file"); { match File::create(&path) { Err(..) => unreachable!(), Ok(f) => { let mut f = f; for _ in range(0u, 1000) { f.write(&[0]); } } } } assert!(path.exists()); assert_eq!(path.stat().unwrap().size, 1000); }
identifier_body
du.rs
(c) Derek Chiang <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate time; #[macro_use] extern crate uucore; use std::fs; use std::iter; use std::io::{stderr, Result, Write}; use std::os::unix::fs::MetadataExt; use std::path::PathBuf; use std::collections::HashSet; use time::Timespec; const NAME: &'static str = "du"; const SUMMARY: &'static str = "estimate file space usage"; const LONG_HELP: &'static str = " Display values are in units of the first available SIZE from --block-size, and the DU_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environ‐ ment variables. Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set). SIZE is an integer and optional unit (example: 10M is 10*1024*1024). Units are K, M, G, T, P, E, Z, Y (powers of 1024) or KB, MB,... (pow‐ ers of 1000). "; // TODO: Suport Z & Y (currently limited by size of u64) static UNITS: [(char, u32); 6] = [('E', 6), ('P', 5), ('T', 4), ('G', 3), ('M', 2), ('K', 1)]; struct Options { all: bool, program_name: String, max_depth: Option<usize>, total: bool, separate_dirs: bool, } struct Stat { path: PathBuf, is_dir: bool, size: u64, blocks: u64, nlink: u64, inode: u64, created: u64, accessed: u64, modified: u64, } impl Stat { fn new(path: PathBuf) -> Result<Stat> { let metadata = fs::symlink_metadata(&path)?; Ok(Stat { path: path, is_dir: metadata.is_dir(), size: metadata.len(), blocks: metadata.blocks() as u64, nlink: metadata.nlink() as u64, inode: metadata.ino() as u64, created: metadata.mtime() as u64, accessed: metadata.atime() as u64, modified: metadata.mtime() as u64, }) } } fn get_default_blocks() -> u64 { 1024 } // this takes `my_stat` to avoid having to stat files multiple times. // XXX: this should use the impl Trait return type when it is stabilized fn du( mut my_stat: Stat, options: &Options, depth: usize, inodes: &mut HashSet<u64>, ) -> Box<DoubleEndedIterator<Item = Stat>> {
Ok(entry) => match Stat::new(entry.path()) { Ok(this_stat) => { if this_stat.is_dir { futures.push(du(this_stat, options, depth + 1, inodes)); } else { if inodes.contains(&this_stat.inode) { continue; } inodes.insert(this_stat.inode); my_stat.size += this_stat.size; my_stat.blocks += this_stat.blocks; if options.all { stats.push(this_stat); } } } Err(error) => show_error!("{}", error), }, Err(error) => show_error!("{}", error), } } } stats.extend( futures .into_iter() .flat_map(|val| val) .rev() .filter_map(|stat| { if!options.separate_dirs && stat.path.parent().unwrap() == my_stat.path { my_stat.size += stat.size; my_stat.blocks += stat.blocks; } if options.max_depth == None || depth < options.max_depth.unwrap() { Some(stat) } else { None } }), ); stats.push(my_stat); Box::new(stats.into_iter()) } pub fn uumain(args: Vec<String>) -> i32 { let syntax = format!( "[OPTION]... [FILE]... {0} [OPTION]... --files0-from=F", NAME ); let matches = new_coreopts!(&syntax, SUMMARY, LONG_HELP) // In task .optflag("a", "all", " write counts for all files, not just directories") // In main .optflag("", "apparent-size", "print apparent sizes, rather than disk usage although the apparent size is usually smaller, it may be larger due to holes in ('sparse') files, internal fragmentation, indirect blocks, and the like") // In main .optopt("B", "block-size", "scale sizes by SIZE before printing them. E.g., '-BM' prints sizes in units of 1,048,576 bytes. See SIZE format below.", "SIZE") // In main .optflag("b", "bytes", "equivalent to '--apparent-size --block-size=1'") // In main .optflag("c", "total", "produce a grand total") // In task // opts.optflag("D", "dereference-args", "dereference only symlinks that are listed // on the command line"), // In main // opts.optopt("", "files0-from", "summarize disk usage of the NUL-terminated file // names specified in file F; // If F is - then read names from standard input", "F"), // // In task // opts.optflag("H", "", "equivalent to --dereference-args (-D)"), // In main .optflag("h", "human-readable", "print sizes in human readable format (e.g., 1K 234M 2G)") // In main .optflag("", "si", "like -h, but use powers of 1000 not 1024") // In main .optflag("k", "", "like --block-size=1K") // In task .optflag("l", "count-links", "count sizes many times if hard linked") // // In main .optflag("m", "", "like --block-size=1M") // // In task // opts.optflag("L", "dereference", "dereference all symbolic links"), // // In task // opts.optflag("P", "no-dereference", "don't follow any symbolic links (this is the default)"), // // In main .optflag("0", "null", "end each output line with 0 byte rather than newline") // In main .optflag("S", "separate-dirs", "do not include size of subdirectories") // In main .optflag("s", "summarize", "display only a total for each argument") // // In task // opts.optflag("x", "one-file-system", "skip directories on different file systems"), // // In task // opts.optopt("X", "exclude-from", "exclude files that match any pattern in FILE", "FILE"), // // In task // opts.optopt("", "exclude", "exclude files that match PATTERN", "PATTERN"), // In main .optopt("d", "max-depth", "print the total for a directory (or file, with --all) only if it is N or fewer levels below the command line argument; --max-depth=0 is the same as --summarize", "N") // In main .optflagopt("", "time", "show time of the last modification of any file in the directory, or any of its subdirectories. If WORD is given, show time as WORD instead of modification time: atime, access, use, ctime or status", "WORD") // In main .optopt("", "time-style", "show times using style STYLE: full-iso, long-iso, iso, +FORMAT FORMAT is interpreted like 'date'", "STYLE") .parse(args); let summarize = matches.opt_present("summarize"); let max_depth_str = matches.opt_str("max-depth"); let max_depth = max_depth_str.as_ref().and_then(|s| s.parse::<usize>().ok()); match (max_depth_str, max_depth) { (Some(ref s), _) if summarize => { show_error!("summarizing conflicts with --max-depth={}", *s); return 1; } (Some(ref s), None) => { show_error!("invalid maximum depth '{}'", *s); return 1; } (Some(_), Some(_)) | (None, _) => { /* valid */ } } let options = Options { all: matches.opt_present("all"), program_name: NAME.to_owned(), max_depth: max_depth, total: matches.opt_present("total"), separate_dirs: matches.opt_present("S"), }; let strs = if matches.free.is_empty() { vec!["./".to_owned()] } else { matches.free.clone() }; let block_size = match matches.opt_str("block-size") { Some(s) => { let mut found_number = false; let mut found_letter = false; let mut numbers = String::new(); let mut letters = String::new(); for c in s.chars() { if found_letter && c.is_digit(10) ||!found_number &&!c.is_digit(10) { show_error!("invalid --block-size argument '{}'", s); return 1; } else if c.is_digit(10) { found_number = true; numbers.push(c); } else if c.is_alphabetic() { found_letter = true; letters.push(c); } } let number = numbers.parse::<u64>().unwrap(); let multiple = match &letters[..] { "K" => 1024u64.pow(1), "M" => 1024u64.pow(2), "G" => 1024u64.pow(3), "T" => 1024u64.pow(4), "P" => 1024u64.pow(5), "E" => 1024u64.pow(6), "Z" => 1024u64.pow(7), "Y" => 1024u64.pow(8), "KB" => 1000u64.pow(1), "MB" => 1000u64.pow(2), "GB" => 1000u64.pow(3), "TB" => 1000u64.pow(4), "PB" => 1000u64.pow(5), "EB" => 1000u64.pow(6), "ZB" => 1000u64.pow(7), "YB" => 1000u64.pow(8), _ => { show_error!("invalid --block-size argument '{}'", s); return 1; } }; number * multiple } None => get_default_blocks(), }; let convert_size = |size: u64| -> String { let multiplier: u64 = if matches.opt_present("si") { 1000 } else { 1024 }; if matches.opt_present("human-readable") || matches.opt_present("si") { for &(unit, power) in &UNITS { let limit = multiplier.pow(power); if size >= limit { return format!("{:.1}{}", (size as f64) / (limit as f64), unit); } } return format!("{}B", size); } else if matches.opt_present("k") { format!("{}", ((size as f64) / (multiplier as f64)).ceil()) } else if matches.opt_present("m") { format!("{}", ((size as f64) / (multiplier.pow(2) as f64)).ceil()) } else { format!("{}", ((size as f64) / (block_size as f64)).ceil()) } }; let time_format_str = match matches.opt_str("time-style") { Some(s) => match &s[..] { "full-iso" => "%Y-%m-%d %H:%M:%S.%f %z", "long-iso" => "%Y-%m-%d %H:%M", "iso" => "%Y-%m-%d", _ => { show_error!( "invalid argument '{}' for 'time style' Valid arguments are: - 'full-iso' - 'long-iso' - 'iso' Try '{} --help' for more information.", s, NAME ); return 1; } }, None => "%Y-%m-%d %H:%M", }; let line_separator = if matches.opt_present("0") { "\0" } else { "\n" }; let mut grand_total = 0; for path_str in strs.into_iter() { let path = PathBuf::from(&path_str); match Stat::new(path) { Ok(stat) => { let mut inodes: HashSet<u64> = HashSet::new(); let iter = du(stat, &options, 0, &mut inodes).into_iter(); let (_, len) = iter.size_hint(); let len = len.unwrap(); for (index, stat) in iter.enumerate() { let size = if matches.opt_present("apparent-size") { stat.nlink * stat.size } else { // C's stat is such that each block is assume to be 512 bytes // See: http://linux.die.net/man/2/stat stat.blocks * 512 }; if matches.opt_present("time") { let tm = { let (secs, nsecs) = { let time = match matches.opt_str("time") { Some(s) => match &s[..] { "accessed" => stat.accessed, "created" => stat.created, "modified" => stat.modified, _ => { show_error!( "invalid argument'modified' for '--time' Valid arguments are: - 'accessed', 'created','modified' Try '{} --help' for more information.", NAME ); return 1; } }, None => stat.modified, }; ((time / 1000) as i64, (time % 1000 * 1000000) as i32) }; time::at(Timespec::new(secs, nsecs)) }; if!summarize || (summarize && index == len - 1) { let time_str = tm.strftime(time_format_str).unwrap(); print!( "{}\t{}\t{}{}", convert_size(size), time_str, stat.path.display(), line_separator ); } } else { if!summarize || (summarize && index == len - 1) { print!( "{}\t{}{}", convert_size(size), stat.path.display(), line_separator ); } } if options.total && index == (len - 1) { // The last element will be the total size of the the path under // path_str. We add it to the grand total. grand_total += size; } } } Err(_) => { show_error!("{}: {}", path_str, "No such file or directory");
let mut stats = vec![]; let mut futures = vec![]; if my_stat.is_dir { let read = match fs::read_dir(&my_stat.path) { Ok(read) => read, Err(e) => { safe_writeln!( stderr(), "{}: cannot read directory ‘{}‘: {}", options.program_name, my_stat.path.display(), e ); return Box::new(iter::once(my_stat)); } }; for f in read.into_iter() { match f {
identifier_body
du.rs
(c) Derek Chiang <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate time; #[macro_use] extern crate uucore; use std::fs; use std::iter; use std::io::{stderr, Result, Write}; use std::os::unix::fs::MetadataExt; use std::path::PathBuf; use std::collections::HashSet; use time::Timespec; const NAME: &'static str = "du"; const SUMMARY: &'static str = "estimate file space usage"; const LONG_HELP: &'static str = " Display values are in units of the first available SIZE from --block-size, and the DU_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environ‐ ment variables. Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set). SIZE is an integer and optional unit (example: 10M is 10*1024*1024). Units are K, M, G, T, P, E, Z, Y (powers of 1024) or KB, MB,... (pow‐ ers of 1000). "; // TODO: Suport Z & Y (currently limited by size of u64) static UNITS: [(char, u32); 6] = [('E', 6), ('P', 5), ('T', 4), ('G', 3), ('M', 2), ('K', 1)]; struct Options { all: bool, program_name: String, max_depth: Option<usize>, total: bool, separate_dirs: bool, } struct Stat { path: PathBuf, is_dir: bool, size: u64, blocks: u64, nlink: u64, inode: u64, created: u64, accessed: u64, modified: u64, } impl Stat { fn new(path: PathBuf) -> Result<Stat> { let metadata = fs::symlink_metadata(&path)?; Ok(Stat { path: path, is_dir: metadata.is_dir(), size: metadata.len(), blocks: metadata.blocks() as u64, nlink: metadata.nlink() as u64, inode: metadata.ino() as u64, created: metadata.mtime() as u64, accessed: metadata.atime() as u64, modified: metadata.mtime() as u64, }) } } fn get_default_blocks() -> u64 { 1024 } // this takes `my_stat` to avoid having to stat files multiple times. // XXX: this should use the impl Trait return type when it is stabilized fn du(
mut my_stat: Stat, options: &Options, depth: usize, inodes: &mut HashSet<u64>, ) -> Box<DoubleEndedIterator<Item = Stat>> { let mut stats = vec![]; let mut futures = vec![]; if my_stat.is_dir { let read = match fs::read_dir(&my_stat.path) { Ok(read) => read, Err(e) => { safe_writeln!( stderr(), "{}: cannot read directory ‘{}‘: {}", options.program_name, my_stat.path.display(), e ); return Box::new(iter::once(my_stat)); } }; for f in read.into_iter() { match f { Ok(entry) => match Stat::new(entry.path()) { Ok(this_stat) => { if this_stat.is_dir { futures.push(du(this_stat, options, depth + 1, inodes)); } else { if inodes.contains(&this_stat.inode) { continue; } inodes.insert(this_stat.inode); my_stat.size += this_stat.size; my_stat.blocks += this_stat.blocks; if options.all { stats.push(this_stat); } } } Err(error) => show_error!("{}", error), }, Err(error) => show_error!("{}", error), } } } stats.extend( futures .into_iter() .flat_map(|val| val) .rev() .filter_map(|stat| { if!options.separate_dirs && stat.path.parent().unwrap() == my_stat.path { my_stat.size += stat.size; my_stat.blocks += stat.blocks; } if options.max_depth == None || depth < options.max_depth.unwrap() { Some(stat) } else { None } }), ); stats.push(my_stat); Box::new(stats.into_iter()) } pub fn uumain(args: Vec<String>) -> i32 { let syntax = format!( "[OPTION]... [FILE]... {0} [OPTION]... --files0-from=F", NAME ); let matches = new_coreopts!(&syntax, SUMMARY, LONG_HELP) // In task .optflag("a", "all", " write counts for all files, not just directories") // In main .optflag("", "apparent-size", "print apparent sizes, rather than disk usage although the apparent size is usually smaller, it may be larger due to holes in ('sparse') files, internal fragmentation, indirect blocks, and the like") // In main .optopt("B", "block-size", "scale sizes by SIZE before printing them. E.g., '-BM' prints sizes in units of 1,048,576 bytes. See SIZE format below.", "SIZE") // In main .optflag("b", "bytes", "equivalent to '--apparent-size --block-size=1'") // In main .optflag("c", "total", "produce a grand total") // In task // opts.optflag("D", "dereference-args", "dereference only symlinks that are listed // on the command line"), // In main // opts.optopt("", "files0-from", "summarize disk usage of the NUL-terminated file // names specified in file F; // If F is - then read names from standard input", "F"), // // In task // opts.optflag("H", "", "equivalent to --dereference-args (-D)"), // In main .optflag("h", "human-readable", "print sizes in human readable format (e.g., 1K 234M 2G)") // In main .optflag("", "si", "like -h, but use powers of 1000 not 1024") // In main .optflag("k", "", "like --block-size=1K") // In task .optflag("l", "count-links", "count sizes many times if hard linked") // // In main .optflag("m", "", "like --block-size=1M") // // In task // opts.optflag("L", "dereference", "dereference all symbolic links"), // // In task // opts.optflag("P", "no-dereference", "don't follow any symbolic links (this is the default)"), // // In main .optflag("0", "null", "end each output line with 0 byte rather than newline") // In main .optflag("S", "separate-dirs", "do not include size of subdirectories") // In main .optflag("s", "summarize", "display only a total for each argument") // // In task // opts.optflag("x", "one-file-system", "skip directories on different file systems"), // // In task // opts.optopt("X", "exclude-from", "exclude files that match any pattern in FILE", "FILE"), // // In task // opts.optopt("", "exclude", "exclude files that match PATTERN", "PATTERN"), // In main .optopt("d", "max-depth", "print the total for a directory (or file, with --all) only if it is N or fewer levels below the command line argument; --max-depth=0 is the same as --summarize", "N") // In main .optflagopt("", "time", "show time of the last modification of any file in the directory, or any of its subdirectories. If WORD is given, show time as WORD instead of modification time: atime, access, use, ctime or status", "WORD") // In main .optopt("", "time-style", "show times using style STYLE: full-iso, long-iso, iso, +FORMAT FORMAT is interpreted like 'date'", "STYLE") .parse(args); let summarize = matches.opt_present("summarize"); let max_depth_str = matches.opt_str("max-depth"); let max_depth = max_depth_str.as_ref().and_then(|s| s.parse::<usize>().ok()); match (max_depth_str, max_depth) { (Some(ref s), _) if summarize => { show_error!("summarizing conflicts with --max-depth={}", *s); return 1; } (Some(ref s), None) => { show_error!("invalid maximum depth '{}'", *s); return 1; } (Some(_), Some(_)) | (None, _) => { /* valid */ } } let options = Options { all: matches.opt_present("all"), program_name: NAME.to_owned(), max_depth: max_depth, total: matches.opt_present("total"), separate_dirs: matches.opt_present("S"), }; let strs = if matches.free.is_empty() { vec!["./".to_owned()] } else { matches.free.clone() }; let block_size = match matches.opt_str("block-size") { Some(s) => { let mut found_number = false; let mut found_letter = false; let mut numbers = String::new(); let mut letters = String::new(); for c in s.chars() { if found_letter && c.is_digit(10) ||!found_number &&!c.is_digit(10) { show_error!("invalid --block-size argument '{}'", s); return 1; } else if c.is_digit(10) { found_number = true; numbers.push(c); } else if c.is_alphabetic() { found_letter = true; letters.push(c); } } let number = numbers.parse::<u64>().unwrap(); let multiple = match &letters[..] { "K" => 1024u64.pow(1), "M" => 1024u64.pow(2), "G" => 1024u64.pow(3), "T" => 1024u64.pow(4), "P" => 1024u64.pow(5), "E" => 1024u64.pow(6), "Z" => 1024u64.pow(7), "Y" => 1024u64.pow(8), "KB" => 1000u64.pow(1), "MB" => 1000u64.pow(2), "GB" => 1000u64.pow(3), "TB" => 1000u64.pow(4), "PB" => 1000u64.pow(5), "EB" => 1000u64.pow(6), "ZB" => 1000u64.pow(7), "YB" => 1000u64.pow(8), _ => { show_error!("invalid --block-size argument '{}'", s); return 1; } }; number * multiple } None => get_default_blocks(), }; let convert_size = |size: u64| -> String { let multiplier: u64 = if matches.opt_present("si") { 1000 } else { 1024 }; if matches.opt_present("human-readable") || matches.opt_present("si") { for &(unit, power) in &UNITS { let limit = multiplier.pow(power); if size >= limit { return format!("{:.1}{}", (size as f64) / (limit as f64), unit); } } return format!("{}B", size); } else if matches.opt_present("k") { format!("{}", ((size as f64) / (multiplier as f64)).ceil()) } else if matches.opt_present("m") { format!("{}", ((size as f64) / (multiplier.pow(2) as f64)).ceil()) } else { format!("{}", ((size as f64) / (block_size as f64)).ceil()) } }; let time_format_str = match matches.opt_str("time-style") { Some(s) => match &s[..] { "full-iso" => "%Y-%m-%d %H:%M:%S.%f %z", "long-iso" => "%Y-%m-%d %H:%M", "iso" => "%Y-%m-%d", _ => { show_error!( "invalid argument '{}' for 'time style' Valid arguments are: - 'full-iso' - 'long-iso' - 'iso' Try '{} --help' for more information.", s, NAME ); return 1; } }, None => "%Y-%m-%d %H:%M", }; let line_separator = if matches.opt_present("0") { "\0" } else { "\n" }; let mut grand_total = 0; for path_str in strs.into_iter() { let path = PathBuf::from(&path_str); match Stat::new(path) { Ok(stat) => { let mut inodes: HashSet<u64> = HashSet::new(); let iter = du(stat, &options, 0, &mut inodes).into_iter(); let (_, len) = iter.size_hint(); let len = len.unwrap(); for (index, stat) in iter.enumerate() { let size = if matches.opt_present("apparent-size") { stat.nlink * stat.size } else { // C's stat is such that each block is assume to be 512 bytes // See: http://linux.die.net/man/2/stat stat.blocks * 512 }; if matches.opt_present("time") { let tm = { let (secs, nsecs) = { let time = match matches.opt_str("time") { Some(s) => match &s[..] { "accessed" => stat.accessed, "created" => stat.created, "modified" => stat.modified, _ => { show_error!( "invalid argument'modified' for '--time' Valid arguments are: - 'accessed', 'created','modified' Try '{} --help' for more information.", NAME ); return 1; } }, None => stat.modified, }; ((time / 1000) as i64, (time % 1000 * 1000000) as i32) }; time::at(Timespec::new(secs, nsecs)) }; if!summarize || (summarize && index == len - 1) { let time_str = tm.strftime(time_format_str).unwrap(); print!( "{}\t{}\t{}{}", convert_size(size), time_str, stat.path.display(), line_separator ); } } else { if!summarize || (summarize && index == len - 1) { print!( "{}\t{}{}", convert_size(size), stat.path.display(), line_separator ); } } if options.total && index == (len - 1) { // The last element will be the total size of the the path under // path_str. We add it to the grand total. grand_total += size; } } } Err(_) => { show_error!("{}: {}", path_str, "No such file or directory");
identifier_name
du.rs
* (c) Derek Chiang <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate time; #[macro_use] extern crate uucore; use std::fs; use std::iter; use std::io::{stderr, Result, Write}; use std::os::unix::fs::MetadataExt; use std::path::PathBuf; use std::collections::HashSet; use time::Timespec; const NAME: &'static str = "du"; const SUMMARY: &'static str = "estimate file space usage"; const LONG_HELP: &'static str = " Display values are in units of the first available SIZE from --block-size, and the DU_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environ‐ ment variables. Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set). SIZE is an integer and optional unit (example: 10M is 10*1024*1024). Units are K, M, G, T, P, E, Z, Y (powers of 1024) or KB, MB,... (pow‐ ers of 1000). "; // TODO: Suport Z & Y (currently limited by size of u64) static UNITS: [(char, u32); 6] = [('E', 6), ('P', 5), ('T', 4), ('G', 3), ('M', 2), ('K', 1)]; struct Options { all: bool, program_name: String, max_depth: Option<usize>, total: bool, separate_dirs: bool, } struct Stat { path: PathBuf, is_dir: bool, size: u64, blocks: u64, nlink: u64, inode: u64,
} impl Stat { fn new(path: PathBuf) -> Result<Stat> { let metadata = fs::symlink_metadata(&path)?; Ok(Stat { path: path, is_dir: metadata.is_dir(), size: metadata.len(), blocks: metadata.blocks() as u64, nlink: metadata.nlink() as u64, inode: metadata.ino() as u64, created: metadata.mtime() as u64, accessed: metadata.atime() as u64, modified: metadata.mtime() as u64, }) } } fn get_default_blocks() -> u64 { 1024 } // this takes `my_stat` to avoid having to stat files multiple times. // XXX: this should use the impl Trait return type when it is stabilized fn du( mut my_stat: Stat, options: &Options, depth: usize, inodes: &mut HashSet<u64>, ) -> Box<DoubleEndedIterator<Item = Stat>> { let mut stats = vec![]; let mut futures = vec![]; if my_stat.is_dir { let read = match fs::read_dir(&my_stat.path) { Ok(read) => read, Err(e) => { safe_writeln!( stderr(), "{}: cannot read directory ‘{}‘: {}", options.program_name, my_stat.path.display(), e ); return Box::new(iter::once(my_stat)); } }; for f in read.into_iter() { match f { Ok(entry) => match Stat::new(entry.path()) { Ok(this_stat) => { if this_stat.is_dir { futures.push(du(this_stat, options, depth + 1, inodes)); } else { if inodes.contains(&this_stat.inode) { continue; } inodes.insert(this_stat.inode); my_stat.size += this_stat.size; my_stat.blocks += this_stat.blocks; if options.all { stats.push(this_stat); } } } Err(error) => show_error!("{}", error), }, Err(error) => show_error!("{}", error), } } } stats.extend( futures .into_iter() .flat_map(|val| val) .rev() .filter_map(|stat| { if!options.separate_dirs && stat.path.parent().unwrap() == my_stat.path { my_stat.size += stat.size; my_stat.blocks += stat.blocks; } if options.max_depth == None || depth < options.max_depth.unwrap() { Some(stat) } else { None } }), ); stats.push(my_stat); Box::new(stats.into_iter()) } pub fn uumain(args: Vec<String>) -> i32 { let syntax = format!( "[OPTION]... [FILE]... {0} [OPTION]... --files0-from=F", NAME ); let matches = new_coreopts!(&syntax, SUMMARY, LONG_HELP) // In task .optflag("a", "all", " write counts for all files, not just directories") // In main .optflag("", "apparent-size", "print apparent sizes, rather than disk usage although the apparent size is usually smaller, it may be larger due to holes in ('sparse') files, internal fragmentation, indirect blocks, and the like") // In main .optopt("B", "block-size", "scale sizes by SIZE before printing them. E.g., '-BM' prints sizes in units of 1,048,576 bytes. See SIZE format below.", "SIZE") // In main .optflag("b", "bytes", "equivalent to '--apparent-size --block-size=1'") // In main .optflag("c", "total", "produce a grand total") // In task // opts.optflag("D", "dereference-args", "dereference only symlinks that are listed // on the command line"), // In main // opts.optopt("", "files0-from", "summarize disk usage of the NUL-terminated file // names specified in file F; // If F is - then read names from standard input", "F"), // // In task // opts.optflag("H", "", "equivalent to --dereference-args (-D)"), // In main .optflag("h", "human-readable", "print sizes in human readable format (e.g., 1K 234M 2G)") // In main .optflag("", "si", "like -h, but use powers of 1000 not 1024") // In main .optflag("k", "", "like --block-size=1K") // In task .optflag("l", "count-links", "count sizes many times if hard linked") // // In main .optflag("m", "", "like --block-size=1M") // // In task // opts.optflag("L", "dereference", "dereference all symbolic links"), // // In task // opts.optflag("P", "no-dereference", "don't follow any symbolic links (this is the default)"), // // In main .optflag("0", "null", "end each output line with 0 byte rather than newline") // In main .optflag("S", "separate-dirs", "do not include size of subdirectories") // In main .optflag("s", "summarize", "display only a total for each argument") // // In task // opts.optflag("x", "one-file-system", "skip directories on different file systems"), // // In task // opts.optopt("X", "exclude-from", "exclude files that match any pattern in FILE", "FILE"), // // In task // opts.optopt("", "exclude", "exclude files that match PATTERN", "PATTERN"), // In main .optopt("d", "max-depth", "print the total for a directory (or file, with --all) only if it is N or fewer levels below the command line argument; --max-depth=0 is the same as --summarize", "N") // In main .optflagopt("", "time", "show time of the last modification of any file in the directory, or any of its subdirectories. If WORD is given, show time as WORD instead of modification time: atime, access, use, ctime or status", "WORD") // In main .optopt("", "time-style", "show times using style STYLE: full-iso, long-iso, iso, +FORMAT FORMAT is interpreted like 'date'", "STYLE") .parse(args); let summarize = matches.opt_present("summarize"); let max_depth_str = matches.opt_str("max-depth"); let max_depth = max_depth_str.as_ref().and_then(|s| s.parse::<usize>().ok()); match (max_depth_str, max_depth) { (Some(ref s), _) if summarize => { show_error!("summarizing conflicts with --max-depth={}", *s); return 1; } (Some(ref s), None) => { show_error!("invalid maximum depth '{}'", *s); return 1; } (Some(_), Some(_)) | (None, _) => { /* valid */ } } let options = Options { all: matches.opt_present("all"), program_name: NAME.to_owned(), max_depth: max_depth, total: matches.opt_present("total"), separate_dirs: matches.opt_present("S"), }; let strs = if matches.free.is_empty() { vec!["./".to_owned()] } else { matches.free.clone() }; let block_size = match matches.opt_str("block-size") { Some(s) => { let mut found_number = false; let mut found_letter = false; let mut numbers = String::new(); let mut letters = String::new(); for c in s.chars() { if found_letter && c.is_digit(10) ||!found_number &&!c.is_digit(10) { show_error!("invalid --block-size argument '{}'", s); return 1; } else if c.is_digit(10) { found_number = true; numbers.push(c); } else if c.is_alphabetic() { found_letter = true; letters.push(c); } } let number = numbers.parse::<u64>().unwrap(); let multiple = match &letters[..] { "K" => 1024u64.pow(1), "M" => 1024u64.pow(2), "G" => 1024u64.pow(3), "T" => 1024u64.pow(4), "P" => 1024u64.pow(5), "E" => 1024u64.pow(6), "Z" => 1024u64.pow(7), "Y" => 1024u64.pow(8), "KB" => 1000u64.pow(1), "MB" => 1000u64.pow(2), "GB" => 1000u64.pow(3), "TB" => 1000u64.pow(4), "PB" => 1000u64.pow(5), "EB" => 1000u64.pow(6), "ZB" => 1000u64.pow(7), "YB" => 1000u64.pow(8), _ => { show_error!("invalid --block-size argument '{}'", s); return 1; } }; number * multiple } None => get_default_blocks(), }; let convert_size = |size: u64| -> String { let multiplier: u64 = if matches.opt_present("si") { 1000 } else { 1024 }; if matches.opt_present("human-readable") || matches.opt_present("si") { for &(unit, power) in &UNITS { let limit = multiplier.pow(power); if size >= limit { return format!("{:.1}{}", (size as f64) / (limit as f64), unit); } } return format!("{}B", size); } else if matches.opt_present("k") { format!("{}", ((size as f64) / (multiplier as f64)).ceil()) } else if matches.opt_present("m") { format!("{}", ((size as f64) / (multiplier.pow(2) as f64)).ceil()) } else { format!("{}", ((size as f64) / (block_size as f64)).ceil()) } }; let time_format_str = match matches.opt_str("time-style") { Some(s) => match &s[..] { "full-iso" => "%Y-%m-%d %H:%M:%S.%f %z", "long-iso" => "%Y-%m-%d %H:%M", "iso" => "%Y-%m-%d", _ => { show_error!( "invalid argument '{}' for 'time style' Valid arguments are: - 'full-iso' - 'long-iso' - 'iso' Try '{} --help' for more information.", s, NAME ); return 1; } }, None => "%Y-%m-%d %H:%M", }; let line_separator = if matches.opt_present("0") { "\0" } else { "\n" }; let mut grand_total = 0; for path_str in strs.into_iter() { let path = PathBuf::from(&path_str); match Stat::new(path) { Ok(stat) => { let mut inodes: HashSet<u64> = HashSet::new(); let iter = du(stat, &options, 0, &mut inodes).into_iter(); let (_, len) = iter.size_hint(); let len = len.unwrap(); for (index, stat) in iter.enumerate() { let size = if matches.opt_present("apparent-size") { stat.nlink * stat.size } else { // C's stat is such that each block is assume to be 512 bytes // See: http://linux.die.net/man/2/stat stat.blocks * 512 }; if matches.opt_present("time") { let tm = { let (secs, nsecs) = { let time = match matches.opt_str("time") { Some(s) => match &s[..] { "accessed" => stat.accessed, "created" => stat.created, "modified" => stat.modified, _ => { show_error!( "invalid argument'modified' for '--time' Valid arguments are: - 'accessed', 'created','modified' Try '{} --help' for more information.", NAME ); return 1; } }, None => stat.modified, }; ((time / 1000) as i64, (time % 1000 * 1000000) as i32) }; time::at(Timespec::new(secs, nsecs)) }; if!summarize || (summarize && index == len - 1) { let time_str = tm.strftime(time_format_str).unwrap(); print!( "{}\t{}\t{}{}", convert_size(size), time_str, stat.path.display(), line_separator ); } } else { if!summarize || (summarize && index == len - 1) { print!( "{}\t{}{}", convert_size(size), stat.path.display(), line_separator ); } } if options.total && index == (len - 1) { // The last element will be the total size of the the path under // path_str. We add it to the grand total. grand_total += size; } } } Err(_) => { show_error!("{}: {}", path_str, "No such file or directory"); }
created: u64, accessed: u64, modified: u64,
random_line_split
du.rs
(c) Derek Chiang <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate time; #[macro_use] extern crate uucore; use std::fs; use std::iter; use std::io::{stderr, Result, Write}; use std::os::unix::fs::MetadataExt; use std::path::PathBuf; use std::collections::HashSet; use time::Timespec; const NAME: &'static str = "du"; const SUMMARY: &'static str = "estimate file space usage"; const LONG_HELP: &'static str = " Display values are in units of the first available SIZE from --block-size, and the DU_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environ‐ ment variables. Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set). SIZE is an integer and optional unit (example: 10M is 10*1024*1024). Units are K, M, G, T, P, E, Z, Y (powers of 1024) or KB, MB,... (pow‐ ers of 1000). "; // TODO: Suport Z & Y (currently limited by size of u64) static UNITS: [(char, u32); 6] = [('E', 6), ('P', 5), ('T', 4), ('G', 3), ('M', 2), ('K', 1)]; struct Options { all: bool, program_name: String, max_depth: Option<usize>, total: bool, separate_dirs: bool, } struct Stat { path: PathBuf, is_dir: bool, size: u64, blocks: u64, nlink: u64, inode: u64, created: u64, accessed: u64, modified: u64, } impl Stat { fn new(path: PathBuf) -> Result<Stat> { let metadata = fs::symlink_metadata(&path)?; Ok(Stat { path: path, is_dir: metadata.is_dir(), size: metadata.len(), blocks: metadata.blocks() as u64, nlink: metadata.nlink() as u64, inode: metadata.ino() as u64, created: metadata.mtime() as u64, accessed: metadata.atime() as u64, modified: metadata.mtime() as u64, }) } } fn get_default_blocks() -> u64 { 1024 } // this takes `my_stat` to avoid having to stat files multiple times. // XXX: this should use the impl Trait return type when it is stabilized fn du( mut my_stat: Stat, options: &Options, depth: usize, inodes: &mut HashSet<u64>, ) -> Box<DoubleEndedIterator<Item = Stat>> { let mut stats = vec![]; let mut futures = vec![]; if my_stat.is_dir { let read = match fs::read_dir(&my_stat.path) { Ok(read) => read, Err(e) => { safe_writeln!( stderr(), "{}: cannot read directory ‘{}‘: {}", options.program_name, my_stat.path.display(), e ); return Box::new(iter::once(my_stat)); } }; for f in read.into_iter() { match f { Ok(entry) => match Stat::new(entry.path()) { Ok(this_stat) => { if this_stat.is_dir { futures.push(du(this_stat, options, depth + 1, inodes)); } else { if inodes.contains(&this_stat.inode) { continue; } inodes.insert(this_stat.inode); my_stat.size += this_stat.size; my_stat.blocks += this_stat.blocks; if options.all { stats.push(this_stat); } } } Err(error) => show_error!("{}", error), }, Err(error) => show_error!("{}", error), } } } stats.extend( futures .into_iter() .flat_map(|val| val) .rev() .filter_map(|stat| { if!options.separate_dirs && stat.path.parent().unwrap() == my_stat.path { my_stat.size += stat.size; my_stat.blocks += stat.blocks; } if options.max_depth == None || depth < options.max_depth.unwrap() { Some(stat) } else { None } }), ); stats.push(my_stat); Box::new(stats.into_iter()) } pub fn uumain(args: Vec<String>) -> i32 { let syntax = format!( "[OPTION]... [FILE]... {0} [OPTION]... --files0-from=F", NAME ); let matches = new_coreopts!(&syntax, SUMMARY, LONG_HELP) // In task .optflag("a", "all", " write counts for all files, not just directories") // In main .optflag("", "apparent-size", "print apparent sizes, rather than disk usage although the apparent size is usually smaller, it may be larger due to holes in ('sparse') files, internal fragmentation, indirect blocks, and the like") // In main .optopt("B", "block-size", "scale sizes by SIZE before printing them. E.g., '-BM' prints sizes in units of 1,048,576 bytes. See SIZE format below.", "SIZE") // In main .optflag("b", "bytes", "equivalent to '--apparent-size --block-size=1'") // In main .optflag("c", "total", "produce a grand total") // In task // opts.optflag("D", "dereference-args", "dereference only symlinks that are listed // on the command line"), // In main // opts.optopt("", "files0-from", "summarize disk usage of the NUL-terminated file // names specified in file F; // If F is - then read names from standard input", "F"), // // In task // opts.optflag("H", "", "equivalent to --dereference-args (-D)"), // In main .optflag("h", "human-readable", "print sizes in human readable format (e.g., 1K 234M 2G)") // In main .optflag("", "si", "like -h, but use powers of 1000 not 1024") // In main .optflag("k", "", "like --block-size=1K") // In task .optflag("l", "count-links", "count sizes many times if hard linked") // // In main .optflag("m", "", "like --block-size=1M") // // In task // opts.optflag("L", "dereference", "dereference all symbolic links"), // // In task // opts.optflag("P", "no-dereference", "don't follow any symbolic links (this is the default)"), // // In main .optflag("0", "null", "end each output line with 0 byte rather than newline") // In main .optflag("S", "separate-dirs", "do not include size of subdirectories") // In main .optflag("s", "summarize", "display only a total for each argument") // // In task // opts.optflag("x", "one-file-system", "skip directories on different file systems"), // // In task // opts.optopt("X", "exclude-from", "exclude files that match any pattern in FILE", "FILE"), // // In task // opts.optopt("", "exclude", "exclude files that match PATTERN", "PATTERN"), // In main .optopt("d", "max-depth", "print the total for a directory (or file, with --all) only if it is N or fewer levels below the command line argument; --max-depth=0 is the same as --summarize", "N") // In main .optflagopt("", "time", "show time of the last modification of any file in the directory, or any of its subdirectories. If WORD is given, show time as WORD instead of modification time: atime, access, use, ctime or status", "WORD") // In main .optopt("", "time-style", "show times using style STYLE: full-iso, long-iso, iso, +FORMAT FORMAT is interpreted like 'date'", "STYLE") .parse(args); let summarize = matches.opt_present("summarize"); let max_depth_str = matches.opt_str("max-depth"); let max_depth = max_depth_str.as_ref().and_then(|s| s.parse::<usize>().ok()); match (max_depth_str, max_depth) { (Some(ref s), _) if summarize => { show_error!("summarizing conflicts with --max-depth={}", *s); return 1; } (Some(ref s), None) => { show_error!("invalid maximum depth '{}'", *s); return 1; } (Some(_), Some(_)) | (None, _) => { /* valid */ } } let options = Options { all: matches.opt_present("all"), program_name: NAME.to_owned(), max_depth: max_depth, total: matches.opt_present("total"), separate_dirs: matches.opt_present("S"), }; let strs = if matches.free.is_empty() { vec!["./".to_owned()] } else { matches.free.clone() }; let block_size = match matches.opt_str("block-size") { Some(s) => { let mut found_number = false; let mut found_letter = false; let mut numbers = String::new(); let mut letters = String::new(); for c in s.chars() { if found_letter && c.is_digit(10) ||!found_number &&!c.is_digit(10) { show_error!("invalid --block-size argument '{}'", s); return 1; } else if c.is_digit(10) { found_number = true; numbers.push(c); } else if c.is_alphabetic() { found_letter = true; letters.push(c); } } let number = numbers.parse::<u64>().unwrap(); let multiple = match &letters[..] { "K" => 1024u64.pow(1), "M" => 1024u64.pow(2), "G" => 1024u64.pow(3), "T" => 1024u64.pow(4), "P" => 1024u64.pow(5), "E" => 1024u64.pow(6), "Z" => 1024u64.pow(7), "Y" => 1024u64.pow(8), "KB" => 1000u64.pow(1), "MB" => 1000u64.pow(2), "GB" => 1000u64.pow(3), "TB" => 1000u64.pow(4), "PB" => 1000u64.pow(5), "EB" => 1000u64.pow(6), "ZB" => 1000u64.pow(7), "YB" => 1000u64.pow(8), _ => { show_error!("invalid --block-size argument '{}'", s); return 1; } }; number * multiple } None => get_default_blocks(), }; let convert_size = |size: u64| -> String { let multiplier: u64 = if matches.opt_present("si") { 1000 } else { 1024 }; if matches.opt_present("human-readable") || matches.opt_present("si") { for &(unit, power) in &UNITS { let limit = multiplier.pow(power); if size >= limit { return format!("{:.1}{}", (size as f64) / (limit as f64), unit); } } return format!("{}B", size); } else if matches.opt_present("k") { format!("{}", ((size as f64) / (multiplier as f64)).ceil()) } else if matches.opt_present("m") { format!("{}", ((size as f64) / (multiplier.pow(2) as f64)).ceil()) } else { format!("{}", ((size as f64) / (block_size as f64)).ceil()) } }; let time_format_str = match matches.opt_str("time-style") { Some(s) => match &s[..] { "full-iso" => "%Y-%m-%d %H:%M:%S.%f %z", "long-iso" => "%Y-%m-%d %H:%M", "iso" => "%Y-%m-%d", _ => { show_error!( "invalid argument '{}' for 'time style' Valid arguments are: - 'full-iso' - 'long-iso' - 'iso' Try '{} --help' for more information.", s, NAME ); return 1; } }, None => "%Y-%m-%d %H:%M", }; let line_separator = if matches.opt_present("0") { "\0" } else { "\n" }; let mut grand_total = 0; for path_str in strs.into_iter() { let path = PathBuf::from(&path_str); match Stat::new(path) { Ok(stat) => { let mut inodes: HashSet<u64> = HashSet::new(); let iter = du(stat, &options, 0, &mut inodes).into_iter(); let (_, len) = iter.size_hint(); let len = len.unwrap(); for (index, stat) in iter.enumerate() { let size = if matches.opt_present("apparent-size") { stat.nlink * stat.size } else { // C's stat is such that each block is assume to be 512 bytes // See: http://linux.die.net/man/2/stat stat.blocks * 512 }; if matches.opt_present("time") { let tm = { let (secs, nsecs) = { let time = match matches.opt_str("time") { Some(s) => match &s[..] { "accessed" => stat.accessed, "created" => stat.created, "modified" => stat.modified, _ => {
}, None => stat.modified, }; ((time / 1000) as i64, (time % 1000 * 1000000) as i32) }; time::at(Timespec::new(secs, nsecs)) }; if!summarize || (summarize && index == len - 1) { let time_str = tm.strftime(time_format_str).unwrap(); print!( "{}\t{}\t{}{}", convert_size(size), time_str, stat.path.display(), line_separator ); } } else { if!summarize || (summarize && index == len - 1) { print!( "{}\t{}{}", convert_size(size), stat.path.display(), line_separator ); } } if options.total && index == (len - 1) { // The last element will be the total size of the the path under // path_str. We add it to the grand total. grand_total += size; } } } Err(_) => { show_error!("{}: {}", path_str, "No such file or directory");
show_error!( "invalid argument 'modified' for '--time' Valid arguments are: - 'accessed', 'created', 'modified' Try '{} --help' for more information.", NAME ); return 1; }
conditional_block
tri6.rs
use russell_lab::{Matrix, Vector}; /// Defines a triangle with 6 nodes (quadratic edges) /// /// # Local IDs of nodes /// /// ```text /// s /// | /// 2, (0,1) /// | ', /// | ', /// | ', /// | ', /// 5 4, /// | ', /// | ', /// | ', /// | (0,0) ', (1,0) /// 0---------3---------1 ---- r /// ``` /// /// # Local IDs of edges /// /// ```text /// |\ /// | \
/// 2| \ /// | \ /// |_____\ /// 0 /// ``` pub struct Tri6 {} impl Tri6 { pub const NDIM: usize = 2; pub const NNODE: usize = 6; pub const NEDGE: usize = 3; pub const NFACE: usize = 0; pub const EDGE_NNODE: usize = 3; pub const FACE_NNODE: usize = 0; pub const FACE_NEDGE: usize = 0; #[rustfmt::skip] pub const EDGE_NODE_IDS: [[usize; Tri6::EDGE_NNODE]; Tri6::NEDGE] = [ [0, 1, 3], [1, 2, 4], [2, 0, 5], ]; #[rustfmt::skip] pub const NODE_REFERENCE_COORDS: [[f64; Tri6::NDIM]; Tri6::NNODE] = [ [0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [0.5, 0.0], [0.5, 0.5], [0.0, 0.5], ]; /// Computes the interpolation functions pub fn calc_interp(interp: &mut Vector, ksi: &[f64]) { let (r, s) = (ksi[0], ksi[1]); interp[0] = 1.0 - (r + s) * (3.0 - 2.0 * (r + s)); interp[1] = r * (2.0 * r - 1.0); interp[2] = s * (2.0 * s - 1.0); interp[3] = 4.0 * r * (1.0 - (r + s)); interp[4] = 4.0 * r * s; interp[5] = 4.0 * s * (1.0 - (r + s)); } /// Computes the derivatives of interpolation functions pub fn calc_deriv(deriv: &mut Matrix, ksi: &[f64]) { let (r, s) = (ksi[0], ksi[1]); deriv[0][0] = -3.0 + 4.0 * (r + s); deriv[1][0] = 4.0 * r - 1.0; deriv[2][0] = 0.0; deriv[3][0] = 4.0 - 8.0 * r - 4.0 * s; deriv[4][0] = 4.0 * s; deriv[5][0] = -4.0 * s; deriv[0][1] = -3.0 + 4.0 * (r + s); deriv[1][1] = 0.0; deriv[2][1] = 4.0 * s - 1.0; deriv[3][1] = -4.0 * r; deriv[4][1] = 4.0 * r; deriv[5][1] = 4.0 - 4.0 * r - 8.0 * s; } }
/// | \ 1
random_line_split
tri6.rs
use russell_lab::{Matrix, Vector}; /// Defines a triangle with 6 nodes (quadratic edges) /// /// # Local IDs of nodes /// /// ```text /// s /// | /// 2, (0,1) /// | ', /// | ', /// | ', /// | ', /// 5 4, /// | ', /// | ', /// | ', /// | (0,0) ', (1,0) /// 0---------3---------1 ---- r /// ``` /// /// # Local IDs of edges /// /// ```text /// |\ /// | \ /// | \ 1 /// 2| \ /// | \ /// |_____\ /// 0 /// ``` pub struct Tri6 {} impl Tri6 { pub const NDIM: usize = 2; pub const NNODE: usize = 6; pub const NEDGE: usize = 3; pub const NFACE: usize = 0; pub const EDGE_NNODE: usize = 3; pub const FACE_NNODE: usize = 0; pub const FACE_NEDGE: usize = 0; #[rustfmt::skip] pub const EDGE_NODE_IDS: [[usize; Tri6::EDGE_NNODE]; Tri6::NEDGE] = [ [0, 1, 3], [1, 2, 4], [2, 0, 5], ]; #[rustfmt::skip] pub const NODE_REFERENCE_COORDS: [[f64; Tri6::NDIM]; Tri6::NNODE] = [ [0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [0.5, 0.0], [0.5, 0.5], [0.0, 0.5], ]; /// Computes the interpolation functions pub fn
(interp: &mut Vector, ksi: &[f64]) { let (r, s) = (ksi[0], ksi[1]); interp[0] = 1.0 - (r + s) * (3.0 - 2.0 * (r + s)); interp[1] = r * (2.0 * r - 1.0); interp[2] = s * (2.0 * s - 1.0); interp[3] = 4.0 * r * (1.0 - (r + s)); interp[4] = 4.0 * r * s; interp[5] = 4.0 * s * (1.0 - (r + s)); } /// Computes the derivatives of interpolation functions pub fn calc_deriv(deriv: &mut Matrix, ksi: &[f64]) { let (r, s) = (ksi[0], ksi[1]); deriv[0][0] = -3.0 + 4.0 * (r + s); deriv[1][0] = 4.0 * r - 1.0; deriv[2][0] = 0.0; deriv[3][0] = 4.0 - 8.0 * r - 4.0 * s; deriv[4][0] = 4.0 * s; deriv[5][0] = -4.0 * s; deriv[0][1] = -3.0 + 4.0 * (r + s); deriv[1][1] = 0.0; deriv[2][1] = 4.0 * s - 1.0; deriv[3][1] = -4.0 * r; deriv[4][1] = 4.0 * r; deriv[5][1] = 4.0 - 4.0 * r - 8.0 * s; } }
calc_interp
identifier_name
lexical-scope-in-unconditional-loop.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // compile-flags:-g // gdb-command:rbreak zzz // gdb-command:run // FIRST ITERATION // gdb-command:finish // gdb-command:print x // gdb-check:$1 = 0 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$2 = 1 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$3 = 101 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$4 = 101 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$5 = -987 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$6 = 101 // gdb-command:continue // SECOND ITERATION // gdb-command:finish // gdb-command:print x // gdb-check:$7 = 1 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$8 = 2 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$9 = 102 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$10 = 102 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$11 = -987 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$12 = 102 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$13 = 2 // gdb-command:continue fn main() { let mut x = 0i; loop { if x >= 2 { break; } zzz(); sentinel(); x += 1; zzz(); sentinel(); // Shadow x let x = x + 100; zzz(); sentinel(); // open scope within loop's top level scope { zzz(); sentinel(); let x = -987i; zzz(); sentinel(); } // Check that we get the x before the inner scope again zzz(); sentinel(); } zzz(); sentinel(); }
fn sentinel() {()}
fn zzz() {()}
random_line_split
lexical-scope-in-unconditional-loop.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // compile-flags:-g // gdb-command:rbreak zzz // gdb-command:run // FIRST ITERATION // gdb-command:finish // gdb-command:print x // gdb-check:$1 = 0 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$2 = 1 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$3 = 101 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$4 = 101 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$5 = -987 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$6 = 101 // gdb-command:continue // SECOND ITERATION // gdb-command:finish // gdb-command:print x // gdb-check:$7 = 1 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$8 = 2 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$9 = 102 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$10 = 102 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$11 = -987 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$12 = 102 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$13 = 2 // gdb-command:continue fn main() { let mut x = 0i; loop { if x >= 2
zzz(); sentinel(); x += 1; zzz(); sentinel(); // Shadow x let x = x + 100; zzz(); sentinel(); // open scope within loop's top level scope { zzz(); sentinel(); let x = -987i; zzz(); sentinel(); } // Check that we get the x before the inner scope again zzz(); sentinel(); } zzz(); sentinel(); } fn zzz() {()} fn sentinel() {()}
{ break; }
conditional_block
lexical-scope-in-unconditional-loop.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // compile-flags:-g // gdb-command:rbreak zzz // gdb-command:run // FIRST ITERATION // gdb-command:finish // gdb-command:print x // gdb-check:$1 = 0 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$2 = 1 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$3 = 101 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$4 = 101 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$5 = -987 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$6 = 101 // gdb-command:continue // SECOND ITERATION // gdb-command:finish // gdb-command:print x // gdb-check:$7 = 1 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$8 = 2 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$9 = 102 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$10 = 102 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$11 = -987 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$12 = 102 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$13 = 2 // gdb-command:continue fn main() { let mut x = 0i; loop { if x >= 2 { break; } zzz(); sentinel(); x += 1; zzz(); sentinel(); // Shadow x let x = x + 100; zzz(); sentinel(); // open scope within loop's top level scope { zzz(); sentinel(); let x = -987i; zzz(); sentinel(); } // Check that we get the x before the inner scope again zzz(); sentinel(); } zzz(); sentinel(); } fn zzz() {()} fn
() {()}
sentinel
identifier_name
lexical-scope-in-unconditional-loop.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // compile-flags:-g // gdb-command:rbreak zzz // gdb-command:run // FIRST ITERATION // gdb-command:finish // gdb-command:print x // gdb-check:$1 = 0 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$2 = 1 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$3 = 101 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$4 = 101 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$5 = -987 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$6 = 101 // gdb-command:continue // SECOND ITERATION // gdb-command:finish // gdb-command:print x // gdb-check:$7 = 1 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$8 = 2 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$9 = 102 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$10 = 102 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$11 = -987 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$12 = 102 // gdb-command:continue // gdb-command:finish // gdb-command:print x // gdb-check:$13 = 2 // gdb-command:continue fn main() { let mut x = 0i; loop { if x >= 2 { break; } zzz(); sentinel(); x += 1; zzz(); sentinel(); // Shadow x let x = x + 100; zzz(); sentinel(); // open scope within loop's top level scope { zzz(); sentinel(); let x = -987i; zzz(); sentinel(); } // Check that we get the x before the inner scope again zzz(); sentinel(); } zzz(); sentinel(); } fn zzz() {()} fn sentinel()
{()}
identifier_body
util.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. #![allow(missing_copy_implementations)] use prelude::v1::*; use io::{self, Read, Write, ErrorKind}; /// Copies the entire contents of a reader into a writer. /// /// This function will continuously read data from `r` and then write it into /// `w` in a streaming fashion until `r` returns EOF. /// /// On success the total number of bytes that were copied from `r` to `w` is /// returned. /// /// # Errors /// /// This function will return an error immediately if any call to `read` or /// `write` returns an error. All instances of `ErrorKind::Interrupted` are /// handled by this function and the underlying operation is retried. pub fn copy<R: Read, W: Write>(r: &mut R, w: &mut W) -> io::Result<u64> { let mut buf = [0; super::DEFAULT_BUF_SIZE]; let mut written = 0; loop { let len = match r.read(&mut buf) { Ok(0) => return Ok(written), Ok(len) => len, Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => return Err(e), }; try!(w.write_all(&buf[..len])); written += len as u64; } } /// A reader which is always at EOF. pub struct Empty { _priv: () } /// Creates an instance of an empty reader. /// /// All reads from the returned reader will return `Ok(0)`. pub fn empty() -> Empty { Empty { _priv: () } } impl Read for Empty { fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) } } /// A reader which infinitely yields one byte. pub struct Repeat { byte: u8 } /// Creates an instance of a reader that infinitely repeats one byte. /// /// All reads from this reader will succeed by filling the specified buffer with /// the given byte. pub fn repeat(byte: u8) -> Repeat { Repeat { byte: byte } } impl Read for Repeat { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>
} /// A writer which will move data into the void. pub struct Sink { _priv: () } /// Creates an instance of a writer which will successfully consume all data. /// /// All calls to `write` on the returned instance will return `Ok(buf.len())` /// and the contents of the buffer will not be inspected. pub fn sink() -> Sink { Sink { _priv: () } } impl Write for Sink { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } #[cfg(test)] mod test { use prelude::v1::*; use io::prelude::*; use io::{sink, empty, repeat}; #[test] fn sink_sinks() { let mut s = sink(); assert_eq!(s.write(&[]), Ok(0)); assert_eq!(s.write(&[0]), Ok(1)); assert_eq!(s.write(&[0; 1024]), Ok(1024)); assert_eq!(s.by_ref().write(&[0; 1024]), Ok(1024)); } #[test] fn empty_reads() { let mut e = empty(); assert_eq!(e.read(&mut []), Ok(0)); assert_eq!(e.read(&mut [0]), Ok(0)); assert_eq!(e.read(&mut [0; 1024]), Ok(0)); assert_eq!(e.by_ref().read(&mut [0; 1024]), Ok(0)); } #[test] fn repeat_repeats() { let mut r = repeat(4); let mut b = [0; 1024]; assert_eq!(r.read(&mut b), Ok(1024)); assert!(b.iter().all(|b| *b == 4)); } #[test] fn take_some_bytes() { assert_eq!(repeat(4).take(100).bytes().count(), 100); assert_eq!(repeat(4).take(100).bytes().next(), Some(Ok(4))); assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20); } #[test] fn tee() { let mut buf = [0; 10]; { let mut ptr: &mut [u8] = &mut buf; assert_eq!(repeat(4).tee(&mut ptr).take(5).read(&mut [0; 10]), Ok(5)); } assert_eq!(buf, [4, 4, 4, 4, 4, 0, 0, 0, 0, 0]); } #[test] fn broadcast() { let mut buf1 = [0; 10]; let mut buf2 = [0; 10]; { let mut ptr1: &mut [u8] = &mut buf1; let mut ptr2: &mut [u8] = &mut buf2; assert_eq!((&mut ptr1).broadcast(&mut ptr2) .write(&[1, 2, 3]), Ok(3)); } assert_eq!(buf1, buf2); assert_eq!(buf1, [1, 2, 3, 0, 0, 0, 0, 0, 0, 0]); } }
{ for slot in buf.iter_mut() { *slot = self.byte; } Ok(buf.len()) }
identifier_body
util.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. #![allow(missing_copy_implementations)] use prelude::v1::*; use io::{self, Read, Write, ErrorKind}; /// Copies the entire contents of a reader into a writer. /// /// This function will continuously read data from `r` and then write it into /// `w` in a streaming fashion until `r` returns EOF. /// /// On success the total number of bytes that were copied from `r` to `w` is /// returned. /// /// # Errors /// /// This function will return an error immediately if any call to `read` or /// `write` returns an error. All instances of `ErrorKind::Interrupted` are /// handled by this function and the underlying operation is retried. pub fn copy<R: Read, W: Write>(r: &mut R, w: &mut W) -> io::Result<u64> { let mut buf = [0; super::DEFAULT_BUF_SIZE]; let mut written = 0; loop { let len = match r.read(&mut buf) { Ok(0) => return Ok(written), Ok(len) => len, Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => return Err(e), }; try!(w.write_all(&buf[..len])); written += len as u64; } } /// A reader which is always at EOF. pub struct Empty { _priv: () } /// Creates an instance of an empty reader. /// /// All reads from the returned reader will return `Ok(0)`. pub fn empty() -> Empty { Empty { _priv: () } } impl Read for Empty { fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) } } /// A reader which infinitely yields one byte. pub struct Repeat { byte: u8 } /// Creates an instance of a reader that infinitely repeats one byte. /// /// All reads from this reader will succeed by filling the specified buffer with /// the given byte. pub fn repeat(byte: u8) -> Repeat { Repeat { byte: byte } } impl Read for Repeat { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { for slot in buf.iter_mut() { *slot = self.byte; } Ok(buf.len()) } } /// A writer which will move data into the void. pub struct
{ _priv: () } /// Creates an instance of a writer which will successfully consume all data. /// /// All calls to `write` on the returned instance will return `Ok(buf.len())` /// and the contents of the buffer will not be inspected. pub fn sink() -> Sink { Sink { _priv: () } } impl Write for Sink { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } #[cfg(test)] mod test { use prelude::v1::*; use io::prelude::*; use io::{sink, empty, repeat}; #[test] fn sink_sinks() { let mut s = sink(); assert_eq!(s.write(&[]), Ok(0)); assert_eq!(s.write(&[0]), Ok(1)); assert_eq!(s.write(&[0; 1024]), Ok(1024)); assert_eq!(s.by_ref().write(&[0; 1024]), Ok(1024)); } #[test] fn empty_reads() { let mut e = empty(); assert_eq!(e.read(&mut []), Ok(0)); assert_eq!(e.read(&mut [0]), Ok(0)); assert_eq!(e.read(&mut [0; 1024]), Ok(0)); assert_eq!(e.by_ref().read(&mut [0; 1024]), Ok(0)); } #[test] fn repeat_repeats() { let mut r = repeat(4); let mut b = [0; 1024]; assert_eq!(r.read(&mut b), Ok(1024)); assert!(b.iter().all(|b| *b == 4)); } #[test] fn take_some_bytes() { assert_eq!(repeat(4).take(100).bytes().count(), 100); assert_eq!(repeat(4).take(100).bytes().next(), Some(Ok(4))); assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20); } #[test] fn tee() { let mut buf = [0; 10]; { let mut ptr: &mut [u8] = &mut buf; assert_eq!(repeat(4).tee(&mut ptr).take(5).read(&mut [0; 10]), Ok(5)); } assert_eq!(buf, [4, 4, 4, 4, 4, 0, 0, 0, 0, 0]); } #[test] fn broadcast() { let mut buf1 = [0; 10]; let mut buf2 = [0; 10]; { let mut ptr1: &mut [u8] = &mut buf1; let mut ptr2: &mut [u8] = &mut buf2; assert_eq!((&mut ptr1).broadcast(&mut ptr2) .write(&[1, 2, 3]), Ok(3)); } assert_eq!(buf1, buf2); assert_eq!(buf1, [1, 2, 3, 0, 0, 0, 0, 0, 0, 0]); } }
Sink
identifier_name
util.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. #![allow(missing_copy_implementations)] use prelude::v1::*; use io::{self, Read, Write, ErrorKind}; /// Copies the entire contents of a reader into a writer. /// /// This function will continuously read data from `r` and then write it into /// `w` in a streaming fashion until `r` returns EOF. /// /// On success the total number of bytes that were copied from `r` to `w` is /// returned. /// /// # Errors /// /// This function will return an error immediately if any call to `read` or /// `write` returns an error. All instances of `ErrorKind::Interrupted` are /// handled by this function and the underlying operation is retried. pub fn copy<R: Read, W: Write>(r: &mut R, w: &mut W) -> io::Result<u64> { let mut buf = [0; super::DEFAULT_BUF_SIZE]; let mut written = 0; loop { let len = match r.read(&mut buf) { Ok(0) => return Ok(written), Ok(len) => len, Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => return Err(e), }; try!(w.write_all(&buf[..len])); written += len as u64; } } /// A reader which is always at EOF. pub struct Empty { _priv: () } /// Creates an instance of an empty reader. /// /// All reads from the returned reader will return `Ok(0)`. pub fn empty() -> Empty { Empty { _priv: () } } impl Read for Empty { fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) } } /// A reader which infinitely yields one byte. pub struct Repeat { byte: u8 } /// Creates an instance of a reader that infinitely repeats one byte. /// /// All reads from this reader will succeed by filling the specified buffer with /// the given byte. pub fn repeat(byte: u8) -> Repeat { Repeat { byte: byte } } impl Read for Repeat { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { for slot in buf.iter_mut() { *slot = self.byte; } Ok(buf.len()) } } /// A writer which will move data into the void. pub struct Sink { _priv: () } /// Creates an instance of a writer which will successfully consume all data. /// /// All calls to `write` on the returned instance will return `Ok(buf.len())` /// and the contents of the buffer will not be inspected. pub fn sink() -> Sink { Sink { _priv: () } } impl Write for Sink { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } #[cfg(test)] mod test { use prelude::v1::*; use io::prelude::*; use io::{sink, empty, repeat}; #[test] fn sink_sinks() { let mut s = sink(); assert_eq!(s.write(&[]), Ok(0)); assert_eq!(s.write(&[0]), Ok(1)); assert_eq!(s.write(&[0; 1024]), Ok(1024)); assert_eq!(s.by_ref().write(&[0; 1024]), Ok(1024)); } #[test] fn empty_reads() { let mut e = empty(); assert_eq!(e.read(&mut []), Ok(0)); assert_eq!(e.read(&mut [0]), Ok(0)); assert_eq!(e.read(&mut [0; 1024]), Ok(0)); assert_eq!(e.by_ref().read(&mut [0; 1024]), Ok(0)); } #[test] fn repeat_repeats() { let mut r = repeat(4); let mut b = [0; 1024]; assert_eq!(r.read(&mut b), Ok(1024)); assert!(b.iter().all(|b| *b == 4)); } #[test] fn take_some_bytes() { assert_eq!(repeat(4).take(100).bytes().count(), 100); assert_eq!(repeat(4).take(100).bytes().next(), Some(Ok(4))); assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20); } #[test] fn tee() { let mut buf = [0; 10]; { let mut ptr: &mut [u8] = &mut buf; assert_eq!(repeat(4).tee(&mut ptr).take(5).read(&mut [0; 10]), Ok(5));
} assert_eq!(buf, [4, 4, 4, 4, 4, 0, 0, 0, 0, 0]); } #[test] fn broadcast() { let mut buf1 = [0; 10]; let mut buf2 = [0; 10]; { let mut ptr1: &mut [u8] = &mut buf1; let mut ptr2: &mut [u8] = &mut buf2; assert_eq!((&mut ptr1).broadcast(&mut ptr2) .write(&[1, 2, 3]), Ok(3)); } assert_eq!(buf1, buf2); assert_eq!(buf1, [1, 2, 3, 0, 0, 0, 0, 0, 0, 0]); } }
random_line_split
htmltablecolelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTableColElementBinding; use dom::bindings::codegen::InheritTypes::HTMLTableColElementDerived; use dom::bindings::js::{JSRef, Temporary};
use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] pub struct HTMLTableColElement { htmlelement: HTMLElement, } impl HTMLTableColElementDerived for EventTarget { fn is_htmltablecolelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableColElement))) } } impl HTMLTableColElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableColElement { HTMLTableColElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTableColElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTableColElement> { let element = HTMLTableColElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTableColElementBinding::Wrap) } }
use dom::document::Document; use dom::eventtarget::{EventTarget, EventTargetTypeId};
random_line_split
htmltablecolelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTableColElementBinding; use dom::bindings::codegen::InheritTypes::HTMLTableColElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] pub struct HTMLTableColElement { htmlelement: HTMLElement, } impl HTMLTableColElementDerived for EventTarget { fn is_htmltablecolelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableColElement))) } } impl HTMLTableColElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableColElement
#[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTableColElement> { let element = HTMLTableColElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTableColElementBinding::Wrap) } }
{ HTMLTableColElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTableColElement, localName, prefix, document) } }
identifier_body
htmltablecolelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTableColElementBinding; use dom::bindings::codegen::InheritTypes::HTMLTableColElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] pub struct HTMLTableColElement { htmlelement: HTMLElement, } impl HTMLTableColElementDerived for EventTarget { fn is_htmltablecolelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableColElement))) } } impl HTMLTableColElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableColElement { HTMLTableColElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTableColElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn
(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTableColElement> { let element = HTMLTableColElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTableColElementBinding::Wrap) } }
new
identifier_name
sodium.rs
extern crate errno; extern crate libc; extern crate serde; extern crate sodiumoxide; use domain::wallet::KeyDerivationMethod; use errors::prelude::*; use self::libc::{c_int, c_ulonglong, size_t}; use self::sodiumoxide::crypto::pwhash; pub const SALTBYTES: usize = pwhash::SALTBYTES; sodium_type!(Salt, pwhash::Salt, SALTBYTES); pub fn gen_salt() -> Salt { Salt(pwhash::gen_salt()) } pub fn pwhash<'a>(key: &'a mut [u8], passwd: &[u8], salt: &Salt, key_derivation_method: &KeyDerivationMethod) -> Result<&'a [u8], IndyError> { let (opslimit, memlimit) = unsafe { match key_derivation_method { KeyDerivationMethod::ARGON2I_MOD => (crypto_pwhash_argon2i_opslimit_moderate(), crypto_pwhash_argon2i_memlimit_moderate()), KeyDerivationMethod::ARGON2I_INT => (crypto_pwhash_argon2i_opslimit_interactive(), crypto_pwhash_argon2i_memlimit_interactive()), KeyDerivationMethod::RAW => return Err(IndyError::from_msg(IndyErrorKind::InvalidStructure, "RAW key derivation method is not acceptable")) } }; let alg = unsafe { crypto_pwhash_alg_argon2i13() }; let res = unsafe { crypto_pwhash(key.as_mut_ptr(), key.len() as c_ulonglong, passwd.as_ptr(), passwd.len() as c_ulonglong, (salt.0).0.as_ptr(), opslimit as c_ulonglong, memlimit, alg) }; if res == 0 { Ok(key) } else { Err(IndyError::from_msg(IndyErrorKind::InvalidState, "Sodium pwhash failed")) } } extern { fn crypto_pwhash_alg_argon2i13() -> c_int; fn crypto_pwhash_argon2i_opslimit_moderate() -> size_t; fn crypto_pwhash_argon2i_memlimit_moderate() -> size_t; fn crypto_pwhash_argon2i_opslimit_interactive() -> size_t; fn crypto_pwhash_argon2i_memlimit_interactive() -> size_t; fn crypto_pwhash(out: *mut u8, outlen: c_ulonglong, passwd: *const u8, passwdlen: c_ulonglong, salt: *const u8, // SODIUM_CRYPTO_PWHASH_SALTBYTES opslimit: c_ulonglong, memlimit: size_t, alg: c_int) -> c_int; } #[cfg(test)] mod tests { use rmp_serde; use super::*; #[test] fn get_salt_works() { let salt = gen_salt(); assert_eq!(salt[..].len(), SALTBYTES) } #[test] fn salt_serialize_deserialize_works() { let salt = gen_salt(); let serialized = rmp_serde::to_vec(&salt).unwrap(); let deserialized: Salt = rmp_serde::from_slice(&serialized).unwrap(); assert_eq!(serialized.len(), SALTBYTES + 2); assert_eq!(salt, deserialized) } #[test] fn pwhash_works() { let passwd = b"Correct Horse Battery Staple"; let mut key = [0u8; 64]; let salt = gen_salt(); let _key = pwhash(&mut key, passwd, &salt, &KeyDerivationMethod::ARGON2I_MOD).unwrap(); } #[test] fn pwhash_works_for_interactive_method() { let passwd = b"Correct Horse Battery Staple"; let salt = gen_salt(); let mut key = [0u8; 64]; let key_moderate = pwhash(&mut key, passwd, &salt, &KeyDerivationMethod::ARGON2I_MOD).unwrap(); let mut key = [0u8; 64]; let key_interactive = pwhash(&mut key, passwd, &salt, &KeyDerivationMethod::ARGON2I_INT).unwrap(); assert_ne!(key_moderate, key_interactive);
} }
random_line_split
sodium.rs
extern crate errno; extern crate libc; extern crate serde; extern crate sodiumoxide; use domain::wallet::KeyDerivationMethod; use errors::prelude::*; use self::libc::{c_int, c_ulonglong, size_t}; use self::sodiumoxide::crypto::pwhash; pub const SALTBYTES: usize = pwhash::SALTBYTES; sodium_type!(Salt, pwhash::Salt, SALTBYTES); pub fn gen_salt() -> Salt { Salt(pwhash::gen_salt()) } pub fn pwhash<'a>(key: &'a mut [u8], passwd: &[u8], salt: &Salt, key_derivation_method: &KeyDerivationMethod) -> Result<&'a [u8], IndyError> { let (opslimit, memlimit) = unsafe { match key_derivation_method { KeyDerivationMethod::ARGON2I_MOD => (crypto_pwhash_argon2i_opslimit_moderate(), crypto_pwhash_argon2i_memlimit_moderate()), KeyDerivationMethod::ARGON2I_INT => (crypto_pwhash_argon2i_opslimit_interactive(), crypto_pwhash_argon2i_memlimit_interactive()), KeyDerivationMethod::RAW => return Err(IndyError::from_msg(IndyErrorKind::InvalidStructure, "RAW key derivation method is not acceptable")) } }; let alg = unsafe { crypto_pwhash_alg_argon2i13() }; let res = unsafe { crypto_pwhash(key.as_mut_ptr(), key.len() as c_ulonglong, passwd.as_ptr(), passwd.len() as c_ulonglong, (salt.0).0.as_ptr(), opslimit as c_ulonglong, memlimit, alg) }; if res == 0 { Ok(key) } else
} extern { fn crypto_pwhash_alg_argon2i13() -> c_int; fn crypto_pwhash_argon2i_opslimit_moderate() -> size_t; fn crypto_pwhash_argon2i_memlimit_moderate() -> size_t; fn crypto_pwhash_argon2i_opslimit_interactive() -> size_t; fn crypto_pwhash_argon2i_memlimit_interactive() -> size_t; fn crypto_pwhash(out: *mut u8, outlen: c_ulonglong, passwd: *const u8, passwdlen: c_ulonglong, salt: *const u8, // SODIUM_CRYPTO_PWHASH_SALTBYTES opslimit: c_ulonglong, memlimit: size_t, alg: c_int) -> c_int; } #[cfg(test)] mod tests { use rmp_serde; use super::*; #[test] fn get_salt_works() { let salt = gen_salt(); assert_eq!(salt[..].len(), SALTBYTES) } #[test] fn salt_serialize_deserialize_works() { let salt = gen_salt(); let serialized = rmp_serde::to_vec(&salt).unwrap(); let deserialized: Salt = rmp_serde::from_slice(&serialized).unwrap(); assert_eq!(serialized.len(), SALTBYTES + 2); assert_eq!(salt, deserialized) } #[test] fn pwhash_works() { let passwd = b"Correct Horse Battery Staple"; let mut key = [0u8; 64]; let salt = gen_salt(); let _key = pwhash(&mut key, passwd, &salt, &KeyDerivationMethod::ARGON2I_MOD).unwrap(); } #[test] fn pwhash_works_for_interactive_method() { let passwd = b"Correct Horse Battery Staple"; let salt = gen_salt(); let mut key = [0u8; 64]; let key_moderate = pwhash(&mut key, passwd, &salt, &KeyDerivationMethod::ARGON2I_MOD).unwrap(); let mut key = [0u8; 64]; let key_interactive = pwhash(&mut key, passwd, &salt, &KeyDerivationMethod::ARGON2I_INT).unwrap(); assert_ne!(key_moderate, key_interactive); } }
{ Err(IndyError::from_msg(IndyErrorKind::InvalidState, "Sodium pwhash failed")) }
conditional_block
sodium.rs
extern crate errno; extern crate libc; extern crate serde; extern crate sodiumoxide; use domain::wallet::KeyDerivationMethod; use errors::prelude::*; use self::libc::{c_int, c_ulonglong, size_t}; use self::sodiumoxide::crypto::pwhash; pub const SALTBYTES: usize = pwhash::SALTBYTES; sodium_type!(Salt, pwhash::Salt, SALTBYTES); pub fn gen_salt() -> Salt { Salt(pwhash::gen_salt()) } pub fn pwhash<'a>(key: &'a mut [u8], passwd: &[u8], salt: &Salt, key_derivation_method: &KeyDerivationMethod) -> Result<&'a [u8], IndyError> { let (opslimit, memlimit) = unsafe { match key_derivation_method { KeyDerivationMethod::ARGON2I_MOD => (crypto_pwhash_argon2i_opslimit_moderate(), crypto_pwhash_argon2i_memlimit_moderate()), KeyDerivationMethod::ARGON2I_INT => (crypto_pwhash_argon2i_opslimit_interactive(), crypto_pwhash_argon2i_memlimit_interactive()), KeyDerivationMethod::RAW => return Err(IndyError::from_msg(IndyErrorKind::InvalidStructure, "RAW key derivation method is not acceptable")) } }; let alg = unsafe { crypto_pwhash_alg_argon2i13() }; let res = unsafe { crypto_pwhash(key.as_mut_ptr(), key.len() as c_ulonglong, passwd.as_ptr(), passwd.len() as c_ulonglong, (salt.0).0.as_ptr(), opslimit as c_ulonglong, memlimit, alg) }; if res == 0 { Ok(key) } else { Err(IndyError::from_msg(IndyErrorKind::InvalidState, "Sodium pwhash failed")) } } extern { fn crypto_pwhash_alg_argon2i13() -> c_int; fn crypto_pwhash_argon2i_opslimit_moderate() -> size_t; fn crypto_pwhash_argon2i_memlimit_moderate() -> size_t; fn crypto_pwhash_argon2i_opslimit_interactive() -> size_t; fn crypto_pwhash_argon2i_memlimit_interactive() -> size_t; fn crypto_pwhash(out: *mut u8, outlen: c_ulonglong, passwd: *const u8, passwdlen: c_ulonglong, salt: *const u8, // SODIUM_CRYPTO_PWHASH_SALTBYTES opslimit: c_ulonglong, memlimit: size_t, alg: c_int) -> c_int; } #[cfg(test)] mod tests { use rmp_serde; use super::*; #[test] fn get_salt_works()
#[test] fn salt_serialize_deserialize_works() { let salt = gen_salt(); let serialized = rmp_serde::to_vec(&salt).unwrap(); let deserialized: Salt = rmp_serde::from_slice(&serialized).unwrap(); assert_eq!(serialized.len(), SALTBYTES + 2); assert_eq!(salt, deserialized) } #[test] fn pwhash_works() { let passwd = b"Correct Horse Battery Staple"; let mut key = [0u8; 64]; let salt = gen_salt(); let _key = pwhash(&mut key, passwd, &salt, &KeyDerivationMethod::ARGON2I_MOD).unwrap(); } #[test] fn pwhash_works_for_interactive_method() { let passwd = b"Correct Horse Battery Staple"; let salt = gen_salt(); let mut key = [0u8; 64]; let key_moderate = pwhash(&mut key, passwd, &salt, &KeyDerivationMethod::ARGON2I_MOD).unwrap(); let mut key = [0u8; 64]; let key_interactive = pwhash(&mut key, passwd, &salt, &KeyDerivationMethod::ARGON2I_INT).unwrap(); assert_ne!(key_moderate, key_interactive); } }
{ let salt = gen_salt(); assert_eq!(salt[..].len(), SALTBYTES) }
identifier_body
sodium.rs
extern crate errno; extern crate libc; extern crate serde; extern crate sodiumoxide; use domain::wallet::KeyDerivationMethod; use errors::prelude::*; use self::libc::{c_int, c_ulonglong, size_t}; use self::sodiumoxide::crypto::pwhash; pub const SALTBYTES: usize = pwhash::SALTBYTES; sodium_type!(Salt, pwhash::Salt, SALTBYTES); pub fn gen_salt() -> Salt { Salt(pwhash::gen_salt()) } pub fn pwhash<'a>(key: &'a mut [u8], passwd: &[u8], salt: &Salt, key_derivation_method: &KeyDerivationMethod) -> Result<&'a [u8], IndyError> { let (opslimit, memlimit) = unsafe { match key_derivation_method { KeyDerivationMethod::ARGON2I_MOD => (crypto_pwhash_argon2i_opslimit_moderate(), crypto_pwhash_argon2i_memlimit_moderate()), KeyDerivationMethod::ARGON2I_INT => (crypto_pwhash_argon2i_opslimit_interactive(), crypto_pwhash_argon2i_memlimit_interactive()), KeyDerivationMethod::RAW => return Err(IndyError::from_msg(IndyErrorKind::InvalidStructure, "RAW key derivation method is not acceptable")) } }; let alg = unsafe { crypto_pwhash_alg_argon2i13() }; let res = unsafe { crypto_pwhash(key.as_mut_ptr(), key.len() as c_ulonglong, passwd.as_ptr(), passwd.len() as c_ulonglong, (salt.0).0.as_ptr(), opslimit as c_ulonglong, memlimit, alg) }; if res == 0 { Ok(key) } else { Err(IndyError::from_msg(IndyErrorKind::InvalidState, "Sodium pwhash failed")) } } extern { fn crypto_pwhash_alg_argon2i13() -> c_int; fn crypto_pwhash_argon2i_opslimit_moderate() -> size_t; fn crypto_pwhash_argon2i_memlimit_moderate() -> size_t; fn crypto_pwhash_argon2i_opslimit_interactive() -> size_t; fn crypto_pwhash_argon2i_memlimit_interactive() -> size_t; fn crypto_pwhash(out: *mut u8, outlen: c_ulonglong, passwd: *const u8, passwdlen: c_ulonglong, salt: *const u8, // SODIUM_CRYPTO_PWHASH_SALTBYTES opslimit: c_ulonglong, memlimit: size_t, alg: c_int) -> c_int; } #[cfg(test)] mod tests { use rmp_serde; use super::*; #[test] fn get_salt_works() { let salt = gen_salt(); assert_eq!(salt[..].len(), SALTBYTES) } #[test] fn
() { let salt = gen_salt(); let serialized = rmp_serde::to_vec(&salt).unwrap(); let deserialized: Salt = rmp_serde::from_slice(&serialized).unwrap(); assert_eq!(serialized.len(), SALTBYTES + 2); assert_eq!(salt, deserialized) } #[test] fn pwhash_works() { let passwd = b"Correct Horse Battery Staple"; let mut key = [0u8; 64]; let salt = gen_salt(); let _key = pwhash(&mut key, passwd, &salt, &KeyDerivationMethod::ARGON2I_MOD).unwrap(); } #[test] fn pwhash_works_for_interactive_method() { let passwd = b"Correct Horse Battery Staple"; let salt = gen_salt(); let mut key = [0u8; 64]; let key_moderate = pwhash(&mut key, passwd, &salt, &KeyDerivationMethod::ARGON2I_MOD).unwrap(); let mut key = [0u8; 64]; let key_interactive = pwhash(&mut key, passwd, &salt, &KeyDerivationMethod::ARGON2I_INT).unwrap(); assert_ne!(key_moderate, key_interactive); } }
salt_serialize_deserialize_works
identifier_name
cell.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/. */ //! A shareable mutable container for the DOM. use dom::bindings::trace::JSTraceable; use js::jsapi::{JSTracer}; use util::task_state; use util::task_state::SCRIPT; use std::cell::{BorrowState, RefCell, Ref, RefMut}; /// A mutable field in the DOM. /// /// This extends the API of `core::cell::RefCell` to allow unsafe access in /// certain situations, with dynamic checking in debug builds. #[derive(Clone, HeapSizeOf)] pub struct DOMRefCell<T> { value: RefCell<T>, } // Functionality specific to Servo's `DOMRefCell` type // =================================================== impl<T> DOMRefCell<T> { /// Return a reference to the contents. /// /// For use in the layout task only. #[allow(unsafe_code)] pub unsafe fn borrow_for_layout(&self) -> &T { debug_assert!(task_state::get().is_layout()); &*self.value.as_unsafe_cell().get() } /// Borrow the contents for the purpose of GC tracing. /// /// This succeeds even if the object is mutably borrowed, /// so you have to be careful in trace code! #[allow(unsafe_code)] pub unsafe fn borrow_for_gc_trace(&self) -> &T { // FIXME: IN_GC isn't reliable enough - doesn't catch minor GCs // https://github.com/servo/servo/issues/6389 //debug_assert!(task_state::get().contains(SCRIPT | IN_GC)); &*self.value.as_unsafe_cell().get() } /// Borrow the contents for the purpose of script deallocation. /// #[allow(unsafe_code)] pub unsafe fn borrow_for_script_deallocation(&self) -> &mut T { debug_assert!(task_state::get().contains(SCRIPT)); &mut *self.value.as_unsafe_cell().get() } /// Is the cell mutably borrowed? /// /// For safety checks in debug builds only. pub fn is_mutably_borrowed(&self) -> bool { self.value.borrow_state() == BorrowState::Writing } /// Attempts to immutably borrow the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time.
/// # Panics /// /// Panics if this is called off the script thread. pub fn try_borrow(&self) -> Option<Ref<T>> { debug_assert!(task_state::get().is_script()); match self.value.borrow_state() { BorrowState::Writing => None, _ => Some(self.value.borrow()), } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// Returns `None` if the value is currently borrowed. /// /// # Panics /// /// Panics if this is called off the script thread. pub fn try_borrow_mut(&self) -> Option<RefMut<T>> { debug_assert!(task_state::get().is_script()); match self.value.borrow_state() { BorrowState::Unused => Some(self.value.borrow_mut()), _ => None, } } } impl<T: JSTraceable> JSTraceable for DOMRefCell<T> { fn trace(&self, trc: *mut JSTracer) { unsafe { (*self).borrow_for_gc_trace().trace(trc) } } } // Functionality duplicated with `core::cell::RefCell` // =================================================== impl<T> DOMRefCell<T> { /// Create a new `DOMRefCell` containing `value`. pub fn new(value: T) -> DOMRefCell<T> { DOMRefCell { value: RefCell::new(value), } } /// Immutably borrows the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// # Panics /// /// Panics if this is called off the script thread. /// /// Panics if the value is currently mutably borrowed. pub fn borrow(&self) -> Ref<T> { self.try_borrow().expect("DOMRefCell<T> already mutably borrowed") } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// # Panics /// /// Panics if this is called off the script thread. /// /// Panics if the value is currently borrowed. pub fn borrow_mut(&self) -> RefMut<T> { self.try_borrow_mut().expect("DOMRefCell<T> already borrowed") } }
/// /// Returns `None` if the value is currently mutably borrowed. ///
random_line_split
cell.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/. */ //! A shareable mutable container for the DOM. use dom::bindings::trace::JSTraceable; use js::jsapi::{JSTracer}; use util::task_state; use util::task_state::SCRIPT; use std::cell::{BorrowState, RefCell, Ref, RefMut}; /// A mutable field in the DOM. /// /// This extends the API of `core::cell::RefCell` to allow unsafe access in /// certain situations, with dynamic checking in debug builds. #[derive(Clone, HeapSizeOf)] pub struct
<T> { value: RefCell<T>, } // Functionality specific to Servo's `DOMRefCell` type // =================================================== impl<T> DOMRefCell<T> { /// Return a reference to the contents. /// /// For use in the layout task only. #[allow(unsafe_code)] pub unsafe fn borrow_for_layout(&self) -> &T { debug_assert!(task_state::get().is_layout()); &*self.value.as_unsafe_cell().get() } /// Borrow the contents for the purpose of GC tracing. /// /// This succeeds even if the object is mutably borrowed, /// so you have to be careful in trace code! #[allow(unsafe_code)] pub unsafe fn borrow_for_gc_trace(&self) -> &T { // FIXME: IN_GC isn't reliable enough - doesn't catch minor GCs // https://github.com/servo/servo/issues/6389 //debug_assert!(task_state::get().contains(SCRIPT | IN_GC)); &*self.value.as_unsafe_cell().get() } /// Borrow the contents for the purpose of script deallocation. /// #[allow(unsafe_code)] pub unsafe fn borrow_for_script_deallocation(&self) -> &mut T { debug_assert!(task_state::get().contains(SCRIPT)); &mut *self.value.as_unsafe_cell().get() } /// Is the cell mutably borrowed? /// /// For safety checks in debug builds only. pub fn is_mutably_borrowed(&self) -> bool { self.value.borrow_state() == BorrowState::Writing } /// Attempts to immutably borrow the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// Returns `None` if the value is currently mutably borrowed. /// /// # Panics /// /// Panics if this is called off the script thread. pub fn try_borrow(&self) -> Option<Ref<T>> { debug_assert!(task_state::get().is_script()); match self.value.borrow_state() { BorrowState::Writing => None, _ => Some(self.value.borrow()), } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// Returns `None` if the value is currently borrowed. /// /// # Panics /// /// Panics if this is called off the script thread. pub fn try_borrow_mut(&self) -> Option<RefMut<T>> { debug_assert!(task_state::get().is_script()); match self.value.borrow_state() { BorrowState::Unused => Some(self.value.borrow_mut()), _ => None, } } } impl<T: JSTraceable> JSTraceable for DOMRefCell<T> { fn trace(&self, trc: *mut JSTracer) { unsafe { (*self).borrow_for_gc_trace().trace(trc) } } } // Functionality duplicated with `core::cell::RefCell` // =================================================== impl<T> DOMRefCell<T> { /// Create a new `DOMRefCell` containing `value`. pub fn new(value: T) -> DOMRefCell<T> { DOMRefCell { value: RefCell::new(value), } } /// Immutably borrows the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// # Panics /// /// Panics if this is called off the script thread. /// /// Panics if the value is currently mutably borrowed. pub fn borrow(&self) -> Ref<T> { self.try_borrow().expect("DOMRefCell<T> already mutably borrowed") } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// # Panics /// /// Panics if this is called off the script thread. /// /// Panics if the value is currently borrowed. pub fn borrow_mut(&self) -> RefMut<T> { self.try_borrow_mut().expect("DOMRefCell<T> already borrowed") } }
DOMRefCell
identifier_name
cell.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/. */ //! A shareable mutable container for the DOM. use dom::bindings::trace::JSTraceable; use js::jsapi::{JSTracer}; use util::task_state; use util::task_state::SCRIPT; use std::cell::{BorrowState, RefCell, Ref, RefMut}; /// A mutable field in the DOM. /// /// This extends the API of `core::cell::RefCell` to allow unsafe access in /// certain situations, with dynamic checking in debug builds. #[derive(Clone, HeapSizeOf)] pub struct DOMRefCell<T> { value: RefCell<T>, } // Functionality specific to Servo's `DOMRefCell` type // =================================================== impl<T> DOMRefCell<T> { /// Return a reference to the contents. /// /// For use in the layout task only. #[allow(unsafe_code)] pub unsafe fn borrow_for_layout(&self) -> &T { debug_assert!(task_state::get().is_layout()); &*self.value.as_unsafe_cell().get() } /// Borrow the contents for the purpose of GC tracing. /// /// This succeeds even if the object is mutably borrowed, /// so you have to be careful in trace code! #[allow(unsafe_code)] pub unsafe fn borrow_for_gc_trace(&self) -> &T { // FIXME: IN_GC isn't reliable enough - doesn't catch minor GCs // https://github.com/servo/servo/issues/6389 //debug_assert!(task_state::get().contains(SCRIPT | IN_GC)); &*self.value.as_unsafe_cell().get() } /// Borrow the contents for the purpose of script deallocation. /// #[allow(unsafe_code)] pub unsafe fn borrow_for_script_deallocation(&self) -> &mut T { debug_assert!(task_state::get().contains(SCRIPT)); &mut *self.value.as_unsafe_cell().get() } /// Is the cell mutably borrowed? /// /// For safety checks in debug builds only. pub fn is_mutably_borrowed(&self) -> bool { self.value.borrow_state() == BorrowState::Writing } /// Attempts to immutably borrow the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// Returns `None` if the value is currently mutably borrowed. /// /// # Panics /// /// Panics if this is called off the script thread. pub fn try_borrow(&self) -> Option<Ref<T>> { debug_assert!(task_state::get().is_script()); match self.value.borrow_state() { BorrowState::Writing => None, _ => Some(self.value.borrow()), } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// Returns `None` if the value is currently borrowed. /// /// # Panics /// /// Panics if this is called off the script thread. pub fn try_borrow_mut(&self) -> Option<RefMut<T>>
} impl<T: JSTraceable> JSTraceable for DOMRefCell<T> { fn trace(&self, trc: *mut JSTracer) { unsafe { (*self).borrow_for_gc_trace().trace(trc) } } } // Functionality duplicated with `core::cell::RefCell` // =================================================== impl<T> DOMRefCell<T> { /// Create a new `DOMRefCell` containing `value`. pub fn new(value: T) -> DOMRefCell<T> { DOMRefCell { value: RefCell::new(value), } } /// Immutably borrows the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// # Panics /// /// Panics if this is called off the script thread. /// /// Panics if the value is currently mutably borrowed. pub fn borrow(&self) -> Ref<T> { self.try_borrow().expect("DOMRefCell<T> already mutably borrowed") } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// # Panics /// /// Panics if this is called off the script thread. /// /// Panics if the value is currently borrowed. pub fn borrow_mut(&self) -> RefMut<T> { self.try_borrow_mut().expect("DOMRefCell<T> already borrowed") } }
{ debug_assert!(task_state::get().is_script()); match self.value.borrow_state() { BorrowState::Unused => Some(self.value.borrow_mut()), _ => None, } }
identifier_body
support.rs
#![no_std] #![allow(visible_private_types)] #![allow(non_camel_case_types)] extern "rust-intrinsic" { fn offset<T>(dst: *mut T, offset: int) -> *mut T; } extern "rust-intrinsic" { fn offset<T>(dst: *const T, offset: int) -> *const T; } type c_int = i32; #[no_mangle] pub extern "C" fn memcpy(dest: *mut u8, src: *const u8, n: int) { unsafe { let mut i = 0; while i < n { *(offset(dest, i) as *mut u8) = *(offset(src, i)); i += 1; } } } #[no_mangle] pub extern "C" fn memmove(dest: *mut u8, src: *const u8, n: int) { unsafe { if src < dest as *const u8 { // copy from end let mut i = n; while i!= 0 { i -= 1; *(offset(dest, i) as *mut u8) = *(offset(src, i)); } } else { // copy from beginning let mut i = 0; while i < n { *(offset(dest, i) as *mut u8) = *(offset(src, i)); i += 1; } } } } #[no_mangle] pub extern "C" fn memset(s: *mut u8, c: c_int, n: int) { unsafe { let mut i = 0; while i < n { *(offset(s, i) as *mut u8) = c as u8; i += 1;
} }
}
random_line_split
support.rs
#![no_std] #![allow(visible_private_types)] #![allow(non_camel_case_types)] extern "rust-intrinsic" { fn offset<T>(dst: *mut T, offset: int) -> *mut T; } extern "rust-intrinsic" { fn offset<T>(dst: *const T, offset: int) -> *const T; } type c_int = i32; #[no_mangle] pub extern "C" fn memcpy(dest: *mut u8, src: *const u8, n: int) { unsafe { let mut i = 0; while i < n { *(offset(dest, i) as *mut u8) = *(offset(src, i)); i += 1; } } } #[no_mangle] pub extern "C" fn memmove(dest: *mut u8, src: *const u8, n: int) { unsafe { if src < dest as *const u8 { // copy from end let mut i = n; while i!= 0 { i -= 1; *(offset(dest, i) as *mut u8) = *(offset(src, i)); } } else { // copy from beginning let mut i = 0; while i < n { *(offset(dest, i) as *mut u8) = *(offset(src, i)); i += 1; } } } } #[no_mangle] pub extern "C" fn memset(s: *mut u8, c: c_int, n: int)
{ unsafe { let mut i = 0; while i < n { *(offset(s, i) as *mut u8) = c as u8; i += 1; } } }
identifier_body
support.rs
#![no_std] #![allow(visible_private_types)] #![allow(non_camel_case_types)] extern "rust-intrinsic" { fn offset<T>(dst: *mut T, offset: int) -> *mut T; } extern "rust-intrinsic" { fn offset<T>(dst: *const T, offset: int) -> *const T; } type c_int = i32; #[no_mangle] pub extern "C" fn
(dest: *mut u8, src: *const u8, n: int) { unsafe { let mut i = 0; while i < n { *(offset(dest, i) as *mut u8) = *(offset(src, i)); i += 1; } } } #[no_mangle] pub extern "C" fn memmove(dest: *mut u8, src: *const u8, n: int) { unsafe { if src < dest as *const u8 { // copy from end let mut i = n; while i!= 0 { i -= 1; *(offset(dest, i) as *mut u8) = *(offset(src, i)); } } else { // copy from beginning let mut i = 0; while i < n { *(offset(dest, i) as *mut u8) = *(offset(src, i)); i += 1; } } } } #[no_mangle] pub extern "C" fn memset(s: *mut u8, c: c_int, n: int) { unsafe { let mut i = 0; while i < n { *(offset(s, i) as *mut u8) = c as u8; i += 1; } } }
memcpy
identifier_name
support.rs
#![no_std] #![allow(visible_private_types)] #![allow(non_camel_case_types)] extern "rust-intrinsic" { fn offset<T>(dst: *mut T, offset: int) -> *mut T; } extern "rust-intrinsic" { fn offset<T>(dst: *const T, offset: int) -> *const T; } type c_int = i32; #[no_mangle] pub extern "C" fn memcpy(dest: *mut u8, src: *const u8, n: int) { unsafe { let mut i = 0; while i < n { *(offset(dest, i) as *mut u8) = *(offset(src, i)); i += 1; } } } #[no_mangle] pub extern "C" fn memmove(dest: *mut u8, src: *const u8, n: int) { unsafe { if src < dest as *const u8
else { // copy from beginning let mut i = 0; while i < n { *(offset(dest, i) as *mut u8) = *(offset(src, i)); i += 1; } } } } #[no_mangle] pub extern "C" fn memset(s: *mut u8, c: c_int, n: int) { unsafe { let mut i = 0; while i < n { *(offset(s, i) as *mut u8) = c as u8; i += 1; } } }
{ // copy from end let mut i = n; while i != 0 { i -= 1; *(offset(dest, i) as *mut u8) = *(offset(src, i)); } }
conditional_block
main.rs
extern crate bf; extern crate clap; use std::io::prelude::*; use std::io::stdout; use std::fs::File; use bf::*; use clap::{Arg, App}; fn main() { let matches = App::new("bfi") .version("0.1.0") .author("David Barentt <[email protected]>") .about("A rust implementation of brainfuck") .arg(Arg::with_name("CODE").help("brainfuck code to execute")) .arg(Arg::with_name("FILE") .short("f") .help("brainfuck code to execute from file") .takes_value(true)) .arg(Arg::with_name("INPUT") .short("i") .long("input") .help("Read input from file instead of stdin") .takes_value(true)) .get_matches(); let code: String = if let Some(s) = matches.value_of("CODE") { // Always take code from ARGS over FILE s.to_string() } else { if let Some(f) = matches.value_of("FILE") { let mut s = String::new(); let mut file = match File::open(f) { Ok(fi) => fi, Err(e) =>
}; if let Err(e) = file.read_to_string(&mut s) { println!("Error while reading from `{}`: {}", f, e); return; } s } else { println!("{}", matches.usage()); return; } }; match BFProgram::parse(&code) { Ok(prog) => { if let Some(read) = matches.value_of("INPUT") { match File::open(read) { Ok(mut r) => prog.run_with(&mut r, &mut stdout()), Err(e) => { println!("Error while opening file `{}` {}", read, e); return; } } } else { prog.run(); } } Err(e) => println!("Error while parsing program: {}", e), } }
{ println!("Error while opening file `{}`: {}", f, e); return; }
conditional_block
main.rs
extern crate bf; extern crate clap; use std::io::prelude::*; use std::io::stdout; use std::fs::File; use bf::*; use clap::{Arg, App}; fn main() { let matches = App::new("bfi") .version("0.1.0") .author("David Barentt <[email protected]>") .about("A rust implementation of brainfuck") .arg(Arg::with_name("CODE").help("brainfuck code to execute")) .arg(Arg::with_name("FILE") .short("f") .help("brainfuck code to execute from file") .takes_value(true)) .arg(Arg::with_name("INPUT") .short("i") .long("input") .help("Read input from file instead of stdin") .takes_value(true)) .get_matches(); let code: String = if let Some(s) = matches.value_of("CODE") { // Always take code from ARGS over FILE s.to_string() } else { if let Some(f) = matches.value_of("FILE") { let mut s = String::new(); let mut file = match File::open(f) { Ok(fi) => fi, Err(e) => { println!("Error while opening file `{}`: {}", f, e); return; } }; if let Err(e) = file.read_to_string(&mut s) { println!("Error while reading from `{}`: {}", f, e); return; } s } else { println!("{}", matches.usage()); return; } }; match BFProgram::parse(&code) { Ok(prog) => { if let Some(read) = matches.value_of("INPUT") { match File::open(read) { Ok(mut r) => prog.run_with(&mut r, &mut stdout()), Err(e) => { println!("Error while opening file `{}` {}", read, e); return; } } } else { prog.run(); } } Err(e) => println!("Error while parsing program: {}", e),
}
}
random_line_split
main.rs
extern crate bf; extern crate clap; use std::io::prelude::*; use std::io::stdout; use std::fs::File; use bf::*; use clap::{Arg, App}; fn main()
} else { if let Some(f) = matches.value_of("FILE") { let mut s = String::new(); let mut file = match File::open(f) { Ok(fi) => fi, Err(e) => { println!("Error while opening file `{}`: {}", f, e); return; } }; if let Err(e) = file.read_to_string(&mut s) { println!("Error while reading from `{}`: {}", f, e); return; } s } else { println!("{}", matches.usage()); return; } }; match BFProgram::parse(&code) { Ok(prog) => { if let Some(read) = matches.value_of("INPUT") { match File::open(read) { Ok(mut r) => prog.run_with(&mut r, &mut stdout()), Err(e) => { println!("Error while opening file `{}` {}", read, e); return; } } } else { prog.run(); } } Err(e) => println!("Error while parsing program: {}", e), } }
{ let matches = App::new("bfi") .version("0.1.0") .author("David Barentt <[email protected]>") .about("A rust implementation of brainfuck") .arg(Arg::with_name("CODE").help("brainfuck code to execute")) .arg(Arg::with_name("FILE") .short("f") .help("brainfuck code to execute from file") .takes_value(true)) .arg(Arg::with_name("INPUT") .short("i") .long("input") .help("Read input from file instead of stdin") .takes_value(true)) .get_matches(); let code: String = if let Some(s) = matches.value_of("CODE") { // Always take code from ARGS over FILE s.to_string()
identifier_body
main.rs
extern crate bf; extern crate clap; use std::io::prelude::*; use std::io::stdout; use std::fs::File; use bf::*; use clap::{Arg, App}; fn
() { let matches = App::new("bfi") .version("0.1.0") .author("David Barentt <[email protected]>") .about("A rust implementation of brainfuck") .arg(Arg::with_name("CODE").help("brainfuck code to execute")) .arg(Arg::with_name("FILE") .short("f") .help("brainfuck code to execute from file") .takes_value(true)) .arg(Arg::with_name("INPUT") .short("i") .long("input") .help("Read input from file instead of stdin") .takes_value(true)) .get_matches(); let code: String = if let Some(s) = matches.value_of("CODE") { // Always take code from ARGS over FILE s.to_string() } else { if let Some(f) = matches.value_of("FILE") { let mut s = String::new(); let mut file = match File::open(f) { Ok(fi) => fi, Err(e) => { println!("Error while opening file `{}`: {}", f, e); return; } }; if let Err(e) = file.read_to_string(&mut s) { println!("Error while reading from `{}`: {}", f, e); return; } s } else { println!("{}", matches.usage()); return; } }; match BFProgram::parse(&code) { Ok(prog) => { if let Some(read) = matches.value_of("INPUT") { match File::open(read) { Ok(mut r) => prog.run_with(&mut r, &mut stdout()), Err(e) => { println!("Error while opening file `{}` {}", read, e); return; } } } else { prog.run(); } } Err(e) => println!("Error while parsing program: {}", e), } }
main
identifier_name
gc-vec.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::gc::{GC}; fn
() { // A fixed-size array allocated in a garbage-collected box let x = box(GC) [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]; assert_eq!(x[0], 1); assert_eq!(x[6], 7); assert_eq!(x[9], 10); let y = x; assert!(*y == [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]); }
main
identifier_name
gc-vec.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::gc::{GC}; fn main()
{ // A fixed-size array allocated in a garbage-collected box let x = box(GC) [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]; assert_eq!(x[0], 1); assert_eq!(x[6], 7); assert_eq!(x[9], 10); let y = x; assert!(*y == [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]); }
identifier_body
gc-vec.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::gc::{GC}; fn main() { // A fixed-size array allocated in a garbage-collected box let x = box(GC) [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]; assert_eq!(x[0], 1);
let y = x; assert!(*y == [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]); }
assert_eq!(x[6], 7); assert_eq!(x[9], 10);
random_line_split
to_url.rs
use url::{mod, Url, UrlParser}; pub trait ToUrl { fn to_url(self) -> Result<Url, String>; } impl ToUrl for Url { fn to_url(self) -> Result<Url, String> { Ok(self) } } impl<'a> ToUrl for &'a Url { fn to_url(self) -> Result<Url, String> { Ok(self.clone()) } } impl<'a> ToUrl for &'a str { fn to_url(self) -> Result<Url, String> { UrlParser::new().scheme_type_mapper(mapper).parse(self).map_err(|s| { format!("invalid url `{}`: {}", self, s) }) } } impl<'a> ToUrl for &'a Path { fn to_url(self) -> Result<Url, String> { Url::from_file_path(self).map_err(|()| { format!("invalid path url `{}`", self.display()) }) } } fn mapper(s: &str) -> url::SchemeType
{ match s { "git" => url::RelativeScheme(9418), "ssh" => url::RelativeScheme(22), s => url::whatwg_scheme_type_mapper(s), } }
identifier_body
to_url.rs
use url::{mod, Url, UrlParser}; pub trait ToUrl { fn to_url(self) -> Result<Url, String>; } impl ToUrl for Url { fn to_url(self) -> Result<Url, String> { Ok(self) } } impl<'a> ToUrl for &'a Url { fn to_url(self) -> Result<Url, String> { Ok(self.clone()) } }
} } impl<'a> ToUrl for &'a Path { fn to_url(self) -> Result<Url, String> { Url::from_file_path(self).map_err(|()| { format!("invalid path url `{}`", self.display()) }) } } fn mapper(s: &str) -> url::SchemeType { match s { "git" => url::RelativeScheme(9418), "ssh" => url::RelativeScheme(22), s => url::whatwg_scheme_type_mapper(s), } }
impl<'a> ToUrl for &'a str { fn to_url(self) -> Result<Url, String> { UrlParser::new().scheme_type_mapper(mapper).parse(self).map_err(|s| { format!("invalid url `{}`: {}", self, s) })
random_line_split
to_url.rs
use url::{mod, Url, UrlParser}; pub trait ToUrl { fn to_url(self) -> Result<Url, String>; } impl ToUrl for Url { fn to_url(self) -> Result<Url, String> { Ok(self) } } impl<'a> ToUrl for &'a Url { fn to_url(self) -> Result<Url, String> { Ok(self.clone()) } } impl<'a> ToUrl for &'a str { fn to_url(self) -> Result<Url, String> { UrlParser::new().scheme_type_mapper(mapper).parse(self).map_err(|s| { format!("invalid url `{}`: {}", self, s) }) } } impl<'a> ToUrl for &'a Path { fn
(self) -> Result<Url, String> { Url::from_file_path(self).map_err(|()| { format!("invalid path url `{}`", self.display()) }) } } fn mapper(s: &str) -> url::SchemeType { match s { "git" => url::RelativeScheme(9418), "ssh" => url::RelativeScheme(22), s => url::whatwg_scheme_type_mapper(s), } }
to_url
identifier_name
text.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Method %> <% data.new_style_struct("Text", inherited=False, gecko_name="TextReset", additional_methods=[Method("has_underline", "bool"), Method("has_overline", "bool"), Method("has_line_through", "bool")]) %> ${helpers.single_keyword("text-overflow", "clip ellipsis")} ${helpers.single_keyword("unicode-bidi", "normal embed isolate bidi-override isolate-override plaintext")} <%helpers:longhand name="text-decoration" custom_cascade="${product =='servo'}"> use cssparser::ToCss; use std::fmt; use values::computed::ComputedValueAsSpecified; impl ComputedValueAsSpecified for SpecifiedValue {} #[derive(PartialEq, Eq, Copy, Clone, Debug, HeapSizeOf)] pub struct SpecifiedValue { pub underline: bool, pub overline: bool, pub line_through: bool, // 'blink' is accepted in the parser but ignored. // Just not blinking the text is a conforming implementation per CSS 2.1. } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut space = false; if self.underline { try!(dest.write_str("underline")); space = true; } if self.overline { if space { try!(dest.write_str(" ")); } try!(dest.write_str("overline")); space = true; } if self.line_through { if space { try!(dest.write_str(" ")); } try!(dest.write_str("line-through")); } Ok(()) } } pub mod computed_value { pub type T = super::SpecifiedValue; #[allow(non_upper_case_globals)] pub const none: T = super::SpecifiedValue { underline: false, overline: false, line_through: false }; } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::none } /// none | [ underline || overline || line-through || blink ] pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { let mut result = SpecifiedValue { underline: false, overline: false, line_through: false, }; if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(result) } let mut blink = false; let mut empty = true; while let Ok(ident) = input.expect_ident() { match_ignore_ascii_case! { ident, "underline" => if result.underline { return Err(()) } else { empty = false; result.underline = true }, "overline" => if result.overline { return Err(()) } else { empty = false; result.overline = true }, "line-through" => if result.line_through { return Err(()) } else { empty = false; result.line_through = true }, "blink" => if blink { return Err(()) } else { empty = false; blink = true }, _ => break } } if!empty { Ok(result) } else { Err(()) } } % if product == "servo": fn cascade_property_custom<C: ComputedValues>( _declaration: &PropertyDeclaration, _inherited_style: &C, context: &mut computed::Context<C>, _seen: &mut PropertyBitField, _cacheable: &mut bool, _error_reporter: &mut StdBox<ParseErrorReporter + Send>)
% endif </%helpers:longhand> ${helpers.single_keyword("text-decoration-style", "-moz-none solid double dotted dashed wavy", products="gecko")} ${helpers.predefined_type( "text-decoration-color", "CSSColor", "CSSParserColor::RGBA(RGBA { red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0 })", products="gecko")}
{ longhands::_servo_text_decorations_in_effect::derive_from_text_decoration(context); }
identifier_body
text.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Method %> <% data.new_style_struct("Text", inherited=False, gecko_name="TextReset", additional_methods=[Method("has_underline", "bool"), Method("has_overline", "bool"), Method("has_line_through", "bool")]) %> ${helpers.single_keyword("text-overflow", "clip ellipsis")} ${helpers.single_keyword("unicode-bidi", "normal embed isolate bidi-override isolate-override plaintext")} <%helpers:longhand name="text-decoration" custom_cascade="${product =='servo'}"> use cssparser::ToCss; use std::fmt; use values::computed::ComputedValueAsSpecified; impl ComputedValueAsSpecified for SpecifiedValue {} #[derive(PartialEq, Eq, Copy, Clone, Debug, HeapSizeOf)] pub struct
{ pub underline: bool, pub overline: bool, pub line_through: bool, // 'blink' is accepted in the parser but ignored. // Just not blinking the text is a conforming implementation per CSS 2.1. } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut space = false; if self.underline { try!(dest.write_str("underline")); space = true; } if self.overline { if space { try!(dest.write_str(" ")); } try!(dest.write_str("overline")); space = true; } if self.line_through { if space { try!(dest.write_str(" ")); } try!(dest.write_str("line-through")); } Ok(()) } } pub mod computed_value { pub type T = super::SpecifiedValue; #[allow(non_upper_case_globals)] pub const none: T = super::SpecifiedValue { underline: false, overline: false, line_through: false }; } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::none } /// none | [ underline || overline || line-through || blink ] pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { let mut result = SpecifiedValue { underline: false, overline: false, line_through: false, }; if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(result) } let mut blink = false; let mut empty = true; while let Ok(ident) = input.expect_ident() { match_ignore_ascii_case! { ident, "underline" => if result.underline { return Err(()) } else { empty = false; result.underline = true }, "overline" => if result.overline { return Err(()) } else { empty = false; result.overline = true }, "line-through" => if result.line_through { return Err(()) } else { empty = false; result.line_through = true }, "blink" => if blink { return Err(()) } else { empty = false; blink = true }, _ => break } } if!empty { Ok(result) } else { Err(()) } } % if product == "servo": fn cascade_property_custom<C: ComputedValues>( _declaration: &PropertyDeclaration, _inherited_style: &C, context: &mut computed::Context<C>, _seen: &mut PropertyBitField, _cacheable: &mut bool, _error_reporter: &mut StdBox<ParseErrorReporter + Send>) { longhands::_servo_text_decorations_in_effect::derive_from_text_decoration(context); } % endif </%helpers:longhand> ${helpers.single_keyword("text-decoration-style", "-moz-none solid double dotted dashed wavy", products="gecko")} ${helpers.predefined_type( "text-decoration-color", "CSSColor", "CSSParserColor::RGBA(RGBA { red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0 })", products="gecko")}
SpecifiedValue
identifier_name
text.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Method %> <% data.new_style_struct("Text", inherited=False, gecko_name="TextReset", additional_methods=[Method("has_underline", "bool"), Method("has_overline", "bool"), Method("has_line_through", "bool")]) %> ${helpers.single_keyword("text-overflow", "clip ellipsis")} ${helpers.single_keyword("unicode-bidi", "normal embed isolate bidi-override isolate-override plaintext")} <%helpers:longhand name="text-decoration" custom_cascade="${product =='servo'}"> use cssparser::ToCss; use std::fmt; use values::computed::ComputedValueAsSpecified; impl ComputedValueAsSpecified for SpecifiedValue {} #[derive(PartialEq, Eq, Copy, Clone, Debug, HeapSizeOf)] pub struct SpecifiedValue { pub underline: bool, pub overline: bool, pub line_through: bool, // 'blink' is accepted in the parser but ignored. // Just not blinking the text is a conforming implementation per CSS 2.1. } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut space = false; if self.underline { try!(dest.write_str("underline")); space = true; } if self.overline { if space { try!(dest.write_str(" ")); } try!(dest.write_str("overline")); space = true; } if self.line_through { if space
try!(dest.write_str("line-through")); } Ok(()) } } pub mod computed_value { pub type T = super::SpecifiedValue; #[allow(non_upper_case_globals)] pub const none: T = super::SpecifiedValue { underline: false, overline: false, line_through: false }; } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::none } /// none | [ underline || overline || line-through || blink ] pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { let mut result = SpecifiedValue { underline: false, overline: false, line_through: false, }; if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(result) } let mut blink = false; let mut empty = true; while let Ok(ident) = input.expect_ident() { match_ignore_ascii_case! { ident, "underline" => if result.underline { return Err(()) } else { empty = false; result.underline = true }, "overline" => if result.overline { return Err(()) } else { empty = false; result.overline = true }, "line-through" => if result.line_through { return Err(()) } else { empty = false; result.line_through = true }, "blink" => if blink { return Err(()) } else { empty = false; blink = true }, _ => break } } if!empty { Ok(result) } else { Err(()) } } % if product == "servo": fn cascade_property_custom<C: ComputedValues>( _declaration: &PropertyDeclaration, _inherited_style: &C, context: &mut computed::Context<C>, _seen: &mut PropertyBitField, _cacheable: &mut bool, _error_reporter: &mut StdBox<ParseErrorReporter + Send>) { longhands::_servo_text_decorations_in_effect::derive_from_text_decoration(context); } % endif </%helpers:longhand> ${helpers.single_keyword("text-decoration-style", "-moz-none solid double dotted dashed wavy", products="gecko")} ${helpers.predefined_type( "text-decoration-color", "CSSColor", "CSSParserColor::RGBA(RGBA { red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0 })", products="gecko")}
{ try!(dest.write_str(" ")); }
conditional_block
text.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Method %> <% data.new_style_struct("Text", inherited=False, gecko_name="TextReset", additional_methods=[Method("has_underline", "bool"), Method("has_overline", "bool"), Method("has_line_through", "bool")]) %> ${helpers.single_keyword("text-overflow", "clip ellipsis")} ${helpers.single_keyword("unicode-bidi", "normal embed isolate bidi-override isolate-override plaintext")} <%helpers:longhand name="text-decoration" custom_cascade="${product =='servo'}"> use cssparser::ToCss; use std::fmt; use values::computed::ComputedValueAsSpecified; impl ComputedValueAsSpecified for SpecifiedValue {} #[derive(PartialEq, Eq, Copy, Clone, Debug, HeapSizeOf)] pub struct SpecifiedValue { pub underline: bool, pub overline: bool, pub line_through: bool, // 'blink' is accepted in the parser but ignored. // Just not blinking the text is a conforming implementation per CSS 2.1. } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut space = false; if self.underline { try!(dest.write_str("underline")); space = true; } if self.overline { if space { try!(dest.write_str(" ")); } try!(dest.write_str("overline")); space = true; } if self.line_through { if space { try!(dest.write_str(" ")); } try!(dest.write_str("line-through")); } Ok(()) } } pub mod computed_value { pub type T = super::SpecifiedValue; #[allow(non_upper_case_globals)] pub const none: T = super::SpecifiedValue { underline: false, overline: false, line_through: false }; } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::none } /// none | [ underline || overline || line-through || blink ] pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { let mut result = SpecifiedValue { underline: false, overline: false, line_through: false, }; if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(result) } let mut blink = false; let mut empty = true; while let Ok(ident) = input.expect_ident() { match_ignore_ascii_case! { ident, "underline" => if result.underline { return Err(()) } else { empty = false; result.underline = true }, "overline" => if result.overline { return Err(()) } else { empty = false; result.overline = true }, "line-through" => if result.line_through { return Err(()) } else { empty = false; result.line_through = true }, "blink" => if blink { return Err(()) } else { empty = false; blink = true }, _ => break
} % if product == "servo": fn cascade_property_custom<C: ComputedValues>( _declaration: &PropertyDeclaration, _inherited_style: &C, context: &mut computed::Context<C>, _seen: &mut PropertyBitField, _cacheable: &mut bool, _error_reporter: &mut StdBox<ParseErrorReporter + Send>) { longhands::_servo_text_decorations_in_effect::derive_from_text_decoration(context); } % endif </%helpers:longhand> ${helpers.single_keyword("text-decoration-style", "-moz-none solid double dotted dashed wavy", products="gecko")} ${helpers.predefined_type( "text-decoration-color", "CSSColor", "CSSParserColor::RGBA(RGBA { red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0 })", products="gecko")}
} } if !empty { Ok(result) } else { Err(()) }
random_line_split
eq.rs
use malachite_base_test_util::bench::bucketers::pair_rational_sequence_max_len_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::generators::unsigned_rational_sequence_pair_gen; use malachite_base_test_util::runner::Runner; pub(crate) fn register(runner: &mut Runner) { register_demo!(runner, demo_rational_sequence_eq); register_bench!(runner, benchmark_rational_sequence_eq); } fn demo_rational_sequence_eq(gm: GenMode, config: GenConfig, limit: usize) { for (xs, ys) in unsigned_rational_sequence_pair_gen::<u8>() .get(gm, &config) .take(limit) { if xs == ys
else { println!("{} ≠ {}", xs, ys); } } } #[allow(clippy::no_effect, unused_must_use)] fn benchmark_rational_sequence_eq(gm: GenMode, config: GenConfig, limit: usize, file_name: &str) { run_benchmark( "RationalSequence == RationalSequence", BenchmarkType::Single, unsigned_rational_sequence_pair_gen::<u8>().get(gm, &config), gm.name(), limit, file_name, &pair_rational_sequence_max_len_bucketer("xs", "ys"), &mut [("Malachite", &mut |(xs, ys)| no_out!(xs == ys))], ); }
{ println!("{} = {}", xs, ys); }
conditional_block
eq.rs
use malachite_base_test_util::bench::bucketers::pair_rational_sequence_max_len_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::generators::unsigned_rational_sequence_pair_gen; use malachite_base_test_util::runner::Runner; pub(crate) fn register(runner: &mut Runner) { register_demo!(runner, demo_rational_sequence_eq); register_bench!(runner, benchmark_rational_sequence_eq); } fn
(gm: GenMode, config: GenConfig, limit: usize) { for (xs, ys) in unsigned_rational_sequence_pair_gen::<u8>() .get(gm, &config) .take(limit) { if xs == ys { println!("{} = {}", xs, ys); } else { println!("{} ≠ {}", xs, ys); } } } #[allow(clippy::no_effect, unused_must_use)] fn benchmark_rational_sequence_eq(gm: GenMode, config: GenConfig, limit: usize, file_name: &str) { run_benchmark( "RationalSequence == RationalSequence", BenchmarkType::Single, unsigned_rational_sequence_pair_gen::<u8>().get(gm, &config), gm.name(), limit, file_name, &pair_rational_sequence_max_len_bucketer("xs", "ys"), &mut [("Malachite", &mut |(xs, ys)| no_out!(xs == ys))], ); }
demo_rational_sequence_eq
identifier_name
eq.rs
use malachite_base_test_util::bench::bucketers::pair_rational_sequence_max_len_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::generators::unsigned_rational_sequence_pair_gen; use malachite_base_test_util::runner::Runner; pub(crate) fn register(runner: &mut Runner) { register_demo!(runner, demo_rational_sequence_eq); register_bench!(runner, benchmark_rational_sequence_eq); }
if xs == ys { println!("{} = {}", xs, ys); } else { println!("{} ≠ {}", xs, ys); } } } #[allow(clippy::no_effect, unused_must_use)] fn benchmark_rational_sequence_eq(gm: GenMode, config: GenConfig, limit: usize, file_name: &str) { run_benchmark( "RationalSequence == RationalSequence", BenchmarkType::Single, unsigned_rational_sequence_pair_gen::<u8>().get(gm, &config), gm.name(), limit, file_name, &pair_rational_sequence_max_len_bucketer("xs", "ys"), &mut [("Malachite", &mut |(xs, ys)| no_out!(xs == ys))], ); }
fn demo_rational_sequence_eq(gm: GenMode, config: GenConfig, limit: usize) { for (xs, ys) in unsigned_rational_sequence_pair_gen::<u8>() .get(gm, &config) .take(limit) {
random_line_split
eq.rs
use malachite_base_test_util::bench::bucketers::pair_rational_sequence_max_len_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::generators::unsigned_rational_sequence_pair_gen; use malachite_base_test_util::runner::Runner; pub(crate) fn register(runner: &mut Runner) { register_demo!(runner, demo_rational_sequence_eq); register_bench!(runner, benchmark_rational_sequence_eq); } fn demo_rational_sequence_eq(gm: GenMode, config: GenConfig, limit: usize) { for (xs, ys) in unsigned_rational_sequence_pair_gen::<u8>() .get(gm, &config) .take(limit) { if xs == ys { println!("{} = {}", xs, ys); } else { println!("{} ≠ {}", xs, ys); } } } #[allow(clippy::no_effect, unused_must_use)] fn benchmark_rational_sequence_eq(gm: GenMode, config: GenConfig, limit: usize, file_name: &str) {
run_benchmark( "RationalSequence == RationalSequence", BenchmarkType::Single, unsigned_rational_sequence_pair_gen::<u8>().get(gm, &config), gm.name(), limit, file_name, &pair_rational_sequence_max_len_bucketer("xs", "ys"), &mut [("Malachite", &mut |(xs, ys)| no_out!(xs == ys))], ); }
identifier_body
main.rs
/// A genetic algorithm in Rust /// Copyright (C) 2015 Andrew Schwartzmeyer #[macro_use] extern crate clap; extern crate rand; extern crate time; use clap::{App, Arg}; use std::thread; mod algorithm; mod individual; mod problem; arg_enum!{ #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum Problem { Ackley, Griewangk, Rastrigin, Rosenbrock, Schwefel, Sphere } } #[derive(Debug, Copy, Clone)] pub struct Parameters { tolerance: f64, dimension: usize, population: usize, iterations: usize, selection: usize, elitism: usize, mutation: f64, crossover: f64, verbosity: usize } /// Setup and run algorithm to search for solution fn main() { let matches = App::new("rust-genetic-algorithm") .version(&crate_version!()[..]) .author("Andrew Schwartzmeyer <[email protected]>") .about("A genetic algorithm in Rust for various benchmark problems.") .arg(Arg::with_name("tolerance").short("t").long("tol").takes_value(true) .help("Sets the convergence tolerance (0.01)")) .arg(Arg::with_name("dimension").short("d").long("dim").takes_value(true) .help("Sets the dimension of the hypercube (30)")) .arg(Arg::with_name("population").short("p").long("pop").takes_value(true) .help("Sets the size of the population (512)")) .arg(Arg::with_name("iterations").short("i").long("iter").takes_value(true) .help("Sets maximum number of generations (10,000)")) .arg(Arg::with_name("selection").short("s").long("select").takes_value(true) .help("Sets the size of the tournament selection (4)")) .arg(Arg::with_name("elitism").short("e").long("elite").takes_value(true) .help("Sets the number of elite replacements (2)")) .arg(Arg::with_name("mutation").short("m").long("mut").takes_value(true) .help("Sets the chance of mutation (0.8)")) .arg(Arg::with_name("crossover").short("c").long("cross").takes_value(true) .help("Sets the chance of crossover (0.8)")) .arg(Arg::with_name("verbose").short("v").long("verbose").multiple(true) .help("Print fitness (1) and solution (2) every 10th generation")) .arg(Arg::with_name("problem").multiple(true) .help("The problems to solve: * Ackley * Griewangk * Rastrigin * Rosenbrock * Schwefel * Sphere")) .get_matches(); let problems = value_t!(matches.values_of("problem"), Problem) .unwrap_or(vec![Problem::Ackley, Problem::Griewangk, Problem::Rastrigin, Problem::Rosenbrock, Problem::Schwefel, Problem::Sphere]); let parameters = Parameters { tolerance: value_t!(matches.value_of("tolerance"), f64).unwrap_or(0.01_f64), dimension: value_t!(matches.value_of("dimension"), usize).unwrap_or(30), population: value_t!(matches.value_of("population"), usize).unwrap_or(512), iterations: value_t!(matches.value_of("iterations"), usize).unwrap_or(10000), selection: value_t!(matches.value_of("selection"), usize).unwrap_or(4), elitism: value_t!(matches.value_of("elitism"), usize).unwrap_or(2), mutation: value_t!(matches.value_of("mutation"), f64).unwrap_or(0.8_f64), crossover: value_t!(matches.value_of("crossover"), f64).unwrap_or(0.8_f64), verbosity: matches.occurrences_of("verbose") as usize }; let workers = problems.iter().map(|&problem| { thread::spawn(move || algorithm::search(problem, parameters)) }); for worker in workers { if let Ok(results) = worker.join()
} }
{ println!("{} converged to {} after {} generations in {} seconds.", results.problem, results.individual.fitness, results.iterations, results.duration); println!("{:?}", results.individual.solution); }
conditional_block
main.rs
/// A genetic algorithm in Rust /// Copyright (C) 2015 Andrew Schwartzmeyer #[macro_use] extern crate clap;
mod algorithm; mod individual; mod problem; arg_enum!{ #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum Problem { Ackley, Griewangk, Rastrigin, Rosenbrock, Schwefel, Sphere } } #[derive(Debug, Copy, Clone)] pub struct Parameters { tolerance: f64, dimension: usize, population: usize, iterations: usize, selection: usize, elitism: usize, mutation: f64, crossover: f64, verbosity: usize } /// Setup and run algorithm to search for solution fn main() { let matches = App::new("rust-genetic-algorithm") .version(&crate_version!()[..]) .author("Andrew Schwartzmeyer <[email protected]>") .about("A genetic algorithm in Rust for various benchmark problems.") .arg(Arg::with_name("tolerance").short("t").long("tol").takes_value(true) .help("Sets the convergence tolerance (0.01)")) .arg(Arg::with_name("dimension").short("d").long("dim").takes_value(true) .help("Sets the dimension of the hypercube (30)")) .arg(Arg::with_name("population").short("p").long("pop").takes_value(true) .help("Sets the size of the population (512)")) .arg(Arg::with_name("iterations").short("i").long("iter").takes_value(true) .help("Sets maximum number of generations (10,000)")) .arg(Arg::with_name("selection").short("s").long("select").takes_value(true) .help("Sets the size of the tournament selection (4)")) .arg(Arg::with_name("elitism").short("e").long("elite").takes_value(true) .help("Sets the number of elite replacements (2)")) .arg(Arg::with_name("mutation").short("m").long("mut").takes_value(true) .help("Sets the chance of mutation (0.8)")) .arg(Arg::with_name("crossover").short("c").long("cross").takes_value(true) .help("Sets the chance of crossover (0.8)")) .arg(Arg::with_name("verbose").short("v").long("verbose").multiple(true) .help("Print fitness (1) and solution (2) every 10th generation")) .arg(Arg::with_name("problem").multiple(true) .help("The problems to solve: * Ackley * Griewangk * Rastrigin * Rosenbrock * Schwefel * Sphere")) .get_matches(); let problems = value_t!(matches.values_of("problem"), Problem) .unwrap_or(vec![Problem::Ackley, Problem::Griewangk, Problem::Rastrigin, Problem::Rosenbrock, Problem::Schwefel, Problem::Sphere]); let parameters = Parameters { tolerance: value_t!(matches.value_of("tolerance"), f64).unwrap_or(0.01_f64), dimension: value_t!(matches.value_of("dimension"), usize).unwrap_or(30), population: value_t!(matches.value_of("population"), usize).unwrap_or(512), iterations: value_t!(matches.value_of("iterations"), usize).unwrap_or(10000), selection: value_t!(matches.value_of("selection"), usize).unwrap_or(4), elitism: value_t!(matches.value_of("elitism"), usize).unwrap_or(2), mutation: value_t!(matches.value_of("mutation"), f64).unwrap_or(0.8_f64), crossover: value_t!(matches.value_of("crossover"), f64).unwrap_or(0.8_f64), verbosity: matches.occurrences_of("verbose") as usize }; let workers = problems.iter().map(|&problem| { thread::spawn(move || algorithm::search(problem, parameters)) }); for worker in workers { if let Ok(results) = worker.join() { println!("{} converged to {} after {} generations in {} seconds.", results.problem, results.individual.fitness, results.iterations, results.duration); println!("{:?}", results.individual.solution); } } }
extern crate rand; extern crate time; use clap::{App, Arg}; use std::thread;
random_line_split
main.rs
/// A genetic algorithm in Rust /// Copyright (C) 2015 Andrew Schwartzmeyer #[macro_use] extern crate clap; extern crate rand; extern crate time; use clap::{App, Arg}; use std::thread; mod algorithm; mod individual; mod problem; arg_enum!{ #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum Problem { Ackley, Griewangk, Rastrigin, Rosenbrock, Schwefel, Sphere } } #[derive(Debug, Copy, Clone)] pub struct
{ tolerance: f64, dimension: usize, population: usize, iterations: usize, selection: usize, elitism: usize, mutation: f64, crossover: f64, verbosity: usize } /// Setup and run algorithm to search for solution fn main() { let matches = App::new("rust-genetic-algorithm") .version(&crate_version!()[..]) .author("Andrew Schwartzmeyer <[email protected]>") .about("A genetic algorithm in Rust for various benchmark problems.") .arg(Arg::with_name("tolerance").short("t").long("tol").takes_value(true) .help("Sets the convergence tolerance (0.01)")) .arg(Arg::with_name("dimension").short("d").long("dim").takes_value(true) .help("Sets the dimension of the hypercube (30)")) .arg(Arg::with_name("population").short("p").long("pop").takes_value(true) .help("Sets the size of the population (512)")) .arg(Arg::with_name("iterations").short("i").long("iter").takes_value(true) .help("Sets maximum number of generations (10,000)")) .arg(Arg::with_name("selection").short("s").long("select").takes_value(true) .help("Sets the size of the tournament selection (4)")) .arg(Arg::with_name("elitism").short("e").long("elite").takes_value(true) .help("Sets the number of elite replacements (2)")) .arg(Arg::with_name("mutation").short("m").long("mut").takes_value(true) .help("Sets the chance of mutation (0.8)")) .arg(Arg::with_name("crossover").short("c").long("cross").takes_value(true) .help("Sets the chance of crossover (0.8)")) .arg(Arg::with_name("verbose").short("v").long("verbose").multiple(true) .help("Print fitness (1) and solution (2) every 10th generation")) .arg(Arg::with_name("problem").multiple(true) .help("The problems to solve: * Ackley * Griewangk * Rastrigin * Rosenbrock * Schwefel * Sphere")) .get_matches(); let problems = value_t!(matches.values_of("problem"), Problem) .unwrap_or(vec![Problem::Ackley, Problem::Griewangk, Problem::Rastrigin, Problem::Rosenbrock, Problem::Schwefel, Problem::Sphere]); let parameters = Parameters { tolerance: value_t!(matches.value_of("tolerance"), f64).unwrap_or(0.01_f64), dimension: value_t!(matches.value_of("dimension"), usize).unwrap_or(30), population: value_t!(matches.value_of("population"), usize).unwrap_or(512), iterations: value_t!(matches.value_of("iterations"), usize).unwrap_or(10000), selection: value_t!(matches.value_of("selection"), usize).unwrap_or(4), elitism: value_t!(matches.value_of("elitism"), usize).unwrap_or(2), mutation: value_t!(matches.value_of("mutation"), f64).unwrap_or(0.8_f64), crossover: value_t!(matches.value_of("crossover"), f64).unwrap_or(0.8_f64), verbosity: matches.occurrences_of("verbose") as usize }; let workers = problems.iter().map(|&problem| { thread::spawn(move || algorithm::search(problem, parameters)) }); for worker in workers { if let Ok(results) = worker.join() { println!("{} converged to {} after {} generations in {} seconds.", results.problem, results.individual.fitness, results.iterations, results.duration); println!("{:?}", results.individual.solution); } } }
Parameters
identifier_name
bounds.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 ast::{MetaItem, MetaWord, Item}; use codemap::Span; use ext::base::ExtCtxt; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use ptr::P; pub fn expand_deriving_bound<F>(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: F) where F: FnOnce(P<Item>), { let name = match mitem.node { MetaWord(ref tname) => { match &tname[..] { "Copy" => "Copy", "Send" | "Sync" => {
should be implemented explicitly", *tname)) } ref tname => { cx.span_bug(span, &format!("expected built-in trait name but \ found {}", *tname)) } } }, _ => { return cx.span_err(span, "unexpected value in deriving, expected \ a trait") } }; let path = Path::new(vec![ if cx.use_std { "std" } else { "core" }, "marker", name ]); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path, additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: Vec::new(), associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) }
return cx.span_err(span, &format!("{} is an unsafe trait and it \
random_line_split
bounds.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 ast::{MetaItem, MetaWord, Item}; use codemap::Span; use ext::base::ExtCtxt; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use ptr::P; pub fn
<F>(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: F) where F: FnOnce(P<Item>), { let name = match mitem.node { MetaWord(ref tname) => { match &tname[..] { "Copy" => "Copy", "Send" | "Sync" => { return cx.span_err(span, &format!("{} is an unsafe trait and it \ should be implemented explicitly", *tname)) } ref tname => { cx.span_bug(span, &format!("expected built-in trait name but \ found {}", *tname)) } } }, _ => { return cx.span_err(span, "unexpected value in deriving, expected \ a trait") } }; let path = Path::new(vec![ if cx.use_std { "std" } else { "core" }, "marker", name ]); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path, additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: Vec::new(), associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) }
expand_deriving_bound
identifier_name
bounds.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 ast::{MetaItem, MetaWord, Item}; use codemap::Span; use ext::base::ExtCtxt; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use ptr::P; pub fn expand_deriving_bound<F>(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: F) where F: FnOnce(P<Item>),
a trait") } }; let path = Path::new(vec![ if cx.use_std { "std" } else { "core" }, "marker", name ]); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path, additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: Vec::new(), associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) }
{ let name = match mitem.node { MetaWord(ref tname) => { match &tname[..] { "Copy" => "Copy", "Send" | "Sync" => { return cx.span_err(span, &format!("{} is an unsafe trait and it \ should be implemented explicitly", *tname)) } ref tname => { cx.span_bug(span, &format!("expected built-in trait name but \ found {}", *tname)) } } }, _ => { return cx.span_err(span, "unexpected value in deriving, expected \
identifier_body
shootout-threadring.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. // Based on threadring.erlang by Jira Isa use std::os; fn start(n_tasks: int, token: int) { let (p, ch1) = stream(); let mut p = p; let mut ch1 = ch1; ch1.send(token); // XXX could not get this to work with a range closure let mut i = 2; while i <= n_tasks { let (next_p, ch) = stream(); let imm_i = i; let imm_p = p; do spawn { roundtrip(imm_i, n_tasks, &imm_p, &ch); }; p = next_p; i += 1; } let imm_p = p; let imm_ch = ch1; do spawn { roundtrip(1, n_tasks, &imm_p, &imm_ch); } } fn roundtrip(id: int, n_tasks: int, p: &Port<int>, ch: &Chan<int>) { while (true) { match p.recv() { 1 => { println(fmt!("%d\n", id)); return; } token => { debug!("thread: %d got token: %d", id, token); ch.send(token - 1); if token <= n_tasks { return; } } } } } fn main() { let args = if os::getenv(~"RUST_BENCH").is_some() { ~[~"", ~"2000000", ~"503"] } else { os::args() }; let token = if args.len() > 1u { FromStr::from_str(args[1]).get() } else
; let n_tasks = if args.len() > 2u { FromStr::from_str(args[2]).get() } else { 503 }; start(n_tasks, token); }
{ 1000 }
conditional_block
shootout-threadring.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. // Based on threadring.erlang by Jira Isa use std::os; fn start(n_tasks: int, token: int) { let (p, ch1) = stream(); let mut p = p; let mut ch1 = ch1; ch1.send(token); // XXX could not get this to work with a range closure let mut i = 2; while i <= n_tasks { let (next_p, ch) = stream(); let imm_i = i; let imm_p = p; do spawn { roundtrip(imm_i, n_tasks, &imm_p, &ch); }; p = next_p; i += 1; } let imm_p = p; let imm_ch = ch1; do spawn { roundtrip(1, n_tasks, &imm_p, &imm_ch); } } fn roundtrip(id: int, n_tasks: int, p: &Port<int>, ch: &Chan<int>)
fn main() { let args = if os::getenv(~"RUST_BENCH").is_some() { ~[~"", ~"2000000", ~"503"] } else { os::args() }; let token = if args.len() > 1u { FromStr::from_str(args[1]).get() } else { 1000 }; let n_tasks = if args.len() > 2u { FromStr::from_str(args[2]).get() } else { 503 }; start(n_tasks, token); }
{ while (true) { match p.recv() { 1 => { println(fmt!("%d\n", id)); return; } token => { debug!("thread: %d got token: %d", id, token); ch.send(token - 1); if token <= n_tasks { return; } } } } }
identifier_body
shootout-threadring.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. // Based on threadring.erlang by Jira Isa use std::os; fn start(n_tasks: int, token: int) { let (p, ch1) = stream(); let mut p = p; let mut ch1 = ch1; ch1.send(token); // XXX could not get this to work with a range closure let mut i = 2; while i <= n_tasks { let (next_p, ch) = stream(); let imm_i = i; let imm_p = p; do spawn { roundtrip(imm_i, n_tasks, &imm_p, &ch); }; p = next_p; i += 1; } let imm_p = p; let imm_ch = ch1; do spawn { roundtrip(1, n_tasks, &imm_p, &imm_ch); } } fn roundtrip(id: int, n_tasks: int, p: &Port<int>, ch: &Chan<int>) { while (true) { match p.recv() { 1 => { println(fmt!("%d\n", id)); return; } token => { debug!("thread: %d got token: %d", id, token);
return; } } } } } fn main() { let args = if os::getenv(~"RUST_BENCH").is_some() { ~[~"", ~"2000000", ~"503"] } else { os::args() }; let token = if args.len() > 1u { FromStr::from_str(args[1]).get() } else { 1000 }; let n_tasks = if args.len() > 2u { FromStr::from_str(args[2]).get() } else { 503 }; start(n_tasks, token); }
ch.send(token - 1); if token <= n_tasks {
random_line_split
shootout-threadring.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. // Based on threadring.erlang by Jira Isa use std::os; fn start(n_tasks: int, token: int) { let (p, ch1) = stream(); let mut p = p; let mut ch1 = ch1; ch1.send(token); // XXX could not get this to work with a range closure let mut i = 2; while i <= n_tasks { let (next_p, ch) = stream(); let imm_i = i; let imm_p = p; do spawn { roundtrip(imm_i, n_tasks, &imm_p, &ch); }; p = next_p; i += 1; } let imm_p = p; let imm_ch = ch1; do spawn { roundtrip(1, n_tasks, &imm_p, &imm_ch); } } fn
(id: int, n_tasks: int, p: &Port<int>, ch: &Chan<int>) { while (true) { match p.recv() { 1 => { println(fmt!("%d\n", id)); return; } token => { debug!("thread: %d got token: %d", id, token); ch.send(token - 1); if token <= n_tasks { return; } } } } } fn main() { let args = if os::getenv(~"RUST_BENCH").is_some() { ~[~"", ~"2000000", ~"503"] } else { os::args() }; let token = if args.len() > 1u { FromStr::from_str(args[1]).get() } else { 1000 }; let n_tasks = if args.len() > 2u { FromStr::from_str(args[2]).get() } else { 503 }; start(n_tasks, token); }
roundtrip
identifier_name
event.rs
//! Interfaces to VST events. // TODO: Update and explain both host and plugin events use std::{mem, slice}; use api::flags::*; use api::{self, flags}; /// A VST event. pub enum Event<'a> { /// A midi event. /// /// These are sent to the plugin before `Plugin::processing()` or `Plugin::processing_f64()` is /// called. Midi { /// The raw midi data associated with this event. data: [u8; 3], /// Number of samples into the current processing block that this event occurs on. /// /// E.g. if the block size is 512 and this value is 123, the event will occur on sample /// `samples[123]`. // TODO: Don't repeat this value in all event types delta_frames: i32, /// This midi event was created live as opposed to being played back in the sequencer. /// /// This can give the plugin priority over this event if it introduces a lot of latency. live: bool, /// The length of the midi note associated with this event, if available. note_length: Option<i32>, /// Offset in samples into note from note start, if available. note_offset: Option<i32>, /// Detuning between -63 and +64 cents. detune: i8, /// Note off velocity between 0 and 127. note_off_velocity: u8, }, /// A system exclusive event. /// /// This is just a block of data and it is up to the plugin to interpret this. Generally used /// by midi controllers. SysEx { /// The SysEx payload. payload: &'a [u8], /// Number of samples into the current processing block that this event occurs on. /// /// E.g. if the block size is 512 and this value is 123, the event will occur on sample /// `samples[123]`. delta_frames: i32, }, /// A deprecated event. /// /// Passes the raw midi event structure along with this so that implementors can handle /// optionally handle this event. Deprecated(api::Event), } impl<'a> From<api::Event> for Event<'a> { fn from(event: api::Event) -> Event<'a>
} SysEx => Event::SysEx { payload: unsafe { // We can safely transmute the event pointer to a `SysExEvent` pointer as // event_type refers to a `SysEx` type. let event: &api::SysExEvent = mem::transmute(&event); slice::from_raw_parts(event.system_data, event.data_size as usize) }, delta_frames: event.delta_frames }, _ => Event::Deprecated(event), } } }
{ use api::EventType::*; match event.event_type { Midi => { let event: api::MidiEvent = unsafe { mem::transmute(event) }; let length = if event.note_length > 0 { Some(event.note_length) } else { None }; let offset = if event.note_offset > 0 { Some(event.note_offset) } else { None }; let flags = flags::MidiEvent::from_bits(event.flags).unwrap(); Event::Midi { data: event.midi_data, delta_frames: event.delta_frames, live: flags.intersects(REALTIME_EVENT), note_length: length, note_offset: offset, detune: event.detune, note_off_velocity: event.note_off_velocity }
identifier_body
event.rs
//! Interfaces to VST events. // TODO: Update and explain both host and plugin events use std::{mem, slice}; use api::flags::*; use api::{self, flags}; /// A VST event. pub enum Event<'a> { /// A midi event. /// /// These are sent to the plugin before `Plugin::processing()` or `Plugin::processing_f64()` is /// called. Midi { /// The raw midi data associated with this event. data: [u8; 3], /// Number of samples into the current processing block that this event occurs on. /// /// E.g. if the block size is 512 and this value is 123, the event will occur on sample /// `samples[123]`. // TODO: Don't repeat this value in all event types delta_frames: i32, /// This midi event was created live as opposed to being played back in the sequencer. /// /// This can give the plugin priority over this event if it introduces a lot of latency. live: bool, /// The length of the midi note associated with this event, if available. note_length: Option<i32>, /// Offset in samples into note from note start, if available. note_offset: Option<i32>, /// Detuning between -63 and +64 cents. detune: i8, /// Note off velocity between 0 and 127. note_off_velocity: u8, }, /// A system exclusive event. /// /// This is just a block of data and it is up to the plugin to interpret this. Generally used /// by midi controllers. SysEx { /// The SysEx payload. payload: &'a [u8], /// Number of samples into the current processing block that this event occurs on. /// /// E.g. if the block size is 512 and this value is 123, the event will occur on sample /// `samples[123]`. delta_frames: i32, }, /// A deprecated event. /// /// Passes the raw midi event structure along with this so that implementors can handle /// optionally handle this event. Deprecated(api::Event), } impl<'a> From<api::Event> for Event<'a> { fn from(event: api::Event) -> Event<'a> { use api::EventType::*; match event.event_type { Midi => { let event: api::MidiEvent = unsafe { mem::transmute(event) }; let length = if event.note_length > 0 { Some(event.note_length) } else { None }; let offset = if event.note_offset > 0 { Some(event.note_offset) } else
; let flags = flags::MidiEvent::from_bits(event.flags).unwrap(); Event::Midi { data: event.midi_data, delta_frames: event.delta_frames, live: flags.intersects(REALTIME_EVENT), note_length: length, note_offset: offset, detune: event.detune, note_off_velocity: event.note_off_velocity } } SysEx => Event::SysEx { payload: unsafe { // We can safely transmute the event pointer to a `SysExEvent` pointer as // event_type refers to a `SysEx` type. let event: &api::SysExEvent = mem::transmute(&event); slice::from_raw_parts(event.system_data, event.data_size as usize) }, delta_frames: event.delta_frames }, _ => Event::Deprecated(event), } } }
{ None }
conditional_block
event.rs
//! Interfaces to VST events. // TODO: Update and explain both host and plugin events use std::{mem, slice}; use api::flags::*; use api::{self, flags}; /// A VST event. pub enum Event<'a> { /// A midi event. /// /// These are sent to the plugin before `Plugin::processing()` or `Plugin::processing_f64()` is /// called. Midi { /// The raw midi data associated with this event. data: [u8; 3], /// Number of samples into the current processing block that this event occurs on. /// /// E.g. if the block size is 512 and this value is 123, the event will occur on sample /// `samples[123]`. // TODO: Don't repeat this value in all event types delta_frames: i32, /// This midi event was created live as opposed to being played back in the sequencer. /// /// This can give the plugin priority over this event if it introduces a lot of latency. live: bool,
/// Offset in samples into note from note start, if available. note_offset: Option<i32>, /// Detuning between -63 and +64 cents. detune: i8, /// Note off velocity between 0 and 127. note_off_velocity: u8, }, /// A system exclusive event. /// /// This is just a block of data and it is up to the plugin to interpret this. Generally used /// by midi controllers. SysEx { /// The SysEx payload. payload: &'a [u8], /// Number of samples into the current processing block that this event occurs on. /// /// E.g. if the block size is 512 and this value is 123, the event will occur on sample /// `samples[123]`. delta_frames: i32, }, /// A deprecated event. /// /// Passes the raw midi event structure along with this so that implementors can handle /// optionally handle this event. Deprecated(api::Event), } impl<'a> From<api::Event> for Event<'a> { fn from(event: api::Event) -> Event<'a> { use api::EventType::*; match event.event_type { Midi => { let event: api::MidiEvent = unsafe { mem::transmute(event) }; let length = if event.note_length > 0 { Some(event.note_length) } else { None }; let offset = if event.note_offset > 0 { Some(event.note_offset) } else { None }; let flags = flags::MidiEvent::from_bits(event.flags).unwrap(); Event::Midi { data: event.midi_data, delta_frames: event.delta_frames, live: flags.intersects(REALTIME_EVENT), note_length: length, note_offset: offset, detune: event.detune, note_off_velocity: event.note_off_velocity } } SysEx => Event::SysEx { payload: unsafe { // We can safely transmute the event pointer to a `SysExEvent` pointer as // event_type refers to a `SysEx` type. let event: &api::SysExEvent = mem::transmute(&event); slice::from_raw_parts(event.system_data, event.data_size as usize) }, delta_frames: event.delta_frames }, _ => Event::Deprecated(event), } } }
/// The length of the midi note associated with this event, if available. note_length: Option<i32>,
random_line_split
event.rs
//! Interfaces to VST events. // TODO: Update and explain both host and plugin events use std::{mem, slice}; use api::flags::*; use api::{self, flags}; /// A VST event. pub enum
<'a> { /// A midi event. /// /// These are sent to the plugin before `Plugin::processing()` or `Plugin::processing_f64()` is /// called. Midi { /// The raw midi data associated with this event. data: [u8; 3], /// Number of samples into the current processing block that this event occurs on. /// /// E.g. if the block size is 512 and this value is 123, the event will occur on sample /// `samples[123]`. // TODO: Don't repeat this value in all event types delta_frames: i32, /// This midi event was created live as opposed to being played back in the sequencer. /// /// This can give the plugin priority over this event if it introduces a lot of latency. live: bool, /// The length of the midi note associated with this event, if available. note_length: Option<i32>, /// Offset in samples into note from note start, if available. note_offset: Option<i32>, /// Detuning between -63 and +64 cents. detune: i8, /// Note off velocity between 0 and 127. note_off_velocity: u8, }, /// A system exclusive event. /// /// This is just a block of data and it is up to the plugin to interpret this. Generally used /// by midi controllers. SysEx { /// The SysEx payload. payload: &'a [u8], /// Number of samples into the current processing block that this event occurs on. /// /// E.g. if the block size is 512 and this value is 123, the event will occur on sample /// `samples[123]`. delta_frames: i32, }, /// A deprecated event. /// /// Passes the raw midi event structure along with this so that implementors can handle /// optionally handle this event. Deprecated(api::Event), } impl<'a> From<api::Event> for Event<'a> { fn from(event: api::Event) -> Event<'a> { use api::EventType::*; match event.event_type { Midi => { let event: api::MidiEvent = unsafe { mem::transmute(event) }; let length = if event.note_length > 0 { Some(event.note_length) } else { None }; let offset = if event.note_offset > 0 { Some(event.note_offset) } else { None }; let flags = flags::MidiEvent::from_bits(event.flags).unwrap(); Event::Midi { data: event.midi_data, delta_frames: event.delta_frames, live: flags.intersects(REALTIME_EVENT), note_length: length, note_offset: offset, detune: event.detune, note_off_velocity: event.note_off_velocity } } SysEx => Event::SysEx { payload: unsafe { // We can safely transmute the event pointer to a `SysExEvent` pointer as // event_type refers to a `SysEx` type. let event: &api::SysExEvent = mem::transmute(&event); slice::from_raw_parts(event.system_data, event.data_size as usize) }, delta_frames: event.delta_frames }, _ => Event::Deprecated(event), } } }
Event
identifier_name
request_registration_token_via_msisdn.rs
//! `POST /_matrix/client/*/register/msisdn/requestToken` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3registermsisdnrequesttoken use js_int::UInt; use ruma_common::{api::ruma_api, ClientSecret, SessionId}; use crate::account::{IdentityServerInfo, IncomingIdentityServerInfo}; ruma_api! { metadata: { description: "Request a registration token with a phone number.", method: POST, name: "request_registration_token_via_msisdn", r0_path: "/_matrix/client/r0/register/msisdn/requestToken", stable_path: "/_matrix/client/v3/register/msisdn/requestToken", rate_limited: false, authentication: None, added: 1.0, } request: { /// Client-generated secret string used to protect this session. pub client_secret: &'a ClientSecret, /// Two-letter ISO 3166 country code for the phone number. pub country: &'a str, /// Phone number to validate. pub phone_number: &'a str, /// Used to distinguish protocol level retries from requests to re-send the SMS. pub send_attempt: UInt, /// Return URL for identity server to redirect the client back to. #[serde(skip_serializing_if = "Option::is_none")] pub next_link: Option<&'a str>, /// Optional identity server hostname and access token. /// /// Deprecated since r0.6.0. #[serde(flatten, skip_serializing_if = "Option::is_none")] pub identity_server_info: Option<IdentityServerInfo<'a>>, } response: { /// The session identifier given by the identity server. pub sid: Box<SessionId>, /// URL to submit validation token to. /// /// If omitted, verification happens without client. /// /// If you activate the `compat` feature, this field being an empty string in JSON will result /// in `None` here during deserialization. #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr( feature = "compat", serde(default, deserialize_with = "ruma_serde::empty_string_as_none") )] pub submit_url: Option<String>, } error: crate::Error } impl<'a> Request<'a> { /// Creates a new `Request` with the given client secret, country code, phone number and /// send-attempt counter. pub fn new( client_secret: &'a ClientSecret, country: &'a str, phone_number: &'a str, send_attempt: UInt, ) -> Self
} impl Response { /// Creates a new `Response` with the given session identifier. pub fn new(sid: Box<SessionId>) -> Self { Self { sid, submit_url: None } } } }
{ Self { client_secret, country, phone_number, send_attempt, next_link: None, identity_server_info: None, } }
identifier_body
request_registration_token_via_msisdn.rs
//! `POST /_matrix/client/*/register/msisdn/requestToken` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3registermsisdnrequesttoken use js_int::UInt; use ruma_common::{api::ruma_api, ClientSecret, SessionId}; use crate::account::{IdentityServerInfo, IncomingIdentityServerInfo}; ruma_api! { metadata: { description: "Request a registration token with a phone number.", method: POST, name: "request_registration_token_via_msisdn", r0_path: "/_matrix/client/r0/register/msisdn/requestToken", stable_path: "/_matrix/client/v3/register/msisdn/requestToken", rate_limited: false, authentication: None, added: 1.0, } request: { /// Client-generated secret string used to protect this session. pub client_secret: &'a ClientSecret, /// Two-letter ISO 3166 country code for the phone number. pub country: &'a str, /// Phone number to validate. pub phone_number: &'a str, /// Used to distinguish protocol level retries from requests to re-send the SMS. pub send_attempt: UInt, /// Return URL for identity server to redirect the client back to. #[serde(skip_serializing_if = "Option::is_none")] pub next_link: Option<&'a str>, /// Optional identity server hostname and access token. /// /// Deprecated since r0.6.0. #[serde(flatten, skip_serializing_if = "Option::is_none")] pub identity_server_info: Option<IdentityServerInfo<'a>>, } response: { /// The session identifier given by the identity server. pub sid: Box<SessionId>, /// URL to submit validation token to. /// /// If omitted, verification happens without client. /// /// If you activate the `compat` feature, this field being an empty string in JSON will result /// in `None` here during deserialization. #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr( feature = "compat", serde(default, deserialize_with = "ruma_serde::empty_string_as_none") )] pub submit_url: Option<String>, } error: crate::Error
} impl<'a> Request<'a> { /// Creates a new `Request` with the given client secret, country code, phone number and /// send-attempt counter. pub fn new( client_secret: &'a ClientSecret, country: &'a str, phone_number: &'a str, send_attempt: UInt, ) -> Self { Self { client_secret, country, phone_number, send_attempt, next_link: None, identity_server_info: None, } } } impl Response { /// Creates a new `Response` with the given session identifier. pub fn new(sid: Box<SessionId>) -> Self { Self { sid, submit_url: None } } } }
random_line_split
request_registration_token_via_msisdn.rs
//! `POST /_matrix/client/*/register/msisdn/requestToken` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3registermsisdnrequesttoken use js_int::UInt; use ruma_common::{api::ruma_api, ClientSecret, SessionId}; use crate::account::{IdentityServerInfo, IncomingIdentityServerInfo}; ruma_api! { metadata: { description: "Request a registration token with a phone number.", method: POST, name: "request_registration_token_via_msisdn", r0_path: "/_matrix/client/r0/register/msisdn/requestToken", stable_path: "/_matrix/client/v3/register/msisdn/requestToken", rate_limited: false, authentication: None, added: 1.0, } request: { /// Client-generated secret string used to protect this session. pub client_secret: &'a ClientSecret, /// Two-letter ISO 3166 country code for the phone number. pub country: &'a str, /// Phone number to validate. pub phone_number: &'a str, /// Used to distinguish protocol level retries from requests to re-send the SMS. pub send_attempt: UInt, /// Return URL for identity server to redirect the client back to. #[serde(skip_serializing_if = "Option::is_none")] pub next_link: Option<&'a str>, /// Optional identity server hostname and access token. /// /// Deprecated since r0.6.0. #[serde(flatten, skip_serializing_if = "Option::is_none")] pub identity_server_info: Option<IdentityServerInfo<'a>>, } response: { /// The session identifier given by the identity server. pub sid: Box<SessionId>, /// URL to submit validation token to. /// /// If omitted, verification happens without client. /// /// If you activate the `compat` feature, this field being an empty string in JSON will result /// in `None` here during deserialization. #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr( feature = "compat", serde(default, deserialize_with = "ruma_serde::empty_string_as_none") )] pub submit_url: Option<String>, } error: crate::Error } impl<'a> Request<'a> { /// Creates a new `Request` with the given client secret, country code, phone number and /// send-attempt counter. pub fn new( client_secret: &'a ClientSecret, country: &'a str, phone_number: &'a str, send_attempt: UInt, ) -> Self { Self { client_secret, country, phone_number, send_attempt, next_link: None, identity_server_info: None, } } } impl Response { /// Creates a new `Response` with the given session identifier. pub fn
(sid: Box<SessionId>) -> Self { Self { sid, submit_url: None } } } }
new
identifier_name
main.rs
#![feature(box_syntax)] extern crate e2d2; extern crate getopts; extern crate rand; extern crate time; use e2d2::allocators::*; use e2d2::common::*; use e2d2::headers::*; use e2d2::interface::*; use e2d2::interface::dpdk::*; use e2d2::operators::*; use e2d2::scheduler::Executable; use e2d2::state::*; use getopts::Options; use std::collections::HashMap; use std::env; use std::process; use std::sync::Arc; use std::thread; use std::time::Duration; const CONVERSION_FACTOR: f64 = 1000000000.; fn monitor<T:'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>( parent: T, mut monitoring_cache: MergeableStoreDP<isize>, ) -> CompositionBatch
fn recv_thread(ports: Vec<CacheAligned<PortQueue>>, core: i32, counter: MergeableStoreDP<isize>) { init_thread(core, core); println!("Receiving started"); let pipelines: Vec<_> = ports .iter() .map(|port| { let ctr = counter.clone(); monitor(ReceiveBatch::new(port.clone()), ctr) .send(port.clone()) .compose() }) .collect(); println!("Running {} pipelines", pipelines.len()); let mut combined = merge(pipelines); loop { combined.execute(); } } fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); opts.optflag("", "secondary", "run as a secondary process"); opts.optopt("n", "name", "name to use for the current process", "name"); opts.optmulti("p", "port", "Port to use", "[type:]id"); opts.optmulti("c", "core", "Core to use", "core"); opts.optopt("m", "master", "Master core", "master"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; if matches.opt_present("h") { print!("{}", opts.usage(&format!("Usage: {} [options]", program))); process::exit(0) } let cores_str = matches.opt_strs("c"); let master_core = matches .opt_str("m") .unwrap_or_else(|| String::from("0")) .parse() .expect("Could not parse master core spec"); println!("Using master core {}", master_core); let name = matches.opt_str("n").unwrap_or_else(|| String::from("recv")); let cores: Vec<i32> = cores_str .iter() .map(|n: &String| { n.parse() .ok() .expect(&format!("Core cannot be parsed {}", n)) }) .collect(); fn extract_cores_for_port(ports: &[String], cores: &[i32]) -> HashMap<String, Vec<i32>> { let mut cores_for_port = HashMap::<String, Vec<i32>>::new(); for (port, core) in ports.iter().zip(cores.iter()) { cores_for_port .entry(port.clone()) .or_insert(vec![]) .push(*core) } cores_for_port } let primary =!matches.opt_present("secondary"); let cores_for_port = extract_cores_for_port(&matches.opt_strs("p"), &cores); if primary { init_system_wl(&name, master_core, &[]); } else { init_system_secondary(&name, master_core); } let ports_to_activate: Vec<_> = cores_for_port.keys().collect(); let mut queues_by_core = HashMap::<i32, Vec<_>>::with_capacity(cores.len()); let mut ports = Vec::<Arc<PmdPort>>::with_capacity(ports_to_activate.len()); for port in &ports_to_activate { let cores = cores_for_port.get(*port).unwrap(); let queues = cores.len() as i32; let pmd_port = PmdPort::new_with_queues(*port, queues, queues, cores, cores).expect("Could not initialize port"); for (idx, core) in cores.iter().enumerate() { let queue = idx as i32; queues_by_core .entry(*core) .or_insert(vec![]) .push(PmdPort::new_queue_pair(&pmd_port, queue, queue).unwrap()); } ports.push(pmd_port); } const _BATCH: usize = 1 << 10; const _CHANNEL_SIZE: usize = 256; let mut consumer = MergeableStoreCP::new(); let _thread: Vec<_> = queues_by_core .iter() .map(|(core, ports)| { let c = core.clone(); let mon = consumer.dp_store(); let p: Vec<_> = ports.iter().map(|p| p.clone()).collect(); std::thread::spawn(move || recv_thread(p, c, mon)) }) .collect(); let mut pkts_so_far = (0, 0); let mut start = time::precise_time_ns() as f64 / CONVERSION_FACTOR; let sleep_time = Duration::from_millis(500); loop { thread::sleep(sleep_time); // Sleep for a bit consumer.sync(); let now = time::precise_time_ns() as f64 / CONVERSION_FACTOR; if now - start > 1.0 { let mut rx = 0; let mut tx = 0; for port in &ports { for q in 0..port.rxqs() { let (rp, tp) = port.stats(q); rx += rp; tx += tp; } } let pkts = (rx, tx); println!( "{:.2} OVERALL RX {:.2} TX {:.2} FLOWS {}", now - start, (pkts.0 - pkts_so_far.0) as f64 / (now - start), (pkts.1 - pkts_so_far.1) as f64 / (now - start), consumer.len() ); start = now; pkts_so_far = pkts; } } }
{ parent .parse::<MacHeader>() .transform(box |pkt| { let hdr = pkt.get_mut_header(); hdr.swap_addresses(); }) .parse::<IpHeader>() .transform(box move |pkt| { let hdr = pkt.get_mut_header(); let ttl = hdr.ttl(); hdr.set_ttl(ttl + 1); monitoring_cache.update(hdr.flow().unwrap(), 1); }) .compose() }
identifier_body
main.rs
#![feature(box_syntax)] extern crate e2d2; extern crate getopts; extern crate rand; extern crate time; use e2d2::allocators::*; use e2d2::common::*; use e2d2::headers::*; use e2d2::interface::*; use e2d2::interface::dpdk::*; use e2d2::operators::*; use e2d2::scheduler::Executable; use e2d2::state::*; use getopts::Options; use std::collections::HashMap; use std::env; use std::process; use std::sync::Arc; use std::thread; use std::time::Duration; const CONVERSION_FACTOR: f64 = 1000000000.; fn monitor<T:'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>( parent: T, mut monitoring_cache: MergeableStoreDP<isize>, ) -> CompositionBatch { parent .parse::<MacHeader>() .transform(box |pkt| { let hdr = pkt.get_mut_header(); hdr.swap_addresses(); }) .parse::<IpHeader>() .transform(box move |pkt| { let hdr = pkt.get_mut_header(); let ttl = hdr.ttl(); hdr.set_ttl(ttl + 1); monitoring_cache.update(hdr.flow().unwrap(), 1); }) .compose() } fn recv_thread(ports: Vec<CacheAligned<PortQueue>>, core: i32, counter: MergeableStoreDP<isize>) { init_thread(core, core); println!("Receiving started"); let pipelines: Vec<_> = ports .iter() .map(|port| { let ctr = counter.clone(); monitor(ReceiveBatch::new(port.clone()), ctr) .send(port.clone()) .compose() }) .collect(); println!("Running {} pipelines", pipelines.len()); let mut combined = merge(pipelines); loop { combined.execute(); } } fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); opts.optflag("", "secondary", "run as a secondary process"); opts.optopt("n", "name", "name to use for the current process", "name"); opts.optmulti("p", "port", "Port to use", "[type:]id"); opts.optmulti("c", "core", "Core to use", "core"); opts.optopt("m", "master", "Master core", "master"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; if matches.opt_present("h") { print!("{}", opts.usage(&format!("Usage: {} [options]", program))); process::exit(0) } let cores_str = matches.opt_strs("c"); let master_core = matches .opt_str("m") .unwrap_or_else(|| String::from("0")) .parse() .expect("Could not parse master core spec"); println!("Using master core {}", master_core); let name = matches.opt_str("n").unwrap_or_else(|| String::from("recv")); let cores: Vec<i32> = cores_str .iter() .map(|n: &String| { n.parse() .ok() .expect(&format!("Core cannot be parsed {}", n)) }) .collect(); fn extract_cores_for_port(ports: &[String], cores: &[i32]) -> HashMap<String, Vec<i32>> { let mut cores_for_port = HashMap::<String, Vec<i32>>::new(); for (port, core) in ports.iter().zip(cores.iter()) { cores_for_port .entry(port.clone()) .or_insert(vec![]) .push(*core) } cores_for_port } let primary =!matches.opt_present("secondary"); let cores_for_port = extract_cores_for_port(&matches.opt_strs("p"), &cores); if primary
else { init_system_secondary(&name, master_core); } let ports_to_activate: Vec<_> = cores_for_port.keys().collect(); let mut queues_by_core = HashMap::<i32, Vec<_>>::with_capacity(cores.len()); let mut ports = Vec::<Arc<PmdPort>>::with_capacity(ports_to_activate.len()); for port in &ports_to_activate { let cores = cores_for_port.get(*port).unwrap(); let queues = cores.len() as i32; let pmd_port = PmdPort::new_with_queues(*port, queues, queues, cores, cores).expect("Could not initialize port"); for (idx, core) in cores.iter().enumerate() { let queue = idx as i32; queues_by_core .entry(*core) .or_insert(vec![]) .push(PmdPort::new_queue_pair(&pmd_port, queue, queue).unwrap()); } ports.push(pmd_port); } const _BATCH: usize = 1 << 10; const _CHANNEL_SIZE: usize = 256; let mut consumer = MergeableStoreCP::new(); let _thread: Vec<_> = queues_by_core .iter() .map(|(core, ports)| { let c = core.clone(); let mon = consumer.dp_store(); let p: Vec<_> = ports.iter().map(|p| p.clone()).collect(); std::thread::spawn(move || recv_thread(p, c, mon)) }) .collect(); let mut pkts_so_far = (0, 0); let mut start = time::precise_time_ns() as f64 / CONVERSION_FACTOR; let sleep_time = Duration::from_millis(500); loop { thread::sleep(sleep_time); // Sleep for a bit consumer.sync(); let now = time::precise_time_ns() as f64 / CONVERSION_FACTOR; if now - start > 1.0 { let mut rx = 0; let mut tx = 0; for port in &ports { for q in 0..port.rxqs() { let (rp, tp) = port.stats(q); rx += rp; tx += tp; } } let pkts = (rx, tx); println!( "{:.2} OVERALL RX {:.2} TX {:.2} FLOWS {}", now - start, (pkts.0 - pkts_so_far.0) as f64 / (now - start), (pkts.1 - pkts_so_far.1) as f64 / (now - start), consumer.len() ); start = now; pkts_so_far = pkts; } } }
{ init_system_wl(&name, master_core, &[]); }
conditional_block
main.rs
#![feature(box_syntax)] extern crate e2d2; extern crate getopts; extern crate rand; extern crate time; use e2d2::allocators::*; use e2d2::common::*; use e2d2::headers::*; use e2d2::interface::*; use e2d2::interface::dpdk::*; use e2d2::operators::*; use e2d2::scheduler::Executable; use e2d2::state::*; use getopts::Options; use std::collections::HashMap; use std::env; use std::process; use std::sync::Arc; use std::thread; use std::time::Duration; const CONVERSION_FACTOR: f64 = 1000000000.; fn monitor<T:'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>( parent: T, mut monitoring_cache: MergeableStoreDP<isize>, ) -> CompositionBatch { parent .parse::<MacHeader>() .transform(box |pkt| { let hdr = pkt.get_mut_header(); hdr.swap_addresses(); }) .parse::<IpHeader>() .transform(box move |pkt| { let hdr = pkt.get_mut_header(); let ttl = hdr.ttl(); hdr.set_ttl(ttl + 1); monitoring_cache.update(hdr.flow().unwrap(), 1); }) .compose() } fn recv_thread(ports: Vec<CacheAligned<PortQueue>>, core: i32, counter: MergeableStoreDP<isize>) { init_thread(core, core); println!("Receiving started"); let pipelines: Vec<_> = ports .iter() .map(|port| { let ctr = counter.clone(); monitor(ReceiveBatch::new(port.clone()), ctr) .send(port.clone()) .compose() }) .collect(); println!("Running {} pipelines", pipelines.len()); let mut combined = merge(pipelines); loop { combined.execute(); } } fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); opts.optflag("", "secondary", "run as a secondary process"); opts.optopt("n", "name", "name to use for the current process", "name"); opts.optmulti("p", "port", "Port to use", "[type:]id"); opts.optmulti("c", "core", "Core to use", "core"); opts.optopt("m", "master", "Master core", "master"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; if matches.opt_present("h") { print!("{}", opts.usage(&format!("Usage: {} [options]", program))); process::exit(0) } let cores_str = matches.opt_strs("c"); let master_core = matches .opt_str("m") .unwrap_or_else(|| String::from("0")) .parse() .expect("Could not parse master core spec"); println!("Using master core {}", master_core); let name = matches.opt_str("n").unwrap_or_else(|| String::from("recv")); let cores: Vec<i32> = cores_str .iter() .map(|n: &String| { n.parse() .ok() .expect(&format!("Core cannot be parsed {}", n)) }) .collect(); fn extract_cores_for_port(ports: &[String], cores: &[i32]) -> HashMap<String, Vec<i32>> { let mut cores_for_port = HashMap::<String, Vec<i32>>::new(); for (port, core) in ports.iter().zip(cores.iter()) { cores_for_port .entry(port.clone()) .or_insert(vec![]) .push(*core) } cores_for_port } let primary =!matches.opt_present("secondary"); let cores_for_port = extract_cores_for_port(&matches.opt_strs("p"), &cores); if primary { init_system_wl(&name, master_core, &[]); } else { init_system_secondary(&name, master_core); } let ports_to_activate: Vec<_> = cores_for_port.keys().collect(); let mut queues_by_core = HashMap::<i32, Vec<_>>::with_capacity(cores.len()); let mut ports = Vec::<Arc<PmdPort>>::with_capacity(ports_to_activate.len()); for port in &ports_to_activate { let cores = cores_for_port.get(*port).unwrap(); let queues = cores.len() as i32; let pmd_port = PmdPort::new_with_queues(*port, queues, queues, cores, cores).expect("Could not initialize port"); for (idx, core) in cores.iter().enumerate() { let queue = idx as i32; queues_by_core .entry(*core) .or_insert(vec![]) .push(PmdPort::new_queue_pair(&pmd_port, queue, queue).unwrap()); } ports.push(pmd_port); } const _BATCH: usize = 1 << 10; const _CHANNEL_SIZE: usize = 256; let mut consumer = MergeableStoreCP::new(); let _thread: Vec<_> = queues_by_core .iter() .map(|(core, ports)| { let c = core.clone(); let mon = consumer.dp_store(); let p: Vec<_> = ports.iter().map(|p| p.clone()).collect(); std::thread::spawn(move || recv_thread(p, c, mon)) }) .collect(); let mut pkts_so_far = (0, 0); let mut start = time::precise_time_ns() as f64 / CONVERSION_FACTOR; let sleep_time = Duration::from_millis(500); loop { thread::sleep(sleep_time); // Sleep for a bit consumer.sync(); let now = time::precise_time_ns() as f64 / CONVERSION_FACTOR; if now - start > 1.0 { let mut rx = 0; let mut tx = 0; for port in &ports { for q in 0..port.rxqs() { let (rp, tp) = port.stats(q); rx += rp; tx += tp; } } let pkts = (rx, tx); println!( "{:.2} OVERALL RX {:.2} TX {:.2} FLOWS {}", now - start, (pkts.0 - pkts_so_far.0) as f64 / (now - start), (pkts.1 - pkts_so_far.1) as f64 / (now - start), consumer.len() ); start = now; pkts_so_far = pkts; } }
}
random_line_split
main.rs
#![feature(box_syntax)] extern crate e2d2; extern crate getopts; extern crate rand; extern crate time; use e2d2::allocators::*; use e2d2::common::*; use e2d2::headers::*; use e2d2::interface::*; use e2d2::interface::dpdk::*; use e2d2::operators::*; use e2d2::scheduler::Executable; use e2d2::state::*; use getopts::Options; use std::collections::HashMap; use std::env; use std::process; use std::sync::Arc; use std::thread; use std::time::Duration; const CONVERSION_FACTOR: f64 = 1000000000.; fn monitor<T:'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>( parent: T, mut monitoring_cache: MergeableStoreDP<isize>, ) -> CompositionBatch { parent .parse::<MacHeader>() .transform(box |pkt| { let hdr = pkt.get_mut_header(); hdr.swap_addresses(); }) .parse::<IpHeader>() .transform(box move |pkt| { let hdr = pkt.get_mut_header(); let ttl = hdr.ttl(); hdr.set_ttl(ttl + 1); monitoring_cache.update(hdr.flow().unwrap(), 1); }) .compose() } fn recv_thread(ports: Vec<CacheAligned<PortQueue>>, core: i32, counter: MergeableStoreDP<isize>) { init_thread(core, core); println!("Receiving started"); let pipelines: Vec<_> = ports .iter() .map(|port| { let ctr = counter.clone(); monitor(ReceiveBatch::new(port.clone()), ctr) .send(port.clone()) .compose() }) .collect(); println!("Running {} pipelines", pipelines.len()); let mut combined = merge(pipelines); loop { combined.execute(); } } fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); opts.optflag("", "secondary", "run as a secondary process"); opts.optopt("n", "name", "name to use for the current process", "name"); opts.optmulti("p", "port", "Port to use", "[type:]id"); opts.optmulti("c", "core", "Core to use", "core"); opts.optopt("m", "master", "Master core", "master"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; if matches.opt_present("h") { print!("{}", opts.usage(&format!("Usage: {} [options]", program))); process::exit(0) } let cores_str = matches.opt_strs("c"); let master_core = matches .opt_str("m") .unwrap_or_else(|| String::from("0")) .parse() .expect("Could not parse master core spec"); println!("Using master core {}", master_core); let name = matches.opt_str("n").unwrap_or_else(|| String::from("recv")); let cores: Vec<i32> = cores_str .iter() .map(|n: &String| { n.parse() .ok() .expect(&format!("Core cannot be parsed {}", n)) }) .collect(); fn
(ports: &[String], cores: &[i32]) -> HashMap<String, Vec<i32>> { let mut cores_for_port = HashMap::<String, Vec<i32>>::new(); for (port, core) in ports.iter().zip(cores.iter()) { cores_for_port .entry(port.clone()) .or_insert(vec![]) .push(*core) } cores_for_port } let primary =!matches.opt_present("secondary"); let cores_for_port = extract_cores_for_port(&matches.opt_strs("p"), &cores); if primary { init_system_wl(&name, master_core, &[]); } else { init_system_secondary(&name, master_core); } let ports_to_activate: Vec<_> = cores_for_port.keys().collect(); let mut queues_by_core = HashMap::<i32, Vec<_>>::with_capacity(cores.len()); let mut ports = Vec::<Arc<PmdPort>>::with_capacity(ports_to_activate.len()); for port in &ports_to_activate { let cores = cores_for_port.get(*port).unwrap(); let queues = cores.len() as i32; let pmd_port = PmdPort::new_with_queues(*port, queues, queues, cores, cores).expect("Could not initialize port"); for (idx, core) in cores.iter().enumerate() { let queue = idx as i32; queues_by_core .entry(*core) .or_insert(vec![]) .push(PmdPort::new_queue_pair(&pmd_port, queue, queue).unwrap()); } ports.push(pmd_port); } const _BATCH: usize = 1 << 10; const _CHANNEL_SIZE: usize = 256; let mut consumer = MergeableStoreCP::new(); let _thread: Vec<_> = queues_by_core .iter() .map(|(core, ports)| { let c = core.clone(); let mon = consumer.dp_store(); let p: Vec<_> = ports.iter().map(|p| p.clone()).collect(); std::thread::spawn(move || recv_thread(p, c, mon)) }) .collect(); let mut pkts_so_far = (0, 0); let mut start = time::precise_time_ns() as f64 / CONVERSION_FACTOR; let sleep_time = Duration::from_millis(500); loop { thread::sleep(sleep_time); // Sleep for a bit consumer.sync(); let now = time::precise_time_ns() as f64 / CONVERSION_FACTOR; if now - start > 1.0 { let mut rx = 0; let mut tx = 0; for port in &ports { for q in 0..port.rxqs() { let (rp, tp) = port.stats(q); rx += rp; tx += tp; } } let pkts = (rx, tx); println!( "{:.2} OVERALL RX {:.2} TX {:.2} FLOWS {}", now - start, (pkts.0 - pkts_so_far.0) as f64 / (now - start), (pkts.1 - pkts_so_far.1) as f64 / (now - start), consumer.len() ); start = now; pkts_so_far = pkts; } } }
extract_cores_for_port
identifier_name
square.rs
use crate::Color; use std::fmt; use std::iter; const ASCII_1: u8 = b'1'; const ASCII_9: u8 = b'9'; const ASCII_LOWER_A: u8 = b'a'; const ASCII_LOWER_I: u8 = b'i'; /// Represents a position of each cell in the game board. /// /// # Examples /// /// ``` /// use shogi::Square; /// /// let sq = Square::new(4, 4).unwrap(); /// assert_eq!("5e", sq.to_string()); /// ``` /// /// `Square` can be created by parsing a SFEN formatted string as well. /// /// ``` /// use shogi::Square; /// /// let sq = Square::from_sfen("5e").unwrap(); /// assert_eq!(4, sq.file()); /// assert_eq!(4, sq.rank()); /// ``` #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] pub struct Square { inner: u8, } impl Square { /// Creates a new instance of `Square`. /// /// `file` can take a value from 0('1') to 8('9'), while `rank` is from 0('a') to 9('i'). pub fn new(file: u8, rank: u8) -> Option<Self> { if file > 8 || rank > 8 { return None; } Some(Square { inner: file * 9 + rank, }) } /// Creates a new instance of `Square` from SFEN formatted string. pub fn from_sfen(s: &str) -> Option<Self> { let bytes: &[u8] = s.as_bytes(); if bytes.len()!= 2 || bytes[0] < ASCII_1 || bytes[0] > ASCII_9 || bytes[1] < ASCII_LOWER_A || bytes[1] > ASCII_LOWER_I { return None; } let file = bytes[0] - ASCII_1; let rank = bytes[1] - ASCII_LOWER_A; debug_assert!( file < 9 && rank < 9, "{} parsed as (file: {}, rank: {})", s, file, rank ); Some(Square { inner: file * 9 + rank, }) } /// Creates a new instance of `Square` with the given index value. pub fn from_index(index: u8) -> Option<Self> { if index >= 81 { return None;
/// Returns an iterator of all variants. pub fn iter() -> SquareIter { SquareIter { current: 0 } } /// Returns a file of the square. pub fn file(self) -> u8 { self.inner / 9 } /// Returns a rank of the square. pub fn rank(self) -> u8 { self.inner % 9 } /// Returns a new `Square` instance by moving the file and the rank values. /// /// # Examples /// /// ``` /// use shogi::square::consts::*; /// /// let sq = SQ_2B; /// let shifted = sq.shift(2, 3).unwrap(); /// /// assert_eq!(3, shifted.file()); /// assert_eq!(4, shifted.rank()); /// ``` #[must_use] pub fn shift(self, df: i8, dr: i8) -> Option<Self> { let f = self.file() as i8 + df; let r = self.rank() as i8 + dr; if!(0..9).contains(&f) ||!(0..9).contains(&r) { return None; } Some(Square { inner: (f * 9 + r) as u8, }) } /// Returns a relative rank as if the specified color is black. /// /// # Examples /// /// ``` /// use shogi::Color; /// use shogi::square::consts::*; /// /// let sq = SQ_1G; /// /// assert_eq!(6, sq.relative_rank(Color::Black)); /// assert_eq!(2, sq.relative_rank(Color::White)); /// ``` pub fn relative_rank(self, c: Color) -> u8 { if c == Color::Black { self.rank() } else { 8 - self.rank() } } /// Tests if the square is in a promotion zone. pub fn in_promotion_zone(self, c: Color) -> bool { self.relative_rank(c) < 3 } /// Converts the instance into the unique number for array indexing purpose. #[inline(always)] pub fn index(self) -> usize { self.inner as usize } } impl fmt::Display for Square { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { debug_assert!( self.file() < 9 && self.rank() < 9, "trying to stringify an invalid square: {:?}", self ); write!( f, "{}{}", (self.file() + ASCII_1) as char, (self.rank() + ASCII_LOWER_A) as char ) } } pub mod consts { use super::Square; macro_rules! make_square { {0, $t:ident $($ts:ident)+} => { pub const $t: Square = Square { inner: 0 }; make_square!{1, $($ts)*} }; {$n:expr, $t:ident $($ts:ident)+} => { pub const $t: Square = Square { inner: $n }; make_square!{($n + 1), $($ts)*} }; {$n:expr, $t:ident} => { pub const $t: Square = Square { inner: $n }; }; } make_square! {0, SQ_1A SQ_1B SQ_1C SQ_1D SQ_1E SQ_1F SQ_1G SQ_1H SQ_1I SQ_2A SQ_2B SQ_2C SQ_2D SQ_2E SQ_2F SQ_2G SQ_2H SQ_2I SQ_3A SQ_3B SQ_3C SQ_3D SQ_3E SQ_3F SQ_3G SQ_3H SQ_3I SQ_4A SQ_4B SQ_4C SQ_4D SQ_4E SQ_4F SQ_4G SQ_4H SQ_4I SQ_5A SQ_5B SQ_5C SQ_5D SQ_5E SQ_5F SQ_5G SQ_5H SQ_5I SQ_6A SQ_6B SQ_6C SQ_6D SQ_6E SQ_6F SQ_6G SQ_6H SQ_6I SQ_7A SQ_7B SQ_7C SQ_7D SQ_7E SQ_7F SQ_7G SQ_7H SQ_7I SQ_8A SQ_8B SQ_8C SQ_8D SQ_8E SQ_8F SQ_8G SQ_8H SQ_8I SQ_9A SQ_9B SQ_9C SQ_9D SQ_9E SQ_9F SQ_9G SQ_9H SQ_9I} } /// This struct is created by the [`iter`] method on [`Square`]. /// /// [`iter`]:./struct.Square.html#method.iter /// [`Square`]: struct.Square.html pub struct SquareIter { current: u8, } impl iter::Iterator for SquareIter { type Item = Square; fn next(&mut self) -> Option<Self::Item> { let cur = self.current; if cur >= 81 { return None; } self.current += 1; Some(Square { inner: cur }) } } #[cfg(test)] mod tests { use super::*; #[test] fn new() { for file in 0..9 { for rank in 0..9 { let sq = Square::new(file, rank).unwrap(); assert_eq!(file, sq.file()); assert_eq!(rank, sq.rank()); } } assert_eq!(None, Square::new(10, 0)); assert_eq!(None, Square::new(0, 10)); assert_eq!(None, Square::new(10, 10)); } #[test] fn from_sfen() { let ok_cases = [ ("9a", 8, 0), ("1a", 0, 0), ("5e", 4, 4), ("9i", 8, 8), ("1i", 0, 8), ]; let ng_cases = ["", "9j", "_a", "a9", "9 ", " a", "9", "foo"]; for case in ok_cases.iter() { let sq = Square::from_sfen(case.0); assert!(sq.is_some()); assert_eq!(case.1, sq.unwrap().file()); assert_eq!(case.2, sq.unwrap().rank()); } for case in ng_cases.iter() { assert!( Square::from_sfen(case).is_none(), "{} should cause an error", case ); } } #[test] fn from_index() { for i in 0..81 { assert!(Square::from_index(i).is_some()); } assert!(Square::from_index(82).is_none()); } #[test] fn to_sfen() { let cases = [ ("9a", 8, 0), ("1a", 0, 0), ("5e", 4, 4), ("9i", 8, 8), ("1i", 0, 8), ]; for case in cases.iter() { let sq = Square::new(case.1, case.2).unwrap(); assert_eq!(case.0, sq.to_string()); } } #[test] fn shift() { let sq = consts::SQ_5E; let ok_cases = [ (-4, -4, 0, 0), (-4, 0, 0, 4), (0, -4, 4, 0), (0, 0, 4, 4), (4, 0, 8, 4), (0, 4, 4, 8), (4, 4, 8, 8), ]; let ng_cases = [(-5, -4), (-4, -5), (5, 0), (0, 5)]; for case in ok_cases.iter() { let shifted = sq.shift(case.0, case.1).unwrap(); assert_eq!(case.2, shifted.file()); assert_eq!(case.3, shifted.rank()); } for case in ng_cases.iter() { assert!(sq.shift(case.0, case.1).is_none()); } } #[test] fn relative_rank() { let cases = [ (0, 0, 0, 8), (0, 1, 1, 7), (0, 2, 2, 6), (0, 3, 3, 5), (0, 4, 4, 4), (0, 5, 5, 3), (0, 6, 6, 2), (0, 7, 7, 1), (0, 8, 8, 0), ]; for case in cases.iter() { let sq = Square::new(case.0, case.1).unwrap(); assert_eq!(case.2, sq.relative_rank(Color::Black)); assert_eq!(case.3, sq.relative_rank(Color::White)); } } #[test] fn in_promotion_zone() { let cases = [ (0, 0, true, false), (0, 1, true, false), (0, 2, true, false), (0, 3, false, false), (0, 4, false, false), (0, 5, false, false), (0, 6, false, true), (0, 7, false, true), (0, 8, false, true), ]; for case in cases.iter() { let sq = Square::new(case.0, case.1).unwrap(); assert_eq!(case.2, sq.in_promotion_zone(Color::Black)); assert_eq!(case.3, sq.in_promotion_zone(Color::White)); } } #[test] fn consts() { for (i, sq) in Square::iter().enumerate() { assert_eq!((i / 9) as u8, sq.file()); assert_eq!((i % 9) as u8, sq.rank()); } } }
} Some(Square { inner: index }) }
random_line_split
square.rs
use crate::Color; use std::fmt; use std::iter; const ASCII_1: u8 = b'1'; const ASCII_9: u8 = b'9'; const ASCII_LOWER_A: u8 = b'a'; const ASCII_LOWER_I: u8 = b'i'; /// Represents a position of each cell in the game board. /// /// # Examples /// /// ``` /// use shogi::Square; /// /// let sq = Square::new(4, 4).unwrap(); /// assert_eq!("5e", sq.to_string()); /// ``` /// /// `Square` can be created by parsing a SFEN formatted string as well. /// /// ``` /// use shogi::Square; /// /// let sq = Square::from_sfen("5e").unwrap(); /// assert_eq!(4, sq.file()); /// assert_eq!(4, sq.rank()); /// ``` #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] pub struct Square { inner: u8, } impl Square { /// Creates a new instance of `Square`. /// /// `file` can take a value from 0('1') to 8('9'), while `rank` is from 0('a') to 9('i'). pub fn new(file: u8, rank: u8) -> Option<Self> { if file > 8 || rank > 8 { return None; } Some(Square { inner: file * 9 + rank, }) } /// Creates a new instance of `Square` from SFEN formatted string. pub fn from_sfen(s: &str) -> Option<Self> { let bytes: &[u8] = s.as_bytes(); if bytes.len()!= 2 || bytes[0] < ASCII_1 || bytes[0] > ASCII_9 || bytes[1] < ASCII_LOWER_A || bytes[1] > ASCII_LOWER_I { return None; } let file = bytes[0] - ASCII_1; let rank = bytes[1] - ASCII_LOWER_A; debug_assert!( file < 9 && rank < 9, "{} parsed as (file: {}, rank: {})", s, file, rank ); Some(Square { inner: file * 9 + rank, }) } /// Creates a new instance of `Square` with the given index value. pub fn from_index(index: u8) -> Option<Self> { if index >= 81
Some(Square { inner: index }) } /// Returns an iterator of all variants. pub fn iter() -> SquareIter { SquareIter { current: 0 } } /// Returns a file of the square. pub fn file(self) -> u8 { self.inner / 9 } /// Returns a rank of the square. pub fn rank(self) -> u8 { self.inner % 9 } /// Returns a new `Square` instance by moving the file and the rank values. /// /// # Examples /// /// ``` /// use shogi::square::consts::*; /// /// let sq = SQ_2B; /// let shifted = sq.shift(2, 3).unwrap(); /// /// assert_eq!(3, shifted.file()); /// assert_eq!(4, shifted.rank()); /// ``` #[must_use] pub fn shift(self, df: i8, dr: i8) -> Option<Self> { let f = self.file() as i8 + df; let r = self.rank() as i8 + dr; if!(0..9).contains(&f) ||!(0..9).contains(&r) { return None; } Some(Square { inner: (f * 9 + r) as u8, }) } /// Returns a relative rank as if the specified color is black. /// /// # Examples /// /// ``` /// use shogi::Color; /// use shogi::square::consts::*; /// /// let sq = SQ_1G; /// /// assert_eq!(6, sq.relative_rank(Color::Black)); /// assert_eq!(2, sq.relative_rank(Color::White)); /// ``` pub fn relative_rank(self, c: Color) -> u8 { if c == Color::Black { self.rank() } else { 8 - self.rank() } } /// Tests if the square is in a promotion zone. pub fn in_promotion_zone(self, c: Color) -> bool { self.relative_rank(c) < 3 } /// Converts the instance into the unique number for array indexing purpose. #[inline(always)] pub fn index(self) -> usize { self.inner as usize } } impl fmt::Display for Square { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { debug_assert!( self.file() < 9 && self.rank() < 9, "trying to stringify an invalid square: {:?}", self ); write!( f, "{}{}", (self.file() + ASCII_1) as char, (self.rank() + ASCII_LOWER_A) as char ) } } pub mod consts { use super::Square; macro_rules! make_square { {0, $t:ident $($ts:ident)+} => { pub const $t: Square = Square { inner: 0 }; make_square!{1, $($ts)*} }; {$n:expr, $t:ident $($ts:ident)+} => { pub const $t: Square = Square { inner: $n }; make_square!{($n + 1), $($ts)*} }; {$n:expr, $t:ident} => { pub const $t: Square = Square { inner: $n }; }; } make_square! {0, SQ_1A SQ_1B SQ_1C SQ_1D SQ_1E SQ_1F SQ_1G SQ_1H SQ_1I SQ_2A SQ_2B SQ_2C SQ_2D SQ_2E SQ_2F SQ_2G SQ_2H SQ_2I SQ_3A SQ_3B SQ_3C SQ_3D SQ_3E SQ_3F SQ_3G SQ_3H SQ_3I SQ_4A SQ_4B SQ_4C SQ_4D SQ_4E SQ_4F SQ_4G SQ_4H SQ_4I SQ_5A SQ_5B SQ_5C SQ_5D SQ_5E SQ_5F SQ_5G SQ_5H SQ_5I SQ_6A SQ_6B SQ_6C SQ_6D SQ_6E SQ_6F SQ_6G SQ_6H SQ_6I SQ_7A SQ_7B SQ_7C SQ_7D SQ_7E SQ_7F SQ_7G SQ_7H SQ_7I SQ_8A SQ_8B SQ_8C SQ_8D SQ_8E SQ_8F SQ_8G SQ_8H SQ_8I SQ_9A SQ_9B SQ_9C SQ_9D SQ_9E SQ_9F SQ_9G SQ_9H SQ_9I} } /// This struct is created by the [`iter`] method on [`Square`]. /// /// [`iter`]:./struct.Square.html#method.iter /// [`Square`]: struct.Square.html pub struct SquareIter { current: u8, } impl iter::Iterator for SquareIter { type Item = Square; fn next(&mut self) -> Option<Self::Item> { let cur = self.current; if cur >= 81 { return None; } self.current += 1; Some(Square { inner: cur }) } } #[cfg(test)] mod tests { use super::*; #[test] fn new() { for file in 0..9 { for rank in 0..9 { let sq = Square::new(file, rank).unwrap(); assert_eq!(file, sq.file()); assert_eq!(rank, sq.rank()); } } assert_eq!(None, Square::new(10, 0)); assert_eq!(None, Square::new(0, 10)); assert_eq!(None, Square::new(10, 10)); } #[test] fn from_sfen() { let ok_cases = [ ("9a", 8, 0), ("1a", 0, 0), ("5e", 4, 4), ("9i", 8, 8), ("1i", 0, 8), ]; let ng_cases = ["", "9j", "_a", "a9", "9 ", " a", "9", "foo"]; for case in ok_cases.iter() { let sq = Square::from_sfen(case.0); assert!(sq.is_some()); assert_eq!(case.1, sq.unwrap().file()); assert_eq!(case.2, sq.unwrap().rank()); } for case in ng_cases.iter() { assert!( Square::from_sfen(case).is_none(), "{} should cause an error", case ); } } #[test] fn from_index() { for i in 0..81 { assert!(Square::from_index(i).is_some()); } assert!(Square::from_index(82).is_none()); } #[test] fn to_sfen() { let cases = [ ("9a", 8, 0), ("1a", 0, 0), ("5e", 4, 4), ("9i", 8, 8), ("1i", 0, 8), ]; for case in cases.iter() { let sq = Square::new(case.1, case.2).unwrap(); assert_eq!(case.0, sq.to_string()); } } #[test] fn shift() { let sq = consts::SQ_5E; let ok_cases = [ (-4, -4, 0, 0), (-4, 0, 0, 4), (0, -4, 4, 0), (0, 0, 4, 4), (4, 0, 8, 4), (0, 4, 4, 8), (4, 4, 8, 8), ]; let ng_cases = [(-5, -4), (-4, -5), (5, 0), (0, 5)]; for case in ok_cases.iter() { let shifted = sq.shift(case.0, case.1).unwrap(); assert_eq!(case.2, shifted.file()); assert_eq!(case.3, shifted.rank()); } for case in ng_cases.iter() { assert!(sq.shift(case.0, case.1).is_none()); } } #[test] fn relative_rank() { let cases = [ (0, 0, 0, 8), (0, 1, 1, 7), (0, 2, 2, 6), (0, 3, 3, 5), (0, 4, 4, 4), (0, 5, 5, 3), (0, 6, 6, 2), (0, 7, 7, 1), (0, 8, 8, 0), ]; for case in cases.iter() { let sq = Square::new(case.0, case.1).unwrap(); assert_eq!(case.2, sq.relative_rank(Color::Black)); assert_eq!(case.3, sq.relative_rank(Color::White)); } } #[test] fn in_promotion_zone() { let cases = [ (0, 0, true, false), (0, 1, true, false), (0, 2, true, false), (0, 3, false, false), (0, 4, false, false), (0, 5, false, false), (0, 6, false, true), (0, 7, false, true), (0, 8, false, true), ]; for case in cases.iter() { let sq = Square::new(case.0, case.1).unwrap(); assert_eq!(case.2, sq.in_promotion_zone(Color::Black)); assert_eq!(case.3, sq.in_promotion_zone(Color::White)); } } #[test] fn consts() { for (i, sq) in Square::iter().enumerate() { assert_eq!((i / 9) as u8, sq.file()); assert_eq!((i % 9) as u8, sq.rank()); } } }
{ return None; }
conditional_block
square.rs
use crate::Color; use std::fmt; use std::iter; const ASCII_1: u8 = b'1'; const ASCII_9: u8 = b'9'; const ASCII_LOWER_A: u8 = b'a'; const ASCII_LOWER_I: u8 = b'i'; /// Represents a position of each cell in the game board. /// /// # Examples /// /// ``` /// use shogi::Square; /// /// let sq = Square::new(4, 4).unwrap(); /// assert_eq!("5e", sq.to_string()); /// ``` /// /// `Square` can be created by parsing a SFEN formatted string as well. /// /// ``` /// use shogi::Square; /// /// let sq = Square::from_sfen("5e").unwrap(); /// assert_eq!(4, sq.file()); /// assert_eq!(4, sq.rank()); /// ``` #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] pub struct Square { inner: u8, } impl Square { /// Creates a new instance of `Square`. /// /// `file` can take a value from 0('1') to 8('9'), while `rank` is from 0('a') to 9('i'). pub fn new(file: u8, rank: u8) -> Option<Self> { if file > 8 || rank > 8 { return None; } Some(Square { inner: file * 9 + rank, }) } /// Creates a new instance of `Square` from SFEN formatted string. pub fn from_sfen(s: &str) -> Option<Self> { let bytes: &[u8] = s.as_bytes(); if bytes.len()!= 2 || bytes[0] < ASCII_1 || bytes[0] > ASCII_9 || bytes[1] < ASCII_LOWER_A || bytes[1] > ASCII_LOWER_I { return None; } let file = bytes[0] - ASCII_1; let rank = bytes[1] - ASCII_LOWER_A; debug_assert!( file < 9 && rank < 9, "{} parsed as (file: {}, rank: {})", s, file, rank ); Some(Square { inner: file * 9 + rank, }) } /// Creates a new instance of `Square` with the given index value. pub fn from_index(index: u8) -> Option<Self> { if index >= 81 { return None; } Some(Square { inner: index }) } /// Returns an iterator of all variants. pub fn iter() -> SquareIter { SquareIter { current: 0 } } /// Returns a file of the square. pub fn file(self) -> u8 { self.inner / 9 } /// Returns a rank of the square. pub fn rank(self) -> u8 { self.inner % 9 } /// Returns a new `Square` instance by moving the file and the rank values. /// /// # Examples /// /// ``` /// use shogi::square::consts::*; /// /// let sq = SQ_2B; /// let shifted = sq.shift(2, 3).unwrap(); /// /// assert_eq!(3, shifted.file()); /// assert_eq!(4, shifted.rank()); /// ``` #[must_use] pub fn shift(self, df: i8, dr: i8) -> Option<Self> { let f = self.file() as i8 + df; let r = self.rank() as i8 + dr; if!(0..9).contains(&f) ||!(0..9).contains(&r) { return None; } Some(Square { inner: (f * 9 + r) as u8, }) } /// Returns a relative rank as if the specified color is black. /// /// # Examples /// /// ``` /// use shogi::Color; /// use shogi::square::consts::*; /// /// let sq = SQ_1G; /// /// assert_eq!(6, sq.relative_rank(Color::Black)); /// assert_eq!(2, sq.relative_rank(Color::White)); /// ``` pub fn relative_rank(self, c: Color) -> u8 { if c == Color::Black { self.rank() } else { 8 - self.rank() } } /// Tests if the square is in a promotion zone. pub fn in_promotion_zone(self, c: Color) -> bool { self.relative_rank(c) < 3 } /// Converts the instance into the unique number for array indexing purpose. #[inline(always)] pub fn index(self) -> usize { self.inner as usize } } impl fmt::Display for Square { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { debug_assert!( self.file() < 9 && self.rank() < 9, "trying to stringify an invalid square: {:?}", self ); write!( f, "{}{}", (self.file() + ASCII_1) as char, (self.rank() + ASCII_LOWER_A) as char ) } } pub mod consts { use super::Square; macro_rules! make_square { {0, $t:ident $($ts:ident)+} => { pub const $t: Square = Square { inner: 0 }; make_square!{1, $($ts)*} }; {$n:expr, $t:ident $($ts:ident)+} => { pub const $t: Square = Square { inner: $n }; make_square!{($n + 1), $($ts)*} }; {$n:expr, $t:ident} => { pub const $t: Square = Square { inner: $n }; }; } make_square! {0, SQ_1A SQ_1B SQ_1C SQ_1D SQ_1E SQ_1F SQ_1G SQ_1H SQ_1I SQ_2A SQ_2B SQ_2C SQ_2D SQ_2E SQ_2F SQ_2G SQ_2H SQ_2I SQ_3A SQ_3B SQ_3C SQ_3D SQ_3E SQ_3F SQ_3G SQ_3H SQ_3I SQ_4A SQ_4B SQ_4C SQ_4D SQ_4E SQ_4F SQ_4G SQ_4H SQ_4I SQ_5A SQ_5B SQ_5C SQ_5D SQ_5E SQ_5F SQ_5G SQ_5H SQ_5I SQ_6A SQ_6B SQ_6C SQ_6D SQ_6E SQ_6F SQ_6G SQ_6H SQ_6I SQ_7A SQ_7B SQ_7C SQ_7D SQ_7E SQ_7F SQ_7G SQ_7H SQ_7I SQ_8A SQ_8B SQ_8C SQ_8D SQ_8E SQ_8F SQ_8G SQ_8H SQ_8I SQ_9A SQ_9B SQ_9C SQ_9D SQ_9E SQ_9F SQ_9G SQ_9H SQ_9I} } /// This struct is created by the [`iter`] method on [`Square`]. /// /// [`iter`]:./struct.Square.html#method.iter /// [`Square`]: struct.Square.html pub struct SquareIter { current: u8, } impl iter::Iterator for SquareIter { type Item = Square; fn next(&mut self) -> Option<Self::Item> { let cur = self.current; if cur >= 81 { return None; } self.current += 1; Some(Square { inner: cur }) } } #[cfg(test)] mod tests { use super::*; #[test] fn new()
#[test] fn from_sfen() { let ok_cases = [ ("9a", 8, 0), ("1a", 0, 0), ("5e", 4, 4), ("9i", 8, 8), ("1i", 0, 8), ]; let ng_cases = ["", "9j", "_a", "a9", "9 ", " a", "9", "foo"]; for case in ok_cases.iter() { let sq = Square::from_sfen(case.0); assert!(sq.is_some()); assert_eq!(case.1, sq.unwrap().file()); assert_eq!(case.2, sq.unwrap().rank()); } for case in ng_cases.iter() { assert!( Square::from_sfen(case).is_none(), "{} should cause an error", case ); } } #[test] fn from_index() { for i in 0..81 { assert!(Square::from_index(i).is_some()); } assert!(Square::from_index(82).is_none()); } #[test] fn to_sfen() { let cases = [ ("9a", 8, 0), ("1a", 0, 0), ("5e", 4, 4), ("9i", 8, 8), ("1i", 0, 8), ]; for case in cases.iter() { let sq = Square::new(case.1, case.2).unwrap(); assert_eq!(case.0, sq.to_string()); } } #[test] fn shift() { let sq = consts::SQ_5E; let ok_cases = [ (-4, -4, 0, 0), (-4, 0, 0, 4), (0, -4, 4, 0), (0, 0, 4, 4), (4, 0, 8, 4), (0, 4, 4, 8), (4, 4, 8, 8), ]; let ng_cases = [(-5, -4), (-4, -5), (5, 0), (0, 5)]; for case in ok_cases.iter() { let shifted = sq.shift(case.0, case.1).unwrap(); assert_eq!(case.2, shifted.file()); assert_eq!(case.3, shifted.rank()); } for case in ng_cases.iter() { assert!(sq.shift(case.0, case.1).is_none()); } } #[test] fn relative_rank() { let cases = [ (0, 0, 0, 8), (0, 1, 1, 7), (0, 2, 2, 6), (0, 3, 3, 5), (0, 4, 4, 4), (0, 5, 5, 3), (0, 6, 6, 2), (0, 7, 7, 1), (0, 8, 8, 0), ]; for case in cases.iter() { let sq = Square::new(case.0, case.1).unwrap(); assert_eq!(case.2, sq.relative_rank(Color::Black)); assert_eq!(case.3, sq.relative_rank(Color::White)); } } #[test] fn in_promotion_zone() { let cases = [ (0, 0, true, false), (0, 1, true, false), (0, 2, true, false), (0, 3, false, false), (0, 4, false, false), (0, 5, false, false), (0, 6, false, true), (0, 7, false, true), (0, 8, false, true), ]; for case in cases.iter() { let sq = Square::new(case.0, case.1).unwrap(); assert_eq!(case.2, sq.in_promotion_zone(Color::Black)); assert_eq!(case.3, sq.in_promotion_zone(Color::White)); } } #[test] fn consts() { for (i, sq) in Square::iter().enumerate() { assert_eq!((i / 9) as u8, sq.file()); assert_eq!((i % 9) as u8, sq.rank()); } } }
{ for file in 0..9 { for rank in 0..9 { let sq = Square::new(file, rank).unwrap(); assert_eq!(file, sq.file()); assert_eq!(rank, sq.rank()); } } assert_eq!(None, Square::new(10, 0)); assert_eq!(None, Square::new(0, 10)); assert_eq!(None, Square::new(10, 10)); }
identifier_body
square.rs
use crate::Color; use std::fmt; use std::iter; const ASCII_1: u8 = b'1'; const ASCII_9: u8 = b'9'; const ASCII_LOWER_A: u8 = b'a'; const ASCII_LOWER_I: u8 = b'i'; /// Represents a position of each cell in the game board. /// /// # Examples /// /// ``` /// use shogi::Square; /// /// let sq = Square::new(4, 4).unwrap(); /// assert_eq!("5e", sq.to_string()); /// ``` /// /// `Square` can be created by parsing a SFEN formatted string as well. /// /// ``` /// use shogi::Square; /// /// let sq = Square::from_sfen("5e").unwrap(); /// assert_eq!(4, sq.file()); /// assert_eq!(4, sq.rank()); /// ``` #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] pub struct Square { inner: u8, } impl Square { /// Creates a new instance of `Square`. /// /// `file` can take a value from 0('1') to 8('9'), while `rank` is from 0('a') to 9('i'). pub fn new(file: u8, rank: u8) -> Option<Self> { if file > 8 || rank > 8 { return None; } Some(Square { inner: file * 9 + rank, }) } /// Creates a new instance of `Square` from SFEN formatted string. pub fn from_sfen(s: &str) -> Option<Self> { let bytes: &[u8] = s.as_bytes(); if bytes.len()!= 2 || bytes[0] < ASCII_1 || bytes[0] > ASCII_9 || bytes[1] < ASCII_LOWER_A || bytes[1] > ASCII_LOWER_I { return None; } let file = bytes[0] - ASCII_1; let rank = bytes[1] - ASCII_LOWER_A; debug_assert!( file < 9 && rank < 9, "{} parsed as (file: {}, rank: {})", s, file, rank ); Some(Square { inner: file * 9 + rank, }) } /// Creates a new instance of `Square` with the given index value. pub fn from_index(index: u8) -> Option<Self> { if index >= 81 { return None; } Some(Square { inner: index }) } /// Returns an iterator of all variants. pub fn iter() -> SquareIter { SquareIter { current: 0 } } /// Returns a file of the square. pub fn file(self) -> u8 { self.inner / 9 } /// Returns a rank of the square. pub fn rank(self) -> u8 { self.inner % 9 } /// Returns a new `Square` instance by moving the file and the rank values. /// /// # Examples /// /// ``` /// use shogi::square::consts::*; /// /// let sq = SQ_2B; /// let shifted = sq.shift(2, 3).unwrap(); /// /// assert_eq!(3, shifted.file()); /// assert_eq!(4, shifted.rank()); /// ``` #[must_use] pub fn shift(self, df: i8, dr: i8) -> Option<Self> { let f = self.file() as i8 + df; let r = self.rank() as i8 + dr; if!(0..9).contains(&f) ||!(0..9).contains(&r) { return None; } Some(Square { inner: (f * 9 + r) as u8, }) } /// Returns a relative rank as if the specified color is black. /// /// # Examples /// /// ``` /// use shogi::Color; /// use shogi::square::consts::*; /// /// let sq = SQ_1G; /// /// assert_eq!(6, sq.relative_rank(Color::Black)); /// assert_eq!(2, sq.relative_rank(Color::White)); /// ``` pub fn relative_rank(self, c: Color) -> u8 { if c == Color::Black { self.rank() } else { 8 - self.rank() } } /// Tests if the square is in a promotion zone. pub fn in_promotion_zone(self, c: Color) -> bool { self.relative_rank(c) < 3 } /// Converts the instance into the unique number for array indexing purpose. #[inline(always)] pub fn index(self) -> usize { self.inner as usize } } impl fmt::Display for Square { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { debug_assert!( self.file() < 9 && self.rank() < 9, "trying to stringify an invalid square: {:?}", self ); write!( f, "{}{}", (self.file() + ASCII_1) as char, (self.rank() + ASCII_LOWER_A) as char ) } } pub mod consts { use super::Square; macro_rules! make_square { {0, $t:ident $($ts:ident)+} => { pub const $t: Square = Square { inner: 0 }; make_square!{1, $($ts)*} }; {$n:expr, $t:ident $($ts:ident)+} => { pub const $t: Square = Square { inner: $n }; make_square!{($n + 1), $($ts)*} }; {$n:expr, $t:ident} => { pub const $t: Square = Square { inner: $n }; }; } make_square! {0, SQ_1A SQ_1B SQ_1C SQ_1D SQ_1E SQ_1F SQ_1G SQ_1H SQ_1I SQ_2A SQ_2B SQ_2C SQ_2D SQ_2E SQ_2F SQ_2G SQ_2H SQ_2I SQ_3A SQ_3B SQ_3C SQ_3D SQ_3E SQ_3F SQ_3G SQ_3H SQ_3I SQ_4A SQ_4B SQ_4C SQ_4D SQ_4E SQ_4F SQ_4G SQ_4H SQ_4I SQ_5A SQ_5B SQ_5C SQ_5D SQ_5E SQ_5F SQ_5G SQ_5H SQ_5I SQ_6A SQ_6B SQ_6C SQ_6D SQ_6E SQ_6F SQ_6G SQ_6H SQ_6I SQ_7A SQ_7B SQ_7C SQ_7D SQ_7E SQ_7F SQ_7G SQ_7H SQ_7I SQ_8A SQ_8B SQ_8C SQ_8D SQ_8E SQ_8F SQ_8G SQ_8H SQ_8I SQ_9A SQ_9B SQ_9C SQ_9D SQ_9E SQ_9F SQ_9G SQ_9H SQ_9I} } /// This struct is created by the [`iter`] method on [`Square`]. /// /// [`iter`]:./struct.Square.html#method.iter /// [`Square`]: struct.Square.html pub struct SquareIter { current: u8, } impl iter::Iterator for SquareIter { type Item = Square; fn next(&mut self) -> Option<Self::Item> { let cur = self.current; if cur >= 81 { return None; } self.current += 1; Some(Square { inner: cur }) } } #[cfg(test)] mod tests { use super::*; #[test] fn new() { for file in 0..9 { for rank in 0..9 { let sq = Square::new(file, rank).unwrap(); assert_eq!(file, sq.file()); assert_eq!(rank, sq.rank()); } } assert_eq!(None, Square::new(10, 0)); assert_eq!(None, Square::new(0, 10)); assert_eq!(None, Square::new(10, 10)); } #[test] fn from_sfen() { let ok_cases = [ ("9a", 8, 0), ("1a", 0, 0), ("5e", 4, 4), ("9i", 8, 8), ("1i", 0, 8), ]; let ng_cases = ["", "9j", "_a", "a9", "9 ", " a", "9", "foo"]; for case in ok_cases.iter() { let sq = Square::from_sfen(case.0); assert!(sq.is_some()); assert_eq!(case.1, sq.unwrap().file()); assert_eq!(case.2, sq.unwrap().rank()); } for case in ng_cases.iter() { assert!( Square::from_sfen(case).is_none(), "{} should cause an error", case ); } } #[test] fn from_index() { for i in 0..81 { assert!(Square::from_index(i).is_some()); } assert!(Square::from_index(82).is_none()); } #[test] fn
() { let cases = [ ("9a", 8, 0), ("1a", 0, 0), ("5e", 4, 4), ("9i", 8, 8), ("1i", 0, 8), ]; for case in cases.iter() { let sq = Square::new(case.1, case.2).unwrap(); assert_eq!(case.0, sq.to_string()); } } #[test] fn shift() { let sq = consts::SQ_5E; let ok_cases = [ (-4, -4, 0, 0), (-4, 0, 0, 4), (0, -4, 4, 0), (0, 0, 4, 4), (4, 0, 8, 4), (0, 4, 4, 8), (4, 4, 8, 8), ]; let ng_cases = [(-5, -4), (-4, -5), (5, 0), (0, 5)]; for case in ok_cases.iter() { let shifted = sq.shift(case.0, case.1).unwrap(); assert_eq!(case.2, shifted.file()); assert_eq!(case.3, shifted.rank()); } for case in ng_cases.iter() { assert!(sq.shift(case.0, case.1).is_none()); } } #[test] fn relative_rank() { let cases = [ (0, 0, 0, 8), (0, 1, 1, 7), (0, 2, 2, 6), (0, 3, 3, 5), (0, 4, 4, 4), (0, 5, 5, 3), (0, 6, 6, 2), (0, 7, 7, 1), (0, 8, 8, 0), ]; for case in cases.iter() { let sq = Square::new(case.0, case.1).unwrap(); assert_eq!(case.2, sq.relative_rank(Color::Black)); assert_eq!(case.3, sq.relative_rank(Color::White)); } } #[test] fn in_promotion_zone() { let cases = [ (0, 0, true, false), (0, 1, true, false), (0, 2, true, false), (0, 3, false, false), (0, 4, false, false), (0, 5, false, false), (0, 6, false, true), (0, 7, false, true), (0, 8, false, true), ]; for case in cases.iter() { let sq = Square::new(case.0, case.1).unwrap(); assert_eq!(case.2, sq.in_promotion_zone(Color::Black)); assert_eq!(case.3, sq.in_promotion_zone(Color::White)); } } #[test] fn consts() { for (i, sq) in Square::iter().enumerate() { assert_eq!((i / 9) as u8, sq.file()); assert_eq!((i % 9) as u8, sq.rank()); } } }
to_sfen
identifier_name
reference-to-struct.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-win32 Broken because of LLVM bug: http://llvm.org/bugs/show_bug.cgi?id=16249 // GDB doesn't know about UTF-32 character encoding and will print a rust char as only its numerical // value. // compile-flags:-Z extra-debug-info // debugger:break zzz // debugger:run // debugger:finish // debugger:print *stack_val_ref // check:$1 = {x = 10, y = 23.5} // debugger:print *stack_val_interior_ref_1 // check:$2 = 10 // debugger:print *stack_val_interior_ref_2 // check:$3 = 23.5 // debugger:print *ref_to_unnamed // check:$4 = {x = 11, y = 24.5} // debugger:print *managed_val_ref // check:$5 = {x = 12, y = 25.5} // debugger:print *managed_val_interior_ref_1 // check:$6 = 12 // debugger:print *managed_val_interior_ref_2 // check:$7 = 25.5 // debugger:print *unique_val_ref // check:$8 = {x = 13, y = 26.5} // debugger:print *unique_val_interior_ref_1 // check:$9 = 13 // debugger:print *unique_val_interior_ref_2 // check:$10 = 26.5 struct SomeStruct { x: int, y: f64 } fn main()
fn zzz() {()}
{ let stack_val: SomeStruct = SomeStruct { x: 10, y: 23.5 }; let stack_val_ref : &SomeStruct = &stack_val; let stack_val_interior_ref_1 : &int = &stack_val.x; let stack_val_interior_ref_2 : &f64 = &stack_val.y; let ref_to_unnamed : &SomeStruct = &SomeStruct { x: 11, y: 24.5 }; let managed_val = @SomeStruct { x: 12, y: 25.5 }; let managed_val_ref : &SomeStruct = managed_val; let managed_val_interior_ref_1 : &int = &managed_val.x; let managed_val_interior_ref_2 : &f64 = &managed_val.y; let unique_val = ~SomeStruct { x: 13, y: 26.5 }; let unique_val_ref : &SomeStruct = unique_val; let unique_val_interior_ref_1 : &int = &unique_val.x; let unique_val_interior_ref_2 : &f64 = &unique_val.y; zzz(); }
identifier_body
reference-to-struct.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
// GDB doesn't know about UTF-32 character encoding and will print a rust char as only its numerical // value. // compile-flags:-Z extra-debug-info // debugger:break zzz // debugger:run // debugger:finish // debugger:print *stack_val_ref // check:$1 = {x = 10, y = 23.5} // debugger:print *stack_val_interior_ref_1 // check:$2 = 10 // debugger:print *stack_val_interior_ref_2 // check:$3 = 23.5 // debugger:print *ref_to_unnamed // check:$4 = {x = 11, y = 24.5} // debugger:print *managed_val_ref // check:$5 = {x = 12, y = 25.5} // debugger:print *managed_val_interior_ref_1 // check:$6 = 12 // debugger:print *managed_val_interior_ref_2 // check:$7 = 25.5 // debugger:print *unique_val_ref // check:$8 = {x = 13, y = 26.5} // debugger:print *unique_val_interior_ref_1 // check:$9 = 13 // debugger:print *unique_val_interior_ref_2 // check:$10 = 26.5 struct SomeStruct { x: int, y: f64 } fn main() { let stack_val: SomeStruct = SomeStruct { x: 10, y: 23.5 }; let stack_val_ref : &SomeStruct = &stack_val; let stack_val_interior_ref_1 : &int = &stack_val.x; let stack_val_interior_ref_2 : &f64 = &stack_val.y; let ref_to_unnamed : &SomeStruct = &SomeStruct { x: 11, y: 24.5 }; let managed_val = @SomeStruct { x: 12, y: 25.5 }; let managed_val_ref : &SomeStruct = managed_val; let managed_val_interior_ref_1 : &int = &managed_val.x; let managed_val_interior_ref_2 : &f64 = &managed_val.y; let unique_val = ~SomeStruct { x: 13, y: 26.5 }; let unique_val_ref : &SomeStruct = unique_val; let unique_val_interior_ref_1 : &int = &unique_val.x; let unique_val_interior_ref_2 : &f64 = &unique_val.y; zzz(); } fn zzz() {()}
// xfail-win32 Broken because of LLVM bug: http://llvm.org/bugs/show_bug.cgi?id=16249
random_line_split
reference-to-struct.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-win32 Broken because of LLVM bug: http://llvm.org/bugs/show_bug.cgi?id=16249 // GDB doesn't know about UTF-32 character encoding and will print a rust char as only its numerical // value. // compile-flags:-Z extra-debug-info // debugger:break zzz // debugger:run // debugger:finish // debugger:print *stack_val_ref // check:$1 = {x = 10, y = 23.5} // debugger:print *stack_val_interior_ref_1 // check:$2 = 10 // debugger:print *stack_val_interior_ref_2 // check:$3 = 23.5 // debugger:print *ref_to_unnamed // check:$4 = {x = 11, y = 24.5} // debugger:print *managed_val_ref // check:$5 = {x = 12, y = 25.5} // debugger:print *managed_val_interior_ref_1 // check:$6 = 12 // debugger:print *managed_val_interior_ref_2 // check:$7 = 25.5 // debugger:print *unique_val_ref // check:$8 = {x = 13, y = 26.5} // debugger:print *unique_val_interior_ref_1 // check:$9 = 13 // debugger:print *unique_val_interior_ref_2 // check:$10 = 26.5 struct SomeStruct { x: int, y: f64 } fn
() { let stack_val: SomeStruct = SomeStruct { x: 10, y: 23.5 }; let stack_val_ref : &SomeStruct = &stack_val; let stack_val_interior_ref_1 : &int = &stack_val.x; let stack_val_interior_ref_2 : &f64 = &stack_val.y; let ref_to_unnamed : &SomeStruct = &SomeStruct { x: 11, y: 24.5 }; let managed_val = @SomeStruct { x: 12, y: 25.5 }; let managed_val_ref : &SomeStruct = managed_val; let managed_val_interior_ref_1 : &int = &managed_val.x; let managed_val_interior_ref_2 : &f64 = &managed_val.y; let unique_val = ~SomeStruct { x: 13, y: 26.5 }; let unique_val_ref : &SomeStruct = unique_val; let unique_val_interior_ref_1 : &int = &unique_val.x; let unique_val_interior_ref_2 : &f64 = &unique_val.y; zzz(); } fn zzz() {()}
main
identifier_name
search.rs
use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap, HashSet}; use std::hash::Hash; /// A node in a graph with a regular grid. pub trait GridNode: PartialEq + Eq + Clone + Hash + PartialOrd + Ord { /// List the neighbor nodes of this graph node. fn neighbors(&self) -> Vec<Self>; } /// A pathfinding map structure. /// /// A Dijkstra map lets you run pathfinding from any graph node it covers /// towards or away from the target nodes of the map. Currently the structure /// only supports underlying graphs with a fixed grid graph where the /// neighbors of each node must be the adjacent grid cells of that node. pub struct Dijkstra<N> { pub weights: HashMap<N, u32>, } impl<N: GridNode> Dijkstra<N> { /// Create a new Dijkstra map up to limit distance from goals, omitting /// nodes for which the is_valid predicate returns false. pub fn new<F: Fn(&N) -> bool>(goals: Vec<N>, is_valid: F, limit: u32) -> Dijkstra<N> { assert!(!goals.is_empty()); let mut weights = HashMap::new(); let mut edge = HashSet::new(); for n in goals { edge.insert(n); } for dist in 0..(limit) {
let mut new_edge = HashSet::new(); for n in &edge { for m in n.neighbors() { if is_valid(&m) &&!weights.contains_key(&m) { new_edge.insert(m); } } } edge = new_edge; if edge.is_empty() { break; } } Dijkstra { weights } } /// Return the neighbors of a cell (if any), sorted from downhill to /// uphill. pub fn sorted_neighbors(&self, node: &N) -> Vec<N> { let mut ret = Vec::new(); for n in &node.neighbors() { if let Some(w) = self.weights.get(n) { ret.push((w, n.clone())); } } ret.sort_by(|&(w1, _), &(w2, _)| w1.cmp(w2)); ret.into_iter().map(|(_, n)| n).collect() } } /// Find A* path in freeform graph. /// /// The `neighbors` function returns neighboring nodes and their estimated distance from the goal. /// The search will treat any node whose distance is zero as a goal and return a path leading to /// it. pub fn astar_path<N, F>(start: N, end: &N, neighbors: F) -> Option<Vec<N>> where N: Eq + Hash + Clone, F: Fn(&N) -> Vec<(N, f32)>, { #[derive(Eq, PartialEq)] struct MetricNode<N> { value: u32, item: N, come_from: Option<N>, } impl<N: Eq> Ord for MetricNode<N> { fn cmp(&self, other: &Self) -> Ordering { self.value.cmp(&other.value) } } impl<N: Eq> PartialOrd for MetricNode<N> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } fn node<N: Eq>(item: N, dist: f32, come_from: Option<N>) -> MetricNode<N> { debug_assert!(dist >= 0.0); // Convert dist to integers so we can push MetricNodes into BinaryHeap that expects Ord. // The trick here is that non-negative IEEE 754 floats have the same ordering as their // binary representations interpreted as integers. // // Also flip the sign on the value, shorter distance means bigger value, since BinaryHeap // returns the largest item first. let value = ::std::u32::MAX - dist.to_bits(); MetricNode { item, value, come_from, } } let mut come_from = HashMap::new(); let mut open = BinaryHeap::new(); open.push(node(start.clone(), ::std::f32::MAX, None)); // Find shortest path. let mut goal = loop { if let Some(closest) = open.pop() { if come_from.contains_key(&closest.item) { // Already saw it through a presumably shorter path... continue; } if let Some(from) = closest.come_from { come_from.insert(closest.item.clone(), from); } if &closest.item == end { break Some(closest.item); } for (item, dist) in neighbors(&closest.item) { let already_seen = come_from.contains_key(&item) || item == start; if already_seen { continue; } open.push(node(item, dist, Some(closest.item.clone()))); } } else { break None; } }; // Extract path from the graph structure. let mut path = Vec::new(); while let Some(x) = goal { goal = come_from.remove(&x); path.push(x); } path.reverse(); if path.is_empty() { None } else { Some(path) } } #[cfg(test)] mod test { use super::*; #[test] fn test_astar() { fn neighbors(origin: i32, &x: &i32) -> Vec<(i32, f32)> { let mut ret = Vec::with_capacity(2); for i in &[-1, 1] { let x = x + i; ret.push((x, (x - origin).abs() as f32)); } ret } assert_eq!(Some(vec![8]), astar_path(8, &8, |_| Vec::new())); assert_eq!(None, astar_path(8, &12, |_| Vec::new())); assert_eq!(Some(vec![8]), astar_path(8, &8, |x| neighbors(8, x))); assert_eq!( Some(vec![8, 9, 10, 11, 12]), astar_path(8, &12, |x| neighbors(8, x)) ); } }
for n in &edge { weights.insert(n.clone(), dist); }
random_line_split
search.rs
use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap, HashSet}; use std::hash::Hash; /// A node in a graph with a regular grid. pub trait GridNode: PartialEq + Eq + Clone + Hash + PartialOrd + Ord { /// List the neighbor nodes of this graph node. fn neighbors(&self) -> Vec<Self>; } /// A pathfinding map structure. /// /// A Dijkstra map lets you run pathfinding from any graph node it covers /// towards or away from the target nodes of the map. Currently the structure /// only supports underlying graphs with a fixed grid graph where the /// neighbors of each node must be the adjacent grid cells of that node. pub struct Dijkstra<N> { pub weights: HashMap<N, u32>, } impl<N: GridNode> Dijkstra<N> { /// Create a new Dijkstra map up to limit distance from goals, omitting /// nodes for which the is_valid predicate returns false. pub fn new<F: Fn(&N) -> bool>(goals: Vec<N>, is_valid: F, limit: u32) -> Dijkstra<N> { assert!(!goals.is_empty()); let mut weights = HashMap::new(); let mut edge = HashSet::new(); for n in goals { edge.insert(n); } for dist in 0..(limit) { for n in &edge { weights.insert(n.clone(), dist); } let mut new_edge = HashSet::new(); for n in &edge { for m in n.neighbors() { if is_valid(&m) &&!weights.contains_key(&m) { new_edge.insert(m); } } } edge = new_edge; if edge.is_empty() { break; } } Dijkstra { weights } } /// Return the neighbors of a cell (if any), sorted from downhill to /// uphill. pub fn sorted_neighbors(&self, node: &N) -> Vec<N> { let mut ret = Vec::new(); for n in &node.neighbors() { if let Some(w) = self.weights.get(n) { ret.push((w, n.clone())); } } ret.sort_by(|&(w1, _), &(w2, _)| w1.cmp(w2)); ret.into_iter().map(|(_, n)| n).collect() } } /// Find A* path in freeform graph. /// /// The `neighbors` function returns neighboring nodes and their estimated distance from the goal. /// The search will treat any node whose distance is zero as a goal and return a path leading to /// it. pub fn astar_path<N, F>(start: N, end: &N, neighbors: F) -> Option<Vec<N>> where N: Eq + Hash + Clone, F: Fn(&N) -> Vec<(N, f32)>, { #[derive(Eq, PartialEq)] struct MetricNode<N> { value: u32, item: N, come_from: Option<N>, } impl<N: Eq> Ord for MetricNode<N> { fn cmp(&self, other: &Self) -> Ordering { self.value.cmp(&other.value) } } impl<N: Eq> PartialOrd for MetricNode<N> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } fn node<N: Eq>(item: N, dist: f32, come_from: Option<N>) -> MetricNode<N> { debug_assert!(dist >= 0.0); // Convert dist to integers so we can push MetricNodes into BinaryHeap that expects Ord. // The trick here is that non-negative IEEE 754 floats have the same ordering as their // binary representations interpreted as integers. // // Also flip the sign on the value, shorter distance means bigger value, since BinaryHeap // returns the largest item first. let value = ::std::u32::MAX - dist.to_bits(); MetricNode { item, value, come_from, } } let mut come_from = HashMap::new(); let mut open = BinaryHeap::new(); open.push(node(start.clone(), ::std::f32::MAX, None)); // Find shortest path. let mut goal = loop { if let Some(closest) = open.pop() { if come_from.contains_key(&closest.item) { // Already saw it through a presumably shorter path... continue; } if let Some(from) = closest.come_from { come_from.insert(closest.item.clone(), from); } if &closest.item == end { break Some(closest.item); } for (item, dist) in neighbors(&closest.item) { let already_seen = come_from.contains_key(&item) || item == start; if already_seen { continue; } open.push(node(item, dist, Some(closest.item.clone()))); } } else { break None; } }; // Extract path from the graph structure. let mut path = Vec::new(); while let Some(x) = goal { goal = come_from.remove(&x); path.push(x); } path.reverse(); if path.is_empty()
else { Some(path) } } #[cfg(test)] mod test { use super::*; #[test] fn test_astar() { fn neighbors(origin: i32, &x: &i32) -> Vec<(i32, f32)> { let mut ret = Vec::with_capacity(2); for i in &[-1, 1] { let x = x + i; ret.push((x, (x - origin).abs() as f32)); } ret } assert_eq!(Some(vec![8]), astar_path(8, &8, |_| Vec::new())); assert_eq!(None, astar_path(8, &12, |_| Vec::new())); assert_eq!(Some(vec![8]), astar_path(8, &8, |x| neighbors(8, x))); assert_eq!( Some(vec![8, 9, 10, 11, 12]), astar_path(8, &12, |x| neighbors(8, x)) ); } }
{ None }
conditional_block
search.rs
use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap, HashSet}; use std::hash::Hash; /// A node in a graph with a regular grid. pub trait GridNode: PartialEq + Eq + Clone + Hash + PartialOrd + Ord { /// List the neighbor nodes of this graph node. fn neighbors(&self) -> Vec<Self>; } /// A pathfinding map structure. /// /// A Dijkstra map lets you run pathfinding from any graph node it covers /// towards or away from the target nodes of the map. Currently the structure /// only supports underlying graphs with a fixed grid graph where the /// neighbors of each node must be the adjacent grid cells of that node. pub struct Dijkstra<N> { pub weights: HashMap<N, u32>, } impl<N: GridNode> Dijkstra<N> { /// Create a new Dijkstra map up to limit distance from goals, omitting /// nodes for which the is_valid predicate returns false. pub fn new<F: Fn(&N) -> bool>(goals: Vec<N>, is_valid: F, limit: u32) -> Dijkstra<N> { assert!(!goals.is_empty()); let mut weights = HashMap::new(); let mut edge = HashSet::new(); for n in goals { edge.insert(n); } for dist in 0..(limit) { for n in &edge { weights.insert(n.clone(), dist); } let mut new_edge = HashSet::new(); for n in &edge { for m in n.neighbors() { if is_valid(&m) &&!weights.contains_key(&m) { new_edge.insert(m); } } } edge = new_edge; if edge.is_empty() { break; } } Dijkstra { weights } } /// Return the neighbors of a cell (if any), sorted from downhill to /// uphill. pub fn sorted_neighbors(&self, node: &N) -> Vec<N> { let mut ret = Vec::new(); for n in &node.neighbors() { if let Some(w) = self.weights.get(n) { ret.push((w, n.clone())); } } ret.sort_by(|&(w1, _), &(w2, _)| w1.cmp(w2)); ret.into_iter().map(|(_, n)| n).collect() } } /// Find A* path in freeform graph. /// /// The `neighbors` function returns neighboring nodes and their estimated distance from the goal. /// The search will treat any node whose distance is zero as a goal and return a path leading to /// it. pub fn astar_path<N, F>(start: N, end: &N, neighbors: F) -> Option<Vec<N>> where N: Eq + Hash + Clone, F: Fn(&N) -> Vec<(N, f32)>, { #[derive(Eq, PartialEq)] struct MetricNode<N> { value: u32, item: N, come_from: Option<N>, } impl<N: Eq> Ord for MetricNode<N> { fn cmp(&self, other: &Self) -> Ordering { self.value.cmp(&other.value) } } impl<N: Eq> PartialOrd for MetricNode<N> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } fn node<N: Eq>(item: N, dist: f32, come_from: Option<N>) -> MetricNode<N> { debug_assert!(dist >= 0.0); // Convert dist to integers so we can push MetricNodes into BinaryHeap that expects Ord. // The trick here is that non-negative IEEE 754 floats have the same ordering as their // binary representations interpreted as integers. // // Also flip the sign on the value, shorter distance means bigger value, since BinaryHeap // returns the largest item first. let value = ::std::u32::MAX - dist.to_bits(); MetricNode { item, value, come_from, } } let mut come_from = HashMap::new(); let mut open = BinaryHeap::new(); open.push(node(start.clone(), ::std::f32::MAX, None)); // Find shortest path. let mut goal = loop { if let Some(closest) = open.pop() { if come_from.contains_key(&closest.item) { // Already saw it through a presumably shorter path... continue; } if let Some(from) = closest.come_from { come_from.insert(closest.item.clone(), from); } if &closest.item == end { break Some(closest.item); } for (item, dist) in neighbors(&closest.item) { let already_seen = come_from.contains_key(&item) || item == start; if already_seen { continue; } open.push(node(item, dist, Some(closest.item.clone()))); } } else { break None; } }; // Extract path from the graph structure. let mut path = Vec::new(); while let Some(x) = goal { goal = come_from.remove(&x); path.push(x); } path.reverse(); if path.is_empty() { None } else { Some(path) } } #[cfg(test)] mod test { use super::*; #[test] fn
() { fn neighbors(origin: i32, &x: &i32) -> Vec<(i32, f32)> { let mut ret = Vec::with_capacity(2); for i in &[-1, 1] { let x = x + i; ret.push((x, (x - origin).abs() as f32)); } ret } assert_eq!(Some(vec![8]), astar_path(8, &8, |_| Vec::new())); assert_eq!(None, astar_path(8, &12, |_| Vec::new())); assert_eq!(Some(vec![8]), astar_path(8, &8, |x| neighbors(8, x))); assert_eq!( Some(vec![8, 9, 10, 11, 12]), astar_path(8, &12, |x| neighbors(8, x)) ); } }
test_astar
identifier_name
search.rs
use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap, HashSet}; use std::hash::Hash; /// A node in a graph with a regular grid. pub trait GridNode: PartialEq + Eq + Clone + Hash + PartialOrd + Ord { /// List the neighbor nodes of this graph node. fn neighbors(&self) -> Vec<Self>; } /// A pathfinding map structure. /// /// A Dijkstra map lets you run pathfinding from any graph node it covers /// towards or away from the target nodes of the map. Currently the structure /// only supports underlying graphs with a fixed grid graph where the /// neighbors of each node must be the adjacent grid cells of that node. pub struct Dijkstra<N> { pub weights: HashMap<N, u32>, } impl<N: GridNode> Dijkstra<N> { /// Create a new Dijkstra map up to limit distance from goals, omitting /// nodes for which the is_valid predicate returns false. pub fn new<F: Fn(&N) -> bool>(goals: Vec<N>, is_valid: F, limit: u32) -> Dijkstra<N> { assert!(!goals.is_empty()); let mut weights = HashMap::new(); let mut edge = HashSet::new(); for n in goals { edge.insert(n); } for dist in 0..(limit) { for n in &edge { weights.insert(n.clone(), dist); } let mut new_edge = HashSet::new(); for n in &edge { for m in n.neighbors() { if is_valid(&m) &&!weights.contains_key(&m) { new_edge.insert(m); } } } edge = new_edge; if edge.is_empty() { break; } } Dijkstra { weights } } /// Return the neighbors of a cell (if any), sorted from downhill to /// uphill. pub fn sorted_neighbors(&self, node: &N) -> Vec<N> { let mut ret = Vec::new(); for n in &node.neighbors() { if let Some(w) = self.weights.get(n) { ret.push((w, n.clone())); } } ret.sort_by(|&(w1, _), &(w2, _)| w1.cmp(w2)); ret.into_iter().map(|(_, n)| n).collect() } } /// Find A* path in freeform graph. /// /// The `neighbors` function returns neighboring nodes and their estimated distance from the goal. /// The search will treat any node whose distance is zero as a goal and return a path leading to /// it. pub fn astar_path<N, F>(start: N, end: &N, neighbors: F) -> Option<Vec<N>> where N: Eq + Hash + Clone, F: Fn(&N) -> Vec<(N, f32)>,
// Also flip the sign on the value, shorter distance means bigger value, since BinaryHeap // returns the largest item first. let value = ::std::u32::MAX - dist.to_bits(); MetricNode { item, value, come_from, } } let mut come_from = HashMap::new(); let mut open = BinaryHeap::new(); open.push(node(start.clone(), ::std::f32::MAX, None)); // Find shortest path. let mut goal = loop { if let Some(closest) = open.pop() { if come_from.contains_key(&closest.item) { // Already saw it through a presumably shorter path... continue; } if let Some(from) = closest.come_from { come_from.insert(closest.item.clone(), from); } if &closest.item == end { break Some(closest.item); } for (item, dist) in neighbors(&closest.item) { let already_seen = come_from.contains_key(&item) || item == start; if already_seen { continue; } open.push(node(item, dist, Some(closest.item.clone()))); } } else { break None; } }; // Extract path from the graph structure. let mut path = Vec::new(); while let Some(x) = goal { goal = come_from.remove(&x); path.push(x); } path.reverse(); if path.is_empty() { None } else { Some(path) } } #[cfg(test)] mod test { use super::*; #[test] fn test_astar() { fn neighbors(origin: i32, &x: &i32) -> Vec<(i32, f32)> { let mut ret = Vec::with_capacity(2); for i in &[-1, 1] { let x = x + i; ret.push((x, (x - origin).abs() as f32)); } ret } assert_eq!(Some(vec![8]), astar_path(8, &8, |_| Vec::new())); assert_eq!(None, astar_path(8, &12, |_| Vec::new())); assert_eq!(Some(vec![8]), astar_path(8, &8, |x| neighbors(8, x))); assert_eq!( Some(vec![8, 9, 10, 11, 12]), astar_path(8, &12, |x| neighbors(8, x)) ); } }
{ #[derive(Eq, PartialEq)] struct MetricNode<N> { value: u32, item: N, come_from: Option<N>, } impl<N: Eq> Ord for MetricNode<N> { fn cmp(&self, other: &Self) -> Ordering { self.value.cmp(&other.value) } } impl<N: Eq> PartialOrd for MetricNode<N> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } fn node<N: Eq>(item: N, dist: f32, come_from: Option<N>) -> MetricNode<N> { debug_assert!(dist >= 0.0); // Convert dist to integers so we can push MetricNodes into BinaryHeap that expects Ord. // The trick here is that non-negative IEEE 754 floats have the same ordering as their // binary representations interpreted as integers. //
identifier_body
try-macro.rs
// run-pass #![allow(deprecated)] // for deprecated `try!()` macro use std::num::{ParseFloatError, ParseIntError}; fn main() { assert_eq!(simple(), Ok(1)); assert_eq!(nested(), Ok(2)); assert_eq!(merge_ok(), Ok(3.0)); assert_eq!(merge_int_err(), Err(Error::Int)); assert_eq!(merge_float_err(), Err(Error::Float)); } fn simple() -> Result<i32, ParseIntError> { Ok(try!("1".parse())) } fn nested() -> Result<i32, ParseIntError> { Ok(try!(try!("2".parse::<i32>()).to_string().parse::<i32>())) } fn merge_ok() -> Result<f32, Error> { Ok(try!("1".parse::<i32>()) as f32 + try!("2.0".parse::<f32>())) } fn merge_int_err() -> Result<f32, Error> { Ok(try!("a".parse::<i32>()) as f32 + try!("2.0".parse::<f32>())) } fn merge_float_err() -> Result<f32, Error> { Ok(try!("1".parse::<i32>()) as f32 + try!("b".parse::<f32>())) } #[derive(Debug, PartialEq)] enum Error { Int, Float, } impl From<ParseIntError> for Error { fn from(_: ParseIntError) -> Error { Error::Int } } impl From<ParseFloatError> for Error { fn
(_: ParseFloatError) -> Error { Error::Float } }
from
identifier_name
try-macro.rs
// run-pass #![allow(deprecated)] // for deprecated `try!()` macro use std::num::{ParseFloatError, ParseIntError}; fn main() { assert_eq!(simple(), Ok(1)); assert_eq!(nested(), Ok(2)); assert_eq!(merge_ok(), Ok(3.0)); assert_eq!(merge_int_err(), Err(Error::Int)); assert_eq!(merge_float_err(), Err(Error::Float)); } fn simple() -> Result<i32, ParseIntError> { Ok(try!("1".parse())) } fn nested() -> Result<i32, ParseIntError> { Ok(try!(try!("2".parse::<i32>()).to_string().parse::<i32>())) } fn merge_ok() -> Result<f32, Error> { Ok(try!("1".parse::<i32>()) as f32 + try!("2.0".parse::<f32>())) } fn merge_int_err() -> Result<f32, Error> { Ok(try!("a".parse::<i32>()) as f32 + try!("2.0".parse::<f32>())) } fn merge_float_err() -> Result<f32, Error> { Ok(try!("1".parse::<i32>()) as f32 + try!("b".parse::<f32>()))
#[derive(Debug, PartialEq)] enum Error { Int, Float, } impl From<ParseIntError> for Error { fn from(_: ParseIntError) -> Error { Error::Int } } impl From<ParseFloatError> for Error { fn from(_: ParseFloatError) -> Error { Error::Float } }
}
random_line_split
try-macro.rs
// run-pass #![allow(deprecated)] // for deprecated `try!()` macro use std::num::{ParseFloatError, ParseIntError}; fn main() { assert_eq!(simple(), Ok(1)); assert_eq!(nested(), Ok(2)); assert_eq!(merge_ok(), Ok(3.0)); assert_eq!(merge_int_err(), Err(Error::Int)); assert_eq!(merge_float_err(), Err(Error::Float)); } fn simple() -> Result<i32, ParseIntError> { Ok(try!("1".parse())) } fn nested() -> Result<i32, ParseIntError> { Ok(try!(try!("2".parse::<i32>()).to_string().parse::<i32>())) } fn merge_ok() -> Result<f32, Error> { Ok(try!("1".parse::<i32>()) as f32 + try!("2.0".parse::<f32>())) } fn merge_int_err() -> Result<f32, Error> { Ok(try!("a".parse::<i32>()) as f32 + try!("2.0".parse::<f32>())) } fn merge_float_err() -> Result<f32, Error> { Ok(try!("1".parse::<i32>()) as f32 + try!("b".parse::<f32>())) } #[derive(Debug, PartialEq)] enum Error { Int, Float, } impl From<ParseIntError> for Error { fn from(_: ParseIntError) -> Error
} impl From<ParseFloatError> for Error { fn from(_: ParseFloatError) -> Error { Error::Float } }
{ Error::Int }
identifier_body
linux.rs
// Copyright (c) 2014 Robert Clipsham <[email protected]> // // 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. #![allow(non_camel_case_types)] #![allow(non_snake_case)] extern crate libc; pub const SOL_PACKET: libc::c_int = 263; pub const PACKET_ADD_MEMBERSHIP: libc::c_int = 1;
// man 7 packet pub struct packet_mreq { pub mr_ifindex: libc::c_int, pub mr_type: libc::c_ushort, pub mr_alen: libc::c_ushort, pub mr_address: [libc::c_uchar; 8] }
pub const PACKET_MR_PROMISC: libc::c_int = 1;
random_line_split
linux.rs
// Copyright (c) 2014 Robert Clipsham <[email protected]> // // 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. #![allow(non_camel_case_types)] #![allow(non_snake_case)] extern crate libc; pub const SOL_PACKET: libc::c_int = 263; pub const PACKET_ADD_MEMBERSHIP: libc::c_int = 1; pub const PACKET_MR_PROMISC: libc::c_int = 1; // man 7 packet pub struct
{ pub mr_ifindex: libc::c_int, pub mr_type: libc::c_ushort, pub mr_alen: libc::c_ushort, pub mr_address: [libc::c_uchar; 8] }
packet_mreq
identifier_name
constraint_conversion.rs
use rustc_infer::infer::canonical::QueryOutlivesConstraint; use rustc_infer::infer::canonical::QueryRegionConstraints; use rustc_infer::infer::outlives::env::RegionBoundPairs; use rustc_infer::infer::outlives::obligations::{TypeOutlives, TypeOutlivesDelegate}; use rustc_infer::infer::region_constraints::{GenericKind, VerifyBound}; use rustc_infer::infer::{self, InferCtxt, SubregionOrigin}; use rustc_middle::mir::ConstraintCategory; use rustc_middle::ty::subst::GenericArgKind; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::DUMMY_SP; use crate::{ constraints::OutlivesConstraint, nll::ToRegionVid, region_infer::TypeTest, type_check::{Locations, MirTypeckRegionConstraints}, universal_regions::UniversalRegions, }; crate struct ConstraintConversion<'a, 'tcx> { infcx: &'a InferCtxt<'a, 'tcx>, tcx: TyCtxt<'tcx>, universal_regions: &'a UniversalRegions<'tcx>, region_bound_pairs: &'a RegionBoundPairs<'tcx>, implicit_region_bound: Option<ty::Region<'tcx>>, param_env: ty::ParamEnv<'tcx>, locations: Locations, category: ConstraintCategory, constraints: &'a mut MirTypeckRegionConstraints<'tcx>, } impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> { crate fn new( infcx: &'a InferCtxt<'a, 'tcx>, universal_regions: &'a UniversalRegions<'tcx>, region_bound_pairs: &'a RegionBoundPairs<'tcx>, implicit_region_bound: Option<ty::Region<'tcx>>, param_env: ty::ParamEnv<'tcx>, locations: Locations, category: ConstraintCategory, constraints: &'a mut MirTypeckRegionConstraints<'tcx>, ) -> Self { Self { infcx, tcx: infcx.tcx, universal_regions, region_bound_pairs, implicit_region_bound, param_env, locations, category, constraints, } } #[instrument(skip(self), level = "debug")] pub(super) fn convert_all(&mut self, query_constraints: &QueryRegionConstraints<'tcx>) { let QueryRegionConstraints { outlives, member_constraints } = query_constraints; // Annoying: to invoke `self.to_region_vid`, we need access to // `self.constraints`, but we also want to be mutating // `self.member_constraints`. For now, just swap out the value // we want and replace at the end. let mut tmp = std::mem::take(&mut self.constraints.member_constraints); for member_constraint in member_constraints { tmp.push_constraint(member_constraint, |r| self.to_region_vid(r)); } self.constraints.member_constraints = tmp; for query_constraint in outlives { self.convert(query_constraint); } } pub(super) fn convert(&mut self, query_constraint: &QueryOutlivesConstraint<'tcx>) { debug!("generate: constraints at: {:#?}", self.locations); // Extract out various useful fields we'll need below. let ConstraintConversion { tcx, region_bound_pairs, implicit_region_bound, param_env,.. } = *self; // At the moment, we never generate any "higher-ranked" // region constraints like `for<'a> 'a: 'b`. At some point // when we move to universes, we will, and this assertion // will start to fail. let ty::OutlivesPredicate(k1, r2) = query_constraint.no_bound_vars().unwrap_or_else(|| { bug!("query_constraint {:?} contained bound vars", query_constraint,); }); match k1.unpack() { GenericArgKind::Lifetime(r1) => { let r1_vid = self.to_region_vid(r1); let r2_vid = self.to_region_vid(r2); self.add_outlives(r1_vid, r2_vid); } GenericArgKind::Type(t1) => { // we don't actually use this for anything, but // the `TypeOutlives` code needs an origin. let origin = infer::RelateParamBound(DUMMY_SP, t1, None); TypeOutlives::new( &mut *self, tcx, region_bound_pairs, implicit_region_bound, param_env, ) .type_must_outlive(origin, t1, r2); } GenericArgKind::Const(_) => { // Consts cannot outlive one another, so we // don't need to handle any relations here. } } } fn verify_to_type_test( &mut self, generic_kind: GenericKind<'tcx>,
TypeTest { generic_kind, lower_bound, locations: self.locations, verify_bound } } fn to_region_vid(&mut self, r: ty::Region<'tcx>) -> ty::RegionVid { if let ty::RePlaceholder(placeholder) = r { self.constraints.placeholder_region(self.infcx, *placeholder).to_region_vid() } else { self.universal_regions.to_region_vid(r) } } fn add_outlives(&mut self, sup: ty::RegionVid, sub: ty::RegionVid) { self.constraints.outlives_constraints.push(OutlivesConstraint { locations: self.locations, category: self.category, sub, sup, variance_info: ty::VarianceDiagInfo::default(), }); } fn add_type_test(&mut self, type_test: TypeTest<'tcx>) { debug!("add_type_test(type_test={:?})", type_test); self.constraints.type_tests.push(type_test); } } impl<'a, 'b, 'tcx> TypeOutlivesDelegate<'tcx> for &'a mut ConstraintConversion<'b, 'tcx> { fn push_sub_region_constraint( &mut self, _origin: SubregionOrigin<'tcx>, a: ty::Region<'tcx>, b: ty::Region<'tcx>, ) { let b = self.to_region_vid(b); let a = self.to_region_vid(a); self.add_outlives(b, a); } fn push_verify( &mut self, _origin: SubregionOrigin<'tcx>, kind: GenericKind<'tcx>, a: ty::Region<'tcx>, bound: VerifyBound<'tcx>, ) { let type_test = self.verify_to_type_test(kind, a, bound); self.add_type_test(type_test); } }
region: ty::Region<'tcx>, verify_bound: VerifyBound<'tcx>, ) -> TypeTest<'tcx> { let lower_bound = self.to_region_vid(region);
random_line_split
constraint_conversion.rs
use rustc_infer::infer::canonical::QueryOutlivesConstraint; use rustc_infer::infer::canonical::QueryRegionConstraints; use rustc_infer::infer::outlives::env::RegionBoundPairs; use rustc_infer::infer::outlives::obligations::{TypeOutlives, TypeOutlivesDelegate}; use rustc_infer::infer::region_constraints::{GenericKind, VerifyBound}; use rustc_infer::infer::{self, InferCtxt, SubregionOrigin}; use rustc_middle::mir::ConstraintCategory; use rustc_middle::ty::subst::GenericArgKind; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::DUMMY_SP; use crate::{ constraints::OutlivesConstraint, nll::ToRegionVid, region_infer::TypeTest, type_check::{Locations, MirTypeckRegionConstraints}, universal_regions::UniversalRegions, }; crate struct
<'a, 'tcx> { infcx: &'a InferCtxt<'a, 'tcx>, tcx: TyCtxt<'tcx>, universal_regions: &'a UniversalRegions<'tcx>, region_bound_pairs: &'a RegionBoundPairs<'tcx>, implicit_region_bound: Option<ty::Region<'tcx>>, param_env: ty::ParamEnv<'tcx>, locations: Locations, category: ConstraintCategory, constraints: &'a mut MirTypeckRegionConstraints<'tcx>, } impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> { crate fn new( infcx: &'a InferCtxt<'a, 'tcx>, universal_regions: &'a UniversalRegions<'tcx>, region_bound_pairs: &'a RegionBoundPairs<'tcx>, implicit_region_bound: Option<ty::Region<'tcx>>, param_env: ty::ParamEnv<'tcx>, locations: Locations, category: ConstraintCategory, constraints: &'a mut MirTypeckRegionConstraints<'tcx>, ) -> Self { Self { infcx, tcx: infcx.tcx, universal_regions, region_bound_pairs, implicit_region_bound, param_env, locations, category, constraints, } } #[instrument(skip(self), level = "debug")] pub(super) fn convert_all(&mut self, query_constraints: &QueryRegionConstraints<'tcx>) { let QueryRegionConstraints { outlives, member_constraints } = query_constraints; // Annoying: to invoke `self.to_region_vid`, we need access to // `self.constraints`, but we also want to be mutating // `self.member_constraints`. For now, just swap out the value // we want and replace at the end. let mut tmp = std::mem::take(&mut self.constraints.member_constraints); for member_constraint in member_constraints { tmp.push_constraint(member_constraint, |r| self.to_region_vid(r)); } self.constraints.member_constraints = tmp; for query_constraint in outlives { self.convert(query_constraint); } } pub(super) fn convert(&mut self, query_constraint: &QueryOutlivesConstraint<'tcx>) { debug!("generate: constraints at: {:#?}", self.locations); // Extract out various useful fields we'll need below. let ConstraintConversion { tcx, region_bound_pairs, implicit_region_bound, param_env,.. } = *self; // At the moment, we never generate any "higher-ranked" // region constraints like `for<'a> 'a: 'b`. At some point // when we move to universes, we will, and this assertion // will start to fail. let ty::OutlivesPredicate(k1, r2) = query_constraint.no_bound_vars().unwrap_or_else(|| { bug!("query_constraint {:?} contained bound vars", query_constraint,); }); match k1.unpack() { GenericArgKind::Lifetime(r1) => { let r1_vid = self.to_region_vid(r1); let r2_vid = self.to_region_vid(r2); self.add_outlives(r1_vid, r2_vid); } GenericArgKind::Type(t1) => { // we don't actually use this for anything, but // the `TypeOutlives` code needs an origin. let origin = infer::RelateParamBound(DUMMY_SP, t1, None); TypeOutlives::new( &mut *self, tcx, region_bound_pairs, implicit_region_bound, param_env, ) .type_must_outlive(origin, t1, r2); } GenericArgKind::Const(_) => { // Consts cannot outlive one another, so we // don't need to handle any relations here. } } } fn verify_to_type_test( &mut self, generic_kind: GenericKind<'tcx>, region: ty::Region<'tcx>, verify_bound: VerifyBound<'tcx>, ) -> TypeTest<'tcx> { let lower_bound = self.to_region_vid(region); TypeTest { generic_kind, lower_bound, locations: self.locations, verify_bound } } fn to_region_vid(&mut self, r: ty::Region<'tcx>) -> ty::RegionVid { if let ty::RePlaceholder(placeholder) = r { self.constraints.placeholder_region(self.infcx, *placeholder).to_region_vid() } else { self.universal_regions.to_region_vid(r) } } fn add_outlives(&mut self, sup: ty::RegionVid, sub: ty::RegionVid) { self.constraints.outlives_constraints.push(OutlivesConstraint { locations: self.locations, category: self.category, sub, sup, variance_info: ty::VarianceDiagInfo::default(), }); } fn add_type_test(&mut self, type_test: TypeTest<'tcx>) { debug!("add_type_test(type_test={:?})", type_test); self.constraints.type_tests.push(type_test); } } impl<'a, 'b, 'tcx> TypeOutlivesDelegate<'tcx> for &'a mut ConstraintConversion<'b, 'tcx> { fn push_sub_region_constraint( &mut self, _origin: SubregionOrigin<'tcx>, a: ty::Region<'tcx>, b: ty::Region<'tcx>, ) { let b = self.to_region_vid(b); let a = self.to_region_vid(a); self.add_outlives(b, a); } fn push_verify( &mut self, _origin: SubregionOrigin<'tcx>, kind: GenericKind<'tcx>, a: ty::Region<'tcx>, bound: VerifyBound<'tcx>, ) { let type_test = self.verify_to_type_test(kind, a, bound); self.add_type_test(type_test); } }
ConstraintConversion
identifier_name
main.rs
// Unseemly is a "core" typed language with (typed!) macros. // You shouldn't write code in Unseemly. // Instead, you should implement your programming language as Unseemly macros. #![allow(dead_code, unused_macros, non_snake_case, non_upper_case_globals, deprecated)] // dead_code and unused_macros are hopefully temporary allowances // non_snake_case is stylistic, so we can write `non__snake_case`. // non_upper_case_globals is stylistic... but maybe thread_locals really ought to be upper case. // deprecated is temporary, until `Sky` replaces `EnvMBE` (and the deprecated calls are cleaned up) #![recursion_limit = "128"] // Yikes. // for testing; requires `cargo +nightly` // #![feature(log_syntax, trace_macros)] // trace_macros!(true); // TODO: turn these into `use` statements in the appropriate places #[macro_use] extern crate custom_derive; pub mod macros; pub mod name; // should maybe be moved to `util`; `mbe` needs it pub mod util; pub mod alpha; pub mod ast; pub mod beta; pub mod read; pub mod earley; pub mod grammar; pub mod unparse; pub mod form; pub mod ast_walk; pub mod expand; pub mod ty; pub mod ty_compare; pub mod walk_mode; pub mod runtime; pub mod core_extra_forms; pub mod core_forms; pub mod core_macro_forms; pub mod core_qq_forms; pub mod core_type_forms; mod end_to_end__tests; use crate::{ ast::Ast, name::Name, runtime::eval::{eval, Value}, util::assoc::Assoc, }; use wasm_bindgen::prelude::*; /// Everything you need to turn text into behavior. #[derive(Clone)] pub struct Language { pub pc: crate::earley::ParseContext, // TODO: how do these differ from the corresponding elements of `ParseContext`? // Should we get rid of `Language` in favor of it??? pub type_env: Assoc<Name, Ast>, pub type_env__phaseless: Assoc<Name, Ast>, pub value_env: Assoc<Name, Value>, } /// Generate Unseemly. /// (This is the core language.) pub fn unseemly() -> Language { Language { pc: crate::core_forms::outermost__parse_context(), type_env: crate::runtime::core_values::core_types(), type_env__phaseless: crate::runtime::core_values::core_types(), value_env: crate::runtime::core_values::core_values(), } } /// Run the file (which hopefully evaluates to `capture_language`), and get the language it defines. /// Returns the parse context, the type environment, the phaseless version of the type environment, /// and the value environment. /// This doesn't take a language 4-tuple -- it assumes that the language is in Unseemly /// (but of course it may do `include /[some_language.unseemly]/` itself). /// TODO: we only need the phaselessness for macros, and maybe we can get rid of it there? pub fn
(path: &std::path::Path) -> Language { let mut raw_lib = String::new(); use std::io::Read; let orig_dir = std::env::current_dir().unwrap(); std::fs::File::open(path) .expect("Error opening file") .read_to_string(&mut raw_lib) .expect("Error reading file"); // Evaluate the file in its own directory: if let Some(dir) = path.parent() { // Might be empty: if dir.is_dir() { std::env::set_current_dir(dir).unwrap(); } } let lang = get_language(&raw_lib, unseemly()); // Go back to the original directory: std::env::set_current_dir(orig_dir).unwrap(); return lang; } pub fn get_language(program: &str, lang: Language) -> Language { // TODO: I guess syntax extensions ought to return `Result`, too... let lib_ast = crate::grammar::parse(&core_forms::outermost_form(), lang.pc, &program).unwrap(); let lib_typed = ast_walk::walk::<ty::SynthTy>( &lib_ast, &ast_walk::LazyWalkReses::new(lang.type_env, lang.type_env__phaseless, lib_ast.clone()), ) .unwrap(); let lib_expanded = crate::expand::expand(&lib_ast).unwrap(); let lib_evaled = crate::runtime::eval::eval(&lib_expanded, lang.value_env).unwrap(); let (new_pc, new__value_env) = if let Value::Sequence(mut lang_and_env) = lib_evaled { let env_value = lang_and_env.pop().unwrap(); let lang_value = lang_and_env.pop().unwrap(); let new_pc = match &*lang_value { Value::ParseContext(boxed_pc) => (**boxed_pc).clone(), _ => icp!("[type error] not a language"), }; let new__value_env = if let Value::Struct(ref env) = *env_value { let mut new__value_env = Assoc::new(); // We need to un-freshen the names that we're importing // so they can actually be referred to. for (k, v) in env.iter_pairs() { new__value_env = new__value_env.set(k.unhygienic_orig(), v.clone()) } new__value_env } else { icp!("[type error] Unexpected lib syntax structure: {:#?}", env_value) }; (new_pc, new__value_env) } else { icp!("[type error] Unexpected lib syntax strucutre: {:#?}", lib_evaled); }; node_let!(lib_typed => {Type tuple} lang_and_types *= component); node_let!(lang_and_types[1] => {Type struct} keys *= component_name, values *= component); let mut new__type_env = Assoc::<Name, Ast>::new(); for (k, v) in keys.into_iter().zip(values.into_iter()) { // As above, unfreshen: new__type_env = new__type_env.set(k.to_name().unhygienic_orig(), v.clone()); } // Do it again, to unpack the phaseless type environment: node_let!(lang_and_types[2] => {Type struct} pl_keys *= component_name, pl_values *= component); let mut new___type_env__phaseless = Assoc::<Name, Ast>::new(); for (k, v) in pl_keys.into_iter().zip(pl_values.into_iter()) { // As above, unfreshen: new___type_env__phaseless = new___type_env__phaseless.set(k.to_name().unhygienic_orig(), v.clone()); } Language { pc: new_pc, type_env: new__type_env, type_env__phaseless: new___type_env__phaseless, value_env: new__value_env, } } /// Evaluate a program written in some language. /// The last four arguments match the values returned by `language_from_file`. pub fn eval_program(program: &str, lang: Language) -> Result<Value, String> { // TODO: looks like `outermost_form` ought to be a property of `ParseContext` let ast: Ast = crate::grammar::parse(&core_forms::outermost_form(), lang.pc, program) .map_err(|e| e.msg)?; let _type = ast_walk::walk::<ty::SynthTy>( &ast, &ast_walk::LazyWalkReses::new(lang.type_env, lang.type_env__phaseless, ast.clone()), ) .map_err(|e| format!("{}", e))?; let core_ast = crate::expand::expand(&ast).map_err(|_| "???".to_string())?; eval(&core_ast, lang.value_env).map_err(|_| "???".to_string()) } /// Evaluate a program written in Unseemly. /// Of course, it may immediately do `include /[something]/` to switch languages. pub fn eval_unseemly_program_top(program: &str) -> Result<Value, String> { eval_program(program, unseemly()) } /// Type program written in Unseemly. /// Of course, it may immediately do `include /[something]/` to switch languages. pub fn type_unseemly_program_top(program: &str) -> Result<Ast, String> { let unseemly = unseemly(); let ast: Ast = crate::grammar::parse(&core_forms::outermost_form(), unseemly.pc, program) .map_err(|e| e.msg)?; ast_walk::walk::<ty::SynthTy>( &ast, &ast_walk::LazyWalkReses::new(unseemly.type_env, unseemly.type_env__phaseless, ast.clone()), ) .map_err(|e| format!("{}", e)) } /// Displays `res` on a color terminal. pub fn terminal_display(res: Result<Value, String>) { match res { Ok(v) => println!("\x1b[1;32m≉\x1b[0m {}", v), Err(s) => println!("\x1b[1;31m✘\x1b[0m {}", s), } } fn html_render(res: Result<Value, String>) -> String { match res { Ok(v) => format!("<b>{}</b>", v), // HACK: codespan_reporting uses terminal escapes Err(s) => format!("<pre>{}</pre>", ansi_to_html::convert_escaped(&s).unwrap()), } } #[wasm_bindgen] pub fn wasm_init() { #[cfg(target_arch = "wasm32")] std::panic::set_hook(Box::new(console_error_panic_hook::hook)); } use std::iter::FromIterator; thread_local! { static language_stash: std::cell::RefCell<std::collections::HashMap<String, Language>> = std::cell::RefCell::new(std::collections::HashMap::from_iter( vec![("unseemly".to_string(), unseemly())].into_iter())); } #[wasm_bindgen] pub fn html__eval_program(program: &str, stashed_lang: &str) -> String { let lang: Language = language_stash.with(|ls| (*ls.borrow()).get(stashed_lang).unwrap().clone()); html_render(eval_program(program, lang)) } #[wasm_bindgen] pub fn stash_lang(result_name: &str, program: &str, orig_stashed: &str) { let orig_lang = language_stash.with(|ls| (*ls.borrow()).get(orig_stashed).unwrap().clone()); let new_lang = get_language(program, orig_lang); language_stash.with(|ls| ls.borrow_mut().insert(result_name.to_string(), new_lang)); } #[wasm_bindgen] pub fn generate__ace_rules(stashed_lang: &str) -> String { language_stash .with(|ls| grammar::ace_rules__for(&(*ls.borrow()).get(stashed_lang).unwrap().pc.grammar)) }
language_from_file
identifier_name
main.rs
// Unseemly is a "core" typed language with (typed!) macros. // You shouldn't write code in Unseemly. // Instead, you should implement your programming language as Unseemly macros. #![allow(dead_code, unused_macros, non_snake_case, non_upper_case_globals, deprecated)] // dead_code and unused_macros are hopefully temporary allowances // non_snake_case is stylistic, so we can write `non__snake_case`. // non_upper_case_globals is stylistic... but maybe thread_locals really ought to be upper case. // deprecated is temporary, until `Sky` replaces `EnvMBE` (and the deprecated calls are cleaned up) #![recursion_limit = "128"] // Yikes. // for testing; requires `cargo +nightly` // #![feature(log_syntax, trace_macros)] // trace_macros!(true); // TODO: turn these into `use` statements in the appropriate places #[macro_use] extern crate custom_derive; pub mod macros; pub mod name; // should maybe be moved to `util`; `mbe` needs it pub mod util; pub mod alpha; pub mod ast; pub mod beta; pub mod read; pub mod earley; pub mod grammar; pub mod unparse; pub mod form; pub mod ast_walk; pub mod expand; pub mod ty; pub mod ty_compare; pub mod walk_mode; pub mod runtime; pub mod core_extra_forms; pub mod core_forms; pub mod core_macro_forms; pub mod core_qq_forms; pub mod core_type_forms; mod end_to_end__tests; use crate::{ ast::Ast, name::Name, runtime::eval::{eval, Value}, util::assoc::Assoc, }; use wasm_bindgen::prelude::*; /// Everything you need to turn text into behavior. #[derive(Clone)] pub struct Language { pub pc: crate::earley::ParseContext, // TODO: how do these differ from the corresponding elements of `ParseContext`? // Should we get rid of `Language` in favor of it??? pub type_env: Assoc<Name, Ast>, pub type_env__phaseless: Assoc<Name, Ast>, pub value_env: Assoc<Name, Value>, } /// Generate Unseemly. /// (This is the core language.) pub fn unseemly() -> Language { Language { pc: crate::core_forms::outermost__parse_context(), type_env: crate::runtime::core_values::core_types(), type_env__phaseless: crate::runtime::core_values::core_types(), value_env: crate::runtime::core_values::core_values(), } } /// Run the file (which hopefully evaluates to `capture_language`), and get the language it defines. /// Returns the parse context, the type environment, the phaseless version of the type environment, /// and the value environment. /// This doesn't take a language 4-tuple -- it assumes that the language is in Unseemly /// (but of course it may do `include /[some_language.unseemly]/` itself). /// TODO: we only need the phaselessness for macros, and maybe we can get rid of it there? pub fn language_from_file(path: &std::path::Path) -> Language { let mut raw_lib = String::new(); use std::io::Read; let orig_dir = std::env::current_dir().unwrap(); std::fs::File::open(path) .expect("Error opening file") .read_to_string(&mut raw_lib) .expect("Error reading file"); // Evaluate the file in its own directory: if let Some(dir) = path.parent() { // Might be empty: if dir.is_dir() { std::env::set_current_dir(dir).unwrap(); } } let lang = get_language(&raw_lib, unseemly()); // Go back to the original directory: std::env::set_current_dir(orig_dir).unwrap(); return lang; } pub fn get_language(program: &str, lang: Language) -> Language { // TODO: I guess syntax extensions ought to return `Result`, too... let lib_ast = crate::grammar::parse(&core_forms::outermost_form(), lang.pc, &program).unwrap(); let lib_typed = ast_walk::walk::<ty::SynthTy>( &lib_ast, &ast_walk::LazyWalkReses::new(lang.type_env, lang.type_env__phaseless, lib_ast.clone()), ) .unwrap(); let lib_expanded = crate::expand::expand(&lib_ast).unwrap(); let lib_evaled = crate::runtime::eval::eval(&lib_expanded, lang.value_env).unwrap(); let (new_pc, new__value_env) = if let Value::Sequence(mut lang_and_env) = lib_evaled { let env_value = lang_and_env.pop().unwrap(); let lang_value = lang_and_env.pop().unwrap(); let new_pc = match &*lang_value { Value::ParseContext(boxed_pc) => (**boxed_pc).clone(), _ => icp!("[type error] not a language"), }; let new__value_env = if let Value::Struct(ref env) = *env_value { let mut new__value_env = Assoc::new(); // We need to un-freshen the names that we're importing // so they can actually be referred to. for (k, v) in env.iter_pairs() { new__value_env = new__value_env.set(k.unhygienic_orig(), v.clone()) } new__value_env } else { icp!("[type error] Unexpected lib syntax structure: {:#?}", env_value) }; (new_pc, new__value_env) } else { icp!("[type error] Unexpected lib syntax strucutre: {:#?}", lib_evaled); }; node_let!(lib_typed => {Type tuple} lang_and_types *= component); node_let!(lang_and_types[1] => {Type struct} keys *= component_name, values *= component); let mut new__type_env = Assoc::<Name, Ast>::new(); for (k, v) in keys.into_iter().zip(values.into_iter()) { // As above, unfreshen: new__type_env = new__type_env.set(k.to_name().unhygienic_orig(), v.clone()); } // Do it again, to unpack the phaseless type environment: node_let!(lang_and_types[2] => {Type struct} pl_keys *= component_name, pl_values *= component); let mut new___type_env__phaseless = Assoc::<Name, Ast>::new(); for (k, v) in pl_keys.into_iter().zip(pl_values.into_iter()) { // As above, unfreshen: new___type_env__phaseless = new___type_env__phaseless.set(k.to_name().unhygienic_orig(), v.clone()); } Language { pc: new_pc, type_env: new__type_env, type_env__phaseless: new___type_env__phaseless, value_env: new__value_env, } } /// Evaluate a program written in some language. /// The last four arguments match the values returned by `language_from_file`. pub fn eval_program(program: &str, lang: Language) -> Result<Value, String>
/// Evaluate a program written in Unseemly. /// Of course, it may immediately do `include /[something]/` to switch languages. pub fn eval_unseemly_program_top(program: &str) -> Result<Value, String> { eval_program(program, unseemly()) } /// Type program written in Unseemly. /// Of course, it may immediately do `include /[something]/` to switch languages. pub fn type_unseemly_program_top(program: &str) -> Result<Ast, String> { let unseemly = unseemly(); let ast: Ast = crate::grammar::parse(&core_forms::outermost_form(), unseemly.pc, program) .map_err(|e| e.msg)?; ast_walk::walk::<ty::SynthTy>( &ast, &ast_walk::LazyWalkReses::new(unseemly.type_env, unseemly.type_env__phaseless, ast.clone()), ) .map_err(|e| format!("{}", e)) } /// Displays `res` on a color terminal. pub fn terminal_display(res: Result<Value, String>) { match res { Ok(v) => println!("\x1b[1;32m≉\x1b[0m {}", v), Err(s) => println!("\x1b[1;31m✘\x1b[0m {}", s), } } fn html_render(res: Result<Value, String>) -> String { match res { Ok(v) => format!("<b>{}</b>", v), // HACK: codespan_reporting uses terminal escapes Err(s) => format!("<pre>{}</pre>", ansi_to_html::convert_escaped(&s).unwrap()), } } #[wasm_bindgen] pub fn wasm_init() { #[cfg(target_arch = "wasm32")] std::panic::set_hook(Box::new(console_error_panic_hook::hook)); } use std::iter::FromIterator; thread_local! { static language_stash: std::cell::RefCell<std::collections::HashMap<String, Language>> = std::cell::RefCell::new(std::collections::HashMap::from_iter( vec![("unseemly".to_string(), unseemly())].into_iter())); } #[wasm_bindgen] pub fn html__eval_program(program: &str, stashed_lang: &str) -> String { let lang: Language = language_stash.with(|ls| (*ls.borrow()).get(stashed_lang).unwrap().clone()); html_render(eval_program(program, lang)) } #[wasm_bindgen] pub fn stash_lang(result_name: &str, program: &str, orig_stashed: &str) { let orig_lang = language_stash.with(|ls| (*ls.borrow()).get(orig_stashed).unwrap().clone()); let new_lang = get_language(program, orig_lang); language_stash.with(|ls| ls.borrow_mut().insert(result_name.to_string(), new_lang)); } #[wasm_bindgen] pub fn generate__ace_rules(stashed_lang: &str) -> String { language_stash .with(|ls| grammar::ace_rules__for(&(*ls.borrow()).get(stashed_lang).unwrap().pc.grammar)) }
{ // TODO: looks like `outermost_form` ought to be a property of `ParseContext` let ast: Ast = crate::grammar::parse(&core_forms::outermost_form(), lang.pc, program) .map_err(|e| e.msg)?; let _type = ast_walk::walk::<ty::SynthTy>( &ast, &ast_walk::LazyWalkReses::new(lang.type_env, lang.type_env__phaseless, ast.clone()), ) .map_err(|e| format!("{}", e))?; let core_ast = crate::expand::expand(&ast).map_err(|_| "???".to_string())?; eval(&core_ast, lang.value_env).map_err(|_| "???".to_string()) }
identifier_body
main.rs
// Unseemly is a "core" typed language with (typed!) macros. // You shouldn't write code in Unseemly. // Instead, you should implement your programming language as Unseemly macros. #![allow(dead_code, unused_macros, non_snake_case, non_upper_case_globals, deprecated)] // dead_code and unused_macros are hopefully temporary allowances // non_snake_case is stylistic, so we can write `non__snake_case`. // non_upper_case_globals is stylistic... but maybe thread_locals really ought to be upper case. // deprecated is temporary, until `Sky` replaces `EnvMBE` (and the deprecated calls are cleaned up) #![recursion_limit = "128"] // Yikes. // for testing; requires `cargo +nightly` // #![feature(log_syntax, trace_macros)] // trace_macros!(true); // TODO: turn these into `use` statements in the appropriate places #[macro_use] extern crate custom_derive; pub mod macros; pub mod name; // should maybe be moved to `util`; `mbe` needs it pub mod util; pub mod alpha; pub mod ast; pub mod beta; pub mod read; pub mod earley; pub mod grammar; pub mod unparse; pub mod form; pub mod ast_walk; pub mod expand; pub mod ty; pub mod ty_compare; pub mod walk_mode; pub mod runtime; pub mod core_extra_forms; pub mod core_forms; pub mod core_macro_forms; pub mod core_qq_forms; pub mod core_type_forms; mod end_to_end__tests; use crate::{ ast::Ast, name::Name, runtime::eval::{eval, Value}, util::assoc::Assoc, }; use wasm_bindgen::prelude::*; /// Everything you need to turn text into behavior. #[derive(Clone)] pub struct Language { pub pc: crate::earley::ParseContext, // TODO: how do these differ from the corresponding elements of `ParseContext`? // Should we get rid of `Language` in favor of it??? pub type_env: Assoc<Name, Ast>, pub type_env__phaseless: Assoc<Name, Ast>, pub value_env: Assoc<Name, Value>, } /// Generate Unseemly. /// (This is the core language.) pub fn unseemly() -> Language { Language { pc: crate::core_forms::outermost__parse_context(), type_env: crate::runtime::core_values::core_types(), type_env__phaseless: crate::runtime::core_values::core_types(), value_env: crate::runtime::core_values::core_values(), } } /// Run the file (which hopefully evaluates to `capture_language`), and get the language it defines. /// Returns the parse context, the type environment, the phaseless version of the type environment, /// and the value environment. /// This doesn't take a language 4-tuple -- it assumes that the language is in Unseemly /// (but of course it may do `include /[some_language.unseemly]/` itself). /// TODO: we only need the phaselessness for macros, and maybe we can get rid of it there? pub fn language_from_file(path: &std::path::Path) -> Language { let mut raw_lib = String::new(); use std::io::Read; let orig_dir = std::env::current_dir().unwrap(); std::fs::File::open(path) .expect("Error opening file") .read_to_string(&mut raw_lib) .expect("Error reading file"); // Evaluate the file in its own directory: if let Some(dir) = path.parent() { // Might be empty: if dir.is_dir() { std::env::set_current_dir(dir).unwrap(); } } let lang = get_language(&raw_lib, unseemly()); // Go back to the original directory: std::env::set_current_dir(orig_dir).unwrap(); return lang; } pub fn get_language(program: &str, lang: Language) -> Language { // TODO: I guess syntax extensions ought to return `Result`, too... let lib_ast = crate::grammar::parse(&core_forms::outermost_form(), lang.pc, &program).unwrap(); let lib_typed = ast_walk::walk::<ty::SynthTy>( &lib_ast, &ast_walk::LazyWalkReses::new(lang.type_env, lang.type_env__phaseless, lib_ast.clone()), ) .unwrap(); let lib_expanded = crate::expand::expand(&lib_ast).unwrap(); let lib_evaled = crate::runtime::eval::eval(&lib_expanded, lang.value_env).unwrap(); let (new_pc, new__value_env) = if let Value::Sequence(mut lang_and_env) = lib_evaled { let env_value = lang_and_env.pop().unwrap(); let lang_value = lang_and_env.pop().unwrap(); let new_pc = match &*lang_value { Value::ParseContext(boxed_pc) => (**boxed_pc).clone(), _ => icp!("[type error] not a language"), }; let new__value_env = if let Value::Struct(ref env) = *env_value { let mut new__value_env = Assoc::new(); // We need to un-freshen the names that we're importing // so they can actually be referred to. for (k, v) in env.iter_pairs() { new__value_env = new__value_env.set(k.unhygienic_orig(), v.clone()) } new__value_env } else { icp!("[type error] Unexpected lib syntax structure: {:#?}", env_value) }; (new_pc, new__value_env) } else { icp!("[type error] Unexpected lib syntax strucutre: {:#?}", lib_evaled); }; node_let!(lib_typed => {Type tuple} lang_and_types *= component); node_let!(lang_and_types[1] => {Type struct} keys *= component_name, values *= component); let mut new__type_env = Assoc::<Name, Ast>::new(); for (k, v) in keys.into_iter().zip(values.into_iter()) { // As above, unfreshen: new__type_env = new__type_env.set(k.to_name().unhygienic_orig(), v.clone()); } // Do it again, to unpack the phaseless type environment: node_let!(lang_and_types[2] => {Type struct} pl_keys *= component_name, pl_values *= component); let mut new___type_env__phaseless = Assoc::<Name, Ast>::new(); for (k, v) in pl_keys.into_iter().zip(pl_values.into_iter()) { // As above, unfreshen: new___type_env__phaseless = new___type_env__phaseless.set(k.to_name().unhygienic_orig(), v.clone()); } Language { pc: new_pc, type_env: new__type_env, type_env__phaseless: new___type_env__phaseless, value_env: new__value_env, } } /// Evaluate a program written in some language. /// The last four arguments match the values returned by `language_from_file`. pub fn eval_program(program: &str, lang: Language) -> Result<Value, String> { // TODO: looks like `outermost_form` ought to be a property of `ParseContext` let ast: Ast = crate::grammar::parse(&core_forms::outermost_form(), lang.pc, program)
) .map_err(|e| format!("{}", e))?; let core_ast = crate::expand::expand(&ast).map_err(|_| "???".to_string())?; eval(&core_ast, lang.value_env).map_err(|_| "???".to_string()) } /// Evaluate a program written in Unseemly. /// Of course, it may immediately do `include /[something]/` to switch languages. pub fn eval_unseemly_program_top(program: &str) -> Result<Value, String> { eval_program(program, unseemly()) } /// Type program written in Unseemly. /// Of course, it may immediately do `include /[something]/` to switch languages. pub fn type_unseemly_program_top(program: &str) -> Result<Ast, String> { let unseemly = unseemly(); let ast: Ast = crate::grammar::parse(&core_forms::outermost_form(), unseemly.pc, program) .map_err(|e| e.msg)?; ast_walk::walk::<ty::SynthTy>( &ast, &ast_walk::LazyWalkReses::new(unseemly.type_env, unseemly.type_env__phaseless, ast.clone()), ) .map_err(|e| format!("{}", e)) } /// Displays `res` on a color terminal. pub fn terminal_display(res: Result<Value, String>) { match res { Ok(v) => println!("\x1b[1;32m≉\x1b[0m {}", v), Err(s) => println!("\x1b[1;31m✘\x1b[0m {}", s), } } fn html_render(res: Result<Value, String>) -> String { match res { Ok(v) => format!("<b>{}</b>", v), // HACK: codespan_reporting uses terminal escapes Err(s) => format!("<pre>{}</pre>", ansi_to_html::convert_escaped(&s).unwrap()), } } #[wasm_bindgen] pub fn wasm_init() { #[cfg(target_arch = "wasm32")] std::panic::set_hook(Box::new(console_error_panic_hook::hook)); } use std::iter::FromIterator; thread_local! { static language_stash: std::cell::RefCell<std::collections::HashMap<String, Language>> = std::cell::RefCell::new(std::collections::HashMap::from_iter( vec![("unseemly".to_string(), unseemly())].into_iter())); } #[wasm_bindgen] pub fn html__eval_program(program: &str, stashed_lang: &str) -> String { let lang: Language = language_stash.with(|ls| (*ls.borrow()).get(stashed_lang).unwrap().clone()); html_render(eval_program(program, lang)) } #[wasm_bindgen] pub fn stash_lang(result_name: &str, program: &str, orig_stashed: &str) { let orig_lang = language_stash.with(|ls| (*ls.borrow()).get(orig_stashed).unwrap().clone()); let new_lang = get_language(program, orig_lang); language_stash.with(|ls| ls.borrow_mut().insert(result_name.to_string(), new_lang)); } #[wasm_bindgen] pub fn generate__ace_rules(stashed_lang: &str) -> String { language_stash .with(|ls| grammar::ace_rules__for(&(*ls.borrow()).get(stashed_lang).unwrap().pc.grammar)) }
.map_err(|e| e.msg)?; let _type = ast_walk::walk::<ty::SynthTy>( &ast, &ast_walk::LazyWalkReses::new(lang.type_env, lang.type_env__phaseless, ast.clone()),
random_line_split
lock_table.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. #![feature(test)] #![feature(bench_black_box)] use concurrency_manager::ConcurrencyManager; use criterion::*; use futures::executor::block_on; use rand::prelude::*; use std::{borrow::Cow, hint::black_box, mem::forget}; use txn_types::{Key, Lock, LockType, TsSet}; const KEY_LEN: usize = 64; const LOCK_COUNT: usize = 10_000; fn
() -> ConcurrencyManager { let cm = ConcurrencyManager::new(1.into()); let mut buf = [0; KEY_LEN]; for _ in 0..LOCK_COUNT { thread_rng().fill_bytes(&mut buf[..]); let key = Key::from_raw(&buf); // Really rare to generate duplicate key. Do not consider it for simplicity. let guard = block_on(cm.lock_key(&key)); guard.with_lock(|l| { *l = Some(Lock::new( LockType::Put, buf.to_vec(), 10.into(), 1000, None, 10.into(), 1, 20.into(), )); }); // Leak the guard so the lock won't be removed. // It doesn't matter because leaked memory is not too much. forget(guard); } cm } fn point_check_baseline(c: &mut Criterion) { let mut buf = [0; KEY_LEN]; c.bench_function("point_check_baseline", |b| { b.iter(|| { thread_rng().fill_bytes(&mut buf[..]); black_box(Key::from_raw(&buf)); }) }); } fn bench_point_check(c: &mut Criterion) { let cm = prepare_cm(); let mut buf = [0; 64]; let ts_set = TsSet::Empty; c.bench_function("point_check_10k_locks", |b| { b.iter(|| { thread_rng().fill_bytes(&mut buf[..]); let key = Key::from_raw(&buf); let _ = cm.read_key_check(&key, |l| { Lock::check_ts_conflict(Cow::Borrowed(l), &key, 1.into(), &ts_set) }); }) }); } fn range_check_baseline(c: &mut Criterion) { c.bench_function("range_check_baseline", |b| { b.iter(|| { let start = thread_rng().gen_range(0u8..245); black_box(Key::from_raw(&[start])); black_box(Key::from_raw(&[start + 25])); }) }); } fn bench_range_check(c: &mut Criterion) { let cm = prepare_cm(); let ts_set = TsSet::Empty; c.bench_function("range_check_1k_in_10k_locks", |b| { b.iter(|| { let start = thread_rng().gen_range(0u8..230); let start_key = Key::from_raw(&[start]); let end_key = Key::from_raw(&[start + 25]); // The key range is roughly 1/10 the key space. let _ = cm.read_range_check(Some(&start_key), Some(&end_key), |key, l| { Lock::check_ts_conflict(Cow::Borrowed(l), key, 1.into(), &ts_set) }); }) }); } criterion_group!( benches, point_check_baseline, bench_point_check, range_check_baseline, bench_range_check ); criterion_main!(benches);
prepare_cm
identifier_name
lock_table.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. #![feature(test)] #![feature(bench_black_box)] use concurrency_manager::ConcurrencyManager; use criterion::*; use futures::executor::block_on; use rand::prelude::*; use std::{borrow::Cow, hint::black_box, mem::forget}; use txn_types::{Key, Lock, LockType, TsSet}; const KEY_LEN: usize = 64; const LOCK_COUNT: usize = 10_000; fn prepare_cm() -> ConcurrencyManager { let cm = ConcurrencyManager::new(1.into()); let mut buf = [0; KEY_LEN]; for _ in 0..LOCK_COUNT { thread_rng().fill_bytes(&mut buf[..]); let key = Key::from_raw(&buf); // Really rare to generate duplicate key. Do not consider it for simplicity. let guard = block_on(cm.lock_key(&key)); guard.with_lock(|l| { *l = Some(Lock::new( LockType::Put, buf.to_vec(), 10.into(), 1000, None, 10.into(), 1, 20.into(), )); }); // Leak the guard so the lock won't be removed. // It doesn't matter because leaked memory is not too much. forget(guard); } cm } fn point_check_baseline(c: &mut Criterion) { let mut buf = [0; KEY_LEN]; c.bench_function("point_check_baseline", |b| { b.iter(|| { thread_rng().fill_bytes(&mut buf[..]); black_box(Key::from_raw(&buf)); }) }); } fn bench_point_check(c: &mut Criterion) { let cm = prepare_cm(); let mut buf = [0; 64]; let ts_set = TsSet::Empty; c.bench_function("point_check_10k_locks", |b| { b.iter(|| { thread_rng().fill_bytes(&mut buf[..]); let key = Key::from_raw(&buf); let _ = cm.read_key_check(&key, |l| { Lock::check_ts_conflict(Cow::Borrowed(l), &key, 1.into(), &ts_set) }); }) }); } fn range_check_baseline(c: &mut Criterion) { c.bench_function("range_check_baseline", |b| { b.iter(|| { let start = thread_rng().gen_range(0u8..245); black_box(Key::from_raw(&[start])); black_box(Key::from_raw(&[start + 25])); }) }); } fn bench_range_check(c: &mut Criterion) { let cm = prepare_cm(); let ts_set = TsSet::Empty; c.bench_function("range_check_1k_in_10k_locks", |b| { b.iter(|| { let start = thread_rng().gen_range(0u8..230); let start_key = Key::from_raw(&[start]); let end_key = Key::from_raw(&[start + 25]); // The key range is roughly 1/10 the key space. let _ = cm.read_range_check(Some(&start_key), Some(&end_key), |key, l| { Lock::check_ts_conflict(Cow::Borrowed(l), key, 1.into(), &ts_set) });
criterion_group!( benches, point_check_baseline, bench_point_check, range_check_baseline, bench_range_check ); criterion_main!(benches);
}) }); }
random_line_split
lock_table.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. #![feature(test)] #![feature(bench_black_box)] use concurrency_manager::ConcurrencyManager; use criterion::*; use futures::executor::block_on; use rand::prelude::*; use std::{borrow::Cow, hint::black_box, mem::forget}; use txn_types::{Key, Lock, LockType, TsSet}; const KEY_LEN: usize = 64; const LOCK_COUNT: usize = 10_000; fn prepare_cm() -> ConcurrencyManager { let cm = ConcurrencyManager::new(1.into()); let mut buf = [0; KEY_LEN]; for _ in 0..LOCK_COUNT { thread_rng().fill_bytes(&mut buf[..]); let key = Key::from_raw(&buf); // Really rare to generate duplicate key. Do not consider it for simplicity. let guard = block_on(cm.lock_key(&key)); guard.with_lock(|l| { *l = Some(Lock::new( LockType::Put, buf.to_vec(), 10.into(), 1000, None, 10.into(), 1, 20.into(), )); }); // Leak the guard so the lock won't be removed. // It doesn't matter because leaked memory is not too much. forget(guard); } cm } fn point_check_baseline(c: &mut Criterion) { let mut buf = [0; KEY_LEN]; c.bench_function("point_check_baseline", |b| { b.iter(|| { thread_rng().fill_bytes(&mut buf[..]); black_box(Key::from_raw(&buf)); }) }); } fn bench_point_check(c: &mut Criterion) { let cm = prepare_cm(); let mut buf = [0; 64]; let ts_set = TsSet::Empty; c.bench_function("point_check_10k_locks", |b| { b.iter(|| { thread_rng().fill_bytes(&mut buf[..]); let key = Key::from_raw(&buf); let _ = cm.read_key_check(&key, |l| { Lock::check_ts_conflict(Cow::Borrowed(l), &key, 1.into(), &ts_set) }); }) }); } fn range_check_baseline(c: &mut Criterion)
fn bench_range_check(c: &mut Criterion) { let cm = prepare_cm(); let ts_set = TsSet::Empty; c.bench_function("range_check_1k_in_10k_locks", |b| { b.iter(|| { let start = thread_rng().gen_range(0u8..230); let start_key = Key::from_raw(&[start]); let end_key = Key::from_raw(&[start + 25]); // The key range is roughly 1/10 the key space. let _ = cm.read_range_check(Some(&start_key), Some(&end_key), |key, l| { Lock::check_ts_conflict(Cow::Borrowed(l), key, 1.into(), &ts_set) }); }) }); } criterion_group!( benches, point_check_baseline, bench_point_check, range_check_baseline, bench_range_check ); criterion_main!(benches);
{ c.bench_function("range_check_baseline", |b| { b.iter(|| { let start = thread_rng().gen_range(0u8..245); black_box(Key::from_raw(&[start])); black_box(Key::from_raw(&[start + 25])); }) }); }
identifier_body
box.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for box properties. use crate::values::animated::ToAnimatedZero; /// A generic value for the `vertical-align` property. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, )] pub enum VerticalAlign<LengthOrPercentage> { /// `baseline` Baseline, /// `sub` Sub, /// `super` Super, /// `top` Top, /// `text-top` TextTop, /// `middle` Middle, /// `bottom` Bottom, /// `text-bottom` TextBottom, /// `-moz-middle-with-baseline` #[cfg(feature = "gecko")] MozMiddleWithBaseline, /// `<length-percentage>` Length(LengthOrPercentage), } impl<L> VerticalAlign<L> { /// Returns `baseline`. #[inline] pub fn baseline() -> Self { VerticalAlign::Baseline } } impl<L> ToAnimatedZero for VerticalAlign<L> { fn to_animated_zero(&self) -> Result<Self, ()>
} /// https://drafts.csswg.org/css-animations/#animation-iteration-count #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub enum AnimationIterationCount<Number> { /// A `<number>` value. Number(Number), /// The `infinite` keyword. Infinite, } /// A generic value for the `perspective` property. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, )] pub enum Perspective<NonNegativeLength> { /// A non-negative length. Length(NonNegativeLength), /// The keyword `none`. None, } impl<L> Perspective<L> { /// Returns `none`. #[inline] pub fn none() -> Self { Perspective::None } }
{ Err(()) }
identifier_body
box.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for box properties. use crate::values::animated::ToAnimatedZero; /// A generic value for the `vertical-align` property.
Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, )] pub enum VerticalAlign<LengthOrPercentage> { /// `baseline` Baseline, /// `sub` Sub, /// `super` Super, /// `top` Top, /// `text-top` TextTop, /// `middle` Middle, /// `bottom` Bottom, /// `text-bottom` TextBottom, /// `-moz-middle-with-baseline` #[cfg(feature = "gecko")] MozMiddleWithBaseline, /// `<length-percentage>` Length(LengthOrPercentage), } impl<L> VerticalAlign<L> { /// Returns `baseline`. #[inline] pub fn baseline() -> Self { VerticalAlign::Baseline } } impl<L> ToAnimatedZero for VerticalAlign<L> { fn to_animated_zero(&self) -> Result<Self, ()> { Err(()) } } /// https://drafts.csswg.org/css-animations/#animation-iteration-count #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub enum AnimationIterationCount<Number> { /// A `<number>` value. Number(Number), /// The `infinite` keyword. Infinite, } /// A generic value for the `perspective` property. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, )] pub enum Perspective<NonNegativeLength> { /// A non-negative length. Length(NonNegativeLength), /// The keyword `none`. None, } impl<L> Perspective<L> { /// Returns `none`. #[inline] pub fn none() -> Self { Perspective::None } }
#[derive( Animate, Clone, ComputeSquaredDistance,
random_line_split
box.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for box properties. use crate::values::animated::ToAnimatedZero; /// A generic value for the `vertical-align` property. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, )] pub enum VerticalAlign<LengthOrPercentage> { /// `baseline` Baseline, /// `sub` Sub, /// `super` Super, /// `top` Top, /// `text-top` TextTop, /// `middle` Middle, /// `bottom` Bottom, /// `text-bottom` TextBottom, /// `-moz-middle-with-baseline` #[cfg(feature = "gecko")] MozMiddleWithBaseline, /// `<length-percentage>` Length(LengthOrPercentage), } impl<L> VerticalAlign<L> { /// Returns `baseline`. #[inline] pub fn baseline() -> Self { VerticalAlign::Baseline } } impl<L> ToAnimatedZero for VerticalAlign<L> { fn to_animated_zero(&self) -> Result<Self, ()> { Err(()) } } /// https://drafts.csswg.org/css-animations/#animation-iteration-count #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub enum
<Number> { /// A `<number>` value. Number(Number), /// The `infinite` keyword. Infinite, } /// A generic value for the `perspective` property. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, )] pub enum Perspective<NonNegativeLength> { /// A non-negative length. Length(NonNegativeLength), /// The keyword `none`. None, } impl<L> Perspective<L> { /// Returns `none`. #[inline] pub fn none() -> Self { Perspective::None } }
AnimationIterationCount
identifier_name
narrowphase_behaviour.rs
macro_rules! assert_narrowphase_behaviour { ( $( $lines:item )+ ) => { $( $lines )+ mod narrowphase_behaviour { use std::mem; use std::marker::PhantomData; use super::type_marker; use collisions::{BodyData, BodyDef, Narrowphase}; use collisions::shapes::convex_shapes::Cuboid; #[test] fn it_passes_the_collision_test_for_definitely_intersecting_bodies() { let marker = type_marker(); let mut body_0 = create_body_data(0, marker, BodyDef { shape: Box::new(Cuboid::cube(1.0)), .. BodyDef::default() }); let mut body_1 = create_body_data(0, marker, BodyDef { shape: Box::new(Cuboid::cube(1.0)), .. BodyDef::default() }); Narrowphase::update(body_0.narrowphase_ref_mut()); Narrowphase::update(body_1.narrowphase_ref_mut()); assert!( Narrowphase::test(body_0.narrowphase_ref(), body_1.narrowphase_ref()), "expected the intersecting bodies to return a positive collision test, but did not" ); } fn create_body_data<N>(id: u32, _marker: PhantomData<N>, def: BodyDef) -> BodyData<N> where N: Narrowphase { BodyData::new(unsafe { mem::transmute(id) }, def) }
} }; }
random_line_split
checkbox.rs
use crate::direction::Direction; use crate::event::{Event, EventResult, Key, MouseButton, MouseEvent}; use crate::theme::ColorStyle; use crate::view::View; use crate::Cursive; use crate::Printer; use crate::Vec2; use crate::With; use std::rc::Rc; /// Checkable box. /// /// # Examples /// /// ``` /// use cursive_core::views::Checkbox; /// use cursive_core::traits::Identifiable; /// /// let checkbox = Checkbox::new().checked().with_name("check"); /// ``` pub struct Checkbox { checked: bool, enabled: bool, on_change: Option<Rc<dyn Fn(&mut Cursive, bool)>>, } new_default!(Checkbox); impl Checkbox { impl_enabled!(self.enabled); /// Creates a new, unchecked checkbox. pub fn new() -> Self
/// Sets a callback to be used when the state changes. pub fn set_on_change<F:'static + Fn(&mut Cursive, bool)>( &mut self, on_change: F, ) { self.on_change = Some(Rc::new(on_change)); } /// Sets a callback to be used when the state changes. /// /// Chainable variant. pub fn on_change<F:'static + Fn(&mut Cursive, bool)>( self, on_change: F, ) -> Self { self.with(|s| s.set_on_change(on_change)) } /// Toggles the checkbox state. pub fn toggle(&mut self) -> EventResult { let checked =!self.checked; self.set_checked(checked) } /// Check the checkbox. pub fn check(&mut self) -> EventResult { self.set_checked(true) } /// Check the checkbox. /// /// Chainable variant. pub fn checked(self) -> Self { self.with(|s| { s.check(); }) } /// Returns `true` if the checkbox is checked. /// /// # Examples /// /// ``` /// use cursive_core::views::Checkbox; /// /// let mut checkbox = Checkbox::new().checked(); /// assert!(checkbox.is_checked()); /// /// checkbox.uncheck(); /// assert!(!checkbox.is_checked()); /// ``` pub fn is_checked(&self) -> bool { self.checked } /// Uncheck the checkbox. pub fn uncheck(&mut self) -> EventResult { self.set_checked(false) } /// Uncheck the checkbox. /// /// Chainable variant. pub fn unchecked(self) -> Self { self.with(|s| { s.uncheck(); }) } /// Sets the checkbox state. pub fn set_checked(&mut self, checked: bool) -> EventResult { self.checked = checked; if let Some(ref on_change) = self.on_change { let on_change = Rc::clone(on_change); EventResult::with_cb(move |s| on_change(s, checked)) } else { EventResult::Consumed(None) } } /// Set the checkbox state. /// /// Chainable variant. pub fn with_checked(self, is_checked: bool) -> Self { self.with(|s| { s.set_checked(is_checked); }) } fn draw_internal(&self, printer: &Printer) { printer.print((0, 0), "[ ]"); if self.checked { printer.print((1, 0), "X"); } } } impl View for Checkbox { fn required_size(&mut self, _: Vec2) -> Vec2 { Vec2::new(3, 1) } fn take_focus(&mut self, _: Direction) -> bool { self.enabled } fn draw(&self, printer: &Printer) { if self.enabled && printer.enabled { printer.with_selection(printer.focused, |printer| { self.draw_internal(printer) }); } else { printer.with_color(ColorStyle::secondary(), |printer| { self.draw_internal(printer) }); } } fn on_event(&mut self, event: Event) -> EventResult { if!self.enabled { return EventResult::Ignored; } match event { Event::Key(Key::Enter) | Event::Char(' ') => self.toggle(), Event::Mouse { event: MouseEvent::Release(MouseButton::Left), position, offset, } if position.fits_in_rect(offset, (3, 1)) => self.toggle(), _ => EventResult::Ignored, } } }
{ Checkbox { checked: false, enabled: true, on_change: None, } }
identifier_body