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
bit.rs
use std::fmt; #[derive(Clone, Copy, PartialEq)] pub(crate) struct Pack { mask: usize, shift: u32, } impl Pack { /// Value is packed in the `width` least-significant bits. pub(crate) const fn least_significant(width: u32) -> Pack
/// Value is packed in the `width` more-significant bits. pub(crate) const fn then(&self, width: u32) -> Pack { let shift = pointer_width() - self.mask.leading_zeros(); let mask = mask_for(width) << shift; Pack { mask, shift } } /// Width, in bits, dedicated to storing the value. pub(crate) const fn width(&self) -> u32 { pointer_width() - (self.mask >> self.shift).leading_zeros() } /// Max representable value. pub(crate) const fn max_value(&self) -> usize { (1 << self.width()) - 1 } pub(crate) fn pack(&self, value: usize, base: usize) -> usize { assert!(value <= self.max_value()); (base &!self.mask) | (value << self.shift) } /// Packs the value with `base`, losing any bits of `value` that fit. /// /// If `value` is larger than the max value that can be represented by the /// allotted width, the most significant bits are truncated. pub(crate) fn pack_lossy(&self, value: usize, base: usize) -> usize { self.pack(value & self.max_value(), base) } pub(crate) fn unpack(&self, src: usize) -> usize { unpack(src, self.mask, self.shift) } } impl fmt::Debug for Pack { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!( fmt, "Pack {{ mask: {:b}, shift: {} }}", self.mask, self.shift ) } } /// Returns the width of a pointer in bits. pub(crate) const fn pointer_width() -> u32 { std::mem::size_of::<usize>() as u32 * 8 } /// Returns a `usize` with the right-most `n` bits set. pub(crate) const fn mask_for(n: u32) -> usize { let shift = 1usize.wrapping_shl(n - 1); shift | (shift - 1) } /// Unpacks a value using a mask & shift. pub(crate) const fn unpack(src: usize, mask: usize, shift: u32) -> usize { (src & mask) >> shift }
{ let mask = mask_for(width); Pack { mask, shift: 0 } }
identifier_body
bit.rs
use std::fmt; #[derive(Clone, Copy, PartialEq)] pub(crate) struct Pack { mask: usize, shift: u32, } impl Pack { /// Value is packed in the `width` least-significant bits. pub(crate) const fn least_significant(width: u32) -> Pack { let mask = mask_for(width); Pack { mask, shift: 0 } } /// Value is packed in the `width` more-significant bits. pub(crate) const fn then(&self, width: u32) -> Pack { let shift = pointer_width() - self.mask.leading_zeros(); let mask = mask_for(width) << shift; Pack { mask, shift } } /// Width, in bits, dedicated to storing the value. pub(crate) const fn width(&self) -> u32 { pointer_width() - (self.mask >> self.shift).leading_zeros() } /// Max representable value. pub(crate) const fn max_value(&self) -> usize { (1 << self.width()) - 1 } pub(crate) fn pack(&self, value: usize, base: usize) -> usize { assert!(value <= self.max_value()); (base &!self.mask) | (value << self.shift) } /// Packs the value with `base`, losing any bits of `value` that fit. /// /// If `value` is larger than the max value that can be represented by the /// allotted width, the most significant bits are truncated. pub(crate) fn pack_lossy(&self, value: usize, base: usize) -> usize { self.pack(value & self.max_value(), base) } pub(crate) fn unpack(&self, src: usize) -> usize { unpack(src, self.mask, self.shift) } } impl fmt::Debug for Pack { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!( fmt, "Pack {{ mask: {:b}, shift: {} }}", self.mask, self.shift ) } } /// Returns the width of a pointer in bits. pub(crate) const fn pointer_width() -> u32 { std::mem::size_of::<usize>() as u32 * 8 } /// Returns a `usize` with the right-most `n` bits set.
/// Unpacks a value using a mask & shift. pub(crate) const fn unpack(src: usize, mask: usize, shift: u32) -> usize { (src & mask) >> shift }
pub(crate) const fn mask_for(n: u32) -> usize { let shift = 1usize.wrapping_shl(n - 1); shift | (shift - 1) }
random_line_split
bit.rs
use std::fmt; #[derive(Clone, Copy, PartialEq)] pub(crate) struct Pack { mask: usize, shift: u32, } impl Pack { /// Value is packed in the `width` least-significant bits. pub(crate) const fn least_significant(width: u32) -> Pack { let mask = mask_for(width); Pack { mask, shift: 0 } } /// Value is packed in the `width` more-significant bits. pub(crate) const fn then(&self, width: u32) -> Pack { let shift = pointer_width() - self.mask.leading_zeros(); let mask = mask_for(width) << shift; Pack { mask, shift } } /// Width, in bits, dedicated to storing the value. pub(crate) const fn width(&self) -> u32 { pointer_width() - (self.mask >> self.shift).leading_zeros() } /// Max representable value. pub(crate) const fn max_value(&self) -> usize { (1 << self.width()) - 1 } pub(crate) fn pack(&self, value: usize, base: usize) -> usize { assert!(value <= self.max_value()); (base &!self.mask) | (value << self.shift) } /// Packs the value with `base`, losing any bits of `value` that fit. /// /// If `value` is larger than the max value that can be represented by the /// allotted width, the most significant bits are truncated. pub(crate) fn
(&self, value: usize, base: usize) -> usize { self.pack(value & self.max_value(), base) } pub(crate) fn unpack(&self, src: usize) -> usize { unpack(src, self.mask, self.shift) } } impl fmt::Debug for Pack { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!( fmt, "Pack {{ mask: {:b}, shift: {} }}", self.mask, self.shift ) } } /// Returns the width of a pointer in bits. pub(crate) const fn pointer_width() -> u32 { std::mem::size_of::<usize>() as u32 * 8 } /// Returns a `usize` with the right-most `n` bits set. pub(crate) const fn mask_for(n: u32) -> usize { let shift = 1usize.wrapping_shl(n - 1); shift | (shift - 1) } /// Unpacks a value using a mask & shift. pub(crate) const fn unpack(src: usize, mask: usize, shift: u32) -> usize { (src & mask) >> shift }
pack_lossy
identifier_name
fmt.rs
use crate::clippy_project_root; use shell_escape::escape; use std::ffi::OsStr; use std::path::Path; use std::process::{self, Command}; use std::{fs, io}; use walkdir::WalkDir; #[derive(Debug)] pub enum CliError { CommandFailed(String, String), IoError(io::Error), RustfmtNotInstalled, WalkDirError(walkdir::Error), RaSetupActive, } impl From<io::Error> for CliError { fn from(error: io::Error) -> Self { Self::IoError(error) } } impl From<walkdir::Error> for CliError { fn from(error: walkdir::Error) -> Self { Self::WalkDirError(error) } } struct FmtContext { check: bool, verbose: bool, } // the "main" function of cargo dev fmt pub fn run(check: bool, verbose: bool) { fn try_run(context: &FmtContext) -> Result<bool, CliError> { let mut success = true; let project_root = clippy_project_root(); // if we added a local rustc repo as path dependency to clippy for rust analyzer, we do NOT want to // format because rustfmt would also format the entire rustc repo as it is a local // dependency if fs::read_to_string(project_root.join("Cargo.toml")) .expect("Failed to read clippy Cargo.toml") .contains(&"[target.'cfg(NOT_A_PLATFORM)'.dependencies]") { return Err(CliError::RaSetupActive); } rustfmt_test(context)?; success &= cargo_fmt(context, project_root.as_path())?; success &= cargo_fmt(context, &project_root.join("clippy_dev"))?; success &= cargo_fmt(context, &project_root.join("rustc_tools_util"))?; success &= cargo_fmt(context, &project_root.join("lintcheck"))?; for entry in WalkDir::new(project_root.join("tests")) { let entry = entry?; let path = entry.path(); if path.extension()!= Some("rs".as_ref()) || entry.file_name() == "ice-3891.rs" { continue; } success &= rustfmt(context, path)?; } Ok(success) } fn output_err(err: CliError) { match err { CliError::CommandFailed(command, stderr) => { eprintln!("error: A command failed! `{}`\nstderr: {}", command, stderr); }, CliError::IoError(err) => { eprintln!("error: {}", err); }, CliError::RustfmtNotInstalled => { eprintln!("error: rustfmt nightly is not installed."); }, CliError::WalkDirError(err) => { eprintln!("error: {}", err); }, CliError::RaSetupActive => { eprintln!( "error: a local rustc repo is enabled as path dependency via `cargo dev setup intellij`. Not formatting because that would format the local repo as well! Please revert the changes to Cargo.tomls first." ); }, } } let context = FmtContext { check, verbose }; let result = try_run(&context); let code = match result { Ok(true) => 0, Ok(false) => { eprintln!(); eprintln!("Formatting check failed."); eprintln!("Run `cargo dev fmt` to update formatting."); 1 }, Err(err) => { output_err(err); 1 }, }; process::exit(code); } fn format_command(program: impl AsRef<OsStr>, dir: impl AsRef<Path>, args: &[impl AsRef<OsStr>]) -> String { let arg_display: Vec<_> = args.iter().map(|a| escape(a.as_ref().to_string_lossy())).collect(); format!( "cd {} && {} {}", escape(dir.as_ref().to_string_lossy()), escape(program.as_ref().to_string_lossy()), arg_display.join(" ") ) } fn exec( context: &FmtContext, program: impl AsRef<OsStr>, dir: impl AsRef<Path>, args: &[impl AsRef<OsStr>], ) -> Result<bool, CliError> { if context.verbose { println!("{}", format_command(&program, &dir, args)); } let child = Command::new(&program).current_dir(&dir).args(args.iter()).spawn()?; let output = child.wait_with_output()?; let success = output.status.success(); if!context.check &&!success { let stderr = std::str::from_utf8(&output.stderr).unwrap_or(""); return Err(CliError::CommandFailed( format_command(&program, &dir, args), String::from(stderr), )); } Ok(success) } fn cargo_fmt(context: &FmtContext, path: &Path) -> Result<bool, CliError> { let mut args = vec!["+nightly", "fmt", "--all"]; if context.check { args.push("--"); args.push("--check"); } let success = exec(context, "cargo", path, &args)?; Ok(success) } fn rustfmt_test(context: &FmtContext) -> Result<(), CliError> { let program = "rustfmt"; let dir = std::env::current_dir()?; let args = &["+nightly", "--version"]; if context.verbose { println!("{}", format_command(&program, &dir, args)); } let output = Command::new(&program).current_dir(&dir).args(args.iter()).output()?; if output.status.success() { Ok(()) } else if std::str::from_utf8(&output.stderr) .unwrap_or("") .starts_with("error: 'rustfmt' is not installed") { Err(CliError::RustfmtNotInstalled) } else { Err(CliError::CommandFailed( format_command(&program, &dir, args), std::str::from_utf8(&output.stderr).unwrap_or("").to_string(), )) } } fn rustfmt(context: &FmtContext, path: &Path) -> Result<bool, CliError>
{ let mut args = vec!["+nightly".as_ref(), path.as_os_str()]; if context.check { args.push("--check".as_ref()); } let success = exec(context, "rustfmt", std::env::current_dir()?, &args)?; if !success { eprintln!("rustfmt failed on {}", path.display()); } Ok(success) }
identifier_body
fmt.rs
use crate::clippy_project_root; use shell_escape::escape; use std::ffi::OsStr; use std::path::Path; use std::process::{self, Command}; use std::{fs, io}; use walkdir::WalkDir; #[derive(Debug)] pub enum CliError { CommandFailed(String, String), IoError(io::Error), RustfmtNotInstalled, WalkDirError(walkdir::Error), RaSetupActive, } impl From<io::Error> for CliError { fn from(error: io::Error) -> Self { Self::IoError(error) } } impl From<walkdir::Error> for CliError { fn from(error: walkdir::Error) -> Self { Self::WalkDirError(error) } } struct FmtContext { check: bool, verbose: bool, } // the "main" function of cargo dev fmt pub fn run(check: bool, verbose: bool) { fn try_run(context: &FmtContext) -> Result<bool, CliError> { let mut success = true; let project_root = clippy_project_root(); // if we added a local rustc repo as path dependency to clippy for rust analyzer, we do NOT want to // format because rustfmt would also format the entire rustc repo as it is a local // dependency if fs::read_to_string(project_root.join("Cargo.toml")) .expect("Failed to read clippy Cargo.toml") .contains(&"[target.'cfg(NOT_A_PLATFORM)'.dependencies]") { return Err(CliError::RaSetupActive); } rustfmt_test(context)?; success &= cargo_fmt(context, project_root.as_path())?; success &= cargo_fmt(context, &project_root.join("clippy_dev"))?; success &= cargo_fmt(context, &project_root.join("rustc_tools_util"))?; success &= cargo_fmt(context, &project_root.join("lintcheck"))?; for entry in WalkDir::new(project_root.join("tests")) { let entry = entry?; let path = entry.path(); if path.extension()!= Some("rs".as_ref()) || entry.file_name() == "ice-3891.rs" { continue; } success &= rustfmt(context, path)?; } Ok(success) } fn output_err(err: CliError) { match err { CliError::CommandFailed(command, stderr) => { eprintln!("error: A command failed! `{}`\nstderr: {}", command, stderr); }, CliError::IoError(err) => { eprintln!("error: {}", err); }, CliError::RustfmtNotInstalled => { eprintln!("error: rustfmt nightly is not installed."); }, CliError::WalkDirError(err) => { eprintln!("error: {}", err); }, CliError::RaSetupActive => { eprintln!( "error: a local rustc repo is enabled as path dependency via `cargo dev setup intellij`. Not formatting because that would format the local repo as well! Please revert the changes to Cargo.tomls first." ); }, }
let context = FmtContext { check, verbose }; let result = try_run(&context); let code = match result { Ok(true) => 0, Ok(false) => { eprintln!(); eprintln!("Formatting check failed."); eprintln!("Run `cargo dev fmt` to update formatting."); 1 }, Err(err) => { output_err(err); 1 }, }; process::exit(code); } fn format_command(program: impl AsRef<OsStr>, dir: impl AsRef<Path>, args: &[impl AsRef<OsStr>]) -> String { let arg_display: Vec<_> = args.iter().map(|a| escape(a.as_ref().to_string_lossy())).collect(); format!( "cd {} && {} {}", escape(dir.as_ref().to_string_lossy()), escape(program.as_ref().to_string_lossy()), arg_display.join(" ") ) } fn exec( context: &FmtContext, program: impl AsRef<OsStr>, dir: impl AsRef<Path>, args: &[impl AsRef<OsStr>], ) -> Result<bool, CliError> { if context.verbose { println!("{}", format_command(&program, &dir, args)); } let child = Command::new(&program).current_dir(&dir).args(args.iter()).spawn()?; let output = child.wait_with_output()?; let success = output.status.success(); if!context.check &&!success { let stderr = std::str::from_utf8(&output.stderr).unwrap_or(""); return Err(CliError::CommandFailed( format_command(&program, &dir, args), String::from(stderr), )); } Ok(success) } fn cargo_fmt(context: &FmtContext, path: &Path) -> Result<bool, CliError> { let mut args = vec!["+nightly", "fmt", "--all"]; if context.check { args.push("--"); args.push("--check"); } let success = exec(context, "cargo", path, &args)?; Ok(success) } fn rustfmt_test(context: &FmtContext) -> Result<(), CliError> { let program = "rustfmt"; let dir = std::env::current_dir()?; let args = &["+nightly", "--version"]; if context.verbose { println!("{}", format_command(&program, &dir, args)); } let output = Command::new(&program).current_dir(&dir).args(args.iter()).output()?; if output.status.success() { Ok(()) } else if std::str::from_utf8(&output.stderr) .unwrap_or("") .starts_with("error: 'rustfmt' is not installed") { Err(CliError::RustfmtNotInstalled) } else { Err(CliError::CommandFailed( format_command(&program, &dir, args), std::str::from_utf8(&output.stderr).unwrap_or("").to_string(), )) } } fn rustfmt(context: &FmtContext, path: &Path) -> Result<bool, CliError> { let mut args = vec!["+nightly".as_ref(), path.as_os_str()]; if context.check { args.push("--check".as_ref()); } let success = exec(context, "rustfmt", std::env::current_dir()?, &args)?; if!success { eprintln!("rustfmt failed on {}", path.display()); } Ok(success) }
}
random_line_split
fmt.rs
use crate::clippy_project_root; use shell_escape::escape; use std::ffi::OsStr; use std::path::Path; use std::process::{self, Command}; use std::{fs, io}; use walkdir::WalkDir; #[derive(Debug)] pub enum
{ CommandFailed(String, String), IoError(io::Error), RustfmtNotInstalled, WalkDirError(walkdir::Error), RaSetupActive, } impl From<io::Error> for CliError { fn from(error: io::Error) -> Self { Self::IoError(error) } } impl From<walkdir::Error> for CliError { fn from(error: walkdir::Error) -> Self { Self::WalkDirError(error) } } struct FmtContext { check: bool, verbose: bool, } // the "main" function of cargo dev fmt pub fn run(check: bool, verbose: bool) { fn try_run(context: &FmtContext) -> Result<bool, CliError> { let mut success = true; let project_root = clippy_project_root(); // if we added a local rustc repo as path dependency to clippy for rust analyzer, we do NOT want to // format because rustfmt would also format the entire rustc repo as it is a local // dependency if fs::read_to_string(project_root.join("Cargo.toml")) .expect("Failed to read clippy Cargo.toml") .contains(&"[target.'cfg(NOT_A_PLATFORM)'.dependencies]") { return Err(CliError::RaSetupActive); } rustfmt_test(context)?; success &= cargo_fmt(context, project_root.as_path())?; success &= cargo_fmt(context, &project_root.join("clippy_dev"))?; success &= cargo_fmt(context, &project_root.join("rustc_tools_util"))?; success &= cargo_fmt(context, &project_root.join("lintcheck"))?; for entry in WalkDir::new(project_root.join("tests")) { let entry = entry?; let path = entry.path(); if path.extension()!= Some("rs".as_ref()) || entry.file_name() == "ice-3891.rs" { continue; } success &= rustfmt(context, path)?; } Ok(success) } fn output_err(err: CliError) { match err { CliError::CommandFailed(command, stderr) => { eprintln!("error: A command failed! `{}`\nstderr: {}", command, stderr); }, CliError::IoError(err) => { eprintln!("error: {}", err); }, CliError::RustfmtNotInstalled => { eprintln!("error: rustfmt nightly is not installed."); }, CliError::WalkDirError(err) => { eprintln!("error: {}", err); }, CliError::RaSetupActive => { eprintln!( "error: a local rustc repo is enabled as path dependency via `cargo dev setup intellij`. Not formatting because that would format the local repo as well! Please revert the changes to Cargo.tomls first." ); }, } } let context = FmtContext { check, verbose }; let result = try_run(&context); let code = match result { Ok(true) => 0, Ok(false) => { eprintln!(); eprintln!("Formatting check failed."); eprintln!("Run `cargo dev fmt` to update formatting."); 1 }, Err(err) => { output_err(err); 1 }, }; process::exit(code); } fn format_command(program: impl AsRef<OsStr>, dir: impl AsRef<Path>, args: &[impl AsRef<OsStr>]) -> String { let arg_display: Vec<_> = args.iter().map(|a| escape(a.as_ref().to_string_lossy())).collect(); format!( "cd {} && {} {}", escape(dir.as_ref().to_string_lossy()), escape(program.as_ref().to_string_lossy()), arg_display.join(" ") ) } fn exec( context: &FmtContext, program: impl AsRef<OsStr>, dir: impl AsRef<Path>, args: &[impl AsRef<OsStr>], ) -> Result<bool, CliError> { if context.verbose { println!("{}", format_command(&program, &dir, args)); } let child = Command::new(&program).current_dir(&dir).args(args.iter()).spawn()?; let output = child.wait_with_output()?; let success = output.status.success(); if!context.check &&!success { let stderr = std::str::from_utf8(&output.stderr).unwrap_or(""); return Err(CliError::CommandFailed( format_command(&program, &dir, args), String::from(stderr), )); } Ok(success) } fn cargo_fmt(context: &FmtContext, path: &Path) -> Result<bool, CliError> { let mut args = vec!["+nightly", "fmt", "--all"]; if context.check { args.push("--"); args.push("--check"); } let success = exec(context, "cargo", path, &args)?; Ok(success) } fn rustfmt_test(context: &FmtContext) -> Result<(), CliError> { let program = "rustfmt"; let dir = std::env::current_dir()?; let args = &["+nightly", "--version"]; if context.verbose { println!("{}", format_command(&program, &dir, args)); } let output = Command::new(&program).current_dir(&dir).args(args.iter()).output()?; if output.status.success() { Ok(()) } else if std::str::from_utf8(&output.stderr) .unwrap_or("") .starts_with("error: 'rustfmt' is not installed") { Err(CliError::RustfmtNotInstalled) } else { Err(CliError::CommandFailed( format_command(&program, &dir, args), std::str::from_utf8(&output.stderr).unwrap_or("").to_string(), )) } } fn rustfmt(context: &FmtContext, path: &Path) -> Result<bool, CliError> { let mut args = vec!["+nightly".as_ref(), path.as_os_str()]; if context.check { args.push("--check".as_ref()); } let success = exec(context, "rustfmt", std::env::current_dir()?, &args)?; if!success { eprintln!("rustfmt failed on {}", path.display()); } Ok(success) }
CliError
identifier_name
fmt.rs
use crate::clippy_project_root; use shell_escape::escape; use std::ffi::OsStr; use std::path::Path; use std::process::{self, Command}; use std::{fs, io}; use walkdir::WalkDir; #[derive(Debug)] pub enum CliError { CommandFailed(String, String), IoError(io::Error), RustfmtNotInstalled, WalkDirError(walkdir::Error), RaSetupActive, } impl From<io::Error> for CliError { fn from(error: io::Error) -> Self { Self::IoError(error) } } impl From<walkdir::Error> for CliError { fn from(error: walkdir::Error) -> Self { Self::WalkDirError(error) } } struct FmtContext { check: bool, verbose: bool, } // the "main" function of cargo dev fmt pub fn run(check: bool, verbose: bool) { fn try_run(context: &FmtContext) -> Result<bool, CliError> { let mut success = true; let project_root = clippy_project_root(); // if we added a local rustc repo as path dependency to clippy for rust analyzer, we do NOT want to // format because rustfmt would also format the entire rustc repo as it is a local // dependency if fs::read_to_string(project_root.join("Cargo.toml")) .expect("Failed to read clippy Cargo.toml") .contains(&"[target.'cfg(NOT_A_PLATFORM)'.dependencies]") { return Err(CliError::RaSetupActive); } rustfmt_test(context)?; success &= cargo_fmt(context, project_root.as_path())?; success &= cargo_fmt(context, &project_root.join("clippy_dev"))?; success &= cargo_fmt(context, &project_root.join("rustc_tools_util"))?; success &= cargo_fmt(context, &project_root.join("lintcheck"))?; for entry in WalkDir::new(project_root.join("tests")) { let entry = entry?; let path = entry.path(); if path.extension()!= Some("rs".as_ref()) || entry.file_name() == "ice-3891.rs" { continue; } success &= rustfmt(context, path)?; } Ok(success) } fn output_err(err: CliError) { match err { CliError::CommandFailed(command, stderr) => { eprintln!("error: A command failed! `{}`\nstderr: {}", command, stderr); }, CliError::IoError(err) => { eprintln!("error: {}", err); }, CliError::RustfmtNotInstalled => { eprintln!("error: rustfmt nightly is not installed."); }, CliError::WalkDirError(err) => { eprintln!("error: {}", err); }, CliError::RaSetupActive => { eprintln!( "error: a local rustc repo is enabled as path dependency via `cargo dev setup intellij`. Not formatting because that would format the local repo as well! Please revert the changes to Cargo.tomls first." ); }, } } let context = FmtContext { check, verbose }; let result = try_run(&context); let code = match result { Ok(true) => 0, Ok(false) => { eprintln!(); eprintln!("Formatting check failed."); eprintln!("Run `cargo dev fmt` to update formatting."); 1 }, Err(err) => { output_err(err); 1 }, }; process::exit(code); } fn format_command(program: impl AsRef<OsStr>, dir: impl AsRef<Path>, args: &[impl AsRef<OsStr>]) -> String { let arg_display: Vec<_> = args.iter().map(|a| escape(a.as_ref().to_string_lossy())).collect(); format!( "cd {} && {} {}", escape(dir.as_ref().to_string_lossy()), escape(program.as_ref().to_string_lossy()), arg_display.join(" ") ) } fn exec( context: &FmtContext, program: impl AsRef<OsStr>, dir: impl AsRef<Path>, args: &[impl AsRef<OsStr>], ) -> Result<bool, CliError> { if context.verbose { println!("{}", format_command(&program, &dir, args)); } let child = Command::new(&program).current_dir(&dir).args(args.iter()).spawn()?; let output = child.wait_with_output()?; let success = output.status.success(); if!context.check &&!success { let stderr = std::str::from_utf8(&output.stderr).unwrap_or(""); return Err(CliError::CommandFailed( format_command(&program, &dir, args), String::from(stderr), )); } Ok(success) } fn cargo_fmt(context: &FmtContext, path: &Path) -> Result<bool, CliError> { let mut args = vec!["+nightly", "fmt", "--all"]; if context.check { args.push("--"); args.push("--check"); } let success = exec(context, "cargo", path, &args)?; Ok(success) } fn rustfmt_test(context: &FmtContext) -> Result<(), CliError> { let program = "rustfmt"; let dir = std::env::current_dir()?; let args = &["+nightly", "--version"]; if context.verbose { println!("{}", format_command(&program, &dir, args)); } let output = Command::new(&program).current_dir(&dir).args(args.iter()).output()?; if output.status.success() { Ok(()) } else if std::str::from_utf8(&output.stderr) .unwrap_or("") .starts_with("error: 'rustfmt' is not installed") { Err(CliError::RustfmtNotInstalled) } else { Err(CliError::CommandFailed( format_command(&program, &dir, args), std::str::from_utf8(&output.stderr).unwrap_or("").to_string(), )) } } fn rustfmt(context: &FmtContext, path: &Path) -> Result<bool, CliError> { let mut args = vec!["+nightly".as_ref(), path.as_os_str()]; if context.check { args.push("--check".as_ref()); } let success = exec(context, "rustfmt", std::env::current_dir()?, &args)?; if!success
Ok(success) }
{ eprintln!("rustfmt failed on {}", path.display()); }
conditional_block
scgi.rs
extern crate collections; use std::io::{BufferedReader, TcpListener, Listener, Acceptor}; use std::io::net::ip::{SocketAddr}; use std::from_str::{from_str}; use std::to_str::{ToStr}; use std::str::from_utf8; use collections::hashmap::HashMap; pub type Headers = HashMap<~str, ~str>; pub type SCGIMessage = (Headers, ~[u8]); pub struct SCGIServer { listen_address: SocketAddr, // XXX: if i write Sender<SCGIMessage, Sender<SCGIMessage>>, that expands to ((Header, ~[u8]), SCGIMessage), and not (Header, ~[u8], SCGIMessage), sad handler: Sender<(Headers, ~[u8], Sender<SCGIMessage>)> } impl SCGIServer { pub fn new(addr: SocketAddr, handler: Sender<(Headers, ~[u8], Sender<SCGIMessage>)>) -> SCGIServer { SCGIServer { listen_address: addr, handler: handler } } pub fn start(&self) { let mut listener = match TcpListener::bind(self.listen_address) { Ok(listener) => listener, Err(_) => fail!("Unable to bind to address {:s}", self.listen_address.to_str()) }; let mut acceptor = match listener.listen() { Ok(acceptor) => acceptor, Err(err) => fail!("Cannot listen on the bound.\nError: {:s}", err.to_str()) }; for stream in acceptor.incoming() { let sender = self.handler.clone(); spawn(proc() { let mut stream = stream.clone(); let mut reader = BufferedReader::new(stream.clone());
reader.read_until(58).map(|b| from_str::<uint>(from_utf8(b.init()).expect("Unable to parse headers' length")).expect("Unable to parse headers' length")).unwrap(); let mut headers_read = 0; let mut headers = HashMap::new(); loop { if headers_read >= headers_length { break; } let header_name = reader.read_until(0).map(|b| from_utf8(b.init()).expect("Invalid header name string").to_owned()).unwrap(); let header_value = reader.read_until(0).map(|b| from_utf8(b.init()).expect("Invalid header value string").to_owned()).unwrap(); headers_read += header_name.len() + header_value.len() + 2; headers.insert(header_name, header_value); } // Next character is a comma, after that it's the body assert!(reader.read_byte().unwrap() == 44); assert!(headers.contains_key(&~"SCGI") && headers.contains_key(&~"CONTENT_LENGTH")); let body = reader.read_bytes(from_str::<uint>(*headers.get(&~"CONTENT_LENGTH")).expect("CONTENT_LENGTH is not a number")).unwrap(); let (response_sender, response_receiver) = channel(); sender.send((headers, body, response_sender)); let (response_headers, response_body) = response_receiver.recv(); for (key, value) in response_headers.iter() { stream.write(format!("{:s}: {:s}\r\n", *key, *value).as_bytes()); } stream.write(bytes!("\r\n")); stream.write(response_body); }); } } }
// XXX: ohgodwhat let headers_length =
random_line_split
scgi.rs
extern crate collections; use std::io::{BufferedReader, TcpListener, Listener, Acceptor}; use std::io::net::ip::{SocketAddr}; use std::from_str::{from_str}; use std::to_str::{ToStr}; use std::str::from_utf8; use collections::hashmap::HashMap; pub type Headers = HashMap<~str, ~str>; pub type SCGIMessage = (Headers, ~[u8]); pub struct SCGIServer { listen_address: SocketAddr, // XXX: if i write Sender<SCGIMessage, Sender<SCGIMessage>>, that expands to ((Header, ~[u8]), SCGIMessage), and not (Header, ~[u8], SCGIMessage), sad handler: Sender<(Headers, ~[u8], Sender<SCGIMessage>)> } impl SCGIServer { pub fn
(addr: SocketAddr, handler: Sender<(Headers, ~[u8], Sender<SCGIMessage>)>) -> SCGIServer { SCGIServer { listen_address: addr, handler: handler } } pub fn start(&self) { let mut listener = match TcpListener::bind(self.listen_address) { Ok(listener) => listener, Err(_) => fail!("Unable to bind to address {:s}", self.listen_address.to_str()) }; let mut acceptor = match listener.listen() { Ok(acceptor) => acceptor, Err(err) => fail!("Cannot listen on the bound.\nError: {:s}", err.to_str()) }; for stream in acceptor.incoming() { let sender = self.handler.clone(); spawn(proc() { let mut stream = stream.clone(); let mut reader = BufferedReader::new(stream.clone()); // XXX: ohgodwhat let headers_length = reader.read_until(58).map(|b| from_str::<uint>(from_utf8(b.init()).expect("Unable to parse headers' length")).expect("Unable to parse headers' length")).unwrap(); let mut headers_read = 0; let mut headers = HashMap::new(); loop { if headers_read >= headers_length { break; } let header_name = reader.read_until(0).map(|b| from_utf8(b.init()).expect("Invalid header name string").to_owned()).unwrap(); let header_value = reader.read_until(0).map(|b| from_utf8(b.init()).expect("Invalid header value string").to_owned()).unwrap(); headers_read += header_name.len() + header_value.len() + 2; headers.insert(header_name, header_value); } // Next character is a comma, after that it's the body assert!(reader.read_byte().unwrap() == 44); assert!(headers.contains_key(&~"SCGI") && headers.contains_key(&~"CONTENT_LENGTH")); let body = reader.read_bytes(from_str::<uint>(*headers.get(&~"CONTENT_LENGTH")).expect("CONTENT_LENGTH is not a number")).unwrap(); let (response_sender, response_receiver) = channel(); sender.send((headers, body, response_sender)); let (response_headers, response_body) = response_receiver.recv(); for (key, value) in response_headers.iter() { stream.write(format!("{:s}: {:s}\r\n", *key, *value).as_bytes()); } stream.write(bytes!("\r\n")); stream.write(response_body); }); } } }
new
identifier_name
issue-573-layout-test-failures.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Outer { pub i: u8, } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct AutoIdVector { pub ar: Outer, } #[test] fn bindgen_test_layout_AutoIdVector()
stringify!(ar) ) ); } #[test] fn __bindgen_test_layout_Outer_open0_int_close0_instantiation() { assert_eq!( ::std::mem::size_of::<Outer>(), 1usize, concat!("Size of template specialization: ", stringify!(Outer)) ); assert_eq!( ::std::mem::align_of::<Outer>(), 1usize, concat!("Alignment of template specialization: ", stringify!(Outer)) ); }
{ assert_eq!( ::std::mem::size_of::<AutoIdVector>(), 1usize, concat!("Size of: ", stringify!(AutoIdVector)) ); assert_eq!( ::std::mem::align_of::<AutoIdVector>(), 1usize, concat!("Alignment of ", stringify!(AutoIdVector)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<AutoIdVector>())).ar as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(AutoIdVector), "::",
identifier_body
issue-573-layout-test-failures.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Outer { pub i: u8, } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct AutoIdVector { pub ar: Outer, } #[test] fn bindgen_test_layout_AutoIdVector() { assert_eq!( ::std::mem::size_of::<AutoIdVector>(),
assert_eq!( ::std::mem::align_of::<AutoIdVector>(), 1usize, concat!("Alignment of ", stringify!(AutoIdVector)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<AutoIdVector>())).ar as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(AutoIdVector), "::", stringify!(ar) ) ); } #[test] fn __bindgen_test_layout_Outer_open0_int_close0_instantiation() { assert_eq!( ::std::mem::size_of::<Outer>(), 1usize, concat!("Size of template specialization: ", stringify!(Outer)) ); assert_eq!( ::std::mem::align_of::<Outer>(), 1usize, concat!("Alignment of template specialization: ", stringify!(Outer)) ); }
1usize, concat!("Size of: ", stringify!(AutoIdVector)) );
random_line_split
issue-573-layout-test-failures.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Outer { pub i: u8, } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct
{ pub ar: Outer, } #[test] fn bindgen_test_layout_AutoIdVector() { assert_eq!( ::std::mem::size_of::<AutoIdVector>(), 1usize, concat!("Size of: ", stringify!(AutoIdVector)) ); assert_eq!( ::std::mem::align_of::<AutoIdVector>(), 1usize, concat!("Alignment of ", stringify!(AutoIdVector)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<AutoIdVector>())).ar as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(AutoIdVector), "::", stringify!(ar) ) ); } #[test] fn __bindgen_test_layout_Outer_open0_int_close0_instantiation() { assert_eq!( ::std::mem::size_of::<Outer>(), 1usize, concat!("Size of template specialization: ", stringify!(Outer)) ); assert_eq!( ::std::mem::align_of::<Outer>(), 1usize, concat!("Alignment of template specialization: ", stringify!(Outer)) ); }
AutoIdVector
identifier_name
hash.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use digest::{Digest, FixedOutput}; use sha2::Sha256; use std::error::Error; use std::fmt; use std::io::{self, Write}; use hex; const FINGERPRINT_SIZE: usize = 32; #[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct Fingerprint(pub [u8; FINGERPRINT_SIZE]); impl Fingerprint { pub fn from_bytes_unsafe(bytes: &[u8]) -> Fingerprint { if bytes.len()!= FINGERPRINT_SIZE { panic!( "Input value was not a fingerprint; had length: {}", bytes.len() ); } let mut fingerprint = [0; FINGERPRINT_SIZE]; fingerprint.clone_from_slice(&bytes[0..FINGERPRINT_SIZE]); Fingerprint(fingerprint) } pub fn from_hex_string(hex_string: &str) -> Result<Fingerprint, String> { <[u8; FINGERPRINT_SIZE] as hex::FromHex>::from_hex(hex_string) .map(|v| Fingerprint(v)) .map_err(|e| e.description().to_string()) } pub fn as_bytes(&self) -> &[u8; FINGERPRINT_SIZE] { &self.0 } pub fn to_hex(&self) -> String { let mut s = String::new(); for &byte in self.0.iter() { fmt::Write::write_fmt(&mut s, format_args!("{:02x}", byte)).unwrap(); } s } } impl fmt::Display for Fingerprint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.to_hex()) } } impl fmt::Debug for Fingerprint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Fingerprint<{}>", self.to_hex()) } } /// /// A Write instance that fingerprints all data that passes through it. /// pub struct WriterHasher<W: Write> { hasher: Sha256, inner: W, } impl<W: Write> WriterHasher<W> { pub fn new(inner: W) -> WriterHasher<W> { WriterHasher { hasher: Sha256::default(), inner: inner, } } /// /// Returns the result of fingerprinting this stream, and Drops the stream. /// pub fn finish(self) -> Fingerprint { Fingerprint::from_bytes_unsafe(&self.hasher.fixed_result()) } } impl<W: Write> Write for WriterHasher<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let written = self.inner.write(buf)?; // Hash the bytes that were successfully written. self.hasher.input(&buf[0..written]); Ok(written) } fn flush(&mut self) -> io::Result<()> { self.inner.flush() } } #[cfg(test)] mod fingerprint_tests { use super::Fingerprint; #[test] fn from_bytes_unsafe() { assert_eq!( Fingerprint::from_bytes_unsafe(&vec![ 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, ]), Fingerprint([0xab; 32]) ); } #[test] fn from_hex_string() { assert_eq!( Fingerprint::from_hex_string( "0123456789abcdefFEDCBA98765432100000000000000000ffFFfFfFFfFfFFff", ).unwrap(), Fingerprint( [ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, ], ) ) } #[test] fn from_hex_string_not_long_enough() { Fingerprint::from_hex_string("abcd").expect_err("Want err"); } #[test] fn from_hex_string_too_long() { Fingerprint::from_hex_string( "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0", ).expect_err("Want err"); } #[test] fn from_hex_string_invalid_chars() { Fingerprint::from_hex_string( "Q123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF", ).expect_err("Want err"); } #[test] fn to_hex() { assert_eq!( Fingerprint( [ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, ], ).to_hex(), "0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff".to_lowercase() ) } #[test] fn display() { let hex = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"; assert_eq!( Fingerprint::from_hex_string(hex).unwrap().to_hex(), hex.to_lowercase() ) } }
0xab,
random_line_split
hash.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use digest::{Digest, FixedOutput}; use sha2::Sha256; use std::error::Error; use std::fmt; use std::io::{self, Write}; use hex; const FINGERPRINT_SIZE: usize = 32; #[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct Fingerprint(pub [u8; FINGERPRINT_SIZE]); impl Fingerprint { pub fn from_bytes_unsafe(bytes: &[u8]) -> Fingerprint { if bytes.len()!= FINGERPRINT_SIZE { panic!( "Input value was not a fingerprint; had length: {}", bytes.len() ); } let mut fingerprint = [0; FINGERPRINT_SIZE]; fingerprint.clone_from_slice(&bytes[0..FINGERPRINT_SIZE]); Fingerprint(fingerprint) } pub fn from_hex_string(hex_string: &str) -> Result<Fingerprint, String> { <[u8; FINGERPRINT_SIZE] as hex::FromHex>::from_hex(hex_string) .map(|v| Fingerprint(v)) .map_err(|e| e.description().to_string()) } pub fn as_bytes(&self) -> &[u8; FINGERPRINT_SIZE] { &self.0 } pub fn to_hex(&self) -> String { let mut s = String::new(); for &byte in self.0.iter() { fmt::Write::write_fmt(&mut s, format_args!("{:02x}", byte)).unwrap(); } s } } impl fmt::Display for Fingerprint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.to_hex()) } } impl fmt::Debug for Fingerprint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Fingerprint<{}>", self.to_hex()) } } /// /// A Write instance that fingerprints all data that passes through it. /// pub struct WriterHasher<W: Write> { hasher: Sha256, inner: W, } impl<W: Write> WriterHasher<W> { pub fn new(inner: W) -> WriterHasher<W> { WriterHasher { hasher: Sha256::default(), inner: inner, } } /// /// Returns the result of fingerprinting this stream, and Drops the stream. /// pub fn finish(self) -> Fingerprint { Fingerprint::from_bytes_unsafe(&self.hasher.fixed_result()) } } impl<W: Write> Write for WriterHasher<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let written = self.inner.write(buf)?; // Hash the bytes that were successfully written. self.hasher.input(&buf[0..written]); Ok(written) } fn flush(&mut self) -> io::Result<()> { self.inner.flush() } } #[cfg(test)] mod fingerprint_tests { use super::Fingerprint; #[test] fn
() { assert_eq!( Fingerprint::from_bytes_unsafe(&vec![ 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, ]), Fingerprint([0xab; 32]) ); } #[test] fn from_hex_string() { assert_eq!( Fingerprint::from_hex_string( "0123456789abcdefFEDCBA98765432100000000000000000ffFFfFfFFfFfFFff", ).unwrap(), Fingerprint( [ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, ], ) ) } #[test] fn from_hex_string_not_long_enough() { Fingerprint::from_hex_string("abcd").expect_err("Want err"); } #[test] fn from_hex_string_too_long() { Fingerprint::from_hex_string( "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0", ).expect_err("Want err"); } #[test] fn from_hex_string_invalid_chars() { Fingerprint::from_hex_string( "Q123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF", ).expect_err("Want err"); } #[test] fn to_hex() { assert_eq!( Fingerprint( [ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, ], ).to_hex(), "0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff".to_lowercase() ) } #[test] fn display() { let hex = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"; assert_eq!( Fingerprint::from_hex_string(hex).unwrap().to_hex(), hex.to_lowercase() ) } }
from_bytes_unsafe
identifier_name
hash.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use digest::{Digest, FixedOutput}; use sha2::Sha256; use std::error::Error; use std::fmt; use std::io::{self, Write}; use hex; const FINGERPRINT_SIZE: usize = 32; #[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct Fingerprint(pub [u8; FINGERPRINT_SIZE]); impl Fingerprint { pub fn from_bytes_unsafe(bytes: &[u8]) -> Fingerprint { if bytes.len()!= FINGERPRINT_SIZE
let mut fingerprint = [0; FINGERPRINT_SIZE]; fingerprint.clone_from_slice(&bytes[0..FINGERPRINT_SIZE]); Fingerprint(fingerprint) } pub fn from_hex_string(hex_string: &str) -> Result<Fingerprint, String> { <[u8; FINGERPRINT_SIZE] as hex::FromHex>::from_hex(hex_string) .map(|v| Fingerprint(v)) .map_err(|e| e.description().to_string()) } pub fn as_bytes(&self) -> &[u8; FINGERPRINT_SIZE] { &self.0 } pub fn to_hex(&self) -> String { let mut s = String::new(); for &byte in self.0.iter() { fmt::Write::write_fmt(&mut s, format_args!("{:02x}", byte)).unwrap(); } s } } impl fmt::Display for Fingerprint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.to_hex()) } } impl fmt::Debug for Fingerprint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Fingerprint<{}>", self.to_hex()) } } /// /// A Write instance that fingerprints all data that passes through it. /// pub struct WriterHasher<W: Write> { hasher: Sha256, inner: W, } impl<W: Write> WriterHasher<W> { pub fn new(inner: W) -> WriterHasher<W> { WriterHasher { hasher: Sha256::default(), inner: inner, } } /// /// Returns the result of fingerprinting this stream, and Drops the stream. /// pub fn finish(self) -> Fingerprint { Fingerprint::from_bytes_unsafe(&self.hasher.fixed_result()) } } impl<W: Write> Write for WriterHasher<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let written = self.inner.write(buf)?; // Hash the bytes that were successfully written. self.hasher.input(&buf[0..written]); Ok(written) } fn flush(&mut self) -> io::Result<()> { self.inner.flush() } } #[cfg(test)] mod fingerprint_tests { use super::Fingerprint; #[test] fn from_bytes_unsafe() { assert_eq!( Fingerprint::from_bytes_unsafe(&vec![ 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, ]), Fingerprint([0xab; 32]) ); } #[test] fn from_hex_string() { assert_eq!( Fingerprint::from_hex_string( "0123456789abcdefFEDCBA98765432100000000000000000ffFFfFfFFfFfFFff", ).unwrap(), Fingerprint( [ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, ], ) ) } #[test] fn from_hex_string_not_long_enough() { Fingerprint::from_hex_string("abcd").expect_err("Want err"); } #[test] fn from_hex_string_too_long() { Fingerprint::from_hex_string( "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0", ).expect_err("Want err"); } #[test] fn from_hex_string_invalid_chars() { Fingerprint::from_hex_string( "Q123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF", ).expect_err("Want err"); } #[test] fn to_hex() { assert_eq!( Fingerprint( [ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, ], ).to_hex(), "0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff".to_lowercase() ) } #[test] fn display() { let hex = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"; assert_eq!( Fingerprint::from_hex_string(hex).unwrap().to_hex(), hex.to_lowercase() ) } }
{ panic!( "Input value was not a fingerprint; had length: {}", bytes.len() ); }
conditional_block
browsingcontext.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::utils::WindowProxyHandler; use dom::bindings::utils::get_array_index_from_id; use dom::document::Document; use dom::element::Element; use dom::window::Window; use js::JSCLASS_IS_GLOBAL; use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy}; use js::glue::{GetProxyPrivate, SetProxyExtra}; use js::jsapi::{Handle, JS_ForwardSetPropertyTo, ObjectOpResult, RootedObject, RootedValue}; use js::jsapi::{HandleId, HandleObject, MutableHandle, MutableHandleValue}; use js::jsapi::{JSAutoCompartment, JSAutoRequest, JS_GetClass}; use js::jsapi::{JSContext, JSErrNum, JSObject, JSPropertyDescriptor}; use js::jsapi::{JS_AlreadyHasOwnPropertyById, JS_ForwardGetPropertyTo}; use js::jsapi::{JS_DefinePropertyById6, JS_GetOwnPropertyDescriptorById}; use js::jsval::{ObjectValue, UndefinedValue, PrivateValue}; #[dom_struct] pub struct BrowsingContext { reflector: Reflector, history: DOMRefCell<Vec<SessionHistoryEntry>>, active_index: usize, frame_element: Option<JS<Element>>, } impl BrowsingContext { pub fn new_inherited(frame_element: Option<&Element>) -> BrowsingContext { BrowsingContext { reflector: Reflector::new(), history: DOMRefCell::new(vec![]), active_index: 0, frame_element: frame_element.map(JS::from_ref), } } #[allow(unsafe_code)] pub fn new(window: &Window, frame_element: Option<&Element>) -> Root<BrowsingContext> { unsafe { let WindowProxyHandler(handler) = window.windowproxy_handler(); assert!(!handler.is_null()); let cx = window.get_cx(); let _ar = JSAutoRequest::new(cx); let parent = window.reflector().get_jsobject(); assert!(!parent.get().is_null()); assert!(((*JS_GetClass(parent.get())).flags & JSCLASS_IS_GLOBAL)!= 0); let _ac = JSAutoCompartment::new(cx, parent.get()); let window_proxy = RootedObject::new(cx, NewWindowProxy(cx, parent, handler)); assert!(!window_proxy.ptr.is_null()); let object = box BrowsingContext::new_inherited(frame_element); let raw = Box::into_raw(object); SetProxyExtra(window_proxy.ptr, 0, PrivateValue(raw as *const _)); (*raw).init_reflector(window_proxy.ptr); Root::from_ref(&*raw) } } pub fn init(&self, document: &Document) { assert!(self.history.borrow().is_empty()); assert_eq!(self.active_index, 0); self.history.borrow_mut().push(SessionHistoryEntry::new(document)); } pub fn active_document(&self) -> Root<Document> { Root::from_ref(&*self.history.borrow()[self.active_index].document) } pub fn active_window(&self) -> Root<Window> { Root::from_ref(self.active_document().window()) } pub fn frame_element(&self) -> Option<&Element> { self.frame_element.r() } pub fn window_proxy(&self) -> *mut JSObject { let window_proxy = self.reflector.get_jsobject(); assert!(!window_proxy.get().is_null()); window_proxy.get() } } // This isn't a DOM struct, just a convenience struct // without a reflector, so we don't mark this as #[dom_struct] #[must_root] #[privatize] #[derive(JSTraceable, HeapSizeOf)] pub struct SessionHistoryEntry { document: JS<Document>, children: Vec<JS<BrowsingContext>>, } impl SessionHistoryEntry { fn new(document: &Document) -> SessionHistoryEntry { SessionHistoryEntry { document: JS::from_ref(document), children: vec![], } } } #[allow(unsafe_code)] unsafe fn GetSubframeWindow(cx: *mut JSContext, proxy: HandleObject, id: HandleId) -> Option<Root<Window>> { let index = get_array_index_from_id(cx, id); if let Some(index) = index { let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); let win = root_from_handleobject::<Window>(target.handle()).unwrap(); let mut found = false; return win.IndexedGetter(index, &mut found); } None } #[allow(unsafe_code)] unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext, proxy: HandleObject, id: HandleId, desc: MutableHandle<JSPropertyDescriptor>) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { let mut val = RootedValue::new(cx, UndefinedValue()); window.to_jsval(cx, val.handle_mut()); (*desc.ptr).value = val.ptr; fill_property_descriptor(&mut *desc.ptr, *proxy.ptr, true); return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); if!JS_GetOwnPropertyDescriptorById(cx, target.handle(), id, desc) { return false; } assert!(desc.get().obj.is_null() || desc.get().obj == target.ptr); if desc.get().obj == target.ptr { desc.get().obj = *proxy.ptr; } true } #[allow(unsafe_code)] unsafe extern "C" fn defineProperty(cx: *mut JSContext, proxy: HandleObject, id: HandleId, desc: Handle<JSPropertyDescriptor>, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Spec says to Reject whether this is a supported index or not, // since we have no indexed setter or indexed creator. That means // throwing in strict mode (FIXME: Bug 828137), doing nothing in // non-strict mode. (*res).code_ = JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as ::libc::uintptr_t; return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); JS_DefinePropertyById6(cx, target.handle(), id, desc, res) } #[allow(unsafe_code)] unsafe extern "C" fn hasOwn(cx: *mut JSContext, proxy: HandleObject, id: HandleId, bp: *mut bool) -> bool { let window = GetSubframeWindow(cx, proxy, id); if window.is_some() { *bp = true; return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); let mut found = false; if!JS_AlreadyHasOwnPropertyById(cx, target.handle(), id, &mut found) { return false; } *bp = found; true } #[allow(unsafe_code)] unsafe extern "C" fn get(cx: *mut JSContext, proxy: HandleObject, receiver: HandleObject, id: HandleId, vp: MutableHandleValue) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { window.to_jsval(cx, vp); return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, vp) } #[allow(unsafe_code)] unsafe extern "C" fn set(cx: *mut JSContext, proxy: HandleObject, receiver: HandleObject, id: HandleId, vp: MutableHandleValue, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Reject (which means throw if and only if strict) the set. (*res).code_ = JSErrNum::JSMSG_READ_ONLY as ::libc::uintptr_t; return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); let receiver = RootedValue::new(cx, ObjectValue(&**receiver.ptr)); JS_ForwardSetPropertyTo(cx, target.handle(), id, vp.to_handle(), receiver.handle(), res) } static PROXY_HANDLER: ProxyTraps = ProxyTraps { enter: None, getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor), defineProperty: Some(defineProperty), ownPropertyKeys: None, delete_: None, enumerate: None, preventExtensions: None, isExtensible: None, has: None, get: Some(get), set: Some(set), call: None, construct: None, getPropertyDescriptor: Some(get_property_descriptor), hasOwn: Some(hasOwn), getOwnEnumerablePropertyKeys: None, nativeCall: None, hasInstance: None, objectClassIs: None, className: None, fun_toString: None, boxedValue_unbox: None, defaultValue: None, trace: None, finalize: None, objectMoved: None, isCallable: None, isConstructor: None, }; #[allow(unsafe_code)] pub fn new_window_proxy_handler() -> WindowProxyHandler { unsafe { WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER)) } }
use dom::bindings::cell::DOMRefCell; use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject}; use dom::bindings::js::{JS, Root, RootedReference}; use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor}; use dom::bindings::reflector::{Reflectable, Reflector};
random_line_split
browsingcontext.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::cell::DOMRefCell; use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject}; use dom::bindings::js::{JS, Root, RootedReference}; use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor}; use dom::bindings::reflector::{Reflectable, Reflector}; use dom::bindings::utils::WindowProxyHandler; use dom::bindings::utils::get_array_index_from_id; use dom::document::Document; use dom::element::Element; use dom::window::Window; use js::JSCLASS_IS_GLOBAL; use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy}; use js::glue::{GetProxyPrivate, SetProxyExtra}; use js::jsapi::{Handle, JS_ForwardSetPropertyTo, ObjectOpResult, RootedObject, RootedValue}; use js::jsapi::{HandleId, HandleObject, MutableHandle, MutableHandleValue}; use js::jsapi::{JSAutoCompartment, JSAutoRequest, JS_GetClass}; use js::jsapi::{JSContext, JSErrNum, JSObject, JSPropertyDescriptor}; use js::jsapi::{JS_AlreadyHasOwnPropertyById, JS_ForwardGetPropertyTo}; use js::jsapi::{JS_DefinePropertyById6, JS_GetOwnPropertyDescriptorById}; use js::jsval::{ObjectValue, UndefinedValue, PrivateValue}; #[dom_struct] pub struct BrowsingContext { reflector: Reflector, history: DOMRefCell<Vec<SessionHistoryEntry>>, active_index: usize, frame_element: Option<JS<Element>>, } impl BrowsingContext { pub fn new_inherited(frame_element: Option<&Element>) -> BrowsingContext { BrowsingContext { reflector: Reflector::new(), history: DOMRefCell::new(vec![]), active_index: 0, frame_element: frame_element.map(JS::from_ref), } } #[allow(unsafe_code)] pub fn new(window: &Window, frame_element: Option<&Element>) -> Root<BrowsingContext> { unsafe { let WindowProxyHandler(handler) = window.windowproxy_handler(); assert!(!handler.is_null()); let cx = window.get_cx(); let _ar = JSAutoRequest::new(cx); let parent = window.reflector().get_jsobject(); assert!(!parent.get().is_null()); assert!(((*JS_GetClass(parent.get())).flags & JSCLASS_IS_GLOBAL)!= 0); let _ac = JSAutoCompartment::new(cx, parent.get()); let window_proxy = RootedObject::new(cx, NewWindowProxy(cx, parent, handler)); assert!(!window_proxy.ptr.is_null()); let object = box BrowsingContext::new_inherited(frame_element); let raw = Box::into_raw(object); SetProxyExtra(window_proxy.ptr, 0, PrivateValue(raw as *const _)); (*raw).init_reflector(window_proxy.ptr); Root::from_ref(&*raw) } } pub fn init(&self, document: &Document) { assert!(self.history.borrow().is_empty()); assert_eq!(self.active_index, 0); self.history.borrow_mut().push(SessionHistoryEntry::new(document)); } pub fn active_document(&self) -> Root<Document> { Root::from_ref(&*self.history.borrow()[self.active_index].document) } pub fn active_window(&self) -> Root<Window> { Root::from_ref(self.active_document().window()) } pub fn frame_element(&self) -> Option<&Element> { self.frame_element.r() } pub fn window_proxy(&self) -> *mut JSObject { let window_proxy = self.reflector.get_jsobject(); assert!(!window_proxy.get().is_null()); window_proxy.get() } } // This isn't a DOM struct, just a convenience struct // without a reflector, so we don't mark this as #[dom_struct] #[must_root] #[privatize] #[derive(JSTraceable, HeapSizeOf)] pub struct SessionHistoryEntry { document: JS<Document>, children: Vec<JS<BrowsingContext>>, } impl SessionHistoryEntry { fn
(document: &Document) -> SessionHistoryEntry { SessionHistoryEntry { document: JS::from_ref(document), children: vec![], } } } #[allow(unsafe_code)] unsafe fn GetSubframeWindow(cx: *mut JSContext, proxy: HandleObject, id: HandleId) -> Option<Root<Window>> { let index = get_array_index_from_id(cx, id); if let Some(index) = index { let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); let win = root_from_handleobject::<Window>(target.handle()).unwrap(); let mut found = false; return win.IndexedGetter(index, &mut found); } None } #[allow(unsafe_code)] unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext, proxy: HandleObject, id: HandleId, desc: MutableHandle<JSPropertyDescriptor>) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { let mut val = RootedValue::new(cx, UndefinedValue()); window.to_jsval(cx, val.handle_mut()); (*desc.ptr).value = val.ptr; fill_property_descriptor(&mut *desc.ptr, *proxy.ptr, true); return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); if!JS_GetOwnPropertyDescriptorById(cx, target.handle(), id, desc) { return false; } assert!(desc.get().obj.is_null() || desc.get().obj == target.ptr); if desc.get().obj == target.ptr { desc.get().obj = *proxy.ptr; } true } #[allow(unsafe_code)] unsafe extern "C" fn defineProperty(cx: *mut JSContext, proxy: HandleObject, id: HandleId, desc: Handle<JSPropertyDescriptor>, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Spec says to Reject whether this is a supported index or not, // since we have no indexed setter or indexed creator. That means // throwing in strict mode (FIXME: Bug 828137), doing nothing in // non-strict mode. (*res).code_ = JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as ::libc::uintptr_t; return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); JS_DefinePropertyById6(cx, target.handle(), id, desc, res) } #[allow(unsafe_code)] unsafe extern "C" fn hasOwn(cx: *mut JSContext, proxy: HandleObject, id: HandleId, bp: *mut bool) -> bool { let window = GetSubframeWindow(cx, proxy, id); if window.is_some() { *bp = true; return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); let mut found = false; if!JS_AlreadyHasOwnPropertyById(cx, target.handle(), id, &mut found) { return false; } *bp = found; true } #[allow(unsafe_code)] unsafe extern "C" fn get(cx: *mut JSContext, proxy: HandleObject, receiver: HandleObject, id: HandleId, vp: MutableHandleValue) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { window.to_jsval(cx, vp); return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, vp) } #[allow(unsafe_code)] unsafe extern "C" fn set(cx: *mut JSContext, proxy: HandleObject, receiver: HandleObject, id: HandleId, vp: MutableHandleValue, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Reject (which means throw if and only if strict) the set. (*res).code_ = JSErrNum::JSMSG_READ_ONLY as ::libc::uintptr_t; return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); let receiver = RootedValue::new(cx, ObjectValue(&**receiver.ptr)); JS_ForwardSetPropertyTo(cx, target.handle(), id, vp.to_handle(), receiver.handle(), res) } static PROXY_HANDLER: ProxyTraps = ProxyTraps { enter: None, getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor), defineProperty: Some(defineProperty), ownPropertyKeys: None, delete_: None, enumerate: None, preventExtensions: None, isExtensible: None, has: None, get: Some(get), set: Some(set), call: None, construct: None, getPropertyDescriptor: Some(get_property_descriptor), hasOwn: Some(hasOwn), getOwnEnumerablePropertyKeys: None, nativeCall: None, hasInstance: None, objectClassIs: None, className: None, fun_toString: None, boxedValue_unbox: None, defaultValue: None, trace: None, finalize: None, objectMoved: None, isCallable: None, isConstructor: None, }; #[allow(unsafe_code)] pub fn new_window_proxy_handler() -> WindowProxyHandler { unsafe { WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER)) } }
new
identifier_name
browsingcontext.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::cell::DOMRefCell; use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject}; use dom::bindings::js::{JS, Root, RootedReference}; use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor}; use dom::bindings::reflector::{Reflectable, Reflector}; use dom::bindings::utils::WindowProxyHandler; use dom::bindings::utils::get_array_index_from_id; use dom::document::Document; use dom::element::Element; use dom::window::Window; use js::JSCLASS_IS_GLOBAL; use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy}; use js::glue::{GetProxyPrivate, SetProxyExtra}; use js::jsapi::{Handle, JS_ForwardSetPropertyTo, ObjectOpResult, RootedObject, RootedValue}; use js::jsapi::{HandleId, HandleObject, MutableHandle, MutableHandleValue}; use js::jsapi::{JSAutoCompartment, JSAutoRequest, JS_GetClass}; use js::jsapi::{JSContext, JSErrNum, JSObject, JSPropertyDescriptor}; use js::jsapi::{JS_AlreadyHasOwnPropertyById, JS_ForwardGetPropertyTo}; use js::jsapi::{JS_DefinePropertyById6, JS_GetOwnPropertyDescriptorById}; use js::jsval::{ObjectValue, UndefinedValue, PrivateValue}; #[dom_struct] pub struct BrowsingContext { reflector: Reflector, history: DOMRefCell<Vec<SessionHistoryEntry>>, active_index: usize, frame_element: Option<JS<Element>>, } impl BrowsingContext { pub fn new_inherited(frame_element: Option<&Element>) -> BrowsingContext { BrowsingContext { reflector: Reflector::new(), history: DOMRefCell::new(vec![]), active_index: 0, frame_element: frame_element.map(JS::from_ref), } } #[allow(unsafe_code)] pub fn new(window: &Window, frame_element: Option<&Element>) -> Root<BrowsingContext> { unsafe { let WindowProxyHandler(handler) = window.windowproxy_handler(); assert!(!handler.is_null()); let cx = window.get_cx(); let _ar = JSAutoRequest::new(cx); let parent = window.reflector().get_jsobject(); assert!(!parent.get().is_null()); assert!(((*JS_GetClass(parent.get())).flags & JSCLASS_IS_GLOBAL)!= 0); let _ac = JSAutoCompartment::new(cx, parent.get()); let window_proxy = RootedObject::new(cx, NewWindowProxy(cx, parent, handler)); assert!(!window_proxy.ptr.is_null()); let object = box BrowsingContext::new_inherited(frame_element); let raw = Box::into_raw(object); SetProxyExtra(window_proxy.ptr, 0, PrivateValue(raw as *const _)); (*raw).init_reflector(window_proxy.ptr); Root::from_ref(&*raw) } } pub fn init(&self, document: &Document) { assert!(self.history.borrow().is_empty()); assert_eq!(self.active_index, 0); self.history.borrow_mut().push(SessionHistoryEntry::new(document)); } pub fn active_document(&self) -> Root<Document> { Root::from_ref(&*self.history.borrow()[self.active_index].document) } pub fn active_window(&self) -> Root<Window>
pub fn frame_element(&self) -> Option<&Element> { self.frame_element.r() } pub fn window_proxy(&self) -> *mut JSObject { let window_proxy = self.reflector.get_jsobject(); assert!(!window_proxy.get().is_null()); window_proxy.get() } } // This isn't a DOM struct, just a convenience struct // without a reflector, so we don't mark this as #[dom_struct] #[must_root] #[privatize] #[derive(JSTraceable, HeapSizeOf)] pub struct SessionHistoryEntry { document: JS<Document>, children: Vec<JS<BrowsingContext>>, } impl SessionHistoryEntry { fn new(document: &Document) -> SessionHistoryEntry { SessionHistoryEntry { document: JS::from_ref(document), children: vec![], } } } #[allow(unsafe_code)] unsafe fn GetSubframeWindow(cx: *mut JSContext, proxy: HandleObject, id: HandleId) -> Option<Root<Window>> { let index = get_array_index_from_id(cx, id); if let Some(index) = index { let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); let win = root_from_handleobject::<Window>(target.handle()).unwrap(); let mut found = false; return win.IndexedGetter(index, &mut found); } None } #[allow(unsafe_code)] unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext, proxy: HandleObject, id: HandleId, desc: MutableHandle<JSPropertyDescriptor>) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { let mut val = RootedValue::new(cx, UndefinedValue()); window.to_jsval(cx, val.handle_mut()); (*desc.ptr).value = val.ptr; fill_property_descriptor(&mut *desc.ptr, *proxy.ptr, true); return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); if!JS_GetOwnPropertyDescriptorById(cx, target.handle(), id, desc) { return false; } assert!(desc.get().obj.is_null() || desc.get().obj == target.ptr); if desc.get().obj == target.ptr { desc.get().obj = *proxy.ptr; } true } #[allow(unsafe_code)] unsafe extern "C" fn defineProperty(cx: *mut JSContext, proxy: HandleObject, id: HandleId, desc: Handle<JSPropertyDescriptor>, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Spec says to Reject whether this is a supported index or not, // since we have no indexed setter or indexed creator. That means // throwing in strict mode (FIXME: Bug 828137), doing nothing in // non-strict mode. (*res).code_ = JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as ::libc::uintptr_t; return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); JS_DefinePropertyById6(cx, target.handle(), id, desc, res) } #[allow(unsafe_code)] unsafe extern "C" fn hasOwn(cx: *mut JSContext, proxy: HandleObject, id: HandleId, bp: *mut bool) -> bool { let window = GetSubframeWindow(cx, proxy, id); if window.is_some() { *bp = true; return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); let mut found = false; if!JS_AlreadyHasOwnPropertyById(cx, target.handle(), id, &mut found) { return false; } *bp = found; true } #[allow(unsafe_code)] unsafe extern "C" fn get(cx: *mut JSContext, proxy: HandleObject, receiver: HandleObject, id: HandleId, vp: MutableHandleValue) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { window.to_jsval(cx, vp); return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, vp) } #[allow(unsafe_code)] unsafe extern "C" fn set(cx: *mut JSContext, proxy: HandleObject, receiver: HandleObject, id: HandleId, vp: MutableHandleValue, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Reject (which means throw if and only if strict) the set. (*res).code_ = JSErrNum::JSMSG_READ_ONLY as ::libc::uintptr_t; return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); let receiver = RootedValue::new(cx, ObjectValue(&**receiver.ptr)); JS_ForwardSetPropertyTo(cx, target.handle(), id, vp.to_handle(), receiver.handle(), res) } static PROXY_HANDLER: ProxyTraps = ProxyTraps { enter: None, getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor), defineProperty: Some(defineProperty), ownPropertyKeys: None, delete_: None, enumerate: None, preventExtensions: None, isExtensible: None, has: None, get: Some(get), set: Some(set), call: None, construct: None, getPropertyDescriptor: Some(get_property_descriptor), hasOwn: Some(hasOwn), getOwnEnumerablePropertyKeys: None, nativeCall: None, hasInstance: None, objectClassIs: None, className: None, fun_toString: None, boxedValue_unbox: None, defaultValue: None, trace: None, finalize: None, objectMoved: None, isCallable: None, isConstructor: None, }; #[allow(unsafe_code)] pub fn new_window_proxy_handler() -> WindowProxyHandler { unsafe { WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER)) } }
{ Root::from_ref(self.active_document().window()) }
identifier_body
browsingcontext.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::cell::DOMRefCell; use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject}; use dom::bindings::js::{JS, Root, RootedReference}; use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor}; use dom::bindings::reflector::{Reflectable, Reflector}; use dom::bindings::utils::WindowProxyHandler; use dom::bindings::utils::get_array_index_from_id; use dom::document::Document; use dom::element::Element; use dom::window::Window; use js::JSCLASS_IS_GLOBAL; use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy}; use js::glue::{GetProxyPrivate, SetProxyExtra}; use js::jsapi::{Handle, JS_ForwardSetPropertyTo, ObjectOpResult, RootedObject, RootedValue}; use js::jsapi::{HandleId, HandleObject, MutableHandle, MutableHandleValue}; use js::jsapi::{JSAutoCompartment, JSAutoRequest, JS_GetClass}; use js::jsapi::{JSContext, JSErrNum, JSObject, JSPropertyDescriptor}; use js::jsapi::{JS_AlreadyHasOwnPropertyById, JS_ForwardGetPropertyTo}; use js::jsapi::{JS_DefinePropertyById6, JS_GetOwnPropertyDescriptorById}; use js::jsval::{ObjectValue, UndefinedValue, PrivateValue}; #[dom_struct] pub struct BrowsingContext { reflector: Reflector, history: DOMRefCell<Vec<SessionHistoryEntry>>, active_index: usize, frame_element: Option<JS<Element>>, } impl BrowsingContext { pub fn new_inherited(frame_element: Option<&Element>) -> BrowsingContext { BrowsingContext { reflector: Reflector::new(), history: DOMRefCell::new(vec![]), active_index: 0, frame_element: frame_element.map(JS::from_ref), } } #[allow(unsafe_code)] pub fn new(window: &Window, frame_element: Option<&Element>) -> Root<BrowsingContext> { unsafe { let WindowProxyHandler(handler) = window.windowproxy_handler(); assert!(!handler.is_null()); let cx = window.get_cx(); let _ar = JSAutoRequest::new(cx); let parent = window.reflector().get_jsobject(); assert!(!parent.get().is_null()); assert!(((*JS_GetClass(parent.get())).flags & JSCLASS_IS_GLOBAL)!= 0); let _ac = JSAutoCompartment::new(cx, parent.get()); let window_proxy = RootedObject::new(cx, NewWindowProxy(cx, parent, handler)); assert!(!window_proxy.ptr.is_null()); let object = box BrowsingContext::new_inherited(frame_element); let raw = Box::into_raw(object); SetProxyExtra(window_proxy.ptr, 0, PrivateValue(raw as *const _)); (*raw).init_reflector(window_proxy.ptr); Root::from_ref(&*raw) } } pub fn init(&self, document: &Document) { assert!(self.history.borrow().is_empty()); assert_eq!(self.active_index, 0); self.history.borrow_mut().push(SessionHistoryEntry::new(document)); } pub fn active_document(&self) -> Root<Document> { Root::from_ref(&*self.history.borrow()[self.active_index].document) } pub fn active_window(&self) -> Root<Window> { Root::from_ref(self.active_document().window()) } pub fn frame_element(&self) -> Option<&Element> { self.frame_element.r() } pub fn window_proxy(&self) -> *mut JSObject { let window_proxy = self.reflector.get_jsobject(); assert!(!window_proxy.get().is_null()); window_proxy.get() } } // This isn't a DOM struct, just a convenience struct // without a reflector, so we don't mark this as #[dom_struct] #[must_root] #[privatize] #[derive(JSTraceable, HeapSizeOf)] pub struct SessionHistoryEntry { document: JS<Document>, children: Vec<JS<BrowsingContext>>, } impl SessionHistoryEntry { fn new(document: &Document) -> SessionHistoryEntry { SessionHistoryEntry { document: JS::from_ref(document), children: vec![], } } } #[allow(unsafe_code)] unsafe fn GetSubframeWindow(cx: *mut JSContext, proxy: HandleObject, id: HandleId) -> Option<Root<Window>> { let index = get_array_index_from_id(cx, id); if let Some(index) = index { let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); let win = root_from_handleobject::<Window>(target.handle()).unwrap(); let mut found = false; return win.IndexedGetter(index, &mut found); } None } #[allow(unsafe_code)] unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext, proxy: HandleObject, id: HandleId, desc: MutableHandle<JSPropertyDescriptor>) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { let mut val = RootedValue::new(cx, UndefinedValue()); window.to_jsval(cx, val.handle_mut()); (*desc.ptr).value = val.ptr; fill_property_descriptor(&mut *desc.ptr, *proxy.ptr, true); return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); if!JS_GetOwnPropertyDescriptorById(cx, target.handle(), id, desc) { return false; } assert!(desc.get().obj.is_null() || desc.get().obj == target.ptr); if desc.get().obj == target.ptr { desc.get().obj = *proxy.ptr; } true } #[allow(unsafe_code)] unsafe extern "C" fn defineProperty(cx: *mut JSContext, proxy: HandleObject, id: HandleId, desc: Handle<JSPropertyDescriptor>, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Spec says to Reject whether this is a supported index or not, // since we have no indexed setter or indexed creator. That means // throwing in strict mode (FIXME: Bug 828137), doing nothing in // non-strict mode. (*res).code_ = JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as ::libc::uintptr_t; return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); JS_DefinePropertyById6(cx, target.handle(), id, desc, res) } #[allow(unsafe_code)] unsafe extern "C" fn hasOwn(cx: *mut JSContext, proxy: HandleObject, id: HandleId, bp: *mut bool) -> bool { let window = GetSubframeWindow(cx, proxy, id); if window.is_some() { *bp = true; return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); let mut found = false; if!JS_AlreadyHasOwnPropertyById(cx, target.handle(), id, &mut found)
*bp = found; true } #[allow(unsafe_code)] unsafe extern "C" fn get(cx: *mut JSContext, proxy: HandleObject, receiver: HandleObject, id: HandleId, vp: MutableHandleValue) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { window.to_jsval(cx, vp); return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, vp) } #[allow(unsafe_code)] unsafe extern "C" fn set(cx: *mut JSContext, proxy: HandleObject, receiver: HandleObject, id: HandleId, vp: MutableHandleValue, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Reject (which means throw if and only if strict) the set. (*res).code_ = JSErrNum::JSMSG_READ_ONLY as ::libc::uintptr_t; return true; } let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); let receiver = RootedValue::new(cx, ObjectValue(&**receiver.ptr)); JS_ForwardSetPropertyTo(cx, target.handle(), id, vp.to_handle(), receiver.handle(), res) } static PROXY_HANDLER: ProxyTraps = ProxyTraps { enter: None, getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor), defineProperty: Some(defineProperty), ownPropertyKeys: None, delete_: None, enumerate: None, preventExtensions: None, isExtensible: None, has: None, get: Some(get), set: Some(set), call: None, construct: None, getPropertyDescriptor: Some(get_property_descriptor), hasOwn: Some(hasOwn), getOwnEnumerablePropertyKeys: None, nativeCall: None, hasInstance: None, objectClassIs: None, className: None, fun_toString: None, boxedValue_unbox: None, defaultValue: None, trace: None, finalize: None, objectMoved: None, isCallable: None, isConstructor: None, }; #[allow(unsafe_code)] pub fn new_window_proxy_handler() -> WindowProxyHandler { unsafe { WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER)) } }
{ return false; }
conditional_block
hextobase64.rs
extern crate matasano; use self::matasano::common::{base64, err}; fn test_hex_to_base64(input: &str, output: &str) { let r: Result<String, err::Error> = base64::hex_to_base64(input); let base64 = match r { Ok(v) => v, Err(e) => { println!("{}", e); String::from("N.A.") } }; assert_eq!(base64, output); } #[test] fn test_cryptopals_case()
#[test] fn test_more() { test_hex_to_base64("00", "AA=="); test_hex_to_base64("00FF", "AP8="); test_hex_to_base64("00FFed", "AP/t"); test_hex_to_base64("00F3ed45", "APPtRQ=="); test_hex_to_base64("00F3ed455727efd982a8b340", "APPtRVcn79mCqLNA"); test_hex_to_base64("", ""); }
{ let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"; let output = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"; test_hex_to_base64(input, output); }
identifier_body
hextobase64.rs
extern crate matasano; use self::matasano::common::{base64, err}; fn test_hex_to_base64(input: &str, output: &str) { let r: Result<String, err::Error> = base64::hex_to_base64(input); let base64 = match r { Ok(v) => v, Err(e) => { println!("{}", e); String::from("N.A.") } }; assert_eq!(base64, output); } #[test] fn
() { let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"; let output = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"; test_hex_to_base64(input, output); } #[test] fn test_more() { test_hex_to_base64("00", "AA=="); test_hex_to_base64("00FF", "AP8="); test_hex_to_base64("00FFed", "AP/t"); test_hex_to_base64("00F3ed45", "APPtRQ=="); test_hex_to_base64("00F3ed455727efd982a8b340", "APPtRVcn79mCqLNA"); test_hex_to_base64("", ""); }
test_cryptopals_case
identifier_name
hextobase64.rs
extern crate matasano; use self::matasano::common::{base64, err}; fn test_hex_to_base64(input: &str, output: &str) { let r: Result<String, err::Error> = base64::hex_to_base64(input); let base64 = match r { Ok(v) => v, Err(e) => { println!("{}", e); String::from("N.A.") } };
#[test] fn test_cryptopals_case() { let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"; let output = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"; test_hex_to_base64(input, output); } #[test] fn test_more() { test_hex_to_base64("00", "AA=="); test_hex_to_base64("00FF", "AP8="); test_hex_to_base64("00FFed", "AP/t"); test_hex_to_base64("00F3ed45", "APPtRQ=="); test_hex_to_base64("00F3ed455727efd982a8b340", "APPtRVcn79mCqLNA"); test_hex_to_base64("", ""); }
assert_eq!(base64, output); }
random_line_split
mod.rs
use crate::flowgger::config::Config; use openssl::bn::BigNum; use openssl::dh::Dh; use openssl::ssl::*; use std::path::{Path, PathBuf}; pub mod tls_input; #[cfg(feature = "coroutines")] pub mod tlsco_input; pub use super::Input; const DEFAULT_CERT: &str = "flowgger.pem"; const DEFAULT_CIPHERS: &str = "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:\ ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:\ ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:\ ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:\ ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:\ AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:\ ECDHE-RSA-DES-CBC3-SHA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:\ !EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"; const DEFAULT_COMPRESSION: bool = false; const DEFAULT_FRAMING: &str = "line"; const DEFAULT_KEY: &str = "flowgger.pem"; const DEFAULT_LISTEN: &str = "0.0.0.0:6514"; #[cfg(feature = "coroutines")] const DEFAULT_THREADS: usize = 1; const DEFAULT_TIMEOUT: u64 = 3600; const DEFAULT_TLS_COMPATIBILITY_LEVEL: &str = "default"; const DEFAULT_VERIFY_PEER: bool = false; const TLS_VERIFY_DEPTH: u32 = 6; #[derive(Clone)] pub struct TlsConfig { framing: String, threads: usize, acceptor: SslAcceptor, } fn set_fs(ctx: &mut SslContextBuilder) { let p = BigNum::from_hex_str("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597").unwrap(); let g = BigNum::from_hex_str("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659").unwrap(); let q = BigNum::from_hex_str("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F5FBD3") .unwrap(); let dh = Dh::from_params(p, g, q).unwrap(); ctx.set_tmp_dh(&dh).unwrap(); } #[cfg(feature = "coroutines")] fn get_default_threads(config: &Config) -> usize { config .lookup("input.tls_threads") .map_or(DEFAULT_THREADS, |x| { x.as_integer() .expect("input.tls_threads must be an unsigned integer") as usize }) } #[cfg(not(feature = "coroutines"))] fn get_default_threads(_config: &Config) -> usize { 1 } pub fn config_parse(config: &Config) -> (TlsConfig, String, u64)
}) .to_owned(); let ciphers = config .lookup("input.tls_ciphers") .map_or(DEFAULT_CIPHERS, |x| { x.as_str() .expect("input.tls_ciphers must be a string with a cipher suite") }) .to_owned(); let tls_modern = match config .lookup("input.tls_compatibility_level") .map_or(DEFAULT_TLS_COMPATIBILITY_LEVEL, |x| { x.as_str().expect( "input.tls_compatibility_level must be a string with the comptibility level", ) }) .to_lowercase() .as_ref() { "default" | "any" | "intermediate" => false, "modern" => true, _ => panic!(r#"TLS compatibility level must be "intermediate" or "modern""#), }; let verify_peer = config .lookup("input.tls_verify_peer") .map_or(DEFAULT_VERIFY_PEER, |x| { x.as_bool() .expect("input.tls_verify_peer must be a boolean") }); let ca_file: Option<PathBuf> = config.lookup("input.tls_ca_file").and_then(|x| { Some(PathBuf::from( x.as_str() .expect("input.tls_ca_file must be a path to a file"), )) }); let compression = config .lookup("input.tls_compression") .map_or(DEFAULT_COMPRESSION, |x| { x.as_bool() .expect("input.tls_compression must be a boolean") }); let timeout = config.lookup("input.timeout").map_or(DEFAULT_TIMEOUT, |x| { x.as_integer().expect("input.timeout must be an integer") as u64 }); let framing = if config.lookup("input.framed").map_or(false, |x| { x.as_bool().expect("input.framed must be a boolean") }) { "syslen" } else { DEFAULT_FRAMING }; let framing = config .lookup("input.framing") .map_or(framing, |x| { x.as_str() .expect(r#"input.framing must be a string set to "line", "nul" or "syslen""#) }) .to_owned(); let mut acceptor_builder = (if tls_modern { SslAcceptor::mozilla_modern(SslMethod::tls()) } else { SslAcceptor::mozilla_intermediate(SslMethod::tls()) }) .unwrap(); { let mut ctx = &mut acceptor_builder; if let Some(ca_file) = ca_file { ctx.set_ca_file(&ca_file) .expect("Unable to read the trusted CA file"); } if!verify_peer { ctx.set_verify(SslVerifyMode::NONE); } else { ctx.set_verify_depth(TLS_VERIFY_DEPTH); ctx.set_verify(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT); } let mut opts = SslOptions::CIPHER_SERVER_PREFERENCE | SslOptions::NO_SESSION_RESUMPTION_ON_RENEGOTIATION; if!compression { opts |= SslOptions::NO_COMPRESSION; } ctx.set_options(opts); set_fs(&mut ctx); ctx.set_certificate_chain_file(&Path::new(&cert)) .expect("Unable to read the TLS certificate chain"); ctx.set_private_key_file(&Path::new(&key), SslFiletype::PEM) .expect("Unable to read the TLS key"); ctx.set_cipher_list(&ciphers) .expect("Unsupported cipher suite"); } let acceptor = acceptor_builder.build(); let tls_config = TlsConfig { framing, threads, acceptor, }; (tls_config, listen, timeout) }
{ let listen = config .lookup("input.listen") .map_or(DEFAULT_LISTEN, |x| { x.as_str().expect("input.listen must be an ip:port string") }) .to_owned(); let threads = get_default_threads(config); let cert = config .lookup("input.tls_cert") .map_or(DEFAULT_CERT, |x| { x.as_str() .expect("input.tls_cert must be a path to a .pem file") }) .to_owned(); let key = config .lookup("input.tls_key") .map_or(DEFAULT_KEY, |x| { x.as_str() .expect("input.tls_key must be a path to a .pem file")
identifier_body
mod.rs
use crate::flowgger::config::Config; use openssl::bn::BigNum; use openssl::dh::Dh; use openssl::ssl::*; use std::path::{Path, PathBuf}; pub mod tls_input; #[cfg(feature = "coroutines")] pub mod tlsco_input; pub use super::Input; const DEFAULT_CERT: &str = "flowgger.pem"; const DEFAULT_CIPHERS: &str = "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:\ ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:\ ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:\ ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:\ ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:\ AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:\ ECDHE-RSA-DES-CBC3-SHA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:\
const DEFAULT_COMPRESSION: bool = false; const DEFAULT_FRAMING: &str = "line"; const DEFAULT_KEY: &str = "flowgger.pem"; const DEFAULT_LISTEN: &str = "0.0.0.0:6514"; #[cfg(feature = "coroutines")] const DEFAULT_THREADS: usize = 1; const DEFAULT_TIMEOUT: u64 = 3600; const DEFAULT_TLS_COMPATIBILITY_LEVEL: &str = "default"; const DEFAULT_VERIFY_PEER: bool = false; const TLS_VERIFY_DEPTH: u32 = 6; #[derive(Clone)] pub struct TlsConfig { framing: String, threads: usize, acceptor: SslAcceptor, } fn set_fs(ctx: &mut SslContextBuilder) { let p = BigNum::from_hex_str("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597").unwrap(); let g = BigNum::from_hex_str("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659").unwrap(); let q = BigNum::from_hex_str("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F5FBD3") .unwrap(); let dh = Dh::from_params(p, g, q).unwrap(); ctx.set_tmp_dh(&dh).unwrap(); } #[cfg(feature = "coroutines")] fn get_default_threads(config: &Config) -> usize { config .lookup("input.tls_threads") .map_or(DEFAULT_THREADS, |x| { x.as_integer() .expect("input.tls_threads must be an unsigned integer") as usize }) } #[cfg(not(feature = "coroutines"))] fn get_default_threads(_config: &Config) -> usize { 1 } pub fn config_parse(config: &Config) -> (TlsConfig, String, u64) { let listen = config .lookup("input.listen") .map_or(DEFAULT_LISTEN, |x| { x.as_str().expect("input.listen must be an ip:port string") }) .to_owned(); let threads = get_default_threads(config); let cert = config .lookup("input.tls_cert") .map_or(DEFAULT_CERT, |x| { x.as_str() .expect("input.tls_cert must be a path to a.pem file") }) .to_owned(); let key = config .lookup("input.tls_key") .map_or(DEFAULT_KEY, |x| { x.as_str() .expect("input.tls_key must be a path to a.pem file") }) .to_owned(); let ciphers = config .lookup("input.tls_ciphers") .map_or(DEFAULT_CIPHERS, |x| { x.as_str() .expect("input.tls_ciphers must be a string with a cipher suite") }) .to_owned(); let tls_modern = match config .lookup("input.tls_compatibility_level") .map_or(DEFAULT_TLS_COMPATIBILITY_LEVEL, |x| { x.as_str().expect( "input.tls_compatibility_level must be a string with the comptibility level", ) }) .to_lowercase() .as_ref() { "default" | "any" | "intermediate" => false, "modern" => true, _ => panic!(r#"TLS compatibility level must be "intermediate" or "modern""#), }; let verify_peer = config .lookup("input.tls_verify_peer") .map_or(DEFAULT_VERIFY_PEER, |x| { x.as_bool() .expect("input.tls_verify_peer must be a boolean") }); let ca_file: Option<PathBuf> = config.lookup("input.tls_ca_file").and_then(|x| { Some(PathBuf::from( x.as_str() .expect("input.tls_ca_file must be a path to a file"), )) }); let compression = config .lookup("input.tls_compression") .map_or(DEFAULT_COMPRESSION, |x| { x.as_bool() .expect("input.tls_compression must be a boolean") }); let timeout = config.lookup("input.timeout").map_or(DEFAULT_TIMEOUT, |x| { x.as_integer().expect("input.timeout must be an integer") as u64 }); let framing = if config.lookup("input.framed").map_or(false, |x| { x.as_bool().expect("input.framed must be a boolean") }) { "syslen" } else { DEFAULT_FRAMING }; let framing = config .lookup("input.framing") .map_or(framing, |x| { x.as_str() .expect(r#"input.framing must be a string set to "line", "nul" or "syslen""#) }) .to_owned(); let mut acceptor_builder = (if tls_modern { SslAcceptor::mozilla_modern(SslMethod::tls()) } else { SslAcceptor::mozilla_intermediate(SslMethod::tls()) }) .unwrap(); { let mut ctx = &mut acceptor_builder; if let Some(ca_file) = ca_file { ctx.set_ca_file(&ca_file) .expect("Unable to read the trusted CA file"); } if!verify_peer { ctx.set_verify(SslVerifyMode::NONE); } else { ctx.set_verify_depth(TLS_VERIFY_DEPTH); ctx.set_verify(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT); } let mut opts = SslOptions::CIPHER_SERVER_PREFERENCE | SslOptions::NO_SESSION_RESUMPTION_ON_RENEGOTIATION; if!compression { opts |= SslOptions::NO_COMPRESSION; } ctx.set_options(opts); set_fs(&mut ctx); ctx.set_certificate_chain_file(&Path::new(&cert)) .expect("Unable to read the TLS certificate chain"); ctx.set_private_key_file(&Path::new(&key), SslFiletype::PEM) .expect("Unable to read the TLS key"); ctx.set_cipher_list(&ciphers) .expect("Unsupported cipher suite"); } let acceptor = acceptor_builder.build(); let tls_config = TlsConfig { framing, threads, acceptor, }; (tls_config, listen, timeout) }
!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA";
random_line_split
mod.rs
use crate::flowgger::config::Config; use openssl::bn::BigNum; use openssl::dh::Dh; use openssl::ssl::*; use std::path::{Path, PathBuf}; pub mod tls_input; #[cfg(feature = "coroutines")] pub mod tlsco_input; pub use super::Input; const DEFAULT_CERT: &str = "flowgger.pem"; const DEFAULT_CIPHERS: &str = "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:\ ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:\ ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:\ ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:\ ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:\ AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:\ ECDHE-RSA-DES-CBC3-SHA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:\ !EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"; const DEFAULT_COMPRESSION: bool = false; const DEFAULT_FRAMING: &str = "line"; const DEFAULT_KEY: &str = "flowgger.pem"; const DEFAULT_LISTEN: &str = "0.0.0.0:6514"; #[cfg(feature = "coroutines")] const DEFAULT_THREADS: usize = 1; const DEFAULT_TIMEOUT: u64 = 3600; const DEFAULT_TLS_COMPATIBILITY_LEVEL: &str = "default"; const DEFAULT_VERIFY_PEER: bool = false; const TLS_VERIFY_DEPTH: u32 = 6; #[derive(Clone)] pub struct
{ framing: String, threads: usize, acceptor: SslAcceptor, } fn set_fs(ctx: &mut SslContextBuilder) { let p = BigNum::from_hex_str("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597").unwrap(); let g = BigNum::from_hex_str("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659").unwrap(); let q = BigNum::from_hex_str("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F5FBD3") .unwrap(); let dh = Dh::from_params(p, g, q).unwrap(); ctx.set_tmp_dh(&dh).unwrap(); } #[cfg(feature = "coroutines")] fn get_default_threads(config: &Config) -> usize { config .lookup("input.tls_threads") .map_or(DEFAULT_THREADS, |x| { x.as_integer() .expect("input.tls_threads must be an unsigned integer") as usize }) } #[cfg(not(feature = "coroutines"))] fn get_default_threads(_config: &Config) -> usize { 1 } pub fn config_parse(config: &Config) -> (TlsConfig, String, u64) { let listen = config .lookup("input.listen") .map_or(DEFAULT_LISTEN, |x| { x.as_str().expect("input.listen must be an ip:port string") }) .to_owned(); let threads = get_default_threads(config); let cert = config .lookup("input.tls_cert") .map_or(DEFAULT_CERT, |x| { x.as_str() .expect("input.tls_cert must be a path to a.pem file") }) .to_owned(); let key = config .lookup("input.tls_key") .map_or(DEFAULT_KEY, |x| { x.as_str() .expect("input.tls_key must be a path to a.pem file") }) .to_owned(); let ciphers = config .lookup("input.tls_ciphers") .map_or(DEFAULT_CIPHERS, |x| { x.as_str() .expect("input.tls_ciphers must be a string with a cipher suite") }) .to_owned(); let tls_modern = match config .lookup("input.tls_compatibility_level") .map_or(DEFAULT_TLS_COMPATIBILITY_LEVEL, |x| { x.as_str().expect( "input.tls_compatibility_level must be a string with the comptibility level", ) }) .to_lowercase() .as_ref() { "default" | "any" | "intermediate" => false, "modern" => true, _ => panic!(r#"TLS compatibility level must be "intermediate" or "modern""#), }; let verify_peer = config .lookup("input.tls_verify_peer") .map_or(DEFAULT_VERIFY_PEER, |x| { x.as_bool() .expect("input.tls_verify_peer must be a boolean") }); let ca_file: Option<PathBuf> = config.lookup("input.tls_ca_file").and_then(|x| { Some(PathBuf::from( x.as_str() .expect("input.tls_ca_file must be a path to a file"), )) }); let compression = config .lookup("input.tls_compression") .map_or(DEFAULT_COMPRESSION, |x| { x.as_bool() .expect("input.tls_compression must be a boolean") }); let timeout = config.lookup("input.timeout").map_or(DEFAULT_TIMEOUT, |x| { x.as_integer().expect("input.timeout must be an integer") as u64 }); let framing = if config.lookup("input.framed").map_or(false, |x| { x.as_bool().expect("input.framed must be a boolean") }) { "syslen" } else { DEFAULT_FRAMING }; let framing = config .lookup("input.framing") .map_or(framing, |x| { x.as_str() .expect(r#"input.framing must be a string set to "line", "nul" or "syslen""#) }) .to_owned(); let mut acceptor_builder = (if tls_modern { SslAcceptor::mozilla_modern(SslMethod::tls()) } else { SslAcceptor::mozilla_intermediate(SslMethod::tls()) }) .unwrap(); { let mut ctx = &mut acceptor_builder; if let Some(ca_file) = ca_file { ctx.set_ca_file(&ca_file) .expect("Unable to read the trusted CA file"); } if!verify_peer { ctx.set_verify(SslVerifyMode::NONE); } else { ctx.set_verify_depth(TLS_VERIFY_DEPTH); ctx.set_verify(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT); } let mut opts = SslOptions::CIPHER_SERVER_PREFERENCE | SslOptions::NO_SESSION_RESUMPTION_ON_RENEGOTIATION; if!compression { opts |= SslOptions::NO_COMPRESSION; } ctx.set_options(opts); set_fs(&mut ctx); ctx.set_certificate_chain_file(&Path::new(&cert)) .expect("Unable to read the TLS certificate chain"); ctx.set_private_key_file(&Path::new(&key), SslFiletype::PEM) .expect("Unable to read the TLS key"); ctx.set_cipher_list(&ciphers) .expect("Unsupported cipher suite"); } let acceptor = acceptor_builder.build(); let tls_config = TlsConfig { framing, threads, acceptor, }; (tls_config, listen, timeout) }
TlsConfig
identifier_name
mod.rs
use crate::flowgger::config::Config; use openssl::bn::BigNum; use openssl::dh::Dh; use openssl::ssl::*; use std::path::{Path, PathBuf}; pub mod tls_input; #[cfg(feature = "coroutines")] pub mod tlsco_input; pub use super::Input; const DEFAULT_CERT: &str = "flowgger.pem"; const DEFAULT_CIPHERS: &str = "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:\ ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:\ ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:\ ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:\ ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:\ AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:\ ECDHE-RSA-DES-CBC3-SHA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:\ !EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"; const DEFAULT_COMPRESSION: bool = false; const DEFAULT_FRAMING: &str = "line"; const DEFAULT_KEY: &str = "flowgger.pem"; const DEFAULT_LISTEN: &str = "0.0.0.0:6514"; #[cfg(feature = "coroutines")] const DEFAULT_THREADS: usize = 1; const DEFAULT_TIMEOUT: u64 = 3600; const DEFAULT_TLS_COMPATIBILITY_LEVEL: &str = "default"; const DEFAULT_VERIFY_PEER: bool = false; const TLS_VERIFY_DEPTH: u32 = 6; #[derive(Clone)] pub struct TlsConfig { framing: String, threads: usize, acceptor: SslAcceptor, } fn set_fs(ctx: &mut SslContextBuilder) { let p = BigNum::from_hex_str("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597").unwrap(); let g = BigNum::from_hex_str("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659").unwrap(); let q = BigNum::from_hex_str("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F5FBD3") .unwrap(); let dh = Dh::from_params(p, g, q).unwrap(); ctx.set_tmp_dh(&dh).unwrap(); } #[cfg(feature = "coroutines")] fn get_default_threads(config: &Config) -> usize { config .lookup("input.tls_threads") .map_or(DEFAULT_THREADS, |x| { x.as_integer() .expect("input.tls_threads must be an unsigned integer") as usize }) } #[cfg(not(feature = "coroutines"))] fn get_default_threads(_config: &Config) -> usize { 1 } pub fn config_parse(config: &Config) -> (TlsConfig, String, u64) { let listen = config .lookup("input.listen") .map_or(DEFAULT_LISTEN, |x| { x.as_str().expect("input.listen must be an ip:port string") }) .to_owned(); let threads = get_default_threads(config); let cert = config .lookup("input.tls_cert") .map_or(DEFAULT_CERT, |x| { x.as_str() .expect("input.tls_cert must be a path to a.pem file") }) .to_owned(); let key = config .lookup("input.tls_key") .map_or(DEFAULT_KEY, |x| { x.as_str() .expect("input.tls_key must be a path to a.pem file") }) .to_owned(); let ciphers = config .lookup("input.tls_ciphers") .map_or(DEFAULT_CIPHERS, |x| { x.as_str() .expect("input.tls_ciphers must be a string with a cipher suite") }) .to_owned(); let tls_modern = match config .lookup("input.tls_compatibility_level") .map_or(DEFAULT_TLS_COMPATIBILITY_LEVEL, |x| { x.as_str().expect( "input.tls_compatibility_level must be a string with the comptibility level", ) }) .to_lowercase() .as_ref() { "default" | "any" | "intermediate" => false, "modern" => true, _ => panic!(r#"TLS compatibility level must be "intermediate" or "modern""#), }; let verify_peer = config .lookup("input.tls_verify_peer") .map_or(DEFAULT_VERIFY_PEER, |x| { x.as_bool() .expect("input.tls_verify_peer must be a boolean") }); let ca_file: Option<PathBuf> = config.lookup("input.tls_ca_file").and_then(|x| { Some(PathBuf::from( x.as_str() .expect("input.tls_ca_file must be a path to a file"), )) }); let compression = config .lookup("input.tls_compression") .map_or(DEFAULT_COMPRESSION, |x| { x.as_bool() .expect("input.tls_compression must be a boolean") }); let timeout = config.lookup("input.timeout").map_or(DEFAULT_TIMEOUT, |x| { x.as_integer().expect("input.timeout must be an integer") as u64 }); let framing = if config.lookup("input.framed").map_or(false, |x| { x.as_bool().expect("input.framed must be a boolean") }) { "syslen" } else { DEFAULT_FRAMING }; let framing = config .lookup("input.framing") .map_or(framing, |x| { x.as_str() .expect(r#"input.framing must be a string set to "line", "nul" or "syslen""#) }) .to_owned(); let mut acceptor_builder = (if tls_modern
else { SslAcceptor::mozilla_intermediate(SslMethod::tls()) }) .unwrap(); { let mut ctx = &mut acceptor_builder; if let Some(ca_file) = ca_file { ctx.set_ca_file(&ca_file) .expect("Unable to read the trusted CA file"); } if!verify_peer { ctx.set_verify(SslVerifyMode::NONE); } else { ctx.set_verify_depth(TLS_VERIFY_DEPTH); ctx.set_verify(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT); } let mut opts = SslOptions::CIPHER_SERVER_PREFERENCE | SslOptions::NO_SESSION_RESUMPTION_ON_RENEGOTIATION; if!compression { opts |= SslOptions::NO_COMPRESSION; } ctx.set_options(opts); set_fs(&mut ctx); ctx.set_certificate_chain_file(&Path::new(&cert)) .expect("Unable to read the TLS certificate chain"); ctx.set_private_key_file(&Path::new(&key), SslFiletype::PEM) .expect("Unable to read the TLS key"); ctx.set_cipher_list(&ciphers) .expect("Unsupported cipher suite"); } let acceptor = acceptor_builder.build(); let tls_config = TlsConfig { framing, threads, acceptor, }; (tls_config, listen, timeout) }
{ SslAcceptor::mozilla_modern(SslMethod::tls()) }
conditional_block
local_rate_limit.rs
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use tokio::time::{timeout, Duration}; use quilkin::{ config::{Builder as ConfigBuilder, Filter}, endpoint::Endpoint, filters::local_rate_limit, test_utils::TestHelper, }; #[tokio::test] async fn local_rate_limit_filter()
t.run_server_with_config(server_config); let (mut recv_chan, socket) = t.open_socket_and_recv_multiple_packets().await; let server_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), server_port); for _ in 0..3 { socket.send_to(b"hello", &server_addr).await.unwrap(); } for _ in 0..2 { assert_eq!(recv_chan.recv().await.unwrap(), "hello"); } // Allow enough time to have received any response. tokio::time::sleep(Duration::from_millis(100)).await; // Check that we do not get any response. assert!(timeout(Duration::from_secs(1), recv_chan.recv()) .await .is_err()); }
{ let mut t = TestHelper::default(); let yaml = " max_packets: 2 period: 1 "; let echo = t.run_echo_server().await; let server_port = 12346; let server_config = ConfigBuilder::empty() .with_port(server_port) .with_static( vec![Filter { name: local_rate_limit::factory().name().into(), config: serde_yaml::from_str(yaml).unwrap(), }], vec![Endpoint::new(echo)], ) .build();
identifier_body
local_rate_limit.rs
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use tokio::time::{timeout, Duration}; use quilkin::{ config::{Builder as ConfigBuilder, Filter}, endpoint::Endpoint, filters::local_rate_limit, test_utils::TestHelper, }; #[tokio::test] async fn
() { let mut t = TestHelper::default(); let yaml = " max_packets: 2 period: 1 "; let echo = t.run_echo_server().await; let server_port = 12346; let server_config = ConfigBuilder::empty() .with_port(server_port) .with_static( vec![Filter { name: local_rate_limit::factory().name().into(), config: serde_yaml::from_str(yaml).unwrap(), }], vec![Endpoint::new(echo)], ) .build(); t.run_server_with_config(server_config); let (mut recv_chan, socket) = t.open_socket_and_recv_multiple_packets().await; let server_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), server_port); for _ in 0..3 { socket.send_to(b"hello", &server_addr).await.unwrap(); } for _ in 0..2 { assert_eq!(recv_chan.recv().await.unwrap(), "hello"); } // Allow enough time to have received any response. tokio::time::sleep(Duration::from_millis(100)).await; // Check that we do not get any response. assert!(timeout(Duration::from_secs(1), recv_chan.recv()) .await .is_err()); }
local_rate_limit_filter
identifier_name
local_rate_limit.rs
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use tokio::time::{timeout, Duration}; use quilkin::{ config::{Builder as ConfigBuilder, Filter}, endpoint::Endpoint, filters::local_rate_limit, test_utils::TestHelper, }; #[tokio::test] async fn local_rate_limit_filter() { let mut t = TestHelper::default(); let yaml = " max_packets: 2 period: 1 "; let echo = t.run_echo_server().await; let server_port = 12346; let server_config = ConfigBuilder::empty() .with_port(server_port) .with_static( vec![Filter { name: local_rate_limit::factory().name().into(), config: serde_yaml::from_str(yaml).unwrap(), }], vec![Endpoint::new(echo)], ) .build(); t.run_server_with_config(server_config); let (mut recv_chan, socket) = t.open_socket_and_recv_multiple_packets().await; let server_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), server_port); for _ in 0..3 { socket.send_to(b"hello", &server_addr).await.unwrap(); } for _ in 0..2 { assert_eq!(recv_chan.recv().await.unwrap(), "hello"); } // Allow enough time to have received any response. tokio::time::sleep(Duration::from_millis(100)).await; // Check that we do not get any response. assert!(timeout(Duration::from_secs(1), recv_chan.recv()) .await .is_err()); }
*
random_line_split
cssmediarule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::Parser; use dom::bindings::codegen::Bindings::CSSMediaRuleBinding; use dom::bindings::codegen::Bindings::CSSMediaRuleBinding::CSSMediaRuleMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::js::{MutNullableJS, Root}; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::cssconditionrule::CSSConditionRule; use dom::cssrule::SpecificCSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::medialist::MediaList; use dom::window::Window; use dom_struct::dom_struct; use std::sync::Arc; use style::media_queries::parse_media_query_list; use style::parser::{LengthParsingMode, ParserContext}; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylesheets::{CssRuleType, MediaRule}; use style_traits::ToCss; #[dom_struct] pub struct CSSMediaRule { cssconditionrule: CSSConditionRule, #[ignore_heap_size_of = "Arc"] mediarule: Arc<Locked<MediaRule>>, medialist: MutNullableJS<MediaList>, } impl CSSMediaRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, mediarule: Arc<Locked<MediaRule>>) -> CSSMediaRule { let guard = parent_stylesheet.shared_lock().read(); let list = mediarule.read_with(&guard).rules.clone(); CSSMediaRule { cssconditionrule: CSSConditionRule::new_inherited(parent_stylesheet, list), mediarule: mediarule, medialist: MutNullableJS::new(None), } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, mediarule: Arc<Locked<MediaRule>>) -> Root<CSSMediaRule> { reflect_dom_object(box CSSMediaRule::new_inherited(parent_stylesheet, mediarule), window, CSSMediaRuleBinding::Wrap) } fn medialist(&self) -> Root<MediaList> { self.medialist.or_init(|| { let guard = self.cssconditionrule.shared_lock().read(); MediaList::new(self.global().as_window(), self.cssconditionrule.parent_stylesheet(), self.mediarule.read_with(&guard).media_queries.clone()) }) } /// https://drafts.csswg.org/css-conditional-3/#the-cssmediarule-interface pub fn get_condition_text(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); let rule = self.mediarule.read_with(&guard); let list = rule.media_queries.read_with(&guard); list.to_css_string().into() } /// https://drafts.csswg.org/css-conditional-3/#the-cssmediarule-interface pub fn set_condition_text(&self, text: DOMString) { let mut input = Parser::new(&text); let global = self.global(); let win = global.as_window(); let url = win.get_url(); let quirks_mode = win.Document().quirks_mode(); let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Media), LengthParsingMode::Default, quirks_mode); let new_medialist = parse_media_query_list(&context, &mut input); let mut guard = self.cssconditionrule.shared_lock().write(); // Clone an Arc because we can’t borrow `guard` twice at the same time. // FIXME(SimonSapin): allow access to multiple objects with one write guard? // Would need a set of usize pointer addresses or something, // the same object is not accessed more than once. let mqs = Arc::clone(&self.mediarule.write_with(&mut guard).media_queries); *mqs.write_with(&mut guard) = new_medialist; } } impl SpecificCSSRule for CSSMediaRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::MEDIA_RULE } fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.mediarule.read_with(&guard).to_css_string(&guard).into() } }
fn Media(&self) -> Root<MediaList> { self.medialist() } }
impl CSSMediaRuleMethods for CSSMediaRule { // https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media
random_line_split
cssmediarule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::Parser; use dom::bindings::codegen::Bindings::CSSMediaRuleBinding; use dom::bindings::codegen::Bindings::CSSMediaRuleBinding::CSSMediaRuleMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::js::{MutNullableJS, Root}; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::cssconditionrule::CSSConditionRule; use dom::cssrule::SpecificCSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::medialist::MediaList; use dom::window::Window; use dom_struct::dom_struct; use std::sync::Arc; use style::media_queries::parse_media_query_list; use style::parser::{LengthParsingMode, ParserContext}; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylesheets::{CssRuleType, MediaRule}; use style_traits::ToCss; #[dom_struct] pub struct CSSMediaRule { cssconditionrule: CSSConditionRule, #[ignore_heap_size_of = "Arc"] mediarule: Arc<Locked<MediaRule>>, medialist: MutNullableJS<MediaList>, } impl CSSMediaRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, mediarule: Arc<Locked<MediaRule>>) -> CSSMediaRule { let guard = parent_stylesheet.shared_lock().read(); let list = mediarule.read_with(&guard).rules.clone(); CSSMediaRule { cssconditionrule: CSSConditionRule::new_inherited(parent_stylesheet, list), mediarule: mediarule, medialist: MutNullableJS::new(None), } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, mediarule: Arc<Locked<MediaRule>>) -> Root<CSSMediaRule> { reflect_dom_object(box CSSMediaRule::new_inherited(parent_stylesheet, mediarule), window, CSSMediaRuleBinding::Wrap) } fn medialist(&self) -> Root<MediaList> { self.medialist.or_init(|| { let guard = self.cssconditionrule.shared_lock().read(); MediaList::new(self.global().as_window(), self.cssconditionrule.parent_stylesheet(), self.mediarule.read_with(&guard).media_queries.clone()) }) } /// https://drafts.csswg.org/css-conditional-3/#the-cssmediarule-interface pub fn get_condition_text(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); let rule = self.mediarule.read_with(&guard); let list = rule.media_queries.read_with(&guard); list.to_css_string().into() } /// https://drafts.csswg.org/css-conditional-3/#the-cssmediarule-interface pub fn set_condition_text(&self, text: DOMString) { let mut input = Parser::new(&text); let global = self.global(); let win = global.as_window(); let url = win.get_url(); let quirks_mode = win.Document().quirks_mode(); let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Media), LengthParsingMode::Default, quirks_mode); let new_medialist = parse_media_query_list(&context, &mut input); let mut guard = self.cssconditionrule.shared_lock().write(); // Clone an Arc because we can’t borrow `guard` twice at the same time. // FIXME(SimonSapin): allow access to multiple objects with one write guard? // Would need a set of usize pointer addresses or something, // the same object is not accessed more than once. let mqs = Arc::clone(&self.mediarule.write_with(&mut guard).media_queries); *mqs.write_with(&mut guard) = new_medialist; } } impl SpecificCSSRule for CSSMediaRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::MEDIA_RULE } fn ge
self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.mediarule.read_with(&guard).to_css_string(&guard).into() } } impl CSSMediaRuleMethods for CSSMediaRule { // https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media fn Media(&self) -> Root<MediaList> { self.medialist() } }
t_css(&
identifier_name
logical_ast.rs
use query::Occur; use schema::Field; use schema::Term; use schema::Type; use std::fmt; use std::ops::Bound; #[derive(Clone)] pub enum LogicalLiteral { Term(Term), Phrase(Vec<(usize, Term)>), Range { field: Field, value_type: Type, lower: Bound<Term>, upper: Bound<Term>, }, All, } #[derive(Clone)] pub enum LogicalAST { Clause(Vec<(Occur, LogicalAST)>), Leaf(Box<LogicalLiteral>), } fn occur_letter(occur: Occur) -> &'static str { match occur { Occur::Must => "+", Occur::MustNot => "-", Occur::Should => "", } } impl fmt::Debug for LogicalAST { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error>
} impl From<LogicalLiteral> for LogicalAST { fn from(literal: LogicalLiteral) -> LogicalAST { LogicalAST::Leaf(Box::new(literal)) } } impl fmt::Debug for LogicalLiteral { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { LogicalLiteral::Term(ref term) => write!(formatter, "{:?}", term), LogicalLiteral::Phrase(ref terms) => write!(formatter, "\"{:?}\"", terms), LogicalLiteral::Range { ref lower, ref upper, .. } => write!(formatter, "({:?} TO {:?})", lower, upper), LogicalLiteral::All => write!(formatter, "*"), } } }
{ match *self { LogicalAST::Clause(ref clause) => { if clause.is_empty() { write!(formatter, "<emptyclause>")?; } else { let (ref occur, ref subquery) = clause[0]; write!(formatter, "({}{:?}", occur_letter(*occur), subquery)?; for &(ref occur, ref subquery) in &clause[1..] { write!(formatter, " {}{:?}", occur_letter(*occur), subquery)?; } formatter.write_str(")")?; } Ok(()) } LogicalAST::Leaf(ref literal) => write!(formatter, "{:?}", literal), } }
identifier_body
logical_ast.rs
use query::Occur; use schema::Field; use schema::Term; use schema::Type; use std::fmt; use std::ops::Bound; #[derive(Clone)] pub enum LogicalLiteral { Term(Term), Phrase(Vec<(usize, Term)>), Range { field: Field, value_type: Type, lower: Bound<Term>, upper: Bound<Term>, }, All, } #[derive(Clone)] pub enum LogicalAST { Clause(Vec<(Occur, LogicalAST)>), Leaf(Box<LogicalLiteral>), } fn occur_letter(occur: Occur) -> &'static str { match occur { Occur::Must => "+", Occur::MustNot => "-", Occur::Should => "", } } impl fmt::Debug for LogicalAST { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { LogicalAST::Clause(ref clause) =>
LogicalAST::Leaf(ref literal) => write!(formatter, "{:?}", literal), } } } impl From<LogicalLiteral> for LogicalAST { fn from(literal: LogicalLiteral) -> LogicalAST { LogicalAST::Leaf(Box::new(literal)) } } impl fmt::Debug for LogicalLiteral { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { LogicalLiteral::Term(ref term) => write!(formatter, "{:?}", term), LogicalLiteral::Phrase(ref terms) => write!(formatter, "\"{:?}\"", terms), LogicalLiteral::Range { ref lower, ref upper, .. } => write!(formatter, "({:?} TO {:?})", lower, upper), LogicalLiteral::All => write!(formatter, "*"), } } }
{ if clause.is_empty() { write!(formatter, "<emptyclause>")?; } else { let (ref occur, ref subquery) = clause[0]; write!(formatter, "({}{:?}", occur_letter(*occur), subquery)?; for &(ref occur, ref subquery) in &clause[1..] { write!(formatter, " {}{:?}", occur_letter(*occur), subquery)?; } formatter.write_str(")")?; } Ok(()) }
conditional_block
logical_ast.rs
use query::Occur; use schema::Field; use schema::Term; use schema::Type; use std::fmt; use std::ops::Bound; #[derive(Clone)] pub enum LogicalLiteral { Term(Term), Phrase(Vec<(usize, Term)>), Range { field: Field, value_type: Type, lower: Bound<Term>, upper: Bound<Term>, }, All,
Clause(Vec<(Occur, LogicalAST)>), Leaf(Box<LogicalLiteral>), } fn occur_letter(occur: Occur) -> &'static str { match occur { Occur::Must => "+", Occur::MustNot => "-", Occur::Should => "", } } impl fmt::Debug for LogicalAST { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { LogicalAST::Clause(ref clause) => { if clause.is_empty() { write!(formatter, "<emptyclause>")?; } else { let (ref occur, ref subquery) = clause[0]; write!(formatter, "({}{:?}", occur_letter(*occur), subquery)?; for &(ref occur, ref subquery) in &clause[1..] { write!(formatter, " {}{:?}", occur_letter(*occur), subquery)?; } formatter.write_str(")")?; } Ok(()) } LogicalAST::Leaf(ref literal) => write!(formatter, "{:?}", literal), } } } impl From<LogicalLiteral> for LogicalAST { fn from(literal: LogicalLiteral) -> LogicalAST { LogicalAST::Leaf(Box::new(literal)) } } impl fmt::Debug for LogicalLiteral { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { LogicalLiteral::Term(ref term) => write!(formatter, "{:?}", term), LogicalLiteral::Phrase(ref terms) => write!(formatter, "\"{:?}\"", terms), LogicalLiteral::Range { ref lower, ref upper, .. } => write!(formatter, "({:?} TO {:?})", lower, upper), LogicalLiteral::All => write!(formatter, "*"), } } }
} #[derive(Clone)] pub enum LogicalAST {
random_line_split
logical_ast.rs
use query::Occur; use schema::Field; use schema::Term; use schema::Type; use std::fmt; use std::ops::Bound; #[derive(Clone)] pub enum
{ Term(Term), Phrase(Vec<(usize, Term)>), Range { field: Field, value_type: Type, lower: Bound<Term>, upper: Bound<Term>, }, All, } #[derive(Clone)] pub enum LogicalAST { Clause(Vec<(Occur, LogicalAST)>), Leaf(Box<LogicalLiteral>), } fn occur_letter(occur: Occur) -> &'static str { match occur { Occur::Must => "+", Occur::MustNot => "-", Occur::Should => "", } } impl fmt::Debug for LogicalAST { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { LogicalAST::Clause(ref clause) => { if clause.is_empty() { write!(formatter, "<emptyclause>")?; } else { let (ref occur, ref subquery) = clause[0]; write!(formatter, "({}{:?}", occur_letter(*occur), subquery)?; for &(ref occur, ref subquery) in &clause[1..] { write!(formatter, " {}{:?}", occur_letter(*occur), subquery)?; } formatter.write_str(")")?; } Ok(()) } LogicalAST::Leaf(ref literal) => write!(formatter, "{:?}", literal), } } } impl From<LogicalLiteral> for LogicalAST { fn from(literal: LogicalLiteral) -> LogicalAST { LogicalAST::Leaf(Box::new(literal)) } } impl fmt::Debug for LogicalLiteral { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { LogicalLiteral::Term(ref term) => write!(formatter, "{:?}", term), LogicalLiteral::Phrase(ref terms) => write!(formatter, "\"{:?}\"", terms), LogicalLiteral::Range { ref lower, ref upper, .. } => write!(formatter, "({:?} TO {:?})", lower, upper), LogicalLiteral::All => write!(formatter, "*"), } } }
LogicalLiteral
identifier_name
deferred.rs
use std::ops; use std::str; use std::fmt; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum Deferred<T> { StaticStr(&'static str), Actual(T), } impl<T> Deferred<T> where T: From<&'static str> { pub(crate) fn into_actual(self) -> T
pub(crate) fn actual(&mut self) -> &mut T { if let Deferred::StaticStr(value) = *self { *self = Deferred::Actual(value.into()); } match *self { Deferred::StaticStr(_) => panic!("unexpected static storage"), Deferred::Actual(ref mut value) => value, } } } impl<T> fmt::Display for Deferred<T> where T: fmt::Display { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { Deferred::StaticStr(value) => fmt::Display::fmt(value, fmt), Deferred::Actual(ref value) => fmt::Display::fmt(value, fmt), } } } impl<T> ops::Deref for Deferred<T> where T: ops::Deref<Target=str> { type Target = str; fn deref(&self) -> &str { match *self { Deferred::StaticStr(value) => value, Deferred::Actual(ref value) => value, } } }
{ match self { Deferred::StaticStr(value) => value.into(), Deferred::Actual(value) => value, } }
identifier_body
deferred.rs
use std::ops; use std::str; use std::fmt; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum Deferred<T> { StaticStr(&'static str),
} impl<T> Deferred<T> where T: From<&'static str> { pub(crate) fn into_actual(self) -> T { match self { Deferred::StaticStr(value) => value.into(), Deferred::Actual(value) => value, } } pub(crate) fn actual(&mut self) -> &mut T { if let Deferred::StaticStr(value) = *self { *self = Deferred::Actual(value.into()); } match *self { Deferred::StaticStr(_) => panic!("unexpected static storage"), Deferred::Actual(ref mut value) => value, } } } impl<T> fmt::Display for Deferred<T> where T: fmt::Display { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { Deferred::StaticStr(value) => fmt::Display::fmt(value, fmt), Deferred::Actual(ref value) => fmt::Display::fmt(value, fmt), } } } impl<T> ops::Deref for Deferred<T> where T: ops::Deref<Target=str> { type Target = str; fn deref(&self) -> &str { match *self { Deferred::StaticStr(value) => value, Deferred::Actual(ref value) => value, } } }
Actual(T),
random_line_split
deferred.rs
use std::ops; use std::str; use std::fmt; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum Deferred<T> { StaticStr(&'static str), Actual(T), } impl<T> Deferred<T> where T: From<&'static str> { pub(crate) fn into_actual(self) -> T { match self { Deferred::StaticStr(value) => value.into(), Deferred::Actual(value) => value, } } pub(crate) fn
(&mut self) -> &mut T { if let Deferred::StaticStr(value) = *self { *self = Deferred::Actual(value.into()); } match *self { Deferred::StaticStr(_) => panic!("unexpected static storage"), Deferred::Actual(ref mut value) => value, } } } impl<T> fmt::Display for Deferred<T> where T: fmt::Display { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { Deferred::StaticStr(value) => fmt::Display::fmt(value, fmt), Deferred::Actual(ref value) => fmt::Display::fmt(value, fmt), } } } impl<T> ops::Deref for Deferred<T> where T: ops::Deref<Target=str> { type Target = str; fn deref(&self) -> &str { match *self { Deferred::StaticStr(value) => value, Deferred::Actual(ref value) => value, } } }
actual
identifier_name
implementations.rs
//! Implementations of `Header` and `ToHeader` for various types. use std::str; use std::fmt; use super::{Header, ToHeader}; impl ToHeader for usize { fn parse(raw: &[u8]) -> Option<usize> { str::from_utf8(raw).ok().and_then(|s| s.parse().ok()) } } impl Header for usize { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", *self) } } #[cfg(test)] mod tests { use std::fmt; use headers::{Header, ToHeader, HeaderDisplayAdapter}; fn eq<H: Header + ToHeader + Eq + fmt::Debug>(raw: &[u8], typed: H) { assert_eq!(format!("{}", HeaderDisplayAdapter(&typed)).as_bytes(), raw); assert_eq!(H::parse(raw), Some(typed)); } fn bad<H: ToHeader + Eq + fmt::Debug>(raw: &[u8]) { assert_eq!(H::parse(raw), None); } #[test] fn test_usize() { eq(b"0", 0usize); eq(b"1", 1usize); eq(b"123456789", 123456789usize); bad::<usize>(b"-1"); bad::<usize>(b"0xdeadbeef"); bad::<usize>(b"deadbeef");
} }
bad::<usize>(b"1234567890123467901245790"); bad::<usize>(b"1,000");
random_line_split
implementations.rs
//! Implementations of `Header` and `ToHeader` for various types. use std::str; use std::fmt; use super::{Header, ToHeader}; impl ToHeader for usize { fn parse(raw: &[u8]) -> Option<usize>
} impl Header for usize { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", *self) } } #[cfg(test)] mod tests { use std::fmt; use headers::{Header, ToHeader, HeaderDisplayAdapter}; fn eq<H: Header + ToHeader + Eq + fmt::Debug>(raw: &[u8], typed: H) { assert_eq!(format!("{}", HeaderDisplayAdapter(&typed)).as_bytes(), raw); assert_eq!(H::parse(raw), Some(typed)); } fn bad<H: ToHeader + Eq + fmt::Debug>(raw: &[u8]) { assert_eq!(H::parse(raw), None); } #[test] fn test_usize() { eq(b"0", 0usize); eq(b"1", 1usize); eq(b"123456789", 123456789usize); bad::<usize>(b"-1"); bad::<usize>(b"0xdeadbeef"); bad::<usize>(b"deadbeef"); bad::<usize>(b"1234567890123467901245790"); bad::<usize>(b"1,000"); } }
{ str::from_utf8(raw).ok().and_then(|s| s.parse().ok()) }
identifier_body
implementations.rs
//! Implementations of `Header` and `ToHeader` for various types. use std::str; use std::fmt; use super::{Header, ToHeader}; impl ToHeader for usize { fn parse(raw: &[u8]) -> Option<usize> { str::from_utf8(raw).ok().and_then(|s| s.parse().ok()) } } impl Header for usize { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", *self) } } #[cfg(test)] mod tests { use std::fmt; use headers::{Header, ToHeader, HeaderDisplayAdapter}; fn eq<H: Header + ToHeader + Eq + fmt::Debug>(raw: &[u8], typed: H) { assert_eq!(format!("{}", HeaderDisplayAdapter(&typed)).as_bytes(), raw); assert_eq!(H::parse(raw), Some(typed)); } fn bad<H: ToHeader + Eq + fmt::Debug>(raw: &[u8]) { assert_eq!(H::parse(raw), None); } #[test] fn
() { eq(b"0", 0usize); eq(b"1", 1usize); eq(b"123456789", 123456789usize); bad::<usize>(b"-1"); bad::<usize>(b"0xdeadbeef"); bad::<usize>(b"deadbeef"); bad::<usize>(b"1234567890123467901245790"); bad::<usize>(b"1,000"); } }
test_usize
identifier_name
thread.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 prelude::v1::*; use alloc::boxed::FnBox; use cmp; use io; use libc::{self, c_void, DWORD}; use mem; use ptr; use sys::c; use sys::handle::Handle; use sys_common::stack::RED_ZONE; use sys_common::thread::*; use time::Duration; pub struct
{ handle: Handle } impl Thread { pub unsafe fn new<'a>(stack: usize, p: Box<FnBox() + 'a>) -> io::Result<Thread> { let p = box p; // FIXME On UNIX, we guard against stack sizes that are too small but // that's because pthreads enforces that stacks are at least // PTHREAD_STACK_MIN bytes big. Windows has no such lower limit, it's // just that below a certain threshold you can't do anything useful. // That threshold is application and architecture-specific, however. // For now, the only requirement is that it's big enough to hold the // red zone. Round up to the next 64 kB because that's what the NT // kernel does, might as well make it explicit. With the current // 20 kB red zone, that makes for a 64 kB minimum stack. let stack_size = (cmp::max(stack, RED_ZONE) + 0xfffe) & (-0xfffe - 1); let ret = c::CreateThread(ptr::null_mut(), stack_size as libc::size_t, thread_start, &*p as *const _ as *mut _, 0, ptr::null_mut()); return if ret as usize == 0 { Err(io::Error::last_os_error()) } else { mem::forget(p); // ownership passed to CreateThread Ok(Thread { handle: Handle::new(ret) }) }; #[no_stack_check] extern "system" fn thread_start(main: *mut libc::c_void) -> DWORD { unsafe { start_thread(main); } 0 } } pub fn set_name(_name: &str) { // Windows threads are nameless // The names in MSVC debugger are obtained using a "magic" exception, // which requires a use of MS C++ extensions. // See https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx } pub fn join(self) { use libc::consts::os::extra::INFINITE; unsafe { c::WaitForSingleObject(self.handle.raw(), INFINITE); } } pub fn yield_now() { // This function will return 0 if there are no other threads to execute, // but this also means that the yield was useless so this isn't really a // case that needs to be worried about. unsafe { c::SwitchToThread(); } } pub fn sleep(dur: Duration) { unsafe { c::Sleep(super::dur2timeout(dur)) } } } pub mod guard { pub unsafe fn main() -> usize { 0 } pub unsafe fn current() -> usize { 0 } pub unsafe fn init() {} }
Thread
identifier_name
thread.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 prelude::v1::*; use alloc::boxed::FnBox; use cmp; use io; use libc::{self, c_void, DWORD}; use mem; use ptr; use sys::c; use sys::handle::Handle; use sys_common::stack::RED_ZONE; use sys_common::thread::*; use time::Duration; pub struct Thread { handle: Handle } impl Thread { pub unsafe fn new<'a>(stack: usize, p: Box<FnBox() + 'a>) -> io::Result<Thread> { let p = box p; // FIXME On UNIX, we guard against stack sizes that are too small but // that's because pthreads enforces that stacks are at least // PTHREAD_STACK_MIN bytes big. Windows has no such lower limit, it's // just that below a certain threshold you can't do anything useful. // That threshold is application and architecture-specific, however. // For now, the only requirement is that it's big enough to hold the // red zone. Round up to the next 64 kB because that's what the NT // kernel does, might as well make it explicit. With the current // 20 kB red zone, that makes for a 64 kB minimum stack. let stack_size = (cmp::max(stack, RED_ZONE) + 0xfffe) & (-0xfffe - 1); let ret = c::CreateThread(ptr::null_mut(), stack_size as libc::size_t, thread_start, &*p as *const _ as *mut _, 0, ptr::null_mut()); return if ret as usize == 0 { Err(io::Error::last_os_error()) } else { mem::forget(p); // ownership passed to CreateThread Ok(Thread { handle: Handle::new(ret) }) }; #[no_stack_check] extern "system" fn thread_start(main: *mut libc::c_void) -> DWORD {
0 } } pub fn set_name(_name: &str) { // Windows threads are nameless // The names in MSVC debugger are obtained using a "magic" exception, // which requires a use of MS C++ extensions. // See https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx } pub fn join(self) { use libc::consts::os::extra::INFINITE; unsafe { c::WaitForSingleObject(self.handle.raw(), INFINITE); } } pub fn yield_now() { // This function will return 0 if there are no other threads to execute, // but this also means that the yield was useless so this isn't really a // case that needs to be worried about. unsafe { c::SwitchToThread(); } } pub fn sleep(dur: Duration) { unsafe { c::Sleep(super::dur2timeout(dur)) } } } pub mod guard { pub unsafe fn main() -> usize { 0 } pub unsafe fn current() -> usize { 0 } pub unsafe fn init() {} }
unsafe { start_thread(main); }
random_line_split
thread.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 prelude::v1::*; use alloc::boxed::FnBox; use cmp; use io; use libc::{self, c_void, DWORD}; use mem; use ptr; use sys::c; use sys::handle::Handle; use sys_common::stack::RED_ZONE; use sys_common::thread::*; use time::Duration; pub struct Thread { handle: Handle } impl Thread { pub unsafe fn new<'a>(stack: usize, p: Box<FnBox() + 'a>) -> io::Result<Thread> { let p = box p; // FIXME On UNIX, we guard against stack sizes that are too small but // that's because pthreads enforces that stacks are at least // PTHREAD_STACK_MIN bytes big. Windows has no such lower limit, it's // just that below a certain threshold you can't do anything useful. // That threshold is application and architecture-specific, however. // For now, the only requirement is that it's big enough to hold the // red zone. Round up to the next 64 kB because that's what the NT // kernel does, might as well make it explicit. With the current // 20 kB red zone, that makes for a 64 kB minimum stack. let stack_size = (cmp::max(stack, RED_ZONE) + 0xfffe) & (-0xfffe - 1); let ret = c::CreateThread(ptr::null_mut(), stack_size as libc::size_t, thread_start, &*p as *const _ as *mut _, 0, ptr::null_mut()); return if ret as usize == 0
else { mem::forget(p); // ownership passed to CreateThread Ok(Thread { handle: Handle::new(ret) }) }; #[no_stack_check] extern "system" fn thread_start(main: *mut libc::c_void) -> DWORD { unsafe { start_thread(main); } 0 } } pub fn set_name(_name: &str) { // Windows threads are nameless // The names in MSVC debugger are obtained using a "magic" exception, // which requires a use of MS C++ extensions. // See https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx } pub fn join(self) { use libc::consts::os::extra::INFINITE; unsafe { c::WaitForSingleObject(self.handle.raw(), INFINITE); } } pub fn yield_now() { // This function will return 0 if there are no other threads to execute, // but this also means that the yield was useless so this isn't really a // case that needs to be worried about. unsafe { c::SwitchToThread(); } } pub fn sleep(dur: Duration) { unsafe { c::Sleep(super::dur2timeout(dur)) } } } pub mod guard { pub unsafe fn main() -> usize { 0 } pub unsafe fn current() -> usize { 0 } pub unsafe fn init() {} }
{ Err(io::Error::last_os_error()) }
conditional_block
change_set.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::ledger_counters::LedgerCounterBumps; use diem_types::transaction::Version; use schemadb::SchemaBatch; use std::collections::HashMap; /// Structure that collects changes to be made to the DB in one transaction. /// /// To be specific it carries a batch of db alternations and counter increases that'll be converted /// to DB alternations on "sealing". This is required to be converted to `SealedChangeSet` before /// committing to the DB. pub(crate) struct ChangeSet { /// A batch of db alternations. pub batch: SchemaBatch, /// Counter bumps to be made on commit. counter_bumps: HashMap<Version, LedgerCounterBumps>, } impl ChangeSet { /// Constructor. pub fn new() -> Self { Self { batch: SchemaBatch::new(), counter_bumps: HashMap::new(), } } pub fn counter_bumps(&mut self, version: Version) -> &mut LedgerCounterBumps { self.counter_bumps .entry(version) .or_insert_with(LedgerCounterBumps::new) } #[cfg(test)] pub fn new_with_bumps(counter_bumps: HashMap<Version, LedgerCounterBumps>) -> Self { Self { batch: SchemaBatch::new(), counter_bumps, } } } /// ChangeSet that's ready to be committed to the DB. ///
pub(crate) struct SealedChangeSet { /// A batch of db alternations. pub batch: SchemaBatch, }
/// This is a wrapper type just to make sure `ChangeSet` to be committed is sealed properly.
random_line_split
change_set.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::ledger_counters::LedgerCounterBumps; use diem_types::transaction::Version; use schemadb::SchemaBatch; use std::collections::HashMap; /// Structure that collects changes to be made to the DB in one transaction. /// /// To be specific it carries a batch of db alternations and counter increases that'll be converted /// to DB alternations on "sealing". This is required to be converted to `SealedChangeSet` before /// committing to the DB. pub(crate) struct ChangeSet { /// A batch of db alternations. pub batch: SchemaBatch, /// Counter bumps to be made on commit. counter_bumps: HashMap<Version, LedgerCounterBumps>, } impl ChangeSet { /// Constructor. pub fn new() -> Self { Self { batch: SchemaBatch::new(), counter_bumps: HashMap::new(), } } pub fn counter_bumps(&mut self, version: Version) -> &mut LedgerCounterBumps { self.counter_bumps .entry(version) .or_insert_with(LedgerCounterBumps::new) } #[cfg(test)] pub fn new_with_bumps(counter_bumps: HashMap<Version, LedgerCounterBumps>) -> Self { Self { batch: SchemaBatch::new(), counter_bumps, } } } /// ChangeSet that's ready to be committed to the DB. /// /// This is a wrapper type just to make sure `ChangeSet` to be committed is sealed properly. pub(crate) struct
{ /// A batch of db alternations. pub batch: SchemaBatch, }
SealedChangeSet
identifier_name
change_set.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::ledger_counters::LedgerCounterBumps; use diem_types::transaction::Version; use schemadb::SchemaBatch; use std::collections::HashMap; /// Structure that collects changes to be made to the DB in one transaction. /// /// To be specific it carries a batch of db alternations and counter increases that'll be converted /// to DB alternations on "sealing". This is required to be converted to `SealedChangeSet` before /// committing to the DB. pub(crate) struct ChangeSet { /// A batch of db alternations. pub batch: SchemaBatch, /// Counter bumps to be made on commit. counter_bumps: HashMap<Version, LedgerCounterBumps>, } impl ChangeSet { /// Constructor. pub fn new() -> Self
pub fn counter_bumps(&mut self, version: Version) -> &mut LedgerCounterBumps { self.counter_bumps .entry(version) .or_insert_with(LedgerCounterBumps::new) } #[cfg(test)] pub fn new_with_bumps(counter_bumps: HashMap<Version, LedgerCounterBumps>) -> Self { Self { batch: SchemaBatch::new(), counter_bumps, } } } /// ChangeSet that's ready to be committed to the DB. /// /// This is a wrapper type just to make sure `ChangeSet` to be committed is sealed properly. pub(crate) struct SealedChangeSet { /// A batch of db alternations. pub batch: SchemaBatch, }
{ Self { batch: SchemaBatch::new(), counter_bumps: HashMap::new(), } }
identifier_body
main.rs
extern crate chrono; #[macro_use] extern crate clap; extern crate cursive; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; use std::cmp; use std::panic; use chrono::prelude::*; use cursive::Cursive; use cursive::direction::*; use cursive::event::*; use cursive::theme::*; use cursive::view::*; use cursive::views::*; mod litrpc; fn
() { let matches = clap_app!(lit_af_rs => (version: "0.1.0") (author: "Trey Del Bonis <[email protected]>") (about: "CLI client for Lit") (@arg a: +takes_value "Address to connect to. Default: localhost") (@arg p: +takes_value "Port to connect to lit to. Default: idk yet lmao") ).get_matches(); // TODO Make these optional. let addr = matches.value_of("a").unwrap_or("localhost"); let port = match matches.value_of("p").map(str::parse) { Some(Ok(p)) => p, Some(Err(_)) => panic!("port is not a number"), None => 12345 // FIXME }; println!("addr: {}, port {}", addr, port); match panic::catch_unwind(|| run_ui(addr, port)) { Ok(_) => {}, // we're ok Err(_) => run_bsod() } } fn run_ui(addr: &str, port: u16) { let mut client = Box::new(litrpc::LitRpcClient::new(addr, port)); let mut layout = LinearLayout::new(Orientation::Horizontal); let mut c_view = LinearLayout::new(Orientation::Vertical); c_view.add_child(TextView::new("Channels")); layout.add_child( BoxView::new( SizeConstraint::Full, SizeConstraint::Full, IdView::new("chans", Panel::new(c_view)))); let mut right_view = LinearLayout::new(Orientation::Vertical); // Balances let mut bal_view = LinearLayout::new(Orientation::Vertical); bal_view.add_child(TextView::new("Balances")); right_view.add_child( BoxView::new( SizeConstraint::Full, SizeConstraint::Full, IdView::new("bals", Panel::new(bal_view))) .squishable()); // Txos let mut txo_view = LinearLayout::new(Orientation::Vertical); txo_view.add_child(TextView::new("Txos")); right_view.add_child( BoxView::new( SizeConstraint::Full, SizeConstraint::Full, IdView::new("txos", Panel::new(txo_view))) .squishable()); layout.add_child(BoxView::new(SizeConstraint::Full, SizeConstraint::Full, right_view)); let mut siv = Cursive::new(); siv.add_layer(BoxView::new(SizeConstraint::Full, SizeConstraint::Full, layout)); siv.set_theme(load_theme(include_str!("ncurses_theme.toml")).unwrap()); siv.add_global_callback(Event::Refresh, make_update_ui_callback_with_client(&mut client)); siv.set_fps(1); siv.run() } fn run_bsod() { let mut siv = Cursive::new(); let d = Dialog::around(TextView::new("RS-AF has encountered an error and needs to exit.")) .title("Panic") .button("Exit", |s| s.quit()); siv.add_layer(d); siv.run(); } fn generate_view_for_chan(chan: litrpc::ChanInfo) -> impl View { let ndt = NaiveDateTime::from_timestamp( (chan.LastUpdate / 1000) as i64, ((chan.LastUpdate % 1000) * 1000) as u32); let dt: DateTime<Utc> = DateTime::from_utc(ndt, chrono::Utc); let mut data = LinearLayout::new(Orientation::Vertical); data.add_child(TextView::new(format!("Channel # {}", chan.CIdx))); data.add_child(TextView::new(format!("Outpoint: {}", chan.OutPoint))); data.add_child(TextView::new(format!("Peer: {}", chan.PeerIdx))); data.add_child(TextView::new(format!("Coin Type: {}", chan.CoinType))); data.add_child(TextView::new(format!("Last Activity: {}", dt.to_rfc3339()))); data.add_child(DummyView); data.add_child(TextView::new(format!("Balance: {}/{}", chan.MyBalance, chan.Capacity))); let mut bar = ProgressBar::new().range(0, chan.Capacity as usize); bar.set_value(chan.MyBalance as usize); data.add_child(bar); let cbox = BoxView::new(SizeConstraint::Full, SizeConstraint::AtLeast(5), data); Panel::new(cbox) } fn generate_view_for_bal(bal: &litrpc::CoinBalInfo, addrs: Vec<String>) -> impl View { let mut data = LinearLayout::new(Orientation::Vertical); let grand_total = bal.ChanTotal + bal.TxoTotal; let bal_str = format!( " Funds: chans {} + txos {} = total {} (sat)", bal.ChanTotal, bal.TxoTotal, grand_total); data.add_child(TextView::new(format!("- Type {} @ height {}", bal.CoinType, bal.SyncHeight))); data.add_child(TextView::new(bal_str)); addrs.into_iter() .map(|a| format!(" - {}", a)) .map(TextView::new) .for_each(|l| data.add_child(l)); data.add_child(DummyView); data } fn generate_view_for_txo(txo: litrpc::TxoInfo) -> impl View { // TODO Make this prettier let strs = vec![ ("Outpoint", txo.OutPoint), ("Amount", format!("{}", txo.Amt)), ("Height", format!("{}", txo.Height)), ("Coin Type", txo.CoinType), ("Key Path", txo.KeyPath) ]; let mut data = LinearLayout::new(Orientation::Vertical); for (k, v) in strs { data.add_child(TextView::new(format!("{}: {}", k, v))); } let cbox = BoxView::new(SizeConstraint::Full, SizeConstraint::Free, data); Panel::new(cbox) } fn make_update_ui_callback_with_client(cl: &mut litrpc::LitRpcClient) -> impl Fn(&mut Cursive) { use std::mem; let clp: *mut litrpc::LitRpcClient = unsafe { mem::transmute(cl) }; move |c: &mut Cursive| { let clrc: &mut litrpc::LitRpcClient = unsafe { mem::transmute(clp) }; // Channels. let chans: Vec<litrpc::ChanInfo> = match clrc.call_chan_list(0) { Ok(clr) => { let mut cls = clr.Channels; // Reversed because we want the newest at the top. cls.sort_by(|a, b| cmp::Ord::cmp(&b.LastUpdate, &a.LastUpdate)); cls }, Err(err) => panic!("{:?}", err) }; c.call_on_id("chans", |cpan: &mut Panel<LinearLayout>| { let mut c_view = LinearLayout::new(Orientation::Vertical); c_view.add_child(TextView::new("Channels")); chans.into_iter() .map(generate_view_for_chan) .for_each(|e| c_view.add_child(e)); *cpan.get_inner_mut() = c_view; }); // Bals let bals: Vec<litrpc::CoinBalInfo> = match clrc.call_bal() { Ok(br) => { let mut bals = br.Balances; bals.sort_by(|a, b| cmp::Ord::cmp(&a.CoinType, &b.CoinType)); bals }, Err(err) => panic!("{:?}", err) }; // Addrs let addrs: Vec<(u32, String)> = match clrc.call_get_addresses() { Ok(ar) => { let mut addrs: Vec<(u32, String)> = ar.CoinTypes.into_iter() .zip(ar.WitAddresses.into_iter()) .collect(); addrs.sort_by(|a, b| match cmp::Ord::cmp(&a.0, &b.0) { cmp::Ordering::Equal => cmp::Ord::cmp(&a.1, &b.1), o => o }); addrs }, Err(err) => panic!("{:?}", err) }; c.call_on_id("bals", |balpan: &mut Panel<LinearLayout>| { let mut bal_view = LinearLayout::new(Orientation::Vertical); bal_view.add_child(TextView::new("Balances")); bal_view.add_child(DummyView); bals.into_iter() .map(|b| generate_view_for_bal( &b, addrs.clone().into_iter() .filter(|(t, _)| *t == b.CoinType) .map(|(_, a)| a) .collect())) .for_each(|e| bal_view.add_child(e)); *balpan.get_inner_mut() = bal_view; }); // Txos let txos: Vec<litrpc::TxoInfo> = match clrc.call_get_txo_list() { Ok(txr) => txr.Txos, Err(err) => { eprintln!("error: {:?}", err); Vec::new() } }; c.call_on_id("txos", |txopan: &mut Panel<LinearLayout>| { let mut txo_view = LinearLayout::new(Orientation::Vertical); txo_view.add_child(TextView::new("Txos")); txos.into_iter() .map(generate_view_for_txo) .for_each(|e| txo_view.add_child(e)); *txopan.get_inner_mut() = txo_view; }); } }
main
identifier_name
main.rs
extern crate chrono; #[macro_use] extern crate clap; extern crate cursive; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; use std::cmp; use std::panic; use chrono::prelude::*; use cursive::Cursive; use cursive::direction::*; use cursive::event::*; use cursive::theme::*; use cursive::view::*; use cursive::views::*; mod litrpc; fn main() { let matches = clap_app!(lit_af_rs => (version: "0.1.0") (author: "Trey Del Bonis <[email protected]>") (about: "CLI client for Lit") (@arg a: +takes_value "Address to connect to. Default: localhost") (@arg p: +takes_value "Port to connect to lit to. Default: idk yet lmao") ).get_matches(); // TODO Make these optional. let addr = matches.value_of("a").unwrap_or("localhost"); let port = match matches.value_of("p").map(str::parse) { Some(Ok(p)) => p, Some(Err(_)) => panic!("port is not a number"), None => 12345 // FIXME }; println!("addr: {}, port {}", addr, port); match panic::catch_unwind(|| run_ui(addr, port)) { Ok(_) => {}, // we're ok Err(_) => run_bsod() } } fn run_ui(addr: &str, port: u16) { let mut client = Box::new(litrpc::LitRpcClient::new(addr, port)); let mut layout = LinearLayout::new(Orientation::Horizontal); let mut c_view = LinearLayout::new(Orientation::Vertical); c_view.add_child(TextView::new("Channels")); layout.add_child( BoxView::new( SizeConstraint::Full, SizeConstraint::Full, IdView::new("chans", Panel::new(c_view)))); let mut right_view = LinearLayout::new(Orientation::Vertical); // Balances let mut bal_view = LinearLayout::new(Orientation::Vertical); bal_view.add_child(TextView::new("Balances")); right_view.add_child( BoxView::new( SizeConstraint::Full, SizeConstraint::Full, IdView::new("bals", Panel::new(bal_view))) .squishable()); // Txos let mut txo_view = LinearLayout::new(Orientation::Vertical); txo_view.add_child(TextView::new("Txos")); right_view.add_child( BoxView::new( SizeConstraint::Full, SizeConstraint::Full, IdView::new("txos", Panel::new(txo_view))) .squishable()); layout.add_child(BoxView::new(SizeConstraint::Full, SizeConstraint::Full, right_view)); let mut siv = Cursive::new(); siv.add_layer(BoxView::new(SizeConstraint::Full, SizeConstraint::Full, layout)); siv.set_theme(load_theme(include_str!("ncurses_theme.toml")).unwrap()); siv.add_global_callback(Event::Refresh, make_update_ui_callback_with_client(&mut client)); siv.set_fps(1); siv.run() } fn run_bsod() { let mut siv = Cursive::new(); let d = Dialog::around(TextView::new("RS-AF has encountered an error and needs to exit.")) .title("Panic") .button("Exit", |s| s.quit()); siv.add_layer(d); siv.run(); } fn generate_view_for_chan(chan: litrpc::ChanInfo) -> impl View { let ndt = NaiveDateTime::from_timestamp( (chan.LastUpdate / 1000) as i64, ((chan.LastUpdate % 1000) * 1000) as u32);
let dt: DateTime<Utc> = DateTime::from_utc(ndt, chrono::Utc); let mut data = LinearLayout::new(Orientation::Vertical); data.add_child(TextView::new(format!("Channel # {}", chan.CIdx))); data.add_child(TextView::new(format!("Outpoint: {}", chan.OutPoint))); data.add_child(TextView::new(format!("Peer: {}", chan.PeerIdx))); data.add_child(TextView::new(format!("Coin Type: {}", chan.CoinType))); data.add_child(TextView::new(format!("Last Activity: {}", dt.to_rfc3339()))); data.add_child(DummyView); data.add_child(TextView::new(format!("Balance: {}/{}", chan.MyBalance, chan.Capacity))); let mut bar = ProgressBar::new().range(0, chan.Capacity as usize); bar.set_value(chan.MyBalance as usize); data.add_child(bar); let cbox = BoxView::new(SizeConstraint::Full, SizeConstraint::AtLeast(5), data); Panel::new(cbox) } fn generate_view_for_bal(bal: &litrpc::CoinBalInfo, addrs: Vec<String>) -> impl View { let mut data = LinearLayout::new(Orientation::Vertical); let grand_total = bal.ChanTotal + bal.TxoTotal; let bal_str = format!( " Funds: chans {} + txos {} = total {} (sat)", bal.ChanTotal, bal.TxoTotal, grand_total); data.add_child(TextView::new(format!("- Type {} @ height {}", bal.CoinType, bal.SyncHeight))); data.add_child(TextView::new(bal_str)); addrs.into_iter() .map(|a| format!(" - {}", a)) .map(TextView::new) .for_each(|l| data.add_child(l)); data.add_child(DummyView); data } fn generate_view_for_txo(txo: litrpc::TxoInfo) -> impl View { // TODO Make this prettier let strs = vec![ ("Outpoint", txo.OutPoint), ("Amount", format!("{}", txo.Amt)), ("Height", format!("{}", txo.Height)), ("Coin Type", txo.CoinType), ("Key Path", txo.KeyPath) ]; let mut data = LinearLayout::new(Orientation::Vertical); for (k, v) in strs { data.add_child(TextView::new(format!("{}: {}", k, v))); } let cbox = BoxView::new(SizeConstraint::Full, SizeConstraint::Free, data); Panel::new(cbox) } fn make_update_ui_callback_with_client(cl: &mut litrpc::LitRpcClient) -> impl Fn(&mut Cursive) { use std::mem; let clp: *mut litrpc::LitRpcClient = unsafe { mem::transmute(cl) }; move |c: &mut Cursive| { let clrc: &mut litrpc::LitRpcClient = unsafe { mem::transmute(clp) }; // Channels. let chans: Vec<litrpc::ChanInfo> = match clrc.call_chan_list(0) { Ok(clr) => { let mut cls = clr.Channels; // Reversed because we want the newest at the top. cls.sort_by(|a, b| cmp::Ord::cmp(&b.LastUpdate, &a.LastUpdate)); cls }, Err(err) => panic!("{:?}", err) }; c.call_on_id("chans", |cpan: &mut Panel<LinearLayout>| { let mut c_view = LinearLayout::new(Orientation::Vertical); c_view.add_child(TextView::new("Channels")); chans.into_iter() .map(generate_view_for_chan) .for_each(|e| c_view.add_child(e)); *cpan.get_inner_mut() = c_view; }); // Bals let bals: Vec<litrpc::CoinBalInfo> = match clrc.call_bal() { Ok(br) => { let mut bals = br.Balances; bals.sort_by(|a, b| cmp::Ord::cmp(&a.CoinType, &b.CoinType)); bals }, Err(err) => panic!("{:?}", err) }; // Addrs let addrs: Vec<(u32, String)> = match clrc.call_get_addresses() { Ok(ar) => { let mut addrs: Vec<(u32, String)> = ar.CoinTypes.into_iter() .zip(ar.WitAddresses.into_iter()) .collect(); addrs.sort_by(|a, b| match cmp::Ord::cmp(&a.0, &b.0) { cmp::Ordering::Equal => cmp::Ord::cmp(&a.1, &b.1), o => o }); addrs }, Err(err) => panic!("{:?}", err) }; c.call_on_id("bals", |balpan: &mut Panel<LinearLayout>| { let mut bal_view = LinearLayout::new(Orientation::Vertical); bal_view.add_child(TextView::new("Balances")); bal_view.add_child(DummyView); bals.into_iter() .map(|b| generate_view_for_bal( &b, addrs.clone().into_iter() .filter(|(t, _)| *t == b.CoinType) .map(|(_, a)| a) .collect())) .for_each(|e| bal_view.add_child(e)); *balpan.get_inner_mut() = bal_view; }); // Txos let txos: Vec<litrpc::TxoInfo> = match clrc.call_get_txo_list() { Ok(txr) => txr.Txos, Err(err) => { eprintln!("error: {:?}", err); Vec::new() } }; c.call_on_id("txos", |txopan: &mut Panel<LinearLayout>| { let mut txo_view = LinearLayout::new(Orientation::Vertical); txo_view.add_child(TextView::new("Txos")); txos.into_iter() .map(generate_view_for_txo) .for_each(|e| txo_view.add_child(e)); *txopan.get_inner_mut() = txo_view; }); } }
random_line_split
main.rs
extern crate chrono; #[macro_use] extern crate clap; extern crate cursive; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; use std::cmp; use std::panic; use chrono::prelude::*; use cursive::Cursive; use cursive::direction::*; use cursive::event::*; use cursive::theme::*; use cursive::view::*; use cursive::views::*; mod litrpc; fn main() { let matches = clap_app!(lit_af_rs => (version: "0.1.0") (author: "Trey Del Bonis <[email protected]>") (about: "CLI client for Lit") (@arg a: +takes_value "Address to connect to. Default: localhost") (@arg p: +takes_value "Port to connect to lit to. Default: idk yet lmao") ).get_matches(); // TODO Make these optional. let addr = matches.value_of("a").unwrap_or("localhost"); let port = match matches.value_of("p").map(str::parse) { Some(Ok(p)) => p, Some(Err(_)) => panic!("port is not a number"), None => 12345 // FIXME }; println!("addr: {}, port {}", addr, port); match panic::catch_unwind(|| run_ui(addr, port)) { Ok(_) => {}, // we're ok Err(_) => run_bsod() } } fn run_ui(addr: &str, port: u16) { let mut client = Box::new(litrpc::LitRpcClient::new(addr, port)); let mut layout = LinearLayout::new(Orientation::Horizontal); let mut c_view = LinearLayout::new(Orientation::Vertical); c_view.add_child(TextView::new("Channels")); layout.add_child( BoxView::new( SizeConstraint::Full, SizeConstraint::Full, IdView::new("chans", Panel::new(c_view)))); let mut right_view = LinearLayout::new(Orientation::Vertical); // Balances let mut bal_view = LinearLayout::new(Orientation::Vertical); bal_view.add_child(TextView::new("Balances")); right_view.add_child( BoxView::new( SizeConstraint::Full, SizeConstraint::Full, IdView::new("bals", Panel::new(bal_view))) .squishable()); // Txos let mut txo_view = LinearLayout::new(Orientation::Vertical); txo_view.add_child(TextView::new("Txos")); right_view.add_child( BoxView::new( SizeConstraint::Full, SizeConstraint::Full, IdView::new("txos", Panel::new(txo_view))) .squishable()); layout.add_child(BoxView::new(SizeConstraint::Full, SizeConstraint::Full, right_view)); let mut siv = Cursive::new(); siv.add_layer(BoxView::new(SizeConstraint::Full, SizeConstraint::Full, layout)); siv.set_theme(load_theme(include_str!("ncurses_theme.toml")).unwrap()); siv.add_global_callback(Event::Refresh, make_update_ui_callback_with_client(&mut client)); siv.set_fps(1); siv.run() } fn run_bsod() { let mut siv = Cursive::new(); let d = Dialog::around(TextView::new("RS-AF has encountered an error and needs to exit.")) .title("Panic") .button("Exit", |s| s.quit()); siv.add_layer(d); siv.run(); } fn generate_view_for_chan(chan: litrpc::ChanInfo) -> impl View { let ndt = NaiveDateTime::from_timestamp( (chan.LastUpdate / 1000) as i64, ((chan.LastUpdate % 1000) * 1000) as u32); let dt: DateTime<Utc> = DateTime::from_utc(ndt, chrono::Utc); let mut data = LinearLayout::new(Orientation::Vertical); data.add_child(TextView::new(format!("Channel # {}", chan.CIdx))); data.add_child(TextView::new(format!("Outpoint: {}", chan.OutPoint))); data.add_child(TextView::new(format!("Peer: {}", chan.PeerIdx))); data.add_child(TextView::new(format!("Coin Type: {}", chan.CoinType))); data.add_child(TextView::new(format!("Last Activity: {}", dt.to_rfc3339()))); data.add_child(DummyView); data.add_child(TextView::new(format!("Balance: {}/{}", chan.MyBalance, chan.Capacity))); let mut bar = ProgressBar::new().range(0, chan.Capacity as usize); bar.set_value(chan.MyBalance as usize); data.add_child(bar); let cbox = BoxView::new(SizeConstraint::Full, SizeConstraint::AtLeast(5), data); Panel::new(cbox) } fn generate_view_for_bal(bal: &litrpc::CoinBalInfo, addrs: Vec<String>) -> impl View { let mut data = LinearLayout::new(Orientation::Vertical); let grand_total = bal.ChanTotal + bal.TxoTotal; let bal_str = format!( " Funds: chans {} + txos {} = total {} (sat)", bal.ChanTotal, bal.TxoTotal, grand_total); data.add_child(TextView::new(format!("- Type {} @ height {}", bal.CoinType, bal.SyncHeight))); data.add_child(TextView::new(bal_str)); addrs.into_iter() .map(|a| format!(" - {}", a)) .map(TextView::new) .for_each(|l| data.add_child(l)); data.add_child(DummyView); data } fn generate_view_for_txo(txo: litrpc::TxoInfo) -> impl View { // TODO Make this prettier let strs = vec![ ("Outpoint", txo.OutPoint), ("Amount", format!("{}", txo.Amt)), ("Height", format!("{}", txo.Height)), ("Coin Type", txo.CoinType), ("Key Path", txo.KeyPath) ]; let mut data = LinearLayout::new(Orientation::Vertical); for (k, v) in strs { data.add_child(TextView::new(format!("{}: {}", k, v))); } let cbox = BoxView::new(SizeConstraint::Full, SizeConstraint::Free, data); Panel::new(cbox) } fn make_update_ui_callback_with_client(cl: &mut litrpc::LitRpcClient) -> impl Fn(&mut Cursive)
c.call_on_id("chans", |cpan: &mut Panel<LinearLayout>| { let mut c_view = LinearLayout::new(Orientation::Vertical); c_view.add_child(TextView::new("Channels")); chans.into_iter() .map(generate_view_for_chan) .for_each(|e| c_view.add_child(e)); *cpan.get_inner_mut() = c_view; }); // Bals let bals: Vec<litrpc::CoinBalInfo> = match clrc.call_bal() { Ok(br) => { let mut bals = br.Balances; bals.sort_by(|a, b| cmp::Ord::cmp(&a.CoinType, &b.CoinType)); bals }, Err(err) => panic!("{:?}", err) }; // Addrs let addrs: Vec<(u32, String)> = match clrc.call_get_addresses() { Ok(ar) => { let mut addrs: Vec<(u32, String)> = ar.CoinTypes.into_iter() .zip(ar.WitAddresses.into_iter()) .collect(); addrs.sort_by(|a, b| match cmp::Ord::cmp(&a.0, &b.0) { cmp::Ordering::Equal => cmp::Ord::cmp(&a.1, &b.1), o => o }); addrs }, Err(err) => panic!("{:?}", err) }; c.call_on_id("bals", |balpan: &mut Panel<LinearLayout>| { let mut bal_view = LinearLayout::new(Orientation::Vertical); bal_view.add_child(TextView::new("Balances")); bal_view.add_child(DummyView); bals.into_iter() .map(|b| generate_view_for_bal( &b, addrs.clone().into_iter() .filter(|(t, _)| *t == b.CoinType) .map(|(_, a)| a) .collect())) .for_each(|e| bal_view.add_child(e)); *balpan.get_inner_mut() = bal_view; }); // Txos let txos: Vec<litrpc::TxoInfo> = match clrc.call_get_txo_list() { Ok(txr) => txr.Txos, Err(err) => { eprintln!("error: {:?}", err); Vec::new() } }; c.call_on_id("txos", |txopan: &mut Panel<LinearLayout>| { let mut txo_view = LinearLayout::new(Orientation::Vertical); txo_view.add_child(TextView::new("Txos")); txos.into_iter() .map(generate_view_for_txo) .for_each(|e| txo_view.add_child(e)); *txopan.get_inner_mut() = txo_view; }); } }
{ use std::mem; let clp: *mut litrpc::LitRpcClient = unsafe { mem::transmute(cl) }; move |c: &mut Cursive| { let clrc: &mut litrpc::LitRpcClient = unsafe { mem::transmute(clp) }; // Channels. let chans: Vec<litrpc::ChanInfo> = match clrc.call_chan_list(0) { Ok(clr) => { let mut cls = clr.Channels; // Reversed because we want the newest at the top. cls.sort_by(|a, b| cmp::Ord::cmp(&b.LastUpdate, &a.LastUpdate)); cls }, Err(err) => panic!("{:?}", err) };
identifier_body
main.rs
extern crate chrono; #[macro_use] extern crate clap; extern crate cursive; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; use std::cmp; use std::panic; use chrono::prelude::*; use cursive::Cursive; use cursive::direction::*; use cursive::event::*; use cursive::theme::*; use cursive::view::*; use cursive::views::*; mod litrpc; fn main() { let matches = clap_app!(lit_af_rs => (version: "0.1.0") (author: "Trey Del Bonis <[email protected]>") (about: "CLI client for Lit") (@arg a: +takes_value "Address to connect to. Default: localhost") (@arg p: +takes_value "Port to connect to lit to. Default: idk yet lmao") ).get_matches(); // TODO Make these optional. let addr = matches.value_of("a").unwrap_or("localhost"); let port = match matches.value_of("p").map(str::parse) { Some(Ok(p)) => p, Some(Err(_)) => panic!("port is not a number"), None => 12345 // FIXME }; println!("addr: {}, port {}", addr, port); match panic::catch_unwind(|| run_ui(addr, port)) { Ok(_) => {}, // we're ok Err(_) => run_bsod() } } fn run_ui(addr: &str, port: u16) { let mut client = Box::new(litrpc::LitRpcClient::new(addr, port)); let mut layout = LinearLayout::new(Orientation::Horizontal); let mut c_view = LinearLayout::new(Orientation::Vertical); c_view.add_child(TextView::new("Channels")); layout.add_child( BoxView::new( SizeConstraint::Full, SizeConstraint::Full, IdView::new("chans", Panel::new(c_view)))); let mut right_view = LinearLayout::new(Orientation::Vertical); // Balances let mut bal_view = LinearLayout::new(Orientation::Vertical); bal_view.add_child(TextView::new("Balances")); right_view.add_child( BoxView::new( SizeConstraint::Full, SizeConstraint::Full, IdView::new("bals", Panel::new(bal_view))) .squishable()); // Txos let mut txo_view = LinearLayout::new(Orientation::Vertical); txo_view.add_child(TextView::new("Txos")); right_view.add_child( BoxView::new( SizeConstraint::Full, SizeConstraint::Full, IdView::new("txos", Panel::new(txo_view))) .squishable()); layout.add_child(BoxView::new(SizeConstraint::Full, SizeConstraint::Full, right_view)); let mut siv = Cursive::new(); siv.add_layer(BoxView::new(SizeConstraint::Full, SizeConstraint::Full, layout)); siv.set_theme(load_theme(include_str!("ncurses_theme.toml")).unwrap()); siv.add_global_callback(Event::Refresh, make_update_ui_callback_with_client(&mut client)); siv.set_fps(1); siv.run() } fn run_bsod() { let mut siv = Cursive::new(); let d = Dialog::around(TextView::new("RS-AF has encountered an error and needs to exit.")) .title("Panic") .button("Exit", |s| s.quit()); siv.add_layer(d); siv.run(); } fn generate_view_for_chan(chan: litrpc::ChanInfo) -> impl View { let ndt = NaiveDateTime::from_timestamp( (chan.LastUpdate / 1000) as i64, ((chan.LastUpdate % 1000) * 1000) as u32); let dt: DateTime<Utc> = DateTime::from_utc(ndt, chrono::Utc); let mut data = LinearLayout::new(Orientation::Vertical); data.add_child(TextView::new(format!("Channel # {}", chan.CIdx))); data.add_child(TextView::new(format!("Outpoint: {}", chan.OutPoint))); data.add_child(TextView::new(format!("Peer: {}", chan.PeerIdx))); data.add_child(TextView::new(format!("Coin Type: {}", chan.CoinType))); data.add_child(TextView::new(format!("Last Activity: {}", dt.to_rfc3339()))); data.add_child(DummyView); data.add_child(TextView::new(format!("Balance: {}/{}", chan.MyBalance, chan.Capacity))); let mut bar = ProgressBar::new().range(0, chan.Capacity as usize); bar.set_value(chan.MyBalance as usize); data.add_child(bar); let cbox = BoxView::new(SizeConstraint::Full, SizeConstraint::AtLeast(5), data); Panel::new(cbox) } fn generate_view_for_bal(bal: &litrpc::CoinBalInfo, addrs: Vec<String>) -> impl View { let mut data = LinearLayout::new(Orientation::Vertical); let grand_total = bal.ChanTotal + bal.TxoTotal; let bal_str = format!( " Funds: chans {} + txos {} = total {} (sat)", bal.ChanTotal, bal.TxoTotal, grand_total); data.add_child(TextView::new(format!("- Type {} @ height {}", bal.CoinType, bal.SyncHeight))); data.add_child(TextView::new(bal_str)); addrs.into_iter() .map(|a| format!(" - {}", a)) .map(TextView::new) .for_each(|l| data.add_child(l)); data.add_child(DummyView); data } fn generate_view_for_txo(txo: litrpc::TxoInfo) -> impl View { // TODO Make this prettier let strs = vec![ ("Outpoint", txo.OutPoint), ("Amount", format!("{}", txo.Amt)), ("Height", format!("{}", txo.Height)), ("Coin Type", txo.CoinType), ("Key Path", txo.KeyPath) ]; let mut data = LinearLayout::new(Orientation::Vertical); for (k, v) in strs { data.add_child(TextView::new(format!("{}: {}", k, v))); } let cbox = BoxView::new(SizeConstraint::Full, SizeConstraint::Free, data); Panel::new(cbox) } fn make_update_ui_callback_with_client(cl: &mut litrpc::LitRpcClient) -> impl Fn(&mut Cursive) { use std::mem; let clp: *mut litrpc::LitRpcClient = unsafe { mem::transmute(cl) }; move |c: &mut Cursive| { let clrc: &mut litrpc::LitRpcClient = unsafe { mem::transmute(clp) }; // Channels. let chans: Vec<litrpc::ChanInfo> = match clrc.call_chan_list(0) { Ok(clr) => { let mut cls = clr.Channels; // Reversed because we want the newest at the top. cls.sort_by(|a, b| cmp::Ord::cmp(&b.LastUpdate, &a.LastUpdate)); cls }, Err(err) => panic!("{:?}", err) }; c.call_on_id("chans", |cpan: &mut Panel<LinearLayout>| { let mut c_view = LinearLayout::new(Orientation::Vertical); c_view.add_child(TextView::new("Channels")); chans.into_iter() .map(generate_view_for_chan) .for_each(|e| c_view.add_child(e)); *cpan.get_inner_mut() = c_view; }); // Bals let bals: Vec<litrpc::CoinBalInfo> = match clrc.call_bal() { Ok(br) => { let mut bals = br.Balances; bals.sort_by(|a, b| cmp::Ord::cmp(&a.CoinType, &b.CoinType)); bals }, Err(err) => panic!("{:?}", err) }; // Addrs let addrs: Vec<(u32, String)> = match clrc.call_get_addresses() { Ok(ar) =>
, Err(err) => panic!("{:?}", err) }; c.call_on_id("bals", |balpan: &mut Panel<LinearLayout>| { let mut bal_view = LinearLayout::new(Orientation::Vertical); bal_view.add_child(TextView::new("Balances")); bal_view.add_child(DummyView); bals.into_iter() .map(|b| generate_view_for_bal( &b, addrs.clone().into_iter() .filter(|(t, _)| *t == b.CoinType) .map(|(_, a)| a) .collect())) .for_each(|e| bal_view.add_child(e)); *balpan.get_inner_mut() = bal_view; }); // Txos let txos: Vec<litrpc::TxoInfo> = match clrc.call_get_txo_list() { Ok(txr) => txr.Txos, Err(err) => { eprintln!("error: {:?}", err); Vec::new() } }; c.call_on_id("txos", |txopan: &mut Panel<LinearLayout>| { let mut txo_view = LinearLayout::new(Orientation::Vertical); txo_view.add_child(TextView::new("Txos")); txos.into_iter() .map(generate_view_for_txo) .for_each(|e| txo_view.add_child(e)); *txopan.get_inner_mut() = txo_view; }); } }
{ let mut addrs: Vec<(u32, String)> = ar.CoinTypes.into_iter() .zip(ar.WitAddresses.into_iter()) .collect(); addrs.sort_by(|a, b| match cmp::Ord::cmp(&a.0, &b.0) { cmp::Ordering::Equal => cmp::Ord::cmp(&a.1, &b.1), o => o }); addrs }
conditional_block
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use consensus_types::block::Block; use diem_crypto::HashValue; use diem_types::transaction::Transaction; mod execution_correctness; mod execution_correctness_manager; mod local; mod process; mod remote_service; mod serializer; mod thread; pub use crate::{ execution_correctness::ExecutionCorrectness, execution_correctness_manager::ExecutionCorrectnessManager, process::Process, }; #[cfg(test)] mod tests; fn
(block: &Block) -> (HashValue, Vec<Transaction>) { let id = block.id(); let mut transactions = vec![Transaction::BlockMetadata(block.into())]; transactions.extend( block .payload() .unwrap_or(&vec![]) .iter() .map(|txn| Transaction::UserTransaction(txn.clone())), ); (id, transactions) }
id_and_transactions_from_block
identifier_name
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use consensus_types::block::Block; use diem_crypto::HashValue; use diem_types::transaction::Transaction; mod execution_correctness; mod execution_correctness_manager; mod local; mod process; mod remote_service; mod serializer; mod thread; pub use crate::{ execution_correctness::ExecutionCorrectness, execution_correctness_manager::ExecutionCorrectnessManager, process::Process, }; #[cfg(test)] mod tests; fn id_and_transactions_from_block(block: &Block) -> (HashValue, Vec<Transaction>)
{ let id = block.id(); let mut transactions = vec![Transaction::BlockMetadata(block.into())]; transactions.extend( block .payload() .unwrap_or(&vec![]) .iter() .map(|txn| Transaction::UserTransaction(txn.clone())), ); (id, transactions) }
identifier_body
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use consensus_types::block::Block; use diem_crypto::HashValue; use diem_types::transaction::Transaction;
mod remote_service; mod serializer; mod thread; pub use crate::{ execution_correctness::ExecutionCorrectness, execution_correctness_manager::ExecutionCorrectnessManager, process::Process, }; #[cfg(test)] mod tests; fn id_and_transactions_from_block(block: &Block) -> (HashValue, Vec<Transaction>) { let id = block.id(); let mut transactions = vec![Transaction::BlockMetadata(block.into())]; transactions.extend( block .payload() .unwrap_or(&vec![]) .iter() .map(|txn| Transaction::UserTransaction(txn.clone())), ); (id, transactions) }
mod execution_correctness; mod execution_correctness_manager; mod local; mod process;
random_line_split
closures.rs
// build-fail // compile-flags:-Zpolymorphize=on #![feature(generic_const_exprs, rustc_attrs)] //~^ WARN the feature `generic_const_exprs` is incomplete // This test checks that the polymorphization analysis correctly detects unused const // parameters in closures. // Function doesn't have any generic parameters to be unused. #[rustc_polymorphize_error] pub fn no_parameters() { let _ = || {}; } // Function has an unused generic parameter in parent and closure. #[rustc_polymorphize_error] pub fn unused<const T: usize>() -> usize
// Function has an unused generic parameter in closure, but not in parent. #[rustc_polymorphize_error] pub fn used_parent<const T: usize>() -> usize { let x: usize = T; let add_one = |x: usize| x + 1; //~^ ERROR item has unused generic parameters x + add_one(3) } // Function uses generic parameter in value of a binding in closure. #[rustc_polymorphize_error] pub fn used_binding<const T: usize>() -> usize { let x = || { let y: usize = T; y }; x() } // Closure uses a value as an upvar, which used the generic parameter. #[rustc_polymorphize_error] pub fn unused_upvar<const T: usize>() -> usize { let x: usize = T; let y = || x; //~^ ERROR item has unused generic parameters y() } // Closure uses generic parameter in substitutions to another function. #[rustc_polymorphize_error] pub fn used_substs<const T: usize>() -> usize { let x = || unused::<T>(); x() } fn main() { no_parameters(); let _ = unused::<1>(); let _ = used_parent::<1>(); let _ = used_binding::<1>(); let _ = unused_upvar::<1>(); let _ = used_substs::<1>(); }
{ //~^ ERROR item has unused generic parameters let add_one = |x: usize| x + 1; //~^ ERROR item has unused generic parameters add_one(3) }
identifier_body
closures.rs
// build-fail // compile-flags:-Zpolymorphize=on #![feature(generic_const_exprs, rustc_attrs)] //~^ WARN the feature `generic_const_exprs` is incomplete // This test checks that the polymorphization analysis correctly detects unused const // parameters in closures. // Function doesn't have any generic parameters to be unused. #[rustc_polymorphize_error] pub fn no_parameters() { let _ = || {}; }
//~^ ERROR item has unused generic parameters add_one(3) } // Function has an unused generic parameter in closure, but not in parent. #[rustc_polymorphize_error] pub fn used_parent<const T: usize>() -> usize { let x: usize = T; let add_one = |x: usize| x + 1; //~^ ERROR item has unused generic parameters x + add_one(3) } // Function uses generic parameter in value of a binding in closure. #[rustc_polymorphize_error] pub fn used_binding<const T: usize>() -> usize { let x = || { let y: usize = T; y }; x() } // Closure uses a value as an upvar, which used the generic parameter. #[rustc_polymorphize_error] pub fn unused_upvar<const T: usize>() -> usize { let x: usize = T; let y = || x; //~^ ERROR item has unused generic parameters y() } // Closure uses generic parameter in substitutions to another function. #[rustc_polymorphize_error] pub fn used_substs<const T: usize>() -> usize { let x = || unused::<T>(); x() } fn main() { no_parameters(); let _ = unused::<1>(); let _ = used_parent::<1>(); let _ = used_binding::<1>(); let _ = unused_upvar::<1>(); let _ = used_substs::<1>(); }
// Function has an unused generic parameter in parent and closure. #[rustc_polymorphize_error] pub fn unused<const T: usize>() -> usize { //~^ ERROR item has unused generic parameters let add_one = |x: usize| x + 1;
random_line_split
closures.rs
// build-fail // compile-flags:-Zpolymorphize=on #![feature(generic_const_exprs, rustc_attrs)] //~^ WARN the feature `generic_const_exprs` is incomplete // This test checks that the polymorphization analysis correctly detects unused const // parameters in closures. // Function doesn't have any generic parameters to be unused. #[rustc_polymorphize_error] pub fn no_parameters() { let _ = || {}; } // Function has an unused generic parameter in parent and closure. #[rustc_polymorphize_error] pub fn
<const T: usize>() -> usize { //~^ ERROR item has unused generic parameters let add_one = |x: usize| x + 1; //~^ ERROR item has unused generic parameters add_one(3) } // Function has an unused generic parameter in closure, but not in parent. #[rustc_polymorphize_error] pub fn used_parent<const T: usize>() -> usize { let x: usize = T; let add_one = |x: usize| x + 1; //~^ ERROR item has unused generic parameters x + add_one(3) } // Function uses generic parameter in value of a binding in closure. #[rustc_polymorphize_error] pub fn used_binding<const T: usize>() -> usize { let x = || { let y: usize = T; y }; x() } // Closure uses a value as an upvar, which used the generic parameter. #[rustc_polymorphize_error] pub fn unused_upvar<const T: usize>() -> usize { let x: usize = T; let y = || x; //~^ ERROR item has unused generic parameters y() } // Closure uses generic parameter in substitutions to another function. #[rustc_polymorphize_error] pub fn used_substs<const T: usize>() -> usize { let x = || unused::<T>(); x() } fn main() { no_parameters(); let _ = unused::<1>(); let _ = used_parent::<1>(); let _ = used_binding::<1>(); let _ = unused_upvar::<1>(); let _ = used_substs::<1>(); }
unused
identifier_name
kill-setuid.rs
extern crate libc; extern crate seccomp_sys; fn main()
assert!(seccomp_sys::seccomp_load(context) == 0); assert!(libc::setuid(1000) == 0); /* process would be killed here */ } }
{ unsafe { let context = seccomp_sys::seccomp_init(seccomp_sys::SCMP_ACT_ALLOW); let comparator = seccomp_sys::scmp_arg_cmp { arg: 0, op: seccomp_sys::scmp_compare::SCMP_CMP_EQ, datum_a: 1000, datum_b: 0, }; /* arg[0] equals 1000 */ let syscall_number = 105; /* setuid on x86_64 */ assert!( seccomp_sys::seccomp_rule_add( context, seccomp_sys::SCMP_ACT_KILL, syscall_number, 1, comparator ) == 0 );
identifier_body
kill-setuid.rs
extern crate libc; extern crate seccomp_sys; fn
() { unsafe { let context = seccomp_sys::seccomp_init(seccomp_sys::SCMP_ACT_ALLOW); let comparator = seccomp_sys::scmp_arg_cmp { arg: 0, op: seccomp_sys::scmp_compare::SCMP_CMP_EQ, datum_a: 1000, datum_b: 0, }; /* arg[0] equals 1000 */ let syscall_number = 105; /* setuid on x86_64 */ assert!( seccomp_sys::seccomp_rule_add( context, seccomp_sys::SCMP_ACT_KILL, syscall_number, 1, comparator ) == 0 ); assert!(seccomp_sys::seccomp_load(context) == 0); assert!(libc::setuid(1000) == 0); /* process would be killed here */ } }
main
identifier_name
kill-setuid.rs
extern crate libc; extern crate seccomp_sys; fn main() { unsafe {
let comparator = seccomp_sys::scmp_arg_cmp { arg: 0, op: seccomp_sys::scmp_compare::SCMP_CMP_EQ, datum_a: 1000, datum_b: 0, }; /* arg[0] equals 1000 */ let syscall_number = 105; /* setuid on x86_64 */ assert!( seccomp_sys::seccomp_rule_add( context, seccomp_sys::SCMP_ACT_KILL, syscall_number, 1, comparator ) == 0 ); assert!(seccomp_sys::seccomp_load(context) == 0); assert!(libc::setuid(1000) == 0); /* process would be killed here */ } }
let context = seccomp_sys::seccomp_init(seccomp_sys::SCMP_ACT_ALLOW);
random_line_split
lib.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #![forbid(unsafe_code)] #![deny( non_camel_case_types, non_snake_case, path_statements, trivial_numeric_casts, unstable_features, unused_allocation, unused_import_braces, unused_imports, unused_must_use, unused_mut, unused_qualifications, while_true, )] extern crate clap; #[macro_use] extern crate log; #[macro_use] extern crate anyhow; extern crate toml_query; extern crate resiter; extern crate libimagentryannotation; extern crate libimagentryedit; extern crate libimagerror; extern crate libimagrt; extern crate libimagstore; extern crate libimagutil; extern crate libimagentrylink; use std::io::Write; use anyhow::Error; use anyhow::Result; use anyhow::Context; use resiter::IterInnerOkOrElse; use resiter::AndThen; use resiter::Map; use toml_query::read::TomlValueReadTypeExt; use clap::App; use libimagentryannotation::annotateable::*; use libimagentryannotation::annotation_fetcher::*; use libimagentryedit::edit::*; use libimagerror::errors::Error as EM; use libimagrt::runtime::Runtime; use libimagrt::application::ImagApplication; use libimagstore::store::FileLockEntry; use libimagstore::iter::get::StoreIdGetIteratorExtension; use libimagentrylink::linkable::Linkable; use libimagrt::iter::ReportTouchedResultEntry; mod ui; pub enum ImagAnnotate {} impl ImagApplication for ImagAnnotate { fn run(rt: Runtime) -> Result<()> { match rt.cli().subcommand_name().ok_or_else(|| anyhow!("No command called"))? { "add" => add(&rt), "remove" => remove(&rt), "list" => list(&rt), other => { debug!("Unknown command"); if rt.handle_unknown_subcommand("imag-annotation", other, rt.cli())?.success() { Ok(()) } else { Err(anyhow!("Failed to handle unknown subcommand")) } }, } } fn build_cli<'a>(app: App<'a, 'a>) -> App<'a, 'a> { ui::build_ui(app) } fn name() -> &'static str { env!("CARGO_PKG_NAME") }
} fn version() -> &'static str { env!("CARGO_PKG_VERSION") } } fn add(rt: &Runtime) -> Result<()> { let scmd = rt.cli().subcommand_matches("add").unwrap(); // safed by main() let mut ids = rt .ids::<crate::ui::PathProvider>() .context("No StoreId supplied")? .ok_or_else(|| anyhow!("No ids supplied"))? .into_iter(); if let Some(first) = ids.next() { let mut annotation = rt.store() .get(first.clone())? .ok_or_else(|| EM::EntryNotFound(first.local_display_string()))? .annotate(rt.store())?; annotation.edit_content(&rt)?; rt.report_touched(&first)?; // report first one first ids.map(Ok).into_get_iter(rt.store()) .map_inner_ok_or_else(|| anyhow!("Did not find one entry")) .and_then_ok(|mut entry| entry.add_link(&mut annotation).map(|_| entry)) .map_report_touched(&rt) .map_ok(|_| ()) .collect::<Result<Vec<_>>>()?; if!scmd.is_present("dont-print-name") { if let Some(annotation_id) = annotation .get_header() .read_string("annotation.name")? { writeln!(rt.stdout(), "Name of the annotation: {}", annotation_id)?; } else { Err(anyhow!("Unnamed annotation: {:?}", annotation.get_location())) .context("This is most likely a BUG, please report!")?; } } rt.report_touched(annotation.get_location())?; } else { debug!("No entries to annotate"); } Ok(()) } fn remove(rt: &Runtime) -> Result<()> { let scmd = rt.cli().subcommand_matches("remove").unwrap(); // safed by main() let annotation_name = scmd.value_of("annotation_name").unwrap(); // safed by clap let delete = scmd.is_present("delete-annotation"); rt.ids::<crate::ui::PathProvider>() .context("No ids supplied")? .ok_or_else(|| anyhow!("No ids supplied"))? .into_iter() .map(|id| { let mut entry = rt.store() .get(id.clone())? .ok_or_else(|| EM::EntryNotFound(id.local_display_string()))?; let annotation = entry.denotate(rt.store(), annotation_name)?; if delete { debug!("Deleting annotation object"); if let Some(an) = annotation { let loc = an.get_location().clone(); drop(an); rt.store().delete(loc)?; } else { warn!("Not having annotation object, cannot delete!"); } } else { debug!("Not deleting annotation object"); } rt.report_touched(entry.get_location()).map_err(Error::from) }) .collect() } fn list(rt: &Runtime) -> Result<()> { let scmd = rt.cli().subcommand_matches("list").unwrap(); // safed by clap let with_text = scmd.is_present("list-with-text"); let ids = rt .ids::<crate::ui::PathProvider>() .context("No ids supplied")? .ok_or_else(|| anyhow!("No ids supplied"))?; if ids.is_empty() { ids.into_iter() .map(|id| -> Result<_> { let lds = id.local_display_string(); Ok(rt.store() .get(id)? .ok_or_else(|| EM::EntryNotFound(lds))? .annotations()? .into_get_iter(rt.store()) .map(|el| el.and_then(|o| o.ok_or_else(|| anyhow!("Cannot find entry")))) .enumerate() .map(|(i, entry)| entry.and_then(|e| list_annotation(&rt, i, &e, with_text).map(|_| e))) .map_report_touched(&rt) .map_ok(|_| ()) .collect()) }) .flatten() .collect() } else { // ids.len() == 0 // show them all rt.store() .all_annotations()? .into_get_iter() .map(|el| el.and_then(|opt| opt.ok_or_else(|| anyhow!("Cannot find entry")))) .enumerate() .map(|(i, entry)| entry.and_then(|e| list_annotation(&rt, i, &e, with_text).map(|_| e))) .map_report_touched(&rt) .map_ok(|_| ()) .collect() } } fn list_annotation<'a>(rt: &Runtime, i: usize, a: &FileLockEntry<'a>, with_text: bool) -> Result<()> { if with_text { writeln!(rt.stdout(), "--- {i: >5} | {id}\n{text}\n\n", i = i, id = a.get_location(), text = a.get_content()) } else { writeln!(rt.stdout(), "{: >5} | {}", i, a.get_location()) }.map_err(Error::from) }
fn description() -> &'static str { "Add annotations to entries"
random_line_split
lib.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #![forbid(unsafe_code)] #![deny( non_camel_case_types, non_snake_case, path_statements, trivial_numeric_casts, unstable_features, unused_allocation, unused_import_braces, unused_imports, unused_must_use, unused_mut, unused_qualifications, while_true, )] extern crate clap; #[macro_use] extern crate log; #[macro_use] extern crate anyhow; extern crate toml_query; extern crate resiter; extern crate libimagentryannotation; extern crate libimagentryedit; extern crate libimagerror; extern crate libimagrt; extern crate libimagstore; extern crate libimagutil; extern crate libimagentrylink; use std::io::Write; use anyhow::Error; use anyhow::Result; use anyhow::Context; use resiter::IterInnerOkOrElse; use resiter::AndThen; use resiter::Map; use toml_query::read::TomlValueReadTypeExt; use clap::App; use libimagentryannotation::annotateable::*; use libimagentryannotation::annotation_fetcher::*; use libimagentryedit::edit::*; use libimagerror::errors::Error as EM; use libimagrt::runtime::Runtime; use libimagrt::application::ImagApplication; use libimagstore::store::FileLockEntry; use libimagstore::iter::get::StoreIdGetIteratorExtension; use libimagentrylink::linkable::Linkable; use libimagrt::iter::ReportTouchedResultEntry; mod ui; pub enum ImagAnnotate {} impl ImagApplication for ImagAnnotate { fn run(rt: Runtime) -> Result<()> { match rt.cli().subcommand_name().ok_or_else(|| anyhow!("No command called"))? { "add" => add(&rt), "remove" => remove(&rt), "list" => list(&rt), other => { debug!("Unknown command"); if rt.handle_unknown_subcommand("imag-annotation", other, rt.cli())?.success() { Ok(()) } else { Err(anyhow!("Failed to handle unknown subcommand")) } }, } } fn build_cli<'a>(app: App<'a, 'a>) -> App<'a, 'a> { ui::build_ui(app) } fn name() -> &'static str { env!("CARGO_PKG_NAME") } fn description() -> &'static str { "Add annotations to entries" } fn version() -> &'static str { env!("CARGO_PKG_VERSION") } } fn add(rt: &Runtime) -> Result<()> { let scmd = rt.cli().subcommand_matches("add").unwrap(); // safed by main() let mut ids = rt .ids::<crate::ui::PathProvider>() .context("No StoreId supplied")? .ok_or_else(|| anyhow!("No ids supplied"))? .into_iter(); if let Some(first) = ids.next() { let mut annotation = rt.store() .get(first.clone())? .ok_or_else(|| EM::EntryNotFound(first.local_display_string()))? .annotate(rt.store())?; annotation.edit_content(&rt)?; rt.report_touched(&first)?; // report first one first ids.map(Ok).into_get_iter(rt.store()) .map_inner_ok_or_else(|| anyhow!("Did not find one entry")) .and_then_ok(|mut entry| entry.add_link(&mut annotation).map(|_| entry)) .map_report_touched(&rt) .map_ok(|_| ()) .collect::<Result<Vec<_>>>()?; if!scmd.is_present("dont-print-name") { if let Some(annotation_id) = annotation .get_header() .read_string("annotation.name")? { writeln!(rt.stdout(), "Name of the annotation: {}", annotation_id)?; } else { Err(anyhow!("Unnamed annotation: {:?}", annotation.get_location())) .context("This is most likely a BUG, please report!")?; } } rt.report_touched(annotation.get_location())?; } else
Ok(()) } fn remove(rt: &Runtime) -> Result<()> { let scmd = rt.cli().subcommand_matches("remove").unwrap(); // safed by main() let annotation_name = scmd.value_of("annotation_name").unwrap(); // safed by clap let delete = scmd.is_present("delete-annotation"); rt.ids::<crate::ui::PathProvider>() .context("No ids supplied")? .ok_or_else(|| anyhow!("No ids supplied"))? .into_iter() .map(|id| { let mut entry = rt.store() .get(id.clone())? .ok_or_else(|| EM::EntryNotFound(id.local_display_string()))?; let annotation = entry.denotate(rt.store(), annotation_name)?; if delete { debug!("Deleting annotation object"); if let Some(an) = annotation { let loc = an.get_location().clone(); drop(an); rt.store().delete(loc)?; } else { warn!("Not having annotation object, cannot delete!"); } } else { debug!("Not deleting annotation object"); } rt.report_touched(entry.get_location()).map_err(Error::from) }) .collect() } fn list(rt: &Runtime) -> Result<()> { let scmd = rt.cli().subcommand_matches("list").unwrap(); // safed by clap let with_text = scmd.is_present("list-with-text"); let ids = rt .ids::<crate::ui::PathProvider>() .context("No ids supplied")? .ok_or_else(|| anyhow!("No ids supplied"))?; if ids.is_empty() { ids.into_iter() .map(|id| -> Result<_> { let lds = id.local_display_string(); Ok(rt.store() .get(id)? .ok_or_else(|| EM::EntryNotFound(lds))? .annotations()? .into_get_iter(rt.store()) .map(|el| el.and_then(|o| o.ok_or_else(|| anyhow!("Cannot find entry")))) .enumerate() .map(|(i, entry)| entry.and_then(|e| list_annotation(&rt, i, &e, with_text).map(|_| e))) .map_report_touched(&rt) .map_ok(|_| ()) .collect()) }) .flatten() .collect() } else { // ids.len() == 0 // show them all rt.store() .all_annotations()? .into_get_iter() .map(|el| el.and_then(|opt| opt.ok_or_else(|| anyhow!("Cannot find entry")))) .enumerate() .map(|(i, entry)| entry.and_then(|e| list_annotation(&rt, i, &e, with_text).map(|_| e))) .map_report_touched(&rt) .map_ok(|_| ()) .collect() } } fn list_annotation<'a>(rt: &Runtime, i: usize, a: &FileLockEntry<'a>, with_text: bool) -> Result<()> { if with_text { writeln!(rt.stdout(), "--- {i: >5} | {id}\n{text}\n\n", i = i, id = a.get_location(), text = a.get_content()) } else { writeln!(rt.stdout(), "{: >5} | {}", i, a.get_location()) }.map_err(Error::from) }
{ debug!("No entries to annotate"); }
conditional_block
lib.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #![forbid(unsafe_code)] #![deny( non_camel_case_types, non_snake_case, path_statements, trivial_numeric_casts, unstable_features, unused_allocation, unused_import_braces, unused_imports, unused_must_use, unused_mut, unused_qualifications, while_true, )] extern crate clap; #[macro_use] extern crate log; #[macro_use] extern crate anyhow; extern crate toml_query; extern crate resiter; extern crate libimagentryannotation; extern crate libimagentryedit; extern crate libimagerror; extern crate libimagrt; extern crate libimagstore; extern crate libimagutil; extern crate libimagentrylink; use std::io::Write; use anyhow::Error; use anyhow::Result; use anyhow::Context; use resiter::IterInnerOkOrElse; use resiter::AndThen; use resiter::Map; use toml_query::read::TomlValueReadTypeExt; use clap::App; use libimagentryannotation::annotateable::*; use libimagentryannotation::annotation_fetcher::*; use libimagentryedit::edit::*; use libimagerror::errors::Error as EM; use libimagrt::runtime::Runtime; use libimagrt::application::ImagApplication; use libimagstore::store::FileLockEntry; use libimagstore::iter::get::StoreIdGetIteratorExtension; use libimagentrylink::linkable::Linkable; use libimagrt::iter::ReportTouchedResultEntry; mod ui; pub enum ImagAnnotate {} impl ImagApplication for ImagAnnotate { fn run(rt: Runtime) -> Result<()>
fn build_cli<'a>(app: App<'a, 'a>) -> App<'a, 'a> { ui::build_ui(app) } fn name() -> &'static str { env!("CARGO_PKG_NAME") } fn description() -> &'static str { "Add annotations to entries" } fn version() -> &'static str { env!("CARGO_PKG_VERSION") } } fn add(rt: &Runtime) -> Result<()> { let scmd = rt.cli().subcommand_matches("add").unwrap(); // safed by main() let mut ids = rt .ids::<crate::ui::PathProvider>() .context("No StoreId supplied")? .ok_or_else(|| anyhow!("No ids supplied"))? .into_iter(); if let Some(first) = ids.next() { let mut annotation = rt.store() .get(first.clone())? .ok_or_else(|| EM::EntryNotFound(first.local_display_string()))? .annotate(rt.store())?; annotation.edit_content(&rt)?; rt.report_touched(&first)?; // report first one first ids.map(Ok).into_get_iter(rt.store()) .map_inner_ok_or_else(|| anyhow!("Did not find one entry")) .and_then_ok(|mut entry| entry.add_link(&mut annotation).map(|_| entry)) .map_report_touched(&rt) .map_ok(|_| ()) .collect::<Result<Vec<_>>>()?; if!scmd.is_present("dont-print-name") { if let Some(annotation_id) = annotation .get_header() .read_string("annotation.name")? { writeln!(rt.stdout(), "Name of the annotation: {}", annotation_id)?; } else { Err(anyhow!("Unnamed annotation: {:?}", annotation.get_location())) .context("This is most likely a BUG, please report!")?; } } rt.report_touched(annotation.get_location())?; } else { debug!("No entries to annotate"); } Ok(()) } fn remove(rt: &Runtime) -> Result<()> { let scmd = rt.cli().subcommand_matches("remove").unwrap(); // safed by main() let annotation_name = scmd.value_of("annotation_name").unwrap(); // safed by clap let delete = scmd.is_present("delete-annotation"); rt.ids::<crate::ui::PathProvider>() .context("No ids supplied")? .ok_or_else(|| anyhow!("No ids supplied"))? .into_iter() .map(|id| { let mut entry = rt.store() .get(id.clone())? .ok_or_else(|| EM::EntryNotFound(id.local_display_string()))?; let annotation = entry.denotate(rt.store(), annotation_name)?; if delete { debug!("Deleting annotation object"); if let Some(an) = annotation { let loc = an.get_location().clone(); drop(an); rt.store().delete(loc)?; } else { warn!("Not having annotation object, cannot delete!"); } } else { debug!("Not deleting annotation object"); } rt.report_touched(entry.get_location()).map_err(Error::from) }) .collect() } fn list(rt: &Runtime) -> Result<()> { let scmd = rt.cli().subcommand_matches("list").unwrap(); // safed by clap let with_text = scmd.is_present("list-with-text"); let ids = rt .ids::<crate::ui::PathProvider>() .context("No ids supplied")? .ok_or_else(|| anyhow!("No ids supplied"))?; if ids.is_empty() { ids.into_iter() .map(|id| -> Result<_> { let lds = id.local_display_string(); Ok(rt.store() .get(id)? .ok_or_else(|| EM::EntryNotFound(lds))? .annotations()? .into_get_iter(rt.store()) .map(|el| el.and_then(|o| o.ok_or_else(|| anyhow!("Cannot find entry")))) .enumerate() .map(|(i, entry)| entry.and_then(|e| list_annotation(&rt, i, &e, with_text).map(|_| e))) .map_report_touched(&rt) .map_ok(|_| ()) .collect()) }) .flatten() .collect() } else { // ids.len() == 0 // show them all rt.store() .all_annotations()? .into_get_iter() .map(|el| el.and_then(|opt| opt.ok_or_else(|| anyhow!("Cannot find entry")))) .enumerate() .map(|(i, entry)| entry.and_then(|e| list_annotation(&rt, i, &e, with_text).map(|_| e))) .map_report_touched(&rt) .map_ok(|_| ()) .collect() } } fn list_annotation<'a>(rt: &Runtime, i: usize, a: &FileLockEntry<'a>, with_text: bool) -> Result<()> { if with_text { writeln!(rt.stdout(), "--- {i: >5} | {id}\n{text}\n\n", i = i, id = a.get_location(), text = a.get_content()) } else { writeln!(rt.stdout(), "{: >5} | {}", i, a.get_location()) }.map_err(Error::from) }
{ match rt.cli().subcommand_name().ok_or_else(|| anyhow!("No command called"))? { "add" => add(&rt), "remove" => remove(&rt), "list" => list(&rt), other => { debug!("Unknown command"); if rt.handle_unknown_subcommand("imag-annotation", other, rt.cli())?.success() { Ok(()) } else { Err(anyhow!("Failed to handle unknown subcommand")) } }, } }
identifier_body
lib.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #![forbid(unsafe_code)] #![deny( non_camel_case_types, non_snake_case, path_statements, trivial_numeric_casts, unstable_features, unused_allocation, unused_import_braces, unused_imports, unused_must_use, unused_mut, unused_qualifications, while_true, )] extern crate clap; #[macro_use] extern crate log; #[macro_use] extern crate anyhow; extern crate toml_query; extern crate resiter; extern crate libimagentryannotation; extern crate libimagentryedit; extern crate libimagerror; extern crate libimagrt; extern crate libimagstore; extern crate libimagutil; extern crate libimagentrylink; use std::io::Write; use anyhow::Error; use anyhow::Result; use anyhow::Context; use resiter::IterInnerOkOrElse; use resiter::AndThen; use resiter::Map; use toml_query::read::TomlValueReadTypeExt; use clap::App; use libimagentryannotation::annotateable::*; use libimagentryannotation::annotation_fetcher::*; use libimagentryedit::edit::*; use libimagerror::errors::Error as EM; use libimagrt::runtime::Runtime; use libimagrt::application::ImagApplication; use libimagstore::store::FileLockEntry; use libimagstore::iter::get::StoreIdGetIteratorExtension; use libimagentrylink::linkable::Linkable; use libimagrt::iter::ReportTouchedResultEntry; mod ui; pub enum ImagAnnotate {} impl ImagApplication for ImagAnnotate { fn run(rt: Runtime) -> Result<()> { match rt.cli().subcommand_name().ok_or_else(|| anyhow!("No command called"))? { "add" => add(&rt), "remove" => remove(&rt), "list" => list(&rt), other => { debug!("Unknown command"); if rt.handle_unknown_subcommand("imag-annotation", other, rt.cli())?.success() { Ok(()) } else { Err(anyhow!("Failed to handle unknown subcommand")) } }, } } fn build_cli<'a>(app: App<'a, 'a>) -> App<'a, 'a> { ui::build_ui(app) } fn name() -> &'static str { env!("CARGO_PKG_NAME") } fn
() -> &'static str { "Add annotations to entries" } fn version() -> &'static str { env!("CARGO_PKG_VERSION") } } fn add(rt: &Runtime) -> Result<()> { let scmd = rt.cli().subcommand_matches("add").unwrap(); // safed by main() let mut ids = rt .ids::<crate::ui::PathProvider>() .context("No StoreId supplied")? .ok_or_else(|| anyhow!("No ids supplied"))? .into_iter(); if let Some(first) = ids.next() { let mut annotation = rt.store() .get(first.clone())? .ok_or_else(|| EM::EntryNotFound(first.local_display_string()))? .annotate(rt.store())?; annotation.edit_content(&rt)?; rt.report_touched(&first)?; // report first one first ids.map(Ok).into_get_iter(rt.store()) .map_inner_ok_or_else(|| anyhow!("Did not find one entry")) .and_then_ok(|mut entry| entry.add_link(&mut annotation).map(|_| entry)) .map_report_touched(&rt) .map_ok(|_| ()) .collect::<Result<Vec<_>>>()?; if!scmd.is_present("dont-print-name") { if let Some(annotation_id) = annotation .get_header() .read_string("annotation.name")? { writeln!(rt.stdout(), "Name of the annotation: {}", annotation_id)?; } else { Err(anyhow!("Unnamed annotation: {:?}", annotation.get_location())) .context("This is most likely a BUG, please report!")?; } } rt.report_touched(annotation.get_location())?; } else { debug!("No entries to annotate"); } Ok(()) } fn remove(rt: &Runtime) -> Result<()> { let scmd = rt.cli().subcommand_matches("remove").unwrap(); // safed by main() let annotation_name = scmd.value_of("annotation_name").unwrap(); // safed by clap let delete = scmd.is_present("delete-annotation"); rt.ids::<crate::ui::PathProvider>() .context("No ids supplied")? .ok_or_else(|| anyhow!("No ids supplied"))? .into_iter() .map(|id| { let mut entry = rt.store() .get(id.clone())? .ok_or_else(|| EM::EntryNotFound(id.local_display_string()))?; let annotation = entry.denotate(rt.store(), annotation_name)?; if delete { debug!("Deleting annotation object"); if let Some(an) = annotation { let loc = an.get_location().clone(); drop(an); rt.store().delete(loc)?; } else { warn!("Not having annotation object, cannot delete!"); } } else { debug!("Not deleting annotation object"); } rt.report_touched(entry.get_location()).map_err(Error::from) }) .collect() } fn list(rt: &Runtime) -> Result<()> { let scmd = rt.cli().subcommand_matches("list").unwrap(); // safed by clap let with_text = scmd.is_present("list-with-text"); let ids = rt .ids::<crate::ui::PathProvider>() .context("No ids supplied")? .ok_or_else(|| anyhow!("No ids supplied"))?; if ids.is_empty() { ids.into_iter() .map(|id| -> Result<_> { let lds = id.local_display_string(); Ok(rt.store() .get(id)? .ok_or_else(|| EM::EntryNotFound(lds))? .annotations()? .into_get_iter(rt.store()) .map(|el| el.and_then(|o| o.ok_or_else(|| anyhow!("Cannot find entry")))) .enumerate() .map(|(i, entry)| entry.and_then(|e| list_annotation(&rt, i, &e, with_text).map(|_| e))) .map_report_touched(&rt) .map_ok(|_| ()) .collect()) }) .flatten() .collect() } else { // ids.len() == 0 // show them all rt.store() .all_annotations()? .into_get_iter() .map(|el| el.and_then(|opt| opt.ok_or_else(|| anyhow!("Cannot find entry")))) .enumerate() .map(|(i, entry)| entry.and_then(|e| list_annotation(&rt, i, &e, with_text).map(|_| e))) .map_report_touched(&rt) .map_ok(|_| ()) .collect() } } fn list_annotation<'a>(rt: &Runtime, i: usize, a: &FileLockEntry<'a>, with_text: bool) -> Result<()> { if with_text { writeln!(rt.stdout(), "--- {i: >5} | {id}\n{text}\n\n", i = i, id = a.get_location(), text = a.get_content()) } else { writeln!(rt.stdout(), "{: >5} | {}", i, a.get_location()) }.map_err(Error::from) }
description
identifier_name
lib.rs
// The code below is a stub. Just enough to satisfy the compiler. // In order to pass the tests you can add-to or change any of this code. use Direction::*; #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub enum Direction { North, East, South, West, } pub struct Robot { x: isize, y: isize, direction: Direction, } impl Robot { pub fn new(x: isize, y: isize, d: Direction) -> Self { Robot { x: x, y: y, direction: d, } } pub fn turn_right(self) -> Self { let new_direction = match self.direction { North => East, East => South, South => West, West => North, }; Robot::new(self.x, self.y, new_direction) } pub fn turn_left(self) -> Self { let new_direction = match self.direction { North => West, East => North, South => East, West => South, }; Robot::new(self.x, self.y, new_direction) } pub fn advance(self) -> Self
pub fn instructions(self, instructions: &str) -> Self { instructions.chars().fold(self, |accu, c| { match c { 'A' => accu.advance(), 'L' => accu.turn_left(), 'R' => accu.turn_right(), _ => unreachable!(), } }) } pub fn position(&self) -> (isize, isize) { (self.x, self.y) } pub fn direction(&self) -> &Direction { &self.direction } }
{ let (new_x, new_y) = match self.direction { North => (self.x, self.y + 1), East => (self.x + 1, self.y), South => (self.x, self.y - 1), West => (self.x - 1, self.y), }; Robot::new(new_x, new_y, self.direction) }
identifier_body
lib.rs
// The code below is a stub. Just enough to satisfy the compiler. // In order to pass the tests you can add-to or change any of this code. use Direction::*; #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub enum Direction { North, East, South, West, } pub struct Robot { x: isize, y: isize, direction: Direction, } impl Robot { pub fn new(x: isize, y: isize, d: Direction) -> Self { Robot { x: x, y: y, direction: d, } } pub fn turn_right(self) -> Self { let new_direction = match self.direction { North => East, East => South, South => West, West => North, }; Robot::new(self.x, self.y, new_direction) } pub fn turn_left(self) -> Self { let new_direction = match self.direction { North => West, East => North, South => East, West => South, }; Robot::new(self.x, self.y, new_direction) } pub fn advance(self) -> Self { let (new_x, new_y) = match self.direction { North => (self.x, self.y + 1), East => (self.x + 1, self.y), South => (self.x, self.y - 1), West => (self.x - 1, self.y), }; Robot::new(new_x, new_y, self.direction)
'A' => accu.advance(), 'L' => accu.turn_left(), 'R' => accu.turn_right(), _ => unreachable!(), } }) } pub fn position(&self) -> (isize, isize) { (self.x, self.y) } pub fn direction(&self) -> &Direction { &self.direction } }
} pub fn instructions(self, instructions: &str) -> Self { instructions.chars().fold(self, |accu, c| { match c {
random_line_split
lib.rs
// The code below is a stub. Just enough to satisfy the compiler. // In order to pass the tests you can add-to or change any of this code. use Direction::*; #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub enum Direction { North, East, South, West, } pub struct
{ x: isize, y: isize, direction: Direction, } impl Robot { pub fn new(x: isize, y: isize, d: Direction) -> Self { Robot { x: x, y: y, direction: d, } } pub fn turn_right(self) -> Self { let new_direction = match self.direction { North => East, East => South, South => West, West => North, }; Robot::new(self.x, self.y, new_direction) } pub fn turn_left(self) -> Self { let new_direction = match self.direction { North => West, East => North, South => East, West => South, }; Robot::new(self.x, self.y, new_direction) } pub fn advance(self) -> Self { let (new_x, new_y) = match self.direction { North => (self.x, self.y + 1), East => (self.x + 1, self.y), South => (self.x, self.y - 1), West => (self.x - 1, self.y), }; Robot::new(new_x, new_y, self.direction) } pub fn instructions(self, instructions: &str) -> Self { instructions.chars().fold(self, |accu, c| { match c { 'A' => accu.advance(), 'L' => accu.turn_left(), 'R' => accu.turn_right(), _ => unreachable!(), } }) } pub fn position(&self) -> (isize, isize) { (self.x, self.y) } pub fn direction(&self) -> &Direction { &self.direction } }
Robot
identifier_name
mod.rs
use super::database::{id_to_class,class_to_type}; use self::parse_ebml_number::parse_ebml_number; use self::parse_ebml_number::Result as EbmlParseNumberResult; use self::parse_ebml_number::Mode as EbmlParseNumberMode; use std::vec::Vec; use std::string::String; use std::fmt; mod parse_ebml_number; #[cfg(test)] mod test; pub mod debug; extern crate byteorder; #[derive(Eq,PartialEq,Clone)] pub struct Info { pub id : u64, pub offset : u64, pub length_including_header : Option<u64>, } /// Note: binary chunks are not related to lacing #[derive(Debug,PartialEq,Clone)] pub enum BinaryChunkStatus { Full, // this chunk is the full data of Binary element First, Middle, Last, } #[derive(Debug,PartialEq,Clone)] pub enum SimpleContent<'a> { Unsigned(u64), Signed(i64), Text(&'a str), Binary(&'a [u8], BinaryChunkStatus), Float(f64), MatroskaDate(i64), // Nanoseconds since 20010101_000000_UTC } #[derive(Debug,PartialEq,Clone)] pub enum Event<'a> { Begin(&'a Info), Data(SimpleContent<'a>), End(&'a Info), Resync, } pub trait EventsHandler { fn event(&mut self, e : Event); } #[cfg(feature="nightly")] impl<F:FnMut(Event)->()> EventsHandler for F { fn event(&mut self, e : Event) { self.call_mut((e,)) } } pub trait Parser { fn new() -> Self; fn feed_bytes<E : EventsHandler +?Sized>(&mut self, bytes : &[u8], cb: &mut E); fn force_resync(&mut self); } pub fn new () -> ParserState { self::Parser::new() } ////////////////////////////// impl fmt::Debug for Info { fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result { let cl = super::database::id_to_class(self.id); let typ = super::database::class_to_type(cl); let cldesc = match cl { super::database::Class::Unknown => format!("0x{:X}", self.id), _ => format!("{:?}", cl), }; let maybelen = match self.length_including_header { None => format!(""), Some(x) => format!(", rawlen:{}", x), }; f.write_str(format!("{}(offset:{}{})", cldesc, self.offset, maybelen).as_str()) } } enum ParserMode { Header, Data(usize, super::Type), Resync, } pub struct ParserState { accumulator : Vec<u8>, opened_elements_stack : Vec<Info>, mode : ParserMode, current_offset : u64, } #[derive(Debug,Eq,PartialEq)] enum ResultOfTryParseSomething<'a> { KeepGoing(&'a [u8]), NoMoreData, Error, } impl ParserState { fn try_resync<'a>(&mut self, buf:&'a [u8]) -> ResultOfTryParseSomething<'a> { use self::ResultOfTryParseSomething::*; if buf.len() < 4 { return NoMoreData; } let (fourbytes, _) = buf.split_at(4); let id : u32 = (fourbytes[0] as u32)*0x1000000 + (fourbytes[1] as u32) * 0x10000 + (fourbytes[2] as u32) * 0x100 + (fourbytes[3] as u32); match id { 0x1A45DFA3 | 0x18538067 | 0x1549A966 | 0x1F43B675 | 0x1654AE6B | 0x1C53BB6B | 0x1941A469 | 0x1043A770 | 0x1254C367 => { self.mode = ParserMode::Header; KeepGoing(buf) } _ =>
} } fn try_parse_element_data<'a, E : EventsHandler+?Sized>(&mut self, buf:&'a [u8], len:usize, typ : super::Type, cb: &mut E) -> ResultOfTryParseSomething<'a> { use self::ResultOfTryParseSomething::{NoMoreData,KeepGoing,Error}; use self::Event::{Data}; use self::SimpleContent:: {Unsigned, Signed, Text, Binary, Float, MatroskaDate}; use self::ParserMode; if len <= buf.len() { self.mode = ParserMode::Header; let (l,r) = buf.split_at(len); let da = match typ { super::Type::Master => panic!("Wrong way"), super::Type::Binary => Binary(l, BinaryChunkStatus::Full), super::Type::Unsigned => { let mut q : u64 = 0; let mut it = l.iter(); if l.len() > 8 { return Error; } loop { match it.next() { Some(x) => {q = q*0x100 + (*x as u64)}, None => break, } }; Unsigned(q) }, super::Type::Signed | super::Type::Date => { let mut q : i64 = 0; let mut it = l.iter(); if l.len() > 8 { return Error; } match it.next() { Some(&x) if x >= 0x80 => { q = -(x as i64) + 0x80; }, Some(&x) => { q = (x as i64); }, None => {}, } loop { match it.next() { Some(&x) => {q = q*0x100 + (x as i64)}, None => break, } }; match typ { super::Type::Signed => Signed(q), super::Type::Date => MatroskaDate(q), _ => panic!("Internal error"), } }, super::Type::TextAscii | super::Type::TextUtf8 => { use std::str::from_utf8; match from_utf8(l) { Ok(x) => Text(x), Err(_) => return Error, } }, super::Type::Float => { use self::byteorder::ReadBytesExt; use self::byteorder::BigEndian; let mut ll = l; match ll.len() { 8 => match ll.read_f64::<BigEndian>() { Ok(x) => Float(x), Err(_) => return Error, }, 4 => match ll.read_f32::<BigEndian>() { Ok(x) => Float(x as f64), Err(_) => return Error, }, 0 => Float(0.0), 10 => { error!("Error: 10-byte floats are not supported in mkv"); Binary(l, BinaryChunkStatus::Full) } _ => return Error, } } }; cb.event( Data(da) ); KeepGoing(r) } else { return NoMoreData; } } fn try_parse_element_header<'a, E:EventsHandler+?Sized>(&mut self, buf:&'a [u8], cb: &mut E) -> ResultOfTryParseSomething<'a> { use self::ResultOfTryParseSomething::{NoMoreData,KeepGoing}; use self::ResultOfTryParseSomething::Error as MyError; use self::parse_ebml_number::Result::*; use self::parse_ebml_number::Mode::*; use super::Type::{Master}; use self::Event::{Begin}; use self::ParserMode; let (r1, restbuf) = parse_ebml_number(buf, Identifier); let element_id = match r1 { Error => return MyError, NaN => return MyError, NotEnoughData => return NoMoreData, Ok(x) => x }; let (r2, restbuf2) = parse_ebml_number(restbuf, Unsigned); let element_header_size = (buf.len() - restbuf2.len()) as u64; let element_size = match r2 { Error => return MyError, NaN => None, NotEnoughData => return NoMoreData, Ok(x) => Some(x) }; let full_element_size = match element_size { None => None, Some(x) => Some(x + element_header_size), }; let cl = id_to_class(element_id); let typ = class_to_type(cl); let mut restbuf3 = restbuf2; self.mode = match typ { Master => ParserMode::Header, t => match element_size { None => ParserMode::Resync, Some(x) => ParserMode::Data(x as usize, t), } }; let el = Info{id: element_id, length_including_header: full_element_size, offset: self.current_offset}; cb.event( Begin( &el )); self.opened_elements_stack.push(el); //cb.auxilary_event( Debug (format!("element class={:?} type={:?} off={} clid={} len={:?}", // cl, typ, self.current_offset, element_id, element_size ))); KeepGoing(restbuf3) } fn close_expired_elements<'a, E:EventsHandler+?Sized>(&mut self, cb: &mut E) { use self::Event::{End}; let mut number_of_elements_to_remove = 0; for i in self.opened_elements_stack.iter().rev() { let retain = match i.length_including_header { None => true, Some(l) => i.offset + l > self.current_offset }; // println!("dr {:?} {} -> {}", i, self.current_offset, retain); if retain { break; } else { number_of_elements_to_remove += 1; } } { let mut j = 0; for i in self.opened_elements_stack.iter().rev() { j += 1; if j > number_of_elements_to_remove { break; } // println!("sending end {:?}", i); cb.event (End(i)); } } let newlen = self.opened_elements_stack.len() - number_of_elements_to_remove; self.opened_elements_stack.truncate(newlen); } fn feed_bytes_1<'a, 'b, E : EventsHandler +?Sized>(&mut self, buf : &'a [u8], cb: &'b mut E) -> Option<&'a [u8]> { use self::ResultOfTryParseSomething::*; use self::ParserMode::*; let r = match self.mode { Resync => self.try_resync(buf), Header => self.try_parse_element_header(buf, cb), Data(x, t) => self.try_parse_element_data(buf, x, t, cb), }; //cb.log( format!("try_parse_something={:?}", r)); let newbuf = match r { NoMoreData => return None, Error => {self.mode = ParserMode::Resync; cb.event(self::Event::Resync); buf}, KeepGoing(rest) => rest }; self.current_offset += (buf.len() - newbuf.len()) as u64; //cb.log(format!("current offset: {}", self.current_offset).as_str()); if let KeepGoing(_) = r { if let Data(0, t) = self.mode { self.try_parse_element_data(newbuf, 0, t, cb); }; }; self.close_expired_elements(cb); Some(newbuf) } } impl Parser for ParserState { fn new() -> ParserState { ParserState { accumulator: vec![], mode : ParserMode::Header, opened_elements_stack : vec![], current_offset : 0, } } fn feed_bytes<E : EventsHandler +?Sized>(&mut self, bytes : &[u8], cb: &mut E) { use self::ResultOfTryParseSomething::*; use self::ParserMode::*; //cb.log(format!("feed_bytes {} len={}", bytes[0], self.accumulator.len()).as_str() ); self.accumulator.extend_from_slice(bytes); let tmpvector = self.accumulator.to_vec(); { let mut buf = tmpvector.as_slice(); //cb.log( format!("feed_bytes2 len={} buflen={}", self.accumulator.len(), buf.len()) ); loop { if let Some(x) = self.feed_bytes_1(buf, cb) { buf = x } else { break; } } self.accumulator = buf.to_vec(); } //cb.log( format!("feed_bytes3 len={}", self.accumulator.len()).as_str()); } fn force_resync(&mut self) { self.mode = self::ParserMode::Resync; } }
{ let (_, trail) = buf.split_at(1); KeepGoing(trail) }
conditional_block
mod.rs
use super::database::{id_to_class,class_to_type}; use self::parse_ebml_number::parse_ebml_number; use self::parse_ebml_number::Result as EbmlParseNumberResult; use self::parse_ebml_number::Mode as EbmlParseNumberMode; use std::vec::Vec; use std::string::String; use std::fmt; mod parse_ebml_number; #[cfg(test)] mod test; pub mod debug; extern crate byteorder; #[derive(Eq,PartialEq,Clone)] pub struct Info { pub id : u64, pub offset : u64, pub length_including_header : Option<u64>, } /// Note: binary chunks are not related to lacing #[derive(Debug,PartialEq,Clone)] pub enum BinaryChunkStatus { Full, // this chunk is the full data of Binary element First, Middle, Last, } #[derive(Debug,PartialEq,Clone)] pub enum SimpleContent<'a> { Unsigned(u64), Signed(i64), Text(&'a str), Binary(&'a [u8], BinaryChunkStatus), Float(f64), MatroskaDate(i64), // Nanoseconds since 20010101_000000_UTC } #[derive(Debug,PartialEq,Clone)] pub enum Event<'a> { Begin(&'a Info), Data(SimpleContent<'a>), End(&'a Info), Resync, } pub trait EventsHandler { fn event(&mut self, e : Event); } #[cfg(feature="nightly")] impl<F:FnMut(Event)->()> EventsHandler for F { fn event(&mut self, e : Event) { self.call_mut((e,)) } } pub trait Parser { fn new() -> Self; fn feed_bytes<E : EventsHandler +?Sized>(&mut self, bytes : &[u8], cb: &mut E); fn force_resync(&mut self); } pub fn new () -> ParserState { self::Parser::new() } ////////////////////////////// impl fmt::Debug for Info { fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result { let cl = super::database::id_to_class(self.id); let typ = super::database::class_to_type(cl); let cldesc = match cl { super::database::Class::Unknown => format!("0x{:X}", self.id), _ => format!("{:?}", cl), }; let maybelen = match self.length_including_header { None => format!(""), Some(x) => format!(", rawlen:{}", x), }; f.write_str(format!("{}(offset:{}{})", cldesc, self.offset, maybelen).as_str()) } } enum ParserMode { Header, Data(usize, super::Type), Resync, } pub struct ParserState { accumulator : Vec<u8>, opened_elements_stack : Vec<Info>, mode : ParserMode, current_offset : u64, } #[derive(Debug,Eq,PartialEq)] enum ResultOfTryParseSomething<'a> { KeepGoing(&'a [u8]), NoMoreData, Error,
} impl ParserState { fn try_resync<'a>(&mut self, buf:&'a [u8]) -> ResultOfTryParseSomething<'a> { use self::ResultOfTryParseSomething::*; if buf.len() < 4 { return NoMoreData; } let (fourbytes, _) = buf.split_at(4); let id : u32 = (fourbytes[0] as u32)*0x1000000 + (fourbytes[1] as u32) * 0x10000 + (fourbytes[2] as u32) * 0x100 + (fourbytes[3] as u32); match id { 0x1A45DFA3 | 0x18538067 | 0x1549A966 | 0x1F43B675 | 0x1654AE6B | 0x1C53BB6B | 0x1941A469 | 0x1043A770 | 0x1254C367 => { self.mode = ParserMode::Header; KeepGoing(buf) } _ => { let (_, trail) = buf.split_at(1); KeepGoing(trail) } } } fn try_parse_element_data<'a, E : EventsHandler+?Sized>(&mut self, buf:&'a [u8], len:usize, typ : super::Type, cb: &mut E) -> ResultOfTryParseSomething<'a> { use self::ResultOfTryParseSomething::{NoMoreData,KeepGoing,Error}; use self::Event::{Data}; use self::SimpleContent:: {Unsigned, Signed, Text, Binary, Float, MatroskaDate}; use self::ParserMode; if len <= buf.len() { self.mode = ParserMode::Header; let (l,r) = buf.split_at(len); let da = match typ { super::Type::Master => panic!("Wrong way"), super::Type::Binary => Binary(l, BinaryChunkStatus::Full), super::Type::Unsigned => { let mut q : u64 = 0; let mut it = l.iter(); if l.len() > 8 { return Error; } loop { match it.next() { Some(x) => {q = q*0x100 + (*x as u64)}, None => break, } }; Unsigned(q) }, super::Type::Signed | super::Type::Date => { let mut q : i64 = 0; let mut it = l.iter(); if l.len() > 8 { return Error; } match it.next() { Some(&x) if x >= 0x80 => { q = -(x as i64) + 0x80; }, Some(&x) => { q = (x as i64); }, None => {}, } loop { match it.next() { Some(&x) => {q = q*0x100 + (x as i64)}, None => break, } }; match typ { super::Type::Signed => Signed(q), super::Type::Date => MatroskaDate(q), _ => panic!("Internal error"), } }, super::Type::TextAscii | super::Type::TextUtf8 => { use std::str::from_utf8; match from_utf8(l) { Ok(x) => Text(x), Err(_) => return Error, } }, super::Type::Float => { use self::byteorder::ReadBytesExt; use self::byteorder::BigEndian; let mut ll = l; match ll.len() { 8 => match ll.read_f64::<BigEndian>() { Ok(x) => Float(x), Err(_) => return Error, }, 4 => match ll.read_f32::<BigEndian>() { Ok(x) => Float(x as f64), Err(_) => return Error, }, 0 => Float(0.0), 10 => { error!("Error: 10-byte floats are not supported in mkv"); Binary(l, BinaryChunkStatus::Full) } _ => return Error, } } }; cb.event( Data(da) ); KeepGoing(r) } else { return NoMoreData; } } fn try_parse_element_header<'a, E:EventsHandler+?Sized>(&mut self, buf:&'a [u8], cb: &mut E) -> ResultOfTryParseSomething<'a> { use self::ResultOfTryParseSomething::{NoMoreData,KeepGoing}; use self::ResultOfTryParseSomething::Error as MyError; use self::parse_ebml_number::Result::*; use self::parse_ebml_number::Mode::*; use super::Type::{Master}; use self::Event::{Begin}; use self::ParserMode; let (r1, restbuf) = parse_ebml_number(buf, Identifier); let element_id = match r1 { Error => return MyError, NaN => return MyError, NotEnoughData => return NoMoreData, Ok(x) => x }; let (r2, restbuf2) = parse_ebml_number(restbuf, Unsigned); let element_header_size = (buf.len() - restbuf2.len()) as u64; let element_size = match r2 { Error => return MyError, NaN => None, NotEnoughData => return NoMoreData, Ok(x) => Some(x) }; let full_element_size = match element_size { None => None, Some(x) => Some(x + element_header_size), }; let cl = id_to_class(element_id); let typ = class_to_type(cl); let mut restbuf3 = restbuf2; self.mode = match typ { Master => ParserMode::Header, t => match element_size { None => ParserMode::Resync, Some(x) => ParserMode::Data(x as usize, t), } }; let el = Info{id: element_id, length_including_header: full_element_size, offset: self.current_offset}; cb.event( Begin( &el )); self.opened_elements_stack.push(el); //cb.auxilary_event( Debug (format!("element class={:?} type={:?} off={} clid={} len={:?}", // cl, typ, self.current_offset, element_id, element_size ))); KeepGoing(restbuf3) } fn close_expired_elements<'a, E:EventsHandler+?Sized>(&mut self, cb: &mut E) { use self::Event::{End}; let mut number_of_elements_to_remove = 0; for i in self.opened_elements_stack.iter().rev() { let retain = match i.length_including_header { None => true, Some(l) => i.offset + l > self.current_offset }; // println!("dr {:?} {} -> {}", i, self.current_offset, retain); if retain { break; } else { number_of_elements_to_remove += 1; } } { let mut j = 0; for i in self.opened_elements_stack.iter().rev() { j += 1; if j > number_of_elements_to_remove { break; } // println!("sending end {:?}", i); cb.event (End(i)); } } let newlen = self.opened_elements_stack.len() - number_of_elements_to_remove; self.opened_elements_stack.truncate(newlen); } fn feed_bytes_1<'a, 'b, E : EventsHandler +?Sized>(&mut self, buf : &'a [u8], cb: &'b mut E) -> Option<&'a [u8]> { use self::ResultOfTryParseSomething::*; use self::ParserMode::*; let r = match self.mode { Resync => self.try_resync(buf), Header => self.try_parse_element_header(buf, cb), Data(x, t) => self.try_parse_element_data(buf, x, t, cb), }; //cb.log( format!("try_parse_something={:?}", r)); let newbuf = match r { NoMoreData => return None, Error => {self.mode = ParserMode::Resync; cb.event(self::Event::Resync); buf}, KeepGoing(rest) => rest }; self.current_offset += (buf.len() - newbuf.len()) as u64; //cb.log(format!("current offset: {}", self.current_offset).as_str()); if let KeepGoing(_) = r { if let Data(0, t) = self.mode { self.try_parse_element_data(newbuf, 0, t, cb); }; }; self.close_expired_elements(cb); Some(newbuf) } } impl Parser for ParserState { fn new() -> ParserState { ParserState { accumulator: vec![], mode : ParserMode::Header, opened_elements_stack : vec![], current_offset : 0, } } fn feed_bytes<E : EventsHandler +?Sized>(&mut self, bytes : &[u8], cb: &mut E) { use self::ResultOfTryParseSomething::*; use self::ParserMode::*; //cb.log(format!("feed_bytes {} len={}", bytes[0], self.accumulator.len()).as_str() ); self.accumulator.extend_from_slice(bytes); let tmpvector = self.accumulator.to_vec(); { let mut buf = tmpvector.as_slice(); //cb.log( format!("feed_bytes2 len={} buflen={}", self.accumulator.len(), buf.len()) ); loop { if let Some(x) = self.feed_bytes_1(buf, cb) { buf = x } else { break; } } self.accumulator = buf.to_vec(); } //cb.log( format!("feed_bytes3 len={}", self.accumulator.len()).as_str()); } fn force_resync(&mut self) { self.mode = self::ParserMode::Resync; } }
random_line_split
mod.rs
use super::database::{id_to_class,class_to_type}; use self::parse_ebml_number::parse_ebml_number; use self::parse_ebml_number::Result as EbmlParseNumberResult; use self::parse_ebml_number::Mode as EbmlParseNumberMode; use std::vec::Vec; use std::string::String; use std::fmt; mod parse_ebml_number; #[cfg(test)] mod test; pub mod debug; extern crate byteorder; #[derive(Eq,PartialEq,Clone)] pub struct Info { pub id : u64, pub offset : u64, pub length_including_header : Option<u64>, } /// Note: binary chunks are not related to lacing #[derive(Debug,PartialEq,Clone)] pub enum BinaryChunkStatus { Full, // this chunk is the full data of Binary element First, Middle, Last, } #[derive(Debug,PartialEq,Clone)] pub enum SimpleContent<'a> { Unsigned(u64), Signed(i64), Text(&'a str), Binary(&'a [u8], BinaryChunkStatus), Float(f64), MatroskaDate(i64), // Nanoseconds since 20010101_000000_UTC } #[derive(Debug,PartialEq,Clone)] pub enum Event<'a> { Begin(&'a Info), Data(SimpleContent<'a>), End(&'a Info), Resync, } pub trait EventsHandler { fn event(&mut self, e : Event); } #[cfg(feature="nightly")] impl<F:FnMut(Event)->()> EventsHandler for F { fn event(&mut self, e : Event) { self.call_mut((e,)) } } pub trait Parser { fn new() -> Self; fn feed_bytes<E : EventsHandler +?Sized>(&mut self, bytes : &[u8], cb: &mut E); fn force_resync(&mut self); } pub fn
() -> ParserState { self::Parser::new() } ////////////////////////////// impl fmt::Debug for Info { fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result { let cl = super::database::id_to_class(self.id); let typ = super::database::class_to_type(cl); let cldesc = match cl { super::database::Class::Unknown => format!("0x{:X}", self.id), _ => format!("{:?}", cl), }; let maybelen = match self.length_including_header { None => format!(""), Some(x) => format!(", rawlen:{}", x), }; f.write_str(format!("{}(offset:{}{})", cldesc, self.offset, maybelen).as_str()) } } enum ParserMode { Header, Data(usize, super::Type), Resync, } pub struct ParserState { accumulator : Vec<u8>, opened_elements_stack : Vec<Info>, mode : ParserMode, current_offset : u64, } #[derive(Debug,Eq,PartialEq)] enum ResultOfTryParseSomething<'a> { KeepGoing(&'a [u8]), NoMoreData, Error, } impl ParserState { fn try_resync<'a>(&mut self, buf:&'a [u8]) -> ResultOfTryParseSomething<'a> { use self::ResultOfTryParseSomething::*; if buf.len() < 4 { return NoMoreData; } let (fourbytes, _) = buf.split_at(4); let id : u32 = (fourbytes[0] as u32)*0x1000000 + (fourbytes[1] as u32) * 0x10000 + (fourbytes[2] as u32) * 0x100 + (fourbytes[3] as u32); match id { 0x1A45DFA3 | 0x18538067 | 0x1549A966 | 0x1F43B675 | 0x1654AE6B | 0x1C53BB6B | 0x1941A469 | 0x1043A770 | 0x1254C367 => { self.mode = ParserMode::Header; KeepGoing(buf) } _ => { let (_, trail) = buf.split_at(1); KeepGoing(trail) } } } fn try_parse_element_data<'a, E : EventsHandler+?Sized>(&mut self, buf:&'a [u8], len:usize, typ : super::Type, cb: &mut E) -> ResultOfTryParseSomething<'a> { use self::ResultOfTryParseSomething::{NoMoreData,KeepGoing,Error}; use self::Event::{Data}; use self::SimpleContent:: {Unsigned, Signed, Text, Binary, Float, MatroskaDate}; use self::ParserMode; if len <= buf.len() { self.mode = ParserMode::Header; let (l,r) = buf.split_at(len); let da = match typ { super::Type::Master => panic!("Wrong way"), super::Type::Binary => Binary(l, BinaryChunkStatus::Full), super::Type::Unsigned => { let mut q : u64 = 0; let mut it = l.iter(); if l.len() > 8 { return Error; } loop { match it.next() { Some(x) => {q = q*0x100 + (*x as u64)}, None => break, } }; Unsigned(q) }, super::Type::Signed | super::Type::Date => { let mut q : i64 = 0; let mut it = l.iter(); if l.len() > 8 { return Error; } match it.next() { Some(&x) if x >= 0x80 => { q = -(x as i64) + 0x80; }, Some(&x) => { q = (x as i64); }, None => {}, } loop { match it.next() { Some(&x) => {q = q*0x100 + (x as i64)}, None => break, } }; match typ { super::Type::Signed => Signed(q), super::Type::Date => MatroskaDate(q), _ => panic!("Internal error"), } }, super::Type::TextAscii | super::Type::TextUtf8 => { use std::str::from_utf8; match from_utf8(l) { Ok(x) => Text(x), Err(_) => return Error, } }, super::Type::Float => { use self::byteorder::ReadBytesExt; use self::byteorder::BigEndian; let mut ll = l; match ll.len() { 8 => match ll.read_f64::<BigEndian>() { Ok(x) => Float(x), Err(_) => return Error, }, 4 => match ll.read_f32::<BigEndian>() { Ok(x) => Float(x as f64), Err(_) => return Error, }, 0 => Float(0.0), 10 => { error!("Error: 10-byte floats are not supported in mkv"); Binary(l, BinaryChunkStatus::Full) } _ => return Error, } } }; cb.event( Data(da) ); KeepGoing(r) } else { return NoMoreData; } } fn try_parse_element_header<'a, E:EventsHandler+?Sized>(&mut self, buf:&'a [u8], cb: &mut E) -> ResultOfTryParseSomething<'a> { use self::ResultOfTryParseSomething::{NoMoreData,KeepGoing}; use self::ResultOfTryParseSomething::Error as MyError; use self::parse_ebml_number::Result::*; use self::parse_ebml_number::Mode::*; use super::Type::{Master}; use self::Event::{Begin}; use self::ParserMode; let (r1, restbuf) = parse_ebml_number(buf, Identifier); let element_id = match r1 { Error => return MyError, NaN => return MyError, NotEnoughData => return NoMoreData, Ok(x) => x }; let (r2, restbuf2) = parse_ebml_number(restbuf, Unsigned); let element_header_size = (buf.len() - restbuf2.len()) as u64; let element_size = match r2 { Error => return MyError, NaN => None, NotEnoughData => return NoMoreData, Ok(x) => Some(x) }; let full_element_size = match element_size { None => None, Some(x) => Some(x + element_header_size), }; let cl = id_to_class(element_id); let typ = class_to_type(cl); let mut restbuf3 = restbuf2; self.mode = match typ { Master => ParserMode::Header, t => match element_size { None => ParserMode::Resync, Some(x) => ParserMode::Data(x as usize, t), } }; let el = Info{id: element_id, length_including_header: full_element_size, offset: self.current_offset}; cb.event( Begin( &el )); self.opened_elements_stack.push(el); //cb.auxilary_event( Debug (format!("element class={:?} type={:?} off={} clid={} len={:?}", // cl, typ, self.current_offset, element_id, element_size ))); KeepGoing(restbuf3) } fn close_expired_elements<'a, E:EventsHandler+?Sized>(&mut self, cb: &mut E) { use self::Event::{End}; let mut number_of_elements_to_remove = 0; for i in self.opened_elements_stack.iter().rev() { let retain = match i.length_including_header { None => true, Some(l) => i.offset + l > self.current_offset }; // println!("dr {:?} {} -> {}", i, self.current_offset, retain); if retain { break; } else { number_of_elements_to_remove += 1; } } { let mut j = 0; for i in self.opened_elements_stack.iter().rev() { j += 1; if j > number_of_elements_to_remove { break; } // println!("sending end {:?}", i); cb.event (End(i)); } } let newlen = self.opened_elements_stack.len() - number_of_elements_to_remove; self.opened_elements_stack.truncate(newlen); } fn feed_bytes_1<'a, 'b, E : EventsHandler +?Sized>(&mut self, buf : &'a [u8], cb: &'b mut E) -> Option<&'a [u8]> { use self::ResultOfTryParseSomething::*; use self::ParserMode::*; let r = match self.mode { Resync => self.try_resync(buf), Header => self.try_parse_element_header(buf, cb), Data(x, t) => self.try_parse_element_data(buf, x, t, cb), }; //cb.log( format!("try_parse_something={:?}", r)); let newbuf = match r { NoMoreData => return None, Error => {self.mode = ParserMode::Resync; cb.event(self::Event::Resync); buf}, KeepGoing(rest) => rest }; self.current_offset += (buf.len() - newbuf.len()) as u64; //cb.log(format!("current offset: {}", self.current_offset).as_str()); if let KeepGoing(_) = r { if let Data(0, t) = self.mode { self.try_parse_element_data(newbuf, 0, t, cb); }; }; self.close_expired_elements(cb); Some(newbuf) } } impl Parser for ParserState { fn new() -> ParserState { ParserState { accumulator: vec![], mode : ParserMode::Header, opened_elements_stack : vec![], current_offset : 0, } } fn feed_bytes<E : EventsHandler +?Sized>(&mut self, bytes : &[u8], cb: &mut E) { use self::ResultOfTryParseSomething::*; use self::ParserMode::*; //cb.log(format!("feed_bytes {} len={}", bytes[0], self.accumulator.len()).as_str() ); self.accumulator.extend_from_slice(bytes); let tmpvector = self.accumulator.to_vec(); { let mut buf = tmpvector.as_slice(); //cb.log( format!("feed_bytes2 len={} buflen={}", self.accumulator.len(), buf.len()) ); loop { if let Some(x) = self.feed_bytes_1(buf, cb) { buf = x } else { break; } } self.accumulator = buf.to_vec(); } //cb.log( format!("feed_bytes3 len={}", self.accumulator.len()).as_str()); } fn force_resync(&mut self) { self.mode = self::ParserMode::Resync; } }
new
identifier_name
mod.rs
use super::database::{id_to_class,class_to_type}; use self::parse_ebml_number::parse_ebml_number; use self::parse_ebml_number::Result as EbmlParseNumberResult; use self::parse_ebml_number::Mode as EbmlParseNumberMode; use std::vec::Vec; use std::string::String; use std::fmt; mod parse_ebml_number; #[cfg(test)] mod test; pub mod debug; extern crate byteorder; #[derive(Eq,PartialEq,Clone)] pub struct Info { pub id : u64, pub offset : u64, pub length_including_header : Option<u64>, } /// Note: binary chunks are not related to lacing #[derive(Debug,PartialEq,Clone)] pub enum BinaryChunkStatus { Full, // this chunk is the full data of Binary element First, Middle, Last, } #[derive(Debug,PartialEq,Clone)] pub enum SimpleContent<'a> { Unsigned(u64), Signed(i64), Text(&'a str), Binary(&'a [u8], BinaryChunkStatus), Float(f64), MatroskaDate(i64), // Nanoseconds since 20010101_000000_UTC } #[derive(Debug,PartialEq,Clone)] pub enum Event<'a> { Begin(&'a Info), Data(SimpleContent<'a>), End(&'a Info), Resync, } pub trait EventsHandler { fn event(&mut self, e : Event); } #[cfg(feature="nightly")] impl<F:FnMut(Event)->()> EventsHandler for F { fn event(&mut self, e : Event) { self.call_mut((e,)) } } pub trait Parser { fn new() -> Self; fn feed_bytes<E : EventsHandler +?Sized>(&mut self, bytes : &[u8], cb: &mut E); fn force_resync(&mut self); } pub fn new () -> ParserState { self::Parser::new() } ////////////////////////////// impl fmt::Debug for Info { fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result { let cl = super::database::id_to_class(self.id); let typ = super::database::class_to_type(cl); let cldesc = match cl { super::database::Class::Unknown => format!("0x{:X}", self.id), _ => format!("{:?}", cl), }; let maybelen = match self.length_including_header { None => format!(""), Some(x) => format!(", rawlen:{}", x), }; f.write_str(format!("{}(offset:{}{})", cldesc, self.offset, maybelen).as_str()) } } enum ParserMode { Header, Data(usize, super::Type), Resync, } pub struct ParserState { accumulator : Vec<u8>, opened_elements_stack : Vec<Info>, mode : ParserMode, current_offset : u64, } #[derive(Debug,Eq,PartialEq)] enum ResultOfTryParseSomething<'a> { KeepGoing(&'a [u8]), NoMoreData, Error, } impl ParserState { fn try_resync<'a>(&mut self, buf:&'a [u8]) -> ResultOfTryParseSomething<'a> { use self::ResultOfTryParseSomething::*; if buf.len() < 4 { return NoMoreData; } let (fourbytes, _) = buf.split_at(4); let id : u32 = (fourbytes[0] as u32)*0x1000000 + (fourbytes[1] as u32) * 0x10000 + (fourbytes[2] as u32) * 0x100 + (fourbytes[3] as u32); match id { 0x1A45DFA3 | 0x18538067 | 0x1549A966 | 0x1F43B675 | 0x1654AE6B | 0x1C53BB6B | 0x1941A469 | 0x1043A770 | 0x1254C367 => { self.mode = ParserMode::Header; KeepGoing(buf) } _ => { let (_, trail) = buf.split_at(1); KeepGoing(trail) } } } fn try_parse_element_data<'a, E : EventsHandler+?Sized>(&mut self, buf:&'a [u8], len:usize, typ : super::Type, cb: &mut E) -> ResultOfTryParseSomething<'a> { use self::ResultOfTryParseSomething::{NoMoreData,KeepGoing,Error}; use self::Event::{Data}; use self::SimpleContent:: {Unsigned, Signed, Text, Binary, Float, MatroskaDate}; use self::ParserMode; if len <= buf.len() { self.mode = ParserMode::Header; let (l,r) = buf.split_at(len); let da = match typ { super::Type::Master => panic!("Wrong way"), super::Type::Binary => Binary(l, BinaryChunkStatus::Full), super::Type::Unsigned => { let mut q : u64 = 0; let mut it = l.iter(); if l.len() > 8 { return Error; } loop { match it.next() { Some(x) => {q = q*0x100 + (*x as u64)}, None => break, } }; Unsigned(q) }, super::Type::Signed | super::Type::Date => { let mut q : i64 = 0; let mut it = l.iter(); if l.len() > 8 { return Error; } match it.next() { Some(&x) if x >= 0x80 => { q = -(x as i64) + 0x80; }, Some(&x) => { q = (x as i64); }, None => {}, } loop { match it.next() { Some(&x) => {q = q*0x100 + (x as i64)}, None => break, } }; match typ { super::Type::Signed => Signed(q), super::Type::Date => MatroskaDate(q), _ => panic!("Internal error"), } }, super::Type::TextAscii | super::Type::TextUtf8 => { use std::str::from_utf8; match from_utf8(l) { Ok(x) => Text(x), Err(_) => return Error, } }, super::Type::Float => { use self::byteorder::ReadBytesExt; use self::byteorder::BigEndian; let mut ll = l; match ll.len() { 8 => match ll.read_f64::<BigEndian>() { Ok(x) => Float(x), Err(_) => return Error, }, 4 => match ll.read_f32::<BigEndian>() { Ok(x) => Float(x as f64), Err(_) => return Error, }, 0 => Float(0.0), 10 => { error!("Error: 10-byte floats are not supported in mkv"); Binary(l, BinaryChunkStatus::Full) } _ => return Error, } } }; cb.event( Data(da) ); KeepGoing(r) } else { return NoMoreData; } } fn try_parse_element_header<'a, E:EventsHandler+?Sized>(&mut self, buf:&'a [u8], cb: &mut E) -> ResultOfTryParseSomething<'a> { use self::ResultOfTryParseSomething::{NoMoreData,KeepGoing}; use self::ResultOfTryParseSomething::Error as MyError; use self::parse_ebml_number::Result::*; use self::parse_ebml_number::Mode::*; use super::Type::{Master}; use self::Event::{Begin}; use self::ParserMode; let (r1, restbuf) = parse_ebml_number(buf, Identifier); let element_id = match r1 { Error => return MyError, NaN => return MyError, NotEnoughData => return NoMoreData, Ok(x) => x }; let (r2, restbuf2) = parse_ebml_number(restbuf, Unsigned); let element_header_size = (buf.len() - restbuf2.len()) as u64; let element_size = match r2 { Error => return MyError, NaN => None, NotEnoughData => return NoMoreData, Ok(x) => Some(x) }; let full_element_size = match element_size { None => None, Some(x) => Some(x + element_header_size), }; let cl = id_to_class(element_id); let typ = class_to_type(cl); let mut restbuf3 = restbuf2; self.mode = match typ { Master => ParserMode::Header, t => match element_size { None => ParserMode::Resync, Some(x) => ParserMode::Data(x as usize, t), } }; let el = Info{id: element_id, length_including_header: full_element_size, offset: self.current_offset}; cb.event( Begin( &el )); self.opened_elements_stack.push(el); //cb.auxilary_event( Debug (format!("element class={:?} type={:?} off={} clid={} len={:?}", // cl, typ, self.current_offset, element_id, element_size ))); KeepGoing(restbuf3) } fn close_expired_elements<'a, E:EventsHandler+?Sized>(&mut self, cb: &mut E) { use self::Event::{End}; let mut number_of_elements_to_remove = 0; for i in self.opened_elements_stack.iter().rev() { let retain = match i.length_including_header { None => true, Some(l) => i.offset + l > self.current_offset }; // println!("dr {:?} {} -> {}", i, self.current_offset, retain); if retain { break; } else { number_of_elements_to_remove += 1; } } { let mut j = 0; for i in self.opened_elements_stack.iter().rev() { j += 1; if j > number_of_elements_to_remove { break; } // println!("sending end {:?}", i); cb.event (End(i)); } } let newlen = self.opened_elements_stack.len() - number_of_elements_to_remove; self.opened_elements_stack.truncate(newlen); } fn feed_bytes_1<'a, 'b, E : EventsHandler +?Sized>(&mut self, buf : &'a [u8], cb: &'b mut E) -> Option<&'a [u8]> { use self::ResultOfTryParseSomething::*; use self::ParserMode::*; let r = match self.mode { Resync => self.try_resync(buf), Header => self.try_parse_element_header(buf, cb), Data(x, t) => self.try_parse_element_data(buf, x, t, cb), }; //cb.log( format!("try_parse_something={:?}", r)); let newbuf = match r { NoMoreData => return None, Error => {self.mode = ParserMode::Resync; cb.event(self::Event::Resync); buf}, KeepGoing(rest) => rest }; self.current_offset += (buf.len() - newbuf.len()) as u64; //cb.log(format!("current offset: {}", self.current_offset).as_str()); if let KeepGoing(_) = r { if let Data(0, t) = self.mode { self.try_parse_element_data(newbuf, 0, t, cb); }; }; self.close_expired_elements(cb); Some(newbuf) } } impl Parser for ParserState { fn new() -> ParserState { ParserState { accumulator: vec![], mode : ParserMode::Header, opened_elements_stack : vec![], current_offset : 0, } } fn feed_bytes<E : EventsHandler +?Sized>(&mut self, bytes : &[u8], cb: &mut E)
//cb.log( format!("feed_bytes3 len={}", self.accumulator.len()).as_str()); } fn force_resync(&mut self) { self.mode = self::ParserMode::Resync; } }
{ use self::ResultOfTryParseSomething::*; use self::ParserMode::*; //cb.log(format!("feed_bytes {} len={}", bytes[0], self.accumulator.len()).as_str() ); self.accumulator.extend_from_slice(bytes); let tmpvector = self.accumulator.to_vec(); { let mut buf = tmpvector.as_slice(); //cb.log( format!("feed_bytes2 len={} buflen={}", self.accumulator.len(), buf.len()) ); loop { if let Some(x) = self.feed_bytes_1(buf, cb) { buf = x } else { break; } } self.accumulator = buf.to_vec(); }
identifier_body
lib.rs
//! This crate defines a macro for creating iterators which implement //! recurrence relations. /* This is an implementation detail, but it *also* needs to be visible at the *expansion* site of the `recurrence` macro (*i.e.* in another crate). Thus, we need to publically export this macro. That said, we don't want it showing up in the documentation; hence the use of `#[doc(hidden)]` and a prefixed name. */ #[doc(hidden)] #[macro_export] macro_rules! _recurrence_count_exprs { () => (0); ($head:expr) => (1); ($head:expr, $($tail:expr),*) => (1 + _recurrence_count_exprs!($($tail),*)); } /// Expands to an expression implementing the `Iterator` trait, which yields /// successive elements of the given recurrence relationship. /// /// For example, you can define a Fibonacci sequence iterator like so: /// /// ``` /// # // Keep in mind that this code block will be run as a test! The lines /// # // beginning with `# ` will be stripped from the generated documentation, /// # // but included in the test. /// # #[macro_use] extern crate recurrence; /// # fn main() { /// # let _ = /// recurrence![ fib[n]: f64 = 0.0, 1.0... fib[n-1] + fib[n-2] ] /// # ; /// # } /// ``` #[macro_export] macro_rules! recurrence { ( $seq:ident [ $ind:ident ]: $sty:ty = $($inits:expr),+... $recur:expr ) => { { use std::ops::Index; const MEM_SIZE: usize = _recurrence_count_exprs!($($inits),+); struct Recurrence { mem: [$sty; MEM_SIZE], pos: usize, } struct IndexOffset<'a> { slice: &'a [$sty; MEM_SIZE], offset: usize, } impl<'a> Index<usize> for IndexOffset<'a> { type Output = $sty; #[inline(always)] fn index<'b>(&'b self, index: usize) -> &'b $sty { use std::num::Wrapping; let index = Wrapping(index);
&self.slice[real_index.0] } } impl Iterator for Recurrence { type Item = $sty; #[inline] fn next(&mut self) -> Option<$sty> { if self.pos < MEM_SIZE { let next_val = self.mem[self.pos]; self.pos += 1; Some(next_val) } else { let next_val = { let $ind = self.pos; let $seq = IndexOffset { slice: &self.mem, offset: $ind }; $recur }; { use std::mem::swap; let mut swap_tmp = next_val; for i in (0..MEM_SIZE).rev() { swap(&mut swap_tmp, &mut self.mem[i]); } } self.pos += 1; Some(next_val) } } } Recurrence { mem: [$($inits),+], pos: 0 } } }; }
let offset = Wrapping(self.offset); let window = Wrapping(MEM_SIZE); let real_index = index - offset + window;
random_line_split
main.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 Takuzu (a.k.a. Binairo) solver. //! //! # Usage //! //! ```shell //! takuzu [FILE]... //! takuzu {--help | --version} //! ``` //! //! If no `FILE` is provided, or if `FILE` is '`-`', reads from standard input. extern crate failure; extern crate libc; extern crate takuzu; use failure::Error; use std::fmt::Write; use std::io::stdin; use takuzu::{Grid, Source}; static VERSION: &str = env!("CARGO_PKG_VERSION"); static USAGE_STRING: &str = "\ Usage: takuzu [FILE]... takuzu {--help | --version} If no FILE is provided, or if FILE is '-', read from standard input. Options: --help display this message and exit --version display the version and exit "; macro_rules! handle_and_print { ($result:expr) => {
match $result { Ok(ok) => print_solutions(&ok.0, &ok.1, None), Err(err) => eprintln!("error: {}", causes_fold(&err)), } }; ($result:expr, $filename:expr) => { match $result { Ok(ok) => print_solutions(&ok.0, &ok.1, Some($filename)), Err(err) => eprintln!("error: \"{}\": {}", $filename, causes_fold(&err)), } }; ($result:expr, $filename:expr, $print_filename:expr) => { if $print_filename { handle_and_print!($result, $filename) } else { handle_and_print!($result) } }; } fn main() { let args: Vec<String> = std::env::args().skip(1).collect(); let mut stdin_found = false; for arg in &args { if arg == "--help" { print!("{}", USAGE_STRING); return; } else if arg == "--version" { println!("takuzu {}", VERSION); return; } else if arg == "-" { if stdin_found { eprintln!("error: can't mention \"-\" (stdin) more than once"); return; } stdin_found = true; } } if args.is_empty() { handle_and_print!(solve_from("-")); } else { handle_and_print!(solve_from(&args[0]), &args[0], args.len() > 1); for filename in args.iter().skip(1) { println!(); handle_and_print!(solve_from(filename), filename); } } } /// Opens a file (or `stdin` if filename is "-"), reads a grid, /// triggers the solving algorithm and returns the grid with its solutions. fn solve_from(filename: &str) -> Result<(Grid, Vec<Grid>), Error> { let grid = match filename { "-" => stdin().source()?, _ => ::std::fs::File::open(filename)?.source()?, }; let solutions = grid.solve()?; Ok((grid, solutions)) } /// Prints a grid's solution(s) to `stdout`. /// /// If there is more than one solution, the grids are separated an empty line. /// If `stdout` is a terminal, prints the grids with colors and preceded by /// a numbered label. Optionnally, prints the filename before the solutions. fn print_solutions(grid: &Grid, solutions: &[Grid], filename: Option<&str>) { if solutions.is_empty() { if let Some(filename) = filename { eprint!("{}: ", filename); } eprintln!("no solution"); } else { if let Some(filename) = filename { println!("{}", filename); } if isatty_stdout() { if solutions.len() == 1 { print!("{}", solutions[0].to_string_diff(grid)); } else { println!("solution 1"); print!("{}", solutions[0].to_string_diff(grid)); for (i, solution) in solutions.iter().enumerate().skip(1) { println!("\nsolution {}", i + 1); print!("{}", solution.to_string_diff(grid)); } } } else { print!("{}", solutions[0]); for sol in solutions.iter().skip(1) { print!("\n{}", sol); } } } } /// Returns a string containing all the causes of an `Error`. fn causes_fold(error: &Error) -> String { error .causes() .skip(1) .fold(error.to_string(), |mut buffer, cause| { write!(&mut buffer, ": {}", cause).unwrap(); buffer }) } /// Returns `true` if `stdout` is a terminal. fn isatty_stdout() -> bool { match unsafe { libc::isatty(libc::STDOUT_FILENO) } { 1 => true, _ => false, } }
random_line_split
main.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 Takuzu (a.k.a. Binairo) solver. //! //! # Usage //! //! ```shell //! takuzu [FILE]... //! takuzu {--help | --version} //! ``` //! //! If no `FILE` is provided, or if `FILE` is '`-`', reads from standard input. extern crate failure; extern crate libc; extern crate takuzu; use failure::Error; use std::fmt::Write; use std::io::stdin; use takuzu::{Grid, Source}; static VERSION: &str = env!("CARGO_PKG_VERSION"); static USAGE_STRING: &str = "\ Usage: takuzu [FILE]... takuzu {--help | --version} If no FILE is provided, or if FILE is '-', read from standard input. Options: --help display this message and exit --version display the version and exit "; macro_rules! handle_and_print { ($result:expr) => { match $result { Ok(ok) => print_solutions(&ok.0, &ok.1, None), Err(err) => eprintln!("error: {}", causes_fold(&err)), } }; ($result:expr, $filename:expr) => { match $result { Ok(ok) => print_solutions(&ok.0, &ok.1, Some($filename)), Err(err) => eprintln!("error: \"{}\": {}", $filename, causes_fold(&err)), } }; ($result:expr, $filename:expr, $print_filename:expr) => { if $print_filename { handle_and_print!($result, $filename) } else { handle_and_print!($result) } }; } fn main() { let args: Vec<String> = std::env::args().skip(1).collect(); let mut stdin_found = false; for arg in &args { if arg == "--help" { print!("{}", USAGE_STRING); return; } else if arg == "--version" { println!("takuzu {}", VERSION); return; } else if arg == "-" { if stdin_found { eprintln!("error: can't mention \"-\" (stdin) more than once"); return; } stdin_found = true; } } if args.is_empty() { handle_and_print!(solve_from("-")); } else { handle_and_print!(solve_from(&args[0]), &args[0], args.len() > 1); for filename in args.iter().skip(1) { println!(); handle_and_print!(solve_from(filename), filename); } } } /// Opens a file (or `stdin` if filename is "-"), reads a grid, /// triggers the solving algorithm and returns the grid with its solutions. fn solve_from(filename: &str) -> Result<(Grid, Vec<Grid>), Error>
/// Prints a grid's solution(s) to `stdout`. /// /// If there is more than one solution, the grids are separated an empty line. /// If `stdout` is a terminal, prints the grids with colors and preceded by /// a numbered label. Optionnally, prints the filename before the solutions. fn print_solutions(grid: &Grid, solutions: &[Grid], filename: Option<&str>) { if solutions.is_empty() { if let Some(filename) = filename { eprint!("{}: ", filename); } eprintln!("no solution"); } else { if let Some(filename) = filename { println!("{}", filename); } if isatty_stdout() { if solutions.len() == 1 { print!("{}", solutions[0].to_string_diff(grid)); } else { println!("solution 1"); print!("{}", solutions[0].to_string_diff(grid)); for (i, solution) in solutions.iter().enumerate().skip(1) { println!("\nsolution {}", i + 1); print!("{}", solution.to_string_diff(grid)); } } } else { print!("{}", solutions[0]); for sol in solutions.iter().skip(1) { print!("\n{}", sol); } } } } /// Returns a string containing all the causes of an `Error`. fn causes_fold(error: &Error) -> String { error .causes() .skip(1) .fold(error.to_string(), |mut buffer, cause| { write!(&mut buffer, ": {}", cause).unwrap(); buffer }) } /// Returns `true` if `stdout` is a terminal. fn isatty_stdout() -> bool { match unsafe { libc::isatty(libc::STDOUT_FILENO) } { 1 => true, _ => false, } }
{ let grid = match filename { "-" => stdin().source()?, _ => ::std::fs::File::open(filename)?.source()?, }; let solutions = grid.solve()?; Ok((grid, solutions)) }
identifier_body
main.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 Takuzu (a.k.a. Binairo) solver. //! //! # Usage //! //! ```shell //! takuzu [FILE]... //! takuzu {--help | --version} //! ``` //! //! If no `FILE` is provided, or if `FILE` is '`-`', reads from standard input. extern crate failure; extern crate libc; extern crate takuzu; use failure::Error; use std::fmt::Write; use std::io::stdin; use takuzu::{Grid, Source}; static VERSION: &str = env!("CARGO_PKG_VERSION"); static USAGE_STRING: &str = "\ Usage: takuzu [FILE]... takuzu {--help | --version} If no FILE is provided, or if FILE is '-', read from standard input. Options: --help display this message and exit --version display the version and exit "; macro_rules! handle_and_print { ($result:expr) => { match $result { Ok(ok) => print_solutions(&ok.0, &ok.1, None), Err(err) => eprintln!("error: {}", causes_fold(&err)), } }; ($result:expr, $filename:expr) => { match $result { Ok(ok) => print_solutions(&ok.0, &ok.1, Some($filename)), Err(err) => eprintln!("error: \"{}\": {}", $filename, causes_fold(&err)), } }; ($result:expr, $filename:expr, $print_filename:expr) => { if $print_filename { handle_and_print!($result, $filename) } else { handle_and_print!($result) } }; } fn main() { let args: Vec<String> = std::env::args().skip(1).collect(); let mut stdin_found = false; for arg in &args { if arg == "--help" { print!("{}", USAGE_STRING); return; } else if arg == "--version" { println!("takuzu {}", VERSION); return; } else if arg == "-" { if stdin_found { eprintln!("error: can't mention \"-\" (stdin) more than once"); return; } stdin_found = true; } } if args.is_empty() { handle_and_print!(solve_from("-")); } else { handle_and_print!(solve_from(&args[0]), &args[0], args.len() > 1); for filename in args.iter().skip(1) { println!(); handle_and_print!(solve_from(filename), filename); } } } /// Opens a file (or `stdin` if filename is "-"), reads a grid, /// triggers the solving algorithm and returns the grid with its solutions. fn solve_from(filename: &str) -> Result<(Grid, Vec<Grid>), Error> { let grid = match filename { "-" => stdin().source()?, _ => ::std::fs::File::open(filename)?.source()?, }; let solutions = grid.solve()?; Ok((grid, solutions)) } /// Prints a grid's solution(s) to `stdout`. /// /// If there is more than one solution, the grids are separated an empty line. /// If `stdout` is a terminal, prints the grids with colors and preceded by /// a numbered label. Optionnally, prints the filename before the solutions. fn print_solutions(grid: &Grid, solutions: &[Grid], filename: Option<&str>) { if solutions.is_empty() { if let Some(filename) = filename { eprint!("{}: ", filename); } eprintln!("no solution"); } else { if let Some(filename) = filename { println!("{}", filename); } if isatty_stdout() { if solutions.len() == 1 { print!("{}", solutions[0].to_string_diff(grid)); } else { println!("solution 1"); print!("{}", solutions[0].to_string_diff(grid)); for (i, solution) in solutions.iter().enumerate().skip(1) { println!("\nsolution {}", i + 1); print!("{}", solution.to_string_diff(grid)); } } } else { print!("{}", solutions[0]); for sol in solutions.iter().skip(1) { print!("\n{}", sol); } } } } /// Returns a string containing all the causes of an `Error`. fn
(error: &Error) -> String { error .causes() .skip(1) .fold(error.to_string(), |mut buffer, cause| { write!(&mut buffer, ": {}", cause).unwrap(); buffer }) } /// Returns `true` if `stdout` is a terminal. fn isatty_stdout() -> bool { match unsafe { libc::isatty(libc::STDOUT_FILENO) } { 1 => true, _ => false, } }
causes_fold
identifier_name
main.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use regex::Regex; use std::{ collections::{btree_map::Entry, BTreeMap, BTreeSet, VecDeque}, env, fs, path::{Path, PathBuf}, }; fn
( graph: &BTreeMap<String, Vec<String>>, out_dir: &Path, is_forward: bool, ) -> anyhow::Result<()> { let empty_list = Vec::new(); for (module, _) in graph.iter() { // (breadth-first) search and gather the modules in `graph` which are reachable from `module`. let mut dot_src: String = String::new(); let mut visited: BTreeSet<String> = BTreeSet::new(); let mut queue: VecDeque<String> = VecDeque::new(); visited.insert(module.clone()); queue.push_back(module.clone()); while let Some(d) = queue.pop_front() { let dep_list = graph.get(&d).unwrap_or(&empty_list); dot_src.push_str(&format!(" {}\n", d)); for dep in dep_list.iter() { if is_forward { dot_src.push_str(&format!(" {} -> {}\n", d, dep)); } else { dot_src.push_str(&format!(" {} -> {}\n", dep, d)); } if!visited.contains(dep) { visited.insert(dep.clone()); queue.push_back(dep.clone()); } } } let out_file = out_dir.join(format!( "{}.{}.dot", module, (if is_forward { "forward" } else { "backward" }).to_string() )); fs::write( &out_file, format!("digraph G {{\n rankdir=BT\n{}}}\n", dot_src), )?; println!("{:?}", out_file); } Ok(()) } fn generate(inp_dir: &Path, out_dir: &Path) -> anyhow::Result<()> { let mut dep_graph: BTreeMap<String, Vec<String>> = BTreeMap::new(); let mut dep_graph_inverse: BTreeMap<String, Vec<String>> = BTreeMap::new(); println!("The stdlib files detected:"); for entry in fs::read_dir(inp_dir)? { let entry = entry?; let path = entry.path(); if path.is_dir() || path.extension().is_none() ||!path.extension().unwrap().eq("move") { // skip anything other than.move file. continue; } println!("{:?}", path); let content = fs::read_to_string(path)?; let rex1 = Regex::new(r"(?m)^module\s+(\w+)\s*\{").unwrap(); let caps = rex1.captures(&content); if caps.is_none() { // skip due to no module declaration found. continue; } let module_name = caps.unwrap()[1].to_string(); if let Entry::Vacant(e) = dep_graph_inverse.entry(module_name.clone()) { e.insert(vec![]); } let mut dep_list: Vec<String> = Vec::new(); // TODO: This is not 100% correct because modules can be used with full qualification and without `use`. // Refer to `move-prover/src/lib.rs` which correctly addresses this issue. let rex2 = Regex::new(r"(?m)use 0x1::(\w+)\s*(;|:)").unwrap(); for cap in rex2.captures_iter(&content) { let dep = cap.get(1).unwrap().as_str().to_string(); dep_list.push(dep.clone()); match dep_graph_inverse.entry(dep) { Entry::Vacant(e) => { e.insert(vec![module_name.clone()]); } Entry::Occupied(mut e) => { e.get_mut().push(module_name.clone()); } } } dep_graph.insert(module_name, dep_list); } fs::create_dir_all(out_dir)?; // Generate a.dot file for the entire dependency graph. let mut dot_src: String = String::new(); for (module, dep_list) in dep_graph.iter() { dot_src.push_str(&format!(" {}\n", module)); for dep in dep_list.iter() { dot_src.push_str(&format!(" {} -> {}\n", module, dep)); } } fs::write( out_dir.join("(EntireGraph).dot"), format!("digraph G {{\n rankdir=BT\n{}}}\n", dot_src), )?; println!( "\nThe diagram files (.dot) generated:\n{:?}", out_dir.join("(EntireGraph).dot") ); // Generate a.forward.dot file for the forward dependency graph per module. generate_diagram_per_module(&dep_graph, out_dir, true)?; // Generate a.backward.dot file for the backward dependency graph per module. generate_diagram_per_module(&dep_graph_inverse, out_dir, false)?; println!( "\nTo convert these.dot files into.pdf files, run {:?}.", out_dir.join("convert_all_dot_to_pdf.sh") ); Ok(()) } fn locate_inp_out_dir() -> (PathBuf, PathBuf) { // locate the language directory let lang_dir = env::current_exe() .unwrap() .parent() .unwrap() .parent() .unwrap() .parent() .unwrap() .join("language"); println!("The `language` directory is located as:\n{:?}\n", lang_dir); // construct the input and the output paths let inp_dir = lang_dir.join("stdlib/modules"); let out_dir = lang_dir.join("move-prover/diagen/diagrams"); (inp_dir, out_dir) } fn main() { let (inp_dir, out_dir) = locate_inp_out_dir(); let err = generate(inp_dir.as_path(), out_dir.as_path()); if let Err(err) = err { println!("Error: {:?}", err); } }
generate_diagram_per_module
identifier_name
main.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use regex::Regex; use std::{ collections::{btree_map::Entry, BTreeMap, BTreeSet, VecDeque}, env, fs, path::{Path, PathBuf}, }; fn generate_diagram_per_module( graph: &BTreeMap<String, Vec<String>>, out_dir: &Path, is_forward: bool, ) -> anyhow::Result<()> {
for (module, _) in graph.iter() { // (breadth-first) search and gather the modules in `graph` which are reachable from `module`. let mut dot_src: String = String::new(); let mut visited: BTreeSet<String> = BTreeSet::new(); let mut queue: VecDeque<String> = VecDeque::new(); visited.insert(module.clone()); queue.push_back(module.clone()); while let Some(d) = queue.pop_front() { let dep_list = graph.get(&d).unwrap_or(&empty_list); dot_src.push_str(&format!(" {}\n", d)); for dep in dep_list.iter() { if is_forward { dot_src.push_str(&format!(" {} -> {}\n", d, dep)); } else { dot_src.push_str(&format!(" {} -> {}\n", dep, d)); } if!visited.contains(dep) { visited.insert(dep.clone()); queue.push_back(dep.clone()); } } } let out_file = out_dir.join(format!( "{}.{}.dot", module, (if is_forward { "forward" } else { "backward" }).to_string() )); fs::write( &out_file, format!("digraph G {{\n rankdir=BT\n{}}}\n", dot_src), )?; println!("{:?}", out_file); } Ok(()) } fn generate(inp_dir: &Path, out_dir: &Path) -> anyhow::Result<()> { let mut dep_graph: BTreeMap<String, Vec<String>> = BTreeMap::new(); let mut dep_graph_inverse: BTreeMap<String, Vec<String>> = BTreeMap::new(); println!("The stdlib files detected:"); for entry in fs::read_dir(inp_dir)? { let entry = entry?; let path = entry.path(); if path.is_dir() || path.extension().is_none() ||!path.extension().unwrap().eq("move") { // skip anything other than.move file. continue; } println!("{:?}", path); let content = fs::read_to_string(path)?; let rex1 = Regex::new(r"(?m)^module\s+(\w+)\s*\{").unwrap(); let caps = rex1.captures(&content); if caps.is_none() { // skip due to no module declaration found. continue; } let module_name = caps.unwrap()[1].to_string(); if let Entry::Vacant(e) = dep_graph_inverse.entry(module_name.clone()) { e.insert(vec![]); } let mut dep_list: Vec<String> = Vec::new(); // TODO: This is not 100% correct because modules can be used with full qualification and without `use`. // Refer to `move-prover/src/lib.rs` which correctly addresses this issue. let rex2 = Regex::new(r"(?m)use 0x1::(\w+)\s*(;|:)").unwrap(); for cap in rex2.captures_iter(&content) { let dep = cap.get(1).unwrap().as_str().to_string(); dep_list.push(dep.clone()); match dep_graph_inverse.entry(dep) { Entry::Vacant(e) => { e.insert(vec![module_name.clone()]); } Entry::Occupied(mut e) => { e.get_mut().push(module_name.clone()); } } } dep_graph.insert(module_name, dep_list); } fs::create_dir_all(out_dir)?; // Generate a.dot file for the entire dependency graph. let mut dot_src: String = String::new(); for (module, dep_list) in dep_graph.iter() { dot_src.push_str(&format!(" {}\n", module)); for dep in dep_list.iter() { dot_src.push_str(&format!(" {} -> {}\n", module, dep)); } } fs::write( out_dir.join("(EntireGraph).dot"), format!("digraph G {{\n rankdir=BT\n{}}}\n", dot_src), )?; println!( "\nThe diagram files (.dot) generated:\n{:?}", out_dir.join("(EntireGraph).dot") ); // Generate a.forward.dot file for the forward dependency graph per module. generate_diagram_per_module(&dep_graph, out_dir, true)?; // Generate a.backward.dot file for the backward dependency graph per module. generate_diagram_per_module(&dep_graph_inverse, out_dir, false)?; println!( "\nTo convert these.dot files into.pdf files, run {:?}.", out_dir.join("convert_all_dot_to_pdf.sh") ); Ok(()) } fn locate_inp_out_dir() -> (PathBuf, PathBuf) { // locate the language directory let lang_dir = env::current_exe() .unwrap() .parent() .unwrap() .parent() .unwrap() .parent() .unwrap() .join("language"); println!("The `language` directory is located as:\n{:?}\n", lang_dir); // construct the input and the output paths let inp_dir = lang_dir.join("stdlib/modules"); let out_dir = lang_dir.join("move-prover/diagen/diagrams"); (inp_dir, out_dir) } fn main() { let (inp_dir, out_dir) = locate_inp_out_dir(); let err = generate(inp_dir.as_path(), out_dir.as_path()); if let Err(err) = err { println!("Error: {:?}", err); } }
let empty_list = Vec::new();
random_line_split
main.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use regex::Regex; use std::{ collections::{btree_map::Entry, BTreeMap, BTreeSet, VecDeque}, env, fs, path::{Path, PathBuf}, }; fn generate_diagram_per_module( graph: &BTreeMap<String, Vec<String>>, out_dir: &Path, is_forward: bool, ) -> anyhow::Result<()> { let empty_list = Vec::new(); for (module, _) in graph.iter() { // (breadth-first) search and gather the modules in `graph` which are reachable from `module`. let mut dot_src: String = String::new(); let mut visited: BTreeSet<String> = BTreeSet::new(); let mut queue: VecDeque<String> = VecDeque::new(); visited.insert(module.clone()); queue.push_back(module.clone()); while let Some(d) = queue.pop_front() { let dep_list = graph.get(&d).unwrap_or(&empty_list); dot_src.push_str(&format!(" {}\n", d)); for dep in dep_list.iter() { if is_forward { dot_src.push_str(&format!(" {} -> {}\n", d, dep)); } else { dot_src.push_str(&format!(" {} -> {}\n", dep, d)); } if!visited.contains(dep) { visited.insert(dep.clone()); queue.push_back(dep.clone()); } } } let out_file = out_dir.join(format!( "{}.{}.dot", module, (if is_forward { "forward" } else { "backward" }).to_string() )); fs::write( &out_file, format!("digraph G {{\n rankdir=BT\n{}}}\n", dot_src), )?; println!("{:?}", out_file); } Ok(()) } fn generate(inp_dir: &Path, out_dir: &Path) -> anyhow::Result<()> { let mut dep_graph: BTreeMap<String, Vec<String>> = BTreeMap::new(); let mut dep_graph_inverse: BTreeMap<String, Vec<String>> = BTreeMap::new(); println!("The stdlib files detected:"); for entry in fs::read_dir(inp_dir)? { let entry = entry?; let path = entry.path(); if path.is_dir() || path.extension().is_none() ||!path.extension().unwrap().eq("move") { // skip anything other than.move file. continue; } println!("{:?}", path); let content = fs::read_to_string(path)?; let rex1 = Regex::new(r"(?m)^module\s+(\w+)\s*\{").unwrap(); let caps = rex1.captures(&content); if caps.is_none() { // skip due to no module declaration found. continue; } let module_name = caps.unwrap()[1].to_string(); if let Entry::Vacant(e) = dep_graph_inverse.entry(module_name.clone()) { e.insert(vec![]); } let mut dep_list: Vec<String> = Vec::new(); // TODO: This is not 100% correct because modules can be used with full qualification and without `use`. // Refer to `move-prover/src/lib.rs` which correctly addresses this issue. let rex2 = Regex::new(r"(?m)use 0x1::(\w+)\s*(;|:)").unwrap(); for cap in rex2.captures_iter(&content) { let dep = cap.get(1).unwrap().as_str().to_string(); dep_list.push(dep.clone()); match dep_graph_inverse.entry(dep) { Entry::Vacant(e) => { e.insert(vec![module_name.clone()]); } Entry::Occupied(mut e) => { e.get_mut().push(module_name.clone()); } } } dep_graph.insert(module_name, dep_list); } fs::create_dir_all(out_dir)?; // Generate a.dot file for the entire dependency graph. let mut dot_src: String = String::new(); for (module, dep_list) in dep_graph.iter() { dot_src.push_str(&format!(" {}\n", module)); for dep in dep_list.iter() { dot_src.push_str(&format!(" {} -> {}\n", module, dep)); } } fs::write( out_dir.join("(EntireGraph).dot"), format!("digraph G {{\n rankdir=BT\n{}}}\n", dot_src), )?; println!( "\nThe diagram files (.dot) generated:\n{:?}", out_dir.join("(EntireGraph).dot") ); // Generate a.forward.dot file for the forward dependency graph per module. generate_diagram_per_module(&dep_graph, out_dir, true)?; // Generate a.backward.dot file for the backward dependency graph per module. generate_diagram_per_module(&dep_graph_inverse, out_dir, false)?; println!( "\nTo convert these.dot files into.pdf files, run {:?}.", out_dir.join("convert_all_dot_to_pdf.sh") ); Ok(()) } fn locate_inp_out_dir() -> (PathBuf, PathBuf) { // locate the language directory let lang_dir = env::current_exe() .unwrap() .parent() .unwrap() .parent() .unwrap() .parent() .unwrap() .join("language"); println!("The `language` directory is located as:\n{:?}\n", lang_dir); // construct the input and the output paths let inp_dir = lang_dir.join("stdlib/modules"); let out_dir = lang_dir.join("move-prover/diagen/diagrams"); (inp_dir, out_dir) } fn main()
{ let (inp_dir, out_dir) = locate_inp_out_dir(); let err = generate(inp_dir.as_path(), out_dir.as_path()); if let Err(err) = err { println!("Error: {:?}", err); } }
identifier_body
main.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use regex::Regex; use std::{ collections::{btree_map::Entry, BTreeMap, BTreeSet, VecDeque}, env, fs, path::{Path, PathBuf}, }; fn generate_diagram_per_module( graph: &BTreeMap<String, Vec<String>>, out_dir: &Path, is_forward: bool, ) -> anyhow::Result<()> { let empty_list = Vec::new(); for (module, _) in graph.iter() { // (breadth-first) search and gather the modules in `graph` which are reachable from `module`. let mut dot_src: String = String::new(); let mut visited: BTreeSet<String> = BTreeSet::new(); let mut queue: VecDeque<String> = VecDeque::new(); visited.insert(module.clone()); queue.push_back(module.clone()); while let Some(d) = queue.pop_front() { let dep_list = graph.get(&d).unwrap_or(&empty_list); dot_src.push_str(&format!(" {}\n", d)); for dep in dep_list.iter() { if is_forward { dot_src.push_str(&format!(" {} -> {}\n", d, dep)); } else { dot_src.push_str(&format!(" {} -> {}\n", dep, d)); } if!visited.contains(dep) { visited.insert(dep.clone()); queue.push_back(dep.clone()); } } } let out_file = out_dir.join(format!( "{}.{}.dot", module, (if is_forward { "forward" } else { "backward" }).to_string() )); fs::write( &out_file, format!("digraph G {{\n rankdir=BT\n{}}}\n", dot_src), )?; println!("{:?}", out_file); } Ok(()) } fn generate(inp_dir: &Path, out_dir: &Path) -> anyhow::Result<()> { let mut dep_graph: BTreeMap<String, Vec<String>> = BTreeMap::new(); let mut dep_graph_inverse: BTreeMap<String, Vec<String>> = BTreeMap::new(); println!("The stdlib files detected:"); for entry in fs::read_dir(inp_dir)? { let entry = entry?; let path = entry.path(); if path.is_dir() || path.extension().is_none() ||!path.extension().unwrap().eq("move") { // skip anything other than.move file. continue; } println!("{:?}", path); let content = fs::read_to_string(path)?; let rex1 = Regex::new(r"(?m)^module\s+(\w+)\s*\{").unwrap(); let caps = rex1.captures(&content); if caps.is_none()
let module_name = caps.unwrap()[1].to_string(); if let Entry::Vacant(e) = dep_graph_inverse.entry(module_name.clone()) { e.insert(vec![]); } let mut dep_list: Vec<String> = Vec::new(); // TODO: This is not 100% correct because modules can be used with full qualification and without `use`. // Refer to `move-prover/src/lib.rs` which correctly addresses this issue. let rex2 = Regex::new(r"(?m)use 0x1::(\w+)\s*(;|:)").unwrap(); for cap in rex2.captures_iter(&content) { let dep = cap.get(1).unwrap().as_str().to_string(); dep_list.push(dep.clone()); match dep_graph_inverse.entry(dep) { Entry::Vacant(e) => { e.insert(vec![module_name.clone()]); } Entry::Occupied(mut e) => { e.get_mut().push(module_name.clone()); } } } dep_graph.insert(module_name, dep_list); } fs::create_dir_all(out_dir)?; // Generate a.dot file for the entire dependency graph. let mut dot_src: String = String::new(); for (module, dep_list) in dep_graph.iter() { dot_src.push_str(&format!(" {}\n", module)); for dep in dep_list.iter() { dot_src.push_str(&format!(" {} -> {}\n", module, dep)); } } fs::write( out_dir.join("(EntireGraph).dot"), format!("digraph G {{\n rankdir=BT\n{}}}\n", dot_src), )?; println!( "\nThe diagram files (.dot) generated:\n{:?}", out_dir.join("(EntireGraph).dot") ); // Generate a.forward.dot file for the forward dependency graph per module. generate_diagram_per_module(&dep_graph, out_dir, true)?; // Generate a.backward.dot file for the backward dependency graph per module. generate_diagram_per_module(&dep_graph_inverse, out_dir, false)?; println!( "\nTo convert these.dot files into.pdf files, run {:?}.", out_dir.join("convert_all_dot_to_pdf.sh") ); Ok(()) } fn locate_inp_out_dir() -> (PathBuf, PathBuf) { // locate the language directory let lang_dir = env::current_exe() .unwrap() .parent() .unwrap() .parent() .unwrap() .parent() .unwrap() .join("language"); println!("The `language` directory is located as:\n{:?}\n", lang_dir); // construct the input and the output paths let inp_dir = lang_dir.join("stdlib/modules"); let out_dir = lang_dir.join("move-prover/diagen/diagrams"); (inp_dir, out_dir) } fn main() { let (inp_dir, out_dir) = locate_inp_out_dir(); let err = generate(inp_dir.as_path(), out_dir.as_path()); if let Err(err) = err { println!("Error: {:?}", err); } }
{ // skip due to no module declaration found. continue; }
conditional_block
doc.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. /*! Region inference module. # Terminology Note that we use the terms region and lifetime interchangeably, though the term `lifetime` is preferred. # Introduction Region inference uses a somewhat more involved algorithm than type inference. It is not the most efficient thing ever written though it seems to work well enough in practice (famous last words). The reason that we use a different algorithm is because, unlike with types, it is impractical to hand-annotate with regions (in some cases, there aren't even the requisite syntactic forms). So we have to get it right, and it's worth spending more time on a more involved analysis. Moreover, regions are a simpler case than types: they don't have aggregate structure, for example. Unlike normal type inference, which is similar in spirit to H-M and thus works progressively, the region type inference works by accumulating constraints over the course of a function. Finally, at the end of processing a function, we process and solve the constraints all at once. The constraints are always of one of three possible forms: - ConstrainVarSubVar(R_i, R_j) states that region variable R_i must be a subregion of R_j - ConstrainRegSubVar(R, R_i) states that the concrete region R (which must not be a variable) must be a subregion of the varibale R_i - ConstrainVarSubReg(R_i, R) is the inverse # Building up the constraints Variables and constraints are created using the following methods: - `new_region_var()` creates a new, unconstrained region variable; - `make_subregion(R_i, R_j)` states that R_i is a subregion of R_j - `lub_regions(R_i, R_j) -> R_k` returns a region R_k which is the smallest region that is greater than both R_i and R_j - `glb_regions(R_i, R_j) -> R_k` returns a region R_k which is the greatest region that is smaller than both R_i and R_j The actual region resolution algorithm is not entirely obvious, though it is also not overly complex. ## Snapshotting It is also permitted to try (and rollback) changes to the graph. This is done by invoking `start_snapshot()`, which returns a value. Then later you can call `rollback_to()` which undoes the work. Alternatively, you can call `commit()` which ends all snapshots. Snapshots can be recursive---so you can start a snapshot when another is in progress, but only the root snapshot can "commit". # Resolving constraints The constraint resolution algorithm is not super complex but also not entirely obvious. Here I describe the problem somewhat abstractly, then describe how the current code works. There may be other, smarter ways of doing this with which I am unfamiliar and can't be bothered to research at the moment. - NDM ## The problem Basically our input is a directed graph where nodes can be divided into two categories: region variables and concrete regions. Each edge `R -> S` in the graph represents a constraint that the region `R` is a subregion of the region `S`. Region variable nodes can have arbitrary degree. There is one region variable node per region variable. Each concrete region node is associated with some, well, concrete region: e.g., a free lifetime, or the region for a particular scope. Note that there may be more than one concrete region node for a particular region value. Moreover, because of how the graph is built, we know that all concrete region nodes have either in-degree 1 or out-degree 1. Before resolution begins, we build up the constraints in a hashmap that maps `Constraint` keys to spans. During resolution, we construct the actual `Graph` structure that we describe here. ## Our current algorithm We divide region variables into two groups: Expanding and Contracting. Expanding region variables are those that have a concrete region predecessor (direct or indirect). Contracting region variables are all others. We first resolve the values of Expanding region variables and then process Contracting ones. We currently use an iterative, fixed-point procedure (but read on, I believe this could be replaced with a linear walk). Basically we iterate over the edges in the graph, ensuring that, if the source of the edge has a value, then this value is a subregion of the target value. If the target does not yet have a value, it takes the value from the source. If the target already had a value, then the resulting value is Least Upper Bound of the old and new values. When we are done, each Expanding node will have the smallest region that it could possibly have and still satisfy the constraints. We next process the Contracting nodes. Here we again iterate over the edges, only this time we move values from target to source (if the source is a Contracting node). For each contracting node, we compute its value as the GLB of all its successors. Basically contracting nodes ensure that there is overlap between their successors; we will ultimately infer the largest overlap possible. # The Region Hierarchy ## Without closures Let's first consider the region hierarchy without thinking about closures, because they add a lot of complications. The region hierarchy *basically* mirrors the lexical structure of the code. There is a region for every piece of 'evaluation' that occurs, meaning every expression, block, and pattern (patterns are considered to "execute" by testing the value they are applied to and creating any relevant bindings). So, for example: fn foo(x: int, y: int) { // -+ // +------------+ // | // | +-----+ // | // | +-+ +-+ +-+ // | // | | | | | | | // | // v v v v v v v // | let z = x + y; // | ... // | } // -+ fn bar() {... } In this example, there is a region for the fn body block as a whole, and then a subregion for the declaration of the local variable. Within that, there are sublifetimes for the assignment pattern and also the expression `x + y`. The expression itself has sublifetimes for evaluating `x` and `y`. ## Function calls Function calls are a bit tricky. I will describe how we handle them *now* and then a bit about how we can improve them (Issue #6268). Consider a function call like `func(expr1, expr2)`, where `func`, `arg1`, and `arg2` are all arbitrary expressions. Currently, we construct a region hierarchy like: +----------------+ | | +--+ +---+ +---+| v v v v v vv func(expr1, expr2) Here you can see that the call as a whole has a region and the function plus arguments are subregions of that. As a side-effect of this, we get a lot of spurious errors around nested calls, in particular when combined with `&mut` functions. For example, a call like this one self.foo(self.bar()) where both `foo` and `bar` are `&mut self` functions will always yield an error. Here is a more involved example (which is safe) so we can see what's going on: struct Foo { f: uint, g: uint } ... fn add(p: &mut uint, v: uint) { *p += v; } ... fn inc(p: &mut uint) -> uint { *p += 1; *p } fn weird() { let mut x: Box<Foo> = box Foo {... }; 'a: add(&mut (*x).f, 'b: inc(&mut (*x).f)) // (..) } The important part is the line marked `(..)` which contains a call to `add()`. The first argument is a mutable borrow of the field `f`. The second argument also borrows the field `f`. Now, in the current borrow checker, the first borrow is given the lifetime of the call to `add()`, `'a`. The second borrow is given the lifetime of `'b` of the call to `inc()`. Because `'b` is considered to be a sublifetime of `'a`, an error is reported since there are two co-existing mutable borrows of the same data. However, if we were to examine the lifetimes a bit more carefully, we can see that this error is unnecessary. Let's examine the lifetimes involved with `'a` in detail. We'll break apart all the steps involved in a call expression: 'a: { 'a_arg1: let a_temp1:... = add; 'a_arg2: let a_temp2: &'a mut uint = &'a mut (*x).f; 'a_arg3: let a_temp3: uint = { let b_temp1:... = inc; let b_temp2: &'b = &'b mut (*x).f; 'b_call: b_temp1(b_temp2) }; 'a_call: a_temp1(a_temp2, a_temp3) // (**) } Here we see that the lifetime `'a` includes a number of substatements. In particular, there is this lifetime I've called `'a_call` that corresponds to the *actual execution of the function `add()`*, after all arguments have been evaluated. There is a corresponding lifetime `'b_call` for the execution of `inc()`. If we wanted to be precise about it, the lifetime of the two borrows should be `'a_call` and `'b_call` respectively, since the references that were created will not be dereferenced except during the execution itself. However, this model by itself is not sound. The reason is that while the two references that are created will never be used simultaneously, it is still true that the first reference is *created* before the second argument is evaluated, and so even though it will not be *dereferenced* during the evaluation of the second argument, it can still be *invalidated* by that evaluation. Consider this similar but unsound example: struct Foo { f: uint, g: uint } ... fn add(p: &mut uint, v: uint) { *p += v; } ... fn consume(x: Box<Foo>) -> uint { x.f + x.g } fn weird() { let mut x: Box<Foo> = box Foo {... }; 'a: add(&mut (*x).f, consume(x)) // (..) } In this case, the second argument to `add` actually consumes `x`, thus invalidating the first argument. So, for now, we exclude the `call` lifetimes from our model. Eventually I would like to include them, but we will have to make the borrow checker handle this situation correctly. In particular, if there is a reference created whose lifetime does not enclose the borrow expression, we must issue sufficient restrictions to ensure that the pointee remains valid. ## Adding closures The other significant complication to the region hierarchy is closures. I will describe here how closures should work, though some of the work to implement this model is ongoing at the time of this writing. The body of closures are type-checked along with the function that creates them. However, unlike other expressions that appear within the function body, it is not entirely obvious when a closure body executes with respect to the other expressions. This is because the closure body will execute whenever the closure is called; however, we can never know precisely when the closure will be called, especially without some sort of alias analysis. However, we can place some sort of limits on when the closure executes. In particular, the type of every closure `fn:'r K` includes a region bound `'r`. This bound indicates the maximum lifetime of that closure; once we exit that region, the closure cannot be called anymore. Therefore, we say that the lifetime of the closure body is a sublifetime of the closure bound, but the closure body itself is unordered with respect to other parts of the code. For example, consider the following fragment of code: 'a: { let closure: fn:'a() = || 'b: { 'c:... }; 'd:... } Here we have four lifetimes, `'a`, `'b`, `'c`, and `'d`. The closure `closure` is bounded by the lifetime `'a`. The lifetime `'b` is the lifetime of the closure body, and `'c` is some statement within the closure body. Finally, `'d` is a statement within the outer block that created the closure. We can say that the closure body `'b` is a sublifetime of `'a` due to the closure bound. By the usual lexical scoping conventions, the statement `'c` is clearly a sublifetime of `'b`, and `'d` is a sublifetime of `'d`. However, there is no ordering between `'c` and `'d` per se (this kind of ordering between statements is actually only an issue for dataflow; passes like the borrow checker must assume that closures could execute at any time from the moment they are created until they go out of scope). ### Complications due to closure bound inference There is only one problem with the above model: in general, we do not actually *know* the closure bounds during region inference! In fact, closure bounds are almost always region variables! This is very tricky because the inference system implicitly assumes that we can do things like compute the LUB of two scoped lifetimes without needing to know the values of any variables. Here is an example to illustrate the problem: fn identify<T>(x: T) -> T { x } fn foo() { // 'foo is the function body 'a: { let closure = identity(|| 'b: { 'c:... }); 'd: closure(); } 'e:...;
In this example, the closure bound is not explicit. At compile time, we will create a region variable (let's call it `V0`) to represent the closure bound. The primary difficulty arises during the constraint propagation phase. Imagine there is some variable with incoming edges from `'c` and `'d`. This means that the value of the variable must be `LUB('c, 'd)`. However, without knowing what the closure bound `V0` is, we can't compute the LUB of `'c` and `'d`! Any we don't know the closure bound until inference is done. The solution is to rely on the fixed point nature of inference. Basically, when we must compute `LUB('c, 'd)`, we just use the current value for `V0` as the closure's bound. If `V0`'s binding should change, then we will do another round of inference, and the result of `LUB('c, 'd)` will change. One minor implication of this is that the graph does not in fact track the full set of dependencies between edges. We cannot easily know whether the result of a LUB computation will change, since there may be indirect dependencies on other variables that are not reflected on the graph. Therefore, we must *always* iterate over all edges when doing the fixed point calculation, not just those adjacent to nodes whose values have changed. Were it not for this requirement, we could in fact avoid fixed-point iteration altogether. In that universe, we could instead first identify and remove strongly connected components (SCC) in the graph. Note that such components must consist solely of region variables; all of these variables can effectively be unified into a single variable. Once SCCs are removed, we are left with a DAG. At this point, we could walk the DAG in topological order once to compute the expanding nodes, and again in reverse topological order to compute the contracting nodes. However, as I said, this does not work given the current treatment of closure bounds, but perhaps in the future we can address this problem somehow and make region inference somewhat more efficient. Note that this is solely a matter of performance, not expressiveness. ### Skolemization For a discussion on skolemization and higher-ranked subtyping, please see the module `middle::typeck::infer::higher_ranked::doc`. */
}
random_line_split
partial_cmp.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // impl PartialOrd for str { // #[inline] // fn partial_cmp(&self, other: &str) -> Option<Ordering> { // Some(self.cmp(other)) // } // } #[test] fn partial_cmp_test1() { let x: &str = "日"; // '\u{65e5}' let other: &str = "月"; // '\u{6708}' let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Less)); } #[test] fn partial_cmp_test2() { l
test] fn partial_cmp_test3() { let x: &str = "人"; let other: &str = x; let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Equal)); } #[test] fn partial_cmp_test4() { let x: &str = "人口"; let other: &str = "人"; let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Greater)); } #[test] fn partial_cmp_test5() { let x: &str = "人"; let other: &str = "人種"; let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Less)); } }
et x: &str = "天"; // '\u{5929}' let other: &str = "地"; // '\u{5730}' let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Greater)); } #[
identifier_body
partial_cmp.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // impl PartialOrd for str { // #[inline] // fn partial_cmp(&self, other: &str) -> Option<Ordering> { // Some(self.cmp(other)) // } // } #[test] fn partial_cmp_test1() { let x: &str = "日"; // '\u{65e5}' let other: &str = "月"; // '\u{6708}' let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Less)); } #[test] fn part
let x: &str = "天"; // '\u{5929}' let other: &str = "地"; // '\u{5730}' let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Greater)); } #[test] fn partial_cmp_test3() { let x: &str = "人"; let other: &str = x; let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Equal)); } #[test] fn partial_cmp_test4() { let x: &str = "人口"; let other: &str = "人"; let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Greater)); } #[test] fn partial_cmp_test5() { let x: &str = "人"; let other: &str = "人種"; let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Less)); } }
ial_cmp_test2() {
identifier_name
partial_cmp.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // impl PartialOrd for str { // #[inline] // fn partial_cmp(&self, other: &str) -> Option<Ordering> { // Some(self.cmp(other)) // } // } #[test] fn partial_cmp_test1() { let x: &str = "日"; // '\u{65e5}' let other: &str = "月"; // '\u{6708}' let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Less)); } #[test] fn partial_cmp_test2() { let x: &str = "天"; // '\u{5929}'
assert_eq!(result, Some::<Ordering>(Greater)); } #[test] fn partial_cmp_test3() { let x: &str = "人"; let other: &str = x; let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Equal)); } #[test] fn partial_cmp_test4() { let x: &str = "人口"; let other: &str = "人"; let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Greater)); } #[test] fn partial_cmp_test5() { let x: &str = "人"; let other: &str = "人種"; let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Less)); } }
let other: &str = "地"; // '\u{5730}' let result: Option<Ordering> = x.partial_cmp(other);
random_line_split
errors.rs
use serde::ser::Serialize; use serde_json::Value; use api::rpc::Error; pub fn parse_error() -> Error { Error { message: "parse error".to_owned(), code: -32700, data: None, } } pub fn invalid_request() -> Error { Error { message: "invalid request".to_owned(), code: -32600, data: None, } } pub fn invalid_version() -> Error
pub fn method_not_found() -> Error { Error { message: "method not found".to_owned(), code: -32601, data: None, } } // pub fn invalid_params(params: Value) -> Error { // Error { // code: -32602, // message: "invalid params".to_owned(), // data: params, // } // } pub fn invalid_param(param: &str, reason: &str) -> Error { Error { code: -32602, message: "invalid params".to_owned(), data: Some(json!([{ param: reason }])), } } pub fn internal_error() -> Error { Error { message: "internal error".to_owned(), code: -32603, data: None, } } pub fn scope_not_found() -> Error { Error { message: "scope_not_found".to_owned(), code: -32000, data: None, } }
{ Error { code: -32600, message: "unsupported JSON-RPC protocol version".to_owned(), data: None, } }
identifier_body
errors.rs
use serde::ser::Serialize; use serde_json::Value; use api::rpc::Error; pub fn parse_error() -> Error { Error { message: "parse error".to_owned(), code: -32700, data: None, } } pub fn
() -> Error { Error { message: "invalid request".to_owned(), code: -32600, data: None, } } pub fn invalid_version() -> Error { Error { code: -32600, message: "unsupported JSON-RPC protocol version".to_owned(), data: None, } } pub fn method_not_found() -> Error { Error { message: "method not found".to_owned(), code: -32601, data: None, } } // pub fn invalid_params(params: Value) -> Error { // Error { // code: -32602, // message: "invalid params".to_owned(), // data: params, // } // } pub fn invalid_param(param: &str, reason: &str) -> Error { Error { code: -32602, message: "invalid params".to_owned(), data: Some(json!([{ param: reason }])), } } pub fn internal_error() -> Error { Error { message: "internal error".to_owned(), code: -32603, data: None, } } pub fn scope_not_found() -> Error { Error { message: "scope_not_found".to_owned(), code: -32000, data: None, } }
invalid_request
identifier_name
errors.rs
use serde::ser::Serialize; use serde_json::Value; use api::rpc::Error; pub fn parse_error() -> Error { Error { message: "parse error".to_owned(), code: -32700, data: None, } } pub fn invalid_request() -> Error { Error { message: "invalid request".to_owned(), code: -32600, data: None, } } pub fn invalid_version() -> Error {
} pub fn method_not_found() -> Error { Error { message: "method not found".to_owned(), code: -32601, data: None, } } // pub fn invalid_params(params: Value) -> Error { // Error { // code: -32602, // message: "invalid params".to_owned(), // data: params, // } // } pub fn invalid_param(param: &str, reason: &str) -> Error { Error { code: -32602, message: "invalid params".to_owned(), data: Some(json!([{ param: reason }])), } } pub fn internal_error() -> Error { Error { message: "internal error".to_owned(), code: -32603, data: None, } } pub fn scope_not_found() -> Error { Error { message: "scope_not_found".to_owned(), code: -32000, data: None, } }
Error { code: -32600, message: "unsupported JSON-RPC protocol version".to_owned(), data: None, }
random_line_split
kshiftrd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn kshiftrd_1() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K7)), operand2: Some(Direct(K6)), operand3: Some(Literal8(51)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 254, 51], OperandSize::Dword) } fn kshiftrd_2()
{ run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K5)), operand2: Some(Direct(K7)), operand3: Some(Literal8(99)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 239, 99], OperandSize::Qword) }
identifier_body
kshiftrd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn kshiftrd_1() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K7)), operand2: Some(Direct(K6)), operand3: Some(Literal8(51)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 254, 51], OperandSize::Dword) } fn
() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K5)), operand2: Some(Direct(K7)), operand3: Some(Literal8(99)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 239, 99], OperandSize::Qword) }
kshiftrd_2
identifier_name
kshiftrd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*;
fn kshiftrd_1() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K7)), operand2: Some(Direct(K6)), operand3: Some(Literal8(51)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 254, 51], OperandSize::Dword) } fn kshiftrd_2() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K5)), operand2: Some(Direct(K7)), operand3: Some(Literal8(99)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 239, 99], OperandSize::Qword) }
use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*;
random_line_split
i386_apple_ios.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use target::Target; use super::apple_ios_base::{opts, Arch}; pub fn
() -> Target { Target { data_layout: "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16\ -i32:32:32-i64:32:64\ -f32:32:32-f64:32:64-v64:64:64\ -v128:128:128-a:0:64-f80:128:128\ -n8:16:32".to_string(), llvm_target: "i386-apple-ios".to_string(), target_endian: "little".to_string(), target_pointer_width: "32".to_string(), arch: "x86".to_string(), target_os: "ios".to_string(), target_env: "".to_string(), options: opts(Arch::I386) } }
target
identifier_name
i386_apple_ios.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use target::Target; use super::apple_ios_base::{opts, Arch}; pub fn target() -> Target
{ Target { data_layout: "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16\ -i32:32:32-i64:32:64\ -f32:32:32-f64:32:64-v64:64:64\ -v128:128:128-a:0:64-f80:128:128\ -n8:16:32".to_string(), llvm_target: "i386-apple-ios".to_string(), target_endian: "little".to_string(), target_pointer_width: "32".to_string(), arch: "x86".to_string(), target_os: "ios".to_string(), target_env: "".to_string(), options: opts(Arch::I386) } }
identifier_body
i386_apple_ios.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use target::Target; use super::apple_ios_base::{opts, Arch}; pub fn target() -> Target { Target { data_layout: "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16\ -i32:32:32-i64:32:64\ -f32:32:32-f64:32:64-v64:64:64\ -v128:128:128-a:0:64-f80:128:128\ -n8:16:32".to_string(), llvm_target: "i386-apple-ios".to_string(), target_endian: "little".to_string(), target_pointer_width: "32".to_string(),
arch: "x86".to_string(), target_os: "ios".to_string(), target_env: "".to_string(), options: opts(Arch::I386) } }
random_line_split
debug_utils.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 std::slice; fn hexdump_slice(buf: &[u8]) { let mut stderr = io::stderr(); stderr.write_all(b" ").unwrap(); for (i, &v) in buf.iter().enumerate() { let output = format!("{:02X} ", v); stderr.write_all(output.as_bytes()).unwrap(); match i % 16 { 15 => { stderr.write_all(b"\n ").unwrap(); }, 7 => { stderr.write_all(b" ").unwrap(); }, _ => () } stderr.flush().unwrap(); } stderr.write_all(b"\n").unwrap(); } pub fn hexdump<T>(obj: &T) { unsafe { let buf: *const u8 = mem::transmute(obj); debug!("dumping at {:p}", buf); let from_buf = slice::from_raw_parts(buf, size_of::<T>()); hexdump_slice(from_buf); } }
use std::io::{self, Write}; use std::mem; use std::mem::size_of;
random_line_split
debug_utils.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 std::io::{self, Write}; use std::mem; use std::mem::size_of; use std::slice; fn hexdump_slice(buf: &[u8]) { let mut stderr = io::stderr(); stderr.write_all(b" ").unwrap(); for (i, &v) in buf.iter().enumerate() { let output = format!("{:02X} ", v); stderr.write_all(output.as_bytes()).unwrap(); match i % 16 { 15 => { stderr.write_all(b"\n ").unwrap(); }, 7 => { stderr.write_all(b" ").unwrap(); }, _ => () } stderr.flush().unwrap(); } stderr.write_all(b"\n").unwrap(); } pub fn hexdump<T>(obj: &T)
{ unsafe { let buf: *const u8 = mem::transmute(obj); debug!("dumping at {:p}", buf); let from_buf = slice::from_raw_parts(buf, size_of::<T>()); hexdump_slice(from_buf); } }
identifier_body
debug_utils.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 std::io::{self, Write}; use std::mem; use std::mem::size_of; use std::slice; fn
(buf: &[u8]) { let mut stderr = io::stderr(); stderr.write_all(b" ").unwrap(); for (i, &v) in buf.iter().enumerate() { let output = format!("{:02X} ", v); stderr.write_all(output.as_bytes()).unwrap(); match i % 16 { 15 => { stderr.write_all(b"\n ").unwrap(); }, 7 => { stderr.write_all(b" ").unwrap(); }, _ => () } stderr.flush().unwrap(); } stderr.write_all(b"\n").unwrap(); } pub fn hexdump<T>(obj: &T) { unsafe { let buf: *const u8 = mem::transmute(obj); debug!("dumping at {:p}", buf); let from_buf = slice::from_raw_parts(buf, size_of::<T>()); hexdump_slice(from_buf); } }
hexdump_slice
identifier_name
vm.rs
', not 'find'). This is a half-measure, but does provide some // perf improvement. // // AFAIK, the DFA/NFA approach is implemented in RE2/C++ but *not* in RE2/Go. // // [1] - http://swtch.com/~rsc/regex/regex3.html pub use self::MatchKind::*; pub use self::StepState::*; use std::cmp; use std::cmp::Ordering::{self, Less, Equal, Greater}; use std::mem; use std::iter::repeat; use std::slice::SliceExt; use compile::{ Program, Match, OneChar, CharClass, Any, EmptyBegin, EmptyEnd, EmptyWordBoundary, Save, Jump, Split, }; use parse::{FLAG_NOCASE, FLAG_MULTI, FLAG_DOTNL, FLAG_NEGATED}; use unicode::regex::PERLW; pub type CaptureLocs = Vec<Option<uint>>; /// Indicates the type of match to be performed by the VM. #[derive(Copy)] pub enum MatchKind { /// Only checks if a match exists or not. Does not return location. Exists, /// Returns the start and end indices of the entire match in the input /// given. Location, /// Returns the start and end indices of each submatch in the input given. Submatches, } /// Runs an NFA simulation on the compiled expression given on the search text /// `input`. The search begins at byte index `start` and ends at byte index /// `end`. (The range is specified here so that zero-width assertions will work /// correctly when searching for successive non-overlapping matches.) /// /// The `which` parameter indicates what kind of capture information the caller /// wants. There are three choices: match existence only, the location of the /// entire match or the locations of the entire match in addition to the /// locations of each submatch. pub fn run<'r, 't>(which: MatchKind, prog: &'r Program, input: &'t str, start: uint, end: uint) -> CaptureLocs { Nfa { which: which, prog: prog, input: input, start: start, end: end, ic: 0, chars: CharReader::new(input), }.run() } struct Nfa<'r, 't> { which: MatchKind, prog: &'r Program, input: &'t str, start: uint, end: uint, ic: uint, chars: CharReader<'t>, } /// Indicates the next action to take after a single non-empty instruction /// is processed. #[derive(Copy)] pub enum StepState { /// This is returned if and only if a Match instruction is reached and /// we only care about the existence of a match. It instructs the VM to /// quit early. StepMatchEarlyReturn, /// Indicates that a match was found. Thus, the rest of the states in the /// *current* queue should be dropped (i.e., leftmost-first semantics). /// States in the "next" queue can still be processed. StepMatch, /// No match was found. Continue with the next state in the queue. StepContinue, } impl<'r, 't> Nfa<'r, 't> { fn run(&mut self) -> CaptureLocs { let ncaps = match self.which { Exists => 0, Location => 1, Submatches => self.prog.num_captures(), }; let mut matched = false; let ninsts = self.prog.insts.len(); let mut clist = &mut Threads::new(self.which, ninsts, ncaps); let mut nlist = &mut Threads::new(self.which, ninsts, ncaps); let mut groups: Vec<_> = repeat(None).take(ncaps * 2).collect(); // Determine if the expression starts with a '^' so we can avoid // simulating.*? // Make sure multi-line mode isn't enabled for it, otherwise we can't // drop the initial.*? let prefix_anchor = match self.prog.insts[1] { EmptyBegin(flags) if flags & FLAG_MULTI == 0 => true, _ => false, }; self.ic = self.start; let mut next_ic = self.chars.set(self.start); while self.ic <= self.end { if clist.size == 0 { // We have a match and we're done exploring alternatives. // Time to quit. if matched { break } // If there are no threads to try, then we'll have to start // over at the beginning of the regex. // BUT, if there's a literal prefix for the program, try to // jump ahead quickly. If it can't be found, then we can bail // out early. if self.prog.prefix.len() > 0 && clist.size == 0 { let needle = self.prog.prefix.as_bytes(); let haystack = &self.input.as_bytes()[self.ic..]; match find_prefix(needle, haystack) { None => break, Some(i) => { self.ic += i; next_ic = self.chars.set(self.ic); } } } } // This simulates a preceding '.*?' for every regex by adding // a state starting at the current position in the input for the // beginning of the program only if we don't already have a match. if clist.size == 0 || (!prefix_anchor &&!matched) { self.add(clist, 0, groups.as_mut_slice()) } // Now we try to read the next character. // As a result, the'step' method will look at the previous // character. self.ic = next_ic; next_ic = self.chars.advance(); for i in range(0, clist.size) { let pc = clist.pc(i); let step_state = self.step(groups.as_mut_slice(), nlist, clist.groups(i), pc); match step_state { StepMatchEarlyReturn => return vec![Some(0), Some(0)], StepMatch => { matched = true; break }, StepContinue => {}, } } mem::swap(&mut clist, &mut nlist); nlist.empty(); } match self.which { Exists if matched => vec![Some(0), Some(0)], Exists => vec![None, None], Location | Submatches => groups, } } fn step(&self, groups: &mut [Option<uint>], nlist: &mut Threads, caps: &mut [Option<uint>], pc: uint) -> StepState { match self.prog.insts[pc] { Match => { match self.which { Exists => { return StepMatchEarlyReturn } Location => { groups[0] = caps[0]; groups[1] = caps[1]; return StepMatch } Submatches => { for (slot, val) in groups.iter_mut().zip(caps.iter()) { *slot = *val; } return StepMatch } } } OneChar(c, flags) => { if self.char_eq(flags & FLAG_NOCASE > 0, self.chars.prev, c) { self.add(nlist, pc+1, caps); } } CharClass(ref ranges, flags) => { if self.chars.prev.is_some() { let c = self.chars.prev.unwrap(); let negate = flags & FLAG_NEGATED > 0; let casei = flags & FLAG_NOCASE > 0; let found = ranges.as_slice(); let found = found.binary_search_by(|&rc| class_cmp(casei, c, rc)).is_ok(); if found ^ negate { self.add(nlist, pc+1, caps); } } } Any(flags) => { if flags & FLAG_DOTNL > 0 ||!self.char_eq(false, self.chars.prev, '\n') { self.add(nlist, pc+1, caps) } } EmptyBegin(_) | EmptyEnd(_) | EmptyWordBoundary(_) | Save(_) | Jump(_) | Split(_, _) => {}, } StepContinue } fn add(&self, nlist: &mut Threads, pc: uint, groups: &mut [Option<uint>]) { if nlist.contains(pc) { return } // We have to add states to the threads list even if their empty. // TL;DR - It prevents cycles. // If we didn't care about cycles, we'd *only* add threads that // correspond to non-jumping instructions (OneChar, Any, Match, etc.). // But, it's possible for valid regexs (like '(a*)*') to result in // a cycle in the instruction list. e.g., We'll keep chasing the Split // instructions forever. // So we add these instructions to our thread queue, but in the main // VM loop, we look for them but simply ignore them. // Adding them to the queue prevents them from being revisited so we // can avoid cycles (and the inevitable stack overflow). // // We make a minor optimization by indicating that the state is "empty" // so that its capture groups are not filled in. match self.prog.insts[pc] { EmptyBegin(flags) => { let multi = flags & FLAG_MULTI > 0; nlist.add(pc, groups, true); if self.chars.is_begin() || (multi && self.char_is(self.chars.prev, '\n')) { self.add(nlist, pc + 1, groups) } } EmptyEnd(flags) => { let multi = flags & FLAG_MULTI > 0; nlist.add(pc, groups, true); if self.chars.is_end() || (multi && self.char_is(self.chars.cur, '\n')) { self.add(nlist, pc + 1, groups) } } EmptyWordBoundary(flags) => { nlist.add(pc, groups, true); if self.chars.is_word_boundary() ==!(flags & FLAG_NEGATED > 0) { self.add(nlist, pc + 1, groups) } } Save(slot) => { nlist.add(pc, groups, true); match self.which { Location if slot <= 1 => { let old = groups[slot]; groups[slot] = Some(self.ic); self.add(nlist, pc + 1, groups); groups[slot] = old; } Submatches => { let old = groups[slot]; groups[slot] = Some(self.ic); self.add(nlist, pc + 1, groups); groups[slot] = old; } Exists | Location => self.add(nlist, pc + 1, groups), } } Jump(to) => { nlist.add(pc, groups, true); self.add(nlist, to, groups) } Split(x, y) => { nlist.add(pc, groups, true); self.add(nlist, x, groups); self.add(nlist, y, groups); } Match | OneChar(_, _) | CharClass(_, _) | Any(_) => { nlist.add(pc, groups, false); } } } // FIXME: For case insensitive comparisons, it uses the uppercase // character and tests for equality. IIUC, this does not generalize to // all of Unicode. I believe we need to check the entire fold for each // character. This will be easy to add if and when it gets added to Rust's // standard library. #[inline] fn char_eq(&self, casei: bool, textc: Option<char>, regc: char) -> bool { match textc { None => false, Some(textc) => { regc == textc || (casei && regc.to_uppercase() == textc.to_uppercase()) } } } #[inline] fn char_is(&self, textc: Option<char>, regc: char) -> bool { textc == Some(regc) } } /// CharReader is responsible for maintaining a "previous" and a "current" /// character. This one-character lookahead is necessary for assertions that /// look one character before or after the current position. pub struct CharReader<'t> { /// The previous character read. It is None only when processing the first /// character of the input. pub prev: Option<char>, /// The current character. pub cur: Option<char>, input: &'t str, next: uint, } impl<'t> CharReader<'t> { /// Returns a new CharReader that advances through the input given. /// Note that a CharReader has no knowledge of the range in which to search /// the input. pub fn new(input: &'t str) -> CharReader<'t> { CharReader { prev: None, cur: None, input: input, next: 0, } } /// Sets the previous and current character given any arbitrary byte /// index (at a Unicode codepoint boundary). #[inline] pub fn set(&mut self, ic: uint) -> uint { self.prev = None; self.cur = None; self.next = 0; if self.input.len() == 0 { return 1 } if ic > 0 { let i = cmp::min(ic, self.input.len()); let prev = self.input.char_range_at_reverse(i); self.prev = Some(prev.ch); } if ic < self.input.len() { let cur = self.input.char_range_at(ic); self.cur = Some(cur.ch); self.next = cur.next; self.next } else { self.input.len() + 1 } } /// Does the same as `set`, except it always advances to the next /// character in the input (and therefore does half as many UTF8 decodings). #[inline] pub fn advance(&mut self) -> uint { self.prev = self.cur; if self.next < self.input.len() { let cur = self.input.char_range_at(self.next); self.cur = Some(cur.ch); self.next = cur.next; } else { self.cur = None; self.next = self.input.len() + 1; } self.next } /// Returns true if and only if this is the beginning of the input /// (ignoring the range of the input to search). #[inline] pub fn is_begin(&self) -> bool { self.prev.is_none() } /// Returns true if and only if this is the end of the input /// (ignoring the range of the input to search). #[inline] pub fn is_end(&self) -> bool { self.cur.is_none() } /// Returns true if and only if the current position is a word boundary. /// (Ignoring the range of the input to search.) pub fn is_word_boundary(&self) -> bool { if self.is_begin() { return is_word(self.cur) } if self.is_end() { return is_word(self.prev) } (is_word(self.cur) &&!is_word(self.prev)) || (is_word(self.prev) &&!is_word(self.cur)) } } struct Thread { pc: uint, groups: Vec<Option<uint>>, } struct Threads { which: MatchKind, queue: Vec<Thread>, sparse: Vec<uint>, size: uint, } impl Threads { // This is using a wicked neat trick to provide constant time lookup // for threads in the queue using a sparse set. A queue of threads is // allocated once with maximal size when the VM initializes and is reused // throughout execution. That is, there should be zero allocation during // the execution of a VM. // // See http://research.swtch.com/sparse for the deets. fn new(which: MatchKind, num_insts: uint, ncaps: uint) -> Threads { Threads { which: which, queue: range(0, num_insts).map(|_| { Thread { pc: 0, groups: repeat(None).take(ncaps * 2).collect() } }).collect(), sparse: repeat(0u).take(num_insts).collect(), size: 0, } }
fn add(&mut self, pc: uint, groups: &[Option<uint>], empty: bool) { let t = &mut self.queue[self.size]; t.pc = pc; match (empty, self.which) { (_, Exists) | (true, _) => {}, (false, Location) => { t.groups[0] = groups[0]; t.groups[1] = groups[1]; } (false, Submatches) => { for (slot, val) in t.groups.iter_mut().zip(groups.iter()) { *slot = *val; } } } self.sparse[pc] = self.size; self.size += 1; } #[inline] fn contains(&self, pc: uint) -> bool { let s = self.sparse[pc]; s < self.size && self.queue[s].pc == pc } #[inline] fn empty(&mut self) { self.size = 0; } #[inline] fn pc(&self, i: uint) -> uint { self.queue[i].pc } #[inline] fn groups<'r>(&'r mut self, i: uint) -> &'r mut [Option<uint>] { let q = &mut self.queue[i]; q.groups.as_mut_slice() } } /// Returns true if the character is a word character, according to the /// (Unicode friendly) Perl character class '\w'. ///
random_line_split
vm.rs
', not 'find'). This is a half-measure, but does provide some // perf improvement. // // AFAIK, the DFA/NFA approach is implemented in RE2/C++ but *not* in RE2/Go. // // [1] - http://swtch.com/~rsc/regex/regex3.html pub use self::MatchKind::*; pub use self::StepState::*; use std::cmp; use std::cmp::Ordering::{self, Less, Equal, Greater}; use std::mem; use std::iter::repeat; use std::slice::SliceExt; use compile::{ Program, Match, OneChar, CharClass, Any, EmptyBegin, EmptyEnd, EmptyWordBoundary, Save, Jump, Split, }; use parse::{FLAG_NOCASE, FLAG_MULTI, FLAG_DOTNL, FLAG_NEGATED}; use unicode::regex::PERLW; pub type CaptureLocs = Vec<Option<uint>>; /// Indicates the type of match to be performed by the VM. #[derive(Copy)] pub enum MatchKind { /// Only checks if a match exists or not. Does not return location. Exists, /// Returns the start and end indices of the entire match in the input /// given. Location, /// Returns the start and end indices of each submatch in the input given. Submatches, } /// Runs an NFA simulation on the compiled expression given on the search text /// `input`. The search begins at byte index `start` and ends at byte index /// `end`. (The range is specified here so that zero-width assertions will work /// correctly when searching for successive non-overlapping matches.) /// /// The `which` parameter indicates what kind of capture information the caller /// wants. There are three choices: match existence only, the location of the /// entire match or the locations of the entire match in addition to the /// locations of each submatch. pub fn run<'r, 't>(which: MatchKind, prog: &'r Program, input: &'t str, start: uint, end: uint) -> CaptureLocs { Nfa { which: which, prog: prog, input: input, start: start, end: end, ic: 0, chars: CharReader::new(input), }.run() } struct Nfa<'r, 't> { which: MatchKind, prog: &'r Program, input: &'t str, start: uint, end: uint, ic: uint, chars: CharReader<'t>, } /// Indicates the next action to take after a single non-empty instruction /// is processed. #[derive(Copy)] pub enum StepState { /// This is returned if and only if a Match instruction is reached and /// we only care about the existence of a match. It instructs the VM to /// quit early. StepMatchEarlyReturn, /// Indicates that a match was found. Thus, the rest of the states in the /// *current* queue should be dropped (i.e., leftmost-first semantics). /// States in the "next" queue can still be processed. StepMatch, /// No match was found. Continue with the next state in the queue. StepContinue, } impl<'r, 't> Nfa<'r, 't> { fn run(&mut self) -> CaptureLocs { let ncaps = match self.which { Exists => 0, Location => 1, Submatches => self.prog.num_captures(), }; let mut matched = false; let ninsts = self.prog.insts.len(); let mut clist = &mut Threads::new(self.which, ninsts, ncaps); let mut nlist = &mut Threads::new(self.which, ninsts, ncaps); let mut groups: Vec<_> = repeat(None).take(ncaps * 2).collect(); // Determine if the expression starts with a '^' so we can avoid // simulating.*? // Make sure multi-line mode isn't enabled for it, otherwise we can't // drop the initial.*? let prefix_anchor = match self.prog.insts[1] { EmptyBegin(flags) if flags & FLAG_MULTI == 0 => true, _ => false, }; self.ic = self.start; let mut next_ic = self.chars.set(self.start); while self.ic <= self.end { if clist.size == 0 { // We have a match and we're done exploring alternatives. // Time to quit. if matched { break } // If there are no threads to try, then we'll have to start // over at the beginning of the regex. // BUT, if there's a literal prefix for the program, try to // jump ahead quickly. If it can't be found, then we can bail // out early. if self.prog.prefix.len() > 0 && clist.size == 0 { let needle = self.prog.prefix.as_bytes(); let haystack = &self.input.as_bytes()[self.ic..]; match find_prefix(needle, haystack) { None => break, Some(i) => { self.ic += i; next_ic = self.chars.set(self.ic); } } } } // This simulates a preceding '.*?' for every regex by adding // a state starting at the current position in the input for the // beginning of the program only if we don't already have a match. if clist.size == 0 || (!prefix_anchor &&!matched) { self.add(clist, 0, groups.as_mut_slice()) } // Now we try to read the next character. // As a result, the'step' method will look at the previous // character. self.ic = next_ic; next_ic = self.chars.advance(); for i in range(0, clist.size) { let pc = clist.pc(i); let step_state = self.step(groups.as_mut_slice(), nlist, clist.groups(i), pc); match step_state { StepMatchEarlyReturn => return vec![Some(0), Some(0)], StepMatch => { matched = true; break }, StepContinue => {}, } } mem::swap(&mut clist, &mut nlist); nlist.empty(); } match self.which { Exists if matched => vec![Some(0), Some(0)], Exists => vec![None, None], Location | Submatches => groups, } } fn step(&self, groups: &mut [Option<uint>], nlist: &mut Threads, caps: &mut [Option<uint>], pc: uint) -> StepState { match self.prog.insts[pc] { Match => { match self.which { Exists => { return StepMatchEarlyReturn } Location => { groups[0] = caps[0]; groups[1] = caps[1]; return StepMatch } Submatches => { for (slot, val) in groups.iter_mut().zip(caps.iter()) { *slot = *val; } return StepMatch } } } OneChar(c, flags) => { if self.char_eq(flags & FLAG_NOCASE > 0, self.chars.prev, c) { self.add(nlist, pc+1, caps); } } CharClass(ref ranges, flags) => { if self.chars.prev.is_some() { let c = self.chars.prev.unwrap(); let negate = flags & FLAG_NEGATED > 0; let casei = flags & FLAG_NOCASE > 0; let found = ranges.as_slice(); let found = found.binary_search_by(|&rc| class_cmp(casei, c, rc)).is_ok(); if found ^ negate { self.add(nlist, pc+1, caps); } } } Any(flags) => { if flags & FLAG_DOTNL > 0 ||!self.char_eq(false, self.chars.prev, '\n') { self.add(nlist, pc+1, caps) } } EmptyBegin(_) | EmptyEnd(_) | EmptyWordBoundary(_) | Save(_) | Jump(_) | Split(_, _) => {}, } StepContinue } fn add(&self, nlist: &mut Threads, pc: uint, groups: &mut [Option<uint>]) { if nlist.contains(pc) { return } // We have to add states to the threads list even if their empty. // TL;DR - It prevents cycles. // If we didn't care about cycles, we'd *only* add threads that // correspond to non-jumping instructions (OneChar, Any, Match, etc.). // But, it's possible for valid regexs (like '(a*)*') to result in // a cycle in the instruction list. e.g., We'll keep chasing the Split // instructions forever. // So we add these instructions to our thread queue, but in the main // VM loop, we look for them but simply ignore them. // Adding them to the queue prevents them from being revisited so we // can avoid cycles (and the inevitable stack overflow). // // We make a minor optimization by indicating that the state is "empty" // so that its capture groups are not filled in. match self.prog.insts[pc] { EmptyBegin(flags) => { let multi = flags & FLAG_MULTI > 0; nlist.add(pc, groups, true); if self.chars.is_begin() || (multi && self.char_is(self.chars.prev, '\n')) { self.add(nlist, pc + 1, groups) } } EmptyEnd(flags) => { let multi = flags & FLAG_MULTI > 0; nlist.add(pc, groups, true); if self.chars.is_end() || (multi && self.char_is(self.chars.cur, '\n')) { self.add(nlist, pc + 1, groups) } } EmptyWordBoundary(flags) => { nlist.add(pc, groups, true); if self.chars.is_word_boundary() ==!(flags & FLAG_NEGATED > 0) { self.add(nlist, pc + 1, groups) } } Save(slot) => { nlist.add(pc, groups, true); match self.which { Location if slot <= 1 => { let old = groups[slot]; groups[slot] = Some(self.ic); self.add(nlist, pc + 1, groups); groups[slot] = old; } Submatches => { let old = groups[slot]; groups[slot] = Some(self.ic); self.add(nlist, pc + 1, groups); groups[slot] = old; } Exists | Location => self.add(nlist, pc + 1, groups), } } Jump(to) => { nlist.add(pc, groups, true); self.add(nlist, to, groups) } Split(x, y) => { nlist.add(pc, groups, true); self.add(nlist, x, groups); self.add(nlist, y, groups); } Match | OneChar(_, _) | CharClass(_, _) | Any(_) => { nlist.add(pc, groups, false); } } } // FIXME: For case insensitive comparisons, it uses the uppercase // character and tests for equality. IIUC, this does not generalize to // all of Unicode. I believe we need to check the entire fold for each // character. This will be easy to add if and when it gets added to Rust's // standard library. #[inline] fn char_eq(&self, casei: bool, textc: Option<char>, regc: char) -> bool { match textc { None => false, Some(textc) => { regc == textc || (casei && regc.to_uppercase() == textc.to_uppercase()) } } } #[inline] fn char_is(&self, textc: Option<char>, regc: char) -> bool { textc == Some(regc) } } /// CharReader is responsible for maintaining a "previous" and a "current" /// character. This one-character lookahead is necessary for assertions that /// look one character before or after the current position. pub struct CharReader<'t> { /// The previous character read. It is None only when processing the first /// character of the input. pub prev: Option<char>, /// The current character. pub cur: Option<char>, input: &'t str, next: uint, } impl<'t> CharReader<'t> { /// Returns a new CharReader that advances through the input given. /// Note that a CharReader has no knowledge of the range in which to search /// the input. pub fn new(input: &'t str) -> CharReader<'t> { CharReader { prev: None, cur: None, input: input, next: 0, } } /// Sets the previous and current character given any arbitrary byte /// index (at a Unicode codepoint boundary). #[inline] pub fn set(&mut self, ic: uint) -> uint { self.prev = None; self.cur = None; self.next = 0; if self.input.len() == 0 { return 1 } if ic > 0 { let i = cmp::min(ic, self.input.len()); let prev = self.input.char_range_at_reverse(i); self.prev = Some(prev.ch); } if ic < self.input.len() { let cur = self.input.char_range_at(ic); self.cur = Some(cur.ch); self.next = cur.next; self.next } else { self.input.len() + 1 } } /// Does the same as `set`, except it always advances to the next /// character in the input (and therefore does half as many UTF8 decodings). #[inline] pub fn advance(&mut self) -> uint { self.prev = self.cur; if self.next < self.input.len() { let cur = self.input.char_range_at(self.next); self.cur = Some(cur.ch); self.next = cur.next; } else { self.cur = None; self.next = self.input.len() + 1; } self.next } /// Returns true if and only if this is the beginning of the input /// (ignoring the range of the input to search). #[inline] pub fn is_begin(&self) -> bool { self.prev.is_none() } /// Returns true if and only if this is the end of the input /// (ignoring the range of the input to search). #[inline] pub fn is_end(&self) -> bool { self.cur.is_none() } /// Returns true if and only if the current position is a word boundary. /// (Ignoring the range of the input to search.) pub fn is_word_boundary(&self) -> bool { if self.is_begin() { return is_word(self.cur) } if self.is_end() { return is_word(self.prev) } (is_word(self.cur) &&!is_word(self.prev)) || (is_word(self.prev) &&!is_word(self.cur)) } } struct Thread { pc: uint, groups: Vec<Option<uint>>, } struct
{ which: MatchKind, queue: Vec<Thread>, sparse: Vec<uint>, size: uint, } impl Threads { // This is using a wicked neat trick to provide constant time lookup // for threads in the queue using a sparse set. A queue of threads is // allocated once with maximal size when the VM initializes and is reused // throughout execution. That is, there should be zero allocation during // the execution of a VM. // // See http://research.swtch.com/sparse for the deets. fn new(which: MatchKind, num_insts: uint, ncaps: uint) -> Threads { Threads { which: which, queue: range(0, num_insts).map(|_| { Thread { pc: 0, groups: repeat(None).take(ncaps * 2).collect() } }).collect(), sparse: repeat(0u).take(num_insts).collect(), size: 0, } } fn add(&mut self, pc: uint, groups: &[Option<uint>], empty: bool) { let t = &mut self.queue[self.size]; t.pc = pc; match (empty, self.which) { (_, Exists) | (true, _) => {}, (false, Location) => { t.groups[0] = groups[0]; t.groups[1] = groups[1]; } (false, Submatches) => { for (slot, val) in t.groups.iter_mut().zip(groups.iter()) { *slot = *val; } } } self.sparse[pc] = self.size; self.size += 1; } #[inline] fn contains(&self, pc: uint) -> bool { let s = self.sparse[pc]; s < self.size && self.queue[s].pc == pc } #[inline] fn empty(&mut self) { self.size = 0; } #[inline] fn pc(&self, i: uint) -> uint { self.queue[i].pc } #[inline] fn groups<'r>(&'r mut self, i: uint) -> &'r mut [Option<uint>] { let q = &mut self.queue[i]; q.groups.as_mut_slice() } } /// Returns true if the character is a word character, according to the /// (Unicode friendly) Perl character class '\w'.
Threads
identifier_name
vm.rs
', not 'find'). This is a half-measure, but does provide some // perf improvement. // // AFAIK, the DFA/NFA approach is implemented in RE2/C++ but *not* in RE2/Go. // // [1] - http://swtch.com/~rsc/regex/regex3.html pub use self::MatchKind::*; pub use self::StepState::*; use std::cmp; use std::cmp::Ordering::{self, Less, Equal, Greater}; use std::mem; use std::iter::repeat; use std::slice::SliceExt; use compile::{ Program, Match, OneChar, CharClass, Any, EmptyBegin, EmptyEnd, EmptyWordBoundary, Save, Jump, Split, }; use parse::{FLAG_NOCASE, FLAG_MULTI, FLAG_DOTNL, FLAG_NEGATED}; use unicode::regex::PERLW; pub type CaptureLocs = Vec<Option<uint>>; /// Indicates the type of match to be performed by the VM. #[derive(Copy)] pub enum MatchKind { /// Only checks if a match exists or not. Does not return location. Exists, /// Returns the start and end indices of the entire match in the input /// given. Location, /// Returns the start and end indices of each submatch in the input given. Submatches, } /// Runs an NFA simulation on the compiled expression given on the search text /// `input`. The search begins at byte index `start` and ends at byte index /// `end`. (The range is specified here so that zero-width assertions will work /// correctly when searching for successive non-overlapping matches.) /// /// The `which` parameter indicates what kind of capture information the caller /// wants. There are three choices: match existence only, the location of the /// entire match or the locations of the entire match in addition to the /// locations of each submatch. pub fn run<'r, 't>(which: MatchKind, prog: &'r Program, input: &'t str, start: uint, end: uint) -> CaptureLocs { Nfa { which: which, prog: prog, input: input, start: start, end: end, ic: 0, chars: CharReader::new(input), }.run() } struct Nfa<'r, 't> { which: MatchKind, prog: &'r Program, input: &'t str, start: uint, end: uint, ic: uint, chars: CharReader<'t>, } /// Indicates the next action to take after a single non-empty instruction /// is processed. #[derive(Copy)] pub enum StepState { /// This is returned if and only if a Match instruction is reached and /// we only care about the existence of a match. It instructs the VM to /// quit early. StepMatchEarlyReturn, /// Indicates that a match was found. Thus, the rest of the states in the /// *current* queue should be dropped (i.e., leftmost-first semantics). /// States in the "next" queue can still be processed. StepMatch, /// No match was found. Continue with the next state in the queue. StepContinue, } impl<'r, 't> Nfa<'r, 't> { fn run(&mut self) -> CaptureLocs { let ncaps = match self.which { Exists => 0, Location => 1, Submatches => self.prog.num_captures(), }; let mut matched = false; let ninsts = self.prog.insts.len(); let mut clist = &mut Threads::new(self.which, ninsts, ncaps); let mut nlist = &mut Threads::new(self.which, ninsts, ncaps); let mut groups: Vec<_> = repeat(None).take(ncaps * 2).collect(); // Determine if the expression starts with a '^' so we can avoid // simulating.*? // Make sure multi-line mode isn't enabled for it, otherwise we can't // drop the initial.*? let prefix_anchor = match self.prog.insts[1] { EmptyBegin(flags) if flags & FLAG_MULTI == 0 => true, _ => false, }; self.ic = self.start; let mut next_ic = self.chars.set(self.start); while self.ic <= self.end { if clist.size == 0 { // We have a match and we're done exploring alternatives. // Time to quit. if matched { break } // If there are no threads to try, then we'll have to start // over at the beginning of the regex. // BUT, if there's a literal prefix for the program, try to // jump ahead quickly. If it can't be found, then we can bail // out early. if self.prog.prefix.len() > 0 && clist.size == 0
} // This simulates a preceding '.*?' for every regex by adding // a state starting at the current position in the input for the // beginning of the program only if we don't already have a match. if clist.size == 0 || (!prefix_anchor &&!matched) { self.add(clist, 0, groups.as_mut_slice()) } // Now we try to read the next character. // As a result, the'step' method will look at the previous // character. self.ic = next_ic; next_ic = self.chars.advance(); for i in range(0, clist.size) { let pc = clist.pc(i); let step_state = self.step(groups.as_mut_slice(), nlist, clist.groups(i), pc); match step_state { StepMatchEarlyReturn => return vec![Some(0), Some(0)], StepMatch => { matched = true; break }, StepContinue => {}, } } mem::swap(&mut clist, &mut nlist); nlist.empty(); } match self.which { Exists if matched => vec![Some(0), Some(0)], Exists => vec![None, None], Location | Submatches => groups, } } fn step(&self, groups: &mut [Option<uint>], nlist: &mut Threads, caps: &mut [Option<uint>], pc: uint) -> StepState { match self.prog.insts[pc] { Match => { match self.which { Exists => { return StepMatchEarlyReturn } Location => { groups[0] = caps[0]; groups[1] = caps[1]; return StepMatch } Submatches => { for (slot, val) in groups.iter_mut().zip(caps.iter()) { *slot = *val; } return StepMatch } } } OneChar(c, flags) => { if self.char_eq(flags & FLAG_NOCASE > 0, self.chars.prev, c) { self.add(nlist, pc+1, caps); } } CharClass(ref ranges, flags) => { if self.chars.prev.is_some() { let c = self.chars.prev.unwrap(); let negate = flags & FLAG_NEGATED > 0; let casei = flags & FLAG_NOCASE > 0; let found = ranges.as_slice(); let found = found.binary_search_by(|&rc| class_cmp(casei, c, rc)).is_ok(); if found ^ negate { self.add(nlist, pc+1, caps); } } } Any(flags) => { if flags & FLAG_DOTNL > 0 ||!self.char_eq(false, self.chars.prev, '\n') { self.add(nlist, pc+1, caps) } } EmptyBegin(_) | EmptyEnd(_) | EmptyWordBoundary(_) | Save(_) | Jump(_) | Split(_, _) => {}, } StepContinue } fn add(&self, nlist: &mut Threads, pc: uint, groups: &mut [Option<uint>]) { if nlist.contains(pc) { return } // We have to add states to the threads list even if their empty. // TL;DR - It prevents cycles. // If we didn't care about cycles, we'd *only* add threads that // correspond to non-jumping instructions (OneChar, Any, Match, etc.). // But, it's possible for valid regexs (like '(a*)*') to result in // a cycle in the instruction list. e.g., We'll keep chasing the Split // instructions forever. // So we add these instructions to our thread queue, but in the main // VM loop, we look for them but simply ignore them. // Adding them to the queue prevents them from being revisited so we // can avoid cycles (and the inevitable stack overflow). // // We make a minor optimization by indicating that the state is "empty" // so that its capture groups are not filled in. match self.prog.insts[pc] { EmptyBegin(flags) => { let multi = flags & FLAG_MULTI > 0; nlist.add(pc, groups, true); if self.chars.is_begin() || (multi && self.char_is(self.chars.prev, '\n')) { self.add(nlist, pc + 1, groups) } } EmptyEnd(flags) => { let multi = flags & FLAG_MULTI > 0; nlist.add(pc, groups, true); if self.chars.is_end() || (multi && self.char_is(self.chars.cur, '\n')) { self.add(nlist, pc + 1, groups) } } EmptyWordBoundary(flags) => { nlist.add(pc, groups, true); if self.chars.is_word_boundary() ==!(flags & FLAG_NEGATED > 0) { self.add(nlist, pc + 1, groups) } } Save(slot) => { nlist.add(pc, groups, true); match self.which { Location if slot <= 1 => { let old = groups[slot]; groups[slot] = Some(self.ic); self.add(nlist, pc + 1, groups); groups[slot] = old; } Submatches => { let old = groups[slot]; groups[slot] = Some(self.ic); self.add(nlist, pc + 1, groups); groups[slot] = old; } Exists | Location => self.add(nlist, pc + 1, groups), } } Jump(to) => { nlist.add(pc, groups, true); self.add(nlist, to, groups) } Split(x, y) => { nlist.add(pc, groups, true); self.add(nlist, x, groups); self.add(nlist, y, groups); } Match | OneChar(_, _) | CharClass(_, _) | Any(_) => { nlist.add(pc, groups, false); } } } // FIXME: For case insensitive comparisons, it uses the uppercase // character and tests for equality. IIUC, this does not generalize to // all of Unicode. I believe we need to check the entire fold for each // character. This will be easy to add if and when it gets added to Rust's // standard library. #[inline] fn char_eq(&self, casei: bool, textc: Option<char>, regc: char) -> bool { match textc { None => false, Some(textc) => { regc == textc || (casei && regc.to_uppercase() == textc.to_uppercase()) } } } #[inline] fn char_is(&self, textc: Option<char>, regc: char) -> bool { textc == Some(regc) } } /// CharReader is responsible for maintaining a "previous" and a "current" /// character. This one-character lookahead is necessary for assertions that /// look one character before or after the current position. pub struct CharReader<'t> { /// The previous character read. It is None only when processing the first /// character of the input. pub prev: Option<char>, /// The current character. pub cur: Option<char>, input: &'t str, next: uint, } impl<'t> CharReader<'t> { /// Returns a new CharReader that advances through the input given. /// Note that a CharReader has no knowledge of the range in which to search /// the input. pub fn new(input: &'t str) -> CharReader<'t> { CharReader { prev: None, cur: None, input: input, next: 0, } } /// Sets the previous and current character given any arbitrary byte /// index (at a Unicode codepoint boundary). #[inline] pub fn set(&mut self, ic: uint) -> uint { self.prev = None; self.cur = None; self.next = 0; if self.input.len() == 0 { return 1 } if ic > 0 { let i = cmp::min(ic, self.input.len()); let prev = self.input.char_range_at_reverse(i); self.prev = Some(prev.ch); } if ic < self.input.len() { let cur = self.input.char_range_at(ic); self.cur = Some(cur.ch); self.next = cur.next; self.next } else { self.input.len() + 1 } } /// Does the same as `set`, except it always advances to the next /// character in the input (and therefore does half as many UTF8 decodings). #[inline] pub fn advance(&mut self) -> uint { self.prev = self.cur; if self.next < self.input.len() { let cur = self.input.char_range_at(self.next); self.cur = Some(cur.ch); self.next = cur.next; } else { self.cur = None; self.next = self.input.len() + 1; } self.next } /// Returns true if and only if this is the beginning of the input /// (ignoring the range of the input to search). #[inline] pub fn is_begin(&self) -> bool { self.prev.is_none() } /// Returns true if and only if this is the end of the input /// (ignoring the range of the input to search). #[inline] pub fn is_end(&self) -> bool { self.cur.is_none() } /// Returns true if and only if the current position is a word boundary. /// (Ignoring the range of the input to search.) pub fn is_word_boundary(&self) -> bool { if self.is_begin() { return is_word(self.cur) } if self.is_end() { return is_word(self.prev) } (is_word(self.cur) &&!is_word(self.prev)) || (is_word(self.prev) &&!is_word(self.cur)) } } struct Thread { pc: uint, groups: Vec<Option<uint>>, } struct Threads { which: MatchKind, queue: Vec<Thread>, sparse: Vec<uint>, size: uint, } impl Threads { // This is using a wicked neat trick to provide constant time lookup // for threads in the queue using a sparse set. A queue of threads is // allocated once with maximal size when the VM initializes and is reused // throughout execution. That is, there should be zero allocation during // the execution of a VM. // // See http://research.swtch.com/sparse for the deets. fn new(which: MatchKind, num_insts: uint, ncaps: uint) -> Threads { Threads { which: which, queue: range(0, num_insts).map(|_| { Thread { pc: 0, groups: repeat(None).take(ncaps * 2).collect() } }).collect(), sparse: repeat(0u).take(num_insts).collect(), size: 0, } } fn add(&mut self, pc: uint, groups: &[Option<uint>], empty: bool) { let t = &mut self.queue[self.size]; t.pc = pc; match (empty, self.which) { (_, Exists) | (true, _) => {}, (false, Location) => { t.groups[0] = groups[0]; t.groups[1] = groups[1]; } (false, Submatches) => { for (slot, val) in t.groups.iter_mut().zip(groups.iter()) { *slot = *val; } } } self.sparse[pc] = self.size; self.size += 1; } #[inline] fn contains(&self, pc: uint) -> bool { let s = self.sparse[pc]; s < self.size && self.queue[s].pc == pc } #[inline] fn empty(&mut self) { self.size = 0; } #[inline] fn pc(&self, i: uint) -> uint { self.queue[i].pc } #[inline] fn groups<'r>(&'r mut self, i: uint) -> &'r mut [Option<uint>] { let q = &mut self.queue[i]; q.groups.as_mut_slice() } } /// Returns true if the character is a word character, according to the /// (Unicode friendly) Perl character class '\w'.
{ let needle = self.prog.prefix.as_bytes(); let haystack = &self.input.as_bytes()[self.ic..]; match find_prefix(needle, haystack) { None => break, Some(i) => { self.ic += i; next_ic = self.chars.set(self.ic); } } }
conditional_block
vm.rs
', not 'find'). This is a half-measure, but does provide some // perf improvement. // // AFAIK, the DFA/NFA approach is implemented in RE2/C++ but *not* in RE2/Go. // // [1] - http://swtch.com/~rsc/regex/regex3.html pub use self::MatchKind::*; pub use self::StepState::*; use std::cmp; use std::cmp::Ordering::{self, Less, Equal, Greater}; use std::mem; use std::iter::repeat; use std::slice::SliceExt; use compile::{ Program, Match, OneChar, CharClass, Any, EmptyBegin, EmptyEnd, EmptyWordBoundary, Save, Jump, Split, }; use parse::{FLAG_NOCASE, FLAG_MULTI, FLAG_DOTNL, FLAG_NEGATED}; use unicode::regex::PERLW; pub type CaptureLocs = Vec<Option<uint>>; /// Indicates the type of match to be performed by the VM. #[derive(Copy)] pub enum MatchKind { /// Only checks if a match exists or not. Does not return location. Exists, /// Returns the start and end indices of the entire match in the input /// given. Location, /// Returns the start and end indices of each submatch in the input given. Submatches, } /// Runs an NFA simulation on the compiled expression given on the search text /// `input`. The search begins at byte index `start` and ends at byte index /// `end`. (The range is specified here so that zero-width assertions will work /// correctly when searching for successive non-overlapping matches.) /// /// The `which` parameter indicates what kind of capture information the caller /// wants. There are three choices: match existence only, the location of the /// entire match or the locations of the entire match in addition to the /// locations of each submatch. pub fn run<'r, 't>(which: MatchKind, prog: &'r Program, input: &'t str, start: uint, end: uint) -> CaptureLocs { Nfa { which: which, prog: prog, input: input, start: start, end: end, ic: 0, chars: CharReader::new(input), }.run() } struct Nfa<'r, 't> { which: MatchKind, prog: &'r Program, input: &'t str, start: uint, end: uint, ic: uint, chars: CharReader<'t>, } /// Indicates the next action to take after a single non-empty instruction /// is processed. #[derive(Copy)] pub enum StepState { /// This is returned if and only if a Match instruction is reached and /// we only care about the existence of a match. It instructs the VM to /// quit early. StepMatchEarlyReturn, /// Indicates that a match was found. Thus, the rest of the states in the /// *current* queue should be dropped (i.e., leftmost-first semantics). /// States in the "next" queue can still be processed. StepMatch, /// No match was found. Continue with the next state in the queue. StepContinue, } impl<'r, 't> Nfa<'r, 't> { fn run(&mut self) -> CaptureLocs { let ncaps = match self.which { Exists => 0, Location => 1, Submatches => self.prog.num_captures(), }; let mut matched = false; let ninsts = self.prog.insts.len(); let mut clist = &mut Threads::new(self.which, ninsts, ncaps); let mut nlist = &mut Threads::new(self.which, ninsts, ncaps); let mut groups: Vec<_> = repeat(None).take(ncaps * 2).collect(); // Determine if the expression starts with a '^' so we can avoid // simulating.*? // Make sure multi-line mode isn't enabled for it, otherwise we can't // drop the initial.*? let prefix_anchor = match self.prog.insts[1] { EmptyBegin(flags) if flags & FLAG_MULTI == 0 => true, _ => false, }; self.ic = self.start; let mut next_ic = self.chars.set(self.start); while self.ic <= self.end { if clist.size == 0 { // We have a match and we're done exploring alternatives. // Time to quit. if matched { break } // If there are no threads to try, then we'll have to start // over at the beginning of the regex. // BUT, if there's a literal prefix for the program, try to // jump ahead quickly. If it can't be found, then we can bail // out early. if self.prog.prefix.len() > 0 && clist.size == 0 { let needle = self.prog.prefix.as_bytes(); let haystack = &self.input.as_bytes()[self.ic..]; match find_prefix(needle, haystack) { None => break, Some(i) => { self.ic += i; next_ic = self.chars.set(self.ic); } } } } // This simulates a preceding '.*?' for every regex by adding // a state starting at the current position in the input for the // beginning of the program only if we don't already have a match. if clist.size == 0 || (!prefix_anchor &&!matched) { self.add(clist, 0, groups.as_mut_slice()) } // Now we try to read the next character. // As a result, the'step' method will look at the previous // character. self.ic = next_ic; next_ic = self.chars.advance(); for i in range(0, clist.size) { let pc = clist.pc(i); let step_state = self.step(groups.as_mut_slice(), nlist, clist.groups(i), pc); match step_state { StepMatchEarlyReturn => return vec![Some(0), Some(0)], StepMatch => { matched = true; break }, StepContinue => {}, } } mem::swap(&mut clist, &mut nlist); nlist.empty(); } match self.which { Exists if matched => vec![Some(0), Some(0)], Exists => vec![None, None], Location | Submatches => groups, } } fn step(&self, groups: &mut [Option<uint>], nlist: &mut Threads, caps: &mut [Option<uint>], pc: uint) -> StepState { match self.prog.insts[pc] { Match => { match self.which { Exists => { return StepMatchEarlyReturn } Location => { groups[0] = caps[0]; groups[1] = caps[1]; return StepMatch } Submatches => { for (slot, val) in groups.iter_mut().zip(caps.iter()) { *slot = *val; } return StepMatch } } } OneChar(c, flags) => { if self.char_eq(flags & FLAG_NOCASE > 0, self.chars.prev, c) { self.add(nlist, pc+1, caps); } } CharClass(ref ranges, flags) => { if self.chars.prev.is_some() { let c = self.chars.prev.unwrap(); let negate = flags & FLAG_NEGATED > 0; let casei = flags & FLAG_NOCASE > 0; let found = ranges.as_slice(); let found = found.binary_search_by(|&rc| class_cmp(casei, c, rc)).is_ok(); if found ^ negate { self.add(nlist, pc+1, caps); } } } Any(flags) => { if flags & FLAG_DOTNL > 0 ||!self.char_eq(false, self.chars.prev, '\n') { self.add(nlist, pc+1, caps) } } EmptyBegin(_) | EmptyEnd(_) | EmptyWordBoundary(_) | Save(_) | Jump(_) | Split(_, _) => {}, } StepContinue } fn add(&self, nlist: &mut Threads, pc: uint, groups: &mut [Option<uint>]) { if nlist.contains(pc) { return } // We have to add states to the threads list even if their empty. // TL;DR - It prevents cycles. // If we didn't care about cycles, we'd *only* add threads that // correspond to non-jumping instructions (OneChar, Any, Match, etc.). // But, it's possible for valid regexs (like '(a*)*') to result in // a cycle in the instruction list. e.g., We'll keep chasing the Split // instructions forever. // So we add these instructions to our thread queue, but in the main // VM loop, we look for them but simply ignore them. // Adding them to the queue prevents them from being revisited so we // can avoid cycles (and the inevitable stack overflow). // // We make a minor optimization by indicating that the state is "empty" // so that its capture groups are not filled in. match self.prog.insts[pc] { EmptyBegin(flags) => { let multi = flags & FLAG_MULTI > 0; nlist.add(pc, groups, true); if self.chars.is_begin() || (multi && self.char_is(self.chars.prev, '\n')) { self.add(nlist, pc + 1, groups) } } EmptyEnd(flags) => { let multi = flags & FLAG_MULTI > 0; nlist.add(pc, groups, true); if self.chars.is_end() || (multi && self.char_is(self.chars.cur, '\n')) { self.add(nlist, pc + 1, groups) } } EmptyWordBoundary(flags) => { nlist.add(pc, groups, true); if self.chars.is_word_boundary() ==!(flags & FLAG_NEGATED > 0) { self.add(nlist, pc + 1, groups) } } Save(slot) => { nlist.add(pc, groups, true); match self.which { Location if slot <= 1 => { let old = groups[slot]; groups[slot] = Some(self.ic); self.add(nlist, pc + 1, groups); groups[slot] = old; } Submatches => { let old = groups[slot]; groups[slot] = Some(self.ic); self.add(nlist, pc + 1, groups); groups[slot] = old; } Exists | Location => self.add(nlist, pc + 1, groups), } } Jump(to) => { nlist.add(pc, groups, true); self.add(nlist, to, groups) } Split(x, y) => { nlist.add(pc, groups, true); self.add(nlist, x, groups); self.add(nlist, y, groups); } Match | OneChar(_, _) | CharClass(_, _) | Any(_) => { nlist.add(pc, groups, false); } } } // FIXME: For case insensitive comparisons, it uses the uppercase // character and tests for equality. IIUC, this does not generalize to // all of Unicode. I believe we need to check the entire fold for each // character. This will be easy to add if and when it gets added to Rust's // standard library. #[inline] fn char_eq(&self, casei: bool, textc: Option<char>, regc: char) -> bool { match textc { None => false, Some(textc) => { regc == textc || (casei && regc.to_uppercase() == textc.to_uppercase()) } } } #[inline] fn char_is(&self, textc: Option<char>, regc: char) -> bool { textc == Some(regc) } } /// CharReader is responsible for maintaining a "previous" and a "current" /// character. This one-character lookahead is necessary for assertions that /// look one character before or after the current position. pub struct CharReader<'t> { /// The previous character read. It is None only when processing the first /// character of the input. pub prev: Option<char>, /// The current character. pub cur: Option<char>, input: &'t str, next: uint, } impl<'t> CharReader<'t> { /// Returns a new CharReader that advances through the input given. /// Note that a CharReader has no knowledge of the range in which to search /// the input. pub fn new(input: &'t str) -> CharReader<'t> { CharReader { prev: None, cur: None, input: input, next: 0, } } /// Sets the previous and current character given any arbitrary byte /// index (at a Unicode codepoint boundary). #[inline] pub fn set(&mut self, ic: uint) -> uint { self.prev = None; self.cur = None; self.next = 0; if self.input.len() == 0 { return 1 } if ic > 0 { let i = cmp::min(ic, self.input.len()); let prev = self.input.char_range_at_reverse(i); self.prev = Some(prev.ch); } if ic < self.input.len() { let cur = self.input.char_range_at(ic); self.cur = Some(cur.ch); self.next = cur.next; self.next } else { self.input.len() + 1 } } /// Does the same as `set`, except it always advances to the next /// character in the input (and therefore does half as many UTF8 decodings). #[inline] pub fn advance(&mut self) -> uint { self.prev = self.cur; if self.next < self.input.len() { let cur = self.input.char_range_at(self.next); self.cur = Some(cur.ch); self.next = cur.next; } else { self.cur = None; self.next = self.input.len() + 1; } self.next } /// Returns true if and only if this is the beginning of the input /// (ignoring the range of the input to search). #[inline] pub fn is_begin(&self) -> bool { self.prev.is_none() } /// Returns true if and only if this is the end of the input /// (ignoring the range of the input to search). #[inline] pub fn is_end(&self) -> bool
/// Returns true if and only if the current position is a word boundary. /// (Ignoring the range of the input to search.) pub fn is_word_boundary(&self) -> bool { if self.is_begin() { return is_word(self.cur) } if self.is_end() { return is_word(self.prev) } (is_word(self.cur) &&!is_word(self.prev)) || (is_word(self.prev) &&!is_word(self.cur)) } } struct Thread { pc: uint, groups: Vec<Option<uint>>, } struct Threads { which: MatchKind, queue: Vec<Thread>, sparse: Vec<uint>, size: uint, } impl Threads { // This is using a wicked neat trick to provide constant time lookup // for threads in the queue using a sparse set. A queue of threads is // allocated once with maximal size when the VM initializes and is reused // throughout execution. That is, there should be zero allocation during // the execution of a VM. // // See http://research.swtch.com/sparse for the deets. fn new(which: MatchKind, num_insts: uint, ncaps: uint) -> Threads { Threads { which: which, queue: range(0, num_insts).map(|_| { Thread { pc: 0, groups: repeat(None).take(ncaps * 2).collect() } }).collect(), sparse: repeat(0u).take(num_insts).collect(), size: 0, } } fn add(&mut self, pc: uint, groups: &[Option<uint>], empty: bool) { let t = &mut self.queue[self.size]; t.pc = pc; match (empty, self.which) { (_, Exists) | (true, _) => {}, (false, Location) => { t.groups[0] = groups[0]; t.groups[1] = groups[1]; } (false, Submatches) => { for (slot, val) in t.groups.iter_mut().zip(groups.iter()) { *slot = *val; } } } self.sparse[pc] = self.size; self.size += 1; } #[inline] fn contains(&self, pc: uint) -> bool { let s = self.sparse[pc]; s < self.size && self.queue[s].pc == pc } #[inline] fn empty(&mut self) { self.size = 0; } #[inline] fn pc(&self, i: uint) -> uint { self.queue[i].pc } #[inline] fn groups<'r>(&'r mut self, i: uint) -> &'r mut [Option<uint>] { let q = &mut self.queue[i]; q.groups.as_mut_slice() } } /// Returns true if the character is a word character, according to the /// (Unicode friendly) Perl character class '\w'.
{ self.cur.is_none() }
identifier_body
mod.rs
pub mod event; use self::event::EventStopable; use std::collections::HashMap; pub trait ListenerCallable: PartialEq { fn call(&self, event_name: &str, event: &mut EventStopable); } pub struct EventListener { callback: fn(event_name: &str, event: &mut EventStopable), } impl EventListener { pub fn new (callback: fn(event_name: &str, event: &mut EventStopable)) -> EventListener { EventListener {callback: callback} } } impl ListenerCallable for EventListener { fn call (&self, event_name: &str, event: &mut EventStopable) { let callback = self.callback; callback(event_name, event); } } impl PartialEq for EventListener { fn eq(&self, other: &EventListener) -> bool { (self.callback as *const()) == (other.callback as *const()) } fn ne(&self, other: &EventListener) -> bool { !self.eq(other) } } pub trait Dispatchable<S> where S: EventStopable { fn dispatch (&self, event_name: &str, event: &mut S); } pub struct EventDispatcher<'a, L> where L: 'a + ListenerCallable { listeners: HashMap<&'a str, Vec<&'a L>>, } impl<'a, L: 'a + ListenerCallable> EventDispatcher<'a, L> { pub fn new() -> EventDispatcher<'a, L> { EventDispatcher{listeners: HashMap::new()} } pub fn add_listener(&mut self, event_name: &'a str, listener: &'a L) { if!self.listeners.contains_key(event_name) { self.listeners.insert(event_name, Vec::new()); } if let Some(mut listeners) = self.listeners.get_mut(event_name) { listeners.push(listener); } } pub fn remove_listener(&mut self, event_name: &'a str, listener: &'a mut L)
} impl<'a, S: 'a + EventStopable> Dispatchable<S> for EventDispatcher<'a, EventListener> { fn dispatch(&self, event_name: &str, event: &mut S) { if let Some(listeners) = self.listeners.get(event_name) { for listener in listeners { listener.call(event_name, event); if!event.is_propagation_stopped() { break; } } } } } #[cfg(test)] mod tests { use super::*; use super::event::*; fn print_event_info(event_name: &str, event: &mut EventStopable) { println!("callback from event: {}", event_name); event.stop_propagation(); } #[test] fn test_dispatcher() { let event_name = "test_a"; let mut event = Event::new(); let callback_one: fn(event_name: &str, event: &mut EventStopable) = print_event_info; let mut listener_one = EventListener::new(callback_one); let mut dispatcher = EventDispatcher::new(); dispatcher.dispatch(event_name, &mut event); assert_eq!(false, event.is_propagation_stopped()); dispatcher.dispatch(event_name, &mut event); assert_eq!(false, event.is_propagation_stopped()); dispatcher.add_listener(event_name, &mut listener_one); dispatcher.dispatch(event_name, &mut event); assert_eq!(true, event.is_propagation_stopped()); } }
{ if self.listeners.contains_key(event_name) { if let Some(mut listeners) = self.listeners.get_mut(event_name) { match listeners.iter().position(|x| *x == listener) { Some(index) => { listeners.remove(index); }, _ => {}, } } } }
identifier_body