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 |
---|---|---|---|---|
cloudformation.rs
|
#![cfg(feature = "cloudformation")]
extern crate rusoto;
use rusoto::cloudformation::{CloudFormationClient, ListStacksInput};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
#[test]
fn
|
() {
let client = CloudFormationClient::new(default_tls_client().unwrap(), DefaultCredentialsProvider::new().unwrap(), Region::UsEast1);
let request = ListStacksInput::default();
let result = client.list_stacks(&request).unwrap();
println!("{:#?}", result);
}
#[test]
fn should_list_stacks_with_status_filter() {
let client = CloudFormationClient::new(default_tls_client().unwrap(), DefaultCredentialsProvider::new().unwrap(), Region::UsEast1);
let filters = vec!["CREATE_COMPLETE".to_owned()];
let request = ListStacksInput {
stack_status_filter: Some(filters),
..Default::default()
};
let result = client.list_stacks(&request).unwrap();
println!("{:#?}", result);
}
|
should_list_stacks
|
identifier_name
|
paths.rs
|
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf, Component};
use util::{human, internal, CargoResult, ChainError};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CargoResult<OsString> {
env::join_paths(paths.iter()).or_else(|e| {
let paths = paths.iter().map(Path::new).collect::<Vec<_>>();
internal(format!("failed to join path array: {:?}", paths)).chain_error(|| {
human(format!("failed to join search paths together: {}\n\
Does ${} have an unterminated quote character?",
e, env))
})
})
}
pub fn
|
() -> &'static str {
if cfg!(windows) {"PATH"}
else if cfg!(target_os = "macos") {"DYLD_LIBRARY_PATH"}
else {"LD_LIBRARY_PATH"}
}
pub fn dylib_path() -> Vec<PathBuf> {
match env::var_os(dylib_path_envvar()) {
Some(var) => env::split_paths(&var).collect(),
None => Vec::new(),
}
}
pub fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek()
.cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => { ret.push(component.as_os_str()); }
Component::CurDir => {}
Component::ParentDir => { ret.pop(); }
Component::Normal(c) => { ret.push(c); }
}
}
ret
}
pub fn without_prefix<'a>(a: &'a Path, b: &'a Path) -> Option<&'a Path> {
let mut a = a.components();
let mut b = b.components();
loop {
match b.next() {
Some(y) => match a.next() {
Some(x) if x == y => continue,
_ => return None,
},
None => return Some(a.as_path()),
}
}
}
pub fn read(path: &Path) -> CargoResult<String> {
(|| -> CargoResult<String> {
let mut ret = String::new();
let mut f = try!(File::open(path));
try!(f.read_to_string(&mut ret));
Ok(ret)
}).chain_error(|| {
internal(format!("failed to read `{}`", path.display()))
})
}
pub fn write(path: &Path, contents: &[u8]) -> CargoResult<()> {
(|| -> CargoResult<()> {
let mut f = try!(File::create(path));
try!(f.write_all(contents));
Ok(())
}).chain_error(|| {
internal(format!("failed to write `{}`", path.display()))
})
}
#[cfg(unix)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
use std::os::unix::prelude::*;
Ok(path.as_os_str().as_bytes())
}
#[cfg(windows)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
match path.as_os_str().to_str() {
Some(s) => Ok(s.as_bytes()),
None => Err(human(format!("invalid non-unicode path: {}",
path.display())))
}
}
#[cfg(unix)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
use std::os::unix::prelude::*;
use std::ffi::OsStr;
Ok(PathBuf::from(OsStr::from_bytes(bytes)))
}
#[cfg(windows)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(bytes) {
Ok(s) => Ok(PathBuf::from(s)),
Err(..) => Err(human("invalid non-unicode path")),
}
}
|
dylib_path_envvar
|
identifier_name
|
paths.rs
|
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf, Component};
use util::{human, internal, CargoResult, ChainError};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CargoResult<OsString> {
env::join_paths(paths.iter()).or_else(|e| {
let paths = paths.iter().map(Path::new).collect::<Vec<_>>();
internal(format!("failed to join path array: {:?}", paths)).chain_error(|| {
human(format!("failed to join search paths together: {}\n\
Does ${} have an unterminated quote character?",
e, env))
})
})
}
pub fn dylib_path_envvar() -> &'static str {
if cfg!(windows) {"PATH"}
else if cfg!(target_os = "macos") {"DYLD_LIBRARY_PATH"}
else {"LD_LIBRARY_PATH"}
}
pub fn dylib_path() -> Vec<PathBuf> {
match env::var_os(dylib_path_envvar()) {
Some(var) => env::split_paths(&var).collect(),
None => Vec::new(),
}
}
pub fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek()
.cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => { ret.push(component.as_os_str()); }
Component::CurDir => {}
Component::ParentDir => { ret.pop(); }
Component::Normal(c) => { ret.push(c); }
}
}
ret
}
pub fn without_prefix<'a>(a: &'a Path, b: &'a Path) -> Option<&'a Path> {
let mut a = a.components();
let mut b = b.components();
loop {
match b.next() {
Some(y) => match a.next() {
Some(x) if x == y => continue,
_ => return None,
},
None => return Some(a.as_path()),
}
}
}
pub fn read(path: &Path) -> CargoResult<String> {
(|| -> CargoResult<String> {
let mut ret = String::new();
let mut f = try!(File::open(path));
try!(f.read_to_string(&mut ret));
Ok(ret)
}).chain_error(|| {
internal(format!("failed to read `{}`", path.display()))
})
}
pub fn write(path: &Path, contents: &[u8]) -> CargoResult<()> {
(|| -> CargoResult<()> {
let mut f = try!(File::create(path));
try!(f.write_all(contents));
Ok(())
}).chain_error(|| {
internal(format!("failed to write `{}`", path.display()))
})
}
#[cfg(unix)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
use std::os::unix::prelude::*;
Ok(path.as_os_str().as_bytes())
}
#[cfg(windows)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
match path.as_os_str().to_str() {
Some(s) => Ok(s.as_bytes()),
None => Err(human(format!("invalid non-unicode path: {}",
path.display())))
}
}
#[cfg(unix)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf>
|
#[cfg(windows)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(bytes) {
Ok(s) => Ok(PathBuf::from(s)),
Err(..) => Err(human("invalid non-unicode path")),
}
}
|
{
use std::os::unix::prelude::*;
use std::ffi::OsStr;
Ok(PathBuf::from(OsStr::from_bytes(bytes)))
}
|
identifier_body
|
paths.rs
|
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf, Component};
use util::{human, internal, CargoResult, ChainError};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CargoResult<OsString> {
env::join_paths(paths.iter()).or_else(|e| {
let paths = paths.iter().map(Path::new).collect::<Vec<_>>();
internal(format!("failed to join path array: {:?}", paths)).chain_error(|| {
human(format!("failed to join search paths together: {}\n\
Does ${} have an unterminated quote character?",
e, env))
})
})
}
pub fn dylib_path_envvar() -> &'static str {
if cfg!(windows)
|
else if cfg!(target_os = "macos") {"DYLD_LIBRARY_PATH"}
else {"LD_LIBRARY_PATH"}
}
pub fn dylib_path() -> Vec<PathBuf> {
match env::var_os(dylib_path_envvar()) {
Some(var) => env::split_paths(&var).collect(),
None => Vec::new(),
}
}
pub fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek()
.cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => { ret.push(component.as_os_str()); }
Component::CurDir => {}
Component::ParentDir => { ret.pop(); }
Component::Normal(c) => { ret.push(c); }
}
}
ret
}
pub fn without_prefix<'a>(a: &'a Path, b: &'a Path) -> Option<&'a Path> {
let mut a = a.components();
let mut b = b.components();
loop {
match b.next() {
Some(y) => match a.next() {
Some(x) if x == y => continue,
_ => return None,
},
None => return Some(a.as_path()),
}
}
}
pub fn read(path: &Path) -> CargoResult<String> {
(|| -> CargoResult<String> {
let mut ret = String::new();
let mut f = try!(File::open(path));
try!(f.read_to_string(&mut ret));
Ok(ret)
}).chain_error(|| {
internal(format!("failed to read `{}`", path.display()))
})
}
pub fn write(path: &Path, contents: &[u8]) -> CargoResult<()> {
(|| -> CargoResult<()> {
let mut f = try!(File::create(path));
try!(f.write_all(contents));
Ok(())
}).chain_error(|| {
internal(format!("failed to write `{}`", path.display()))
})
}
#[cfg(unix)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
use std::os::unix::prelude::*;
Ok(path.as_os_str().as_bytes())
}
#[cfg(windows)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
match path.as_os_str().to_str() {
Some(s) => Ok(s.as_bytes()),
None => Err(human(format!("invalid non-unicode path: {}",
path.display())))
}
}
#[cfg(unix)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
use std::os::unix::prelude::*;
use std::ffi::OsStr;
Ok(PathBuf::from(OsStr::from_bytes(bytes)))
}
#[cfg(windows)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(bytes) {
Ok(s) => Ok(PathBuf::from(s)),
Err(..) => Err(human("invalid non-unicode path")),
}
}
|
{"PATH"}
|
conditional_block
|
paths.rs
|
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf, Component};
use util::{human, internal, CargoResult, ChainError};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CargoResult<OsString> {
env::join_paths(paths.iter()).or_else(|e| {
let paths = paths.iter().map(Path::new).collect::<Vec<_>>();
internal(format!("failed to join path array: {:?}", paths)).chain_error(|| {
human(format!("failed to join search paths together: {}\n\
Does ${} have an unterminated quote character?",
e, env))
})
})
}
|
if cfg!(windows) {"PATH"}
else if cfg!(target_os = "macos") {"DYLD_LIBRARY_PATH"}
else {"LD_LIBRARY_PATH"}
}
pub fn dylib_path() -> Vec<PathBuf> {
match env::var_os(dylib_path_envvar()) {
Some(var) => env::split_paths(&var).collect(),
None => Vec::new(),
}
}
pub fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek()
.cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => { ret.push(component.as_os_str()); }
Component::CurDir => {}
Component::ParentDir => { ret.pop(); }
Component::Normal(c) => { ret.push(c); }
}
}
ret
}
pub fn without_prefix<'a>(a: &'a Path, b: &'a Path) -> Option<&'a Path> {
let mut a = a.components();
let mut b = b.components();
loop {
match b.next() {
Some(y) => match a.next() {
Some(x) if x == y => continue,
_ => return None,
},
None => return Some(a.as_path()),
}
}
}
pub fn read(path: &Path) -> CargoResult<String> {
(|| -> CargoResult<String> {
let mut ret = String::new();
let mut f = try!(File::open(path));
try!(f.read_to_string(&mut ret));
Ok(ret)
}).chain_error(|| {
internal(format!("failed to read `{}`", path.display()))
})
}
pub fn write(path: &Path, contents: &[u8]) -> CargoResult<()> {
(|| -> CargoResult<()> {
let mut f = try!(File::create(path));
try!(f.write_all(contents));
Ok(())
}).chain_error(|| {
internal(format!("failed to write `{}`", path.display()))
})
}
#[cfg(unix)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
use std::os::unix::prelude::*;
Ok(path.as_os_str().as_bytes())
}
#[cfg(windows)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
match path.as_os_str().to_str() {
Some(s) => Ok(s.as_bytes()),
None => Err(human(format!("invalid non-unicode path: {}",
path.display())))
}
}
#[cfg(unix)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
use std::os::unix::prelude::*;
use std::ffi::OsStr;
Ok(PathBuf::from(OsStr::from_bytes(bytes)))
}
#[cfg(windows)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(bytes) {
Ok(s) => Ok(PathBuf::from(s)),
Err(..) => Err(human("invalid non-unicode path")),
}
}
|
pub fn dylib_path_envvar() -> &'static str {
|
random_line_split
|
mod.rs
|
mod pic;
#[macro_use]
mod macros;
use x86;
use drivers;
use vga_buffer;
use kernel::kget;
use schedule::task::TaskContext;
use x86_64::structures::idt::{ExceptionStackFrame, Idt, PageFaultErrorCode};
lazy_static! {
static ref IDT: Idt = {
let mut idt = Idt::new();
// Set all the handlers. Set default handler if a specific is not defined
// to help debugging
idt.divide_by_zero.set_handler_fn(except_00);
idt.page_fault.set_handler_fn(except_14);
// Interrupts
irq_handler!(idt, 0, irq0);
irq_handler!(idt, 1, irq1);
idt
};
}
|
/// Initialises the PIC and IDT. Enables CPU interrupts.
pub fn init() {
PIC.init();
// Enable some pic interrupts
PIC.clear_mask(0);
PIC.clear_mask(1);
// PIC.clear_mask(2);
// PIC.clear_mask(3);
// PIC.clear_mask(4);
// PIC.clear_mask(5);
IDT.load();
// Enable interrupts
unsafe {
x86::irq::enable();
}
}
// Exception Handlers
/// Divide by zero handler
///
/// Prints out details of the exception then sleeps the CPU forever.
extern "x86-interrupt" fn except_00(_: &mut ExceptionStackFrame) {
unsafe {
vga_buffer::print_error(format_args!("EXCEPTION: Divide By Zero\n"));
};
hang!();
}
/// Page fault handler
///
/// Prints out details of the exception then sleeps the CPU forever.
extern "x86-interrupt" fn except_14(
stack_frame: &mut ExceptionStackFrame,
error_code: PageFaultErrorCode,
) {
unsafe {
vga_buffer::print_error(format_args!(
"EXCEPTION: Page Fault accessing {:#x} \nerror code: {:?}\n{:#?}",
x86::controlregs::cr2(),
error_code,
stack_frame.instruction_pointer
));
};
hang!();
}
// IRQ Handlers...
/// Handler for IRQ0 - The PIT interrupt
///
/// Ticks the system clock once.
unsafe fn irq0() {
let clock = &mut *kget().clock.get();
clock.tick();
}
/// Handler for IRQ1 - The keyboard interrupt
///
/// Instantiates and queues up a new keyboard driver bottom half.
unsafe fn irq1() {
let scheduler = &*kget().scheduler.get();
let bh_manager = scheduler.bh_manager();
let bh = box drivers::KeyboardBottomHalf::new();
bh_manager.add_bh(bh);
}
|
static PIC: pic::Pic = pic::Pic::new();
/// Initialise kernel interrupt handling
///
|
random_line_split
|
mod.rs
|
mod pic;
#[macro_use]
mod macros;
use x86;
use drivers;
use vga_buffer;
use kernel::kget;
use schedule::task::TaskContext;
use x86_64::structures::idt::{ExceptionStackFrame, Idt, PageFaultErrorCode};
lazy_static! {
static ref IDT: Idt = {
let mut idt = Idt::new();
// Set all the handlers. Set default handler if a specific is not defined
// to help debugging
idt.divide_by_zero.set_handler_fn(except_00);
idt.page_fault.set_handler_fn(except_14);
// Interrupts
irq_handler!(idt, 0, irq0);
irq_handler!(idt, 1, irq1);
idt
};
}
static PIC: pic::Pic = pic::Pic::new();
/// Initialise kernel interrupt handling
///
/// Initialises the PIC and IDT. Enables CPU interrupts.
pub fn init() {
PIC.init();
// Enable some pic interrupts
PIC.clear_mask(0);
PIC.clear_mask(1);
// PIC.clear_mask(2);
// PIC.clear_mask(3);
// PIC.clear_mask(4);
// PIC.clear_mask(5);
IDT.load();
// Enable interrupts
unsafe {
x86::irq::enable();
}
}
// Exception Handlers
/// Divide by zero handler
///
/// Prints out details of the exception then sleeps the CPU forever.
extern "x86-interrupt" fn except_00(_: &mut ExceptionStackFrame) {
unsafe {
vga_buffer::print_error(format_args!("EXCEPTION: Divide By Zero\n"));
};
hang!();
}
/// Page fault handler
///
/// Prints out details of the exception then sleeps the CPU forever.
extern "x86-interrupt" fn
|
(
stack_frame: &mut ExceptionStackFrame,
error_code: PageFaultErrorCode,
) {
unsafe {
vga_buffer::print_error(format_args!(
"EXCEPTION: Page Fault accessing {:#x} \nerror code: {:?}\n{:#?}",
x86::controlregs::cr2(),
error_code,
stack_frame.instruction_pointer
));
};
hang!();
}
// IRQ Handlers...
/// Handler for IRQ0 - The PIT interrupt
///
/// Ticks the system clock once.
unsafe fn irq0() {
let clock = &mut *kget().clock.get();
clock.tick();
}
/// Handler for IRQ1 - The keyboard interrupt
///
/// Instantiates and queues up a new keyboard driver bottom half.
unsafe fn irq1() {
let scheduler = &*kget().scheduler.get();
let bh_manager = scheduler.bh_manager();
let bh = box drivers::KeyboardBottomHalf::new();
bh_manager.add_bh(bh);
}
|
except_14
|
identifier_name
|
mod.rs
|
mod pic;
#[macro_use]
mod macros;
use x86;
use drivers;
use vga_buffer;
use kernel::kget;
use schedule::task::TaskContext;
use x86_64::structures::idt::{ExceptionStackFrame, Idt, PageFaultErrorCode};
lazy_static! {
static ref IDT: Idt = {
let mut idt = Idt::new();
// Set all the handlers. Set default handler if a specific is not defined
// to help debugging
idt.divide_by_zero.set_handler_fn(except_00);
idt.page_fault.set_handler_fn(except_14);
// Interrupts
irq_handler!(idt, 0, irq0);
irq_handler!(idt, 1, irq1);
idt
};
}
static PIC: pic::Pic = pic::Pic::new();
/// Initialise kernel interrupt handling
///
/// Initialises the PIC and IDT. Enables CPU interrupts.
pub fn init() {
PIC.init();
// Enable some pic interrupts
PIC.clear_mask(0);
PIC.clear_mask(1);
// PIC.clear_mask(2);
// PIC.clear_mask(3);
// PIC.clear_mask(4);
// PIC.clear_mask(5);
IDT.load();
// Enable interrupts
unsafe {
x86::irq::enable();
}
}
// Exception Handlers
/// Divide by zero handler
///
/// Prints out details of the exception then sleeps the CPU forever.
extern "x86-interrupt" fn except_00(_: &mut ExceptionStackFrame) {
unsafe {
vga_buffer::print_error(format_args!("EXCEPTION: Divide By Zero\n"));
};
hang!();
}
/// Page fault handler
///
/// Prints out details of the exception then sleeps the CPU forever.
extern "x86-interrupt" fn except_14(
stack_frame: &mut ExceptionStackFrame,
error_code: PageFaultErrorCode,
) {
unsafe {
vga_buffer::print_error(format_args!(
"EXCEPTION: Page Fault accessing {:#x} \nerror code: {:?}\n{:#?}",
x86::controlregs::cr2(),
error_code,
stack_frame.instruction_pointer
));
};
hang!();
}
// IRQ Handlers...
/// Handler for IRQ0 - The PIT interrupt
///
/// Ticks the system clock once.
unsafe fn irq0()
|
/// Handler for IRQ1 - The keyboard interrupt
///
/// Instantiates and queues up a new keyboard driver bottom half.
unsafe fn irq1() {
let scheduler = &*kget().scheduler.get();
let bh_manager = scheduler.bh_manager();
let bh = box drivers::KeyboardBottomHalf::new();
bh_manager.add_bh(bh);
}
|
{
let clock = &mut *kget().clock.get();
clock.tick();
}
|
identifier_body
|
lib.rs
|
, such that the oldest modified file is returned first.
fn get_all_files<P: AsRef<Path>>(path: P) -> Box<dyn Iterator<Item = (PathBuf, u64)>> {
let mut files: Vec<_> = WalkDir::new(path.as_ref())
.into_iter()
.filter_map(|e| {
e.ok().and_then(|f| {
// Only look at files
if f.file_type().is_file() {
// Get the last-modified time, size, and the full path.
f.metadata().ok().and_then(|m| {
m.modified()
.ok()
.map(|mtime| (mtime, f.path().to_owned(), m.len()))
})
} else {
None
}
})
})
.collect();
// Sort by last-modified-time, so oldest file first.
files.sort_by_key(|k| k.0);
Box::new(files.into_iter().map(|(_mtime, path, size)| (path, size)))
}
/// An LRU cache of files on disk.
pub struct LruDiskCache<S: BuildHasher = RandomState> {
lru: LruCache<OsString, u64, S, FileSize>,
root: PathBuf,
}
/// Errors returned by this crate.
#[derive(Debug)]
pub enum Error {
/// The file was too large to fit in the cache.
FileTooLarge,
/// The file was not in the cache.
FileNotInCache,
/// An IO Error occurred.
Io(io::Error),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn std::error::Error +'static)> {
match self {
Error::FileTooLarge => None,
Error::FileNotInCache => None,
Error::Io(ref e) => Some(e),
}
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Error {
Error::Io(e)
}
}
/// A convenience `Result` type
pub type Result<T> = std::result::Result<T, Error>;
/// Trait objects can't be bounded by more than one non-builtin trait.
pub trait ReadSeek: Read + Seek + Send {}
impl<T: Read + Seek + Send> ReadSeek for T {}
enum AddFile<'a> {
AbsPath(PathBuf),
RelPath(&'a OsStr),
}
impl LruDiskCache {
/// Create an `LruDiskCache` that stores files in `path`, limited to `size` bytes.
///
/// Existing files in `path` will be stored with their last-modified time from the filesystem
/// used as the order for the recency of their use. Any files that are individually larger
/// than `size` bytes will be removed.
///
/// The cache is not observant of changes to files under `path` from external sources, it
/// expects to have sole maintence of the contents.
pub fn new<T>(path: T, size: u64) -> Result<Self>
where
PathBuf: From<T>,
{
LruDiskCache {
lru: LruCache::with_meter(size, FileSize),
root: PathBuf::from(path),
}
.init()
}
/// Return the current size of all the files in the cache.
pub fn size(&self) -> u64 {
self.lru.size()
}
/// Return the count of entries in the cache.
pub fn len(&self) -> usize {
self.lru.len()
}
pub fn is_empty(&self) -> bool {
self.lru.len() == 0
}
/// Return the maximum size of the cache.
pub fn capacity(&self) -> u64 {
self.lru.capacity()
}
/// Return the path in which the cache is stored.
pub fn path(&self) -> &Path {
self.root.as_path()
}
/// Return the path that `key` would be stored at.
fn rel_to_abs_path<K: AsRef<Path>>(&self, rel_path: K) -> PathBuf {
self.root.join(rel_path)
}
/// Scan `self.root` for existing files and store them.
fn init(mut self) -> Result<Self> {
fs::create_dir_all(&self.root)?;
for (file, size) in get_all_files(&self.root) {
if!self.can_store(size) {
fs::remove_file(file).unwrap_or_else(|e| {
error!(
"Error removing file `{}` which is too large for the cache ({} bytes)",
e, size
)
});
} else
|
}
Ok(self)
}
/// Returns `true` if the disk cache can store a file of `size` bytes.
pub fn can_store(&self, size: u64) -> bool {
size <= self.lru.capacity() as u64
}
/// Add the file at `path` of size `size` to the cache.
fn add_file(&mut self, addfile_path: AddFile<'_>, size: u64) -> Result<()> {
if!self.can_store(size) {
return Err(Error::FileTooLarge);
}
let rel_path = match addfile_path {
AddFile::AbsPath(ref p) => p.strip_prefix(&self.root).expect("Bad path?").as_os_str(),
AddFile::RelPath(p) => p,
};
//TODO: ideally LRUCache::insert would give us back the entries it had to remove.
while self.lru.size() as u64 + size > self.lru.capacity() as u64 {
let (rel_path, _) = self.lru.remove_lru().expect("Unexpectedly empty cache!");
let remove_path = self.rel_to_abs_path(rel_path);
//TODO: check that files are removable during `init`, so that this is only
// due to outside interference.
fs::remove_file(&remove_path).unwrap_or_else(|e| {
panic!("Error removing file from cache: `{:?}`: {}", remove_path, e)
});
}
self.lru.insert(rel_path.to_owned(), size);
Ok(())
}
fn insert_by<K: AsRef<OsStr>, F: FnOnce(&Path) -> io::Result<()>>(
&mut self,
key: K,
size: Option<u64>,
by: F,
) -> Result<()> {
if let Some(size) = size {
if!self.can_store(size) {
return Err(Error::FileTooLarge);
}
}
let rel_path = key.as_ref();
let path = self.rel_to_abs_path(rel_path);
fs::create_dir_all(path.parent().expect("Bad path?"))?;
by(&path)?;
let size = match size {
Some(size) => size,
None => fs::metadata(path)?.len(),
};
self.add_file(AddFile::RelPath(rel_path), size)
.map_err(|e| {
error!(
"Failed to insert file `{}`: {}",
rel_path.to_string_lossy(),
e
);
fs::remove_file(&self.rel_to_abs_path(rel_path))
.expect("Failed to remove file we just created!");
e
})
}
/// Add a file by calling `with` with the open `File` corresponding to the cache at path `key`.
pub fn insert_with<K: AsRef<OsStr>, F: FnOnce(File) -> io::Result<()>>(
&mut self,
key: K,
with: F,
) -> Result<()> {
self.insert_by(key, None, |path| with(File::create(&path)?))
}
/// Add a file with `bytes` as its contents to the cache at path `key`.
pub fn insert_bytes<K: AsRef<OsStr>>(&mut self, key: K, bytes: &[u8]) -> Result<()> {
self.insert_by(key, Some(bytes.len() as u64), |path| {
let mut f = File::create(&path)?;
f.write_all(bytes)?;
Ok(())
})
}
/// Add an existing file at `path` to the cache at path `key`.
pub fn insert_file<K: AsRef<OsStr>, P: AsRef<OsStr>>(&mut self, key: K, path: P) -> Result<()> {
let size = fs::metadata(path.as_ref())?.len();
self.insert_by(key, Some(size), |new_path| {
fs::rename(path.as_ref(), new_path).or_else(|_| {
warn!("fs::rename failed, falling back to copy!");
fs::copy(path.as_ref(), new_path)?;
fs::remove_file(path.as_ref()).unwrap_or_else(|e| {
error!("Failed to remove original file in insert_file: {}", e)
});
Ok(())
})
})
}
/// Return `true` if a file with path `key` is in the cache.
pub fn contains_key<K: AsRef<OsStr>>(&self, key: K) -> bool {
self.lru.contains_key(key.as_ref())
}
/// Get an opened `File` for `key`, if one exists and can be opened. Updates the LRU state
/// of the file if present. Avoid using this method if at all possible, prefer `.get`.
pub fn get_file<K: AsRef<OsStr>>(&mut self, key: K) -> Result<File> {
let rel_path = key.as_ref();
let path = self.rel_to_abs_path(rel_path);
self.lru
.get(rel_path)
.ok_or(Error::FileNotInCache)
.and_then(|_| {
let t = FileTime::now();
set_file_times(&path, t, t)?;
File::open(path).map_err(Into::into)
})
}
/// Get an opened readable and seekable handle to the file at `key`, if one exists and can
/// be opened. Updates the LRU state of the file if present.
pub fn get<K: AsRef<OsStr>>(&mut self, key: K) -> Result<Box<dyn ReadSeek>> {
self.get_file(key).map(|f| Box::new(f) as Box<dyn ReadSeek>)
}
/// Remove the given key from the cache.
pub fn remove<K: AsRef<OsStr>>(&mut self, key: K) -> Result<()> {
match self.lru.remove(key.as_ref()) {
Some(_) => {
let path = self.rel_to_abs_path(key.as_ref());
fs::remove_file(&path).map_err(|e| {
error!("Error removing file from cache: `{:?}`: {}", path, e);
Into::into(e)
})
}
None => Ok(()),
}
}
}
#[cfg(test)]
mod tests {
use super::{Error, LruDiskCache};
use filetime::{set_file_times, FileTime};
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use tempfile::TempDir;
struct TestFixture {
/// Temp directory.
pub tempdir: TempDir,
}
fn create_file<T: AsRef<Path>, F: FnOnce(File) -> io::Result<()>>(
dir: &Path,
path: T,
fill_contents: F,
) -> io::Result<PathBuf> {
let b = dir.join(path);
fs::create_dir_all(b.parent().unwrap())?;
let f = fs::File::create(&b)?;
fill_contents(f)?;
b.canonicalize()
}
/// Set the last modified time of `path` backwards by `seconds` seconds.
fn set_mtime_back<T: AsRef<Path>>(path: T, seconds: usize) {
let m = fs::metadata(path.as_ref()).unwrap();
let t = FileTime::from_last_modification_time(&m);
let t = FileTime::from_unix_time(t.unix_seconds() - seconds as i64, t.nanoseconds());
set_file_times(path, t, t).unwrap();
}
fn read_all<R: Read>(r: &mut R) -> io::Result<Vec<u8>> {
let mut v = vec![];
r.read_to_end(&mut v)?;
Ok(v)
}
impl TestFixture {
pub fn new() -> TestFixture {
TestFixture {
tempdir: tempfile::Builder::new()
.prefix("lru-disk-cache-test")
.tempdir()
.unwrap(),
}
}
pub fn tmp(&self) -> &Path {
self.tempdir.path()
}
pub fn create_file<T: AsRef<Path>>(&self, path: T, size: usize) -> PathBuf {
create_file(self.tempdir.path(), path, |mut f| {
f.write_all(&vec![0; size])
})
.unwrap()
}
}
#[test]
fn test_empty_dir() {
let f = TestFixture::new();
LruDiskCache::new(f.tmp(), 1024).unwrap();
}
#[test]
fn test_missing_root() {
let f = TestFixture::new();
LruDiskCache::new(f.tmp().join("not-here"), 1024).unwrap();
}
#[test]
fn test_some_existing_files() {
let f = TestFixture::new();
f.create_file("file1", 10);
f.create_file("file2", 10);
let c = LruDiskCache::new(f.tmp(), 20).unwrap();
assert_eq!(c.size(), 20);
assert_eq!(c.len(), 2);
}
#[test]
fn test_existing_file_too_large() {
let f = TestFixture::new();
// Create files explicitly in the past.
set_mtime_back(f.create_file("file1", 10), 10);
set_mtime_back(f.create_file("file2", 10), 5);
let c = LruDiskCache::new(f.tmp(), 15).unwrap();
assert_eq!(c.size(), 10);
assert_eq!(c.len(), 1);
assert!(!c.contains_key("file1"));
assert!(c.contains_key("file2"));
}
#[test]
fn test_existing_files_lru_mtime() {
let f = TestFixture::new();
// Create files explicitly in the past.
set_mtime_back(f.create_file("file1", 10), 5);
set_mtime_back(f.create_file("file2", 10), 10);
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
assert_eq!(c.size(), 20);
c.insert_bytes("file3", &vec![0; 10]).unwrap();
assert_eq!(c.size(), 20);
// The oldest file on disk should have been removed.
assert!(!c.contains_key("file2"));
assert!(c.contains_key("file1"));
}
#[test]
fn test_insert_bytes() {
let f = TestFixture::new();
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
c.insert_bytes("a/b/c", &vec![0; 10]).unwrap();
assert!(c.contains_key("a/b/c"));
c.insert_bytes("a/b/d", &vec![0; 10]).unwrap();
assert_eq!(c.size(), 20);
// Adding this third file should put the cache above the limit.
c.insert_bytes("x/y/z", &vec![0; 10]).unwrap();
assert_eq!(c.size(), 20);
// The least-recently-used file should have been removed.
assert!(!c.contains_key("a/b/c"));
assert!(!f.tmp().join("a/b/c").exists());
}
#[test]
fn test_insert_bytes_exact() {
// Test that files adding up to exactly the size limit works.
let f = TestFixture::new();
let mut c = LruDiskCache::new(f.tmp(), 20).unwrap();
c.insert_bytes("file1", &vec![1; 10]).unwrap();
c.insert_bytes("file2", &vec![2; 10]).unwrap();
assert_eq!(c.size(), 20);
c.insert_bytes("file3", &vec![3; 10]).unwrap();
assert_eq!(c.size(), 20);
assert!(!c.contains_key("file1"));
}
#[test]
fn test_add_get_lru() {
let f = TestFixture::new();
{
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
c.insert_bytes("file1", &vec![1; 10]).unwrap();
c.insert_bytes("file2", &vec![2; 10]).unwrap();
// Get the file to bump its LRU status.
assert_eq!(
read_all(&mut c.get("file1").unwrap()).unwrap(),
vec![1u8; 10]
);
// Adding this third file should put the cache above the limit.
c.insert_bytes("file3", &vec![3; 10]).unwrap();
assert_eq!(c.size(), 20);
// The least-recently-used file should have been removed.
assert!(!c.contains_key("file2"));
}
// Get rid of the cache, to test that the LRU persists on-disk as mtimes.
// This is hacky, but mtime resolution on my mac with HFS+ is only 1 second, so we either
// need to have a 1 second sleep in the test (boo) or adjust the mtimes back a bit so
// that updating one file to the current time actually works to make it newer.
set_mtime_back(f.tmp().join("file1"), 5);
set_mtime_back(f.tmp().join("file3"), 5);
{
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
// Bump file1 again.
c.get("file1").unwrap();
}
// Now check that the on-disk mtimes were updated and used.
{
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
assert!(c.contains_key("file1"));
assert!(c.contains_key("file3"));
assert_eq!(c.size(), 20);
// Add another file to bump out the least-recently-used.
c.insert_bytes("file4", &vec![4; 10]).unwrap();
assert_eq!(c.size(), 20);
assert!(!c.contains_key("file3"));
assert!(c.contains_key("file1"));
}
}
#[test]
fn test_insert_bytes_too_large() {
let f = TestFixture::new();
let mut c = LruDiskCache::new(f.tmp(), 1).unwrap();
match c.insert_bytes("a/b/c", &vec![0; 2]) {
Err(Error::FileTooLarge) => assert!(true),
x @ _ => panic!("Unexpected result: {:?}", x),
}
}
#[test]
fn test_insert_file() {
let f = TestFixture::new();
let p1 = f.create_file("file1", 10);
let p2 = f.create_file("file2", 10);
let p3 = f.create_file("file3", 10);
let mut c = LruDiskCache::new(f.tmp().join("cache"), 25).unwrap();
c.insert_file("file1", &p1).unwrap();
assert_eq!(c.len(), 1);
c.insert_file("file2", &p2).unwrap();
assert_eq!(c.len(), 2);
// Get the file to bump its LRU status.
assert_eq!(
read_all(&mut c.get("file1").unwrap()).unwrap(),
vec![0u8; 10]
);
// Adding this third file
|
{
self.add_file(AddFile::AbsPath(file), size)
.unwrap_or_else(|e| error!("Error adding file: {}", e));
}
|
conditional_block
|
lib.rs
|
, such that the oldest modified file is returned first.
fn get_all_files<P: AsRef<Path>>(path: P) -> Box<dyn Iterator<Item = (PathBuf, u64)>> {
let mut files: Vec<_> = WalkDir::new(path.as_ref())
.into_iter()
.filter_map(|e| {
e.ok().and_then(|f| {
// Only look at files
if f.file_type().is_file() {
// Get the last-modified time, size, and the full path.
f.metadata().ok().and_then(|m| {
m.modified()
.ok()
.map(|mtime| (mtime, f.path().to_owned(), m.len()))
})
} else {
None
}
})
})
.collect();
// Sort by last-modified-time, so oldest file first.
files.sort_by_key(|k| k.0);
Box::new(files.into_iter().map(|(_mtime, path, size)| (path, size)))
}
/// An LRU cache of files on disk.
pub struct LruDiskCache<S: BuildHasher = RandomState> {
lru: LruCache<OsString, u64, S, FileSize>,
root: PathBuf,
}
/// Errors returned by this crate.
#[derive(Debug)]
pub enum Error {
/// The file was too large to fit in the cache.
FileTooLarge,
/// The file was not in the cache.
FileNotInCache,
/// An IO Error occurred.
Io(io::Error),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn std::error::Error +'static)> {
match self {
Error::FileTooLarge => None,
Error::FileNotInCache => None,
Error::Io(ref e) => Some(e),
}
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Error {
Error::Io(e)
}
}
/// A convenience `Result` type
pub type Result<T> = std::result::Result<T, Error>;
/// Trait objects can't be bounded by more than one non-builtin trait.
pub trait ReadSeek: Read + Seek + Send {}
impl<T: Read + Seek + Send> ReadSeek for T {}
enum AddFile<'a> {
AbsPath(PathBuf),
RelPath(&'a OsStr),
}
impl LruDiskCache {
/// Create an `LruDiskCache` that stores files in `path`, limited to `size` bytes.
///
/// Existing files in `path` will be stored with their last-modified time from the filesystem
/// used as the order for the recency of their use. Any files that are individually larger
/// than `size` bytes will be removed.
///
/// The cache is not observant of changes to files under `path` from external sources, it
/// expects to have sole maintence of the contents.
pub fn new<T>(path: T, size: u64) -> Result<Self>
where
PathBuf: From<T>,
{
LruDiskCache {
lru: LruCache::with_meter(size, FileSize),
root: PathBuf::from(path),
}
.init()
}
/// Return the current size of all the files in the cache.
pub fn size(&self) -> u64 {
self.lru.size()
}
/// Return the count of entries in the cache.
pub fn len(&self) -> usize {
self.lru.len()
}
pub fn is_empty(&self) -> bool {
self.lru.len() == 0
}
/// Return the maximum size of the cache.
pub fn capacity(&self) -> u64 {
self.lru.capacity()
}
/// Return the path in which the cache is stored.
pub fn path(&self) -> &Path {
self.root.as_path()
}
/// Return the path that `key` would be stored at.
fn rel_to_abs_path<K: AsRef<Path>>(&self, rel_path: K) -> PathBuf {
self.root.join(rel_path)
}
/// Scan `self.root` for existing files and store them.
fn init(mut self) -> Result<Self> {
fs::create_dir_all(&self.root)?;
for (file, size) in get_all_files(&self.root) {
if!self.can_store(size) {
fs::remove_file(file).unwrap_or_else(|e| {
error!(
"Error removing file `{}` which is too large for the cache ({} bytes)",
e, size
)
});
} else {
self.add_file(AddFile::AbsPath(file), size)
.unwrap_or_else(|e| error!("Error adding file: {}", e));
}
}
Ok(self)
}
/// Returns `true` if the disk cache can store a file of `size` bytes.
pub fn can_store(&self, size: u64) -> bool {
size <= self.lru.capacity() as u64
}
/// Add the file at `path` of size `size` to the cache.
fn add_file(&mut self, addfile_path: AddFile<'_>, size: u64) -> Result<()> {
if!self.can_store(size) {
return Err(Error::FileTooLarge);
}
let rel_path = match addfile_path {
AddFile::AbsPath(ref p) => p.strip_prefix(&self.root).expect("Bad path?").as_os_str(),
AddFile::RelPath(p) => p,
};
//TODO: ideally LRUCache::insert would give us back the entries it had to remove.
while self.lru.size() as u64 + size > self.lru.capacity() as u64 {
let (rel_path, _) = self.lru.remove_lru().expect("Unexpectedly empty cache!");
let remove_path = self.rel_to_abs_path(rel_path);
//TODO: check that files are removable during `init`, so that this is only
// due to outside interference.
fs::remove_file(&remove_path).unwrap_or_else(|e| {
panic!("Error removing file from cache: `{:?}`: {}", remove_path, e)
});
}
self.lru.insert(rel_path.to_owned(), size);
Ok(())
}
fn insert_by<K: AsRef<OsStr>, F: FnOnce(&Path) -> io::Result<()>>(
&mut self,
key: K,
size: Option<u64>,
by: F,
) -> Result<()> {
if let Some(size) = size {
if!self.can_store(size) {
return Err(Error::FileTooLarge);
}
}
let rel_path = key.as_ref();
let path = self.rel_to_abs_path(rel_path);
fs::create_dir_all(path.parent().expect("Bad path?"))?;
by(&path)?;
let size = match size {
Some(size) => size,
None => fs::metadata(path)?.len(),
};
self.add_file(AddFile::RelPath(rel_path), size)
.map_err(|e| {
error!(
"Failed to insert file `{}`: {}",
rel_path.to_string_lossy(),
e
);
fs::remove_file(&self.rel_to_abs_path(rel_path))
.expect("Failed to remove file we just created!");
e
})
}
/// Add a file by calling `with` with the open `File` corresponding to the cache at path `key`.
pub fn insert_with<K: AsRef<OsStr>, F: FnOnce(File) -> io::Result<()>>(
&mut self,
key: K,
with: F,
) -> Result<()> {
self.insert_by(key, None, |path| with(File::create(&path)?))
}
/// Add a file with `bytes` as its contents to the cache at path `key`.
pub fn insert_bytes<K: AsRef<OsStr>>(&mut self, key: K, bytes: &[u8]) -> Result<()> {
self.insert_by(key, Some(bytes.len() as u64), |path| {
let mut f = File::create(&path)?;
f.write_all(bytes)?;
Ok(())
})
}
/// Add an existing file at `path` to the cache at path `key`.
pub fn insert_file<K: AsRef<OsStr>, P: AsRef<OsStr>>(&mut self, key: K, path: P) -> Result<()> {
let size = fs::metadata(path.as_ref())?.len();
self.insert_by(key, Some(size), |new_path| {
fs::rename(path.as_ref(), new_path).or_else(|_| {
warn!("fs::rename failed, falling back to copy!");
fs::copy(path.as_ref(), new_path)?;
fs::remove_file(path.as_ref()).unwrap_or_else(|e| {
error!("Failed to remove original file in insert_file: {}", e)
});
Ok(())
})
})
}
/// Return `true` if a file with path `key` is in the cache.
pub fn contains_key<K: AsRef<OsStr>>(&self, key: K) -> bool {
self.lru.contains_key(key.as_ref())
}
/// Get an opened `File` for `key`, if one exists and can be opened. Updates the LRU state
/// of the file if present. Avoid using this method if at all possible, prefer `.get`.
pub fn get_file<K: AsRef<OsStr>>(&mut self, key: K) -> Result<File> {
let rel_path = key.as_ref();
let path = self.rel_to_abs_path(rel_path);
self.lru
.get(rel_path)
.ok_or(Error::FileNotInCache)
.and_then(|_| {
let t = FileTime::now();
set_file_times(&path, t, t)?;
File::open(path).map_err(Into::into)
})
}
/// Get an opened readable and seekable handle to the file at `key`, if one exists and can
/// be opened. Updates the LRU state of the file if present.
pub fn get<K: AsRef<OsStr>>(&mut self, key: K) -> Result<Box<dyn ReadSeek>> {
self.get_file(key).map(|f| Box::new(f) as Box<dyn ReadSeek>)
}
/// Remove the given key from the cache.
pub fn remove<K: AsRef<OsStr>>(&mut self, key: K) -> Result<()> {
match self.lru.remove(key.as_ref()) {
Some(_) => {
let path = self.rel_to_abs_path(key.as_ref());
fs::remove_file(&path).map_err(|e| {
error!("Error removing file from cache: `{:?}`: {}", path, e);
Into::into(e)
})
}
None => Ok(()),
}
}
}
#[cfg(test)]
mod tests {
use super::{Error, LruDiskCache};
use filetime::{set_file_times, FileTime};
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use tempfile::TempDir;
struct TestFixture {
/// Temp directory.
pub tempdir: TempDir,
}
fn create_file<T: AsRef<Path>, F: FnOnce(File) -> io::Result<()>>(
dir: &Path,
path: T,
fill_contents: F,
) -> io::Result<PathBuf> {
let b = dir.join(path);
fs::create_dir_all(b.parent().unwrap())?;
let f = fs::File::create(&b)?;
fill_contents(f)?;
b.canonicalize()
}
/// Set the last modified time of `path` backwards by `seconds` seconds.
fn set_mtime_back<T: AsRef<Path>>(path: T, seconds: usize) {
let m = fs::metadata(path.as_ref()).unwrap();
let t = FileTime::from_last_modification_time(&m);
let t = FileTime::from_unix_time(t.unix_seconds() - seconds as i64, t.nanoseconds());
set_file_times(path, t, t).unwrap();
}
fn
|
<R: Read>(r: &mut R) -> io::Result<Vec<u8>> {
let mut v = vec![];
r.read_to_end(&mut v)?;
Ok(v)
}
impl TestFixture {
pub fn new() -> TestFixture {
TestFixture {
tempdir: tempfile::Builder::new()
.prefix("lru-disk-cache-test")
.tempdir()
.unwrap(),
}
}
pub fn tmp(&self) -> &Path {
self.tempdir.path()
}
pub fn create_file<T: AsRef<Path>>(&self, path: T, size: usize) -> PathBuf {
create_file(self.tempdir.path(), path, |mut f| {
f.write_all(&vec![0; size])
})
.unwrap()
}
}
#[test]
fn test_empty_dir() {
let f = TestFixture::new();
LruDiskCache::new(f.tmp(), 1024).unwrap();
}
#[test]
fn test_missing_root() {
let f = TestFixture::new();
LruDiskCache::new(f.tmp().join("not-here"), 1024).unwrap();
}
#[test]
fn test_some_existing_files() {
let f = TestFixture::new();
f.create_file("file1", 10);
f.create_file("file2", 10);
let c = LruDiskCache::new(f.tmp(), 20).unwrap();
assert_eq!(c.size(), 20);
assert_eq!(c.len(), 2);
}
#[test]
fn test_existing_file_too_large() {
let f = TestFixture::new();
// Create files explicitly in the past.
set_mtime_back(f.create_file("file1", 10), 10);
set_mtime_back(f.create_file("file2", 10), 5);
let c = LruDiskCache::new(f.tmp(), 15).unwrap();
assert_eq!(c.size(), 10);
assert_eq!(c.len(), 1);
assert!(!c.contains_key("file1"));
assert!(c.contains_key("file2"));
}
#[test]
fn test_existing_files_lru_mtime() {
let f = TestFixture::new();
// Create files explicitly in the past.
set_mtime_back(f.create_file("file1", 10), 5);
set_mtime_back(f.create_file("file2", 10), 10);
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
assert_eq!(c.size(), 20);
c.insert_bytes("file3", &vec![0; 10]).unwrap();
assert_eq!(c.size(), 20);
// The oldest file on disk should have been removed.
assert!(!c.contains_key("file2"));
assert!(c.contains_key("file1"));
}
#[test]
fn test_insert_bytes() {
let f = TestFixture::new();
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
c.insert_bytes("a/b/c", &vec![0; 10]).unwrap();
assert!(c.contains_key("a/b/c"));
c.insert_bytes("a/b/d", &vec![0; 10]).unwrap();
assert_eq!(c.size(), 20);
// Adding this third file should put the cache above the limit.
c.insert_bytes("x/y/z", &vec![0; 10]).unwrap();
assert_eq!(c.size(), 20);
// The least-recently-used file should have been removed.
assert!(!c.contains_key("a/b/c"));
assert!(!f.tmp().join("a/b/c").exists());
}
#[test]
fn test_insert_bytes_exact() {
// Test that files adding up to exactly the size limit works.
let f = TestFixture::new();
let mut c = LruDiskCache::new(f.tmp(), 20).unwrap();
c.insert_bytes("file1", &vec![1; 10]).unwrap();
c.insert_bytes("file2", &vec![2; 10]).unwrap();
assert_eq!(c.size(), 20);
c.insert_bytes("file3", &vec![3; 10]).unwrap();
assert_eq!(c.size(), 20);
assert!(!c.contains_key("file1"));
}
#[test]
fn test_add_get_lru() {
let f = TestFixture::new();
{
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
c.insert_bytes("file1", &vec![1; 10]).unwrap();
c.insert_bytes("file2", &vec![2; 10]).unwrap();
// Get the file to bump its LRU status.
assert_eq!(
read_all(&mut c.get("file1").unwrap()).unwrap(),
vec![1u8; 10]
);
// Adding this third file should put the cache above the limit.
c.insert_bytes("file3", &vec![3; 10]).unwrap();
assert_eq!(c.size(), 20);
// The least-recently-used file should have been removed.
assert!(!c.contains_key("file2"));
}
// Get rid of the cache, to test that the LRU persists on-disk as mtimes.
// This is hacky, but mtime resolution on my mac with HFS+ is only 1 second, so we either
// need to have a 1 second sleep in the test (boo) or adjust the mtimes back a bit so
// that updating one file to the current time actually works to make it newer.
set_mtime_back(f.tmp().join("file1"), 5);
set_mtime_back(f.tmp().join("file3"), 5);
{
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
// Bump file1 again.
c.get("file1").unwrap();
}
// Now check that the on-disk mtimes were updated and used.
{
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
assert!(c.contains_key("file1"));
assert!(c.contains_key("file3"));
assert_eq!(c.size(), 20);
// Add another file to bump out the least-recently-used.
c.insert_bytes("file4", &vec![4; 10]).unwrap();
assert_eq!(c.size(), 20);
assert!(!c.contains_key("file3"));
assert!(c.contains_key("file1"));
}
}
#[test]
fn test_insert_bytes_too_large() {
let f = TestFixture::new();
let mut c = LruDiskCache::new(f.tmp(), 1).unwrap();
match c.insert_bytes("a/b/c", &vec![0; 2]) {
Err(Error::FileTooLarge) => assert!(true),
x @ _ => panic!("Unexpected result: {:?}", x),
}
}
#[test]
fn test_insert_file() {
let f = TestFixture::new();
let p1 = f.create_file("file1", 10);
let p2 = f.create_file("file2", 10);
let p3 = f.create_file("file3", 10);
let mut c = LruDiskCache::new(f.tmp().join("cache"), 25).unwrap();
c.insert_file("file1", &p1).unwrap();
assert_eq!(c.len(), 1);
c.insert_file("file2", &p2).unwrap();
assert_eq!(c.len(), 2);
// Get the file to bump its LRU status.
assert_eq!(
read_all(&mut c.get("file1").unwrap()).unwrap(),
vec![0u8; 10]
);
// Adding this third file
|
read_all
|
identifier_name
|
lib.rs
|
time, such that the oldest modified file is returned first.
fn get_all_files<P: AsRef<Path>>(path: P) -> Box<dyn Iterator<Item = (PathBuf, u64)>> {
let mut files: Vec<_> = WalkDir::new(path.as_ref())
.into_iter()
.filter_map(|e| {
e.ok().and_then(|f| {
// Only look at files
if f.file_type().is_file() {
// Get the last-modified time, size, and the full path.
f.metadata().ok().and_then(|m| {
m.modified()
.ok()
.map(|mtime| (mtime, f.path().to_owned(), m.len()))
})
} else {
None
}
})
})
.collect();
// Sort by last-modified-time, so oldest file first.
files.sort_by_key(|k| k.0);
Box::new(files.into_iter().map(|(_mtime, path, size)| (path, size)))
}
/// An LRU cache of files on disk.
pub struct LruDiskCache<S: BuildHasher = RandomState> {
lru: LruCache<OsString, u64, S, FileSize>,
root: PathBuf,
}
/// Errors returned by this crate.
#[derive(Debug)]
pub enum Error {
/// The file was too large to fit in the cache.
FileTooLarge,
/// The file was not in the cache.
FileNotInCache,
/// An IO Error occurred.
Io(io::Error),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn std::error::Error +'static)> {
match self {
Error::FileTooLarge => None,
Error::FileNotInCache => None,
Error::Io(ref e) => Some(e),
}
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Error {
Error::Io(e)
}
}
/// A convenience `Result` type
pub type Result<T> = std::result::Result<T, Error>;
/// Trait objects can't be bounded by more than one non-builtin trait.
pub trait ReadSeek: Read + Seek + Send {}
impl<T: Read + Seek + Send> ReadSeek for T {}
enum AddFile<'a> {
AbsPath(PathBuf),
RelPath(&'a OsStr),
}
impl LruDiskCache {
/// Create an `LruDiskCache` that stores files in `path`, limited to `size` bytes.
///
/// Existing files in `path` will be stored with their last-modified time from the filesystem
/// used as the order for the recency of their use. Any files that are individually larger
/// than `size` bytes will be removed.
///
/// The cache is not observant of changes to files under `path` from external sources, it
/// expects to have sole maintence of the contents.
pub fn new<T>(path: T, size: u64) -> Result<Self>
where
PathBuf: From<T>,
{
LruDiskCache {
lru: LruCache::with_meter(size, FileSize),
root: PathBuf::from(path),
}
.init()
}
/// Return the current size of all the files in the cache.
pub fn size(&self) -> u64 {
self.lru.size()
}
/// Return the count of entries in the cache.
pub fn len(&self) -> usize {
self.lru.len()
}
pub fn is_empty(&self) -> bool {
self.lru.len() == 0
}
/// Return the maximum size of the cache.
pub fn capacity(&self) -> u64 {
self.lru.capacity()
}
/// Return the path in which the cache is stored.
pub fn path(&self) -> &Path {
self.root.as_path()
}
/// Return the path that `key` would be stored at.
fn rel_to_abs_path<K: AsRef<Path>>(&self, rel_path: K) -> PathBuf {
self.root.join(rel_path)
}
/// Scan `self.root` for existing files and store them.
fn init(mut self) -> Result<Self> {
fs::create_dir_all(&self.root)?;
for (file, size) in get_all_files(&self.root) {
if!self.can_store(size) {
fs::remove_file(file).unwrap_or_else(|e| {
error!(
"Error removing file `{}` which is too large for the cache ({} bytes)",
e, size
)
});
} else {
self.add_file(AddFile::AbsPath(file), size)
.unwrap_or_else(|e| error!("Error adding file: {}", e));
}
}
Ok(self)
}
/// Returns `true` if the disk cache can store a file of `size` bytes.
pub fn can_store(&self, size: u64) -> bool {
size <= self.lru.capacity() as u64
}
/// Add the file at `path` of size `size` to the cache.
fn add_file(&mut self, addfile_path: AddFile<'_>, size: u64) -> Result<()> {
if!self.can_store(size) {
return Err(Error::FileTooLarge);
}
let rel_path = match addfile_path {
AddFile::AbsPath(ref p) => p.strip_prefix(&self.root).expect("Bad path?").as_os_str(),
AddFile::RelPath(p) => p,
};
//TODO: ideally LRUCache::insert would give us back the entries it had to remove.
while self.lru.size() as u64 + size > self.lru.capacity() as u64 {
let (rel_path, _) = self.lru.remove_lru().expect("Unexpectedly empty cache!");
let remove_path = self.rel_to_abs_path(rel_path);
//TODO: check that files are removable during `init`, so that this is only
// due to outside interference.
fs::remove_file(&remove_path).unwrap_or_else(|e| {
panic!("Error removing file from cache: `{:?}`: {}", remove_path, e)
});
}
self.lru.insert(rel_path.to_owned(), size);
Ok(())
}
fn insert_by<K: AsRef<OsStr>, F: FnOnce(&Path) -> io::Result<()>>(
&mut self,
key: K,
size: Option<u64>,
by: F,
) -> Result<()> {
if let Some(size) = size {
if!self.can_store(size) {
return Err(Error::FileTooLarge);
}
}
let rel_path = key.as_ref();
let path = self.rel_to_abs_path(rel_path);
fs::create_dir_all(path.parent().expect("Bad path?"))?;
by(&path)?;
let size = match size {
Some(size) => size,
None => fs::metadata(path)?.len(),
};
self.add_file(AddFile::RelPath(rel_path), size)
.map_err(|e| {
error!(
"Failed to insert file `{}`: {}",
rel_path.to_string_lossy(),
e
);
fs::remove_file(&self.rel_to_abs_path(rel_path))
.expect("Failed to remove file we just created!");
e
})
}
/// Add a file by calling `with` with the open `File` corresponding to the cache at path `key`.
pub fn insert_with<K: AsRef<OsStr>, F: FnOnce(File) -> io::Result<()>>(
&mut self,
key: K,
with: F,
) -> Result<()> {
self.insert_by(key, None, |path| with(File::create(&path)?))
}
/// Add a file with `bytes` as its contents to the cache at path `key`.
pub fn insert_bytes<K: AsRef<OsStr>>(&mut self, key: K, bytes: &[u8]) -> Result<()> {
self.insert_by(key, Some(bytes.len() as u64), |path| {
let mut f = File::create(&path)?;
f.write_all(bytes)?;
Ok(())
})
}
/// Add an existing file at `path` to the cache at path `key`.
pub fn insert_file<K: AsRef<OsStr>, P: AsRef<OsStr>>(&mut self, key: K, path: P) -> Result<()> {
let size = fs::metadata(path.as_ref())?.len();
self.insert_by(key, Some(size), |new_path| {
fs::rename(path.as_ref(), new_path).or_else(|_| {
warn!("fs::rename failed, falling back to copy!");
fs::copy(path.as_ref(), new_path)?;
fs::remove_file(path.as_ref()).unwrap_or_else(|e| {
error!("Failed to remove original file in insert_file: {}", e)
});
Ok(())
})
})
}
/// Return `true` if a file with path `key` is in the cache.
pub fn contains_key<K: AsRef<OsStr>>(&self, key: K) -> bool {
self.lru.contains_key(key.as_ref())
}
/// Get an opened `File` for `key`, if one exists and can be opened. Updates the LRU state
/// of the file if present. Avoid using this method if at all possible, prefer `.get`.
pub fn get_file<K: AsRef<OsStr>>(&mut self, key: K) -> Result<File> {
let rel_path = key.as_ref();
let path = self.rel_to_abs_path(rel_path);
self.lru
.get(rel_path)
.ok_or(Error::FileNotInCache)
.and_then(|_| {
let t = FileTime::now();
set_file_times(&path, t, t)?;
File::open(path).map_err(Into::into)
})
}
/// Get an opened readable and seekable handle to the file at `key`, if one exists and can
/// be opened. Updates the LRU state of the file if present.
pub fn get<K: AsRef<OsStr>>(&mut self, key: K) -> Result<Box<dyn ReadSeek>> {
self.get_file(key).map(|f| Box::new(f) as Box<dyn ReadSeek>)
}
/// Remove the given key from the cache.
pub fn remove<K: AsRef<OsStr>>(&mut self, key: K) -> Result<()> {
match self.lru.remove(key.as_ref()) {
Some(_) => {
let path = self.rel_to_abs_path(key.as_ref());
fs::remove_file(&path).map_err(|e| {
error!("Error removing file from cache: `{:?}`: {}", path, e);
Into::into(e)
})
}
None => Ok(()),
}
}
}
#[cfg(test)]
mod tests {
use super::{Error, LruDiskCache};
use filetime::{set_file_times, FileTime};
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use tempfile::TempDir;
struct TestFixture {
/// Temp directory.
pub tempdir: TempDir,
}
fn create_file<T: AsRef<Path>, F: FnOnce(File) -> io::Result<()>>(
dir: &Path,
path: T,
fill_contents: F,
) -> io::Result<PathBuf> {
let b = dir.join(path);
fs::create_dir_all(b.parent().unwrap())?;
let f = fs::File::create(&b)?;
fill_contents(f)?;
b.canonicalize()
}
/// Set the last modified time of `path` backwards by `seconds` seconds.
fn set_mtime_back<T: AsRef<Path>>(path: T, seconds: usize) {
let m = fs::metadata(path.as_ref()).unwrap();
let t = FileTime::from_last_modification_time(&m);
let t = FileTime::from_unix_time(t.unix_seconds() - seconds as i64, t.nanoseconds());
set_file_times(path, t, t).unwrap();
}
fn read_all<R: Read>(r: &mut R) -> io::Result<Vec<u8>> {
let mut v = vec![];
r.read_to_end(&mut v)?;
Ok(v)
|
}
impl TestFixture {
pub fn new() -> TestFixture {
TestFixture {
tempdir: tempfile::Builder::new()
.prefix("lru-disk-cache-test")
.tempdir()
.unwrap(),
}
}
pub fn tmp(&self) -> &Path {
self.tempdir.path()
}
pub fn create_file<T: AsRef<Path>>(&self, path: T, size: usize) -> PathBuf {
create_file(self.tempdir.path(), path, |mut f| {
f.write_all(&vec![0; size])
})
.unwrap()
}
}
#[test]
fn test_empty_dir() {
let f = TestFixture::new();
LruDiskCache::new(f.tmp(), 1024).unwrap();
}
#[test]
fn test_missing_root() {
let f = TestFixture::new();
LruDiskCache::new(f.tmp().join("not-here"), 1024).unwrap();
}
#[test]
fn test_some_existing_files() {
let f = TestFixture::new();
f.create_file("file1", 10);
f.create_file("file2", 10);
let c = LruDiskCache::new(f.tmp(), 20).unwrap();
assert_eq!(c.size(), 20);
assert_eq!(c.len(), 2);
}
#[test]
fn test_existing_file_too_large() {
let f = TestFixture::new();
// Create files explicitly in the past.
set_mtime_back(f.create_file("file1", 10), 10);
set_mtime_back(f.create_file("file2", 10), 5);
let c = LruDiskCache::new(f.tmp(), 15).unwrap();
assert_eq!(c.size(), 10);
assert_eq!(c.len(), 1);
assert!(!c.contains_key("file1"));
assert!(c.contains_key("file2"));
}
#[test]
fn test_existing_files_lru_mtime() {
let f = TestFixture::new();
// Create files explicitly in the past.
set_mtime_back(f.create_file("file1", 10), 5);
set_mtime_back(f.create_file("file2", 10), 10);
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
assert_eq!(c.size(), 20);
c.insert_bytes("file3", &vec![0; 10]).unwrap();
assert_eq!(c.size(), 20);
// The oldest file on disk should have been removed.
assert!(!c.contains_key("file2"));
assert!(c.contains_key("file1"));
}
#[test]
fn test_insert_bytes() {
let f = TestFixture::new();
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
c.insert_bytes("a/b/c", &vec![0; 10]).unwrap();
assert!(c.contains_key("a/b/c"));
c.insert_bytes("a/b/d", &vec![0; 10]).unwrap();
assert_eq!(c.size(), 20);
// Adding this third file should put the cache above the limit.
c.insert_bytes("x/y/z", &vec![0; 10]).unwrap();
assert_eq!(c.size(), 20);
// The least-recently-used file should have been removed.
assert!(!c.contains_key("a/b/c"));
assert!(!f.tmp().join("a/b/c").exists());
}
#[test]
fn test_insert_bytes_exact() {
// Test that files adding up to exactly the size limit works.
let f = TestFixture::new();
let mut c = LruDiskCache::new(f.tmp(), 20).unwrap();
c.insert_bytes("file1", &vec![1; 10]).unwrap();
c.insert_bytes("file2", &vec![2; 10]).unwrap();
assert_eq!(c.size(), 20);
c.insert_bytes("file3", &vec![3; 10]).unwrap();
assert_eq!(c.size(), 20);
assert!(!c.contains_key("file1"));
}
#[test]
fn test_add_get_lru() {
let f = TestFixture::new();
{
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
c.insert_bytes("file1", &vec![1; 10]).unwrap();
c.insert_bytes("file2", &vec![2; 10]).unwrap();
// Get the file to bump its LRU status.
assert_eq!(
read_all(&mut c.get("file1").unwrap()).unwrap(),
vec![1u8; 10]
);
// Adding this third file should put the cache above the limit.
c.insert_bytes("file3", &vec![3; 10]).unwrap();
assert_eq!(c.size(), 20);
// The least-recently-used file should have been removed.
assert!(!c.contains_key("file2"));
}
// Get rid of the cache, to test that the LRU persists on-disk as mtimes.
// This is hacky, but mtime resolution on my mac with HFS+ is only 1 second, so we either
// need to have a 1 second sleep in the test (boo) or adjust the mtimes back a bit so
// that updating one file to the current time actually works to make it newer.
set_mtime_back(f.tmp().join("file1"), 5);
set_mtime_back(f.tmp().join("file3"), 5);
{
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
// Bump file1 again.
c.get("file1").unwrap();
}
// Now check that the on-disk mtimes were updated and used.
{
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
assert!(c.contains_key("file1"));
assert!(c.contains_key("file3"));
assert_eq!(c.size(), 20);
// Add another file to bump out the least-recently-used.
c.insert_bytes("file4", &vec![4; 10]).unwrap();
assert_eq!(c.size(), 20);
assert!(!c.contains_key("file3"));
assert!(c.contains_key("file1"));
}
}
#[test]
fn test_insert_bytes_too_large() {
let f = TestFixture::new();
let mut c = LruDiskCache::new(f.tmp(), 1).unwrap();
match c.insert_bytes("a/b/c", &vec![0; 2]) {
Err(Error::FileTooLarge) => assert!(true),
x @ _ => panic!("Unexpected result: {:?}", x),
}
}
#[test]
fn test_insert_file() {
let f = TestFixture::new();
let p1 = f.create_file("file1", 10);
let p2 = f.create_file("file2", 10);
let p3 = f.create_file("file3", 10);
let mut c = LruDiskCache::new(f.tmp().join("cache"), 25).unwrap();
c.insert_file("file1", &p1).unwrap();
assert_eq!(c.len(), 1);
c.insert_file("file2", &p2).unwrap();
assert_eq!(c.len(), 2);
// Get the file to bump its LRU status.
assert_eq!(
read_all(&mut c.get("file1").unwrap()).unwrap(),
vec![0u8; 10]
);
// Adding this third file should
|
random_line_split
|
|
lib.rs
|
, such that the oldest modified file is returned first.
fn get_all_files<P: AsRef<Path>>(path: P) -> Box<dyn Iterator<Item = (PathBuf, u64)>> {
let mut files: Vec<_> = WalkDir::new(path.as_ref())
.into_iter()
.filter_map(|e| {
e.ok().and_then(|f| {
// Only look at files
if f.file_type().is_file() {
// Get the last-modified time, size, and the full path.
f.metadata().ok().and_then(|m| {
m.modified()
.ok()
.map(|mtime| (mtime, f.path().to_owned(), m.len()))
})
} else {
None
}
})
})
.collect();
// Sort by last-modified-time, so oldest file first.
files.sort_by_key(|k| k.0);
Box::new(files.into_iter().map(|(_mtime, path, size)| (path, size)))
}
/// An LRU cache of files on disk.
pub struct LruDiskCache<S: BuildHasher = RandomState> {
lru: LruCache<OsString, u64, S, FileSize>,
root: PathBuf,
}
/// Errors returned by this crate.
#[derive(Debug)]
pub enum Error {
/// The file was too large to fit in the cache.
FileTooLarge,
/// The file was not in the cache.
FileNotInCache,
/// An IO Error occurred.
Io(io::Error),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn std::error::Error +'static)>
|
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Error {
Error::Io(e)
}
}
/// A convenience `Result` type
pub type Result<T> = std::result::Result<T, Error>;
/// Trait objects can't be bounded by more than one non-builtin trait.
pub trait ReadSeek: Read + Seek + Send {}
impl<T: Read + Seek + Send> ReadSeek for T {}
enum AddFile<'a> {
AbsPath(PathBuf),
RelPath(&'a OsStr),
}
impl LruDiskCache {
/// Create an `LruDiskCache` that stores files in `path`, limited to `size` bytes.
///
/// Existing files in `path` will be stored with their last-modified time from the filesystem
/// used as the order for the recency of their use. Any files that are individually larger
/// than `size` bytes will be removed.
///
/// The cache is not observant of changes to files under `path` from external sources, it
/// expects to have sole maintence of the contents.
pub fn new<T>(path: T, size: u64) -> Result<Self>
where
PathBuf: From<T>,
{
LruDiskCache {
lru: LruCache::with_meter(size, FileSize),
root: PathBuf::from(path),
}
.init()
}
/// Return the current size of all the files in the cache.
pub fn size(&self) -> u64 {
self.lru.size()
}
/// Return the count of entries in the cache.
pub fn len(&self) -> usize {
self.lru.len()
}
pub fn is_empty(&self) -> bool {
self.lru.len() == 0
}
/// Return the maximum size of the cache.
pub fn capacity(&self) -> u64 {
self.lru.capacity()
}
/// Return the path in which the cache is stored.
pub fn path(&self) -> &Path {
self.root.as_path()
}
/// Return the path that `key` would be stored at.
fn rel_to_abs_path<K: AsRef<Path>>(&self, rel_path: K) -> PathBuf {
self.root.join(rel_path)
}
/// Scan `self.root` for existing files and store them.
fn init(mut self) -> Result<Self> {
fs::create_dir_all(&self.root)?;
for (file, size) in get_all_files(&self.root) {
if!self.can_store(size) {
fs::remove_file(file).unwrap_or_else(|e| {
error!(
"Error removing file `{}` which is too large for the cache ({} bytes)",
e, size
)
});
} else {
self.add_file(AddFile::AbsPath(file), size)
.unwrap_or_else(|e| error!("Error adding file: {}", e));
}
}
Ok(self)
}
/// Returns `true` if the disk cache can store a file of `size` bytes.
pub fn can_store(&self, size: u64) -> bool {
size <= self.lru.capacity() as u64
}
/// Add the file at `path` of size `size` to the cache.
fn add_file(&mut self, addfile_path: AddFile<'_>, size: u64) -> Result<()> {
if!self.can_store(size) {
return Err(Error::FileTooLarge);
}
let rel_path = match addfile_path {
AddFile::AbsPath(ref p) => p.strip_prefix(&self.root).expect("Bad path?").as_os_str(),
AddFile::RelPath(p) => p,
};
//TODO: ideally LRUCache::insert would give us back the entries it had to remove.
while self.lru.size() as u64 + size > self.lru.capacity() as u64 {
let (rel_path, _) = self.lru.remove_lru().expect("Unexpectedly empty cache!");
let remove_path = self.rel_to_abs_path(rel_path);
//TODO: check that files are removable during `init`, so that this is only
// due to outside interference.
fs::remove_file(&remove_path).unwrap_or_else(|e| {
panic!("Error removing file from cache: `{:?}`: {}", remove_path, e)
});
}
self.lru.insert(rel_path.to_owned(), size);
Ok(())
}
fn insert_by<K: AsRef<OsStr>, F: FnOnce(&Path) -> io::Result<()>>(
&mut self,
key: K,
size: Option<u64>,
by: F,
) -> Result<()> {
if let Some(size) = size {
if!self.can_store(size) {
return Err(Error::FileTooLarge);
}
}
let rel_path = key.as_ref();
let path = self.rel_to_abs_path(rel_path);
fs::create_dir_all(path.parent().expect("Bad path?"))?;
by(&path)?;
let size = match size {
Some(size) => size,
None => fs::metadata(path)?.len(),
};
self.add_file(AddFile::RelPath(rel_path), size)
.map_err(|e| {
error!(
"Failed to insert file `{}`: {}",
rel_path.to_string_lossy(),
e
);
fs::remove_file(&self.rel_to_abs_path(rel_path))
.expect("Failed to remove file we just created!");
e
})
}
/// Add a file by calling `with` with the open `File` corresponding to the cache at path `key`.
pub fn insert_with<K: AsRef<OsStr>, F: FnOnce(File) -> io::Result<()>>(
&mut self,
key: K,
with: F,
) -> Result<()> {
self.insert_by(key, None, |path| with(File::create(&path)?))
}
/// Add a file with `bytes` as its contents to the cache at path `key`.
pub fn insert_bytes<K: AsRef<OsStr>>(&mut self, key: K, bytes: &[u8]) -> Result<()> {
self.insert_by(key, Some(bytes.len() as u64), |path| {
let mut f = File::create(&path)?;
f.write_all(bytes)?;
Ok(())
})
}
/// Add an existing file at `path` to the cache at path `key`.
pub fn insert_file<K: AsRef<OsStr>, P: AsRef<OsStr>>(&mut self, key: K, path: P) -> Result<()> {
let size = fs::metadata(path.as_ref())?.len();
self.insert_by(key, Some(size), |new_path| {
fs::rename(path.as_ref(), new_path).or_else(|_| {
warn!("fs::rename failed, falling back to copy!");
fs::copy(path.as_ref(), new_path)?;
fs::remove_file(path.as_ref()).unwrap_or_else(|e| {
error!("Failed to remove original file in insert_file: {}", e)
});
Ok(())
})
})
}
/// Return `true` if a file with path `key` is in the cache.
pub fn contains_key<K: AsRef<OsStr>>(&self, key: K) -> bool {
self.lru.contains_key(key.as_ref())
}
/// Get an opened `File` for `key`, if one exists and can be opened. Updates the LRU state
/// of the file if present. Avoid using this method if at all possible, prefer `.get`.
pub fn get_file<K: AsRef<OsStr>>(&mut self, key: K) -> Result<File> {
let rel_path = key.as_ref();
let path = self.rel_to_abs_path(rel_path);
self.lru
.get(rel_path)
.ok_or(Error::FileNotInCache)
.and_then(|_| {
let t = FileTime::now();
set_file_times(&path, t, t)?;
File::open(path).map_err(Into::into)
})
}
/// Get an opened readable and seekable handle to the file at `key`, if one exists and can
/// be opened. Updates the LRU state of the file if present.
pub fn get<K: AsRef<OsStr>>(&mut self, key: K) -> Result<Box<dyn ReadSeek>> {
self.get_file(key).map(|f| Box::new(f) as Box<dyn ReadSeek>)
}
/// Remove the given key from the cache.
pub fn remove<K: AsRef<OsStr>>(&mut self, key: K) -> Result<()> {
match self.lru.remove(key.as_ref()) {
Some(_) => {
let path = self.rel_to_abs_path(key.as_ref());
fs::remove_file(&path).map_err(|e| {
error!("Error removing file from cache: `{:?}`: {}", path, e);
Into::into(e)
})
}
None => Ok(()),
}
}
}
#[cfg(test)]
mod tests {
use super::{Error, LruDiskCache};
use filetime::{set_file_times, FileTime};
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use tempfile::TempDir;
struct TestFixture {
/// Temp directory.
pub tempdir: TempDir,
}
fn create_file<T: AsRef<Path>, F: FnOnce(File) -> io::Result<()>>(
dir: &Path,
path: T,
fill_contents: F,
) -> io::Result<PathBuf> {
let b = dir.join(path);
fs::create_dir_all(b.parent().unwrap())?;
let f = fs::File::create(&b)?;
fill_contents(f)?;
b.canonicalize()
}
/// Set the last modified time of `path` backwards by `seconds` seconds.
fn set_mtime_back<T: AsRef<Path>>(path: T, seconds: usize) {
let m = fs::metadata(path.as_ref()).unwrap();
let t = FileTime::from_last_modification_time(&m);
let t = FileTime::from_unix_time(t.unix_seconds() - seconds as i64, t.nanoseconds());
set_file_times(path, t, t).unwrap();
}
fn read_all<R: Read>(r: &mut R) -> io::Result<Vec<u8>> {
let mut v = vec![];
r.read_to_end(&mut v)?;
Ok(v)
}
impl TestFixture {
pub fn new() -> TestFixture {
TestFixture {
tempdir: tempfile::Builder::new()
.prefix("lru-disk-cache-test")
.tempdir()
.unwrap(),
}
}
pub fn tmp(&self) -> &Path {
self.tempdir.path()
}
pub fn create_file<T: AsRef<Path>>(&self, path: T, size: usize) -> PathBuf {
create_file(self.tempdir.path(), path, |mut f| {
f.write_all(&vec![0; size])
})
.unwrap()
}
}
#[test]
fn test_empty_dir() {
let f = TestFixture::new();
LruDiskCache::new(f.tmp(), 1024).unwrap();
}
#[test]
fn test_missing_root() {
let f = TestFixture::new();
LruDiskCache::new(f.tmp().join("not-here"), 1024).unwrap();
}
#[test]
fn test_some_existing_files() {
let f = TestFixture::new();
f.create_file("file1", 10);
f.create_file("file2", 10);
let c = LruDiskCache::new(f.tmp(), 20).unwrap();
assert_eq!(c.size(), 20);
assert_eq!(c.len(), 2);
}
#[test]
fn test_existing_file_too_large() {
let f = TestFixture::new();
// Create files explicitly in the past.
set_mtime_back(f.create_file("file1", 10), 10);
set_mtime_back(f.create_file("file2", 10), 5);
let c = LruDiskCache::new(f.tmp(), 15).unwrap();
assert_eq!(c.size(), 10);
assert_eq!(c.len(), 1);
assert!(!c.contains_key("file1"));
assert!(c.contains_key("file2"));
}
#[test]
fn test_existing_files_lru_mtime() {
let f = TestFixture::new();
// Create files explicitly in the past.
set_mtime_back(f.create_file("file1", 10), 5);
set_mtime_back(f.create_file("file2", 10), 10);
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
assert_eq!(c.size(), 20);
c.insert_bytes("file3", &vec![0; 10]).unwrap();
assert_eq!(c.size(), 20);
// The oldest file on disk should have been removed.
assert!(!c.contains_key("file2"));
assert!(c.contains_key("file1"));
}
#[test]
fn test_insert_bytes() {
let f = TestFixture::new();
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
c.insert_bytes("a/b/c", &vec![0; 10]).unwrap();
assert!(c.contains_key("a/b/c"));
c.insert_bytes("a/b/d", &vec![0; 10]).unwrap();
assert_eq!(c.size(), 20);
// Adding this third file should put the cache above the limit.
c.insert_bytes("x/y/z", &vec![0; 10]).unwrap();
assert_eq!(c.size(), 20);
// The least-recently-used file should have been removed.
assert!(!c.contains_key("a/b/c"));
assert!(!f.tmp().join("a/b/c").exists());
}
#[test]
fn test_insert_bytes_exact() {
// Test that files adding up to exactly the size limit works.
let f = TestFixture::new();
let mut c = LruDiskCache::new(f.tmp(), 20).unwrap();
c.insert_bytes("file1", &vec![1; 10]).unwrap();
c.insert_bytes("file2", &vec![2; 10]).unwrap();
assert_eq!(c.size(), 20);
c.insert_bytes("file3", &vec![3; 10]).unwrap();
assert_eq!(c.size(), 20);
assert!(!c.contains_key("file1"));
}
#[test]
fn test_add_get_lru() {
let f = TestFixture::new();
{
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
c.insert_bytes("file1", &vec![1; 10]).unwrap();
c.insert_bytes("file2", &vec![2; 10]).unwrap();
// Get the file to bump its LRU status.
assert_eq!(
read_all(&mut c.get("file1").unwrap()).unwrap(),
vec![1u8; 10]
);
// Adding this third file should put the cache above the limit.
c.insert_bytes("file3", &vec![3; 10]).unwrap();
assert_eq!(c.size(), 20);
// The least-recently-used file should have been removed.
assert!(!c.contains_key("file2"));
}
// Get rid of the cache, to test that the LRU persists on-disk as mtimes.
// This is hacky, but mtime resolution on my mac with HFS+ is only 1 second, so we either
// need to have a 1 second sleep in the test (boo) or adjust the mtimes back a bit so
// that updating one file to the current time actually works to make it newer.
set_mtime_back(f.tmp().join("file1"), 5);
set_mtime_back(f.tmp().join("file3"), 5);
{
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
// Bump file1 again.
c.get("file1").unwrap();
}
// Now check that the on-disk mtimes were updated and used.
{
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
assert!(c.contains_key("file1"));
assert!(c.contains_key("file3"));
assert_eq!(c.size(), 20);
// Add another file to bump out the least-recently-used.
c.insert_bytes("file4", &vec![4; 10]).unwrap();
assert_eq!(c.size(), 20);
assert!(!c.contains_key("file3"));
assert!(c.contains_key("file1"));
}
}
#[test]
fn test_insert_bytes_too_large() {
let f = TestFixture::new();
let mut c = LruDiskCache::new(f.tmp(), 1).unwrap();
match c.insert_bytes("a/b/c", &vec![0; 2]) {
Err(Error::FileTooLarge) => assert!(true),
x @ _ => panic!("Unexpected result: {:?}", x),
}
}
#[test]
fn test_insert_file() {
let f = TestFixture::new();
let p1 = f.create_file("file1", 10);
let p2 = f.create_file("file2", 10);
let p3 = f.create_file("file3", 10);
let mut c = LruDiskCache::new(f.tmp().join("cache"), 25).unwrap();
c.insert_file("file1", &p1).unwrap();
assert_eq!(c.len(), 1);
c.insert_file("file2", &p2).unwrap();
assert_eq!(c.len(), 2);
// Get the file to bump its LRU status.
assert_eq!(
read_all(&mut c.get("file1").unwrap()).unwrap(),
vec![0u8; 10]
);
// Adding this third file
|
{
match self {
Error::FileTooLarge => None,
Error::FileNotInCache => None,
Error::Io(ref e) => Some(e),
}
}
|
identifier_body
|
extern.rs
|
extern "C" {
|
fn c_func(x: *mut *mut libc::c_void);
fn c_func(x: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX, y: YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY);
#[test123]
fn foo() -> uint64_t;
pub fn bar() ;
}
extern {
fn DMR_GetDevice(pHDev: *mut HDEV, searchMode: DeviceSearchMode, pSearchString: *const c_char, devNr: c_uint, wildcard: c_char) -> TDMR_ERROR;
fn quux() -> (); // Post comment
}
extern "Rust" { static ext: u32;
// Some comment.
pub static mut var : SomeType ; }
extern "C" {
fn syscall(number: libc::c_long /* comment 1 */, /* comm 2 */... /* sup? */) -> libc::c_long;
fn foo (x: *const c_char, ... ) ->
libc::c_long;
}
extern {
pub fn freopen(filename: *const c_char, mode: *const c_char
, mode2: *const c_char
, mode3: *const c_char,
file: *mut FILE)
-> *mut FILE;
}
extern {
}
|
random_line_split
|
|
main.rs
|
#![cfg_attr(feature = "nightly-testing", feature(plugin))]
mod botocore;
mod cargo;
mod commands;
mod config;
mod doco;
mod service;
mod util;
use std::path::Path;
use clap::{crate_authors, crate_description, crate_version, App, Arg, SubCommand};
use crate::botocore::ServiceDefinition;
use crate::config::ServiceConfig;
use crate::service::Service;
fn main() {
let matches = App::new("Rusoto Service Crate Generator")
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.subcommand(
SubCommand::with_name("check").arg(
Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true),
),
)
.subcommand(
SubCommand::with_name("generate")
.arg(
Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true),
)
.arg(
Arg::with_name("out_dir")
.long("outdir")
.short("o")
.takes_value(true)
.required(true),
)
.arg(
Arg::with_name("service")
.long("service")
.short("s")
.takes_value(true)
.multiple(true)
.required(false),
),
)
.get_matches();
if let Some(matches) = matches.subcommand_matches("check") {
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path)
.expect("Unable to read services configuration file.");
commands::check::check(service_configs);
}
if let Some(matches) = matches.subcommand_matches("generate") {
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path)
.expect("Unable to read services configuration file.");
let out_dir = Path::new(matches.value_of("out_dir").unwrap());
let service: Option<Vec<&str>> = matches
.values_of("service")
.map(std::iter::Iterator::collect);
commands::generate::generate_services(&service_configs, out_dir, service.as_ref());
}
|
}
|
random_line_split
|
|
main.rs
|
#![cfg_attr(feature = "nightly-testing", feature(plugin))]
mod botocore;
mod cargo;
mod commands;
mod config;
mod doco;
mod service;
mod util;
use std::path::Path;
use clap::{crate_authors, crate_description, crate_version, App, Arg, SubCommand};
use crate::botocore::ServiceDefinition;
use crate::config::ServiceConfig;
use crate::service::Service;
fn main()
|
)
.arg(
Arg::with_name("out_dir")
.long("outdir")
.short("o")
.takes_value(true)
.required(true),
)
.arg(
Arg::with_name("service")
.long("service")
.short("s")
.takes_value(true)
.multiple(true)
.required(false),
),
)
.get_matches();
if let Some(matches) = matches.subcommand_matches("check") {
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path)
.expect("Unable to read services configuration file.");
commands::check::check(service_configs);
}
if let Some(matches) = matches.subcommand_matches("generate") {
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path)
.expect("Unable to read services configuration file.");
let out_dir = Path::new(matches.value_of("out_dir").unwrap());
let service: Option<Vec<&str>> = matches
.values_of("service")
.map(std::iter::Iterator::collect);
commands::generate::generate_services(&service_configs, out_dir, service.as_ref());
}
}
|
{
let matches = App::new("Rusoto Service Crate Generator")
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.subcommand(
SubCommand::with_name("check").arg(
Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true),
),
)
.subcommand(
SubCommand::with_name("generate")
.arg(
Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true),
|
identifier_body
|
main.rs
|
#![cfg_attr(feature = "nightly-testing", feature(plugin))]
mod botocore;
mod cargo;
mod commands;
mod config;
mod doco;
mod service;
mod util;
use std::path::Path;
use clap::{crate_authors, crate_description, crate_version, App, Arg, SubCommand};
use crate::botocore::ServiceDefinition;
use crate::config::ServiceConfig;
use crate::service::Service;
fn
|
() {
let matches = App::new("Rusoto Service Crate Generator")
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.subcommand(
SubCommand::with_name("check").arg(
Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true),
),
)
.subcommand(
SubCommand::with_name("generate")
.arg(
Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true),
)
.arg(
Arg::with_name("out_dir")
.long("outdir")
.short("o")
.takes_value(true)
.required(true),
)
.arg(
Arg::with_name("service")
.long("service")
.short("s")
.takes_value(true)
.multiple(true)
.required(false),
),
)
.get_matches();
if let Some(matches) = matches.subcommand_matches("check") {
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path)
.expect("Unable to read services configuration file.");
commands::check::check(service_configs);
}
if let Some(matches) = matches.subcommand_matches("generate") {
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path)
.expect("Unable to read services configuration file.");
let out_dir = Path::new(matches.value_of("out_dir").unwrap());
let service: Option<Vec<&str>> = matches
.values_of("service")
.map(std::iter::Iterator::collect);
commands::generate::generate_services(&service_configs, out_dir, service.as_ref());
}
}
|
main
|
identifier_name
|
main.rs
|
#![cfg_attr(feature = "nightly-testing", feature(plugin))]
mod botocore;
mod cargo;
mod commands;
mod config;
mod doco;
mod service;
mod util;
use std::path::Path;
use clap::{crate_authors, crate_description, crate_version, App, Arg, SubCommand};
use crate::botocore::ServiceDefinition;
use crate::config::ServiceConfig;
use crate::service::Service;
fn main() {
let matches = App::new("Rusoto Service Crate Generator")
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.subcommand(
SubCommand::with_name("check").arg(
Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true),
),
)
.subcommand(
SubCommand::with_name("generate")
.arg(
Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true),
)
.arg(
Arg::with_name("out_dir")
.long("outdir")
.short("o")
.takes_value(true)
.required(true),
)
.arg(
Arg::with_name("service")
.long("service")
.short("s")
.takes_value(true)
.multiple(true)
.required(false),
),
)
.get_matches();
if let Some(matches) = matches.subcommand_matches("check")
|
if let Some(matches) = matches.subcommand_matches("generate") {
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path)
.expect("Unable to read services configuration file.");
let out_dir = Path::new(matches.value_of("out_dir").unwrap());
let service: Option<Vec<&str>> = matches
.values_of("service")
.map(std::iter::Iterator::collect);
commands::generate::generate_services(&service_configs, out_dir, service.as_ref());
}
}
|
{
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path)
.expect("Unable to read services configuration file.");
commands::check::check(service_configs);
}
|
conditional_block
|
slice-panic-1.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that if a slicing expr[..] fails, the correct cleanups happen.
// pretty-expanded FIXME #23616
use std::thread;
struct Foo;
static mut DTOR_COUNT: isize = 0;
impl Drop for Foo {
fn drop(&mut self)
|
}
fn foo() {
let x: &[_] = &[Foo, Foo];
&x[3..4];
}
fn main() {
let _ = thread::spawn(move|| foo()).join();
unsafe { assert!(DTOR_COUNT == 2); }
}
|
{ unsafe { DTOR_COUNT += 1; } }
|
identifier_body
|
slice-panic-1.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that if a slicing expr[..] fails, the correct cleanups happen.
// pretty-expanded FIXME #23616
use std::thread;
struct Foo;
static mut DTOR_COUNT: isize = 0;
impl Drop for Foo {
fn drop(&mut self) { unsafe { DTOR_COUNT += 1; } }
}
fn
|
() {
let x: &[_] = &[Foo, Foo];
&x[3..4];
}
fn main() {
let _ = thread::spawn(move|| foo()).join();
unsafe { assert!(DTOR_COUNT == 2); }
}
|
foo
|
identifier_name
|
slice-panic-1.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that if a slicing expr[..] fails, the correct cleanups happen.
// pretty-expanded FIXME #23616
use std::thread;
|
fn drop(&mut self) { unsafe { DTOR_COUNT += 1; } }
}
fn foo() {
let x: &[_] = &[Foo, Foo];
&x[3..4];
}
fn main() {
let _ = thread::spawn(move|| foo()).join();
unsafe { assert!(DTOR_COUNT == 2); }
}
|
struct Foo;
static mut DTOR_COUNT: isize = 0;
impl Drop for Foo {
|
random_line_split
|
raw.rs
|
// Copyright 2015 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.
//! Raw OS-specific types for the current platform/architecture
#![unstable(feature = "raw_os", reason = "recently added API")]
#[cfg(target_arch = "aarch64")] pub type c_char = u8;
#[cfg(not(target_arch = "aarch64"))] pub type c_char = i8;
pub type c_schar = i8;
pub type c_uchar = u8;
pub type c_short = i16;
pub type c_ushort = u16;
pub type c_int = i32;
pub type c_uint = u32;
#[cfg(any(target_pointer_width = "32", windows))] pub type c_long = i32;
#[cfg(any(target_pointer_width = "32", windows))] pub type c_ulong = u32;
#[cfg(all(target_pointer_width = "64", not(windows)))] pub type c_long = i64;
#[cfg(all(target_pointer_width = "64", not(windows)))] pub type c_ulong = u64;
pub type c_longlong = i64;
pub type c_ulonglong = u64;
pub type c_float = f32;
pub type c_double = f64;
/// Type used to construct void pointers for use with C.
///
/// This type is only useful as a pointer target. Do not use it as a
/// return type for FFI functions which have the `void` return type in
/// C. Use the unit type `()` or omit the return type instead.
// NB: For LLVM to recognize the void pointer type and by extension
// functions like malloc(), we need to have it represented as i8* in
// LLVM bitcode. The enum used here ensures this and prevents misuse
// of the "raw" type by only having private variants.. We need two
// variants, because the compiler complains about the repr attribute
// otherwise.
#[repr(u8)]
pub enum c_void {
#[doc(hidden)] __variant1,
#[doc(hidden)] __variant2,
}
#[cfg(test)]
mod tests {
use any::TypeId;
use libc;
use mem;
macro_rules! ok {
($($t:ident)*) => {$(
assert!(TypeId::of::<libc::$t>() == TypeId::of::<raw::$t>(),
"{} is wrong", stringify!($t));
)*}
}
macro_rules! ok_size {
($($t:ident)*) => {$(
assert!(mem::size_of::<libc::$t>() == mem::size_of::<raw::$t>(),
"{} is wrong", stringify!($t));
)*}
}
#[test]
fn same() {
use os::raw;
ok!(c_char c_schar c_uchar c_short c_ushort c_int c_uint c_long c_ulong
c_longlong c_ulonglong c_float c_double);
}
#[cfg(unix)]
fn unix() {
{
use os::unix::raw;
ok!(uid_t gid_t dev_t ino_t mode_t nlink_t off_t blksize_t blkcnt_t);
}
{
use sys::platform::raw;
ok_size!(stat);
}
}
#[cfg(windows)]
fn
|
() {
use os::windows::raw;
}
}
|
windows
|
identifier_name
|
raw.rs
|
// Copyright 2015 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.
//! Raw OS-specific types for the current platform/architecture
#![unstable(feature = "raw_os", reason = "recently added API")]
#[cfg(target_arch = "aarch64")] pub type c_char = u8;
#[cfg(not(target_arch = "aarch64"))] pub type c_char = i8;
pub type c_schar = i8;
pub type c_uchar = u8;
pub type c_short = i16;
pub type c_ushort = u16;
pub type c_int = i32;
pub type c_uint = u32;
#[cfg(any(target_pointer_width = "32", windows))] pub type c_long = i32;
#[cfg(any(target_pointer_width = "32", windows))] pub type c_ulong = u32;
#[cfg(all(target_pointer_width = "64", not(windows)))] pub type c_long = i64;
#[cfg(all(target_pointer_width = "64", not(windows)))] pub type c_ulong = u64;
pub type c_longlong = i64;
pub type c_ulonglong = u64;
pub type c_float = f32;
pub type c_double = f64;
/// Type used to construct void pointers for use with C.
///
/// This type is only useful as a pointer target. Do not use it as a
/// return type for FFI functions which have the `void` return type in
/// C. Use the unit type `()` or omit the return type instead.
// NB: For LLVM to recognize the void pointer type and by extension
// functions like malloc(), we need to have it represented as i8* in
// LLVM bitcode. The enum used here ensures this and prevents misuse
// of the "raw" type by only having private variants.. We need two
// variants, because the compiler complains about the repr attribute
// otherwise.
#[repr(u8)]
pub enum c_void {
#[doc(hidden)] __variant1,
#[doc(hidden)] __variant2,
}
#[cfg(test)]
mod tests {
use any::TypeId;
use libc;
use mem;
macro_rules! ok {
($($t:ident)*) => {$(
assert!(TypeId::of::<libc::$t>() == TypeId::of::<raw::$t>(),
"{} is wrong", stringify!($t));
)*}
}
macro_rules! ok_size {
($($t:ident)*) => {$(
assert!(mem::size_of::<libc::$t>() == mem::size_of::<raw::$t>(),
"{} is wrong", stringify!($t));
)*}
}
#[test]
fn same() {
use os::raw;
ok!(c_char c_schar c_uchar c_short c_ushort c_int c_uint c_long c_ulong
c_longlong c_ulonglong c_float c_double);
}
#[cfg(unix)]
fn unix() {
{
use os::unix::raw;
ok!(uid_t gid_t dev_t ino_t mode_t nlink_t off_t blksize_t blkcnt_t);
}
{
use sys::platform::raw;
|
#[cfg(windows)]
fn windows() {
use os::windows::raw;
}
}
|
ok_size!(stat);
}
}
|
random_line_split
|
raw.rs
|
// Copyright 2015 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.
//! Raw OS-specific types for the current platform/architecture
#![unstable(feature = "raw_os", reason = "recently added API")]
#[cfg(target_arch = "aarch64")] pub type c_char = u8;
#[cfg(not(target_arch = "aarch64"))] pub type c_char = i8;
pub type c_schar = i8;
pub type c_uchar = u8;
pub type c_short = i16;
pub type c_ushort = u16;
pub type c_int = i32;
pub type c_uint = u32;
#[cfg(any(target_pointer_width = "32", windows))] pub type c_long = i32;
#[cfg(any(target_pointer_width = "32", windows))] pub type c_ulong = u32;
#[cfg(all(target_pointer_width = "64", not(windows)))] pub type c_long = i64;
#[cfg(all(target_pointer_width = "64", not(windows)))] pub type c_ulong = u64;
pub type c_longlong = i64;
pub type c_ulonglong = u64;
pub type c_float = f32;
pub type c_double = f64;
/// Type used to construct void pointers for use with C.
///
/// This type is only useful as a pointer target. Do not use it as a
/// return type for FFI functions which have the `void` return type in
/// C. Use the unit type `()` or omit the return type instead.
// NB: For LLVM to recognize the void pointer type and by extension
// functions like malloc(), we need to have it represented as i8* in
// LLVM bitcode. The enum used here ensures this and prevents misuse
// of the "raw" type by only having private variants.. We need two
// variants, because the compiler complains about the repr attribute
// otherwise.
#[repr(u8)]
pub enum c_void {
#[doc(hidden)] __variant1,
#[doc(hidden)] __variant2,
}
#[cfg(test)]
mod tests {
use any::TypeId;
use libc;
use mem;
macro_rules! ok {
($($t:ident)*) => {$(
assert!(TypeId::of::<libc::$t>() == TypeId::of::<raw::$t>(),
"{} is wrong", stringify!($t));
)*}
}
macro_rules! ok_size {
($($t:ident)*) => {$(
assert!(mem::size_of::<libc::$t>() == mem::size_of::<raw::$t>(),
"{} is wrong", stringify!($t));
)*}
}
#[test]
fn same()
|
#[cfg(unix)]
fn unix() {
{
use os::unix::raw;
ok!(uid_t gid_t dev_t ino_t mode_t nlink_t off_t blksize_t blkcnt_t);
}
{
use sys::platform::raw;
ok_size!(stat);
}
}
#[cfg(windows)]
fn windows() {
use os::windows::raw;
}
}
|
{
use os::raw;
ok!(c_char c_schar c_uchar c_short c_ushort c_int c_uint c_long c_ulong
c_longlong c_ulonglong c_float c_double);
}
|
identifier_body
|
issue-9129.rs
|
// run-pass
#![allow(dead_code)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(deprecated)] // llvm_asm!
// ignore-pretty unreported
#![feature(box_syntax)]
pub trait bomb { fn boom(&self, _: Ident); }
pub struct S;
impl bomb for S { fn
|
(&self, _: Ident) { } }
pub struct Ident { name: usize }
// macro_rules! int3 { () => ( unsafe { llvm_asm!( "int3" ); } ) }
macro_rules! int3 { () => ( { } ) }
fn Ident_new() -> Ident {
int3!();
Ident {name: 0x6789ABCD }
}
pub fn light_fuse(fld: Box<dyn bomb>) {
int3!();
let f = || {
int3!();
fld.boom(Ident_new()); // *** 1
};
f();
}
pub fn main() {
let b = box S as Box<dyn bomb>;
light_fuse(b);
}
|
boom
|
identifier_name
|
issue-9129.rs
|
// run-pass
#![allow(dead_code)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(deprecated)] // llvm_asm!
// ignore-pretty unreported
#![feature(box_syntax)]
pub trait bomb { fn boom(&self, _: Ident); }
pub struct S;
impl bomb for S { fn boom(&self, _: Ident) { } }
pub struct Ident { name: usize }
// macro_rules! int3 { () => ( unsafe { llvm_asm!( "int3" ); } ) }
macro_rules! int3 { () => ( { } ) }
fn Ident_new() -> Ident
|
pub fn light_fuse(fld: Box<dyn bomb>) {
int3!();
let f = || {
int3!();
fld.boom(Ident_new()); // *** 1
};
f();
}
pub fn main() {
let b = box S as Box<dyn bomb>;
light_fuse(b);
}
|
{
int3!();
Ident {name: 0x6789ABCD }
}
|
identifier_body
|
issue-9129.rs
|
// run-pass
#![allow(dead_code)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(deprecated)] // llvm_asm!
// ignore-pretty unreported
#![feature(box_syntax)]
|
pub struct S;
impl bomb for S { fn boom(&self, _: Ident) { } }
pub struct Ident { name: usize }
// macro_rules! int3 { () => ( unsafe { llvm_asm!( "int3" ); } ) }
macro_rules! int3 { () => ( { } ) }
fn Ident_new() -> Ident {
int3!();
Ident {name: 0x6789ABCD }
}
pub fn light_fuse(fld: Box<dyn bomb>) {
int3!();
let f = || {
int3!();
fld.boom(Ident_new()); // *** 1
};
f();
}
pub fn main() {
let b = box S as Box<dyn bomb>;
light_fuse(b);
}
|
pub trait bomb { fn boom(&self, _: Ident); }
|
random_line_split
|
modulo_arithmetic_float.rs
|
#![warn(clippy::modulo_arithmetic)]
#![allow(
unused,
clippy::shadow_reuse,
clippy::shadow_unrelated,
clippy::no_effect,
clippy::unnecessary_operation,
clippy::modulo_one
)]
fn main()
|
// No lint when both sides are const and of the same sign
1.6 % 2.1;
-1.6 % -2.1;
(1.1 + 2.3) % (-1.1 + 2.3);
(-1.1 - 2.3) % (1.1 - 2.3);
}
|
{
// Lint when both sides are const and of the opposite sign
-1.6 % 2.1;
1.6 % -2.1;
(1.1 - 2.3) % (1.1 + 2.3);
(1.1 + 2.3) % (1.1 - 2.3);
// Lint on floating point numbers
let a_f32: f32 = -1.6;
let mut b_f32: f32 = 2.1;
a_f32 % b_f32;
b_f32 % a_f32;
b_f32 %= a_f32;
let a_f64: f64 = -1.6;
let mut b_f64: f64 = 2.1;
a_f64 % b_f64;
b_f64 % a_f64;
b_f64 %= a_f64;
|
identifier_body
|
modulo_arithmetic_float.rs
|
#![warn(clippy::modulo_arithmetic)]
#![allow(
unused,
clippy::shadow_reuse,
clippy::shadow_unrelated,
clippy::no_effect,
clippy::unnecessary_operation,
clippy::modulo_one
)]
fn
|
() {
// Lint when both sides are const and of the opposite sign
-1.6 % 2.1;
1.6 % -2.1;
(1.1 - 2.3) % (1.1 + 2.3);
(1.1 + 2.3) % (1.1 - 2.3);
// Lint on floating point numbers
let a_f32: f32 = -1.6;
let mut b_f32: f32 = 2.1;
a_f32 % b_f32;
b_f32 % a_f32;
b_f32 %= a_f32;
let a_f64: f64 = -1.6;
let mut b_f64: f64 = 2.1;
a_f64 % b_f64;
b_f64 % a_f64;
b_f64 %= a_f64;
// No lint when both sides are const and of the same sign
1.6 % 2.1;
-1.6 % -2.1;
(1.1 + 2.3) % (-1.1 + 2.3);
(-1.1 - 2.3) % (1.1 - 2.3);
}
|
main
|
identifier_name
|
modulo_arithmetic_float.rs
|
#![warn(clippy::modulo_arithmetic)]
#![allow(
unused,
clippy::shadow_reuse,
clippy::shadow_unrelated,
clippy::no_effect,
clippy::unnecessary_operation,
clippy::modulo_one
)]
fn main() {
// Lint when both sides are const and of the opposite sign
-1.6 % 2.1;
1.6 % -2.1;
(1.1 - 2.3) % (1.1 + 2.3);
(1.1 + 2.3) % (1.1 - 2.3);
// Lint on floating point numbers
let a_f32: f32 = -1.6;
let mut b_f32: f32 = 2.1;
a_f32 % b_f32;
b_f32 % a_f32;
b_f32 %= a_f32;
let a_f64: f64 = -1.6;
let mut b_f64: f64 = 2.1;
a_f64 % b_f64;
b_f64 % a_f64;
b_f64 %= a_f64;
// No lint when both sides are const and of the same sign
1.6 % 2.1;
|
(1.1 + 2.3) % (-1.1 + 2.3);
(-1.1 - 2.3) % (1.1 - 2.3);
}
|
-1.6 % -2.1;
|
random_line_split
|
deriving-span-PartialOrd-struct.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.
// This file was auto-generated using'src/etc/generate-deriving-span-tests.py'
extern crate rand;
#[derive(PartialEq)]
struct Error;
#[derive(PartialOrd,PartialEq)]
struct
|
{
x: Error //~ ERROR
//~^ ERROR
//~^^ ERROR
//~^^^ ERROR
//~^^^^ ERROR
//~^^^^^ ERROR
//~^^^^^^ ERROR
//~^^^^^^^ ERROR
//~^^^^^^^^ ERROR
}
fn main() {}
|
Struct
|
identifier_name
|
deriving-span-PartialOrd-struct.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.
// This file was auto-generated using'src/etc/generate-deriving-span-tests.py'
extern crate rand;
#[derive(PartialEq)]
struct Error;
#[derive(PartialOrd,PartialEq)]
struct Struct {
x: Error //~ ERROR
//~^ ERROR
|
//~^^^ ERROR
//~^^^^ ERROR
//~^^^^^ ERROR
//~^^^^^^ ERROR
//~^^^^^^^ ERROR
//~^^^^^^^^ ERROR
}
fn main() {}
|
//~^^ ERROR
|
random_line_split
|
core_thread.rs
|
use modulo_traits::core_msg::ToCoreThreadMsg;
use modulo_traits::file_msg::{FileThreadId, ToFileThreadMsg};
use file::file_thread::FileThread;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::mpsc::{self, Sender, Receiver};
use std::thread::{self, JoinHandle};
pub struct Core {
file_threads: HashMap<FileThreadId, Sender<ToFileThreadMsg>>,
file_receiver: Receiver<ToCoreThreadMsg>,
file_sender: Sender<ToCoreThreadMsg>,
|
impl Core {
pub fn start() -> (Sender<ToCoreThreadMsg>, JoinHandle<()>) {
let (sender, receiver) = mpsc::channel();
let file_sender = sender.clone();
let handle = thread::spawn(move || {
let mut core = Core {
file_threads: HashMap::new(),
file_receiver: receiver,
file_sender: file_sender,
file_id_counter: 0,
};
core.run();
});
(sender, handle)
}
/// Runs the event loop for the `CoreThread`
pub fn run(&mut self) {
while let Ok(msg) = self.file_receiver.recv() {
match msg {
ToCoreThreadMsg::FileThreadMsg(id, msg) => {
let file_thread = match self.file_threads.get(&id) {
Some(file_thread) => file_thread,
None => return warn!("Received message for closed file thread: {:?}", id),
};
let _ = file_thread.send(msg);
},
ToCoreThreadMsg::SpawnFileThread(path) =>
self.handle_spawn_file_thread(path),
}
}
}
pub fn handle_spawn_file_thread(&mut self, path: Option<PathBuf>) {
let (sender, receiver) = mpsc::channel();
let id = FileThreadId(self.file_id_counter);
FileThread::start(id,
path,
self.file_sender.clone(),
receiver);
self.file_threads.insert(id, sender);
self.file_id_counter += 1;
}
}
|
file_id_counter: usize,
}
|
random_line_split
|
core_thread.rs
|
use modulo_traits::core_msg::ToCoreThreadMsg;
use modulo_traits::file_msg::{FileThreadId, ToFileThreadMsg};
use file::file_thread::FileThread;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::mpsc::{self, Sender, Receiver};
use std::thread::{self, JoinHandle};
pub struct Core {
file_threads: HashMap<FileThreadId, Sender<ToFileThreadMsg>>,
file_receiver: Receiver<ToCoreThreadMsg>,
file_sender: Sender<ToCoreThreadMsg>,
file_id_counter: usize,
}
impl Core {
pub fn start() -> (Sender<ToCoreThreadMsg>, JoinHandle<()>) {
let (sender, receiver) = mpsc::channel();
let file_sender = sender.clone();
let handle = thread::spawn(move || {
let mut core = Core {
file_threads: HashMap::new(),
file_receiver: receiver,
file_sender: file_sender,
file_id_counter: 0,
};
core.run();
});
(sender, handle)
}
/// Runs the event loop for the `CoreThread`
pub fn run(&mut self) {
while let Ok(msg) = self.file_receiver.recv() {
match msg {
ToCoreThreadMsg::FileThreadMsg(id, msg) => {
let file_thread = match self.file_threads.get(&id) {
Some(file_thread) => file_thread,
None => return warn!("Received message for closed file thread: {:?}", id),
};
let _ = file_thread.send(msg);
},
ToCoreThreadMsg::SpawnFileThread(path) =>
self.handle_spawn_file_thread(path),
}
}
}
pub fn handle_spawn_file_thread(&mut self, path: Option<PathBuf>)
|
}
|
{
let (sender, receiver) = mpsc::channel();
let id = FileThreadId(self.file_id_counter);
FileThread::start(id,
path,
self.file_sender.clone(),
receiver);
self.file_threads.insert(id, sender);
self.file_id_counter += 1;
}
|
identifier_body
|
core_thread.rs
|
use modulo_traits::core_msg::ToCoreThreadMsg;
use modulo_traits::file_msg::{FileThreadId, ToFileThreadMsg};
use file::file_thread::FileThread;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::mpsc::{self, Sender, Receiver};
use std::thread::{self, JoinHandle};
pub struct
|
{
file_threads: HashMap<FileThreadId, Sender<ToFileThreadMsg>>,
file_receiver: Receiver<ToCoreThreadMsg>,
file_sender: Sender<ToCoreThreadMsg>,
file_id_counter: usize,
}
impl Core {
pub fn start() -> (Sender<ToCoreThreadMsg>, JoinHandle<()>) {
let (sender, receiver) = mpsc::channel();
let file_sender = sender.clone();
let handle = thread::spawn(move || {
let mut core = Core {
file_threads: HashMap::new(),
file_receiver: receiver,
file_sender: file_sender,
file_id_counter: 0,
};
core.run();
});
(sender, handle)
}
/// Runs the event loop for the `CoreThread`
pub fn run(&mut self) {
while let Ok(msg) = self.file_receiver.recv() {
match msg {
ToCoreThreadMsg::FileThreadMsg(id, msg) => {
let file_thread = match self.file_threads.get(&id) {
Some(file_thread) => file_thread,
None => return warn!("Received message for closed file thread: {:?}", id),
};
let _ = file_thread.send(msg);
},
ToCoreThreadMsg::SpawnFileThread(path) =>
self.handle_spawn_file_thread(path),
}
}
}
pub fn handle_spawn_file_thread(&mut self, path: Option<PathBuf>) {
let (sender, receiver) = mpsc::channel();
let id = FileThreadId(self.file_id_counter);
FileThread::start(id,
path,
self.file_sender.clone(),
receiver);
self.file_threads.insert(id, sender);
self.file_id_counter += 1;
}
}
|
Core
|
identifier_name
|
authz_error.rs
|
use url::Url;
#[derive(Clone, Copy, Debug, PartialEq, Deserialize)]
pub enum AuthzErrorCode {
#[serde(rename="invalid_request")]
InvalidRequest,
#[serde(rename="unauthorized_client")]
UnauthorizedClient,
#[serde(rename="access_denied")]
AccessDenied,
#[serde(rename="unsupported_response_type")]
UnsupportedResponseType,
#[serde(rename="invalid_scope")]
|
ServerError,
#[serde(rename="temporarily_unavailable")]
TemporarilyUnavailable
}
impl From<AuthzErrorCode> for &'static str {
fn from(e: AuthzErrorCode) -> &'static str {
match e {
AuthzErrorCode::InvalidRequest => "invalid_request",
AuthzErrorCode::UnauthorizedClient => "unauthorized_client",
AuthzErrorCode::AccessDenied => "access_denied",
AuthzErrorCode::UnsupportedResponseType => "unsupported_response_type",
AuthzErrorCode::InvalidScope => "invalid_scope",
AuthzErrorCode::ServerError => "server_error",
AuthzErrorCode::TemporarilyUnavailable => "temporarily_unavailable",
}
}
}
#[derive(Clone, Debug, Deserialize)]
pub struct AuthzError {
pub error: AuthzErrorCode,
pub error_description: Option<String>,
pub error_uri: Option<String>,
pub state: Option<String>,
}
impl AuthzError {
// AuthzErrors are returned via the return_url query string parameters.
// This function adds the error fields to the given url
pub fn put_into_query_string(&self, url: &mut Url) {
url.query_pairs_mut()
.append_pair("error", <&'static str as From<AuthzErrorCode>>::from(self.error));
if self.error_description.is_some() {
url.query_pairs_mut()
.append_pair("error_description", self.error_description.as_ref().unwrap());
}
if self.error_uri.is_some() {
url.query_pairs_mut()
.append_pair("error_uri", self.error_uri.as_ref().unwrap());
}
if self.state.is_some() {
url.query_pairs_mut()
.append_pair("state", self.state.as_ref().unwrap());
}
}
}
|
InvalidScope,
#[serde(rename="server_error")]
|
random_line_split
|
authz_error.rs
|
use url::Url;
#[derive(Clone, Copy, Debug, PartialEq, Deserialize)]
pub enum AuthzErrorCode {
#[serde(rename="invalid_request")]
InvalidRequest,
#[serde(rename="unauthorized_client")]
UnauthorizedClient,
#[serde(rename="access_denied")]
AccessDenied,
#[serde(rename="unsupported_response_type")]
UnsupportedResponseType,
#[serde(rename="invalid_scope")]
InvalidScope,
#[serde(rename="server_error")]
ServerError,
#[serde(rename="temporarily_unavailable")]
TemporarilyUnavailable
}
impl From<AuthzErrorCode> for &'static str {
fn from(e: AuthzErrorCode) -> &'static str {
match e {
AuthzErrorCode::InvalidRequest => "invalid_request",
AuthzErrorCode::UnauthorizedClient => "unauthorized_client",
AuthzErrorCode::AccessDenied => "access_denied",
AuthzErrorCode::UnsupportedResponseType => "unsupported_response_type",
AuthzErrorCode::InvalidScope => "invalid_scope",
AuthzErrorCode::ServerError => "server_error",
AuthzErrorCode::TemporarilyUnavailable => "temporarily_unavailable",
}
}
}
#[derive(Clone, Debug, Deserialize)]
pub struct AuthzError {
pub error: AuthzErrorCode,
pub error_description: Option<String>,
pub error_uri: Option<String>,
pub state: Option<String>,
}
impl AuthzError {
// AuthzErrors are returned via the return_url query string parameters.
// This function adds the error fields to the given url
pub fn put_into_query_string(&self, url: &mut Url)
|
}
|
{
url.query_pairs_mut()
.append_pair("error", <&'static str as From<AuthzErrorCode>>::from(self.error));
if self.error_description.is_some() {
url.query_pairs_mut()
.append_pair("error_description", self.error_description.as_ref().unwrap());
}
if self.error_uri.is_some() {
url.query_pairs_mut()
.append_pair("error_uri", self.error_uri.as_ref().unwrap());
}
if self.state.is_some() {
url.query_pairs_mut()
.append_pair("state", self.state.as_ref().unwrap());
}
}
|
identifier_body
|
authz_error.rs
|
use url::Url;
#[derive(Clone, Copy, Debug, PartialEq, Deserialize)]
pub enum AuthzErrorCode {
#[serde(rename="invalid_request")]
InvalidRequest,
#[serde(rename="unauthorized_client")]
UnauthorizedClient,
#[serde(rename="access_denied")]
AccessDenied,
#[serde(rename="unsupported_response_type")]
UnsupportedResponseType,
#[serde(rename="invalid_scope")]
InvalidScope,
#[serde(rename="server_error")]
ServerError,
#[serde(rename="temporarily_unavailable")]
TemporarilyUnavailable
}
impl From<AuthzErrorCode> for &'static str {
fn from(e: AuthzErrorCode) -> &'static str {
match e {
AuthzErrorCode::InvalidRequest => "invalid_request",
AuthzErrorCode::UnauthorizedClient => "unauthorized_client",
AuthzErrorCode::AccessDenied => "access_denied",
AuthzErrorCode::UnsupportedResponseType => "unsupported_response_type",
AuthzErrorCode::InvalidScope => "invalid_scope",
AuthzErrorCode::ServerError => "server_error",
AuthzErrorCode::TemporarilyUnavailable => "temporarily_unavailable",
}
}
}
#[derive(Clone, Debug, Deserialize)]
pub struct AuthzError {
pub error: AuthzErrorCode,
pub error_description: Option<String>,
pub error_uri: Option<String>,
pub state: Option<String>,
}
impl AuthzError {
// AuthzErrors are returned via the return_url query string parameters.
// This function adds the error fields to the given url
pub fn
|
(&self, url: &mut Url) {
url.query_pairs_mut()
.append_pair("error", <&'static str as From<AuthzErrorCode>>::from(self.error));
if self.error_description.is_some() {
url.query_pairs_mut()
.append_pair("error_description", self.error_description.as_ref().unwrap());
}
if self.error_uri.is_some() {
url.query_pairs_mut()
.append_pair("error_uri", self.error_uri.as_ref().unwrap());
}
if self.state.is_some() {
url.query_pairs_mut()
.append_pair("state", self.state.as_ref().unwrap());
}
}
}
|
put_into_query_string
|
identifier_name
|
error.rs
|
use http;
use hyper::Error as HttpError;
use serde_json::Error as JsonError;
use serde_yaml::Error as YamlError;
use std::error::Error as StdError;
use std::fmt::{Display, Error as FmtError, Formatter};
use std::io::{Error as IOError, ErrorKind};
use url::ParseError;
#[derive(Debug)]
pub enum Error {
Io(IOError),
Http(String),
Ssl(String),
Serialize(String),
Request(String, String),
NotPermitted(String, Vec<String>),
Other(String),
}
impl Error {
pub fn io_timeout() -> Error {
Error::Io(IOError::new(ErrorKind::TimedOut, "timeout"))
}
pub fn is_timeout(&self) -> bool {
match self {
Error::Io(e) => e.kind() == ErrorKind::TimedOut,
Error::Request(code, _) => code == "DEADLINE_EXCEEDED",
_ => false,
}
}
pub fn is_not_found(&self) -> bool {
if let Error::Request(code, _) = self {
if code == "NOT_FOUND" {
return true;
}
}
false
}
pub fn can_retry(&self) -> bool {
match self {
Error::Ssl(_) => false,
Error::Serialize(_) => false,
Error::Request(code, _) => matches!(
code.as_str(),
"SYSTEM_ERROR" | "TOO_MANY_ATTEMPTS" | "DEADLINE_EXCEEDED" | "CANCELLED"
),
Error::NotPermitted(_, _) => false,
Error::Other(_) => false,
_ => true,
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
match self {
Error::Io(e) => e.fmt(f),
Error::Http(e) => write!(f, "{}", e),
Error::Ssl(e) => write!(f, "{}", e),
Error::Serialize(e) => write!(f, "{}", e),
Error::Request(code, message) => write!(f, "request fail[{}]: {}", code, message),
Error::NotPermitted(message, _) => write!(f, "not permitted: {}", message),
Error::Other(e) => write!(f, "{}", e),
}
}
}
impl StdError for Error {}
impl From<IOError> for Error {
fn from(err: IOError) -> Error {
Error::Io(err)
}
}
impl From<HttpError> for Error {
fn from(err: HttpError) -> Error {
Error::Http(format!("{}", err))
}
}
impl From<JsonError> for Error {
fn from(err: JsonError) -> Error {
Error::Serialize(format!("{}", err))
}
}
impl From<YamlError> for Error {
fn from(err: YamlError) -> Error {
Error::Serialize(format!("{}", err))
}
}
impl From<ParseError> for Error {
fn from(err: ParseError) -> Error {
Error::Other(format!("parse url fail: {}", err))
}
}
impl From<String> for Error {
fn from(msg: String) -> Error {
Error::Other(msg)
}
}
impl<'a> From<&'a str> for Error {
fn from(msg: &'a str) -> Error
|
}
impl From<http::Error> for Error {
fn from(e: http::Error) -> Error {
Error::Http(format!("{}", e))
}
}
|
{
Error::Other(msg.to_owned())
}
|
identifier_body
|
error.rs
|
use http;
use hyper::Error as HttpError;
use serde_json::Error as JsonError;
use serde_yaml::Error as YamlError;
use std::error::Error as StdError;
use std::fmt::{Display, Error as FmtError, Formatter};
use std::io::{Error as IOError, ErrorKind};
use url::ParseError;
#[derive(Debug)]
pub enum Error {
Io(IOError),
Http(String),
Ssl(String),
Serialize(String),
Request(String, String),
NotPermitted(String, Vec<String>),
Other(String),
}
impl Error {
pub fn io_timeout() -> Error {
Error::Io(IOError::new(ErrorKind::TimedOut, "timeout"))
}
pub fn is_timeout(&self) -> bool {
match self {
Error::Io(e) => e.kind() == ErrorKind::TimedOut,
Error::Request(code, _) => code == "DEADLINE_EXCEEDED",
_ => false,
}
}
pub fn is_not_found(&self) -> bool {
if let Error::Request(code, _) = self {
if code == "NOT_FOUND" {
return true;
}
}
false
}
pub fn can_retry(&self) -> bool {
match self {
Error::Ssl(_) => false,
Error::Serialize(_) => false,
Error::Request(code, _) => matches!(
code.as_str(),
"SYSTEM_ERROR" | "TOO_MANY_ATTEMPTS" | "DEADLINE_EXCEEDED" | "CANCELLED"
),
Error::NotPermitted(_, _) => false,
Error::Other(_) => false,
_ => true,
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
match self {
Error::Io(e) => e.fmt(f),
Error::Http(e) => write!(f, "{}", e),
Error::Ssl(e) => write!(f, "{}", e),
Error::Serialize(e) => write!(f, "{}", e),
Error::Request(code, message) => write!(f, "request fail[{}]: {}", code, message),
Error::NotPermitted(message, _) => write!(f, "not permitted: {}", message),
Error::Other(e) => write!(f, "{}", e),
}
}
}
impl StdError for Error {}
impl From<IOError> for Error {
fn from(err: IOError) -> Error {
Error::Io(err)
}
}
impl From<HttpError> for Error {
fn from(err: HttpError) -> Error {
Error::Http(format!("{}", err))
}
}
impl From<JsonError> for Error {
fn
|
(err: JsonError) -> Error {
Error::Serialize(format!("{}", err))
}
}
impl From<YamlError> for Error {
fn from(err: YamlError) -> Error {
Error::Serialize(format!("{}", err))
}
}
impl From<ParseError> for Error {
fn from(err: ParseError) -> Error {
Error::Other(format!("parse url fail: {}", err))
}
}
impl From<String> for Error {
fn from(msg: String) -> Error {
Error::Other(msg)
}
}
impl<'a> From<&'a str> for Error {
fn from(msg: &'a str) -> Error {
Error::Other(msg.to_owned())
}
}
impl From<http::Error> for Error {
fn from(e: http::Error) -> Error {
Error::Http(format!("{}", e))
}
}
|
from
|
identifier_name
|
error.rs
|
use http;
use hyper::Error as HttpError;
use serde_json::Error as JsonError;
use serde_yaml::Error as YamlError;
use std::error::Error as StdError;
use std::fmt::{Display, Error as FmtError, Formatter};
use std::io::{Error as IOError, ErrorKind};
use url::ParseError;
#[derive(Debug)]
pub enum Error {
Io(IOError),
Http(String),
Ssl(String),
Serialize(String),
Request(String, String),
NotPermitted(String, Vec<String>),
Other(String),
}
impl Error {
pub fn io_timeout() -> Error {
Error::Io(IOError::new(ErrorKind::TimedOut, "timeout"))
}
pub fn is_timeout(&self) -> bool {
match self {
Error::Io(e) => e.kind() == ErrorKind::TimedOut,
Error::Request(code, _) => code == "DEADLINE_EXCEEDED",
_ => false,
}
}
pub fn is_not_found(&self) -> bool {
if let Error::Request(code, _) = self {
if code == "NOT_FOUND" {
return true;
}
|
pub fn can_retry(&self) -> bool {
match self {
Error::Ssl(_) => false,
Error::Serialize(_) => false,
Error::Request(code, _) => matches!(
code.as_str(),
"SYSTEM_ERROR" | "TOO_MANY_ATTEMPTS" | "DEADLINE_EXCEEDED" | "CANCELLED"
),
Error::NotPermitted(_, _) => false,
Error::Other(_) => false,
_ => true,
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
match self {
Error::Io(e) => e.fmt(f),
Error::Http(e) => write!(f, "{}", e),
Error::Ssl(e) => write!(f, "{}", e),
Error::Serialize(e) => write!(f, "{}", e),
Error::Request(code, message) => write!(f, "request fail[{}]: {}", code, message),
Error::NotPermitted(message, _) => write!(f, "not permitted: {}", message),
Error::Other(e) => write!(f, "{}", e),
}
}
}
impl StdError for Error {}
impl From<IOError> for Error {
fn from(err: IOError) -> Error {
Error::Io(err)
}
}
impl From<HttpError> for Error {
fn from(err: HttpError) -> Error {
Error::Http(format!("{}", err))
}
}
impl From<JsonError> for Error {
fn from(err: JsonError) -> Error {
Error::Serialize(format!("{}", err))
}
}
impl From<YamlError> for Error {
fn from(err: YamlError) -> Error {
Error::Serialize(format!("{}", err))
}
}
impl From<ParseError> for Error {
fn from(err: ParseError) -> Error {
Error::Other(format!("parse url fail: {}", err))
}
}
impl From<String> for Error {
fn from(msg: String) -> Error {
Error::Other(msg)
}
}
impl<'a> From<&'a str> for Error {
fn from(msg: &'a str) -> Error {
Error::Other(msg.to_owned())
}
}
impl From<http::Error> for Error {
fn from(e: http::Error) -> Error {
Error::Http(format!("{}", e))
}
}
|
}
false
}
|
random_line_split
|
typestate-cfg-nesting.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.
#![allow(dead_assignment)]
#![allow(unused_variable)]
fn f()
|
pub fn main() {
let x = 10;
let mut y = 11;
if true { while false { y = x; } } else { }
}
|
{
let x = 10; let mut y = 11;
if true { match x { _ => { y = x; } } } else { }
}
|
identifier_body
|
typestate-cfg-nesting.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.
#![allow(dead_assignment)]
#![allow(unused_variable)]
fn f() {
let x = 10; let mut y = 11;
if true { match x { _ => { y = x; } } } else { }
}
pub fn
|
() {
let x = 10;
let mut y = 11;
if true { while false { y = x; } } else { }
}
|
main
|
identifier_name
|
typestate-cfg-nesting.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.
#![allow(dead_assignment)]
#![allow(unused_variable)]
fn f() {
let x = 10; let mut y = 11;
if true { match x { _ => { y = x; } } } else
|
}
pub fn main() {
let x = 10;
let mut y = 11;
if true { while false { y = x; } } else { }
}
|
{ }
|
conditional_block
|
typestate-cfg-nesting.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.
|
fn f() {
let x = 10; let mut y = 11;
if true { match x { _ => { y = x; } } } else { }
}
pub fn main() {
let x = 10;
let mut y = 11;
if true { while false { y = x; } } else { }
}
|
#![allow(dead_assignment)]
#![allow(unused_variable)]
|
random_line_split
|
lib.rs
|
#![allow(non_upper_case_globals)]
// External crates
#[macro_use]
extern crate clap;
extern crate num_cpus;
extern crate num;
extern crate time;
// External modules
use clap::App;
use num::complex::Complex64;
use time::{precise_time_ns};
// Rust modules
use std::fs::File;
use std::io::prelude::Write;
use std::io::Result;
use std::io::BufWriter;
use std::fs::OpenOptions;
use std::path::Path;
use std::fs;
// Configuration file, reflects command line options
#[derive(Copy, Clone)]
pub struct
|
{
pub re1: f64,
pub re2: f64,
pub img1: f64,
pub img2: f64,
pub x_step: f64,
pub y_step: f64,
pub max_iter: u32,
pub img_size: u32,
pub write_metadata: bool,
pub no_ppm: bool,
pub num_threads: u32,
pub num_of_runs: u32
}
include!(concat!(env!("OUT_DIR"), "/compiler_version.rs"));
// Parse command line options via clap and returns the responding configuration
pub fn parse_arguments() -> MandelConfig {
let matches = App::new("mandel_rust")
.version("0.3")
.author("Willi Kappler <[email protected]>")
.about("Simple mandelbrot written in pure rust")
.args_from_usage(
"--re1=[REAL1] 'left real part (default: -2.0)'
--re2=[REAL2] 'right real part (default: 1.0)'
--img1=[IMAGINARY1] 'lower part (default: -1.50)'
--img2=[IMAGINARY2] 'upper part (default: 1.50)'
--write_metadata 'write metadata like run time into the ppm file (default: off)'
--no_ppm 'disable creation of the ppm file, just run the calculation (default: off)'
--bench 'use all available CPUs (default: off), will change in the future'
--max_iter=[MAX_ITER]'maximum number of iterations (default: 4096)'
--img_size=[IMAGE_SIZE]'size of image in pixel (square, default: 2048, must be a power of two)'
--num_of_runs=[NUM_OF_RUNS] 'number of repetitive runs (default: 2)'
--num_threads=[NUMBER_OF_THREADS] 'number of threads to use (default: 2)'")
.get_matches();
let re1 = value_t!(matches.value_of("REAL1"), f64).unwrap_or(-2.0);
let re2 = value_t!(matches.value_of("REAL2"), f64).unwrap_or(1.0);
let img1 = value_t!(matches.value_of("IMAGINARY1"), f64).unwrap_or(-1.5);
let img2 = value_t!(matches.value_of("IMAGINARY2"), f64).unwrap_or(1.5);
let metadata = matches.is_present("write_metadata");
let bench = matches.is_present("bench");
let no_ppm = matches.is_present("no_ppm");
let max_iter = value_t!(matches.value_of("MAX_ITER"), u32).unwrap_or(4096);
let img_size = value_t!(matches.value_of("IMAGE_SIZE"), u32).unwrap_or(2048);
let num_of_runs = value_t!(matches.value_of("NUM_OF_RUNS"), u32).unwrap_or(2);
let num_threads = if bench { num_cpus::get() as u32 } else {
value_t!(matches.value_of("NUMBER_OF_THREADS"), u32).unwrap_or(2) };
assert!(re1 < re2);
assert!(img1 < img2);
assert!(max_iter > 0);
assert!(img_size > 0);
assert!(num_threads > 0);
println!("Configuration: re1: {:.2}, re2: {:.2}, img1: {:.2}, img2: {:.2}, max_iter: {}, img_size: {}, num_threads: {}",
re1, re2, img1, img2, max_iter, img_size, num_threads);
let x_step = (re2 - re1) / (img_size as f64);
let y_step = (img2 - img1) / (img_size as f64);
MandelConfig{
re1: re1,
re2: re2,
img1: img1,
img2: img2,
x_step: x_step,
y_step: y_step,
max_iter: max_iter,
img_size: img_size,
write_metadata: metadata,
no_ppm: no_ppm,
num_threads: num_threads,
num_of_runs: num_of_runs
}
}
// The inner iteration loop of the mandelbrot calculation
// See https://en.wikipedia.org/wiki/Mandelbrot_set
pub fn mandel_iter(max_iter: u32, c: Complex64) -> u32 {
let mut z: Complex64 = c;
let mut iter = 0;
while (z.norm_sqr() <= 4.0) && (iter < max_iter) {
z = c + (z * z);
iter = iter + 1;
}
iter
}
// Write calculated mandelbrot set as PPM image.
// Add run time information as comment.
fn write_image(file_name: &str, mandel_config: &MandelConfig, time_in_ms: f64, image: &[u32]) -> Result<()> {
let mut buffer = BufWriter::new(try!(File::create(file_name)));
try!(buffer.write(b"P3\n"));
try!(write!(buffer, "# mandelbrot, max_iter: {}\n", mandel_config.max_iter));
if mandel_config.write_metadata {
// TODO: add more meta data: date and time, method,...
try!(write!(buffer, "# computation time: {} ms\n", time_in_ms));
}
try!(write!(buffer, "{0} {0}\n", mandel_config.img_size));
try!(buffer.write(b"255\n"));
let mut img_value: u32;
for y in 0..mandel_config.img_size {
for x in 0..mandel_config.img_size {
img_value = image[((y * mandel_config.img_size) + x) as usize];
if img_value == mandel_config.max_iter {
try!(buffer.write(b"0 0 0 "));
} else {
try!(write!(buffer, "255 {} 0 ", (img_value % 16) * 16));
}
}
try!(buffer.write(b"\n"));
}
Ok(())
}
fn write_benchmark_result(method: &str, num_threads: u32,
time_in_ms: f64, min_time: f64, max_time: f64) -> Result<()> {
// Check if output folder "plot" is available:
if!Path::new("plot").exists() {
// If not, create it!
println!("Folder 'plot' does not exist, creating it...");
try!(fs::create_dir("plot"));
}
let mut buffer = BufWriter::new(try!(
OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(format!("plot{}{}.txt", std::path::MAIN_SEPARATOR, method))));
try!(write!(buffer, "{} {} {} {}\n", num_threads, time_in_ms, min_time, max_time));
Ok(())
}
// Prepares and runs one version of the mandelbrot set calculation.
pub fn do_run(method: &str, mandel_func: &Fn(&MandelConfig, &mut [u32]) -> (),
mandel_config: &MandelConfig, image: &mut [u32], time_now: &str) {
let mut repetitive_times = Vec::new();
let mut min_time = std::f64::MAX;
let mut max_time = 0.0;
for _ in 0..mandel_config.num_of_runs {
let start_time = precise_time_ns();
mandel_func(mandel_config, image);
let end_time = precise_time_ns();
let total_time_in_ms = ((end_time - start_time) as f64) / (1000.0 * 1000.0);
if total_time_in_ms > max_time {
max_time = total_time_in_ms;
}
if total_time_in_ms < min_time {
min_time = total_time_in_ms;
}
repetitive_times.push(total_time_in_ms);
}
let mean_time = repetitive_times.iter().fold(0.0, |sum, t| sum + t) /
(mandel_config.num_of_runs as f64);
println!("Time taken for this run ({}): {:.5} ms", method, mean_time);
write_benchmark_result(&method, mandel_config.num_threads, mean_time,
min_time, max_time).expect("I/O error while writing benchmark results");
if!mandel_config.no_ppm {
let file_name = format!("{}_{}.ppm", method, &time_now);
write_image(&file_name, &mandel_config, mean_time, &image).expect(
&format!("I/O error while writing image: '{}'", file_name));
}
}
|
MandelConfig
|
identifier_name
|
lib.rs
|
#![allow(non_upper_case_globals)]
// External crates
#[macro_use]
extern crate clap;
extern crate num_cpus;
extern crate num;
extern crate time;
// External modules
use clap::App;
use num::complex::Complex64;
use time::{precise_time_ns};
// Rust modules
use std::fs::File;
use std::io::prelude::Write;
use std::io::Result;
use std::io::BufWriter;
use std::fs::OpenOptions;
use std::path::Path;
use std::fs;
// Configuration file, reflects command line options
#[derive(Copy, Clone)]
pub struct MandelConfig {
pub re1: f64,
pub re2: f64,
pub img1: f64,
pub img2: f64,
pub x_step: f64,
pub y_step: f64,
pub max_iter: u32,
pub img_size: u32,
pub write_metadata: bool,
pub no_ppm: bool,
pub num_threads: u32,
pub num_of_runs: u32
}
include!(concat!(env!("OUT_DIR"), "/compiler_version.rs"));
// Parse command line options via clap and returns the responding configuration
pub fn parse_arguments() -> MandelConfig {
let matches = App::new("mandel_rust")
.version("0.3")
.author("Willi Kappler <[email protected]>")
.about("Simple mandelbrot written in pure rust")
.args_from_usage(
"--re1=[REAL1] 'left real part (default: -2.0)'
|
--write_metadata 'write metadata like run time into the ppm file (default: off)'
--no_ppm 'disable creation of the ppm file, just run the calculation (default: off)'
--bench 'use all available CPUs (default: off), will change in the future'
--max_iter=[MAX_ITER]'maximum number of iterations (default: 4096)'
--img_size=[IMAGE_SIZE]'size of image in pixel (square, default: 2048, must be a power of two)'
--num_of_runs=[NUM_OF_RUNS] 'number of repetitive runs (default: 2)'
--num_threads=[NUMBER_OF_THREADS] 'number of threads to use (default: 2)'")
.get_matches();
let re1 = value_t!(matches.value_of("REAL1"), f64).unwrap_or(-2.0);
let re2 = value_t!(matches.value_of("REAL2"), f64).unwrap_or(1.0);
let img1 = value_t!(matches.value_of("IMAGINARY1"), f64).unwrap_or(-1.5);
let img2 = value_t!(matches.value_of("IMAGINARY2"), f64).unwrap_or(1.5);
let metadata = matches.is_present("write_metadata");
let bench = matches.is_present("bench");
let no_ppm = matches.is_present("no_ppm");
let max_iter = value_t!(matches.value_of("MAX_ITER"), u32).unwrap_or(4096);
let img_size = value_t!(matches.value_of("IMAGE_SIZE"), u32).unwrap_or(2048);
let num_of_runs = value_t!(matches.value_of("NUM_OF_RUNS"), u32).unwrap_or(2);
let num_threads = if bench { num_cpus::get() as u32 } else {
value_t!(matches.value_of("NUMBER_OF_THREADS"), u32).unwrap_or(2) };
assert!(re1 < re2);
assert!(img1 < img2);
assert!(max_iter > 0);
assert!(img_size > 0);
assert!(num_threads > 0);
println!("Configuration: re1: {:.2}, re2: {:.2}, img1: {:.2}, img2: {:.2}, max_iter: {}, img_size: {}, num_threads: {}",
re1, re2, img1, img2, max_iter, img_size, num_threads);
let x_step = (re2 - re1) / (img_size as f64);
let y_step = (img2 - img1) / (img_size as f64);
MandelConfig{
re1: re1,
re2: re2,
img1: img1,
img2: img2,
x_step: x_step,
y_step: y_step,
max_iter: max_iter,
img_size: img_size,
write_metadata: metadata,
no_ppm: no_ppm,
num_threads: num_threads,
num_of_runs: num_of_runs
}
}
// The inner iteration loop of the mandelbrot calculation
// See https://en.wikipedia.org/wiki/Mandelbrot_set
pub fn mandel_iter(max_iter: u32, c: Complex64) -> u32 {
let mut z: Complex64 = c;
let mut iter = 0;
while (z.norm_sqr() <= 4.0) && (iter < max_iter) {
z = c + (z * z);
iter = iter + 1;
}
iter
}
// Write calculated mandelbrot set as PPM image.
// Add run time information as comment.
fn write_image(file_name: &str, mandel_config: &MandelConfig, time_in_ms: f64, image: &[u32]) -> Result<()> {
let mut buffer = BufWriter::new(try!(File::create(file_name)));
try!(buffer.write(b"P3\n"));
try!(write!(buffer, "# mandelbrot, max_iter: {}\n", mandel_config.max_iter));
if mandel_config.write_metadata {
// TODO: add more meta data: date and time, method,...
try!(write!(buffer, "# computation time: {} ms\n", time_in_ms));
}
try!(write!(buffer, "{0} {0}\n", mandel_config.img_size));
try!(buffer.write(b"255\n"));
let mut img_value: u32;
for y in 0..mandel_config.img_size {
for x in 0..mandel_config.img_size {
img_value = image[((y * mandel_config.img_size) + x) as usize];
if img_value == mandel_config.max_iter {
try!(buffer.write(b"0 0 0 "));
} else {
try!(write!(buffer, "255 {} 0 ", (img_value % 16) * 16));
}
}
try!(buffer.write(b"\n"));
}
Ok(())
}
fn write_benchmark_result(method: &str, num_threads: u32,
time_in_ms: f64, min_time: f64, max_time: f64) -> Result<()> {
// Check if output folder "plot" is available:
if!Path::new("plot").exists() {
// If not, create it!
println!("Folder 'plot' does not exist, creating it...");
try!(fs::create_dir("plot"));
}
let mut buffer = BufWriter::new(try!(
OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(format!("plot{}{}.txt", std::path::MAIN_SEPARATOR, method))));
try!(write!(buffer, "{} {} {} {}\n", num_threads, time_in_ms, min_time, max_time));
Ok(())
}
// Prepares and runs one version of the mandelbrot set calculation.
pub fn do_run(method: &str, mandel_func: &Fn(&MandelConfig, &mut [u32]) -> (),
mandel_config: &MandelConfig, image: &mut [u32], time_now: &str) {
let mut repetitive_times = Vec::new();
let mut min_time = std::f64::MAX;
let mut max_time = 0.0;
for _ in 0..mandel_config.num_of_runs {
let start_time = precise_time_ns();
mandel_func(mandel_config, image);
let end_time = precise_time_ns();
let total_time_in_ms = ((end_time - start_time) as f64) / (1000.0 * 1000.0);
if total_time_in_ms > max_time {
max_time = total_time_in_ms;
}
if total_time_in_ms < min_time {
min_time = total_time_in_ms;
}
repetitive_times.push(total_time_in_ms);
}
let mean_time = repetitive_times.iter().fold(0.0, |sum, t| sum + t) /
(mandel_config.num_of_runs as f64);
println!("Time taken for this run ({}): {:.5} ms", method, mean_time);
write_benchmark_result(&method, mandel_config.num_threads, mean_time,
min_time, max_time).expect("I/O error while writing benchmark results");
if!mandel_config.no_ppm {
let file_name = format!("{}_{}.ppm", method, &time_now);
write_image(&file_name, &mandel_config, mean_time, &image).expect(
&format!("I/O error while writing image: '{}'", file_name));
}
}
|
--re2=[REAL2] 'right real part (default: 1.0)'
--img1=[IMAGINARY1] 'lower part (default: -1.50)'
--img2=[IMAGINARY2] 'upper part (default: 1.50)'
|
random_line_split
|
lib.rs
|
#![allow(non_upper_case_globals)]
// External crates
#[macro_use]
extern crate clap;
extern crate num_cpus;
extern crate num;
extern crate time;
// External modules
use clap::App;
use num::complex::Complex64;
use time::{precise_time_ns};
// Rust modules
use std::fs::File;
use std::io::prelude::Write;
use std::io::Result;
use std::io::BufWriter;
use std::fs::OpenOptions;
use std::path::Path;
use std::fs;
// Configuration file, reflects command line options
#[derive(Copy, Clone)]
pub struct MandelConfig {
pub re1: f64,
pub re2: f64,
pub img1: f64,
pub img2: f64,
pub x_step: f64,
pub y_step: f64,
pub max_iter: u32,
pub img_size: u32,
pub write_metadata: bool,
pub no_ppm: bool,
pub num_threads: u32,
pub num_of_runs: u32
}
include!(concat!(env!("OUT_DIR"), "/compiler_version.rs"));
// Parse command line options via clap and returns the responding configuration
pub fn parse_arguments() -> MandelConfig {
let matches = App::new("mandel_rust")
.version("0.3")
.author("Willi Kappler <[email protected]>")
.about("Simple mandelbrot written in pure rust")
.args_from_usage(
"--re1=[REAL1] 'left real part (default: -2.0)'
--re2=[REAL2] 'right real part (default: 1.0)'
--img1=[IMAGINARY1] 'lower part (default: -1.50)'
--img2=[IMAGINARY2] 'upper part (default: 1.50)'
--write_metadata 'write metadata like run time into the ppm file (default: off)'
--no_ppm 'disable creation of the ppm file, just run the calculation (default: off)'
--bench 'use all available CPUs (default: off), will change in the future'
--max_iter=[MAX_ITER]'maximum number of iterations (default: 4096)'
--img_size=[IMAGE_SIZE]'size of image in pixel (square, default: 2048, must be a power of two)'
--num_of_runs=[NUM_OF_RUNS] 'number of repetitive runs (default: 2)'
--num_threads=[NUMBER_OF_THREADS] 'number of threads to use (default: 2)'")
.get_matches();
let re1 = value_t!(matches.value_of("REAL1"), f64).unwrap_or(-2.0);
let re2 = value_t!(matches.value_of("REAL2"), f64).unwrap_or(1.0);
let img1 = value_t!(matches.value_of("IMAGINARY1"), f64).unwrap_or(-1.5);
let img2 = value_t!(matches.value_of("IMAGINARY2"), f64).unwrap_or(1.5);
let metadata = matches.is_present("write_metadata");
let bench = matches.is_present("bench");
let no_ppm = matches.is_present("no_ppm");
let max_iter = value_t!(matches.value_of("MAX_ITER"), u32).unwrap_or(4096);
let img_size = value_t!(matches.value_of("IMAGE_SIZE"), u32).unwrap_or(2048);
let num_of_runs = value_t!(matches.value_of("NUM_OF_RUNS"), u32).unwrap_or(2);
let num_threads = if bench { num_cpus::get() as u32 } else {
value_t!(matches.value_of("NUMBER_OF_THREADS"), u32).unwrap_or(2) };
assert!(re1 < re2);
assert!(img1 < img2);
assert!(max_iter > 0);
assert!(img_size > 0);
assert!(num_threads > 0);
println!("Configuration: re1: {:.2}, re2: {:.2}, img1: {:.2}, img2: {:.2}, max_iter: {}, img_size: {}, num_threads: {}",
re1, re2, img1, img2, max_iter, img_size, num_threads);
let x_step = (re2 - re1) / (img_size as f64);
let y_step = (img2 - img1) / (img_size as f64);
MandelConfig{
re1: re1,
re2: re2,
img1: img1,
img2: img2,
x_step: x_step,
y_step: y_step,
max_iter: max_iter,
img_size: img_size,
write_metadata: metadata,
no_ppm: no_ppm,
num_threads: num_threads,
num_of_runs: num_of_runs
}
}
// The inner iteration loop of the mandelbrot calculation
// See https://en.wikipedia.org/wiki/Mandelbrot_set
pub fn mandel_iter(max_iter: u32, c: Complex64) -> u32 {
let mut z: Complex64 = c;
let mut iter = 0;
while (z.norm_sqr() <= 4.0) && (iter < max_iter) {
z = c + (z * z);
iter = iter + 1;
}
iter
}
// Write calculated mandelbrot set as PPM image.
// Add run time information as comment.
fn write_image(file_name: &str, mandel_config: &MandelConfig, time_in_ms: f64, image: &[u32]) -> Result<()> {
let mut buffer = BufWriter::new(try!(File::create(file_name)));
try!(buffer.write(b"P3\n"));
try!(write!(buffer, "# mandelbrot, max_iter: {}\n", mandel_config.max_iter));
if mandel_config.write_metadata
|
try!(write!(buffer, "{0} {0}\n", mandel_config.img_size));
try!(buffer.write(b"255\n"));
let mut img_value: u32;
for y in 0..mandel_config.img_size {
for x in 0..mandel_config.img_size {
img_value = image[((y * mandel_config.img_size) + x) as usize];
if img_value == mandel_config.max_iter {
try!(buffer.write(b"0 0 0 "));
} else {
try!(write!(buffer, "255 {} 0 ", (img_value % 16) * 16));
}
}
try!(buffer.write(b"\n"));
}
Ok(())
}
fn write_benchmark_result(method: &str, num_threads: u32,
time_in_ms: f64, min_time: f64, max_time: f64) -> Result<()> {
// Check if output folder "plot" is available:
if!Path::new("plot").exists() {
// If not, create it!
println!("Folder 'plot' does not exist, creating it...");
try!(fs::create_dir("plot"));
}
let mut buffer = BufWriter::new(try!(
OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(format!("plot{}{}.txt", std::path::MAIN_SEPARATOR, method))));
try!(write!(buffer, "{} {} {} {}\n", num_threads, time_in_ms, min_time, max_time));
Ok(())
}
// Prepares and runs one version of the mandelbrot set calculation.
pub fn do_run(method: &str, mandel_func: &Fn(&MandelConfig, &mut [u32]) -> (),
mandel_config: &MandelConfig, image: &mut [u32], time_now: &str) {
let mut repetitive_times = Vec::new();
let mut min_time = std::f64::MAX;
let mut max_time = 0.0;
for _ in 0..mandel_config.num_of_runs {
let start_time = precise_time_ns();
mandel_func(mandel_config, image);
let end_time = precise_time_ns();
let total_time_in_ms = ((end_time - start_time) as f64) / (1000.0 * 1000.0);
if total_time_in_ms > max_time {
max_time = total_time_in_ms;
}
if total_time_in_ms < min_time {
min_time = total_time_in_ms;
}
repetitive_times.push(total_time_in_ms);
}
let mean_time = repetitive_times.iter().fold(0.0, |sum, t| sum + t) /
(mandel_config.num_of_runs as f64);
println!("Time taken for this run ({}): {:.5} ms", method, mean_time);
write_benchmark_result(&method, mandel_config.num_threads, mean_time,
min_time, max_time).expect("I/O error while writing benchmark results");
if!mandel_config.no_ppm {
let file_name = format!("{}_{}.ppm", method, &time_now);
write_image(&file_name, &mandel_config, mean_time, &image).expect(
&format!("I/O error while writing image: '{}'", file_name));
}
}
|
{
// TODO: add more meta data: date and time, method, ...
try!(write!(buffer, "# computation time: {} ms\n", time_in_ms));
}
|
conditional_block
|
check_tx.rs
|
// Copyright 2020 The Exonum Team
//
// 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 criterion::{BatchSize, Bencher, Criterion};
use rand::{rngs::StdRng, Rng, SeedableRng};
use exonum::{
blockchain::{
config::GenesisConfigBuilder, ApiSender, Blockchain, BlockchainBuilder, ConsensusConfig,
TxCheckCache,
},
crypto::KeyPair,
merkledb::{Snapshot, TemporaryDB},
messages::{AnyTx, Verified},
runtime::{
migrations::{InitMigrationError, MigrationScript},
oneshot::Receiver,
versioning::Version,
ArtifactId, CallInfo, ExecutionContext, ExecutionError, InstanceId, InstanceState, Mailbox,
Runtime, WellKnownRuntime,
},
};
#[derive(Debug)]
struct DummyRuntime;
impl Runtime for DummyRuntime {
fn deploy_artifact(&mut self, _artifact: ArtifactId, _deploy_spec: Vec<u8>) -> Receiver {
Receiver::with_result(Ok(()))
}
fn is_artifact_deployed(&self, _artifact: &ArtifactId) -> bool {
true
}
fn initiate_adding_service(
&self,
_context: ExecutionContext<'_>,
_artifact: &ArtifactId,
_parameters: Vec<u8>,
) -> Result<(), ExecutionError> {
Ok(())
}
fn initiate_resuming_service(
&self,
_context: ExecutionContext<'_>,
_artifact: &ArtifactId,
_parameters: Vec<u8>,
) -> Result<(), ExecutionError> {
Ok(())
}
fn update_service_status(&mut self, _snapshot: &dyn Snapshot, _state: &InstanceState) {
// Do nothing.
}
fn migrate(
&self,
_new_artifact: &ArtifactId,
_data_version: &Version,
) -> Result<Option<MigrationScript>, InitMigrationError> {
unimplemented!()
}
fn execute(
&self,
_context: ExecutionContext<'_>,
_method_id: u32,
_arguments: &[u8],
) -> Result<(), ExecutionError> {
Ok(())
}
fn before_transactions(&self, _context: ExecutionContext<'_>) -> Result<(), ExecutionError> {
Ok(())
}
fn after_transactions(&self, _context: ExecutionContext<'_>) -> Result<(), ExecutionError> {
Ok(())
}
fn after_commit(&mut self, _snapshot: &dyn Snapshot, _mailbox: &mut Mailbox) {
// Do nothing.
}
}
impl WellKnownRuntime for DummyRuntime {
const ID: u32 = 255;
}
fn prepare_blockchain() -> Blockchain {
const SERVICE_ID: InstanceId = 100;
let (consensus_config, keys) = ConsensusConfig::for_tests(1);
let artifact = ArtifactId::new(DummyRuntime::ID, "ts", Version::new(1, 0, 0)).unwrap();
let service = artifact.clone().into_default_instance(SERVICE_ID, "ts");
let blockchain = Blockchain::new(TemporaryDB::new(), keys.service, ApiSender::closed());
let genesis_config = GenesisConfigBuilder::with_consensus_config(consensus_config)
.with_artifact(artifact)
.with_instance(service)
.build();
BlockchainBuilder::new(blockchain)
.with_genesis_config(genesis_config)
.with_runtime(DummyRuntime)
.build()
.immutable_view()
}
fn prepare_transactions(count: usize) -> Vec<Verified<AnyTx>> {
const RNG_SEED: u64 = 123_456_789;
let mut rng = StdRng::seed_from_u64(RNG_SEED);
(0..count)
.map(|_| {
let mut payload = [0_u8; 64];
rng.fill(&mut payload[..]);
let payload = AnyTx::new(CallInfo::new(100, 0), payload.to_vec());
payload.sign_with_keypair(&KeyPair::random())
})
.collect()
}
fn check_tx_no_cache(bencher: &mut Bencher)
|
fn check_tx_cache(bencher: &mut Bencher) {
let blockchain = prepare_blockchain();
let transactions = prepare_transactions(128);
let snapshot = blockchain.snapshot();
bencher.iter_batched(
TxCheckCache::new,
|mut cache| {
assert!(transactions
.iter()
.all(|tx| Blockchain::check_tx_with_cache(&snapshot, tx, &mut cache).is_ok()));
},
BatchSize::SmallInput,
)
}
pub fn bench_check_tx(c: &mut Criterion) {
let mut group = c.benchmark_group("check_tx/single_service");
group
.bench_function("no_cache", check_tx_no_cache)
.bench_function("cache", check_tx_cache);
group.finish();
}
|
{
let blockchain = prepare_blockchain();
let transactions = prepare_transactions(128);
let snapshot = blockchain.snapshot();
bencher.iter(|| {
assert!(transactions
.iter()
.all(|tx| Blockchain::check_tx(&snapshot, tx).is_ok()));
})
}
|
identifier_body
|
check_tx.rs
|
// Copyright 2020 The Exonum Team
//
// 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 criterion::{BatchSize, Bencher, Criterion};
use rand::{rngs::StdRng, Rng, SeedableRng};
use exonum::{
blockchain::{
config::GenesisConfigBuilder, ApiSender, Blockchain, BlockchainBuilder, ConsensusConfig,
TxCheckCache,
},
crypto::KeyPair,
merkledb::{Snapshot, TemporaryDB},
messages::{AnyTx, Verified},
runtime::{
migrations::{InitMigrationError, MigrationScript},
oneshot::Receiver,
versioning::Version,
ArtifactId, CallInfo, ExecutionContext, ExecutionError, InstanceId, InstanceState, Mailbox,
Runtime, WellKnownRuntime,
},
};
#[derive(Debug)]
struct DummyRuntime;
impl Runtime for DummyRuntime {
fn deploy_artifact(&mut self, _artifact: ArtifactId, _deploy_spec: Vec<u8>) -> Receiver {
Receiver::with_result(Ok(()))
}
fn is_artifact_deployed(&self, _artifact: &ArtifactId) -> bool {
true
}
fn initiate_adding_service(
&self,
_context: ExecutionContext<'_>,
_artifact: &ArtifactId,
_parameters: Vec<u8>,
) -> Result<(), ExecutionError> {
Ok(())
}
fn initiate_resuming_service(
&self,
_context: ExecutionContext<'_>,
_artifact: &ArtifactId,
_parameters: Vec<u8>,
) -> Result<(), ExecutionError> {
Ok(())
}
fn update_service_status(&mut self, _snapshot: &dyn Snapshot, _state: &InstanceState) {
// Do nothing.
}
fn migrate(
&self,
_new_artifact: &ArtifactId,
_data_version: &Version,
) -> Result<Option<MigrationScript>, InitMigrationError> {
unimplemented!()
}
fn execute(
&self,
_context: ExecutionContext<'_>,
_method_id: u32,
_arguments: &[u8],
) -> Result<(), ExecutionError> {
Ok(())
}
fn before_transactions(&self, _context: ExecutionContext<'_>) -> Result<(), ExecutionError> {
Ok(())
}
fn after_transactions(&self, _context: ExecutionContext<'_>) -> Result<(), ExecutionError> {
Ok(())
}
fn after_commit(&mut self, _snapshot: &dyn Snapshot, _mailbox: &mut Mailbox) {
// Do nothing.
}
}
impl WellKnownRuntime for DummyRuntime {
const ID: u32 = 255;
}
fn prepare_blockchain() -> Blockchain {
const SERVICE_ID: InstanceId = 100;
let (consensus_config, keys) = ConsensusConfig::for_tests(1);
let artifact = ArtifactId::new(DummyRuntime::ID, "ts", Version::new(1, 0, 0)).unwrap();
let service = artifact.clone().into_default_instance(SERVICE_ID, "ts");
let blockchain = Blockchain::new(TemporaryDB::new(), keys.service, ApiSender::closed());
let genesis_config = GenesisConfigBuilder::with_consensus_config(consensus_config)
.with_artifact(artifact)
.with_instance(service)
.build();
BlockchainBuilder::new(blockchain)
.with_genesis_config(genesis_config)
.with_runtime(DummyRuntime)
.build()
.immutable_view()
}
|
let mut rng = StdRng::seed_from_u64(RNG_SEED);
(0..count)
.map(|_| {
let mut payload = [0_u8; 64];
rng.fill(&mut payload[..]);
let payload = AnyTx::new(CallInfo::new(100, 0), payload.to_vec());
payload.sign_with_keypair(&KeyPair::random())
})
.collect()
}
fn check_tx_no_cache(bencher: &mut Bencher) {
let blockchain = prepare_blockchain();
let transactions = prepare_transactions(128);
let snapshot = blockchain.snapshot();
bencher.iter(|| {
assert!(transactions
.iter()
.all(|tx| Blockchain::check_tx(&snapshot, tx).is_ok()));
})
}
fn check_tx_cache(bencher: &mut Bencher) {
let blockchain = prepare_blockchain();
let transactions = prepare_transactions(128);
let snapshot = blockchain.snapshot();
bencher.iter_batched(
TxCheckCache::new,
|mut cache| {
assert!(transactions
.iter()
.all(|tx| Blockchain::check_tx_with_cache(&snapshot, tx, &mut cache).is_ok()));
},
BatchSize::SmallInput,
)
}
pub fn bench_check_tx(c: &mut Criterion) {
let mut group = c.benchmark_group("check_tx/single_service");
group
.bench_function("no_cache", check_tx_no_cache)
.bench_function("cache", check_tx_cache);
group.finish();
}
|
fn prepare_transactions(count: usize) -> Vec<Verified<AnyTx>> {
const RNG_SEED: u64 = 123_456_789;
|
random_line_split
|
check_tx.rs
|
// Copyright 2020 The Exonum Team
//
// 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 criterion::{BatchSize, Bencher, Criterion};
use rand::{rngs::StdRng, Rng, SeedableRng};
use exonum::{
blockchain::{
config::GenesisConfigBuilder, ApiSender, Blockchain, BlockchainBuilder, ConsensusConfig,
TxCheckCache,
},
crypto::KeyPair,
merkledb::{Snapshot, TemporaryDB},
messages::{AnyTx, Verified},
runtime::{
migrations::{InitMigrationError, MigrationScript},
oneshot::Receiver,
versioning::Version,
ArtifactId, CallInfo, ExecutionContext, ExecutionError, InstanceId, InstanceState, Mailbox,
Runtime, WellKnownRuntime,
},
};
#[derive(Debug)]
struct DummyRuntime;
impl Runtime for DummyRuntime {
fn
|
(&mut self, _artifact: ArtifactId, _deploy_spec: Vec<u8>) -> Receiver {
Receiver::with_result(Ok(()))
}
fn is_artifact_deployed(&self, _artifact: &ArtifactId) -> bool {
true
}
fn initiate_adding_service(
&self,
_context: ExecutionContext<'_>,
_artifact: &ArtifactId,
_parameters: Vec<u8>,
) -> Result<(), ExecutionError> {
Ok(())
}
fn initiate_resuming_service(
&self,
_context: ExecutionContext<'_>,
_artifact: &ArtifactId,
_parameters: Vec<u8>,
) -> Result<(), ExecutionError> {
Ok(())
}
fn update_service_status(&mut self, _snapshot: &dyn Snapshot, _state: &InstanceState) {
// Do nothing.
}
fn migrate(
&self,
_new_artifact: &ArtifactId,
_data_version: &Version,
) -> Result<Option<MigrationScript>, InitMigrationError> {
unimplemented!()
}
fn execute(
&self,
_context: ExecutionContext<'_>,
_method_id: u32,
_arguments: &[u8],
) -> Result<(), ExecutionError> {
Ok(())
}
fn before_transactions(&self, _context: ExecutionContext<'_>) -> Result<(), ExecutionError> {
Ok(())
}
fn after_transactions(&self, _context: ExecutionContext<'_>) -> Result<(), ExecutionError> {
Ok(())
}
fn after_commit(&mut self, _snapshot: &dyn Snapshot, _mailbox: &mut Mailbox) {
// Do nothing.
}
}
impl WellKnownRuntime for DummyRuntime {
const ID: u32 = 255;
}
fn prepare_blockchain() -> Blockchain {
const SERVICE_ID: InstanceId = 100;
let (consensus_config, keys) = ConsensusConfig::for_tests(1);
let artifact = ArtifactId::new(DummyRuntime::ID, "ts", Version::new(1, 0, 0)).unwrap();
let service = artifact.clone().into_default_instance(SERVICE_ID, "ts");
let blockchain = Blockchain::new(TemporaryDB::new(), keys.service, ApiSender::closed());
let genesis_config = GenesisConfigBuilder::with_consensus_config(consensus_config)
.with_artifact(artifact)
.with_instance(service)
.build();
BlockchainBuilder::new(blockchain)
.with_genesis_config(genesis_config)
.with_runtime(DummyRuntime)
.build()
.immutable_view()
}
fn prepare_transactions(count: usize) -> Vec<Verified<AnyTx>> {
const RNG_SEED: u64 = 123_456_789;
let mut rng = StdRng::seed_from_u64(RNG_SEED);
(0..count)
.map(|_| {
let mut payload = [0_u8; 64];
rng.fill(&mut payload[..]);
let payload = AnyTx::new(CallInfo::new(100, 0), payload.to_vec());
payload.sign_with_keypair(&KeyPair::random())
})
.collect()
}
fn check_tx_no_cache(bencher: &mut Bencher) {
let blockchain = prepare_blockchain();
let transactions = prepare_transactions(128);
let snapshot = blockchain.snapshot();
bencher.iter(|| {
assert!(transactions
.iter()
.all(|tx| Blockchain::check_tx(&snapshot, tx).is_ok()));
})
}
fn check_tx_cache(bencher: &mut Bencher) {
let blockchain = prepare_blockchain();
let transactions = prepare_transactions(128);
let snapshot = blockchain.snapshot();
bencher.iter_batched(
TxCheckCache::new,
|mut cache| {
assert!(transactions
.iter()
.all(|tx| Blockchain::check_tx_with_cache(&snapshot, tx, &mut cache).is_ok()));
},
BatchSize::SmallInput,
)
}
pub fn bench_check_tx(c: &mut Criterion) {
let mut group = c.benchmark_group("check_tx/single_service");
group
.bench_function("no_cache", check_tx_no_cache)
.bench_function("cache", check_tx_cache);
group.finish();
}
|
deploy_artifact
|
identifier_name
|
main.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#![deny(clippy::all)]
use clap::Parser;
use colored::Colorize;
use signedsource::{sign_file, SIGNING_TOKEN};
use std::collections::HashMap;
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
#[derive(Debug, Parser)]
#[clap(name = "fixture-tests", about = "Generates fixture tests.")]
struct Options {
/// List of directories, each should contain a `/fixtures` subdirectory
/// from which a test file will be generated
#[clap(name = "DIR", parse(from_os_str))]
dirs: Vec<PathBuf>,
}
#[derive(Debug)]
struct TestCase {
name: String,
input: Option<PathBuf>,
expected: Option<PathBuf>,
}
const EXPECTED_EXTENSION: &str = "expected";
fn main() {
let opt = Options::parse();
for dir in opt.dirs {
let test_name = dir.file_name().unwrap().to_str().unwrap();
let fixtures_dir = dir.join("fixtures");
let paths = fs::read_dir(&fixtures_dir)
.unwrap_or_else(|_| panic!("Fixtures dir does not exist: {:?}", &fixtures_dir));
let mut test_cases: HashMap<String, TestCase> = HashMap::new();
for dir_entry in paths {
let path = dir_entry.unwrap().path();
if path.extension().is_none() {
continue;
}
let name = sanitize_identifier(path.file_stem().unwrap().to_str().unwrap());
let mut test_case = test_cases.entry(name.clone()).or_insert_with(|| TestCase {
name,
input: None,
expected: None,
});
if path.extension().unwrap() == EXPECTED_EXTENSION {
if let Some(ref previous) = test_case.expected {
panic!("Conflicting fixture name, {:?} and {:?}", previous, path);
}
test_case.expected = Some(path);
} else {
if let Some(ref previous) = test_case.input {
panic!("Conflicting fixture name, {:?} and {:?}", previous, path);
}
test_case.input = Some(path);
}
}
for mut test_case in test_cases.values_mut() {
if test_case.expected.is_none() {
if let Some(ref input) = test_case.input {
let mut expected = input.clone();
expected.set_extension(EXPECTED_EXTENSION);
File::create(&expected)
.unwrap()
.write_all(
"\x40nocommit\nRun snapshot tests with UPDATE_SNAPSHOTS=1 to update this new file.\n"
.as_bytes(),
)
.unwrap();
test_case.expected = Some(expected);
}
}
}
let mut test_cases: Vec<(_, _)> = test_cases.into_iter().collect();
test_cases.sort_by_key(|entry| entry.0.to_owned());
let test_cases = test_cases
.into_iter()
.map(|(_, test_case)| {
let test_case_name = &test_case.name;
format!(
r#"#[test]
fn {0}() {{
let input = include_str!("{1}/fixtures/{2}");
let expected = include_str!("{1}/fixtures/{3}");
test_fixture(transform_fixture, "{2}", "{1}/fixtures/{3}", input, expected);
}}"#,
test_case.name,
&test_name,
test_case
.input
.unwrap_or_else(|| panic!(
"Expected input for test {:?} to exist",
test_case_name
))
.file_name()
.and_then(|x| x.to_str())
.unwrap(),
test_case
.expected
.unwrap_or_else(|| panic!(
"Expected output for test {:?} to exist",
test_case_name
))
.file_name()
.and_then(|x| x.to_str())
.unwrap()
)
})
.collect::<Vec<_>>()
.join("\n\n");
let mut file = File::create(
dir.parent()
.unwrap()
.join(format!("{}_test.rs", &test_name)),
)
.unwrap();
// Slightly hacky way to find out if these fixture tests are in the OSS
// directory. This test should work on GitHub and in the internal repo.
let is_oss = dir
.components()
.any(|comp| comp == std::path::Component::Normal("crates".as_ref()));
let header = if is_oss {
format!(
"/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
|
",
signing_token = SIGNING_TOKEN,
)
} else {
format!(
"// {signing_token}
// Generated by $ cargo run -p fixture-tests -- {dir_name}
",
signing_token = SIGNING_TOKEN,
dir_name = dir.display(),
)
};
let content = format!(
"{header}
mod {test_name};
use {test_name}::transform_fixture;
use fixture_tests::test_fixture;
{test_cases}
",
header = header,
test_name = &test_name,
test_cases = test_cases,
);
file.write_all(sign_file(&content).as_bytes()).unwrap();
check_targets_file(&dir);
}
}
fn check_targets_file(test_dir: &Path) {
let targets_path = test_dir.parent().unwrap().parent().unwrap().join("TARGETS");
let targets_content = match std::fs::read_to_string(&targets_path) {
Ok(content) => content,
Err(_) => return,
};
let expected_substr = format!(
"\"tests/{}_test.rs\"",
test_dir.file_stem().unwrap().to_str().unwrap()
);
if!targets_content.contains(&expected_substr) {
eprintln!(
"{}",
format!(
"WARNING: expected {:?} to contain substring {}",
targets_path, expected_substr
)
.yellow()
);
}
}
fn sanitize_identifier(input: &str) -> String {
input
.chars()
.map(|chr| match chr {
'a'..='z' | '0'..='9' | '_' => chr,
'A'..='Z' => chr.to_ascii_lowercase(),
_ => '_',
})
.collect()
}
|
*
* {signing_token}
*/
|
random_line_split
|
main.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#![deny(clippy::all)]
use clap::Parser;
use colored::Colorize;
use signedsource::{sign_file, SIGNING_TOKEN};
use std::collections::HashMap;
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
#[derive(Debug, Parser)]
#[clap(name = "fixture-tests", about = "Generates fixture tests.")]
struct Options {
/// List of directories, each should contain a `/fixtures` subdirectory
/// from which a test file will be generated
#[clap(name = "DIR", parse(from_os_str))]
dirs: Vec<PathBuf>,
}
#[derive(Debug)]
struct TestCase {
name: String,
input: Option<PathBuf>,
expected: Option<PathBuf>,
}
const EXPECTED_EXTENSION: &str = "expected";
fn main() {
let opt = Options::parse();
for dir in opt.dirs {
let test_name = dir.file_name().unwrap().to_str().unwrap();
let fixtures_dir = dir.join("fixtures");
let paths = fs::read_dir(&fixtures_dir)
.unwrap_or_else(|_| panic!("Fixtures dir does not exist: {:?}", &fixtures_dir));
let mut test_cases: HashMap<String, TestCase> = HashMap::new();
for dir_entry in paths {
let path = dir_entry.unwrap().path();
if path.extension().is_none() {
continue;
}
let name = sanitize_identifier(path.file_stem().unwrap().to_str().unwrap());
let mut test_case = test_cases.entry(name.clone()).or_insert_with(|| TestCase {
name,
input: None,
expected: None,
});
if path.extension().unwrap() == EXPECTED_EXTENSION
|
else {
if let Some(ref previous) = test_case.input {
panic!("Conflicting fixture name, {:?} and {:?}", previous, path);
}
test_case.input = Some(path);
}
}
for mut test_case in test_cases.values_mut() {
if test_case.expected.is_none() {
if let Some(ref input) = test_case.input {
let mut expected = input.clone();
expected.set_extension(EXPECTED_EXTENSION);
File::create(&expected)
.unwrap()
.write_all(
"\x40nocommit\nRun snapshot tests with UPDATE_SNAPSHOTS=1 to update this new file.\n"
.as_bytes(),
)
.unwrap();
test_case.expected = Some(expected);
}
}
}
let mut test_cases: Vec<(_, _)> = test_cases.into_iter().collect();
test_cases.sort_by_key(|entry| entry.0.to_owned());
let test_cases = test_cases
.into_iter()
.map(|(_, test_case)| {
let test_case_name = &test_case.name;
format!(
r#"#[test]
fn {0}() {{
let input = include_str!("{1}/fixtures/{2}");
let expected = include_str!("{1}/fixtures/{3}");
test_fixture(transform_fixture, "{2}", "{1}/fixtures/{3}", input, expected);
}}"#,
test_case.name,
&test_name,
test_case
.input
.unwrap_or_else(|| panic!(
"Expected input for test {:?} to exist",
test_case_name
))
.file_name()
.and_then(|x| x.to_str())
.unwrap(),
test_case
.expected
.unwrap_or_else(|| panic!(
"Expected output for test {:?} to exist",
test_case_name
))
.file_name()
.and_then(|x| x.to_str())
.unwrap()
)
})
.collect::<Vec<_>>()
.join("\n\n");
let mut file = File::create(
dir.parent()
.unwrap()
.join(format!("{}_test.rs", &test_name)),
)
.unwrap();
// Slightly hacky way to find out if these fixture tests are in the OSS
// directory. This test should work on GitHub and in the internal repo.
let is_oss = dir
.components()
.any(|comp| comp == std::path::Component::Normal("crates".as_ref()));
let header = if is_oss {
format!(
"/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* {signing_token}
*/
",
signing_token = SIGNING_TOKEN,
)
} else {
format!(
"// {signing_token}
// Generated by $ cargo run -p fixture-tests -- {dir_name}
",
signing_token = SIGNING_TOKEN,
dir_name = dir.display(),
)
};
let content = format!(
"{header}
mod {test_name};
use {test_name}::transform_fixture;
use fixture_tests::test_fixture;
{test_cases}
",
header = header,
test_name = &test_name,
test_cases = test_cases,
);
file.write_all(sign_file(&content).as_bytes()).unwrap();
check_targets_file(&dir);
}
}
fn check_targets_file(test_dir: &Path) {
let targets_path = test_dir.parent().unwrap().parent().unwrap().join("TARGETS");
let targets_content = match std::fs::read_to_string(&targets_path) {
Ok(content) => content,
Err(_) => return,
};
let expected_substr = format!(
"\"tests/{}_test.rs\"",
test_dir.file_stem().unwrap().to_str().unwrap()
);
if!targets_content.contains(&expected_substr) {
eprintln!(
"{}",
format!(
"WARNING: expected {:?} to contain substring {}",
targets_path, expected_substr
)
.yellow()
);
}
}
fn sanitize_identifier(input: &str) -> String {
input
.chars()
.map(|chr| match chr {
'a'..='z' | '0'..='9' | '_' => chr,
'A'..='Z' => chr.to_ascii_lowercase(),
_ => '_',
})
.collect()
}
|
{
if let Some(ref previous) = test_case.expected {
panic!("Conflicting fixture name, {:?} and {:?}", previous, path);
}
test_case.expected = Some(path);
}
|
conditional_block
|
main.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#![deny(clippy::all)]
use clap::Parser;
use colored::Colorize;
use signedsource::{sign_file, SIGNING_TOKEN};
use std::collections::HashMap;
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
#[derive(Debug, Parser)]
#[clap(name = "fixture-tests", about = "Generates fixture tests.")]
struct
|
{
/// List of directories, each should contain a `/fixtures` subdirectory
/// from which a test file will be generated
#[clap(name = "DIR", parse(from_os_str))]
dirs: Vec<PathBuf>,
}
#[derive(Debug)]
struct TestCase {
name: String,
input: Option<PathBuf>,
expected: Option<PathBuf>,
}
const EXPECTED_EXTENSION: &str = "expected";
fn main() {
let opt = Options::parse();
for dir in opt.dirs {
let test_name = dir.file_name().unwrap().to_str().unwrap();
let fixtures_dir = dir.join("fixtures");
let paths = fs::read_dir(&fixtures_dir)
.unwrap_or_else(|_| panic!("Fixtures dir does not exist: {:?}", &fixtures_dir));
let mut test_cases: HashMap<String, TestCase> = HashMap::new();
for dir_entry in paths {
let path = dir_entry.unwrap().path();
if path.extension().is_none() {
continue;
}
let name = sanitize_identifier(path.file_stem().unwrap().to_str().unwrap());
let mut test_case = test_cases.entry(name.clone()).or_insert_with(|| TestCase {
name,
input: None,
expected: None,
});
if path.extension().unwrap() == EXPECTED_EXTENSION {
if let Some(ref previous) = test_case.expected {
panic!("Conflicting fixture name, {:?} and {:?}", previous, path);
}
test_case.expected = Some(path);
} else {
if let Some(ref previous) = test_case.input {
panic!("Conflicting fixture name, {:?} and {:?}", previous, path);
}
test_case.input = Some(path);
}
}
for mut test_case in test_cases.values_mut() {
if test_case.expected.is_none() {
if let Some(ref input) = test_case.input {
let mut expected = input.clone();
expected.set_extension(EXPECTED_EXTENSION);
File::create(&expected)
.unwrap()
.write_all(
"\x40nocommit\nRun snapshot tests with UPDATE_SNAPSHOTS=1 to update this new file.\n"
.as_bytes(),
)
.unwrap();
test_case.expected = Some(expected);
}
}
}
let mut test_cases: Vec<(_, _)> = test_cases.into_iter().collect();
test_cases.sort_by_key(|entry| entry.0.to_owned());
let test_cases = test_cases
.into_iter()
.map(|(_, test_case)| {
let test_case_name = &test_case.name;
format!(
r#"#[test]
fn {0}() {{
let input = include_str!("{1}/fixtures/{2}");
let expected = include_str!("{1}/fixtures/{3}");
test_fixture(transform_fixture, "{2}", "{1}/fixtures/{3}", input, expected);
}}"#,
test_case.name,
&test_name,
test_case
.input
.unwrap_or_else(|| panic!(
"Expected input for test {:?} to exist",
test_case_name
))
.file_name()
.and_then(|x| x.to_str())
.unwrap(),
test_case
.expected
.unwrap_or_else(|| panic!(
"Expected output for test {:?} to exist",
test_case_name
))
.file_name()
.and_then(|x| x.to_str())
.unwrap()
)
})
.collect::<Vec<_>>()
.join("\n\n");
let mut file = File::create(
dir.parent()
.unwrap()
.join(format!("{}_test.rs", &test_name)),
)
.unwrap();
// Slightly hacky way to find out if these fixture tests are in the OSS
// directory. This test should work on GitHub and in the internal repo.
let is_oss = dir
.components()
.any(|comp| comp == std::path::Component::Normal("crates".as_ref()));
let header = if is_oss {
format!(
"/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* {signing_token}
*/
",
signing_token = SIGNING_TOKEN,
)
} else {
format!(
"// {signing_token}
// Generated by $ cargo run -p fixture-tests -- {dir_name}
",
signing_token = SIGNING_TOKEN,
dir_name = dir.display(),
)
};
let content = format!(
"{header}
mod {test_name};
use {test_name}::transform_fixture;
use fixture_tests::test_fixture;
{test_cases}
",
header = header,
test_name = &test_name,
test_cases = test_cases,
);
file.write_all(sign_file(&content).as_bytes()).unwrap();
check_targets_file(&dir);
}
}
fn check_targets_file(test_dir: &Path) {
let targets_path = test_dir.parent().unwrap().parent().unwrap().join("TARGETS");
let targets_content = match std::fs::read_to_string(&targets_path) {
Ok(content) => content,
Err(_) => return,
};
let expected_substr = format!(
"\"tests/{}_test.rs\"",
test_dir.file_stem().unwrap().to_str().unwrap()
);
if!targets_content.contains(&expected_substr) {
eprintln!(
"{}",
format!(
"WARNING: expected {:?} to contain substring {}",
targets_path, expected_substr
)
.yellow()
);
}
}
fn sanitize_identifier(input: &str) -> String {
input
.chars()
.map(|chr| match chr {
'a'..='z' | '0'..='9' | '_' => chr,
'A'..='Z' => chr.to_ascii_lowercase(),
_ => '_',
})
.collect()
}
|
Options
|
identifier_name
|
sync-send-iterators-in-libcore.rs
|
// run-pass
// pretty-expanded FIXME #23616
#![allow(warnings)]
use std::iter::{empty, once, repeat};
fn is_sync<T>(_: T) where T: Sync {}
fn
|
<T>(_: T) where T: Send {}
macro_rules! all_sync_send {
($ctor:expr, $iter:ident) => ({
let mut x = $ctor;
is_sync(x.$iter());
let mut y = $ctor;
is_send(y.$iter());
});
($ctor:expr, $iter:ident($($param:expr),+)) => ({
let mut x = $ctor;
is_sync(x.$iter($( $param ),+));
let mut y = $ctor;
is_send(y.$iter($( $param ),+));
});
($ctor:expr, $iter:ident, $($rest:tt)*) => ({
all_sync_send!($ctor, $iter);
all_sync_send!($ctor, $($rest)*);
});
($ctor:expr, $iter:ident($($param:expr),+), $($rest:tt)*) => ({
all_sync_send!($ctor, $iter($( $param ),+));
all_sync_send!($ctor, $($rest)*);
});
}
macro_rules! all_sync_send_mutable_ref {
($ctor:expr, $($iter:ident),+) => ({
$(
let mut x = $ctor;
is_sync((&mut x).$iter());
let mut y = $ctor;
is_send((&mut y).$iter());
)+
})
}
macro_rules! is_sync_send {
($ctor:expr) => ({
let x = $ctor;
is_sync(x);
let y = $ctor;
is_send(y);
})
}
fn main() {
// for char.rs
all_sync_send!("Я", escape_debug, escape_default, escape_unicode);
// for iter.rs
all_sync_send_mutable_ref!([1], iter);
// Bytes implements DoubleEndedIterator
all_sync_send!("a".bytes(), rev);
let a = [1];
let b = [2];
all_sync_send!(a.iter(),
cloned,
cycle,
chain([2].iter()),
zip([2].iter()),
map(|_| 1),
filter(|_| true),
filter_map(|_| Some(1)),
enumerate,
peekable,
skip_while(|_| true),
take_while(|_| true),
skip(1),
take(1),
scan(1, |_, _| Some(1)),
flat_map(|_| b.iter()),
fuse,
inspect(|_| ()));
is_sync_send!((1..).step_by(2));
is_sync_send!((1..2).step_by(2));
is_sync_send!((1..2));
is_sync_send!((1..));
is_sync_send!(repeat(1));
is_sync_send!(empty::<usize>());
is_sync_send!(empty::<*mut i32>());
is_sync_send!(once(1));
// for option.rs
// FIXME
// for result.rs
// FIXME
// for slice.rs
// FIXME
// for str/mod.rs
// FIXME
}
|
is_send
|
identifier_name
|
sync-send-iterators-in-libcore.rs
|
// run-pass
// pretty-expanded FIXME #23616
#![allow(warnings)]
use std::iter::{empty, once, repeat};
fn is_sync<T>(_: T) where T: Sync
|
fn is_send<T>(_: T) where T: Send {}
macro_rules! all_sync_send {
($ctor:expr, $iter:ident) => ({
let mut x = $ctor;
is_sync(x.$iter());
let mut y = $ctor;
is_send(y.$iter());
});
($ctor:expr, $iter:ident($($param:expr),+)) => ({
let mut x = $ctor;
is_sync(x.$iter($( $param ),+));
let mut y = $ctor;
is_send(y.$iter($( $param ),+));
});
($ctor:expr, $iter:ident, $($rest:tt)*) => ({
all_sync_send!($ctor, $iter);
all_sync_send!($ctor, $($rest)*);
});
($ctor:expr, $iter:ident($($param:expr),+), $($rest:tt)*) => ({
all_sync_send!($ctor, $iter($( $param ),+));
all_sync_send!($ctor, $($rest)*);
});
}
macro_rules! all_sync_send_mutable_ref {
($ctor:expr, $($iter:ident),+) => ({
$(
let mut x = $ctor;
is_sync((&mut x).$iter());
let mut y = $ctor;
is_send((&mut y).$iter());
)+
})
}
macro_rules! is_sync_send {
($ctor:expr) => ({
let x = $ctor;
is_sync(x);
let y = $ctor;
is_send(y);
})
}
fn main() {
// for char.rs
all_sync_send!("Я", escape_debug, escape_default, escape_unicode);
// for iter.rs
all_sync_send_mutable_ref!([1], iter);
// Bytes implements DoubleEndedIterator
all_sync_send!("a".bytes(), rev);
let a = [1];
let b = [2];
all_sync_send!(a.iter(),
cloned,
cycle,
chain([2].iter()),
zip([2].iter()),
map(|_| 1),
filter(|_| true),
filter_map(|_| Some(1)),
enumerate,
peekable,
skip_while(|_| true),
take_while(|_| true),
skip(1),
take(1),
scan(1, |_, _| Some(1)),
flat_map(|_| b.iter()),
fuse,
inspect(|_| ()));
is_sync_send!((1..).step_by(2));
is_sync_send!((1..2).step_by(2));
is_sync_send!((1..2));
is_sync_send!((1..));
is_sync_send!(repeat(1));
is_sync_send!(empty::<usize>());
is_sync_send!(empty::<*mut i32>());
is_sync_send!(once(1));
// for option.rs
// FIXME
// for result.rs
// FIXME
// for slice.rs
// FIXME
// for str/mod.rs
// FIXME
}
|
{}
|
identifier_body
|
sync-send-iterators-in-libcore.rs
|
// run-pass
// pretty-expanded FIXME #23616
#![allow(warnings)]
use std::iter::{empty, once, repeat};
fn is_sync<T>(_: T) where T: Sync {}
fn is_send<T>(_: T) where T: Send {}
macro_rules! all_sync_send {
($ctor:expr, $iter:ident) => ({
let mut x = $ctor;
is_sync(x.$iter());
let mut y = $ctor;
is_send(y.$iter());
});
($ctor:expr, $iter:ident($($param:expr),+)) => ({
let mut x = $ctor;
is_sync(x.$iter($( $param ),+));
let mut y = $ctor;
is_send(y.$iter($( $param ),+));
});
($ctor:expr, $iter:ident, $($rest:tt)*) => ({
all_sync_send!($ctor, $iter);
all_sync_send!($ctor, $($rest)*);
});
($ctor:expr, $iter:ident($($param:expr),+), $($rest:tt)*) => ({
all_sync_send!($ctor, $iter($( $param ),+));
all_sync_send!($ctor, $($rest)*);
});
}
macro_rules! all_sync_send_mutable_ref {
($ctor:expr, $($iter:ident),+) => ({
$(
let mut x = $ctor;
is_sync((&mut x).$iter());
let mut y = $ctor;
is_send((&mut y).$iter());
)+
})
}
macro_rules! is_sync_send {
($ctor:expr) => ({
let x = $ctor;
is_sync(x);
let y = $ctor;
is_send(y);
})
}
fn main() {
// for char.rs
all_sync_send!("Я", escape_debug, escape_default, escape_unicode);
// for iter.rs
all_sync_send_mutable_ref!([1], iter);
// Bytes implements DoubleEndedIterator
all_sync_send!("a".bytes(), rev);
let a = [1];
let b = [2];
all_sync_send!(a.iter(),
cloned,
cycle,
chain([2].iter()),
zip([2].iter()),
map(|_| 1),
filter(|_| true),
filter_map(|_| Some(1)),
enumerate,
peekable,
skip_while(|_| true),
take_while(|_| true),
skip(1),
take(1),
scan(1, |_, _| Some(1)),
flat_map(|_| b.iter()),
fuse,
inspect(|_| ()));
|
is_sync_send!((1..).step_by(2));
is_sync_send!((1..2).step_by(2));
is_sync_send!((1..2));
is_sync_send!((1..));
is_sync_send!(repeat(1));
is_sync_send!(empty::<usize>());
is_sync_send!(empty::<*mut i32>());
is_sync_send!(once(1));
// for option.rs
// FIXME
// for result.rs
// FIXME
// for slice.rs
// FIXME
// for str/mod.rs
// FIXME
}
|
random_line_split
|
|
associated-types-normalize-in-bounds-binding.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that we normalize associated types that appear in a bound that
// contains a binding. Issue #21664.
#![allow(dead_code)]
pub trait Integral {
type Opposite;
}
impl Integral for i32 {
type Opposite = u32;
}
impl Integral for u32 {
type Opposite = i32;
}
pub trait FnLike<A> {
type R;
}
fn foo<T>()
where T : FnLike<<i32 as Integral>::Opposite, R=bool>
{
bar::<T>();
}
fn
|
<T>()
where T : FnLike<u32, R=bool>
{}
fn main() { }
|
bar
|
identifier_name
|
associated-types-normalize-in-bounds-binding.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that we normalize associated types that appear in a bound that
// contains a binding. Issue #21664.
#![allow(dead_code)]
pub trait Integral {
type Opposite;
}
impl Integral for i32 {
type Opposite = u32;
}
impl Integral for u32 {
type Opposite = i32;
}
pub trait FnLike<A> {
type R;
}
fn foo<T>()
where T : FnLike<<i32 as Integral>::Opposite, R=bool>
{
bar::<T>();
}
fn bar<T>()
where T : FnLike<u32, R=bool>
{}
|
fn main() { }
|
random_line_split
|
|
associated-types-normalize-in-bounds-binding.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that we normalize associated types that appear in a bound that
// contains a binding. Issue #21664.
#![allow(dead_code)]
pub trait Integral {
type Opposite;
}
impl Integral for i32 {
type Opposite = u32;
}
impl Integral for u32 {
type Opposite = i32;
}
pub trait FnLike<A> {
type R;
}
fn foo<T>()
where T : FnLike<<i32 as Integral>::Opposite, R=bool>
{
bar::<T>();
}
fn bar<T>()
where T : FnLike<u32, R=bool>
{}
fn main()
|
{ }
|
identifier_body
|
|
issue-18685.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that the self param space is not used in a conflicting
// manner by unboxed closures within a default method on a trait
#![feature(unboxed_closures)]
trait Tr {
fn foo(&self);
fn bar(&self) {
(|| { self.foo() })()
}
}
impl Tr for () {
fn
|
(&self) {}
}
fn main() {
().bar();
}
|
foo
|
identifier_name
|
issue-18685.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that the self param space is not used in a conflicting
// manner by unboxed closures within a default method on a trait
#![feature(unboxed_closures)]
trait Tr {
fn foo(&self);
fn bar(&self) {
(|| { self.foo() })()
}
}
impl Tr for () {
|
().bar();
}
|
fn foo(&self) {}
}
fn main() {
|
random_line_split
|
issue-18685.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that the self param space is not used in a conflicting
// manner by unboxed closures within a default method on a trait
#![feature(unboxed_closures)]
trait Tr {
fn foo(&self);
fn bar(&self) {
(|| { self.foo() })()
}
}
impl Tr for () {
fn foo(&self)
|
}
fn main() {
().bar();
}
|
{}
|
identifier_body
|
mod.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Runtime services
//!
//! The `rt` module provides a narrow set of runtime services,
//! including the global heap (exported in `heap`) and unwinding and
//! backtrace support. The APIs in this module are highly unstable,
//! and should be considered as private implementation details for the
//! time being.
#![unstable(feature = "std_misc")]
#![allow(missing_docs)]
use prelude::v1::*;
use sys;
use usize;
// Reexport some of our utilities which are expected by other crates.
pub use self::util::{min_stack, running_on_valgrind};
pub use self::unwind::{begin_unwind, begin_unwind_fmt};
// Reexport some functionality from liballoc.
pub use alloc::heap;
// Simple backtrace functionality (to print on panic)
pub mod backtrace;
// Internals
#[macro_use]
mod macros;
// These should be refactored/moved/made private over time
pub mod util;
pub mod unwind;
pub mod args;
mod at_exit_imp;
mod libunwind;
/// The default error code of the rust runtime if the main thread panics instead
/// of exiting cleanly.
pub const DEFAULT_ERROR_CODE: isize = 101;
#[cfg(any(windows, android))]
const OS_DEFAULT_STACK_ESTIMATE: usize = 1 << 20;
#[cfg(all(unix, not(android)))]
const OS_DEFAULT_STACK_ESTIMATE: usize = 2 * (1 << 20);
#[cfg(not(test))]
#[lang = "start"]
fn lang_start(main: *const u8, argc: isize, argv: *const *const u8) -> isize {
use prelude::v1::*;
use mem;
use env;
use rt;
use sys_common::thread_info::{self, NewThread};
use sys_common;
use thread::Thread;
let something_around_the_top_of_the_stack = 1;
let addr = &something_around_the_top_of_the_stack as *const _ as *const isize;
let my_stack_top = addr as usize;
// FIXME #11359 we just assume that this thread has a stack of a
// certain size, and estimate that there's at most 20KB of stack
// frames above our current position.
const TWENTY_KB: usize = 20000;
// saturating-add to sidestep overflow
let top_plus_spill = if usize::MAX - TWENTY_KB < my_stack_top {
usize::MAX
} else {
my_stack_top + TWENTY_KB
};
// saturating-sub to sidestep underflow
let my_stack_bottom = if top_plus_spill < OS_DEFAULT_STACK_ESTIMATE {
0
} else {
top_plus_spill - OS_DEFAULT_STACK_ESTIMATE
};
let failed = unsafe {
// First, make sure we don't trigger any __morestack overflow checks,
// and next set up our stack to have a guard page and run through our
// own fault handlers if we hit it.
sys_common::stack::record_os_managed_stack_bounds(my_stack_bottom,
my_stack_top);
sys::thread::guard::init();
sys::stack_overflow::init();
// Next, set up the current Thread with the guard information we just
// created. Note that this isn't necessary in general for new threads,
// but we just do this to name the main thread and to give it correct
// info about the stack bounds.
let thread: Thread = NewThread::new(Some("<main>".to_string()));
thread_info::set(sys::thread::guard::main(), thread);
// By default, some platforms will send a *signal* when a EPIPE error
// would otherwise be delivered. This runtime doesn't install a SIGPIPE
// handler, causing it to kill the program, which isn't exactly what we
// want!
//
// Hence, we set SIGPIPE to ignore when the program starts up in order
// to prevent this problem.
#[cfg(windows)] fn
|
() {}
#[cfg(unix)] fn ignore_sigpipe() {
use libc;
use libc::funcs::posix01::signal::signal;
unsafe {
assert!(signal(libc::SIGPIPE, libc::SIG_IGN)!=!0);
}
}
ignore_sigpipe();
// Store our args if necessary in a squirreled away location
args::init(argc, argv);
// And finally, let's run some code!
let res = unwind::try(|| {
let main: fn() = mem::transmute(main);
main();
});
cleanup();
res.is_err()
};
// If the exit code wasn't set, then the try block must have panicked.
if failed {
rt::DEFAULT_ERROR_CODE
} else {
env::get_exit_status() as isize
}
}
/// Enqueues a procedure to run when the main thread exits.
///
/// Currently these closures are only run once the main *Rust* thread exits.
/// Once the `at_exit` handlers begin running, more may be enqueued, but not
/// infinitely so. Eventually a handler registration will be forced to fail.
///
/// Returns `Ok` if the handler was successfully registered, meaning that the
/// closure will be run once the main thread exits. Returns `Err` to indicate
/// that the closure could not be registered, meaning that it is not scheduled
/// to be rune.
pub fn at_exit<F: FnOnce() + Send +'static>(f: F) -> Result<(), ()> {
if at_exit_imp::push(Box::new(f)) {Ok(())} else {Err(())}
}
/// One-time runtime cleanup.
///
/// This function is unsafe because it performs no checks to ensure that the
/// runtime has completely ceased running. It is the responsibility of the
/// caller to ensure that the runtime is entirely shut down and nothing will be
/// poking around at the internal components.
///
/// Invoking cleanup while portions of the runtime are still in use may cause
/// undefined behavior.
pub unsafe fn cleanup() {
args::cleanup();
sys::stack_overflow::cleanup();
at_exit_imp::cleanup();
}
|
ignore_sigpipe
|
identifier_name
|
mod.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Runtime services
//!
//! The `rt` module provides a narrow set of runtime services,
//! including the global heap (exported in `heap`) and unwinding and
//! backtrace support. The APIs in this module are highly unstable,
//! and should be considered as private implementation details for the
//! time being.
#![unstable(feature = "std_misc")]
#![allow(missing_docs)]
use prelude::v1::*;
use sys;
use usize;
// Reexport some of our utilities which are expected by other crates.
pub use self::util::{min_stack, running_on_valgrind};
pub use self::unwind::{begin_unwind, begin_unwind_fmt};
// Reexport some functionality from liballoc.
pub use alloc::heap;
// Simple backtrace functionality (to print on panic)
pub mod backtrace;
// Internals
#[macro_use]
mod macros;
// These should be refactored/moved/made private over time
pub mod util;
pub mod unwind;
pub mod args;
mod at_exit_imp;
mod libunwind;
/// The default error code of the rust runtime if the main thread panics instead
/// of exiting cleanly.
pub const DEFAULT_ERROR_CODE: isize = 101;
#[cfg(any(windows, android))]
const OS_DEFAULT_STACK_ESTIMATE: usize = 1 << 20;
#[cfg(all(unix, not(android)))]
const OS_DEFAULT_STACK_ESTIMATE: usize = 2 * (1 << 20);
#[cfg(not(test))]
#[lang = "start"]
fn lang_start(main: *const u8, argc: isize, argv: *const *const u8) -> isize {
use prelude::v1::*;
use mem;
use env;
use rt;
use sys_common::thread_info::{self, NewThread};
use sys_common;
use thread::Thread;
let something_around_the_top_of_the_stack = 1;
let addr = &something_around_the_top_of_the_stack as *const _ as *const isize;
let my_stack_top = addr as usize;
// FIXME #11359 we just assume that this thread has a stack of a
// certain size, and estimate that there's at most 20KB of stack
// frames above our current position.
const TWENTY_KB: usize = 20000;
// saturating-add to sidestep overflow
let top_plus_spill = if usize::MAX - TWENTY_KB < my_stack_top {
usize::MAX
} else {
my_stack_top + TWENTY_KB
};
// saturating-sub to sidestep underflow
let my_stack_bottom = if top_plus_spill < OS_DEFAULT_STACK_ESTIMATE {
0
} else {
top_plus_spill - OS_DEFAULT_STACK_ESTIMATE
};
let failed = unsafe {
// First, make sure we don't trigger any __morestack overflow checks,
// and next set up our stack to have a guard page and run through our
// own fault handlers if we hit it.
sys_common::stack::record_os_managed_stack_bounds(my_stack_bottom,
my_stack_top);
sys::thread::guard::init();
sys::stack_overflow::init();
// Next, set up the current Thread with the guard information we just
// created. Note that this isn't necessary in general for new threads,
// but we just do this to name the main thread and to give it correct
// info about the stack bounds.
let thread: Thread = NewThread::new(Some("<main>".to_string()));
thread_info::set(sys::thread::guard::main(), thread);
// By default, some platforms will send a *signal* when a EPIPE error
// would otherwise be delivered. This runtime doesn't install a SIGPIPE
// handler, causing it to kill the program, which isn't exactly what we
// want!
//
// Hence, we set SIGPIPE to ignore when the program starts up in order
// to prevent this problem.
#[cfg(windows)] fn ignore_sigpipe() {}
#[cfg(unix)] fn ignore_sigpipe() {
use libc;
use libc::funcs::posix01::signal::signal;
unsafe {
assert!(signal(libc::SIGPIPE, libc::SIG_IGN)!=!0);
}
}
ignore_sigpipe();
// Store our args if necessary in a squirreled away location
args::init(argc, argv);
// And finally, let's run some code!
let res = unwind::try(|| {
let main: fn() = mem::transmute(main);
main();
});
cleanup();
res.is_err()
};
// If the exit code wasn't set, then the try block must have panicked.
if failed {
rt::DEFAULT_ERROR_CODE
} else {
env::get_exit_status() as isize
}
}
/// Enqueues a procedure to run when the main thread exits.
///
/// Currently these closures are only run once the main *Rust* thread exits.
/// Once the `at_exit` handlers begin running, more may be enqueued, but not
/// infinitely so. Eventually a handler registration will be forced to fail.
///
/// Returns `Ok` if the handler was successfully registered, meaning that the
/// closure will be run once the main thread exits. Returns `Err` to indicate
/// that the closure could not be registered, meaning that it is not scheduled
/// to be rune.
pub fn at_exit<F: FnOnce() + Send +'static>(f: F) -> Result<(), ()> {
if at_exit_imp::push(Box::new(f))
|
else {Err(())}
}
/// One-time runtime cleanup.
///
/// This function is unsafe because it performs no checks to ensure that the
/// runtime has completely ceased running. It is the responsibility of the
/// caller to ensure that the runtime is entirely shut down and nothing will be
/// poking around at the internal components.
///
/// Invoking cleanup while portions of the runtime are still in use may cause
/// undefined behavior.
pub unsafe fn cleanup() {
args::cleanup();
sys::stack_overflow::cleanup();
at_exit_imp::cleanup();
}
|
{Ok(())}
|
conditional_block
|
mod.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Runtime services
//!
//! The `rt` module provides a narrow set of runtime services,
//! including the global heap (exported in `heap`) and unwinding and
//! backtrace support. The APIs in this module are highly unstable,
//! and should be considered as private implementation details for the
//! time being.
#![unstable(feature = "std_misc")]
#![allow(missing_docs)]
use prelude::v1::*;
use sys;
use usize;
// Reexport some of our utilities which are expected by other crates.
pub use self::util::{min_stack, running_on_valgrind};
pub use self::unwind::{begin_unwind, begin_unwind_fmt};
// Reexport some functionality from liballoc.
pub use alloc::heap;
// Simple backtrace functionality (to print on panic)
pub mod backtrace;
// Internals
#[macro_use]
mod macros;
// These should be refactored/moved/made private over time
pub mod util;
pub mod unwind;
pub mod args;
mod at_exit_imp;
mod libunwind;
/// The default error code of the rust runtime if the main thread panics instead
/// of exiting cleanly.
pub const DEFAULT_ERROR_CODE: isize = 101;
#[cfg(any(windows, android))]
const OS_DEFAULT_STACK_ESTIMATE: usize = 1 << 20;
#[cfg(all(unix, not(android)))]
const OS_DEFAULT_STACK_ESTIMATE: usize = 2 * (1 << 20);
#[cfg(not(test))]
#[lang = "start"]
fn lang_start(main: *const u8, argc: isize, argv: *const *const u8) -> isize {
use prelude::v1::*;
use mem;
use env;
use rt;
use sys_common::thread_info::{self, NewThread};
use sys_common;
use thread::Thread;
let something_around_the_top_of_the_stack = 1;
let addr = &something_around_the_top_of_the_stack as *const _ as *const isize;
let my_stack_top = addr as usize;
// FIXME #11359 we just assume that this thread has a stack of a
// certain size, and estimate that there's at most 20KB of stack
// frames above our current position.
const TWENTY_KB: usize = 20000;
// saturating-add to sidestep overflow
let top_plus_spill = if usize::MAX - TWENTY_KB < my_stack_top {
usize::MAX
} else {
my_stack_top + TWENTY_KB
};
// saturating-sub to sidestep underflow
let my_stack_bottom = if top_plus_spill < OS_DEFAULT_STACK_ESTIMATE {
0
} else {
top_plus_spill - OS_DEFAULT_STACK_ESTIMATE
};
let failed = unsafe {
// First, make sure we don't trigger any __morestack overflow checks,
// and next set up our stack to have a guard page and run through our
// own fault handlers if we hit it.
sys_common::stack::record_os_managed_stack_bounds(my_stack_bottom,
my_stack_top);
sys::thread::guard::init();
sys::stack_overflow::init();
// Next, set up the current Thread with the guard information we just
// created. Note that this isn't necessary in general for new threads,
// but we just do this to name the main thread and to give it correct
// info about the stack bounds.
let thread: Thread = NewThread::new(Some("<main>".to_string()));
thread_info::set(sys::thread::guard::main(), thread);
// By default, some platforms will send a *signal* when a EPIPE error
// would otherwise be delivered. This runtime doesn't install a SIGPIPE
// handler, causing it to kill the program, which isn't exactly what we
// want!
//
// Hence, we set SIGPIPE to ignore when the program starts up in order
// to prevent this problem.
#[cfg(windows)] fn ignore_sigpipe() {}
#[cfg(unix)] fn ignore_sigpipe()
|
ignore_sigpipe();
// Store our args if necessary in a squirreled away location
args::init(argc, argv);
// And finally, let's run some code!
let res = unwind::try(|| {
let main: fn() = mem::transmute(main);
main();
});
cleanup();
res.is_err()
};
// If the exit code wasn't set, then the try block must have panicked.
if failed {
rt::DEFAULT_ERROR_CODE
} else {
env::get_exit_status() as isize
}
}
/// Enqueues a procedure to run when the main thread exits.
///
/// Currently these closures are only run once the main *Rust* thread exits.
/// Once the `at_exit` handlers begin running, more may be enqueued, but not
/// infinitely so. Eventually a handler registration will be forced to fail.
///
/// Returns `Ok` if the handler was successfully registered, meaning that the
/// closure will be run once the main thread exits. Returns `Err` to indicate
/// that the closure could not be registered, meaning that it is not scheduled
/// to be rune.
pub fn at_exit<F: FnOnce() + Send +'static>(f: F) -> Result<(), ()> {
if at_exit_imp::push(Box::new(f)) {Ok(())} else {Err(())}
}
/// One-time runtime cleanup.
///
/// This function is unsafe because it performs no checks to ensure that the
/// runtime has completely ceased running. It is the responsibility of the
/// caller to ensure that the runtime is entirely shut down and nothing will be
/// poking around at the internal components.
///
/// Invoking cleanup while portions of the runtime are still in use may cause
/// undefined behavior.
pub unsafe fn cleanup() {
args::cleanup();
sys::stack_overflow::cleanup();
at_exit_imp::cleanup();
}
|
{
use libc;
use libc::funcs::posix01::signal::signal;
unsafe {
assert!(signal(libc::SIGPIPE, libc::SIG_IGN) != !0);
}
}
|
identifier_body
|
mod.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Runtime services
//!
//! The `rt` module provides a narrow set of runtime services,
//! including the global heap (exported in `heap`) and unwinding and
//! backtrace support. The APIs in this module are highly unstable,
//! and should be considered as private implementation details for the
//! time being.
#![unstable(feature = "std_misc")]
#![allow(missing_docs)]
use prelude::v1::*;
use sys;
use usize;
// Reexport some of our utilities which are expected by other crates.
pub use self::util::{min_stack, running_on_valgrind};
pub use self::unwind::{begin_unwind, begin_unwind_fmt};
// Reexport some functionality from liballoc.
pub use alloc::heap;
// Simple backtrace functionality (to print on panic)
pub mod backtrace;
// Internals
#[macro_use]
mod macros;
// These should be refactored/moved/made private over time
pub mod util;
pub mod unwind;
pub mod args;
mod at_exit_imp;
mod libunwind;
/// The default error code of the rust runtime if the main thread panics instead
/// of exiting cleanly.
pub const DEFAULT_ERROR_CODE: isize = 101;
#[cfg(any(windows, android))]
const OS_DEFAULT_STACK_ESTIMATE: usize = 1 << 20;
#[cfg(all(unix, not(android)))]
const OS_DEFAULT_STACK_ESTIMATE: usize = 2 * (1 << 20);
#[cfg(not(test))]
#[lang = "start"]
fn lang_start(main: *const u8, argc: isize, argv: *const *const u8) -> isize {
use prelude::v1::*;
use mem;
use env;
use rt;
use sys_common::thread_info::{self, NewThread};
use sys_common;
use thread::Thread;
let something_around_the_top_of_the_stack = 1;
let addr = &something_around_the_top_of_the_stack as *const _ as *const isize;
let my_stack_top = addr as usize;
// FIXME #11359 we just assume that this thread has a stack of a
// certain size, and estimate that there's at most 20KB of stack
// frames above our current position.
const TWENTY_KB: usize = 20000;
// saturating-add to sidestep overflow
let top_plus_spill = if usize::MAX - TWENTY_KB < my_stack_top {
usize::MAX
} else {
my_stack_top + TWENTY_KB
};
// saturating-sub to sidestep underflow
let my_stack_bottom = if top_plus_spill < OS_DEFAULT_STACK_ESTIMATE {
0
} else {
top_plus_spill - OS_DEFAULT_STACK_ESTIMATE
};
let failed = unsafe {
// First, make sure we don't trigger any __morestack overflow checks,
// and next set up our stack to have a guard page and run through our
// own fault handlers if we hit it.
sys_common::stack::record_os_managed_stack_bounds(my_stack_bottom,
my_stack_top);
sys::thread::guard::init();
sys::stack_overflow::init();
// Next, set up the current Thread with the guard information we just
// created. Note that this isn't necessary in general for new threads,
// but we just do this to name the main thread and to give it correct
// info about the stack bounds.
let thread: Thread = NewThread::new(Some("<main>".to_string()));
thread_info::set(sys::thread::guard::main(), thread);
// By default, some platforms will send a *signal* when a EPIPE error
// would otherwise be delivered. This runtime doesn't install a SIGPIPE
|
// want!
//
// Hence, we set SIGPIPE to ignore when the program starts up in order
// to prevent this problem.
#[cfg(windows)] fn ignore_sigpipe() {}
#[cfg(unix)] fn ignore_sigpipe() {
use libc;
use libc::funcs::posix01::signal::signal;
unsafe {
assert!(signal(libc::SIGPIPE, libc::SIG_IGN)!=!0);
}
}
ignore_sigpipe();
// Store our args if necessary in a squirreled away location
args::init(argc, argv);
// And finally, let's run some code!
let res = unwind::try(|| {
let main: fn() = mem::transmute(main);
main();
});
cleanup();
res.is_err()
};
// If the exit code wasn't set, then the try block must have panicked.
if failed {
rt::DEFAULT_ERROR_CODE
} else {
env::get_exit_status() as isize
}
}
/// Enqueues a procedure to run when the main thread exits.
///
/// Currently these closures are only run once the main *Rust* thread exits.
/// Once the `at_exit` handlers begin running, more may be enqueued, but not
/// infinitely so. Eventually a handler registration will be forced to fail.
///
/// Returns `Ok` if the handler was successfully registered, meaning that the
/// closure will be run once the main thread exits. Returns `Err` to indicate
/// that the closure could not be registered, meaning that it is not scheduled
/// to be rune.
pub fn at_exit<F: FnOnce() + Send +'static>(f: F) -> Result<(), ()> {
if at_exit_imp::push(Box::new(f)) {Ok(())} else {Err(())}
}
/// One-time runtime cleanup.
///
/// This function is unsafe because it performs no checks to ensure that the
/// runtime has completely ceased running. It is the responsibility of the
/// caller to ensure that the runtime is entirely shut down and nothing will be
/// poking around at the internal components.
///
/// Invoking cleanup while portions of the runtime are still in use may cause
/// undefined behavior.
pub unsafe fn cleanup() {
args::cleanup();
sys::stack_overflow::cleanup();
at_exit_imp::cleanup();
}
|
// handler, causing it to kill the program, which isn't exactly what we
|
random_line_split
|
greed.rs
|
use std::collections::HashMap;
use std::collections::hash_map;
use std::default::Default;
use std::cmp::Ordering;
use std::fmt;
use ::rand::{thread_rng, Rng, Rand};
use ::rand::distributions::{Sample, Range};
use irc::legacy::{
ChannelId,
User,
UserId,
};
use irc::{IrcMsg, server};
use irc::legacy::MessageEndpoint::{
KnownChannel,
KnownUser,
};
use command_mapper::{
RustBotPlugin,
CommandMapperDispatch,
IrcBotConfigurator,
Format,
Token,
};
const CMD_GREED: Token = Token(0);
const CMD_GREED_STATS: Token = Token(1);
type ScorePrefix = [u8; 6];
type ScoreRec = (usize, ScorePrefix, i32);
static SCORING_TABLE: [ScoreRec; 28] = [
(6, [1, 2, 3, 4, 5, 6], 1200),
(6, [2, 2, 3, 3, 4, 4], 800),
(6, [1, 1, 1, 1, 1, 1], 8000),
(5, [1, 1, 1, 1, 1, 0], 4000),
(4, [1, 1, 1, 1, 0, 0], 2000),
(3, [1, 1, 1, 0, 0, 0], 1000),
(1, [1, 0, 0, 0, 0, 0], 100),
(6, [2, 2, 2, 2, 2, 2], 1600),
(5, [2, 2, 2, 2, 2, 0], 800),
(4, [2, 2, 2, 2, 0, 0], 400),
(3, [2, 2, 2, 0, 0, 0], 200),
(6, [3, 3, 3, 3, 3, 3], 2400),
(5, [3, 3, 3, 3, 3, 0], 1200),
(4, [3, 3, 3, 3, 0, 0], 600),
(3, [3, 3, 3, 0, 0, 0], 300),
(6, [4, 4, 4, 4, 4, 4], 3200),
(5, [4, 4, 4, 4, 4, 0], 1600),
(4, [4, 4, 4, 4, 0, 0], 800),
(3, [4, 4, 4, 0, 0, 0], 400),
(6, [5, 5, 5, 5, 5, 5], 4000),
(5, [5, 5, 5, 5, 5, 0], 2000),
(4, [5, 5, 5, 5, 0, 0], 1000),
(3, [5, 5, 5, 0, 0, 0], 500),
(1, [5, 0, 0, 0, 0, 0], 50),
(6, [6, 6, 6, 6, 6, 6], 4800),
(5, [6, 6, 6, 6, 6, 0], 2400),
(4, [6, 6, 6, 6, 0, 0], 1200),
(3, [6, 6, 6, 0, 0, 0], 600),
];
struct RollResult([u8; 6]);
#[inline]
fn is_prefix(rec: &ScoreRec, roll_res: &RollResult, start_idx: usize) -> bool {
let RollResult(ref roll_data) = *roll_res;
let (prefix_len, ref roll_target, _) = *rec;
if roll_data.len() < start_idx + prefix_len {
return false;
}
for idx in 0..prefix_len {
if roll_data[idx + start_idx]!= roll_target[idx] {
return false;
}
}
true
}
impl RollResult {
fn get_scores(&self) -> Vec<&'static ScoreRec> {
let RollResult(ref roll) = *self;
let mut idx = 0;
let mut score_comps = Vec::new();
while idx < roll.len() {
let mut idx_incr = 1;
for score_rec in SCORING_TABLE.iter() {
if is_prefix(score_rec, self, idx) {
let (prefix_len, _, _) = *score_rec;
idx_incr = prefix_len;
score_comps.push(score_rec);
break;
}
}
idx += idx_incr;
}
score_comps
}
fn total_score(&self) -> i32 {
let mut sum = 0;
for score in self.get_scores().iter() {
let (_, _, score_val) = **score;
sum += score_val;
}
sum
}
fn format_score_component_bare(score_pref: &ScorePrefix) -> String {
let mut rolls = String::new();
for value in score_pref.iter() {
if *value == 0 {
break
}
rolls.push_str(&format!("{}, ", value));
}
rolls.pop(); rolls.pop();
format!("{}", rolls)
}
fn format_score_component(score_components: &ScoreRec) -> String {
let (_, ref prefix_data, _) = *score_components;
RollResult::format_score_component_bare(prefix_data)
}
fn format_score(score_components: &Vec<&ScoreRec>) -> String {
let mut output = String::new();
for tuple in score_components.iter() {
let (_, _, score) = **tuple;
let roll_res = RollResult::format_score_component(*tuple);
output.push_str(&format!("[{} => {}], ", roll_res, score));
}
output.pop(); output.pop();
output
}
}
impl Rand for RollResult {
fn rand<R: Rng>(rng: &mut R) -> RollResult {
let mut out: ScorePrefix = [0u8; 6];
let mut between = Range::new(1u8, 7u8);
for val in out.iter_mut() {
*val = between.sample(rng);
}
out.sort();
RollResult(out)
}
}
impl fmt::Display for RollResult {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let RollResult(ref roll) = *self;
write!(f, "[{}] => [{}] for {} points",
RollResult::format_score_component_bare(roll),
RollResult::format_score(&self.get_scores()),
self.total_score())
}
}
pub struct GreedPlugin {
games: HashMap<ChannelId, GreedPlayResult>,
userstats: HashMap<UserId, UserStats>,
}
enum GreedCommandType {
Greed,
GreedStats
}
struct GreedPlayResult {
user_id: UserId,
user_nick: String,
roll: RollResult,
}
fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<GreedCommandType> {
match m.command().token {
CMD_GREED => Some(GreedCommandType::Greed),
CMD_GREED_STATS => Some(GreedCommandType::GreedStats),
_ => None
}
}
struct UserStats {
games: u32,
wins: u32,
score_sum: i32,
opponent_score_sum: i32
}
impl Default for UserStats {
fn default() -> UserStats {
UserStats {
games: 0,
wins: 0,
score_sum: 0,
opponent_score_sum: 0,
}
}
}
impl fmt::Display for UserStats {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error>
|
}
impl GreedPlugin {
pub fn new() -> GreedPlugin {
GreedPlugin {
games: HashMap::new(),
userstats: HashMap::new(),
}
}
pub fn get_plugin_name() -> &'static str {
"greed"
}
fn dispatch_cmd_greed_stats(&mut self, m: &CommandMapperDispatch, msg: &server::Privmsg) {
let user_id = match m.source {
KnownUser(user_id) => user_id,
_ => return
};
m.reply(match self.userstats.get(&user_id) {
Some(stats) => format!("{}: {}", msg.source_nick(), stats),
None => format!("{}: You haven't played any games yet", msg.source_nick())
}.as_ref());
}
fn add_userstats_roll(&mut self, uid: UserId, win: bool, self_score: i32, opp_score: i32) {
let cur_user = match self.userstats.entry(uid) {
hash_map::Entry::Occupied(entry) => entry.into_mut(),
hash_map::Entry::Vacant(entry) => entry.insert(Default::default())
};
cur_user.games += 1;
cur_user.wins += if win { 1 } else { 0 };
cur_user.score_sum += self_score;
cur_user.opponent_score_sum += opp_score;
}
fn dispatch_cmd_greed(&mut self, m: &CommandMapperDispatch, msg: &server::Privmsg) {
let (user_id, channel_id) = match (m.source.clone(), m.target.clone()) {
(KnownUser(uid), KnownChannel(cid)) => (uid, cid),
_ => return
};
let source_nick = msg.source_nick();
let prev_play_opt: Option<GreedPlayResult> = match self.games.entry(channel_id) {
hash_map::Entry::Vacant(entry) => {
let roll = thread_rng().gen::<RollResult>();
m.reply(&format!("{}: {}", source_nick, roll));
entry.insert(GreedPlayResult {
user_id: user_id,
user_nick: source_nick.to_string(),
roll: roll
});
None
},
hash_map::Entry::Occupied(entry) => {
if entry.get().user_id == user_id {
m.reply(&format!("You can't go twice in a row, {}", source_nick));
None
} else {
Some(entry.remove())
}
}
};
if let Some(prev_play) = prev_play_opt {
let roll = thread_rng().gen::<RollResult>();
m.reply(&format!("{}: {}", source_nick, roll));
let prev_play_nick = m.get_state().resolve_user(prev_play.user_id)
.and_then(|user: &User| Some(user.get_nick().to_string()))
.unwrap_or_else(|| format!("{} (deceased)", prev_play.user_nick));
let prev_play_score = prev_play.roll.total_score();
let cur_play_score = roll.total_score();
let cmp_result = prev_play_score.cmp(&cur_play_score);
let (prev_user_wins, cur_user_wins) = match cmp_result {
Ordering::Less => (false, true),
Ordering::Equal => (false, false),
Ordering::Greater => (true, false)
};
let score_diff = (prev_play_score - cur_play_score).abs();
let response = match cmp_result {
Ordering::Less => format!("{} wins {} points from {}!",
source_nick, score_diff, prev_play_nick),
Ordering::Equal => format!("{} and {} tie.", source_nick, prev_play_nick),
Ordering::Greater => format!("{} wins {} points from {}!",
prev_play_nick, score_diff, source_nick),
};
m.reply(&response);
self.add_userstats_roll(user_id, cur_user_wins,
cur_play_score, prev_play_score);
self.add_userstats_roll(prev_play.user_id, prev_user_wins,
prev_play_score, cur_play_score);
}
}
}
impl RustBotPlugin for GreedPlugin {
fn configure(&mut self, conf: &mut IrcBotConfigurator) {
conf.map_format(CMD_GREED, Format::from_str("greed").unwrap());
conf.map_format(CMD_GREED_STATS, Format::from_str("greed-stats").unwrap());
}
fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, msg: &IrcMsg) {
let privmsg;
match msg.as_tymsg::<&server::Privmsg>() {
Ok(p) => privmsg = p,
Err(_) => return,
}
match parse_command(m) {
Some(GreedCommandType::Greed) => self.dispatch_cmd_greed(m, privmsg),
Some(GreedCommandType::GreedStats) => self.dispatch_cmd_greed_stats(m, privmsg),
None => ()
}
}
}
|
{
write!(f, "{} wins over {} games; points: {}",
self.wins, self.games, self.score_sum - self.opponent_score_sum)
}
|
identifier_body
|
greed.rs
|
use std::collections::HashMap;
use std::collections::hash_map;
use std::default::Default;
use std::cmp::Ordering;
use std::fmt;
use ::rand::{thread_rng, Rng, Rand};
use ::rand::distributions::{Sample, Range};
use irc::legacy::{
ChannelId,
User,
UserId,
};
use irc::{IrcMsg, server};
use irc::legacy::MessageEndpoint::{
KnownChannel,
KnownUser,
};
use command_mapper::{
RustBotPlugin,
CommandMapperDispatch,
IrcBotConfigurator,
Format,
Token,
};
const CMD_GREED: Token = Token(0);
const CMD_GREED_STATS: Token = Token(1);
type ScorePrefix = [u8; 6];
type ScoreRec = (usize, ScorePrefix, i32);
static SCORING_TABLE: [ScoreRec; 28] = [
(6, [1, 2, 3, 4, 5, 6], 1200),
(6, [2, 2, 3, 3, 4, 4], 800),
(6, [1, 1, 1, 1, 1, 1], 8000),
(5, [1, 1, 1, 1, 1, 0], 4000),
(4, [1, 1, 1, 1, 0, 0], 2000),
(3, [1, 1, 1, 0, 0, 0], 1000),
(1, [1, 0, 0, 0, 0, 0], 100),
(6, [2, 2, 2, 2, 2, 2], 1600),
(5, [2, 2, 2, 2, 2, 0], 800),
(4, [2, 2, 2, 2, 0, 0], 400),
(3, [2, 2, 2, 0, 0, 0], 200),
(6, [3, 3, 3, 3, 3, 3], 2400),
(5, [3, 3, 3, 3, 3, 0], 1200),
(4, [3, 3, 3, 3, 0, 0], 600),
(3, [3, 3, 3, 0, 0, 0], 300),
(6, [4, 4, 4, 4, 4, 4], 3200),
(5, [4, 4, 4, 4, 4, 0], 1600),
(4, [4, 4, 4, 4, 0, 0], 800),
(3, [4, 4, 4, 0, 0, 0], 400),
(6, [5, 5, 5, 5, 5, 5], 4000),
(5, [5, 5, 5, 5, 5, 0], 2000),
(4, [5, 5, 5, 5, 0, 0], 1000),
(3, [5, 5, 5, 0, 0, 0], 500),
(1, [5, 0, 0, 0, 0, 0], 50),
(6, [6, 6, 6, 6, 6, 6], 4800),
(5, [6, 6, 6, 6, 6, 0], 2400),
(4, [6, 6, 6, 6, 0, 0], 1200),
(3, [6, 6, 6, 0, 0, 0], 600),
];
struct RollResult([u8; 6]);
#[inline]
fn is_prefix(rec: &ScoreRec, roll_res: &RollResult, start_idx: usize) -> bool {
let RollResult(ref roll_data) = *roll_res;
let (prefix_len, ref roll_target, _) = *rec;
if roll_data.len() < start_idx + prefix_len {
return false;
}
for idx in 0..prefix_len {
if roll_data[idx + start_idx]!= roll_target[idx] {
return false;
}
}
true
}
impl RollResult {
fn get_scores(&self) -> Vec<&'static ScoreRec> {
let RollResult(ref roll) = *self;
let mut idx = 0;
let mut score_comps = Vec::new();
while idx < roll.len() {
let mut idx_incr = 1;
for score_rec in SCORING_TABLE.iter() {
if is_prefix(score_rec, self, idx) {
let (prefix_len, _, _) = *score_rec;
idx_incr = prefix_len;
score_comps.push(score_rec);
break;
}
}
idx += idx_incr;
}
score_comps
}
fn total_score(&self) -> i32 {
let mut sum = 0;
for score in self.get_scores().iter() {
let (_, _, score_val) = **score;
sum += score_val;
}
sum
}
fn format_score_component_bare(score_pref: &ScorePrefix) -> String {
let mut rolls = String::new();
for value in score_pref.iter() {
if *value == 0 {
break
}
rolls.push_str(&format!("{}, ", value));
}
rolls.pop(); rolls.pop();
format!("{}", rolls)
}
fn format_score_component(score_components: &ScoreRec) -> String {
let (_, ref prefix_data, _) = *score_components;
RollResult::format_score_component_bare(prefix_data)
}
fn format_score(score_components: &Vec<&ScoreRec>) -> String {
let mut output = String::new();
for tuple in score_components.iter() {
let (_, _, score) = **tuple;
let roll_res = RollResult::format_score_component(*tuple);
output.push_str(&format!("[{} => {}], ", roll_res, score));
}
output.pop(); output.pop();
output
}
}
impl Rand for RollResult {
fn rand<R: Rng>(rng: &mut R) -> RollResult {
let mut out: ScorePrefix = [0u8; 6];
let mut between = Range::new(1u8, 7u8);
for val in out.iter_mut() {
*val = between.sample(rng);
}
out.sort();
RollResult(out)
}
}
impl fmt::Display for RollResult {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let RollResult(ref roll) = *self;
write!(f, "[{}] => [{}] for {} points",
RollResult::format_score_component_bare(roll),
RollResult::format_score(&self.get_scores()),
self.total_score())
}
}
pub struct GreedPlugin {
games: HashMap<ChannelId, GreedPlayResult>,
userstats: HashMap<UserId, UserStats>,
}
enum GreedCommandType {
Greed,
GreedStats
}
struct GreedPlayResult {
user_id: UserId,
user_nick: String,
roll: RollResult,
}
fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<GreedCommandType> {
match m.command().token {
CMD_GREED => Some(GreedCommandType::Greed),
CMD_GREED_STATS => Some(GreedCommandType::GreedStats),
_ => None
}
}
struct UserStats {
games: u32,
wins: u32,
score_sum: i32,
opponent_score_sum: i32
}
impl Default for UserStats {
fn default() -> UserStats {
UserStats {
games: 0,
wins: 0,
score_sum: 0,
opponent_score_sum: 0,
}
}
}
impl fmt::Display for UserStats {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{} wins over {} games; points: {}",
self.wins, self.games, self.score_sum - self.opponent_score_sum)
}
}
impl GreedPlugin {
pub fn new() -> GreedPlugin {
GreedPlugin {
games: HashMap::new(),
userstats: HashMap::new(),
}
}
pub fn
|
() -> &'static str {
"greed"
}
fn dispatch_cmd_greed_stats(&mut self, m: &CommandMapperDispatch, msg: &server::Privmsg) {
let user_id = match m.source {
KnownUser(user_id) => user_id,
_ => return
};
m.reply(match self.userstats.get(&user_id) {
Some(stats) => format!("{}: {}", msg.source_nick(), stats),
None => format!("{}: You haven't played any games yet", msg.source_nick())
}.as_ref());
}
fn add_userstats_roll(&mut self, uid: UserId, win: bool, self_score: i32, opp_score: i32) {
let cur_user = match self.userstats.entry(uid) {
hash_map::Entry::Occupied(entry) => entry.into_mut(),
hash_map::Entry::Vacant(entry) => entry.insert(Default::default())
};
cur_user.games += 1;
cur_user.wins += if win { 1 } else { 0 };
cur_user.score_sum += self_score;
cur_user.opponent_score_sum += opp_score;
}
fn dispatch_cmd_greed(&mut self, m: &CommandMapperDispatch, msg: &server::Privmsg) {
let (user_id, channel_id) = match (m.source.clone(), m.target.clone()) {
(KnownUser(uid), KnownChannel(cid)) => (uid, cid),
_ => return
};
let source_nick = msg.source_nick();
let prev_play_opt: Option<GreedPlayResult> = match self.games.entry(channel_id) {
hash_map::Entry::Vacant(entry) => {
let roll = thread_rng().gen::<RollResult>();
m.reply(&format!("{}: {}", source_nick, roll));
entry.insert(GreedPlayResult {
user_id: user_id,
user_nick: source_nick.to_string(),
roll: roll
});
None
},
hash_map::Entry::Occupied(entry) => {
if entry.get().user_id == user_id {
m.reply(&format!("You can't go twice in a row, {}", source_nick));
None
} else {
Some(entry.remove())
}
}
};
if let Some(prev_play) = prev_play_opt {
let roll = thread_rng().gen::<RollResult>();
m.reply(&format!("{}: {}", source_nick, roll));
let prev_play_nick = m.get_state().resolve_user(prev_play.user_id)
.and_then(|user: &User| Some(user.get_nick().to_string()))
.unwrap_or_else(|| format!("{} (deceased)", prev_play.user_nick));
let prev_play_score = prev_play.roll.total_score();
let cur_play_score = roll.total_score();
let cmp_result = prev_play_score.cmp(&cur_play_score);
let (prev_user_wins, cur_user_wins) = match cmp_result {
Ordering::Less => (false, true),
Ordering::Equal => (false, false),
Ordering::Greater => (true, false)
};
let score_diff = (prev_play_score - cur_play_score).abs();
let response = match cmp_result {
Ordering::Less => format!("{} wins {} points from {}!",
source_nick, score_diff, prev_play_nick),
Ordering::Equal => format!("{} and {} tie.", source_nick, prev_play_nick),
Ordering::Greater => format!("{} wins {} points from {}!",
prev_play_nick, score_diff, source_nick),
};
m.reply(&response);
self.add_userstats_roll(user_id, cur_user_wins,
cur_play_score, prev_play_score);
self.add_userstats_roll(prev_play.user_id, prev_user_wins,
prev_play_score, cur_play_score);
}
}
}
impl RustBotPlugin for GreedPlugin {
fn configure(&mut self, conf: &mut IrcBotConfigurator) {
conf.map_format(CMD_GREED, Format::from_str("greed").unwrap());
conf.map_format(CMD_GREED_STATS, Format::from_str("greed-stats").unwrap());
}
fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, msg: &IrcMsg) {
let privmsg;
match msg.as_tymsg::<&server::Privmsg>() {
Ok(p) => privmsg = p,
Err(_) => return,
}
match parse_command(m) {
Some(GreedCommandType::Greed) => self.dispatch_cmd_greed(m, privmsg),
Some(GreedCommandType::GreedStats) => self.dispatch_cmd_greed_stats(m, privmsg),
None => ()
}
}
}
|
get_plugin_name
|
identifier_name
|
greed.rs
|
use std::collections::HashMap;
use std::collections::hash_map;
use std::default::Default;
use std::cmp::Ordering;
use std::fmt;
use ::rand::{thread_rng, Rng, Rand};
use ::rand::distributions::{Sample, Range};
use irc::legacy::{
ChannelId,
User,
UserId,
};
use irc::{IrcMsg, server};
use irc::legacy::MessageEndpoint::{
KnownChannel,
KnownUser,
};
use command_mapper::{
RustBotPlugin,
CommandMapperDispatch,
IrcBotConfigurator,
Format,
Token,
};
const CMD_GREED: Token = Token(0);
const CMD_GREED_STATS: Token = Token(1);
type ScorePrefix = [u8; 6];
type ScoreRec = (usize, ScorePrefix, i32);
static SCORING_TABLE: [ScoreRec; 28] = [
(6, [1, 2, 3, 4, 5, 6], 1200),
(6, [2, 2, 3, 3, 4, 4], 800),
(6, [1, 1, 1, 1, 1, 1], 8000),
(5, [1, 1, 1, 1, 1, 0], 4000),
(4, [1, 1, 1, 1, 0, 0], 2000),
(3, [1, 1, 1, 0, 0, 0], 1000),
(1, [1, 0, 0, 0, 0, 0], 100),
(6, [2, 2, 2, 2, 2, 2], 1600),
(5, [2, 2, 2, 2, 2, 0], 800),
(4, [2, 2, 2, 2, 0, 0], 400),
(3, [2, 2, 2, 0, 0, 0], 200),
(6, [3, 3, 3, 3, 3, 3], 2400),
(5, [3, 3, 3, 3, 3, 0], 1200),
(4, [3, 3, 3, 3, 0, 0], 600),
(3, [3, 3, 3, 0, 0, 0], 300),
(6, [4, 4, 4, 4, 4, 4], 3200),
(5, [4, 4, 4, 4, 4, 0], 1600),
(4, [4, 4, 4, 4, 0, 0], 800),
(3, [4, 4, 4, 0, 0, 0], 400),
(6, [5, 5, 5, 5, 5, 5], 4000),
(5, [5, 5, 5, 5, 5, 0], 2000),
(4, [5, 5, 5, 5, 0, 0], 1000),
(3, [5, 5, 5, 0, 0, 0], 500),
(1, [5, 0, 0, 0, 0, 0], 50),
(6, [6, 6, 6, 6, 6, 6], 4800),
(5, [6, 6, 6, 6, 6, 0], 2400),
(4, [6, 6, 6, 6, 0, 0], 1200),
(3, [6, 6, 6, 0, 0, 0], 600),
];
struct RollResult([u8; 6]);
#[inline]
fn is_prefix(rec: &ScoreRec, roll_res: &RollResult, start_idx: usize) -> bool {
let RollResult(ref roll_data) = *roll_res;
let (prefix_len, ref roll_target, _) = *rec;
if roll_data.len() < start_idx + prefix_len {
return false;
}
for idx in 0..prefix_len {
if roll_data[idx + start_idx]!= roll_target[idx] {
return false;
}
}
true
}
impl RollResult {
fn get_scores(&self) -> Vec<&'static ScoreRec> {
let RollResult(ref roll) = *self;
let mut idx = 0;
let mut score_comps = Vec::new();
while idx < roll.len() {
let mut idx_incr = 1;
for score_rec in SCORING_TABLE.iter() {
if is_prefix(score_rec, self, idx) {
let (prefix_len, _, _) = *score_rec;
idx_incr = prefix_len;
score_comps.push(score_rec);
break;
}
}
idx += idx_incr;
}
score_comps
}
fn total_score(&self) -> i32 {
let mut sum = 0;
for score in self.get_scores().iter() {
let (_, _, score_val) = **score;
sum += score_val;
}
sum
}
fn format_score_component_bare(score_pref: &ScorePrefix) -> String {
let mut rolls = String::new();
for value in score_pref.iter() {
if *value == 0 {
break
}
rolls.push_str(&format!("{}, ", value));
}
rolls.pop(); rolls.pop();
format!("{}", rolls)
}
fn format_score_component(score_components: &ScoreRec) -> String {
let (_, ref prefix_data, _) = *score_components;
RollResult::format_score_component_bare(prefix_data)
}
fn format_score(score_components: &Vec<&ScoreRec>) -> String {
let mut output = String::new();
for tuple in score_components.iter() {
let (_, _, score) = **tuple;
let roll_res = RollResult::format_score_component(*tuple);
output.push_str(&format!("[{} => {}], ", roll_res, score));
}
output.pop(); output.pop();
output
}
}
impl Rand for RollResult {
fn rand<R: Rng>(rng: &mut R) -> RollResult {
let mut out: ScorePrefix = [0u8; 6];
let mut between = Range::new(1u8, 7u8);
for val in out.iter_mut() {
*val = between.sample(rng);
}
out.sort();
RollResult(out)
}
}
impl fmt::Display for RollResult {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let RollResult(ref roll) = *self;
write!(f, "[{}] => [{}] for {} points",
RollResult::format_score_component_bare(roll),
RollResult::format_score(&self.get_scores()),
self.total_score())
}
}
pub struct GreedPlugin {
games: HashMap<ChannelId, GreedPlayResult>,
userstats: HashMap<UserId, UserStats>,
}
enum GreedCommandType {
Greed,
GreedStats
}
struct GreedPlayResult {
user_id: UserId,
user_nick: String,
roll: RollResult,
}
fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<GreedCommandType> {
match m.command().token {
CMD_GREED => Some(GreedCommandType::Greed),
CMD_GREED_STATS => Some(GreedCommandType::GreedStats),
_ => None
}
}
struct UserStats {
games: u32,
wins: u32,
score_sum: i32,
opponent_score_sum: i32
}
impl Default for UserStats {
fn default() -> UserStats {
UserStats {
games: 0,
wins: 0,
score_sum: 0,
opponent_score_sum: 0,
}
}
}
impl fmt::Display for UserStats {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{} wins over {} games; points: {}",
self.wins, self.games, self.score_sum - self.opponent_score_sum)
}
}
impl GreedPlugin {
pub fn new() -> GreedPlugin {
GreedPlugin {
games: HashMap::new(),
userstats: HashMap::new(),
}
}
pub fn get_plugin_name() -> &'static str {
"greed"
}
fn dispatch_cmd_greed_stats(&mut self, m: &CommandMapperDispatch, msg: &server::Privmsg) {
let user_id = match m.source {
KnownUser(user_id) => user_id,
_ => return
};
m.reply(match self.userstats.get(&user_id) {
Some(stats) => format!("{}: {}", msg.source_nick(), stats),
None => format!("{}: You haven't played any games yet", msg.source_nick())
}.as_ref());
}
fn add_userstats_roll(&mut self, uid: UserId, win: bool, self_score: i32, opp_score: i32) {
let cur_user = match self.userstats.entry(uid) {
hash_map::Entry::Occupied(entry) => entry.into_mut(),
hash_map::Entry::Vacant(entry) => entry.insert(Default::default())
};
cur_user.games += 1;
cur_user.wins += if win { 1 } else { 0 };
cur_user.score_sum += self_score;
cur_user.opponent_score_sum += opp_score;
}
fn dispatch_cmd_greed(&mut self, m: &CommandMapperDispatch, msg: &server::Privmsg) {
let (user_id, channel_id) = match (m.source.clone(), m.target.clone()) {
(KnownUser(uid), KnownChannel(cid)) => (uid, cid),
_ => return
};
let source_nick = msg.source_nick();
let prev_play_opt: Option<GreedPlayResult> = match self.games.entry(channel_id) {
hash_map::Entry::Vacant(entry) => {
let roll = thread_rng().gen::<RollResult>();
m.reply(&format!("{}: {}", source_nick, roll));
entry.insert(GreedPlayResult {
user_id: user_id,
user_nick: source_nick.to_string(),
roll: roll
});
None
},
hash_map::Entry::Occupied(entry) => {
if entry.get().user_id == user_id {
m.reply(&format!("You can't go twice in a row, {}", source_nick));
None
} else {
Some(entry.remove())
}
}
};
if let Some(prev_play) = prev_play_opt {
let roll = thread_rng().gen::<RollResult>();
m.reply(&format!("{}: {}", source_nick, roll));
|
let prev_play_nick = m.get_state().resolve_user(prev_play.user_id)
.and_then(|user: &User| Some(user.get_nick().to_string()))
.unwrap_or_else(|| format!("{} (deceased)", prev_play.user_nick));
let prev_play_score = prev_play.roll.total_score();
let cur_play_score = roll.total_score();
let cmp_result = prev_play_score.cmp(&cur_play_score);
let (prev_user_wins, cur_user_wins) = match cmp_result {
Ordering::Less => (false, true),
Ordering::Equal => (false, false),
Ordering::Greater => (true, false)
};
let score_diff = (prev_play_score - cur_play_score).abs();
let response = match cmp_result {
Ordering::Less => format!("{} wins {} points from {}!",
source_nick, score_diff, prev_play_nick),
Ordering::Equal => format!("{} and {} tie.", source_nick, prev_play_nick),
Ordering::Greater => format!("{} wins {} points from {}!",
prev_play_nick, score_diff, source_nick),
};
m.reply(&response);
self.add_userstats_roll(user_id, cur_user_wins,
cur_play_score, prev_play_score);
self.add_userstats_roll(prev_play.user_id, prev_user_wins,
prev_play_score, cur_play_score);
}
}
}
impl RustBotPlugin for GreedPlugin {
fn configure(&mut self, conf: &mut IrcBotConfigurator) {
conf.map_format(CMD_GREED, Format::from_str("greed").unwrap());
conf.map_format(CMD_GREED_STATS, Format::from_str("greed-stats").unwrap());
}
fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, msg: &IrcMsg) {
let privmsg;
match msg.as_tymsg::<&server::Privmsg>() {
Ok(p) => privmsg = p,
Err(_) => return,
}
match parse_command(m) {
Some(GreedCommandType::Greed) => self.dispatch_cmd_greed(m, privmsg),
Some(GreedCommandType::GreedStats) => self.dispatch_cmd_greed_stats(m, privmsg),
None => ()
}
}
}
|
random_line_split
|
|
population_builder.rs
|
//! This module defines helper functions (builder pattern) to create a valid population.
//!
//! darwin-rs: evolutionary algorithms with Rust
//!
//! Written by Willi Kappler, Version 0.4 (2017.06.26)
//!
//! Repository: https://github.com/willi-kappler/darwin-rs
//!
//! License: MIT
//!
//! This library allows you to write evolutionary algorithms (EA) in Rust.
//! Examples provided: TSP, Sudoku, Queens Problem, OCR
//!
//!
use std;
use individual::{Individual, IndividualWrapper};
use population::Population;
/// This is a helper struct in order to build (configure) a valid population.
/// See builder pattern: https://en.wikipedia.org/wiki/Builder_pattern
///
/// Maybe use phantom types, see https://github.com/willi-kappler/darwin-rs/issues/9
pub struct PopulationBuilder<T: Individual> {
/// The actual simulation
population: Population<T>,
}
error_chain! {
errors {
IndividualsTooLow
LimitEndTooLow
}
}
/// This implementation contains all the helper method to build (configure) a valid population.
impl<T: Individual + Clone> PopulationBuilder<T> {
/// Start with this method, it must always be called as the first one.
/// It creates a default population with some dummy (but invalid) values.
pub fn new() -> PopulationBuilder<T>
|
/// Sets the initial population provided inside a vector, length must be >= 3
pub fn initial_population(mut self, individuals: &[T]) -> PopulationBuilder<T> {
self.population.num_of_individuals = individuals.len() as u32;
for individual in individuals {
self.population.population.push(IndividualWrapper {
individual: (*individual).clone(),
fitness: std::f64::MAX,
num_of_mutations: 1,
id: self.population.id,
});
}
self
}
/// Configures the mutation rates (number of mutation runs) for all the individuals
/// in the population: The first individual will mutate once, the second will mutate twice,
/// the nth individual will Mutate n-times per iteration.
pub fn increasing_mutation_rate(mut self) -> PopulationBuilder<T> {
let mut mutation_rate = 1;
for wrapper in &mut self.population.population {
wrapper.num_of_mutations = mutation_rate;
mutation_rate += 1;
}
self
}
/// Configures the mutation rates (number of mutation runs) for all the individuals in the
/// population: Instead of a linear growing mutation rate like in the
/// `increasing_mutation_rate` function above this sets an exponention mutation rate for
/// all the individuals. The first individual will mutate base^1 times, the second will
/// mutate base^2 times, and nth will mutate base^n times per iteration.
pub fn increasing_exp_mutation_rate(mut self, base: f64) -> PopulationBuilder<T> {
let mut mutation_rate = 1;
for wrapper in &mut self.population.population {
wrapper.num_of_mutations = base.powi(mutation_rate).floor() as u32;
mutation_rate += 1;
}
self
}
/// Configures the mutation rates (number of mutation runs) for all the individuals in the
/// population: This allows to specify an arbitrary mutation scheme for each individual.
/// The number of rates must be equal to the number of individuals.
pub fn mutation_rate(mut self, mutation_rate: Vec<u32>) -> PopulationBuilder<T> {
// TODO: better error handling
assert!(self.population.population.len() == mutation_rate.len());
for (individual, mutation_rate) in self.population
.population
.iter_mut()
.zip(mutation_rate.into_iter()) {
individual.num_of_mutations = mutation_rate;
}
self
}
/// Configures the reset limit for the population. If reset_limit_end is greater than zero
/// then a reset counter is increased each iteration. If that counter is greater than the
/// limit, all individuals will be resetted, the limit will be increased by 1000 and the
/// counter is set back to zero. Default value for reset_limit_start is 1000.
pub fn reset_limit_start(mut self, reset_limit_start: u32) -> PopulationBuilder<T> {
self.population.reset_limit_start = reset_limit_start;
self.population.reset_limit = reset_limit_start;
self
}
/// Configures the end value for the reset_limit. If the reset_limit >= reset_limit_end
/// then the reset_limit will be resetted to the start value reset_limit_start.
/// Default value for reset_limit_end is 100000.
/// If reset_limit_end == 0 then the reset limit feature will be disabled.
pub fn reset_limit_end(mut self, reset_limit_end: u32) -> PopulationBuilder<T> {
self.population.reset_limit_end = reset_limit_end;
self
}
/// Configure the increment for the reset_limit. If the reset_limit is reached, its value
/// is incrementet by the amount of reset_limit_increment.
pub fn reset_limit_increment(mut self, reset_limit_increment: u32) -> PopulationBuilder<T> {
self.population.reset_limit_increment = reset_limit_increment;
self
}
/// Set the population id. Currently this is only used for statistics.
pub fn set_id(mut self, id: u32) -> PopulationBuilder<T> {
for individual in &mut self.population.population {
individual.id = id;
}
self.population.id = id;
self
}
/// This checks the configuration of the simulation and returns an PopError or Ok if no PopErrors
/// where found.
pub fn finalize(self) -> Result<Population<T>> {
match self.population {
Population { num_of_individuals: 0...2,..} => {
Err(ErrorKind::IndividualsTooLow.into())
}
Population { reset_limit_start: start,
reset_limit_end: end,..} if (end > 0) && (start >= end) => {
Err(ErrorKind::LimitEndTooLow.into())
}
_ => Ok(self.population)
}
}
}
|
{
PopulationBuilder {
population: Population {
num_of_individuals: 0,
population: Vec::new(),
reset_limit: 0,
reset_limit_start: 1000,
reset_limit_end: 10000,
reset_limit_increment: 1000,
reset_counter: 0,
id: 1,
fitness_counter: 0
}
}
}
|
identifier_body
|
population_builder.rs
|
//! This module defines helper functions (builder pattern) to create a valid population.
//!
//! darwin-rs: evolutionary algorithms with Rust
//!
//! Written by Willi Kappler, Version 0.4 (2017.06.26)
//!
//! Repository: https://github.com/willi-kappler/darwin-rs
//!
//! License: MIT
//!
//! This library allows you to write evolutionary algorithms (EA) in Rust.
//! Examples provided: TSP, Sudoku, Queens Problem, OCR
//!
//!
use std;
use individual::{Individual, IndividualWrapper};
use population::Population;
/// This is a helper struct in order to build (configure) a valid population.
/// See builder pattern: https://en.wikipedia.org/wiki/Builder_pattern
///
/// Maybe use phantom types, see https://github.com/willi-kappler/darwin-rs/issues/9
pub struct PopulationBuilder<T: Individual> {
/// The actual simulation
population: Population<T>,
}
error_chain! {
errors {
IndividualsTooLow
LimitEndTooLow
}
}
/// This implementation contains all the helper method to build (configure) a valid population.
impl<T: Individual + Clone> PopulationBuilder<T> {
/// Start with this method, it must always be called as the first one.
/// It creates a default population with some dummy (but invalid) values.
pub fn new() -> PopulationBuilder<T> {
PopulationBuilder {
population: Population {
num_of_individuals: 0,
population: Vec::new(),
reset_limit: 0,
reset_limit_start: 1000,
reset_limit_end: 10000,
reset_limit_increment: 1000,
reset_counter: 0,
id: 1,
fitness_counter: 0
}
}
}
/// Sets the initial population provided inside a vector, length must be >= 3
pub fn initial_population(mut self, individuals: &[T]) -> PopulationBuilder<T> {
self.population.num_of_individuals = individuals.len() as u32;
for individual in individuals {
self.population.population.push(IndividualWrapper {
individual: (*individual).clone(),
fitness: std::f64::MAX,
num_of_mutations: 1,
id: self.population.id,
});
}
self
}
/// Configures the mutation rates (number of mutation runs) for all the individuals
/// in the population: The first individual will mutate once, the second will mutate twice,
/// the nth individual will Mutate n-times per iteration.
pub fn increasing_mutation_rate(mut self) -> PopulationBuilder<T> {
let mut mutation_rate = 1;
for wrapper in &mut self.population.population {
wrapper.num_of_mutations = mutation_rate;
mutation_rate += 1;
}
self
}
/// Configures the mutation rates (number of mutation runs) for all the individuals in the
/// population: Instead of a linear growing mutation rate like in the
/// `increasing_mutation_rate` function above this sets an exponention mutation rate for
/// all the individuals. The first individual will mutate base^1 times, the second will
/// mutate base^2 times, and nth will mutate base^n times per iteration.
pub fn increasing_exp_mutation_rate(mut self, base: f64) -> PopulationBuilder<T> {
let mut mutation_rate = 1;
for wrapper in &mut self.population.population {
wrapper.num_of_mutations = base.powi(mutation_rate).floor() as u32;
mutation_rate += 1;
}
self
}
/// Configures the mutation rates (number of mutation runs) for all the individuals in the
/// population: This allows to specify an arbitrary mutation scheme for each individual.
/// The number of rates must be equal to the number of individuals.
pub fn mutation_rate(mut self, mutation_rate: Vec<u32>) -> PopulationBuilder<T> {
// TODO: better error handling
assert!(self.population.population.len() == mutation_rate.len());
for (individual, mutation_rate) in self.population
.population
.iter_mut()
.zip(mutation_rate.into_iter()) {
individual.num_of_mutations = mutation_rate;
}
self
}
/// Configures the reset limit for the population. If reset_limit_end is greater than zero
/// then a reset counter is increased each iteration. If that counter is greater than the
/// limit, all individuals will be resetted, the limit will be increased by 1000 and the
/// counter is set back to zero. Default value for reset_limit_start is 1000.
pub fn reset_limit_start(mut self, reset_limit_start: u32) -> PopulationBuilder<T> {
self.population.reset_limit_start = reset_limit_start;
self.population.reset_limit = reset_limit_start;
self
}
/// Configures the end value for the reset_limit. If the reset_limit >= reset_limit_end
/// then the reset_limit will be resetted to the start value reset_limit_start.
/// Default value for reset_limit_end is 100000.
|
}
/// Configure the increment for the reset_limit. If the reset_limit is reached, its value
/// is incrementet by the amount of reset_limit_increment.
pub fn reset_limit_increment(mut self, reset_limit_increment: u32) -> PopulationBuilder<T> {
self.population.reset_limit_increment = reset_limit_increment;
self
}
/// Set the population id. Currently this is only used for statistics.
pub fn set_id(mut self, id: u32) -> PopulationBuilder<T> {
for individual in &mut self.population.population {
individual.id = id;
}
self.population.id = id;
self
}
/// This checks the configuration of the simulation and returns an PopError or Ok if no PopErrors
/// where found.
pub fn finalize(self) -> Result<Population<T>> {
match self.population {
Population { num_of_individuals: 0...2,..} => {
Err(ErrorKind::IndividualsTooLow.into())
}
Population { reset_limit_start: start,
reset_limit_end: end,..} if (end > 0) && (start >= end) => {
Err(ErrorKind::LimitEndTooLow.into())
}
_ => Ok(self.population)
}
}
}
|
/// If reset_limit_end == 0 then the reset limit feature will be disabled.
pub fn reset_limit_end(mut self, reset_limit_end: u32) -> PopulationBuilder<T> {
self.population.reset_limit_end = reset_limit_end;
self
|
random_line_split
|
population_builder.rs
|
//! This module defines helper functions (builder pattern) to create a valid population.
//!
//! darwin-rs: evolutionary algorithms with Rust
//!
//! Written by Willi Kappler, Version 0.4 (2017.06.26)
//!
//! Repository: https://github.com/willi-kappler/darwin-rs
//!
//! License: MIT
//!
//! This library allows you to write evolutionary algorithms (EA) in Rust.
//! Examples provided: TSP, Sudoku, Queens Problem, OCR
//!
//!
use std;
use individual::{Individual, IndividualWrapper};
use population::Population;
/// This is a helper struct in order to build (configure) a valid population.
/// See builder pattern: https://en.wikipedia.org/wiki/Builder_pattern
///
/// Maybe use phantom types, see https://github.com/willi-kappler/darwin-rs/issues/9
pub struct PopulationBuilder<T: Individual> {
/// The actual simulation
population: Population<T>,
}
error_chain! {
errors {
IndividualsTooLow
LimitEndTooLow
}
}
/// This implementation contains all the helper method to build (configure) a valid population.
impl<T: Individual + Clone> PopulationBuilder<T> {
/// Start with this method, it must always be called as the first one.
/// It creates a default population with some dummy (but invalid) values.
pub fn new() -> PopulationBuilder<T> {
PopulationBuilder {
population: Population {
num_of_individuals: 0,
population: Vec::new(),
reset_limit: 0,
reset_limit_start: 1000,
reset_limit_end: 10000,
reset_limit_increment: 1000,
reset_counter: 0,
id: 1,
fitness_counter: 0
}
}
}
/// Sets the initial population provided inside a vector, length must be >= 3
pub fn initial_population(mut self, individuals: &[T]) -> PopulationBuilder<T> {
self.population.num_of_individuals = individuals.len() as u32;
for individual in individuals {
self.population.population.push(IndividualWrapper {
individual: (*individual).clone(),
fitness: std::f64::MAX,
num_of_mutations: 1,
id: self.population.id,
});
}
self
}
/// Configures the mutation rates (number of mutation runs) for all the individuals
/// in the population: The first individual will mutate once, the second will mutate twice,
/// the nth individual will Mutate n-times per iteration.
pub fn
|
(mut self) -> PopulationBuilder<T> {
let mut mutation_rate = 1;
for wrapper in &mut self.population.population {
wrapper.num_of_mutations = mutation_rate;
mutation_rate += 1;
}
self
}
/// Configures the mutation rates (number of mutation runs) for all the individuals in the
/// population: Instead of a linear growing mutation rate like in the
/// `increasing_mutation_rate` function above this sets an exponention mutation rate for
/// all the individuals. The first individual will mutate base^1 times, the second will
/// mutate base^2 times, and nth will mutate base^n times per iteration.
pub fn increasing_exp_mutation_rate(mut self, base: f64) -> PopulationBuilder<T> {
let mut mutation_rate = 1;
for wrapper in &mut self.population.population {
wrapper.num_of_mutations = base.powi(mutation_rate).floor() as u32;
mutation_rate += 1;
}
self
}
/// Configures the mutation rates (number of mutation runs) for all the individuals in the
/// population: This allows to specify an arbitrary mutation scheme for each individual.
/// The number of rates must be equal to the number of individuals.
pub fn mutation_rate(mut self, mutation_rate: Vec<u32>) -> PopulationBuilder<T> {
// TODO: better error handling
assert!(self.population.population.len() == mutation_rate.len());
for (individual, mutation_rate) in self.population
.population
.iter_mut()
.zip(mutation_rate.into_iter()) {
individual.num_of_mutations = mutation_rate;
}
self
}
/// Configures the reset limit for the population. If reset_limit_end is greater than zero
/// then a reset counter is increased each iteration. If that counter is greater than the
/// limit, all individuals will be resetted, the limit will be increased by 1000 and the
/// counter is set back to zero. Default value for reset_limit_start is 1000.
pub fn reset_limit_start(mut self, reset_limit_start: u32) -> PopulationBuilder<T> {
self.population.reset_limit_start = reset_limit_start;
self.population.reset_limit = reset_limit_start;
self
}
/// Configures the end value for the reset_limit. If the reset_limit >= reset_limit_end
/// then the reset_limit will be resetted to the start value reset_limit_start.
/// Default value for reset_limit_end is 100000.
/// If reset_limit_end == 0 then the reset limit feature will be disabled.
pub fn reset_limit_end(mut self, reset_limit_end: u32) -> PopulationBuilder<T> {
self.population.reset_limit_end = reset_limit_end;
self
}
/// Configure the increment for the reset_limit. If the reset_limit is reached, its value
/// is incrementet by the amount of reset_limit_increment.
pub fn reset_limit_increment(mut self, reset_limit_increment: u32) -> PopulationBuilder<T> {
self.population.reset_limit_increment = reset_limit_increment;
self
}
/// Set the population id. Currently this is only used for statistics.
pub fn set_id(mut self, id: u32) -> PopulationBuilder<T> {
for individual in &mut self.population.population {
individual.id = id;
}
self.population.id = id;
self
}
/// This checks the configuration of the simulation and returns an PopError or Ok if no PopErrors
/// where found.
pub fn finalize(self) -> Result<Population<T>> {
match self.population {
Population { num_of_individuals: 0...2,..} => {
Err(ErrorKind::IndividualsTooLow.into())
}
Population { reset_limit_start: start,
reset_limit_end: end,..} if (end > 0) && (start >= end) => {
Err(ErrorKind::LimitEndTooLow.into())
}
_ => Ok(self.population)
}
}
}
|
increasing_mutation_rate
|
identifier_name
|
internal_unstable.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(staged_api, allow_internal_unstable)]
#![staged_api]
#![stable(feature = "stable", since = "1.0.0")]
#[unstable(feature = "function", issue = "0")]
pub fn unstable()
|
#[stable(feature = "stable", since = "1.0.0")]
pub struct Foo {
#[unstable(feature = "struct_field", issue = "0")]
pub x: u8
}
impl Foo {
#[unstable(feature = "method", issue = "0")]
pub fn method(&self) {}
}
#[stable(feature = "stable", since = "1.0.0")]
pub struct Bar {
#[unstable(feature = "struct2_field", issue = "0")]
pub x: u8
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! call_unstable_allow {
() => { $crate::unstable() }
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! construct_unstable_allow {
($e: expr) => {
$crate::Foo { x: $e }
}
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! call_method_allow {
($e: expr) => { $e.method() }
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! access_field_allow {
($e: expr) => { $e.x }
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! pass_through_allow {
($e: expr) => { $e }
}
#[macro_export]
macro_rules! call_unstable_noallow {
() => { $crate::unstable() }
}
#[macro_export]
macro_rules! construct_unstable_noallow {
($e: expr) => {
$crate::Foo { x: $e }
}
}
#[macro_export]
macro_rules! call_method_noallow {
($e: expr) => { $e.method() }
}
#[macro_export]
macro_rules! access_field_noallow {
($e: expr) => { $e.x }
}
#[macro_export]
macro_rules! pass_through_noallow {
($e: expr) => { $e }
}
|
{}
|
identifier_body
|
internal_unstable.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(staged_api, allow_internal_unstable)]
#![staged_api]
#![stable(feature = "stable", since = "1.0.0")]
#[unstable(feature = "function", issue = "0")]
pub fn unstable() {}
#[stable(feature = "stable", since = "1.0.0")]
pub struct Foo {
#[unstable(feature = "struct_field", issue = "0")]
pub x: u8
}
impl Foo {
#[unstable(feature = "method", issue = "0")]
pub fn method(&self) {}
}
#[stable(feature = "stable", since = "1.0.0")]
pub struct Bar {
#[unstable(feature = "struct2_field", issue = "0")]
pub x: u8
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! call_unstable_allow {
() => { $crate::unstable() }
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! construct_unstable_allow {
($e: expr) => {
$crate::Foo { x: $e }
}
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! call_method_allow {
($e: expr) => { $e.method() }
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! access_field_allow {
($e: expr) => { $e.x }
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! pass_through_allow {
($e: expr) => { $e }
}
#[macro_export]
macro_rules! call_unstable_noallow {
() => { $crate::unstable() }
}
#[macro_export]
macro_rules! construct_unstable_noallow {
($e: expr) => {
$crate::Foo { x: $e }
}
}
#[macro_export]
macro_rules! call_method_noallow {
($e: expr) => { $e.method() }
}
#[macro_export]
macro_rules! access_field_noallow {
($e: expr) => { $e.x }
}
#[macro_export]
macro_rules! pass_through_noallow {
($e: expr) => { $e }
|
}
|
random_line_split
|
|
internal_unstable.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(staged_api, allow_internal_unstable)]
#![staged_api]
#![stable(feature = "stable", since = "1.0.0")]
#[unstable(feature = "function", issue = "0")]
pub fn unstable() {}
#[stable(feature = "stable", since = "1.0.0")]
pub struct Foo {
#[unstable(feature = "struct_field", issue = "0")]
pub x: u8
}
impl Foo {
#[unstable(feature = "method", issue = "0")]
pub fn
|
(&self) {}
}
#[stable(feature = "stable", since = "1.0.0")]
pub struct Bar {
#[unstable(feature = "struct2_field", issue = "0")]
pub x: u8
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! call_unstable_allow {
() => { $crate::unstable() }
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! construct_unstable_allow {
($e: expr) => {
$crate::Foo { x: $e }
}
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! call_method_allow {
($e: expr) => { $e.method() }
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! access_field_allow {
($e: expr) => { $e.x }
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! pass_through_allow {
($e: expr) => { $e }
}
#[macro_export]
macro_rules! call_unstable_noallow {
() => { $crate::unstable() }
}
#[macro_export]
macro_rules! construct_unstable_noallow {
($e: expr) => {
$crate::Foo { x: $e }
}
}
#[macro_export]
macro_rules! call_method_noallow {
($e: expr) => { $e.method() }
}
#[macro_export]
macro_rules! access_field_noallow {
($e: expr) => { $e.x }
}
#[macro_export]
macro_rules! pass_through_noallow {
($e: expr) => { $e }
}
|
method
|
identifier_name
|
binops.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.
// Binop corner cases
fn
|
() {
assert_eq!((), ());
assert!((!(()!= ())));
assert!((!(() < ())));
assert!((() <= ()));
assert!((!(() > ())));
assert!((() >= ()));
}
fn test_bool() {
assert!((!(true < false)));
assert!((!(true <= false)));
assert!((true > false));
assert!((true >= false));
assert!((false < true));
assert!((false <= true));
assert!((!(false > true)));
assert!((!(false >= true)));
// Bools support bitwise binops
assert_eq!(false & false, false);
assert_eq!(true & false, false);
assert_eq!(true & true, true);
assert_eq!(false | false, false);
assert_eq!(true | false, true);
assert_eq!(true | true, true);
assert_eq!(false ^ false, false);
assert_eq!(true ^ false, true);
assert_eq!(true ^ true, false);
}
fn test_box() {
assert_eq!(@10, @10);
}
fn test_ptr() {
unsafe {
let p1: *u8 = ::std::cast::transmute(0);
let p2: *u8 = ::std::cast::transmute(0);
let p3: *u8 = ::std::cast::transmute(1);
assert_eq!(p1, p2);
assert!(p1!= p3);
assert!(p1 < p3);
assert!(p1 <= p3);
assert!(p3 > p1);
assert!(p3 >= p3);
assert!(p1 <= p2);
assert!(p1 >= p2);
}
}
#[deriving(Eq)]
struct p {
x: int,
y: int,
}
fn p(x: int, y: int) -> p {
p {
x: x,
y: y
}
}
fn test_class() {
let q = p(1, 2);
let mut r = p(1, 2);
unsafe {
error2!("q = {:x}, r = {:x}",
(::std::cast::transmute::<*p, uint>(&q)),
(::std::cast::transmute::<*p, uint>(&r)));
}
assert_eq!(q, r);
r.y = 17;
assert!((r.y!= q.y));
assert_eq!(r.y, 17);
assert!((q!= r));
}
pub fn main() {
test_nil();
test_bool();
test_box();
test_ptr();
test_class();
}
|
test_nil
|
identifier_name
|
binops.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.
|
// 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.
// Binop corner cases
fn test_nil() {
assert_eq!((), ());
assert!((!(()!= ())));
assert!((!(() < ())));
assert!((() <= ()));
assert!((!(() > ())));
assert!((() >= ()));
}
fn test_bool() {
assert!((!(true < false)));
assert!((!(true <= false)));
assert!((true > false));
assert!((true >= false));
assert!((false < true));
assert!((false <= true));
assert!((!(false > true)));
assert!((!(false >= true)));
// Bools support bitwise binops
assert_eq!(false & false, false);
assert_eq!(true & false, false);
assert_eq!(true & true, true);
assert_eq!(false | false, false);
assert_eq!(true | false, true);
assert_eq!(true | true, true);
assert_eq!(false ^ false, false);
assert_eq!(true ^ false, true);
assert_eq!(true ^ true, false);
}
fn test_box() {
assert_eq!(@10, @10);
}
fn test_ptr() {
unsafe {
let p1: *u8 = ::std::cast::transmute(0);
let p2: *u8 = ::std::cast::transmute(0);
let p3: *u8 = ::std::cast::transmute(1);
assert_eq!(p1, p2);
assert!(p1!= p3);
assert!(p1 < p3);
assert!(p1 <= p3);
assert!(p3 > p1);
assert!(p3 >= p3);
assert!(p1 <= p2);
assert!(p1 >= p2);
}
}
#[deriving(Eq)]
struct p {
x: int,
y: int,
}
fn p(x: int, y: int) -> p {
p {
x: x,
y: y
}
}
fn test_class() {
let q = p(1, 2);
let mut r = p(1, 2);
unsafe {
error2!("q = {:x}, r = {:x}",
(::std::cast::transmute::<*p, uint>(&q)),
(::std::cast::transmute::<*p, uint>(&r)));
}
assert_eq!(q, r);
r.y = 17;
assert!((r.y!= q.y));
assert_eq!(r.y, 17);
assert!((q!= r));
}
pub fn main() {
test_nil();
test_bool();
test_box();
test_ptr();
test_class();
}
|
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
random_line_split
|
euclid.rs
|
struct UnknownUnit;
struct LayoutUnit;
#[repr(C)]
struct TypedLength<T, Unit>(T, PhantomData<Unit>);
#[repr(C)]
struct TypedSideOffsets2D<T, U> {
top: T,
right: T,
bottom: T,
left: T,
_phantom: PhantomData<U>,
}
#[repr(C)]
struct TypedSize2D<T, U> {
width: T,
height: T,
_phantom: PhantomData<U>,
}
#[repr(C)]
struct TypedPoint2D<T, U> {
x: T,
y: T,
_phantom: PhantomData<U>,
}
#[repr(C)]
struct TypedRect<T, U> {
origin: TypedPoint2D<T, U>,
size: TypedSize2D<T, U>,
_phantom: PhantomData<U>,
}
#[repr(C)]
struct TypedTransform2D<T, Src, Dst> {
m11: T, m12: T,
m21: T, m22: T,
m31: T, m32: T,
_phantom: PhantomData<U>,
}
type Length<T> = TypedLength<T, UnknownUnit>;
type SideOffsets2D<T> = TypedSideOffsets2D<T, UnknownUnit>;
type Size2D<T> = TypedSize2D<T, UnknownUnit>;
type Point2D<T> = TypedPoint2D<T, UnknownUnit>;
type Rect<T> = TypedRect<T, UnknownUnit>;
type LayoutLength = TypedLength<f32, LayoutUnit>;
type LayoutSideOffsets2D = TypedSideOffsets2D<f32, LayoutUnit>;
type LayoutSize2D = TypedSize2D<f32, LayoutUnit>;
type LayoutPoint2D = TypedPoint2D<f32, LayoutUnit>;
type LayoutRect = TypedRect<f32, LayoutUnit>;
#[no_mangle]
pub extern "C" fn root(
length_a: TypedLength<f32, UnknownUnit>,
length_b: TypedLength<f32, LayoutUnit>,
length_c: Length<f32>,
length_d: LayoutLength,
side_offsets_a: TypedSideOffsets2D<f32, UnknownUnit>,
side_offsets_b: TypedSideOffsets2D<f32, LayoutUnit>,
side_offsets_c: SideOffsets2D<f32>,
side_offsets_d: LayoutSideOffsets2D,
size_a: TypedSize2D<f32, UnknownUnit>,
size_b: TypedSize2D<f32, LayoutUnit>,
size_c: Size2D<f32>,
size_d: LayoutSize2D,
point_a: TypedPoint2D<f32, UnknownUnit>,
point_b: TypedPoint2D<f32, LayoutUnit>,
point_c: Point2D<f32>,
point_d: LayoutPoint2D,
rect_a: TypedRect<f32, UnknownUnit>,
rect_b: TypedRect<f32, LayoutUnit>,
rect_c: Rect<f32>,
rect_d: LayoutRect,
transform_a: TypedTransform2D<f32, UnknownUnit, LayoutUnit>,
|
transform_b: TypedTransform2D<f32, LayoutUnit, UnknownUnit>
) { }
|
random_line_split
|
|
euclid.rs
|
struct UnknownUnit;
struct LayoutUnit;
#[repr(C)]
struct TypedLength<T, Unit>(T, PhantomData<Unit>);
#[repr(C)]
struct
|
<T, U> {
top: T,
right: T,
bottom: T,
left: T,
_phantom: PhantomData<U>,
}
#[repr(C)]
struct TypedSize2D<T, U> {
width: T,
height: T,
_phantom: PhantomData<U>,
}
#[repr(C)]
struct TypedPoint2D<T, U> {
x: T,
y: T,
_phantom: PhantomData<U>,
}
#[repr(C)]
struct TypedRect<T, U> {
origin: TypedPoint2D<T, U>,
size: TypedSize2D<T, U>,
_phantom: PhantomData<U>,
}
#[repr(C)]
struct TypedTransform2D<T, Src, Dst> {
m11: T, m12: T,
m21: T, m22: T,
m31: T, m32: T,
_phantom: PhantomData<U>,
}
type Length<T> = TypedLength<T, UnknownUnit>;
type SideOffsets2D<T> = TypedSideOffsets2D<T, UnknownUnit>;
type Size2D<T> = TypedSize2D<T, UnknownUnit>;
type Point2D<T> = TypedPoint2D<T, UnknownUnit>;
type Rect<T> = TypedRect<T, UnknownUnit>;
type LayoutLength = TypedLength<f32, LayoutUnit>;
type LayoutSideOffsets2D = TypedSideOffsets2D<f32, LayoutUnit>;
type LayoutSize2D = TypedSize2D<f32, LayoutUnit>;
type LayoutPoint2D = TypedPoint2D<f32, LayoutUnit>;
type LayoutRect = TypedRect<f32, LayoutUnit>;
#[no_mangle]
pub extern "C" fn root(
length_a: TypedLength<f32, UnknownUnit>,
length_b: TypedLength<f32, LayoutUnit>,
length_c: Length<f32>,
length_d: LayoutLength,
side_offsets_a: TypedSideOffsets2D<f32, UnknownUnit>,
side_offsets_b: TypedSideOffsets2D<f32, LayoutUnit>,
side_offsets_c: SideOffsets2D<f32>,
side_offsets_d: LayoutSideOffsets2D,
size_a: TypedSize2D<f32, UnknownUnit>,
size_b: TypedSize2D<f32, LayoutUnit>,
size_c: Size2D<f32>,
size_d: LayoutSize2D,
point_a: TypedPoint2D<f32, UnknownUnit>,
point_b: TypedPoint2D<f32, LayoutUnit>,
point_c: Point2D<f32>,
point_d: LayoutPoint2D,
rect_a: TypedRect<f32, UnknownUnit>,
rect_b: TypedRect<f32, LayoutUnit>,
rect_c: Rect<f32>,
rect_d: LayoutRect,
transform_a: TypedTransform2D<f32, UnknownUnit, LayoutUnit>,
transform_b: TypedTransform2D<f32, LayoutUnit, UnknownUnit>
) { }
|
TypedSideOffsets2D
|
identifier_name
|
variable-scope.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-test
// compile-flags:-Z extra-debug-info
// debugger:break zzz
// debugger:run
// debugger:finish
// debugger:print x
// check:$1 = false
// debugger:print y
// check:$2 = true
// debugger:continue
// debugger:finish
// debugger:print x
// check:$3 = 10
// debugger:continue
// debugger:finish
// debugger:print x
// check:$4 = false
// debugger:print y
// check:$5 = 11
fn main()
|
fn zzz() {()}
|
{
let x = false;
let y = true;
zzz();
{
let x = 10;
zzz();
}
let y = 11;
zzz();
}
|
identifier_body
|
variable-scope.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-test
// compile-flags:-Z extra-debug-info
// debugger:break zzz
// debugger:run
// debugger:finish
// debugger:print x
// check:$1 = false
// debugger:print y
// check:$2 = true
// debugger:continue
// debugger:finish
// debugger:print x
// check:$3 = 10
// debugger:continue
// debugger:finish
// debugger:print x
// check:$4 = false
// debugger:print y
// check:$5 = 11
fn main() {
let x = false;
let y = true;
zzz();
{
let x = 10;
zzz();
}
let y = 11;
zzz();
}
fn
|
() {()}
|
zzz
|
identifier_name
|
variable-scope.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
|
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-test
// compile-flags:-Z extra-debug-info
// debugger:break zzz
// debugger:run
// debugger:finish
// debugger:print x
// check:$1 = false
// debugger:print y
// check:$2 = true
// debugger:continue
// debugger:finish
// debugger:print x
// check:$3 = 10
// debugger:continue
// debugger:finish
// debugger:print x
// check:$4 = false
// debugger:print y
// check:$5 = 11
fn main() {
let x = false;
let y = true;
zzz();
{
let x = 10;
zzz();
}
let y = 11;
zzz();
}
fn zzz() {()}
|
random_line_split
|
|
builder.rs
|
// Copyright (c) 2015 Takeru Ohta <[email protected]>
//
// This software is released under the MIT License,
// see the LICENSE file at the top-level directory.
use std::mem;
use std::collections::HashMap;
use std::rc::Rc;
use std::error::Error;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Error as FmtError;
use binary_tree::Node;
use binary_tree::Trie;
use EOS;
use Char;
use Word;
pub struct Builder {
memo: Memo,
root: Node,
}
type Memo = HashMap<Rc<Node>, Rc<Node>>;
impl Builder {
|
pub fn new() -> Self {
Builder {
memo: Memo::new(),
root: Node::new(EOS),
}
}
pub fn insert(&mut self, word: Word) -> InsertResult {
let mut root = mem::replace(&mut self.root, Node::new(EOS));
try!(self.insert_word(&mut root, word));
self.root = root;
Ok(())
}
pub fn finish(mut self) -> Trie {
let mut root = mem::replace(&mut self.root, Node::new(EOS));
self.share_children(&mut root);
root.fix();
Trie::new(root)
}
fn insert_word(&mut self, parent: &mut Node, mut word: Word) -> InsertResult {
match word.next() {
Some(ch) if parent.child.as_ref().map_or(false, |c| c.ch == ch) => {
let child = parent.child.as_mut().unwrap();
self.insert_word(Rc::get_mut(child).unwrap(), word)
}
next_ch => self.add_new_child(parent, next_ch, word),
}
}
fn add_new_child(&mut self,
parent: &mut Node,
ch: Option<Char>,
mut word: Word)
-> InsertResult {
match ch {
None => {
parent.is_terminal = true;
Ok(())
}
Some(ch) => {
if ch == EOS {
return Err(InsertError::Eos);
}
if parent.child.as_ref().map_or(false, |c| c.ch > ch) {
return Err(InsertError::Unsorted);
}
let mut child = Node::new(ch);
try!(self.add_new_child(&mut child, word.next(), word));
child.sibling = parent.child.take().map(|c| self.share(c));
parent.child = Some(Rc::new(child));
Ok(())
}
}
}
fn share(&mut self, mut node: Rc<Node>) -> Rc<Node> {
if let Some(n) = self.memo.get(&node) {
return n.clone();
}
self.share_children(Rc::get_mut(&mut node).unwrap());
if let Some(n) = self.memo.get(&node) {
return n.clone();
}
Rc::get_mut(&mut node).unwrap().fix();
self.memo.insert(node.clone(), node.clone());
node
}
fn share_children(&mut self, node: &mut Node) {
node.sibling = node.sibling.take().map(|n| self.share(n));
node.child = node.child.take().map(|n| self.share(n));
}
}
pub type InsertResult = Result<(), InsertError>;
#[derive(Debug)]
pub enum InsertError {
Eos,
Unsorted,
}
impl Error for InsertError {
fn description(&self) -> &str {
match self {
&InsertError::Eos => "unexpected eos",
&InsertError::Unsorted => "unsorted words",
}
}
}
impl Display for InsertError {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
let reason = match self {
&InsertError::Eos => "a word can not have the EOS character",
&InsertError::Unsorted => "words are not sorted",
};
f.write_str(reason)
}
}
|
random_line_split
|
|
builder.rs
|
// Copyright (c) 2015 Takeru Ohta <[email protected]>
//
// This software is released under the MIT License,
// see the LICENSE file at the top-level directory.
use std::mem;
use std::collections::HashMap;
use std::rc::Rc;
use std::error::Error;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Error as FmtError;
use binary_tree::Node;
use binary_tree::Trie;
use EOS;
use Char;
use Word;
pub struct Builder {
memo: Memo,
root: Node,
}
type Memo = HashMap<Rc<Node>, Rc<Node>>;
impl Builder {
pub fn new() -> Self {
Builder {
memo: Memo::new(),
root: Node::new(EOS),
}
}
pub fn insert(&mut self, word: Word) -> InsertResult {
let mut root = mem::replace(&mut self.root, Node::new(EOS));
try!(self.insert_word(&mut root, word));
self.root = root;
Ok(())
}
pub fn finish(mut self) -> Trie {
let mut root = mem::replace(&mut self.root, Node::new(EOS));
self.share_children(&mut root);
root.fix();
Trie::new(root)
}
fn insert_word(&mut self, parent: &mut Node, mut word: Word) -> InsertResult {
match word.next() {
Some(ch) if parent.child.as_ref().map_or(false, |c| c.ch == ch) => {
let child = parent.child.as_mut().unwrap();
self.insert_word(Rc::get_mut(child).unwrap(), word)
}
next_ch => self.add_new_child(parent, next_ch, word),
}
}
fn
|
(&mut self,
parent: &mut Node,
ch: Option<Char>,
mut word: Word)
-> InsertResult {
match ch {
None => {
parent.is_terminal = true;
Ok(())
}
Some(ch) => {
if ch == EOS {
return Err(InsertError::Eos);
}
if parent.child.as_ref().map_or(false, |c| c.ch > ch) {
return Err(InsertError::Unsorted);
}
let mut child = Node::new(ch);
try!(self.add_new_child(&mut child, word.next(), word));
child.sibling = parent.child.take().map(|c| self.share(c));
parent.child = Some(Rc::new(child));
Ok(())
}
}
}
fn share(&mut self, mut node: Rc<Node>) -> Rc<Node> {
if let Some(n) = self.memo.get(&node) {
return n.clone();
}
self.share_children(Rc::get_mut(&mut node).unwrap());
if let Some(n) = self.memo.get(&node) {
return n.clone();
}
Rc::get_mut(&mut node).unwrap().fix();
self.memo.insert(node.clone(), node.clone());
node
}
fn share_children(&mut self, node: &mut Node) {
node.sibling = node.sibling.take().map(|n| self.share(n));
node.child = node.child.take().map(|n| self.share(n));
}
}
pub type InsertResult = Result<(), InsertError>;
#[derive(Debug)]
pub enum InsertError {
Eos,
Unsorted,
}
impl Error for InsertError {
fn description(&self) -> &str {
match self {
&InsertError::Eos => "unexpected eos",
&InsertError::Unsorted => "unsorted words",
}
}
}
impl Display for InsertError {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
let reason = match self {
&InsertError::Eos => "a word can not have the EOS character",
&InsertError::Unsorted => "words are not sorted",
};
f.write_str(reason)
}
}
|
add_new_child
|
identifier_name
|
builder.rs
|
// Copyright (c) 2015 Takeru Ohta <[email protected]>
//
// This software is released under the MIT License,
// see the LICENSE file at the top-level directory.
use std::mem;
use std::collections::HashMap;
use std::rc::Rc;
use std::error::Error;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Error as FmtError;
use binary_tree::Node;
use binary_tree::Trie;
use EOS;
use Char;
use Word;
pub struct Builder {
memo: Memo,
root: Node,
}
type Memo = HashMap<Rc<Node>, Rc<Node>>;
impl Builder {
pub fn new() -> Self {
Builder {
memo: Memo::new(),
root: Node::new(EOS),
}
}
pub fn insert(&mut self, word: Word) -> InsertResult {
let mut root = mem::replace(&mut self.root, Node::new(EOS));
try!(self.insert_word(&mut root, word));
self.root = root;
Ok(())
}
pub fn finish(mut self) -> Trie {
let mut root = mem::replace(&mut self.root, Node::new(EOS));
self.share_children(&mut root);
root.fix();
Trie::new(root)
}
fn insert_word(&mut self, parent: &mut Node, mut word: Word) -> InsertResult
|
fn add_new_child(&mut self,
parent: &mut Node,
ch: Option<Char>,
mut word: Word)
-> InsertResult {
match ch {
None => {
parent.is_terminal = true;
Ok(())
}
Some(ch) => {
if ch == EOS {
return Err(InsertError::Eos);
}
if parent.child.as_ref().map_or(false, |c| c.ch > ch) {
return Err(InsertError::Unsorted);
}
let mut child = Node::new(ch);
try!(self.add_new_child(&mut child, word.next(), word));
child.sibling = parent.child.take().map(|c| self.share(c));
parent.child = Some(Rc::new(child));
Ok(())
}
}
}
fn share(&mut self, mut node: Rc<Node>) -> Rc<Node> {
if let Some(n) = self.memo.get(&node) {
return n.clone();
}
self.share_children(Rc::get_mut(&mut node).unwrap());
if let Some(n) = self.memo.get(&node) {
return n.clone();
}
Rc::get_mut(&mut node).unwrap().fix();
self.memo.insert(node.clone(), node.clone());
node
}
fn share_children(&mut self, node: &mut Node) {
node.sibling = node.sibling.take().map(|n| self.share(n));
node.child = node.child.take().map(|n| self.share(n));
}
}
pub type InsertResult = Result<(), InsertError>;
#[derive(Debug)]
pub enum InsertError {
Eos,
Unsorted,
}
impl Error for InsertError {
fn description(&self) -> &str {
match self {
&InsertError::Eos => "unexpected eos",
&InsertError::Unsorted => "unsorted words",
}
}
}
impl Display for InsertError {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
let reason = match self {
&InsertError::Eos => "a word can not have the EOS character",
&InsertError::Unsorted => "words are not sorted",
};
f.write_str(reason)
}
}
|
{
match word.next() {
Some(ch) if parent.child.as_ref().map_or(false, |c| c.ch == ch) => {
let child = parent.child.as_mut().unwrap();
self.insert_word(Rc::get_mut(child).unwrap(), word)
}
next_ch => self.add_new_child(parent, next_ch, word),
}
}
|
identifier_body
|
error.rs
|
use std::collections::HashSet;
use std::io;
use serde::{Deserializer, Deserialize};
use reqwest;
#[derive(Fail, Debug)]
|
Reqwest(#[cause] reqwest::Error),
#[fail(display = "{}", _0)]
Io(#[cause] io::Error),
}
impl From<reqwest::Error> for Error {
fn from(err: reqwest::Error) -> Error {
Error::Reqwest(err)
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::Io(err)
}
}
#[derive(PartialEq, Eq, Hash, Debug)]
pub enum Code {
MissingSecret,
InvalidSecret,
MissingResponse,
InvalidResponse,
BadRequest,
TimeoutOrDuplicate,
Unknown(String)
}
impl<'de> Deserialize<'de> for Code {
fn deserialize<D>(de: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>
{
let code = String::deserialize(de)?;
Ok(match &*code {
"missing-input-secret" => Code::MissingSecret,
"invalid-input-secret" => Code::InvalidSecret,
"missing-input-response" => Code::MissingResponse,
"invalid-input-response" => Code::InvalidResponse,
"bad-request" => Code::BadRequest,
"timeout-or-duplicate" => Code::TimeoutOrDuplicate,
_ => Code::Unknown(code),
})
}
}
|
pub enum Error {
#[fail(display = "{:?}", _0)]
Codes(HashSet<Code>),
#[fail(display = "{}", _0)]
|
random_line_split
|
error.rs
|
use std::collections::HashSet;
use std::io;
use serde::{Deserializer, Deserialize};
use reqwest;
#[derive(Fail, Debug)]
pub enum Error {
#[fail(display = "{:?}", _0)]
Codes(HashSet<Code>),
#[fail(display = "{}", _0)]
Reqwest(#[cause] reqwest::Error),
#[fail(display = "{}", _0)]
Io(#[cause] io::Error),
}
impl From<reqwest::Error> for Error {
fn
|
(err: reqwest::Error) -> Error {
Error::Reqwest(err)
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::Io(err)
}
}
#[derive(PartialEq, Eq, Hash, Debug)]
pub enum Code {
MissingSecret,
InvalidSecret,
MissingResponse,
InvalidResponse,
BadRequest,
TimeoutOrDuplicate,
Unknown(String)
}
impl<'de> Deserialize<'de> for Code {
fn deserialize<D>(de: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>
{
let code = String::deserialize(de)?;
Ok(match &*code {
"missing-input-secret" => Code::MissingSecret,
"invalid-input-secret" => Code::InvalidSecret,
"missing-input-response" => Code::MissingResponse,
"invalid-input-response" => Code::InvalidResponse,
"bad-request" => Code::BadRequest,
"timeout-or-duplicate" => Code::TimeoutOrDuplicate,
_ => Code::Unknown(code),
})
}
}
|
from
|
identifier_name
|
cnf_system.rs
|
use std::collections::{BTreeSet, HashSet};
use std::collections::btree_set::Iter;
#[allow(dead_code)]
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub enum ClauseType {
Tautology, // Always true -- all interpretations are models
Satisfiable, // Sometimes true -- has some models
Unsatisfiable, // Never true -- no models
}
#[derive(Eq, PartialEq, Hash, Clone, Debug)]
/// A clause in clausal normal form (CNF) i.e. a disjunction (∨) of literals
pub struct CNFClause {
// Ordered set of literals, as order doesn't matter and the amount of times a literal occurs
// doesn't matter: (a ∨ a) <=> (a)
literals: BTreeSet<isize>,
}
impl CNFClause {
pub fn new() -> CNFClause {
CNFClause{ literals: BTreeSet::new() }
}
/// Add a new literal to the clause
/// Returns true if value was not already present in the set
pub fn add(&mut self, literal: isize) -> bool {
match literal {
0 => panic!("Can't insert a literal of value zero"),
x => self.literals.insert(x),
}
}
/// Removes a literal from the set, returning true if value was present in the set
pub fn remove(&mut self, literal: &isize) -> bool {
self.literals.remove(&literal)
}
/// Returns an iterator over the literals
pub fn iter(&self) -> Iter<isize> {
self.literals.iter()
}
/// Returns true if this clause contains the literal
pub fn contains(&self, literal: isize) -> bool {
self.literals.contains(&literal)
}
/// Returns the amount of elements in the set
pub fn len(&self) -> usize {
self.literals.len()
}
} // impl CNFClause
#[test]
fn test_cnf_clause() {
let t1: isize = 1;
let f1: isize = -1;
let mut clause = CNFClause::new();
clause.add(t1);
clause.add(f1);
// Assert n1,¬n1 is a tautology
assert!(clause.is_tautology());
clause.remove(&t1);
let mut clause2 = CNFClause::new();
clause2.add(f1);
assert_eq!(clause, clause2);
clause.remove(&-1);
assert_eq!(clause, CNFClause::new());
// Clear
let mut clause = CNFClause::new();
let mut clause2 = CNFClause::new();
clause.add(-5);
clause.add(4);
clause.add(2);
// Add n2 and assert it contains() it
clause2.add(2);
assert!(clause2.contains(2));
// Remove it and assert it doesn't contain it and it's length is zero
clause2.remove(&2);
assert!(!clause2.contains(2));
assert_eq!(0, clause2.len());
// Now make clause and clause2 have the equivalent literals in reverse order
clause2.add(2);
clause2.add(4);
clause2.add(-5);
//...and assert they're still equal because it should be a sorted set
assert_eq!(clause, clause2);
// they shouldn't be tautologies yet...
assert!(!clause.is_tautology());
assert!(!clause2.is_tautology());
//...but now they should be!
clause2.add(-2);
assert!(clause!= clause2);
clause.add(-2);
|
assert_eq!(clause, clause2);
}
/// A conjunction (∧) of clauses
#[derive(Eq, PartialEq, Clone, Debug)]
pub struct CNFSystem {
pub clauses: HashSet<CNFClause>,
}
impl CNFSystem {
pub fn new(initial_clauses: Option<HashSet<CNFClause>>) -> CNFSystem {
match initial_clauses {
Some(c) => CNFSystem{ clauses: c, },
None => CNFSystem{ clauses: HashSet::new(), },
}
}
/// Add a clause to the system. Returns false if the value was already in the system
pub fn add_clause(&mut self, clause: CNFClause) -> bool {
self.clauses.insert(clause)
}
/// Removes a clause from the system. Returns false if the value wasn't already in the system
pub fn remove_clause(&mut self, clause: &CNFClause) -> bool {
self.clauses.remove(clause)
}
/// Return the amount of clauses in the system
pub fn len(&self) -> usize {
self.clauses.len()
}
}
|
assert_eq!(clause, clause2);
assert!(clause.is_tautology());
// Assert that adding the same element means they're still equal (it's a set)
clause2.add(2);
|
random_line_split
|
cnf_system.rs
|
use std::collections::{BTreeSet, HashSet};
use std::collections::btree_set::Iter;
#[allow(dead_code)]
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub enum ClauseType {
Tautology, // Always true -- all interpretations are models
Satisfiable, // Sometimes true -- has some models
Unsatisfiable, // Never true -- no models
}
#[derive(Eq, PartialEq, Hash, Clone, Debug)]
/// A clause in clausal normal form (CNF) i.e. a disjunction (∨) of literals
pub struct CNFClause {
// Ordered set of literals, as order doesn't matter and the amount of times a literal occurs
// doesn't matter: (a ∨ a) <=> (a)
literals: BTreeSet<isize>,
}
impl CNFClause {
pub fn new() -> CNFClause {
CNFClause{ literals: BTreeSet::new() }
}
/// Add a new literal to the clause
/// Returns true if value was not already present in the set
pub fn add(&mut self, literal: isize) -> bool {
match literal {
0 => panic!("Can't insert a literal of value zero"),
x => self.literals.insert(x),
}
}
/// Removes a literal from the set, returning true if value was present in the set
pub fn remove(&mut self, literal: &isize) -> bool {
self.literals.remove(&literal)
}
/// Returns an iterator over the literals
pub fn iter(&self) -> Iter<isize> {
self.literals.iter()
}
/// Returns true if this clause contains the literal
pub fn contains(&self, literal: isize) -> bool {
self.literals.contains(&literal)
}
/// Returns the amount of elements in the set
pub fn len(&self) -> usize {
self.literals.len()
}
} // impl CNFClause
#[test]
fn test_cnf_clause() {
let t1: isize = 1;
let f1: isize = -1;
let mut clause = CNFClause::new();
clause.add(t1);
clause.add(f1);
// Assert n1,¬n1 is a tautology
assert!(clause.is_tautology());
clause.remove(&t1);
let mut clause2 = CNFClause::new();
clause2.add(f1);
assert_eq!(clause, clause2);
clause.remove(&-1);
assert_eq!(clause, CNFClause::new());
// Clear
let mut clause = CNFClause::new();
let mut clause2 = CNFClause::new();
clause.add(-5);
clause.add(4);
clause.add(2);
// Add n2 and assert it contains() it
clause2.add(2);
assert!(clause2.contains(2));
// Remove it and assert it doesn't contain it and it's length is zero
clause2.remove(&2);
assert!(!clause2.contains(2));
assert_eq!(0, clause2.len());
// Now make clause and clause2 have the equivalent literals in reverse order
clause2.add(2);
clause2.add(4);
clause2.add(-5);
//...and assert they're still equal because it should be a sorted set
assert_eq!(clause, clause2);
// they shouldn't be tautologies yet...
assert!(!clause.is_tautology());
assert!(!clause2.is_tautology());
//...but now they should be!
clause2.add(-2);
assert!(clause!= clause2);
clause.add(-2);
assert_eq!(clause, clause2);
assert!(clause.is_tautology());
// Assert that adding the same element means they're still equal (it's a set)
clause2.add(2);
assert_eq!(clause, clause2);
}
/// A conjunction (∧) of clauses
#[derive(Eq, PartialEq, Clone, Debug)]
pub struct CNFSystem {
pub clauses: HashSet<CNFClause>,
}
impl CNFSystem {
pub fn new(initial_clauses: Option<HashSet<CNFClause>>) -> CNFSystem {
match initial_clauses {
Some(c) => CNFSystem{ clauses: c, },
None => CNFSystem{ clauses: HashSet::new(), },
}
}
/// Add a clause to the system. Returns false if the value was already in the system
pub fn add_clause(&mut self, clause: CNFClause) -> bool {
|
// Removes a clause from the system. Returns false if the value wasn't already in the system
pub fn remove_clause(&mut self, clause: &CNFClause) -> bool {
self.clauses.remove(clause)
}
/// Return the amount of clauses in the system
pub fn len(&self) -> usize {
self.clauses.len()
}
}
|
self.clauses.insert(clause)
}
/
|
identifier_body
|
cnf_system.rs
|
use std::collections::{BTreeSet, HashSet};
use std::collections::btree_set::Iter;
#[allow(dead_code)]
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub enum ClauseType {
Tautology, // Always true -- all interpretations are models
Satisfiable, // Sometimes true -- has some models
Unsatisfiable, // Never true -- no models
}
#[derive(Eq, PartialEq, Hash, Clone, Debug)]
/// A clause in clausal normal form (CNF) i.e. a disjunction (∨) of literals
pub struct CNFClause {
// Ordered set of literals, as order doesn't matter and the amount of times a literal occurs
// doesn't matter: (a ∨ a) <=> (a)
literals: BTreeSet<isize>,
}
impl CNFClause {
pub fn new() -> CNFClause {
CNFClause{ literals: BTreeSet::new() }
}
/// Add a new literal to the clause
/// Returns true if value was not already present in the set
pub fn add(&mut self, literal: isize) -> bool {
match literal {
0 => panic!("Can't insert a literal of value zero"),
x => self.literals.insert(x),
}
}
/// Removes a literal from the set, returning true if value was present in the set
pub fn remo
|
t self, literal: &isize) -> bool {
self.literals.remove(&literal)
}
/// Returns an iterator over the literals
pub fn iter(&self) -> Iter<isize> {
self.literals.iter()
}
/// Returns true if this clause contains the literal
pub fn contains(&self, literal: isize) -> bool {
self.literals.contains(&literal)
}
/// Returns the amount of elements in the set
pub fn len(&self) -> usize {
self.literals.len()
}
} // impl CNFClause
#[test]
fn test_cnf_clause() {
let t1: isize = 1;
let f1: isize = -1;
let mut clause = CNFClause::new();
clause.add(t1);
clause.add(f1);
// Assert n1,¬n1 is a tautology
assert!(clause.is_tautology());
clause.remove(&t1);
let mut clause2 = CNFClause::new();
clause2.add(f1);
assert_eq!(clause, clause2);
clause.remove(&-1);
assert_eq!(clause, CNFClause::new());
// Clear
let mut clause = CNFClause::new();
let mut clause2 = CNFClause::new();
clause.add(-5);
clause.add(4);
clause.add(2);
// Add n2 and assert it contains() it
clause2.add(2);
assert!(clause2.contains(2));
// Remove it and assert it doesn't contain it and it's length is zero
clause2.remove(&2);
assert!(!clause2.contains(2));
assert_eq!(0, clause2.len());
// Now make clause and clause2 have the equivalent literals in reverse order
clause2.add(2);
clause2.add(4);
clause2.add(-5);
//...and assert they're still equal because it should be a sorted set
assert_eq!(clause, clause2);
// they shouldn't be tautologies yet...
assert!(!clause.is_tautology());
assert!(!clause2.is_tautology());
//...but now they should be!
clause2.add(-2);
assert!(clause!= clause2);
clause.add(-2);
assert_eq!(clause, clause2);
assert!(clause.is_tautology());
// Assert that adding the same element means they're still equal (it's a set)
clause2.add(2);
assert_eq!(clause, clause2);
}
/// A conjunction (∧) of clauses
#[derive(Eq, PartialEq, Clone, Debug)]
pub struct CNFSystem {
pub clauses: HashSet<CNFClause>,
}
impl CNFSystem {
pub fn new(initial_clauses: Option<HashSet<CNFClause>>) -> CNFSystem {
match initial_clauses {
Some(c) => CNFSystem{ clauses: c, },
None => CNFSystem{ clauses: HashSet::new(), },
}
}
/// Add a clause to the system. Returns false if the value was already in the system
pub fn add_clause(&mut self, clause: CNFClause) -> bool {
self.clauses.insert(clause)
}
/// Removes a clause from the system. Returns false if the value wasn't already in the system
pub fn remove_clause(&mut self, clause: &CNFClause) -> bool {
self.clauses.remove(clause)
}
/// Return the amount of clauses in the system
pub fn len(&self) -> usize {
self.clauses.len()
}
}
|
ve(&mu
|
identifier_name
|
parse-complex-macro-invoc-op.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test parsing binary operators after macro invocations.
// pretty-expanded FIXME #23616
#![feature(macro_rules)]
macro_rules! id {
($e: expr) => { $e }
}
fn foo() {
id!(1) + 1;
id![1] - 1;
id!(1) * 1;
id![1] / 1;
id!(1) % 1;
id!(1) & 1;
id![1] | 1;
id!(1) ^ 1;
let mut x = 1;
id![x] = 2;
id!(x) += 1;
id!(1f64).clone();
id!([1, 2, 3])[1];
id;
id!(true) && true;
id![true] || true;
}
fn
|
() {}
|
main
|
identifier_name
|
parse-complex-macro-invoc-op.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test parsing binary operators after macro invocations.
// pretty-expanded FIXME #23616
#![feature(macro_rules)]
macro_rules! id {
($e: expr) => { $e }
}
fn foo() {
id!(1) + 1;
id![1] - 1;
id!(1) * 1;
id![1] / 1;
id!(1) % 1;
id!(1) & 1;
id![1] | 1;
id!(1) ^ 1;
let mut x = 1;
id![x] = 2;
id!(x) += 1;
id!(1f64).clone();
id!([1, 2, 3])[1];
id;
id!(true) && true;
id![true] || true;
}
fn main()
|
{}
|
identifier_body
|
|
parse-complex-macro-invoc-op.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.
|
// pretty-expanded FIXME #23616
#![feature(macro_rules)]
macro_rules! id {
($e: expr) => { $e }
}
fn foo() {
id!(1) + 1;
id![1] - 1;
id!(1) * 1;
id![1] / 1;
id!(1) % 1;
id!(1) & 1;
id![1] | 1;
id!(1) ^ 1;
let mut x = 1;
id![x] = 2;
id!(x) += 1;
id!(1f64).clone();
id!([1, 2, 3])[1];
id;
id!(true) && true;
id![true] || true;
}
fn main() {}
|
// Test parsing binary operators after macro invocations.
|
random_line_split
|
cton-util.rs
|
extern crate cretonne;
extern crate cton_reader;
extern crate cton_wasm;
extern crate cton_filetests;
extern crate docopt;
#[macro_use]
extern crate serde_derive;
extern crate filecheck;
extern crate tempdir;
extern crate term;
use cretonne::{VERSION, timing};
use docopt::Docopt;
use std::io::{self, Write};
use std::process;
mod utils;
mod cat;
mod print_cfg;
mod rsfilecheck;
mod wasm;
mod compile;
const USAGE: &str = "
Cretonne code generator utility
Usage:
cton-util test [-vT] <file>...
cton-util cat <file>...
cton-util filecheck [-v] <file>
cton-util print-cfg <file>...
cton-util compile [-vpT] [--set <set>]... [--isa <isa>] <file>...
cton-util wasm [-ctvpTs] [--set <set>]... [--isa <isa>] <file>...
cton-util --help | --version
Options:
-v, --verbose be more verbose
-T, --time-passes
print pass timing report
-t, --just-decode
just decode WebAssembly to Cretonne IL
-s, --print-size
prints generated code size
-c, --check-translation
just checks the correctness of Cretonne IL translated from WebAssembly
-p, --print print the resulting Cretonne IL
-h, --help print this help message
--set=<set> configure Cretonne settings
--isa=<isa> specify the Cretonne ISA
--version print the Cretonne version
";
#[derive(Deserialize, Debug)]
struct Args {
cmd_test: bool,
cmd_cat: bool,
cmd_filecheck: bool,
cmd_print_cfg: bool,
cmd_compile: bool,
cmd_wasm: bool,
arg_file: Vec<String>,
flag_just_decode: bool,
flag_check_translation: bool,
flag_print: bool,
flag_verbose: bool,
flag_set: Vec<String>,
flag_isa: String,
flag_time_passes: bool,
flag_print_size: bool,
}
/// A command either succeeds or fails with an error message.
pub type CommandResult = Result<(), String>;
/// Parse the command line arguments and run the requested command.
fn cton_util() -> CommandResult {
// Parse command line arguments.
let args: Args = Docopt::new(USAGE)
.and_then(|d| {
d.help(true)
.version(Some(format!("Cretonne {}", VERSION)))
.deserialize()
})
.unwrap_or_else(|e| e.exit());
// Find the sub-command to execute.
let result = if args.cmd_test {
cton_filetests::run(args.flag_verbose, &args.arg_file).map(|_time| ())
} else if args.cmd_cat {
cat::run(&args.arg_file)
} else if args.cmd_filecheck {
rsfilecheck::run(&args.arg_file, args.flag_verbose)
} else if args.cmd_print_cfg {
print_cfg::run(&args.arg_file)
} else if args.cmd_compile {
compile::run(
args.arg_file,
args.flag_print,
&args.flag_set,
&args.flag_isa,
)
} else if args.cmd_wasm {
wasm::run(
args.arg_file,
args.flag_verbose,
args.flag_just_decode,
args.flag_check_translation,
args.flag_print,
&args.flag_set,
&args.flag_isa,
args.flag_print_size,
)
} else {
// Debugging / shouldn't happen with proper command line handling above.
Err(format!("Unhandled args: {:?}", args))
};
if args.flag_time_passes {
print!("{}", timing::take_current());
}
result
}
fn
|
() {
if let Err(mut msg) = cton_util() {
if!msg.ends_with('\n') {
msg.push('\n');
}
io::stdout().flush().expect("flushing stdout");
io::stderr().write_all(msg.as_bytes()).unwrap();
process::exit(1);
}
}
|
main
|
identifier_name
|
cton-util.rs
|
extern crate cretonne;
extern crate cton_reader;
extern crate cton_wasm;
extern crate cton_filetests;
extern crate docopt;
#[macro_use]
extern crate serde_derive;
extern crate filecheck;
extern crate tempdir;
extern crate term;
use cretonne::{VERSION, timing};
use docopt::Docopt;
use std::io::{self, Write};
use std::process;
mod utils;
mod cat;
mod print_cfg;
mod rsfilecheck;
mod wasm;
mod compile;
const USAGE: &str = "
Cretonne code generator utility
Usage:
cton-util test [-vT] <file>...
cton-util cat <file>...
cton-util filecheck [-v] <file>
cton-util print-cfg <file>...
cton-util compile [-vpT] [--set <set>]... [--isa <isa>] <file>...
cton-util wasm [-ctvpTs] [--set <set>]... [--isa <isa>] <file>...
cton-util --help | --version
Options:
-v, --verbose be more verbose
-T, --time-passes
print pass timing report
-t, --just-decode
just decode WebAssembly to Cretonne IL
-s, --print-size
prints generated code size
-c, --check-translation
just checks the correctness of Cretonne IL translated from WebAssembly
-p, --print print the resulting Cretonne IL
-h, --help print this help message
--set=<set> configure Cretonne settings
--isa=<isa> specify the Cretonne ISA
--version print the Cretonne version
";
#[derive(Deserialize, Debug)]
struct Args {
cmd_test: bool,
cmd_cat: bool,
cmd_filecheck: bool,
cmd_print_cfg: bool,
cmd_compile: bool,
cmd_wasm: bool,
arg_file: Vec<String>,
flag_just_decode: bool,
flag_check_translation: bool,
flag_print: bool,
flag_verbose: bool,
flag_set: Vec<String>,
flag_isa: String,
flag_time_passes: bool,
flag_print_size: bool,
}
/// A command either succeeds or fails with an error message.
pub type CommandResult = Result<(), String>;
/// Parse the command line arguments and run the requested command.
fn cton_util() -> CommandResult {
// Parse command line arguments.
let args: Args = Docopt::new(USAGE)
.and_then(|d| {
d.help(true)
.version(Some(format!("Cretonne {}", VERSION)))
.deserialize()
})
.unwrap_or_else(|e| e.exit());
// Find the sub-command to execute.
let result = if args.cmd_test {
cton_filetests::run(args.flag_verbose, &args.arg_file).map(|_time| ())
} else if args.cmd_cat {
cat::run(&args.arg_file)
} else if args.cmd_filecheck {
rsfilecheck::run(&args.arg_file, args.flag_verbose)
|
} else if args.cmd_print_cfg {
print_cfg::run(&args.arg_file)
} else if args.cmd_compile {
compile::run(
args.arg_file,
args.flag_print,
&args.flag_set,
&args.flag_isa,
)
} else if args.cmd_wasm {
wasm::run(
args.arg_file,
args.flag_verbose,
args.flag_just_decode,
args.flag_check_translation,
args.flag_print,
&args.flag_set,
&args.flag_isa,
args.flag_print_size,
)
} else {
// Debugging / shouldn't happen with proper command line handling above.
Err(format!("Unhandled args: {:?}", args))
};
if args.flag_time_passes {
print!("{}", timing::take_current());
}
result
}
fn main() {
if let Err(mut msg) = cton_util() {
if!msg.ends_with('\n') {
msg.push('\n');
}
io::stdout().flush().expect("flushing stdout");
io::stderr().write_all(msg.as_bytes()).unwrap();
process::exit(1);
}
}
|
random_line_split
|
|
cton-util.rs
|
extern crate cretonne;
extern crate cton_reader;
extern crate cton_wasm;
extern crate cton_filetests;
extern crate docopt;
#[macro_use]
extern crate serde_derive;
extern crate filecheck;
extern crate tempdir;
extern crate term;
use cretonne::{VERSION, timing};
use docopt::Docopt;
use std::io::{self, Write};
use std::process;
mod utils;
mod cat;
mod print_cfg;
mod rsfilecheck;
mod wasm;
mod compile;
const USAGE: &str = "
Cretonne code generator utility
Usage:
cton-util test [-vT] <file>...
cton-util cat <file>...
cton-util filecheck [-v] <file>
cton-util print-cfg <file>...
cton-util compile [-vpT] [--set <set>]... [--isa <isa>] <file>...
cton-util wasm [-ctvpTs] [--set <set>]... [--isa <isa>] <file>...
cton-util --help | --version
Options:
-v, --verbose be more verbose
-T, --time-passes
print pass timing report
-t, --just-decode
just decode WebAssembly to Cretonne IL
-s, --print-size
prints generated code size
-c, --check-translation
just checks the correctness of Cretonne IL translated from WebAssembly
-p, --print print the resulting Cretonne IL
-h, --help print this help message
--set=<set> configure Cretonne settings
--isa=<isa> specify the Cretonne ISA
--version print the Cretonne version
";
#[derive(Deserialize, Debug)]
struct Args {
cmd_test: bool,
cmd_cat: bool,
cmd_filecheck: bool,
cmd_print_cfg: bool,
cmd_compile: bool,
cmd_wasm: bool,
arg_file: Vec<String>,
flag_just_decode: bool,
flag_check_translation: bool,
flag_print: bool,
flag_verbose: bool,
flag_set: Vec<String>,
flag_isa: String,
flag_time_passes: bool,
flag_print_size: bool,
}
/// A command either succeeds or fails with an error message.
pub type CommandResult = Result<(), String>;
/// Parse the command line arguments and run the requested command.
fn cton_util() -> CommandResult {
// Parse command line arguments.
let args: Args = Docopt::new(USAGE)
.and_then(|d| {
d.help(true)
.version(Some(format!("Cretonne {}", VERSION)))
.deserialize()
})
.unwrap_or_else(|e| e.exit());
// Find the sub-command to execute.
let result = if args.cmd_test {
cton_filetests::run(args.flag_verbose, &args.arg_file).map(|_time| ())
} else if args.cmd_cat
|
else if args.cmd_filecheck {
rsfilecheck::run(&args.arg_file, args.flag_verbose)
} else if args.cmd_print_cfg {
print_cfg::run(&args.arg_file)
} else if args.cmd_compile {
compile::run(
args.arg_file,
args.flag_print,
&args.flag_set,
&args.flag_isa,
)
} else if args.cmd_wasm {
wasm::run(
args.arg_file,
args.flag_verbose,
args.flag_just_decode,
args.flag_check_translation,
args.flag_print,
&args.flag_set,
&args.flag_isa,
args.flag_print_size,
)
} else {
// Debugging / shouldn't happen with proper command line handling above.
Err(format!("Unhandled args: {:?}", args))
};
if args.flag_time_passes {
print!("{}", timing::take_current());
}
result
}
fn main() {
if let Err(mut msg) = cton_util() {
if!msg.ends_with('\n') {
msg.push('\n');
}
io::stdout().flush().expect("flushing stdout");
io::stderr().write_all(msg.as_bytes()).unwrap();
process::exit(1);
}
}
|
{
cat::run(&args.arg_file)
}
|
conditional_block
|
mod.rs
|
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos.
//
// Serkr is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Serkr is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Serkr. If not, see <http://www.gnu.org/licenses/>.
//
//! Contains the parser for the TPTP format.
|
/// Autogenerated code, don't care about any warnings.
#[allow(missing_docs)]
#[allow(dead_code)]
#[cfg_attr(rustfmt, rustfmt_skip)]
#[cfg_attr(feature="clippy", allow(clippy))]
#[cfg_attr(feature="clippy", allow(clippy_pedantic))]
mod parser_grammar;
/// Contains a function for parsing a formula in the TPTP format to the abstract syntax tree.
#[cfg_attr(rustfmt, rustfmt_skip)]
#[cfg_attr(feature="clippy", allow(result_unwrap_used))]
pub mod parser;
/// The abstract syntax tree the parser constructs.
pub mod ast;
|
random_line_split
|
|
run.rs
|
use std::process::{Command, Child};
use env::EnvList;
use super::Result;
use error::BenvError;
|
let mut command = Command::new(&program);
command.args(&args);
for env in env_list {
command.env(env.name, env.value);
}
let child = try!(command.spawn());
Ok(child)
}
fn split_program_and_args(program_with_args: &str) -> Result<(String, Vec<&str>)> {
// Life would have been good...
// match program_with_args.split_whitespace() {
// [program,.. args] => (program.to_string(), args.to_string())
// }
let mut vec: Vec<&str> = program_with_args.split_whitespace().collect();
if vec.len() == 0 {
return Err(BenvError::MissingProgram);
}
let program = vec.remove(0).to_string();
Ok((program, vec))
}
// #[cfg(test)]
// mod test {
// use super::*;
// use env::{Env, EnvList};
// #[test]
// fn test_simple_command() {
// // TODO
// //
// // With latest nightly, it seems impossible to write a proper test case
// // where stdout of the child process is captured.
// //
// // let envlist: EnvList = vec![Env::new("HELLO", "World")];
// // let child = run("echo $HELLO", envlist).unwrap().wait_with_output().unwrap();
// // println!("{:?}", child.stderr);
// // let result = String::from_utf8(child.stdout).unwrap();
// // assert_eq!(result, "world");
// }
// }
|
pub fn run(program_with_args: &str, env_list: EnvList) -> Result<Child> {
let (program, args) = try!(split_program_and_args(program_with_args));
|
random_line_split
|
run.rs
|
use std::process::{Command, Child};
use env::EnvList;
use super::Result;
use error::BenvError;
pub fn run(program_with_args: &str, env_list: EnvList) -> Result<Child> {
let (program, args) = try!(split_program_and_args(program_with_args));
let mut command = Command::new(&program);
command.args(&args);
for env in env_list {
command.env(env.name, env.value);
}
let child = try!(command.spawn());
Ok(child)
}
fn split_program_and_args(program_with_args: &str) -> Result<(String, Vec<&str>)> {
// Life would have been good...
// match program_with_args.split_whitespace() {
// [program,.. args] => (program.to_string(), args.to_string())
// }
let mut vec: Vec<&str> = program_with_args.split_whitespace().collect();
if vec.len() == 0
|
let program = vec.remove(0).to_string();
Ok((program, vec))
}
// #[cfg(test)]
// mod test {
// use super::*;
// use env::{Env, EnvList};
// #[test]
// fn test_simple_command() {
// // TODO
// //
// // With latest nightly, it seems impossible to write a proper test case
// // where stdout of the child process is captured.
// //
// // let envlist: EnvList = vec![Env::new("HELLO", "World")];
// // let child = run("echo $HELLO", envlist).unwrap().wait_with_output().unwrap();
// // println!("{:?}", child.stderr);
// // let result = String::from_utf8(child.stdout).unwrap();
// // assert_eq!(result, "world");
// }
// }
|
{
return Err(BenvError::MissingProgram);
}
|
conditional_block
|
run.rs
|
use std::process::{Command, Child};
use env::EnvList;
use super::Result;
use error::BenvError;
pub fn
|
(program_with_args: &str, env_list: EnvList) -> Result<Child> {
let (program, args) = try!(split_program_and_args(program_with_args));
let mut command = Command::new(&program);
command.args(&args);
for env in env_list {
command.env(env.name, env.value);
}
let child = try!(command.spawn());
Ok(child)
}
fn split_program_and_args(program_with_args: &str) -> Result<(String, Vec<&str>)> {
// Life would have been good...
// match program_with_args.split_whitespace() {
// [program,.. args] => (program.to_string(), args.to_string())
// }
let mut vec: Vec<&str> = program_with_args.split_whitespace().collect();
if vec.len() == 0 {
return Err(BenvError::MissingProgram);
}
let program = vec.remove(0).to_string();
Ok((program, vec))
}
// #[cfg(test)]
// mod test {
// use super::*;
// use env::{Env, EnvList};
// #[test]
// fn test_simple_command() {
// // TODO
// //
// // With latest nightly, it seems impossible to write a proper test case
// // where stdout of the child process is captured.
// //
// // let envlist: EnvList = vec![Env::new("HELLO", "World")];
// // let child = run("echo $HELLO", envlist).unwrap().wait_with_output().unwrap();
// // println!("{:?}", child.stderr);
// // let result = String::from_utf8(child.stdout).unwrap();
// // assert_eq!(result, "world");
// }
// }
|
run
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.