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 |
---|---|---|---|---|
lithos_switch.rs | extern crate libc;
extern crate nix;
extern crate env_logger;
extern crate regex;
extern crate argparse;
extern crate quire;
#[macro_use] extern crate log;
extern crate lithos;
use std::env;
use std::io::{stderr, Read, Write};
use std::process::exit;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::fs::{File};
use std::fs::{copy, rename};
use std::process::{Command, Stdio};
use argparse::{ArgumentParser, Parse, StoreTrue, Print};
use quire::{parse_config, Options};
use nix::sys::signal::{SIGQUIT, kill};
use nix::unistd::Pid;
use lithos::master_config::MasterConfig;
use lithos::sandbox_config::SandboxConfig;
fn switch_config(master_cfg: &Path, sandbox_name: String, config_file: &Path)
-> Result<(), String>
{
match Command::new(env::current_exe().unwrap()
.parent().unwrap().join("lithos_check"))
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.arg("--config")
.arg(&master_cfg)
.arg("--sandbox")
.arg(&sandbox_name)
.arg("--alternate-config")
.arg(&config_file)
.output()
{
Ok(ref po) if po.status.code() == Some(0) => { }
Ok(ref po) => {
return Err(format!(
"Configuration check failed with exit status: {}",
po.status));
}
Err(e) => {
return Err(format!("Can't check configuration: {}", e));
}
}
info!("Checked. Proceeding");
let master: MasterConfig = match parse_config(&master_cfg,
&MasterConfig::validator(), &Options::default())
{
Ok(cfg) => cfg,
Err(e) => |
};
let sandbox_fn = master_cfg.parent().unwrap()
.join(&master.sandboxes_dir)
.join(&(sandbox_name.clone() + ".yaml"));
let sandbox: SandboxConfig = match parse_config(&sandbox_fn,
&SandboxConfig::validator(), &Options::default())
{
Ok(cfg) => cfg,
Err(e) => {
return Err(format!("Can't parse sandbox config: {}", e));
}
};
let target_fn = master_cfg.parent().unwrap()
.join(&master.processes_dir)
.join(sandbox.config_file.as_ref().unwrap_or(
&PathBuf::from(&(sandbox_name.clone() + ".yaml"))));
debug!("Target filename {:?}", target_fn);
let tmp_filename = target_fn.with_file_name(
&format!(".tmp.{}", sandbox_name));
try!(copy(&config_file, &tmp_filename)
.map_err(|e| format!("Error copying: {}", e)));
try!(rename(&tmp_filename, &target_fn)
.map_err(|e| format!("Error replacing file: {}", e)));
info!("Done. Sending SIGQUIT to lithos_tree");
let pid_file = master.runtime_dir.join("master.pid");
let mut buf = String::with_capacity(50);
let read_pid = File::open(&pid_file)
.and_then(|mut f| f.read_to_string(&mut buf))
.ok()
.and_then(|_| FromStr::from_str(buf[..].trim()).ok())
.map(Pid::from_raw);
match read_pid {
Some(pid) if kill(pid, None).is_ok() => {
kill(pid, SIGQUIT)
.map_err(|e| error!("Error sending QUIT to master: {:?}", e)).ok();
}
Some(pid) => {
warn!("Process with pid {} is not running...", pid);
}
None => {
warn!("Can't read pid file {}. Probably daemon is not running.",
pid_file.display());
}
};
return Ok(());
}
fn main() {
if env::var("RUST_LOG").is_err() {
env::set_var("RUST_LOG", "warn");
}
env_logger::init();
let mut master_config = PathBuf::from("/etc/lithos/master.yaml");
let mut verbose = false;
let mut config_file = PathBuf::from("");
let mut sandbox_name = "".to_string();
{
let mut ap = ArgumentParser::new();
ap.set_description("Checks if lithos configuration is ok");
ap.refer(&mut master_config)
.add_option(&["--master"], Parse,
"Name of the master configuration file \
(default /etc/lithos/master.yaml)")
.metavar("FILE");
ap.refer(&mut verbose)
.add_option(&["-v", "--verbose"], StoreTrue,
"Verbose configuration");
ap.refer(&mut sandbox_name)
.add_argument("sandbox", Parse,
"Name of the sandbox which configuration will be switched for")
.required()
.metavar("NAME");
ap.refer(&mut config_file)
.add_argument("new_config", Parse, "
Name of the process configuration file for this sandbox to switch
to. The file is copied over current config after configuration is
validated and just before sending a signal to lithos_tree.")
.metavar("FILE")
.required();
ap.add_option(&["--version"],
Print(env!("CARGO_PKG_VERSION").to_string()),
"Show version");
match ap.parse_args() {
Ok(()) => {}
Err(x) => {
exit(x);
}
}
}
match switch_config(&master_config, sandbox_name, &config_file)
{
Ok(()) => {
exit(0);
}
Err(e) => {
write!(&mut stderr(), "Fatal error: {}\n", e).unwrap();
exit(1);
}
}
}
| {
return Err(format!("Can't parse master config: {}", e));
} | conditional_block |
lithos_switch.rs | extern crate libc;
extern crate nix;
extern crate env_logger;
extern crate regex;
extern crate argparse;
extern crate quire;
#[macro_use] extern crate log;
extern crate lithos;
use std::env;
use std::io::{stderr, Read, Write};
use std::process::exit;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::fs::{File};
use std::fs::{copy, rename};
use std::process::{Command, Stdio};
use argparse::{ArgumentParser, Parse, StoreTrue, Print};
use quire::{parse_config, Options};
use nix::sys::signal::{SIGQUIT, kill};
use nix::unistd::Pid;
use lithos::master_config::MasterConfig;
use lithos::sandbox_config::SandboxConfig;
fn switch_config(master_cfg: &Path, sandbox_name: String, config_file: &Path)
-> Result<(), String>
{
match Command::new(env::current_exe().unwrap()
.parent().unwrap().join("lithos_check"))
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.arg("--config")
.arg(&master_cfg)
.arg("--sandbox")
.arg(&sandbox_name)
.arg("--alternate-config")
.arg(&config_file)
.output()
{
Ok(ref po) if po.status.code() == Some(0) => { }
Ok(ref po) => {
return Err(format!(
"Configuration check failed with exit status: {}",
po.status));
}
Err(e) => {
return Err(format!("Can't check configuration: {}", e));
}
}
info!("Checked. Proceeding");
let master: MasterConfig = match parse_config(&master_cfg,
&MasterConfig::validator(), &Options::default())
{
Ok(cfg) => cfg,
Err(e) => {
return Err(format!("Can't parse master config: {}", e));
}
};
let sandbox_fn = master_cfg.parent().unwrap()
.join(&master.sandboxes_dir)
.join(&(sandbox_name.clone() + ".yaml"));
let sandbox: SandboxConfig = match parse_config(&sandbox_fn,
&SandboxConfig::validator(), &Options::default())
{
Ok(cfg) => cfg,
Err(e) => {
return Err(format!("Can't parse sandbox config: {}", e));
}
};
let target_fn = master_cfg.parent().unwrap()
.join(&master.processes_dir)
.join(sandbox.config_file.as_ref().unwrap_or(
&PathBuf::from(&(sandbox_name.clone() + ".yaml"))));
debug!("Target filename {:?}", target_fn);
let tmp_filename = target_fn.with_file_name(
&format!(".tmp.{}", sandbox_name));
try!(copy(&config_file, &tmp_filename)
.map_err(|e| format!("Error copying: {}", e)));
try!(rename(&tmp_filename, &target_fn)
.map_err(|e| format!("Error replacing file: {}", e)));
info!("Done. Sending SIGQUIT to lithos_tree");
let pid_file = master.runtime_dir.join("master.pid");
let mut buf = String::with_capacity(50);
let read_pid = File::open(&pid_file)
.and_then(|mut f| f.read_to_string(&mut buf))
.ok()
.and_then(|_| FromStr::from_str(buf[..].trim()).ok())
.map(Pid::from_raw);
match read_pid {
Some(pid) if kill(pid, None).is_ok() => {
kill(pid, SIGQUIT)
.map_err(|e| error!("Error sending QUIT to master: {:?}", e)).ok();
}
Some(pid) => {
warn!("Process with pid {} is not running...", pid); | pid_file.display());
}
};
return Ok(());
}
fn main() {
if env::var("RUST_LOG").is_err() {
env::set_var("RUST_LOG", "warn");
}
env_logger::init();
let mut master_config = PathBuf::from("/etc/lithos/master.yaml");
let mut verbose = false;
let mut config_file = PathBuf::from("");
let mut sandbox_name = "".to_string();
{
let mut ap = ArgumentParser::new();
ap.set_description("Checks if lithos configuration is ok");
ap.refer(&mut master_config)
.add_option(&["--master"], Parse,
"Name of the master configuration file \
(default /etc/lithos/master.yaml)")
.metavar("FILE");
ap.refer(&mut verbose)
.add_option(&["-v", "--verbose"], StoreTrue,
"Verbose configuration");
ap.refer(&mut sandbox_name)
.add_argument("sandbox", Parse,
"Name of the sandbox which configuration will be switched for")
.required()
.metavar("NAME");
ap.refer(&mut config_file)
.add_argument("new_config", Parse, "
Name of the process configuration file for this sandbox to switch
to. The file is copied over current config after configuration is
validated and just before sending a signal to lithos_tree.")
.metavar("FILE")
.required();
ap.add_option(&["--version"],
Print(env!("CARGO_PKG_VERSION").to_string()),
"Show version");
match ap.parse_args() {
Ok(()) => {}
Err(x) => {
exit(x);
}
}
}
match switch_config(&master_config, sandbox_name, &config_file)
{
Ok(()) => {
exit(0);
}
Err(e) => {
write!(&mut stderr(), "Fatal error: {}\n", e).unwrap();
exit(1);
}
}
} | }
None => {
warn!("Can't read pid file {}. Probably daemon is not running.", | random_line_split |
lithos_switch.rs | extern crate libc;
extern crate nix;
extern crate env_logger;
extern crate regex;
extern crate argparse;
extern crate quire;
#[macro_use] extern crate log;
extern crate lithos;
use std::env;
use std::io::{stderr, Read, Write};
use std::process::exit;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::fs::{File};
use std::fs::{copy, rename};
use std::process::{Command, Stdio};
use argparse::{ArgumentParser, Parse, StoreTrue, Print};
use quire::{parse_config, Options};
use nix::sys::signal::{SIGQUIT, kill};
use nix::unistd::Pid;
use lithos::master_config::MasterConfig;
use lithos::sandbox_config::SandboxConfig;
fn switch_config(master_cfg: &Path, sandbox_name: String, config_file: &Path)
-> Result<(), String>
{
match Command::new(env::current_exe().unwrap()
.parent().unwrap().join("lithos_check"))
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.arg("--config")
.arg(&master_cfg)
.arg("--sandbox")
.arg(&sandbox_name)
.arg("--alternate-config")
.arg(&config_file)
.output()
{
Ok(ref po) if po.status.code() == Some(0) => { }
Ok(ref po) => {
return Err(format!(
"Configuration check failed with exit status: {}",
po.status));
}
Err(e) => {
return Err(format!("Can't check configuration: {}", e));
}
}
info!("Checked. Proceeding");
let master: MasterConfig = match parse_config(&master_cfg,
&MasterConfig::validator(), &Options::default())
{
Ok(cfg) => cfg,
Err(e) => {
return Err(format!("Can't parse master config: {}", e));
}
};
let sandbox_fn = master_cfg.parent().unwrap()
.join(&master.sandboxes_dir)
.join(&(sandbox_name.clone() + ".yaml"));
let sandbox: SandboxConfig = match parse_config(&sandbox_fn,
&SandboxConfig::validator(), &Options::default())
{
Ok(cfg) => cfg,
Err(e) => {
return Err(format!("Can't parse sandbox config: {}", e));
}
};
let target_fn = master_cfg.parent().unwrap()
.join(&master.processes_dir)
.join(sandbox.config_file.as_ref().unwrap_or(
&PathBuf::from(&(sandbox_name.clone() + ".yaml"))));
debug!("Target filename {:?}", target_fn);
let tmp_filename = target_fn.with_file_name(
&format!(".tmp.{}", sandbox_name));
try!(copy(&config_file, &tmp_filename)
.map_err(|e| format!("Error copying: {}", e)));
try!(rename(&tmp_filename, &target_fn)
.map_err(|e| format!("Error replacing file: {}", e)));
info!("Done. Sending SIGQUIT to lithos_tree");
let pid_file = master.runtime_dir.join("master.pid");
let mut buf = String::with_capacity(50);
let read_pid = File::open(&pid_file)
.and_then(|mut f| f.read_to_string(&mut buf))
.ok()
.and_then(|_| FromStr::from_str(buf[..].trim()).ok())
.map(Pid::from_raw);
match read_pid {
Some(pid) if kill(pid, None).is_ok() => {
kill(pid, SIGQUIT)
.map_err(|e| error!("Error sending QUIT to master: {:?}", e)).ok();
}
Some(pid) => {
warn!("Process with pid {} is not running...", pid);
}
None => {
warn!("Can't read pid file {}. Probably daemon is not running.",
pid_file.display());
}
};
return Ok(());
}
fn main() | "Verbose configuration");
ap.refer(&mut sandbox_name)
.add_argument("sandbox", Parse,
"Name of the sandbox which configuration will be switched for")
.required()
.metavar("NAME");
ap.refer(&mut config_file)
.add_argument("new_config", Parse, "
Name of the process configuration file for this sandbox to switch
to. The file is copied over current config after configuration is
validated and just before sending a signal to lithos_tree.")
.metavar("FILE")
.required();
ap.add_option(&["--version"],
Print(env!("CARGO_PKG_VERSION").to_string()),
"Show version");
match ap.parse_args() {
Ok(()) => {}
Err(x) => {
exit(x);
}
}
}
match switch_config(&master_config, sandbox_name, &config_file)
{
Ok(()) => {
exit(0);
}
Err(e) => {
write!(&mut stderr(), "Fatal error: {}\n", e).unwrap();
exit(1);
}
}
}
| {
if env::var("RUST_LOG").is_err() {
env::set_var("RUST_LOG", "warn");
}
env_logger::init();
let mut master_config = PathBuf::from("/etc/lithos/master.yaml");
let mut verbose = false;
let mut config_file = PathBuf::from("");
let mut sandbox_name = "".to_string();
{
let mut ap = ArgumentParser::new();
ap.set_description("Checks if lithos configuration is ok");
ap.refer(&mut master_config)
.add_option(&["--master"], Parse,
"Name of the master configuration file \
(default /etc/lithos/master.yaml)")
.metavar("FILE");
ap.refer(&mut verbose)
.add_option(&["-v", "--verbose"], StoreTrue, | identifier_body |
lithos_switch.rs | extern crate libc;
extern crate nix;
extern crate env_logger;
extern crate regex;
extern crate argparse;
extern crate quire;
#[macro_use] extern crate log;
extern crate lithos;
use std::env;
use std::io::{stderr, Read, Write};
use std::process::exit;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::fs::{File};
use std::fs::{copy, rename};
use std::process::{Command, Stdio};
use argparse::{ArgumentParser, Parse, StoreTrue, Print};
use quire::{parse_config, Options};
use nix::sys::signal::{SIGQUIT, kill};
use nix::unistd::Pid;
use lithos::master_config::MasterConfig;
use lithos::sandbox_config::SandboxConfig;
fn switch_config(master_cfg: &Path, sandbox_name: String, config_file: &Path)
-> Result<(), String>
{
match Command::new(env::current_exe().unwrap()
.parent().unwrap().join("lithos_check"))
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.arg("--config")
.arg(&master_cfg)
.arg("--sandbox")
.arg(&sandbox_name)
.arg("--alternate-config")
.arg(&config_file)
.output()
{
Ok(ref po) if po.status.code() == Some(0) => { }
Ok(ref po) => {
return Err(format!(
"Configuration check failed with exit status: {}",
po.status));
}
Err(e) => {
return Err(format!("Can't check configuration: {}", e));
}
}
info!("Checked. Proceeding");
let master: MasterConfig = match parse_config(&master_cfg,
&MasterConfig::validator(), &Options::default())
{
Ok(cfg) => cfg,
Err(e) => {
return Err(format!("Can't parse master config: {}", e));
}
};
let sandbox_fn = master_cfg.parent().unwrap()
.join(&master.sandboxes_dir)
.join(&(sandbox_name.clone() + ".yaml"));
let sandbox: SandboxConfig = match parse_config(&sandbox_fn,
&SandboxConfig::validator(), &Options::default())
{
Ok(cfg) => cfg,
Err(e) => {
return Err(format!("Can't parse sandbox config: {}", e));
}
};
let target_fn = master_cfg.parent().unwrap()
.join(&master.processes_dir)
.join(sandbox.config_file.as_ref().unwrap_or(
&PathBuf::from(&(sandbox_name.clone() + ".yaml"))));
debug!("Target filename {:?}", target_fn);
let tmp_filename = target_fn.with_file_name(
&format!(".tmp.{}", sandbox_name));
try!(copy(&config_file, &tmp_filename)
.map_err(|e| format!("Error copying: {}", e)));
try!(rename(&tmp_filename, &target_fn)
.map_err(|e| format!("Error replacing file: {}", e)));
info!("Done. Sending SIGQUIT to lithos_tree");
let pid_file = master.runtime_dir.join("master.pid");
let mut buf = String::with_capacity(50);
let read_pid = File::open(&pid_file)
.and_then(|mut f| f.read_to_string(&mut buf))
.ok()
.and_then(|_| FromStr::from_str(buf[..].trim()).ok())
.map(Pid::from_raw);
match read_pid {
Some(pid) if kill(pid, None).is_ok() => {
kill(pid, SIGQUIT)
.map_err(|e| error!("Error sending QUIT to master: {:?}", e)).ok();
}
Some(pid) => {
warn!("Process with pid {} is not running...", pid);
}
None => {
warn!("Can't read pid file {}. Probably daemon is not running.",
pid_file.display());
}
};
return Ok(());
}
fn | () {
if env::var("RUST_LOG").is_err() {
env::set_var("RUST_LOG", "warn");
}
env_logger::init();
let mut master_config = PathBuf::from("/etc/lithos/master.yaml");
let mut verbose = false;
let mut config_file = PathBuf::from("");
let mut sandbox_name = "".to_string();
{
let mut ap = ArgumentParser::new();
ap.set_description("Checks if lithos configuration is ok");
ap.refer(&mut master_config)
.add_option(&["--master"], Parse,
"Name of the master configuration file \
(default /etc/lithos/master.yaml)")
.metavar("FILE");
ap.refer(&mut verbose)
.add_option(&["-v", "--verbose"], StoreTrue,
"Verbose configuration");
ap.refer(&mut sandbox_name)
.add_argument("sandbox", Parse,
"Name of the sandbox which configuration will be switched for")
.required()
.metavar("NAME");
ap.refer(&mut config_file)
.add_argument("new_config", Parse, "
Name of the process configuration file for this sandbox to switch
to. The file is copied over current config after configuration is
validated and just before sending a signal to lithos_tree.")
.metavar("FILE")
.required();
ap.add_option(&["--version"],
Print(env!("CARGO_PKG_VERSION").to_string()),
"Show version");
match ap.parse_args() {
Ok(()) => {}
Err(x) => {
exit(x);
}
}
}
match switch_config(&master_config, sandbox_name, &config_file)
{
Ok(()) => {
exit(0);
}
Err(e) => {
write!(&mut stderr(), "Fatal error: {}\n", e).unwrap();
exit(1);
}
}
}
| main | identifier_name |
fs.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use os::unix::prelude::*;
use ffi::{OsString, OsStr};
use fmt;
use io::{self, Error, ErrorKind, SeekFrom};
use path::{Path, PathBuf};
use sync::Arc;
use sys::fd::FileDesc;
use sys::time::SystemTime;
use sys::{cvt, syscall};
use sys_common::{AsInner, FromInner};
pub struct File(FileDesc);
#[derive(Clone)]
pub struct FileAttr {
stat: syscall::Stat,
}
pub struct ReadDir {
data: Vec<u8>,
i: usize,
root: Arc<PathBuf>,
}
struct Dir(FileDesc);
unsafe impl Send for Dir {}
unsafe impl Sync for Dir {}
pub struct DirEntry {
root: Arc<PathBuf>,
name: Box<[u8]>
}
#[derive(Clone, Debug)]
pub struct OpenOptions {
// generic
read: bool,
write: bool,
append: bool,
truncate: bool,
create: bool,
create_new: bool,
// system-specific
custom_flags: i32,
mode: u16,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FilePermissions { mode: u16 }
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct FileType { mode: u16 }
#[derive(Debug)]
pub struct DirBuilder { mode: u16 }
impl FileAttr {
pub fn size(&self) -> u64 { self.stat.st_size as u64 }
pub fn perm(&self) -> FilePermissions {
FilePermissions { mode: (self.stat.st_mode as u16) & 0o777 }
}
pub fn file_type(&self) -> FileType {
FileType { mode: self.stat.st_mode as u16 }
}
}
impl FileAttr {
pub fn modified(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(syscall::TimeSpec {
tv_sec: self.stat.st_mtime as i64,
tv_nsec: self.stat.st_mtime_nsec as i32,
}))
}
pub fn accessed(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(syscall::TimeSpec {
tv_sec: self.stat.st_atime as i64,
tv_nsec: self.stat.st_atime_nsec as i32,
}))
}
pub fn created(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(syscall::TimeSpec {
tv_sec: self.stat.st_ctime as i64,
tv_nsec: self.stat.st_ctime_nsec as i32,
}))
}
}
impl AsInner<syscall::Stat> for FileAttr {
fn as_inner(&self) -> &syscall::Stat { &self.stat }
}
impl FilePermissions {
pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
pub fn set_readonly(&mut self, readonly: bool) {
if readonly {
self.mode &=!0o222;
} else {
self.mode |= 0o222;
}
}
pub fn mode(&self) -> u32 { self.mode as u32 }
}
impl FileType {
pub fn is_dir(&self) -> bool { self.is(syscall::MODE_DIR) }
pub fn is_file(&self) -> bool { self.is(syscall::MODE_FILE) }
pub fn is_symlink(&self) -> bool { self.is(syscall::MODE_SYMLINK) }
pub fn is(&self, mode: u16) -> bool {
self.mode & syscall::MODE_TYPE == mode
}
}
impl FromInner<u32> for FilePermissions {
fn from_inner(mode: u32) -> FilePermissions {
FilePermissions { mode: mode as u16 }
}
}
impl fmt::Debug for ReadDir {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
// Thus the result will be e g 'ReadDir("/home")'
fmt::Debug::fmt(&*self.root, f)
}
}
impl Iterator for ReadDir {
type Item = io::Result<DirEntry>;
fn next(&mut self) -> Option<io::Result<DirEntry>> {
loop {
let start = self.i;
let mut i = self.i;
while i < self.data.len() {
self.i += 1;
if self.data[i] == b'\n' {
break;
}
i += 1;
}
if start < self.i {
let ret = DirEntry {
name: self.data[start.. i].to_owned().into_boxed_slice(),
root: self.root.clone()
};
if ret.name_bytes()!= b"." && ret.name_bytes()!= b".." {
return Some(Ok(ret))
}
} else {
return None;
}
}
}
}
impl DirEntry {
pub fn path(&self) -> PathBuf {
self.root.join(OsStr::from_bytes(self.name_bytes()))
}
pub fn file_name(&self) -> OsString {
OsStr::from_bytes(self.name_bytes()).to_os_string()
}
pub fn metadata(&self) -> io::Result<FileAttr> {
lstat(&self.path())
}
pub fn file_type(&self) -> io::Result<FileType> {
lstat(&self.path()).map(|m| m.file_type())
}
fn name_bytes(&self) -> &[u8] {
&*self.name
}
}
impl OpenOptions {
pub fn new() -> OpenOptions {
OpenOptions {
// generic
read: false,
write: false,
append: false,
truncate: false,
create: false,
create_new: false,
// system-specific
custom_flags: 0,
mode: 0o666,
}
}
pub fn read(&mut self, read: bool) { self.read = read; }
pub fn write(&mut self, write: bool) { self.write = write; }
pub fn append(&mut self, append: bool) { self.append = append; }
pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
pub fn create(&mut self, create: bool) { self.create = create; }
pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; }
pub fn mode(&mut self, mode: u32) { self.mode = mode as u16; }
fn get_access_mode(&self) -> io::Result<usize> {
match (self.read, self.write, self.append) {
(true, false, false) => Ok(syscall::O_RDONLY),
(false, true, false) => Ok(syscall::O_WRONLY),
(true, true, false) => Ok(syscall::O_RDWR),
(false, _, true) => Ok(syscall::O_WRONLY | syscall::O_APPEND),
(true, _, true) => Ok(syscall::O_RDWR | syscall::O_APPEND),
(false, false, false) => Err(Error::from_raw_os_error(syscall::EINVAL)),
}
}
fn get_creation_mode(&self) -> io::Result<usize> {
match (self.write, self.append) {
(true, false) => {}
(false, false) =>
if self.truncate || self.create || self.create_new {
return Err(Error::from_raw_os_error(syscall::EINVAL));
},
(_, true) =>
if self.truncate &&!self.create_new {
return Err(Error::from_raw_os_error(syscall::EINVAL));
},
}
Ok(match (self.create, self.truncate, self.create_new) {
(false, false, false) => 0,
(true, false, false) => syscall::O_CREAT,
(false, true, false) => syscall::O_TRUNC,
(true, true, false) => syscall::O_CREAT | syscall::O_TRUNC,
(_, _, true) => syscall::O_CREAT | syscall::O_EXCL,
})
}
}
impl File {
pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
let flags = syscall::O_CLOEXEC |
opts.get_access_mode()? as usize |
opts.get_creation_mode()? as usize |
(opts.custom_flags as usize &!syscall::O_ACCMODE);
let fd = cvt(syscall::open(path.to_str().unwrap(), flags | opts.mode as usize))?;
Ok(File(FileDesc::new(fd)))
}
pub fn file_attr(&self) -> io::Result<FileAttr> {
let mut stat = syscall::Stat::default();
cvt(syscall::fstat(self.0.raw(), &mut stat))?;
Ok(FileAttr { stat: stat })
}
pub fn fsync(&self) -> io::Result<()> {
cvt(syscall::fsync(self.0.raw()))?;
Ok(())
}
pub fn datasync(&self) -> io::Result<()> {
self.fsync()
}
pub fn truncate(&self, size: u64) -> io::Result<()> {
cvt(syscall::ftruncate(self.0.raw(), size as usize))?;
Ok(())
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
pub fn flush(&self) -> io::Result<()> { Ok(()) }
pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
let (whence, pos) = match pos {
// Casting to `i64` is fine, too large values will end up as
// negative which will cause an error in `lseek64`.
SeekFrom::Start(off) => (syscall::SEEK_SET, off as i64),
SeekFrom::End(off) => (syscall::SEEK_END, off),
SeekFrom::Current(off) => (syscall::SEEK_CUR, off),
};
let n = cvt(syscall::lseek(self.0.raw(), pos as isize, whence))?;
Ok(n as u64)
}
pub fn duplicate(&self) -> io::Result<File> {
self.0.duplicate().map(File)
}
pub fn dup(&self, buf: &[u8]) -> io::Result<File> {
let fd = cvt(syscall::dup(*self.fd().as_inner() as usize, buf))?;
Ok(File(FileDesc::new(fd)))
}
pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
set_perm(&self.path()?, perm)
}
pub fn path(&self) -> io::Result<PathBuf> {
let mut buf: [u8; 4096] = [0; 4096];
let count = cvt(syscall::fpath(*self.fd().as_inner() as usize, &mut buf))?;
Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[..count])) }))
}
pub fn fd(&self) -> &FileDesc { &self.0 }
pub fn into_fd(self) -> FileDesc { self.0 }
}
impl DirBuilder {
pub fn new() -> DirBuilder {
DirBuilder { mode: 0o777 }
}
pub fn mkdir(&self, p: &Path) -> io::Result<()> {
let flags = syscall::O_CREAT | syscall::O_CLOEXEC | syscall::O_DIRECTORY | syscall::O_EXCL;
let fd = cvt(syscall::open(p.to_str().unwrap(), flags | (self.mode as usize & 0o777)))?;
let _ = syscall::close(fd);
Ok(())
}
pub fn set_mode(&mut self, mode: u32) {
self.mode = mode as u16;
}
}
impl FromInner<usize> for File {
fn from_inner(fd: usize) -> File {
File(FileDesc::new(fd))
}
}
impl fmt::Debug for File {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut b = f.debug_struct("File");
b.field("fd", &self.0.raw());
if let Ok(path) = self.path() {
b.field("path", &path);
}
/*
if let Some((read, write)) = get_mode(fd) {
b.field("read", &read).field("write", &write);
}
*/
b.finish()
}
}
pub fn readdir(p: &Path) -> io::Result<ReadDir> {
let root = Arc::new(p.to_path_buf());
let flags = syscall::O_CLOEXEC | syscall::O_RDONLY | syscall::O_DIRECTORY;
let fd = cvt(syscall::open(p.to_str().unwrap(), flags))?;
let file = FileDesc::new(fd);
let mut data = Vec::new();
file.read_to_end(&mut data)?;
Ok(ReadDir { data: data, i: 0, root: root })
}
pub fn unlink(p: &Path) -> io::Result<()> {
cvt(syscall::unlink(p.to_str().unwrap()))?;
Ok(())
}
pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
let fd = cvt(syscall::open(old.to_str().unwrap(), | let res = cvt(syscall::frename(fd, new.to_str().unwrap()));
cvt(syscall::close(fd))?;
res?;
Ok(())
}
pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
cvt(syscall::chmod(p.to_str().unwrap(), perm.mode as usize))?;
Ok(())
}
pub fn rmdir(p: &Path) -> io::Result<()> {
cvt(syscall::rmdir(p.to_str().unwrap()))?;
Ok(())
}
pub fn remove_dir_all(path: &Path) -> io::Result<()> {
let filetype = lstat(path)?.file_type();
if filetype.is_symlink() {
unlink(path)
} else {
remove_dir_all_recursive(path)
}
}
fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
for child in readdir(path)? {
let child = child?;
if child.file_type()?.is_dir() {
remove_dir_all_recursive(&child.path())?;
} else {
unlink(&child.path())?;
}
}
rmdir(path)
}
pub fn readlink(p: &Path) -> io::Result<PathBuf> {
let fd = cvt(syscall::open(p.to_str().unwrap(),
syscall::O_CLOEXEC | syscall::O_SYMLINK | syscall::O_RDONLY))?;
let mut buf: [u8; 4096] = [0; 4096];
let res = cvt(syscall::read(fd, &mut buf));
cvt(syscall::close(fd))?;
let count = res?;
Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[..count])) }))
}
pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
let fd = cvt(syscall::open(dst.to_str().unwrap(),
syscall::O_CLOEXEC | syscall::O_SYMLINK |
syscall::O_CREAT | syscall::O_WRONLY | 0o777))?;
let res = cvt(syscall::write(fd, src.to_str().unwrap().as_bytes()));
cvt(syscall::close(fd))?;
res?;
Ok(())
}
pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> {
Err(Error::from_raw_os_error(syscall::ENOSYS))
}
pub fn stat(p: &Path) -> io::Result<FileAttr> {
let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT))?;
let file = File(FileDesc::new(fd));
file.file_attr()
}
pub fn lstat(p: &Path) -> io::Result<FileAttr> {
let fd = cvt(syscall::open(p.to_str().unwrap(),
syscall::O_CLOEXEC | syscall::O_STAT | syscall::O_NOFOLLOW))?;
let file = File(FileDesc::new(fd));
file.file_attr()
}
pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT))?;
let file = File(FileDesc::new(fd));
file.path()
}
pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
use fs::{File, set_permissions};
if!from.is_file() {
return Err(Error::new(ErrorKind::InvalidInput,
"the source path is not an existing regular file"))
}
let mut reader = File::open(from)?;
let mut writer = File::create(to)?;
let perm = reader.metadata()?.permissions();
let ret = io::copy(&mut reader, &mut writer)?;
set_permissions(to, perm)?;
Ok(ret)
} | syscall::O_CLOEXEC | syscall::O_STAT | syscall::O_NOFOLLOW))?; | random_line_split |
fs.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use os::unix::prelude::*;
use ffi::{OsString, OsStr};
use fmt;
use io::{self, Error, ErrorKind, SeekFrom};
use path::{Path, PathBuf};
use sync::Arc;
use sys::fd::FileDesc;
use sys::time::SystemTime;
use sys::{cvt, syscall};
use sys_common::{AsInner, FromInner};
pub struct File(FileDesc);
#[derive(Clone)]
pub struct FileAttr {
stat: syscall::Stat,
}
pub struct ReadDir {
data: Vec<u8>,
i: usize,
root: Arc<PathBuf>,
}
struct Dir(FileDesc);
unsafe impl Send for Dir {}
unsafe impl Sync for Dir {}
pub struct DirEntry {
root: Arc<PathBuf>,
name: Box<[u8]>
}
#[derive(Clone, Debug)]
pub struct OpenOptions {
// generic
read: bool,
write: bool,
append: bool,
truncate: bool,
create: bool,
create_new: bool,
// system-specific
custom_flags: i32,
mode: u16,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FilePermissions { mode: u16 }
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct FileType { mode: u16 }
#[derive(Debug)]
pub struct DirBuilder { mode: u16 }
impl FileAttr {
pub fn size(&self) -> u64 { self.stat.st_size as u64 }
pub fn perm(&self) -> FilePermissions {
FilePermissions { mode: (self.stat.st_mode as u16) & 0o777 }
}
pub fn file_type(&self) -> FileType {
FileType { mode: self.stat.st_mode as u16 }
}
}
impl FileAttr {
pub fn modified(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(syscall::TimeSpec {
tv_sec: self.stat.st_mtime as i64,
tv_nsec: self.stat.st_mtime_nsec as i32,
}))
}
pub fn accessed(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(syscall::TimeSpec {
tv_sec: self.stat.st_atime as i64,
tv_nsec: self.stat.st_atime_nsec as i32,
}))
}
pub fn created(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(syscall::TimeSpec {
tv_sec: self.stat.st_ctime as i64,
tv_nsec: self.stat.st_ctime_nsec as i32,
}))
}
}
impl AsInner<syscall::Stat> for FileAttr {
fn as_inner(&self) -> &syscall::Stat { &self.stat }
}
impl FilePermissions {
pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
pub fn set_readonly(&mut self, readonly: bool) {
if readonly {
self.mode &=!0o222;
} else {
self.mode |= 0o222;
}
}
pub fn mode(&self) -> u32 { self.mode as u32 }
}
impl FileType {
pub fn is_dir(&self) -> bool { self.is(syscall::MODE_DIR) }
pub fn is_file(&self) -> bool { self.is(syscall::MODE_FILE) }
pub fn is_symlink(&self) -> bool { self.is(syscall::MODE_SYMLINK) }
pub fn is(&self, mode: u16) -> bool {
self.mode & syscall::MODE_TYPE == mode
}
}
impl FromInner<u32> for FilePermissions {
fn from_inner(mode: u32) -> FilePermissions {
FilePermissions { mode: mode as u16 }
}
}
impl fmt::Debug for ReadDir {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
// Thus the result will be e g 'ReadDir("/home")'
fmt::Debug::fmt(&*self.root, f)
}
}
impl Iterator for ReadDir {
type Item = io::Result<DirEntry>;
fn next(&mut self) -> Option<io::Result<DirEntry>> {
loop {
let start = self.i;
let mut i = self.i;
while i < self.data.len() {
self.i += 1;
if self.data[i] == b'\n' {
break;
}
i += 1;
}
if start < self.i {
let ret = DirEntry {
name: self.data[start.. i].to_owned().into_boxed_slice(),
root: self.root.clone()
};
if ret.name_bytes()!= b"." && ret.name_bytes()!= b".." {
return Some(Ok(ret))
}
} else {
return None;
}
}
}
}
impl DirEntry {
pub fn path(&self) -> PathBuf {
self.root.join(OsStr::from_bytes(self.name_bytes()))
}
pub fn file_name(&self) -> OsString {
OsStr::from_bytes(self.name_bytes()).to_os_string()
}
pub fn metadata(&self) -> io::Result<FileAttr> {
lstat(&self.path())
}
pub fn file_type(&self) -> io::Result<FileType> {
lstat(&self.path()).map(|m| m.file_type())
}
fn name_bytes(&self) -> &[u8] {
&*self.name
}
}
impl OpenOptions {
pub fn new() -> OpenOptions {
OpenOptions {
// generic
read: false,
write: false,
append: false,
truncate: false,
create: false,
create_new: false,
// system-specific
custom_flags: 0,
mode: 0o666,
}
}
pub fn read(&mut self, read: bool) { self.read = read; }
pub fn write(&mut self, write: bool) { self.write = write; }
pub fn append(&mut self, append: bool) |
pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
pub fn create(&mut self, create: bool) { self.create = create; }
pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; }
pub fn mode(&mut self, mode: u32) { self.mode = mode as u16; }
fn get_access_mode(&self) -> io::Result<usize> {
match (self.read, self.write, self.append) {
(true, false, false) => Ok(syscall::O_RDONLY),
(false, true, false) => Ok(syscall::O_WRONLY),
(true, true, false) => Ok(syscall::O_RDWR),
(false, _, true) => Ok(syscall::O_WRONLY | syscall::O_APPEND),
(true, _, true) => Ok(syscall::O_RDWR | syscall::O_APPEND),
(false, false, false) => Err(Error::from_raw_os_error(syscall::EINVAL)),
}
}
fn get_creation_mode(&self) -> io::Result<usize> {
match (self.write, self.append) {
(true, false) => {}
(false, false) =>
if self.truncate || self.create || self.create_new {
return Err(Error::from_raw_os_error(syscall::EINVAL));
},
(_, true) =>
if self.truncate &&!self.create_new {
return Err(Error::from_raw_os_error(syscall::EINVAL));
},
}
Ok(match (self.create, self.truncate, self.create_new) {
(false, false, false) => 0,
(true, false, false) => syscall::O_CREAT,
(false, true, false) => syscall::O_TRUNC,
(true, true, false) => syscall::O_CREAT | syscall::O_TRUNC,
(_, _, true) => syscall::O_CREAT | syscall::O_EXCL,
})
}
}
impl File {
pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
let flags = syscall::O_CLOEXEC |
opts.get_access_mode()? as usize |
opts.get_creation_mode()? as usize |
(opts.custom_flags as usize &!syscall::O_ACCMODE);
let fd = cvt(syscall::open(path.to_str().unwrap(), flags | opts.mode as usize))?;
Ok(File(FileDesc::new(fd)))
}
pub fn file_attr(&self) -> io::Result<FileAttr> {
let mut stat = syscall::Stat::default();
cvt(syscall::fstat(self.0.raw(), &mut stat))?;
Ok(FileAttr { stat: stat })
}
pub fn fsync(&self) -> io::Result<()> {
cvt(syscall::fsync(self.0.raw()))?;
Ok(())
}
pub fn datasync(&self) -> io::Result<()> {
self.fsync()
}
pub fn truncate(&self, size: u64) -> io::Result<()> {
cvt(syscall::ftruncate(self.0.raw(), size as usize))?;
Ok(())
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
pub fn flush(&self) -> io::Result<()> { Ok(()) }
pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
let (whence, pos) = match pos {
// Casting to `i64` is fine, too large values will end up as
// negative which will cause an error in `lseek64`.
SeekFrom::Start(off) => (syscall::SEEK_SET, off as i64),
SeekFrom::End(off) => (syscall::SEEK_END, off),
SeekFrom::Current(off) => (syscall::SEEK_CUR, off),
};
let n = cvt(syscall::lseek(self.0.raw(), pos as isize, whence))?;
Ok(n as u64)
}
pub fn duplicate(&self) -> io::Result<File> {
self.0.duplicate().map(File)
}
pub fn dup(&self, buf: &[u8]) -> io::Result<File> {
let fd = cvt(syscall::dup(*self.fd().as_inner() as usize, buf))?;
Ok(File(FileDesc::new(fd)))
}
pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
set_perm(&self.path()?, perm)
}
pub fn path(&self) -> io::Result<PathBuf> {
let mut buf: [u8; 4096] = [0; 4096];
let count = cvt(syscall::fpath(*self.fd().as_inner() as usize, &mut buf))?;
Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[..count])) }))
}
pub fn fd(&self) -> &FileDesc { &self.0 }
pub fn into_fd(self) -> FileDesc { self.0 }
}
impl DirBuilder {
pub fn new() -> DirBuilder {
DirBuilder { mode: 0o777 }
}
pub fn mkdir(&self, p: &Path) -> io::Result<()> {
let flags = syscall::O_CREAT | syscall::O_CLOEXEC | syscall::O_DIRECTORY | syscall::O_EXCL;
let fd = cvt(syscall::open(p.to_str().unwrap(), flags | (self.mode as usize & 0o777)))?;
let _ = syscall::close(fd);
Ok(())
}
pub fn set_mode(&mut self, mode: u32) {
self.mode = mode as u16;
}
}
impl FromInner<usize> for File {
fn from_inner(fd: usize) -> File {
File(FileDesc::new(fd))
}
}
impl fmt::Debug for File {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut b = f.debug_struct("File");
b.field("fd", &self.0.raw());
if let Ok(path) = self.path() {
b.field("path", &path);
}
/*
if let Some((read, write)) = get_mode(fd) {
b.field("read", &read).field("write", &write);
}
*/
b.finish()
}
}
pub fn readdir(p: &Path) -> io::Result<ReadDir> {
let root = Arc::new(p.to_path_buf());
let flags = syscall::O_CLOEXEC | syscall::O_RDONLY | syscall::O_DIRECTORY;
let fd = cvt(syscall::open(p.to_str().unwrap(), flags))?;
let file = FileDesc::new(fd);
let mut data = Vec::new();
file.read_to_end(&mut data)?;
Ok(ReadDir { data: data, i: 0, root: root })
}
pub fn unlink(p: &Path) -> io::Result<()> {
cvt(syscall::unlink(p.to_str().unwrap()))?;
Ok(())
}
pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
let fd = cvt(syscall::open(old.to_str().unwrap(),
syscall::O_CLOEXEC | syscall::O_STAT | syscall::O_NOFOLLOW))?;
let res = cvt(syscall::frename(fd, new.to_str().unwrap()));
cvt(syscall::close(fd))?;
res?;
Ok(())
}
pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
cvt(syscall::chmod(p.to_str().unwrap(), perm.mode as usize))?;
Ok(())
}
pub fn rmdir(p: &Path) -> io::Result<()> {
cvt(syscall::rmdir(p.to_str().unwrap()))?;
Ok(())
}
pub fn remove_dir_all(path: &Path) -> io::Result<()> {
let filetype = lstat(path)?.file_type();
if filetype.is_symlink() {
unlink(path)
} else {
remove_dir_all_recursive(path)
}
}
fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
for child in readdir(path)? {
let child = child?;
if child.file_type()?.is_dir() {
remove_dir_all_recursive(&child.path())?;
} else {
unlink(&child.path())?;
}
}
rmdir(path)
}
pub fn readlink(p: &Path) -> io::Result<PathBuf> {
let fd = cvt(syscall::open(p.to_str().unwrap(),
syscall::O_CLOEXEC | syscall::O_SYMLINK | syscall::O_RDONLY))?;
let mut buf: [u8; 4096] = [0; 4096];
let res = cvt(syscall::read(fd, &mut buf));
cvt(syscall::close(fd))?;
let count = res?;
Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[..count])) }))
}
pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
let fd = cvt(syscall::open(dst.to_str().unwrap(),
syscall::O_CLOEXEC | syscall::O_SYMLINK |
syscall::O_CREAT | syscall::O_WRONLY | 0o777))?;
let res = cvt(syscall::write(fd, src.to_str().unwrap().as_bytes()));
cvt(syscall::close(fd))?;
res?;
Ok(())
}
pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> {
Err(Error::from_raw_os_error(syscall::ENOSYS))
}
pub fn stat(p: &Path) -> io::Result<FileAttr> {
let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT))?;
let file = File(FileDesc::new(fd));
file.file_attr()
}
pub fn lstat(p: &Path) -> io::Result<FileAttr> {
let fd = cvt(syscall::open(p.to_str().unwrap(),
syscall::O_CLOEXEC | syscall::O_STAT | syscall::O_NOFOLLOW))?;
let file = File(FileDesc::new(fd));
file.file_attr()
}
pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT))?;
let file = File(FileDesc::new(fd));
file.path()
}
pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
use fs::{File, set_permissions};
if!from.is_file() {
return Err(Error::new(ErrorKind::InvalidInput,
"the source path is not an existing regular file"))
}
let mut reader = File::open(from)?;
let mut writer = File::create(to)?;
let perm = reader.metadata()?.permissions();
let ret = io::copy(&mut reader, &mut writer)?;
set_permissions(to, perm)?;
Ok(ret)
}
| { self.append = append; } | identifier_body |
fs.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use os::unix::prelude::*;
use ffi::{OsString, OsStr};
use fmt;
use io::{self, Error, ErrorKind, SeekFrom};
use path::{Path, PathBuf};
use sync::Arc;
use sys::fd::FileDesc;
use sys::time::SystemTime;
use sys::{cvt, syscall};
use sys_common::{AsInner, FromInner};
pub struct File(FileDesc);
#[derive(Clone)]
pub struct FileAttr {
stat: syscall::Stat,
}
pub struct ReadDir {
data: Vec<u8>,
i: usize,
root: Arc<PathBuf>,
}
struct Dir(FileDesc);
unsafe impl Send for Dir {}
unsafe impl Sync for Dir {}
pub struct DirEntry {
root: Arc<PathBuf>,
name: Box<[u8]>
}
#[derive(Clone, Debug)]
pub struct OpenOptions {
// generic
read: bool,
write: bool,
append: bool,
truncate: bool,
create: bool,
create_new: bool,
// system-specific
custom_flags: i32,
mode: u16,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FilePermissions { mode: u16 }
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct FileType { mode: u16 }
#[derive(Debug)]
pub struct DirBuilder { mode: u16 }
impl FileAttr {
pub fn size(&self) -> u64 { self.stat.st_size as u64 }
pub fn perm(&self) -> FilePermissions {
FilePermissions { mode: (self.stat.st_mode as u16) & 0o777 }
}
pub fn file_type(&self) -> FileType {
FileType { mode: self.stat.st_mode as u16 }
}
}
impl FileAttr {
pub fn modified(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(syscall::TimeSpec {
tv_sec: self.stat.st_mtime as i64,
tv_nsec: self.stat.st_mtime_nsec as i32,
}))
}
pub fn accessed(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(syscall::TimeSpec {
tv_sec: self.stat.st_atime as i64,
tv_nsec: self.stat.st_atime_nsec as i32,
}))
}
pub fn created(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(syscall::TimeSpec {
tv_sec: self.stat.st_ctime as i64,
tv_nsec: self.stat.st_ctime_nsec as i32,
}))
}
}
impl AsInner<syscall::Stat> for FileAttr {
fn as_inner(&self) -> &syscall::Stat { &self.stat }
}
impl FilePermissions {
pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
pub fn set_readonly(&mut self, readonly: bool) {
if readonly {
self.mode &=!0o222;
} else {
self.mode |= 0o222;
}
}
pub fn mode(&self) -> u32 { self.mode as u32 }
}
impl FileType {
pub fn is_dir(&self) -> bool { self.is(syscall::MODE_DIR) }
pub fn is_file(&self) -> bool { self.is(syscall::MODE_FILE) }
pub fn is_symlink(&self) -> bool { self.is(syscall::MODE_SYMLINK) }
pub fn is(&self, mode: u16) -> bool {
self.mode & syscall::MODE_TYPE == mode
}
}
impl FromInner<u32> for FilePermissions {
fn from_inner(mode: u32) -> FilePermissions {
FilePermissions { mode: mode as u16 }
}
}
impl fmt::Debug for ReadDir {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
// Thus the result will be e g 'ReadDir("/home")'
fmt::Debug::fmt(&*self.root, f)
}
}
impl Iterator for ReadDir {
type Item = io::Result<DirEntry>;
fn next(&mut self) -> Option<io::Result<DirEntry>> {
loop {
let start = self.i;
let mut i = self.i;
while i < self.data.len() {
self.i += 1;
if self.data[i] == b'\n' {
break;
}
i += 1;
}
if start < self.i {
let ret = DirEntry {
name: self.data[start.. i].to_owned().into_boxed_slice(),
root: self.root.clone()
};
if ret.name_bytes()!= b"." && ret.name_bytes()!= b".." {
return Some(Ok(ret))
}
} else {
return None;
}
}
}
}
impl DirEntry {
pub fn path(&self) -> PathBuf {
self.root.join(OsStr::from_bytes(self.name_bytes()))
}
pub fn file_name(&self) -> OsString {
OsStr::from_bytes(self.name_bytes()).to_os_string()
}
pub fn metadata(&self) -> io::Result<FileAttr> {
lstat(&self.path())
}
pub fn file_type(&self) -> io::Result<FileType> {
lstat(&self.path()).map(|m| m.file_type())
}
fn name_bytes(&self) -> &[u8] {
&*self.name
}
}
impl OpenOptions {
pub fn new() -> OpenOptions {
OpenOptions {
// generic
read: false,
write: false,
append: false,
truncate: false,
create: false,
create_new: false,
// system-specific
custom_flags: 0,
mode: 0o666,
}
}
pub fn read(&mut self, read: bool) { self.read = read; }
pub fn write(&mut self, write: bool) { self.write = write; }
pub fn append(&mut self, append: bool) { self.append = append; }
pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
pub fn create(&mut self, create: bool) { self.create = create; }
pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; }
pub fn mode(&mut self, mode: u32) { self.mode = mode as u16; }
fn get_access_mode(&self) -> io::Result<usize> {
match (self.read, self.write, self.append) {
(true, false, false) => Ok(syscall::O_RDONLY),
(false, true, false) => Ok(syscall::O_WRONLY),
(true, true, false) => Ok(syscall::O_RDWR),
(false, _, true) => Ok(syscall::O_WRONLY | syscall::O_APPEND),
(true, _, true) => Ok(syscall::O_RDWR | syscall::O_APPEND),
(false, false, false) => Err(Error::from_raw_os_error(syscall::EINVAL)),
}
}
fn get_creation_mode(&self) -> io::Result<usize> {
match (self.write, self.append) {
(true, false) => {}
(false, false) =>
if self.truncate || self.create || self.create_new {
return Err(Error::from_raw_os_error(syscall::EINVAL));
},
(_, true) =>
if self.truncate &&!self.create_new {
return Err(Error::from_raw_os_error(syscall::EINVAL));
},
}
Ok(match (self.create, self.truncate, self.create_new) {
(false, false, false) => 0,
(true, false, false) => syscall::O_CREAT,
(false, true, false) => syscall::O_TRUNC,
(true, true, false) => syscall::O_CREAT | syscall::O_TRUNC,
(_, _, true) => syscall::O_CREAT | syscall::O_EXCL,
})
}
}
impl File {
pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
let flags = syscall::O_CLOEXEC |
opts.get_access_mode()? as usize |
opts.get_creation_mode()? as usize |
(opts.custom_flags as usize &!syscall::O_ACCMODE);
let fd = cvt(syscall::open(path.to_str().unwrap(), flags | opts.mode as usize))?;
Ok(File(FileDesc::new(fd)))
}
pub fn file_attr(&self) -> io::Result<FileAttr> {
let mut stat = syscall::Stat::default();
cvt(syscall::fstat(self.0.raw(), &mut stat))?;
Ok(FileAttr { stat: stat })
}
pub fn fsync(&self) -> io::Result<()> {
cvt(syscall::fsync(self.0.raw()))?;
Ok(())
}
pub fn datasync(&self) -> io::Result<()> {
self.fsync()
}
pub fn truncate(&self, size: u64) -> io::Result<()> {
cvt(syscall::ftruncate(self.0.raw(), size as usize))?;
Ok(())
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
pub fn flush(&self) -> io::Result<()> { Ok(()) }
pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
let (whence, pos) = match pos {
// Casting to `i64` is fine, too large values will end up as
// negative which will cause an error in `lseek64`.
SeekFrom::Start(off) => (syscall::SEEK_SET, off as i64),
SeekFrom::End(off) => (syscall::SEEK_END, off),
SeekFrom::Current(off) => (syscall::SEEK_CUR, off),
};
let n = cvt(syscall::lseek(self.0.raw(), pos as isize, whence))?;
Ok(n as u64)
}
pub fn | (&self) -> io::Result<File> {
self.0.duplicate().map(File)
}
pub fn dup(&self, buf: &[u8]) -> io::Result<File> {
let fd = cvt(syscall::dup(*self.fd().as_inner() as usize, buf))?;
Ok(File(FileDesc::new(fd)))
}
pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
set_perm(&self.path()?, perm)
}
pub fn path(&self) -> io::Result<PathBuf> {
let mut buf: [u8; 4096] = [0; 4096];
let count = cvt(syscall::fpath(*self.fd().as_inner() as usize, &mut buf))?;
Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[..count])) }))
}
pub fn fd(&self) -> &FileDesc { &self.0 }
pub fn into_fd(self) -> FileDesc { self.0 }
}
impl DirBuilder {
pub fn new() -> DirBuilder {
DirBuilder { mode: 0o777 }
}
pub fn mkdir(&self, p: &Path) -> io::Result<()> {
let flags = syscall::O_CREAT | syscall::O_CLOEXEC | syscall::O_DIRECTORY | syscall::O_EXCL;
let fd = cvt(syscall::open(p.to_str().unwrap(), flags | (self.mode as usize & 0o777)))?;
let _ = syscall::close(fd);
Ok(())
}
pub fn set_mode(&mut self, mode: u32) {
self.mode = mode as u16;
}
}
impl FromInner<usize> for File {
fn from_inner(fd: usize) -> File {
File(FileDesc::new(fd))
}
}
impl fmt::Debug for File {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut b = f.debug_struct("File");
b.field("fd", &self.0.raw());
if let Ok(path) = self.path() {
b.field("path", &path);
}
/*
if let Some((read, write)) = get_mode(fd) {
b.field("read", &read).field("write", &write);
}
*/
b.finish()
}
}
pub fn readdir(p: &Path) -> io::Result<ReadDir> {
let root = Arc::new(p.to_path_buf());
let flags = syscall::O_CLOEXEC | syscall::O_RDONLY | syscall::O_DIRECTORY;
let fd = cvt(syscall::open(p.to_str().unwrap(), flags))?;
let file = FileDesc::new(fd);
let mut data = Vec::new();
file.read_to_end(&mut data)?;
Ok(ReadDir { data: data, i: 0, root: root })
}
pub fn unlink(p: &Path) -> io::Result<()> {
cvt(syscall::unlink(p.to_str().unwrap()))?;
Ok(())
}
pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
let fd = cvt(syscall::open(old.to_str().unwrap(),
syscall::O_CLOEXEC | syscall::O_STAT | syscall::O_NOFOLLOW))?;
let res = cvt(syscall::frename(fd, new.to_str().unwrap()));
cvt(syscall::close(fd))?;
res?;
Ok(())
}
pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
cvt(syscall::chmod(p.to_str().unwrap(), perm.mode as usize))?;
Ok(())
}
pub fn rmdir(p: &Path) -> io::Result<()> {
cvt(syscall::rmdir(p.to_str().unwrap()))?;
Ok(())
}
pub fn remove_dir_all(path: &Path) -> io::Result<()> {
let filetype = lstat(path)?.file_type();
if filetype.is_symlink() {
unlink(path)
} else {
remove_dir_all_recursive(path)
}
}
fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
for child in readdir(path)? {
let child = child?;
if child.file_type()?.is_dir() {
remove_dir_all_recursive(&child.path())?;
} else {
unlink(&child.path())?;
}
}
rmdir(path)
}
pub fn readlink(p: &Path) -> io::Result<PathBuf> {
let fd = cvt(syscall::open(p.to_str().unwrap(),
syscall::O_CLOEXEC | syscall::O_SYMLINK | syscall::O_RDONLY))?;
let mut buf: [u8; 4096] = [0; 4096];
let res = cvt(syscall::read(fd, &mut buf));
cvt(syscall::close(fd))?;
let count = res?;
Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[..count])) }))
}
pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
let fd = cvt(syscall::open(dst.to_str().unwrap(),
syscall::O_CLOEXEC | syscall::O_SYMLINK |
syscall::O_CREAT | syscall::O_WRONLY | 0o777))?;
let res = cvt(syscall::write(fd, src.to_str().unwrap().as_bytes()));
cvt(syscall::close(fd))?;
res?;
Ok(())
}
pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> {
Err(Error::from_raw_os_error(syscall::ENOSYS))
}
pub fn stat(p: &Path) -> io::Result<FileAttr> {
let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT))?;
let file = File(FileDesc::new(fd));
file.file_attr()
}
pub fn lstat(p: &Path) -> io::Result<FileAttr> {
let fd = cvt(syscall::open(p.to_str().unwrap(),
syscall::O_CLOEXEC | syscall::O_STAT | syscall::O_NOFOLLOW))?;
let file = File(FileDesc::new(fd));
file.file_attr()
}
pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT))?;
let file = File(FileDesc::new(fd));
file.path()
}
pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
use fs::{File, set_permissions};
if!from.is_file() {
return Err(Error::new(ErrorKind::InvalidInput,
"the source path is not an existing regular file"))
}
let mut reader = File::open(from)?;
let mut writer = File::create(to)?;
let perm = reader.metadata()?.permissions();
let ret = io::copy(&mut reader, &mut writer)?;
set_permissions(to, perm)?;
Ok(ret)
}
| duplicate | identifier_name |
mkfifo.rs | #![crate_name = "uu_mkfifo"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
#[macro_use]
extern crate uucore;
use libc::mkfifo;
use std::ffi::CString;
use std::io::{Error, Write};
static NAME: &'static str = "mkfifo";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub fn | (args: Vec<String>) -> i32 {
let mut opts = getopts::Options::new();
opts.optopt("m", "mode", "file permissions for the fifo", "(default 0666)");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(err) => panic!("{}", err),
};
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
if matches.opt_present("help") || matches.free.is_empty() {
let msg = format!("{0} {1}
Usage:
{0} [OPTIONS] NAME...
Create a FIFO with the given name.", NAME, VERSION);
print!("{}", opts.usage(&msg));
if matches.free.is_empty() {
return 1;
}
return 0;
}
let mode = match matches.opt_str("m") {
Some(m) => match usize::from_str_radix(&m, 8) {
Ok(m) => m,
Err(e)=> {
show_error!("invalid mode: {}", e);
return 1;
}
},
None => 0o666,
};
let mut exit_status = 0;
for f in &matches.free {
let err = unsafe { mkfifo(CString::new(f.as_bytes()).unwrap().as_ptr(), mode as libc::mode_t) };
if err == -1 {
show_error!("creating '{}': {}", f, Error::last_os_error().raw_os_error().unwrap());
exit_status = 1;
}
}
exit_status
}
| uumain | identifier_name |
mkfifo.rs | #![crate_name = "uu_mkfifo"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
#[macro_use]
extern crate uucore;
use libc::mkfifo;
use std::ffi::CString;
use std::io::{Error, Write};
static NAME: &'static str = "mkfifo";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub fn uumain(args: Vec<String>) -> i32 | Usage:
{0} [OPTIONS] NAME...
Create a FIFO with the given name.", NAME, VERSION);
print!("{}", opts.usage(&msg));
if matches.free.is_empty() {
return 1;
}
return 0;
}
let mode = match matches.opt_str("m") {
Some(m) => match usize::from_str_radix(&m, 8) {
Ok(m) => m,
Err(e)=> {
show_error!("invalid mode: {}", e);
return 1;
}
},
None => 0o666,
};
let mut exit_status = 0;
for f in &matches.free {
let err = unsafe { mkfifo(CString::new(f.as_bytes()).unwrap().as_ptr(), mode as libc::mode_t) };
if err == -1 {
show_error!("creating '{}': {}", f, Error::last_os_error().raw_os_error().unwrap());
exit_status = 1;
}
}
exit_status
}
| {
let mut opts = getopts::Options::new();
opts.optopt("m", "mode", "file permissions for the fifo", "(default 0666)");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(err) => panic!("{}", err),
};
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
if matches.opt_present("help") || matches.free.is_empty() {
let msg = format!("{0} {1}
| identifier_body |
mkfifo.rs | #![crate_name = "uu_mkfifo"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
#[macro_use]
extern crate uucore;
use libc::mkfifo;
use std::ffi::CString;
use std::io::{Error, Write};
static NAME: &'static str = "mkfifo";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub fn uumain(args: Vec<String>) -> i32 {
let mut opts = getopts::Options::new();
opts.optopt("m", "mode", "file permissions for the fifo", "(default 0666)");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(err) => panic!("{}", err),
};
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
if matches.opt_present("help") || matches.free.is_empty() |
let mode = match matches.opt_str("m") {
Some(m) => match usize::from_str_radix(&m, 8) {
Ok(m) => m,
Err(e)=> {
show_error!("invalid mode: {}", e);
return 1;
}
},
None => 0o666,
};
let mut exit_status = 0;
for f in &matches.free {
let err = unsafe { mkfifo(CString::new(f.as_bytes()).unwrap().as_ptr(), mode as libc::mode_t) };
if err == -1 {
show_error!("creating '{}': {}", f, Error::last_os_error().raw_os_error().unwrap());
exit_status = 1;
}
}
exit_status
}
| {
let msg = format!("{0} {1}
Usage:
{0} [OPTIONS] NAME...
Create a FIFO with the given name.", NAME, VERSION);
print!("{}", opts.usage(&msg));
if matches.free.is_empty() {
return 1;
}
return 0;
} | conditional_block |
binnode.rs | use std::collections::Bitv;
use BinGraph;
/// Contains a binary state and the choices.
#[deriving(PartialEq, Eq, Show, Clone)]
pub struct BinNode {
/// The state composed of bits.
pub state: Bitv,
/// The choices represented as bits that can be flipped.
pub choices: Bitv
}
impl BinNode {
/// Gets pairs from pair of booleans.
pub fn from_pairs(pairs: &[(bool, bool)]) -> BinNode {
BinNode {
state: pairs.iter().map(|&(a, _)| a).collect(),
choices: pairs.iter().map(|&(_, b)| b).collect()
}
}
/// Call closure for each available choice.
#[inline(always)]
pub fn with_choices(&self, f: |i: uint|) {
for i in range(0, self.choices.len())
.zip(self.choices.iter())
.filter(|&(_, v)| v)
.map(|(i, _)| i
) {
f(i)
}
}
/// Calls closure for all choices that are not in graph.
#[inline(always)]
pub fn with_choices_not_in<TAction>(
&self,
graph: &BinGraph<TAction>,
f: |i: uint|
) {
self.with_choices(|i| if!graph.contains_choice(self, i) | )
}
}
| {
f(i)
} | conditional_block |
binnode.rs | use std::collections::Bitv;
use BinGraph;
/// Contains a binary state and the choices.
#[deriving(PartialEq, Eq, Show, Clone)]
pub struct BinNode {
/// The state composed of bits.
pub state: Bitv,
/// The choices represented as bits that can be flipped.
pub choices: Bitv
}
impl BinNode {
/// Gets pairs from pair of booleans.
pub fn from_pairs(pairs: &[(bool, bool)]) -> BinNode {
BinNode {
state: pairs.iter().map(|&(a, _)| a).collect(),
choices: pairs.iter().map(|&(_, b)| b).collect()
}
} |
/// Call closure for each available choice.
#[inline(always)]
pub fn with_choices(&self, f: |i: uint|) {
for i in range(0, self.choices.len())
.zip(self.choices.iter())
.filter(|&(_, v)| v)
.map(|(i, _)| i
) {
f(i)
}
}
/// Calls closure for all choices that are not in graph.
#[inline(always)]
pub fn with_choices_not_in<TAction>(
&self,
graph: &BinGraph<TAction>,
f: |i: uint|
) {
self.with_choices(|i| if!graph.contains_choice(self, i) {
f(i)
})
}
} | random_line_split |
|
binnode.rs | use std::collections::Bitv;
use BinGraph;
/// Contains a binary state and the choices.
#[deriving(PartialEq, Eq, Show, Clone)]
pub struct BinNode {
/// The state composed of bits.
pub state: Bitv,
/// The choices represented as bits that can be flipped.
pub choices: Bitv
}
impl BinNode {
/// Gets pairs from pair of booleans.
pub fn from_pairs(pairs: &[(bool, bool)]) -> BinNode |
/// Call closure for each available choice.
#[inline(always)]
pub fn with_choices(&self, f: |i: uint|) {
for i in range(0, self.choices.len())
.zip(self.choices.iter())
.filter(|&(_, v)| v)
.map(|(i, _)| i
) {
f(i)
}
}
/// Calls closure for all choices that are not in graph.
#[inline(always)]
pub fn with_choices_not_in<TAction>(
&self,
graph: &BinGraph<TAction>,
f: |i: uint|
) {
self.with_choices(|i| if!graph.contains_choice(self, i) {
f(i)
})
}
}
| {
BinNode {
state: pairs.iter().map(|&(a, _)| a).collect(),
choices: pairs.iter().map(|&(_, b)| b).collect()
}
} | identifier_body |
binnode.rs | use std::collections::Bitv;
use BinGraph;
/// Contains a binary state and the choices.
#[deriving(PartialEq, Eq, Show, Clone)]
pub struct BinNode {
/// The state composed of bits.
pub state: Bitv,
/// The choices represented as bits that can be flipped.
pub choices: Bitv
}
impl BinNode {
/// Gets pairs from pair of booleans.
pub fn from_pairs(pairs: &[(bool, bool)]) -> BinNode {
BinNode {
state: pairs.iter().map(|&(a, _)| a).collect(),
choices: pairs.iter().map(|&(_, b)| b).collect()
}
}
/// Call closure for each available choice.
#[inline(always)]
pub fn | (&self, f: |i: uint|) {
for i in range(0, self.choices.len())
.zip(self.choices.iter())
.filter(|&(_, v)| v)
.map(|(i, _)| i
) {
f(i)
}
}
/// Calls closure for all choices that are not in graph.
#[inline(always)]
pub fn with_choices_not_in<TAction>(
&self,
graph: &BinGraph<TAction>,
f: |i: uint|
) {
self.with_choices(|i| if!graph.contains_choice(self, i) {
f(i)
})
}
}
| with_choices | identifier_name |
node_void_ptr.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS library requires that DOM nodes be convertable to *c_void through this trait
extern mod netsurfcss;
use dom::node::AbstractNode;
use core::cast;
// FIXME: Rust #3908. rust-css can't reexport VoidPtrLike
use css::node_void_ptr::netsurfcss::util::VoidPtrLike;
impl VoidPtrLike for AbstractNode {
fn | (node: *libc::c_void) -> AbstractNode {
assert!(node.is_not_null());
unsafe {
cast::transmute(node)
}
}
fn to_void_ptr(&self) -> *libc::c_void {
unsafe {
cast::transmute(*self)
}
}
}
| from_void_ptr | identifier_name |
node_void_ptr.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS library requires that DOM nodes be convertable to *c_void through this trait
extern mod netsurfcss;
use dom::node::AbstractNode;
use core::cast;
// FIXME: Rust #3908. rust-css can't reexport VoidPtrLike
use css::node_void_ptr::netsurfcss::util::VoidPtrLike;
impl VoidPtrLike for AbstractNode {
fn from_void_ptr(node: *libc::c_void) -> AbstractNode {
assert!(node.is_not_null());
unsafe {
cast::transmute(node)
}
}
fn to_void_ptr(&self) -> *libc::c_void |
}
| {
unsafe {
cast::transmute(*self)
}
} | identifier_body |
node_void_ptr.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS library requires that DOM nodes be convertable to *c_void through this trait
extern mod netsurfcss;
use dom::node::AbstractNode;
use core::cast;
// FIXME: Rust #3908. rust-css can't reexport VoidPtrLike
use css::node_void_ptr::netsurfcss::util::VoidPtrLike; | fn from_void_ptr(node: *libc::c_void) -> AbstractNode {
assert!(node.is_not_null());
unsafe {
cast::transmute(node)
}
}
fn to_void_ptr(&self) -> *libc::c_void {
unsafe {
cast::transmute(*self)
}
}
} |
impl VoidPtrLike for AbstractNode { | random_line_split |
lmmsg.rs | // Copyright © 2015-2017 winapi-rs developers
// 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.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according to those terms.
//! This file contains structures, function prototypes, and definitions for the NetMessage API
use shared::lmcons::NET_API_STATUS;
use shared::minwindef::{DWORD, LPBYTE, LPDWORD};
use um::winnt::{LPCWSTR, LPWSTR};
extern "system" {
pub fn NetMessageNameAdd(
servername: LPCWSTR,
msgname: LPCWSTR,
) -> NET_API_STATUS;
pub fn NetMessageNameEnum(
servername: LPCWSTR,
level: DWORD,
bufptr: *mut LPBYTE,
prefmaxlen: DWORD,
entriesread: LPDWORD,
totalentries: LPDWORD,
resumehandle: LPDWORD,
) -> NET_API_STATUS;
pub fn NetMessageNameGetInfo(
servername: LPCWSTR,
msgname: LPCWSTR,
level: DWORD,
bufptr: *mut LPBYTE,
) -> NET_API_STATUS;
pub fn NetMessageNameDel(
servername: LPCWSTR,
msgname: LPCWSTR,
) -> NET_API_STATUS;
pub fn NetMessageBufferSend(
servername: LPCWSTR,
msgname: LPCWSTR,
fromname: LPCWSTR,
buf: LPBYTE,
buflen: DWORD,
) -> NET_API_STATUS;
}
STRUCT!{struct MSG_INFO_0 {
msgi0_name: LPWSTR,
}}
pub type PMSG_INFO_0 = *mut MSG_INFO_0;
pub type LPMSG_INFO_0 = *mut MSG_INFO_0;
STRUCT!{struct MSG_INFO_1 {
msgi1_name: LPWSTR,
msgi1_forward_flag: DWORD,
msgi1_forward: LPWSTR, | pub type LPMSG_INFO_1 = *mut MSG_INFO_1;
pub const MSGNAME_NOT_FORWARDED: DWORD = 0;
pub const MSGNAME_FORWARDED_TO: DWORD = 0x04;
pub const MSGNAME_FORWARDED_FROM: DWORD = 0x10; | }}
pub type PMSG_INFO_1 = *mut MSG_INFO_1; | random_line_split |
reseeding.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.
//! A wrapper around another RNG that reseeds it after it
//! generates a certain number of random bytes.
use core::prelude::*;
use {Rng, SeedableRng};
/// How many bytes of entropy the underling RNG is allowed to generate
/// before it is reseeded.
const DEFAULT_GENERATION_THRESHOLD: usize = 32 * 1024;
/// A wrapper around any RNG which reseeds the underlying RNG after it
/// has generated a certain number of random bytes.
pub struct ReseedingRng<R, Rsdr> {
rng: R,
generation_threshold: usize,
bytes_generated: usize,
/// Controls the behaviour when reseeding the RNG.
pub reseeder: Rsdr,
}
impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> {
/// Create a new `ReseedingRng` with the given parameters.
///
/// # Arguments
///
/// * `rng`: the random number generator to use.
/// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG.
/// * `reseeder`: the reseeding object to use.
pub fn new(rng: R, generation_threshold: usize, reseeder: Rsdr) -> ReseedingRng<R,Rsdr> |
/// Reseed the internal RNG if the number of bytes that have been
/// generated exceed the threshold.
pub fn reseed_if_necessary(&mut self) {
if self.bytes_generated >= self.generation_threshold {
self.reseeder.reseed(&mut self.rng);
self.bytes_generated = 0;
}
}
}
impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> {
fn next_u32(&mut self) -> u32 {
self.reseed_if_necessary();
self.bytes_generated += 4;
self.rng.next_u32()
}
fn next_u64(&mut self) -> u64 {
self.reseed_if_necessary();
self.bytes_generated += 8;
self.rng.next_u64()
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
self.reseed_if_necessary();
self.bytes_generated += dest.len();
self.rng.fill_bytes(dest)
}
}
impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default>
SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> {
fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) {
self.rng.reseed(seed);
self.reseeder = rsdr;
self.bytes_generated = 0;
}
/// Create a new `ReseedingRng` from the given reseeder and
/// seed. This uses a default value for `generation_threshold`.
fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> {
ReseedingRng {
rng: SeedableRng::from_seed(seed),
generation_threshold: DEFAULT_GENERATION_THRESHOLD,
bytes_generated: 0,
reseeder: rsdr
}
}
}
/// Something that can be used to reseed an RNG via `ReseedingRng`.
pub trait Reseeder<R> {
/// Reseed the given RNG.
fn reseed(&mut self, rng: &mut R);
}
/// Reseed an RNG using a `Default` instance. This reseeds by
/// replacing the RNG with the result of a `Default::default` call.
#[derive(Copy, Clone)]
pub struct ReseedWithDefault;
impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault {
fn reseed(&mut self, rng: &mut R) {
*rng = Default::default();
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Default for ReseedWithDefault {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> ReseedWithDefault { ReseedWithDefault }
}
#[cfg(test)]
mod tests {
use std::prelude::v1::*;
use core::iter::{order, repeat};
use super::{ReseedingRng, ReseedWithDefault};
use {SeedableRng, Rng};
struct Counter {
i: u32
}
impl Rng for Counter {
fn next_u32(&mut self) -> u32 {
self.i += 1;
// very random
self.i - 1
}
}
impl Default for Counter {
fn default() -> Counter {
Counter { i: 0 }
}
}
impl SeedableRng<u32> for Counter {
fn reseed(&mut self, seed: u32) {
self.i = seed;
}
fn from_seed(seed: u32) -> Counter {
Counter { i: seed }
}
}
type MyRng = ReseedingRng<Counter, ReseedWithDefault>;
#[test]
fn test_reseeding() {
let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault);
let mut i = 0;
for _ in 0..1000 {
assert_eq!(rs.next_u32(), i % 100);
i += 1;
}
}
#[test]
fn test_rng_seeded() {
let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_rng_reseed() {
let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3));
let string1: String = r.gen_ascii_chars().take(100).collect();
r.reseed((ReseedWithDefault, 3));
let string2: String = r.gen_ascii_chars().take(100).collect();
assert_eq!(string1, string2);
}
const FILL_BYTES_V_LEN: usize = 13579;
#[test]
fn test_rng_fill_bytes() {
let mut v = vec![0; FILL_BYTES_V_LEN];
::test::rng().fill_bytes(&mut v);
// Sanity test: if we've gotten here, `fill_bytes` has not infinitely
// recursed.
assert_eq!(v.len(), FILL_BYTES_V_LEN);
// To test that `fill_bytes` actually did something, check that the
// average of `v` is not 0.
let mut sum = 0.0;
for &x in &v {
sum += x as f64;
}
assert!(sum / v.len() as f64!= 0.0);
}
}
| {
ReseedingRng {
rng: rng,
generation_threshold: generation_threshold,
bytes_generated: 0,
reseeder: reseeder
}
} | identifier_body |
reseeding.rs | // 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.
//! A wrapper around another RNG that reseeds it after it
//! generates a certain number of random bytes.
use core::prelude::*;
use {Rng, SeedableRng};
/// How many bytes of entropy the underling RNG is allowed to generate
/// before it is reseeded.
const DEFAULT_GENERATION_THRESHOLD: usize = 32 * 1024;
/// A wrapper around any RNG which reseeds the underlying RNG after it
/// has generated a certain number of random bytes.
pub struct ReseedingRng<R, Rsdr> {
rng: R,
generation_threshold: usize,
bytes_generated: usize,
/// Controls the behaviour when reseeding the RNG.
pub reseeder: Rsdr,
}
impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> {
/// Create a new `ReseedingRng` with the given parameters.
///
/// # Arguments
///
/// * `rng`: the random number generator to use.
/// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG.
/// * `reseeder`: the reseeding object to use.
pub fn new(rng: R, generation_threshold: usize, reseeder: Rsdr) -> ReseedingRng<R,Rsdr> {
ReseedingRng {
rng: rng,
generation_threshold: generation_threshold,
bytes_generated: 0,
reseeder: reseeder
}
}
/// Reseed the internal RNG if the number of bytes that have been
/// generated exceed the threshold.
pub fn reseed_if_necessary(&mut self) {
if self.bytes_generated >= self.generation_threshold {
self.reseeder.reseed(&mut self.rng);
self.bytes_generated = 0;
}
}
}
impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> {
fn next_u32(&mut self) -> u32 {
self.reseed_if_necessary();
self.bytes_generated += 4;
self.rng.next_u32()
}
fn next_u64(&mut self) -> u64 {
self.reseed_if_necessary();
self.bytes_generated += 8;
self.rng.next_u64()
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
self.reseed_if_necessary();
self.bytes_generated += dest.len();
self.rng.fill_bytes(dest)
}
}
impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default>
SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> {
fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) {
self.rng.reseed(seed);
self.reseeder = rsdr;
self.bytes_generated = 0;
}
/// Create a new `ReseedingRng` from the given reseeder and
/// seed. This uses a default value for `generation_threshold`.
fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> {
ReseedingRng {
rng: SeedableRng::from_seed(seed),
generation_threshold: DEFAULT_GENERATION_THRESHOLD,
bytes_generated: 0,
reseeder: rsdr
}
}
}
/// Something that can be used to reseed an RNG via `ReseedingRng`.
pub trait Reseeder<R> {
/// Reseed the given RNG.
fn reseed(&mut self, rng: &mut R);
}
/// Reseed an RNG using a `Default` instance. This reseeds by
/// replacing the RNG with the result of a `Default::default` call.
#[derive(Copy, Clone)]
pub struct ReseedWithDefault;
impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault {
fn reseed(&mut self, rng: &mut R) {
*rng = Default::default();
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Default for ReseedWithDefault {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> ReseedWithDefault { ReseedWithDefault }
}
#[cfg(test)]
mod tests {
use std::prelude::v1::*;
use core::iter::{order, repeat};
use super::{ReseedingRng, ReseedWithDefault};
use {SeedableRng, Rng};
struct Counter {
i: u32
}
impl Rng for Counter {
fn next_u32(&mut self) -> u32 {
self.i += 1;
// very random
self.i - 1
}
}
impl Default for Counter {
fn default() -> Counter {
Counter { i: 0 }
}
}
impl SeedableRng<u32> for Counter {
fn reseed(&mut self, seed: u32) {
self.i = seed;
}
fn from_seed(seed: u32) -> Counter {
Counter { i: seed }
}
}
type MyRng = ReseedingRng<Counter, ReseedWithDefault>;
#[test]
fn test_reseeding() {
let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault);
let mut i = 0;
for _ in 0..1000 {
assert_eq!(rs.next_u32(), i % 100);
i += 1;
}
}
#[test]
fn test_rng_seeded() {
let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_rng_reseed() {
let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3));
let string1: String = r.gen_ascii_chars().take(100).collect();
r.reseed((ReseedWithDefault, 3));
let string2: String = r.gen_ascii_chars().take(100).collect();
assert_eq!(string1, string2);
}
const FILL_BYTES_V_LEN: usize = 13579;
#[test]
fn test_rng_fill_bytes() {
let mut v = vec![0; FILL_BYTES_V_LEN];
::test::rng().fill_bytes(&mut v);
// Sanity test: if we've gotten here, `fill_bytes` has not infinitely
// recursed.
assert_eq!(v.len(), FILL_BYTES_V_LEN);
// To test that `fill_bytes` actually did something, check that the
// average of `v` is not 0.
let mut sum = 0.0;
for &x in &v {
sum += x as f64;
}
assert!(sum / v.len() as f64!= 0.0);
}
} | // 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.
// | random_line_split |
|
reseeding.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.
//! A wrapper around another RNG that reseeds it after it
//! generates a certain number of random bytes.
use core::prelude::*;
use {Rng, SeedableRng};
/// How many bytes of entropy the underling RNG is allowed to generate
/// before it is reseeded.
const DEFAULT_GENERATION_THRESHOLD: usize = 32 * 1024;
/// A wrapper around any RNG which reseeds the underlying RNG after it
/// has generated a certain number of random bytes.
pub struct ReseedingRng<R, Rsdr> {
rng: R,
generation_threshold: usize,
bytes_generated: usize,
/// Controls the behaviour when reseeding the RNG.
pub reseeder: Rsdr,
}
impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> {
/// Create a new `ReseedingRng` with the given parameters.
///
/// # Arguments
///
/// * `rng`: the random number generator to use.
/// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG.
/// * `reseeder`: the reseeding object to use.
pub fn new(rng: R, generation_threshold: usize, reseeder: Rsdr) -> ReseedingRng<R,Rsdr> {
ReseedingRng {
rng: rng,
generation_threshold: generation_threshold,
bytes_generated: 0,
reseeder: reseeder
}
}
/// Reseed the internal RNG if the number of bytes that have been
/// generated exceed the threshold.
pub fn reseed_if_necessary(&mut self) {
if self.bytes_generated >= self.generation_threshold |
}
}
impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> {
fn next_u32(&mut self) -> u32 {
self.reseed_if_necessary();
self.bytes_generated += 4;
self.rng.next_u32()
}
fn next_u64(&mut self) -> u64 {
self.reseed_if_necessary();
self.bytes_generated += 8;
self.rng.next_u64()
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
self.reseed_if_necessary();
self.bytes_generated += dest.len();
self.rng.fill_bytes(dest)
}
}
impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default>
SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> {
fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) {
self.rng.reseed(seed);
self.reseeder = rsdr;
self.bytes_generated = 0;
}
/// Create a new `ReseedingRng` from the given reseeder and
/// seed. This uses a default value for `generation_threshold`.
fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> {
ReseedingRng {
rng: SeedableRng::from_seed(seed),
generation_threshold: DEFAULT_GENERATION_THRESHOLD,
bytes_generated: 0,
reseeder: rsdr
}
}
}
/// Something that can be used to reseed an RNG via `ReseedingRng`.
pub trait Reseeder<R> {
/// Reseed the given RNG.
fn reseed(&mut self, rng: &mut R);
}
/// Reseed an RNG using a `Default` instance. This reseeds by
/// replacing the RNG with the result of a `Default::default` call.
#[derive(Copy, Clone)]
pub struct ReseedWithDefault;
impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault {
fn reseed(&mut self, rng: &mut R) {
*rng = Default::default();
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Default for ReseedWithDefault {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> ReseedWithDefault { ReseedWithDefault }
}
#[cfg(test)]
mod tests {
use std::prelude::v1::*;
use core::iter::{order, repeat};
use super::{ReseedingRng, ReseedWithDefault};
use {SeedableRng, Rng};
struct Counter {
i: u32
}
impl Rng for Counter {
fn next_u32(&mut self) -> u32 {
self.i += 1;
// very random
self.i - 1
}
}
impl Default for Counter {
fn default() -> Counter {
Counter { i: 0 }
}
}
impl SeedableRng<u32> for Counter {
fn reseed(&mut self, seed: u32) {
self.i = seed;
}
fn from_seed(seed: u32) -> Counter {
Counter { i: seed }
}
}
type MyRng = ReseedingRng<Counter, ReseedWithDefault>;
#[test]
fn test_reseeding() {
let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault);
let mut i = 0;
for _ in 0..1000 {
assert_eq!(rs.next_u32(), i % 100);
i += 1;
}
}
#[test]
fn test_rng_seeded() {
let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_rng_reseed() {
let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3));
let string1: String = r.gen_ascii_chars().take(100).collect();
r.reseed((ReseedWithDefault, 3));
let string2: String = r.gen_ascii_chars().take(100).collect();
assert_eq!(string1, string2);
}
const FILL_BYTES_V_LEN: usize = 13579;
#[test]
fn test_rng_fill_bytes() {
let mut v = vec![0; FILL_BYTES_V_LEN];
::test::rng().fill_bytes(&mut v);
// Sanity test: if we've gotten here, `fill_bytes` has not infinitely
// recursed.
assert_eq!(v.len(), FILL_BYTES_V_LEN);
// To test that `fill_bytes` actually did something, check that the
// average of `v` is not 0.
let mut sum = 0.0;
for &x in &v {
sum += x as f64;
}
assert!(sum / v.len() as f64!= 0.0);
}
}
| {
self.reseeder.reseed(&mut self.rng);
self.bytes_generated = 0;
} | conditional_block |
reseeding.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.
//! A wrapper around another RNG that reseeds it after it
//! generates a certain number of random bytes.
use core::prelude::*;
use {Rng, SeedableRng};
/// How many bytes of entropy the underling RNG is allowed to generate
/// before it is reseeded.
const DEFAULT_GENERATION_THRESHOLD: usize = 32 * 1024;
/// A wrapper around any RNG which reseeds the underlying RNG after it
/// has generated a certain number of random bytes.
pub struct | <R, Rsdr> {
rng: R,
generation_threshold: usize,
bytes_generated: usize,
/// Controls the behaviour when reseeding the RNG.
pub reseeder: Rsdr,
}
impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> {
/// Create a new `ReseedingRng` with the given parameters.
///
/// # Arguments
///
/// * `rng`: the random number generator to use.
/// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG.
/// * `reseeder`: the reseeding object to use.
pub fn new(rng: R, generation_threshold: usize, reseeder: Rsdr) -> ReseedingRng<R,Rsdr> {
ReseedingRng {
rng: rng,
generation_threshold: generation_threshold,
bytes_generated: 0,
reseeder: reseeder
}
}
/// Reseed the internal RNG if the number of bytes that have been
/// generated exceed the threshold.
pub fn reseed_if_necessary(&mut self) {
if self.bytes_generated >= self.generation_threshold {
self.reseeder.reseed(&mut self.rng);
self.bytes_generated = 0;
}
}
}
impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> {
fn next_u32(&mut self) -> u32 {
self.reseed_if_necessary();
self.bytes_generated += 4;
self.rng.next_u32()
}
fn next_u64(&mut self) -> u64 {
self.reseed_if_necessary();
self.bytes_generated += 8;
self.rng.next_u64()
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
self.reseed_if_necessary();
self.bytes_generated += dest.len();
self.rng.fill_bytes(dest)
}
}
impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default>
SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> {
fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) {
self.rng.reseed(seed);
self.reseeder = rsdr;
self.bytes_generated = 0;
}
/// Create a new `ReseedingRng` from the given reseeder and
/// seed. This uses a default value for `generation_threshold`.
fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> {
ReseedingRng {
rng: SeedableRng::from_seed(seed),
generation_threshold: DEFAULT_GENERATION_THRESHOLD,
bytes_generated: 0,
reseeder: rsdr
}
}
}
/// Something that can be used to reseed an RNG via `ReseedingRng`.
pub trait Reseeder<R> {
/// Reseed the given RNG.
fn reseed(&mut self, rng: &mut R);
}
/// Reseed an RNG using a `Default` instance. This reseeds by
/// replacing the RNG with the result of a `Default::default` call.
#[derive(Copy, Clone)]
pub struct ReseedWithDefault;
impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault {
fn reseed(&mut self, rng: &mut R) {
*rng = Default::default();
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Default for ReseedWithDefault {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> ReseedWithDefault { ReseedWithDefault }
}
#[cfg(test)]
mod tests {
use std::prelude::v1::*;
use core::iter::{order, repeat};
use super::{ReseedingRng, ReseedWithDefault};
use {SeedableRng, Rng};
struct Counter {
i: u32
}
impl Rng for Counter {
fn next_u32(&mut self) -> u32 {
self.i += 1;
// very random
self.i - 1
}
}
impl Default for Counter {
fn default() -> Counter {
Counter { i: 0 }
}
}
impl SeedableRng<u32> for Counter {
fn reseed(&mut self, seed: u32) {
self.i = seed;
}
fn from_seed(seed: u32) -> Counter {
Counter { i: seed }
}
}
type MyRng = ReseedingRng<Counter, ReseedWithDefault>;
#[test]
fn test_reseeding() {
let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault);
let mut i = 0;
for _ in 0..1000 {
assert_eq!(rs.next_u32(), i % 100);
i += 1;
}
}
#[test]
fn test_rng_seeded() {
let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_rng_reseed() {
let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3));
let string1: String = r.gen_ascii_chars().take(100).collect();
r.reseed((ReseedWithDefault, 3));
let string2: String = r.gen_ascii_chars().take(100).collect();
assert_eq!(string1, string2);
}
const FILL_BYTES_V_LEN: usize = 13579;
#[test]
fn test_rng_fill_bytes() {
let mut v = vec![0; FILL_BYTES_V_LEN];
::test::rng().fill_bytes(&mut v);
// Sanity test: if we've gotten here, `fill_bytes` has not infinitely
// recursed.
assert_eq!(v.len(), FILL_BYTES_V_LEN);
// To test that `fill_bytes` actually did something, check that the
// average of `v` is not 0.
let mut sum = 0.0;
for &x in &v {
sum += x as f64;
}
assert!(sum / v.len() as f64!= 0.0);
}
}
| ReseedingRng | identifier_name |
error.rs | use std::error::Error as StdError;
use std::string;
use std::{fmt, io};
/// The errors that can arise while parsing a JSON stream.
#[derive(Clone, Copy, PartialEq)]
pub enum ErrorCode {
InvalidSyntax,
InvalidNumber,
EOFWhileParsingObject,
EOFWhileParsingArray,
EOFWhileParsingValue,
EOFWhileParsingString,
KeyMustBeAString,
ExpectedColon,
TrailingCharacters,
TrailingComma,
InvalidEscape,
InvalidUnicodeCodePoint,
LoneLeadingSurrogateInHexEscape,
UnexpectedEndOfHexEscape,
UnrecognizedHex,
NotFourDigit,
ControlCharacterInString,
NotUtf8,
}
#[derive(Debug)]
pub enum ParserError {
/// msg, line, col
SyntaxError(ErrorCode, usize, usize),
IoError(io::Error),
}
impl PartialEq for ParserError {
fn eq(&self, other: &ParserError) -> bool {
match (self, other) {
(&ParserError::SyntaxError(msg0, line0, col0), &ParserError::SyntaxError(msg1, line1, col1)) =>
msg0 == msg1 && line0 == line1 && col0 == col1,
(&ParserError::IoError(_), _) => false,
(_, &ParserError::IoError(_)) => false,
}
}
}
/// Returns a readable error string for a given error code.
pub fn error_str(error: ErrorCode) -> &'static str {
match error {
ErrorCode::InvalidSyntax => "invalid syntax",
ErrorCode::InvalidNumber => "invalid number",
ErrorCode::EOFWhileParsingObject => "EOF While parsing object",
ErrorCode::EOFWhileParsingArray => "EOF While parsing array",
ErrorCode::EOFWhileParsingValue => "EOF While parsing value",
ErrorCode::EOFWhileParsingString => "EOF While parsing string",
ErrorCode::KeyMustBeAString => "key must be a string",
ErrorCode::ExpectedColon => "expected `:`",
ErrorCode::TrailingCharacters => "trailing characters",
ErrorCode::TrailingComma => "trailing comma",
ErrorCode::InvalidEscape => "invalid escape",
ErrorCode::UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
ErrorCode::NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
ErrorCode::ControlCharacterInString => "unescaped control character in string",
ErrorCode::NotUtf8 => "contents not utf-8",
ErrorCode::InvalidUnicodeCodePoint => "invalid Unicode code point",
ErrorCode::LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
ErrorCode::UnexpectedEndOfHexEscape => "unexpected end of hex escape",
}
}
#[derive(PartialEq, Debug)]
pub enum DecoderError {
ParseError(ParserError),
ExpectedError(string::String, string::String),
MissingFieldError(string::String),
UnknownVariantError(string::String),
ApplicationError(string::String),
EOF,
}
#[derive(Copy, Debug)]
pub enum EncoderError {
FmtError(fmt::Error),
BadHashmapKey,
}
impl Clone for EncoderError {
fn clone(&self) -> Self { *self }
}
impl fmt::Debug for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
error_str(*self).fmt(f)
}
}
impl StdError for DecoderError {
fn description(&self) -> &str { "decoder error" }
fn cause(&self) -> Option<&StdError> {
match *self {
DecoderError::ParseError(ref e) => Some(e),
_ => None,
}
}
}
impl fmt::Display for DecoderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<ParserError> for DecoderError {
fn from(err: ParserError) -> DecoderError {
DecoderError::ParseError(From::from(err))
}
}
impl StdError for ParserError {
fn description(&self) -> &str { "failed to parse json" }
}
impl fmt::Display for ParserError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<io::Error> for ParserError {
fn from(err: io::Error) -> ParserError {
ParserError::IoError(err)
}
}
impl StdError for EncoderError {
fn | (&self) -> &str { "encoder error" }
}
impl fmt::Display for EncoderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<fmt::Error> for EncoderError {
fn from(err: fmt::Error) -> EncoderError { EncoderError::FmtError(err) }
}
| description | identifier_name |
error.rs | use std::error::Error as StdError;
use std::string;
use std::{fmt, io};
/// The errors that can arise while parsing a JSON stream.
#[derive(Clone, Copy, PartialEq)]
pub enum ErrorCode {
InvalidSyntax,
InvalidNumber,
EOFWhileParsingObject,
EOFWhileParsingArray,
EOFWhileParsingValue,
EOFWhileParsingString,
KeyMustBeAString,
ExpectedColon,
TrailingCharacters,
TrailingComma,
InvalidEscape,
InvalidUnicodeCodePoint,
LoneLeadingSurrogateInHexEscape, | NotUtf8,
}
#[derive(Debug)]
pub enum ParserError {
/// msg, line, col
SyntaxError(ErrorCode, usize, usize),
IoError(io::Error),
}
impl PartialEq for ParserError {
fn eq(&self, other: &ParserError) -> bool {
match (self, other) {
(&ParserError::SyntaxError(msg0, line0, col0), &ParserError::SyntaxError(msg1, line1, col1)) =>
msg0 == msg1 && line0 == line1 && col0 == col1,
(&ParserError::IoError(_), _) => false,
(_, &ParserError::IoError(_)) => false,
}
}
}
/// Returns a readable error string for a given error code.
pub fn error_str(error: ErrorCode) -> &'static str {
match error {
ErrorCode::InvalidSyntax => "invalid syntax",
ErrorCode::InvalidNumber => "invalid number",
ErrorCode::EOFWhileParsingObject => "EOF While parsing object",
ErrorCode::EOFWhileParsingArray => "EOF While parsing array",
ErrorCode::EOFWhileParsingValue => "EOF While parsing value",
ErrorCode::EOFWhileParsingString => "EOF While parsing string",
ErrorCode::KeyMustBeAString => "key must be a string",
ErrorCode::ExpectedColon => "expected `:`",
ErrorCode::TrailingCharacters => "trailing characters",
ErrorCode::TrailingComma => "trailing comma",
ErrorCode::InvalidEscape => "invalid escape",
ErrorCode::UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
ErrorCode::NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
ErrorCode::ControlCharacterInString => "unescaped control character in string",
ErrorCode::NotUtf8 => "contents not utf-8",
ErrorCode::InvalidUnicodeCodePoint => "invalid Unicode code point",
ErrorCode::LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
ErrorCode::UnexpectedEndOfHexEscape => "unexpected end of hex escape",
}
}
#[derive(PartialEq, Debug)]
pub enum DecoderError {
ParseError(ParserError),
ExpectedError(string::String, string::String),
MissingFieldError(string::String),
UnknownVariantError(string::String),
ApplicationError(string::String),
EOF,
}
#[derive(Copy, Debug)]
pub enum EncoderError {
FmtError(fmt::Error),
BadHashmapKey,
}
impl Clone for EncoderError {
fn clone(&self) -> Self { *self }
}
impl fmt::Debug for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
error_str(*self).fmt(f)
}
}
impl StdError for DecoderError {
fn description(&self) -> &str { "decoder error" }
fn cause(&self) -> Option<&StdError> {
match *self {
DecoderError::ParseError(ref e) => Some(e),
_ => None,
}
}
}
impl fmt::Display for DecoderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<ParserError> for DecoderError {
fn from(err: ParserError) -> DecoderError {
DecoderError::ParseError(From::from(err))
}
}
impl StdError for ParserError {
fn description(&self) -> &str { "failed to parse json" }
}
impl fmt::Display for ParserError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<io::Error> for ParserError {
fn from(err: io::Error) -> ParserError {
ParserError::IoError(err)
}
}
impl StdError for EncoderError {
fn description(&self) -> &str { "encoder error" }
}
impl fmt::Display for EncoderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<fmt::Error> for EncoderError {
fn from(err: fmt::Error) -> EncoderError { EncoderError::FmtError(err) }
} | UnexpectedEndOfHexEscape,
UnrecognizedHex,
NotFourDigit,
ControlCharacterInString, | random_line_split |
error.rs | use std::error::Error as StdError;
use std::string;
use std::{fmt, io};
/// The errors that can arise while parsing a JSON stream.
#[derive(Clone, Copy, PartialEq)]
pub enum ErrorCode {
InvalidSyntax,
InvalidNumber,
EOFWhileParsingObject,
EOFWhileParsingArray,
EOFWhileParsingValue,
EOFWhileParsingString,
KeyMustBeAString,
ExpectedColon,
TrailingCharacters,
TrailingComma,
InvalidEscape,
InvalidUnicodeCodePoint,
LoneLeadingSurrogateInHexEscape,
UnexpectedEndOfHexEscape,
UnrecognizedHex,
NotFourDigit,
ControlCharacterInString,
NotUtf8,
}
#[derive(Debug)]
pub enum ParserError {
/// msg, line, col
SyntaxError(ErrorCode, usize, usize),
IoError(io::Error),
}
impl PartialEq for ParserError {
fn eq(&self, other: &ParserError) -> bool {
match (self, other) {
(&ParserError::SyntaxError(msg0, line0, col0), &ParserError::SyntaxError(msg1, line1, col1)) =>
msg0 == msg1 && line0 == line1 && col0 == col1,
(&ParserError::IoError(_), _) => false,
(_, &ParserError::IoError(_)) => false,
}
}
}
/// Returns a readable error string for a given error code.
pub fn error_str(error: ErrorCode) -> &'static str | }
}
#[derive(PartialEq, Debug)]
pub enum DecoderError {
ParseError(ParserError),
ExpectedError(string::String, string::String),
MissingFieldError(string::String),
UnknownVariantError(string::String),
ApplicationError(string::String),
EOF,
}
#[derive(Copy, Debug)]
pub enum EncoderError {
FmtError(fmt::Error),
BadHashmapKey,
}
impl Clone for EncoderError {
fn clone(&self) -> Self { *self }
}
impl fmt::Debug for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
error_str(*self).fmt(f)
}
}
impl StdError for DecoderError {
fn description(&self) -> &str { "decoder error" }
fn cause(&self) -> Option<&StdError> {
match *self {
DecoderError::ParseError(ref e) => Some(e),
_ => None,
}
}
}
impl fmt::Display for DecoderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<ParserError> for DecoderError {
fn from(err: ParserError) -> DecoderError {
DecoderError::ParseError(From::from(err))
}
}
impl StdError for ParserError {
fn description(&self) -> &str { "failed to parse json" }
}
impl fmt::Display for ParserError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<io::Error> for ParserError {
fn from(err: io::Error) -> ParserError {
ParserError::IoError(err)
}
}
impl StdError for EncoderError {
fn description(&self) -> &str { "encoder error" }
}
impl fmt::Display for EncoderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<fmt::Error> for EncoderError {
fn from(err: fmt::Error) -> EncoderError { EncoderError::FmtError(err) }
}
| {
match error {
ErrorCode::InvalidSyntax => "invalid syntax",
ErrorCode::InvalidNumber => "invalid number",
ErrorCode::EOFWhileParsingObject => "EOF While parsing object",
ErrorCode::EOFWhileParsingArray => "EOF While parsing array",
ErrorCode::EOFWhileParsingValue => "EOF While parsing value",
ErrorCode::EOFWhileParsingString => "EOF While parsing string",
ErrorCode::KeyMustBeAString => "key must be a string",
ErrorCode::ExpectedColon => "expected `:`",
ErrorCode::TrailingCharacters => "trailing characters",
ErrorCode::TrailingComma => "trailing comma",
ErrorCode::InvalidEscape => "invalid escape",
ErrorCode::UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
ErrorCode::NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
ErrorCode::ControlCharacterInString => "unescaped control character in string",
ErrorCode::NotUtf8 => "contents not utf-8",
ErrorCode::InvalidUnicodeCodePoint => "invalid Unicode code point",
ErrorCode::LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
ErrorCode::UnexpectedEndOfHexEscape => "unexpected end of hex escape", | identifier_body |
traits.rs | // Copyright (C) 2017-2020 Free Software Foundation, Inc.
// This program 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.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#![allow(warnings)]
pub trait T {
}
impl T for f64 {
}
impl T for u8 {
}
pub fn main() | {
let d = 23.5f64;
let u = 23u8;
let td = &d as &T;
let tu = &u as &T;
println!(""); // set breakpoint here
} | identifier_body |
|
traits.rs | // Copyright (C) 2017-2020 Free Software Foundation, Inc.
// This program 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.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#![allow(warnings)]
pub trait T {
}
impl T for f64 {
}
impl T for u8 {
}
pub fn main() {
let d = 23.5f64;
let u = 23u8;
let td = &d as &T;
let tu = &u as &T;
| } | println!(""); // set breakpoint here | random_line_split |
traits.rs | // Copyright (C) 2017-2020 Free Software Foundation, Inc.
// This program 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.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#![allow(warnings)]
pub trait T {
}
impl T for f64 {
}
impl T for u8 {
}
pub fn | () {
let d = 23.5f64;
let u = 23u8;
let td = &d as &T;
let tu = &u as &T;
println!(""); // set breakpoint here
}
| main | identifier_name |
transmute_int_to_float.rs | use super::TRANSMUTE_INT_TO_FLOAT;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::sugg;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::{self, Ty};
/// Checks for `transmute_int_to_float` lint.
/// Returns `true` if it's triggered, otherwise returns `false`.
pub(super) fn check<'tcx>(
cx: &LateContext<'tcx>,
e: &'tcx Expr<'_>, | match (&from_ty.kind(), &to_ty.kind()) {
(ty::Int(_) | ty::Uint(_), ty::Float(_)) if!const_context => {
span_lint_and_then(
cx,
TRANSMUTE_INT_TO_FLOAT,
e.span,
&format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
|diag| {
let arg = sugg::Sugg::hir(cx, &args[0], "..");
let arg = if let ty::Int(int_ty) = from_ty.kind() {
arg.as_ty(format!(
"u{}",
int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
))
} else {
arg
};
diag.span_suggestion(
e.span,
"consider using",
format!("{}::from_bits({})", to_ty, arg.to_string()),
Applicability::Unspecified,
);
},
);
true
},
_ => false,
}
} | from_ty: Ty<'tcx>,
to_ty: Ty<'tcx>,
args: &'tcx [Expr<'_>],
const_context: bool,
) -> bool { | random_line_split |
transmute_int_to_float.rs | use super::TRANSMUTE_INT_TO_FLOAT;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::sugg;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::{self, Ty};
/// Checks for `transmute_int_to_float` lint.
/// Returns `true` if it's triggered, otherwise returns `false`.
pub(super) fn check<'tcx>(
cx: &LateContext<'tcx>,
e: &'tcx Expr<'_>,
from_ty: Ty<'tcx>,
to_ty: Ty<'tcx>,
args: &'tcx [Expr<'_>],
const_context: bool,
) -> bool | "consider using",
format!("{}::from_bits({})", to_ty, arg.to_string()),
Applicability::Unspecified,
);
},
);
true
},
_ => false,
}
}
| {
match (&from_ty.kind(), &to_ty.kind()) {
(ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => {
span_lint_and_then(
cx,
TRANSMUTE_INT_TO_FLOAT,
e.span,
&format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
|diag| {
let arg = sugg::Sugg::hir(cx, &args[0], "..");
let arg = if let ty::Int(int_ty) = from_ty.kind() {
arg.as_ty(format!(
"u{}",
int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
))
} else {
arg
};
diag.span_suggestion(
e.span, | identifier_body |
transmute_int_to_float.rs | use super::TRANSMUTE_INT_TO_FLOAT;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::sugg;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::{self, Ty};
/// Checks for `transmute_int_to_float` lint.
/// Returns `true` if it's triggered, otherwise returns `false`.
pub(super) fn | <'tcx>(
cx: &LateContext<'tcx>,
e: &'tcx Expr<'_>,
from_ty: Ty<'tcx>,
to_ty: Ty<'tcx>,
args: &'tcx [Expr<'_>],
const_context: bool,
) -> bool {
match (&from_ty.kind(), &to_ty.kind()) {
(ty::Int(_) | ty::Uint(_), ty::Float(_)) if!const_context => {
span_lint_and_then(
cx,
TRANSMUTE_INT_TO_FLOAT,
e.span,
&format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
|diag| {
let arg = sugg::Sugg::hir(cx, &args[0], "..");
let arg = if let ty::Int(int_ty) = from_ty.kind() {
arg.as_ty(format!(
"u{}",
int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
))
} else {
arg
};
diag.span_suggestion(
e.span,
"consider using",
format!("{}::from_bits({})", to_ty, arg.to_string()),
Applicability::Unspecified,
);
},
);
true
},
_ => false,
}
}
| check | identifier_name |
main.rs | extern crate ffmpeg_next as ffmpeg;
extern crate pretty_env_logger;
use std::env;
use std::process::Command;
use std::thread;
use std::time;
use futures::{FutureExt, StreamExt};
use http::Uri;
use warp::Filter;
use getopts::Options;
//ffmpeg -i rtsp://192.xxx.xxx:5554 -y c:a aac -b:a 160000 -ac 2 s 854x480 -c:v libx264 -b:v 800000 -hls_time 10 -hls_list_size 10 -start_number 1 playlist.m3u8
fn run(input_address: Uri, output_file: &str) -> Option<u32> {
Command::new("ffmpeg")
.args(&[
"-i", | "c:a",
"aac",
"-b:a",
"160000",
"-ac",
"2",
"s",
"854x480",
"-c:v",
"libx264",
"-b:v",
"800000",
"-hls_time",
"10",
"-hls_list_size",
"10",
"-start_number",
"1",
output_file,
])
.spawn()
.ok()
.map(|child| child.id())
}
fn run_http(input_address: Uri, output_address: Uri) -> Option<u32> {
Command::new("ffmpeg")
.args(&[
"-i",
format!("{}", input_address).as_str(),
"-f",
"mpeg1video",
"-b",
"800k",
"-r",
"30",
format!("{}", output_address).as_str(),
])
.spawn()
.ok()
.map(|child| child.id())
}
fn run_http_server() {
println!("Trying to run http server");
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
pretty_env_logger::init();
let dispatch_websocket = |ws: warp::ws::Ws| {
// And then our closure will be called when it completes...
ws.on_upgrade(|websocket| {
// Just echo all messages back...
let (tx, rx) = websocket.split();
rx.forward(tx).map(|result| {
if let Err(e) = result {
eprintln!("websocket error: {:?}", e);
} else {
let info = result.unwrap();
println!("{:?}", info)
}
})
})
};
let videos_endpoint = warp::path("videos").and(warp::ws()).map(dispatch_websocket);
warp::serve(videos_endpoint)
.run(([127, 0, 0, 1], 3030))
.await;
})
}
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} FILE [options]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("o", "", "set output file name", "NAME");
opts.optopt("i", "", "set input file name", "NAME");
opts.optflag("h", "help", "print this help menu");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => {
panic!(f.to_string())
}
};
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
if!matches.opt_str("o").is_some() ||!matches.opt_str("i").is_some() {
print_usage(&program, opts);
return;
}
let input = matches.opt_str("i").expect("Expected input file");
let output = matches.opt_str("o").expect("Expected output file");
let pos_uri_input = input.parse::<Uri>();
let pos_uri_output = output.parse::<Uri>();
let uri_input = match pos_uri_input {
Ok(v) => v,
Err(_) => {
print_usage(&program, opts);
return;
}
};
let uri_output = match pos_uri_output {
Ok(v) => v,
Err(_) => {
print_usage(&program, opts);
return;
}
};
thread::spawn(move || run_http_server());
thread::sleep(time::Duration::from_secs(5));
if let Some(return_id) = run_http(uri_input, uri_output) {
println!("Type of return value {}", return_id);
} else {
println!("Error t get id")
}
thread::sleep(time::Duration::from_secs(20));
} | format!("{}", input_address).as_str(),
"-y", | random_line_split |
main.rs | extern crate ffmpeg_next as ffmpeg;
extern crate pretty_env_logger;
use std::env;
use std::process::Command;
use std::thread;
use std::time;
use futures::{FutureExt, StreamExt};
use http::Uri;
use warp::Filter;
use getopts::Options;
//ffmpeg -i rtsp://192.xxx.xxx:5554 -y c:a aac -b:a 160000 -ac 2 s 854x480 -c:v libx264 -b:v 800000 -hls_time 10 -hls_list_size 10 -start_number 1 playlist.m3u8
fn run(input_address: Uri, output_file: &str) -> Option<u32> {
Command::new("ffmpeg")
.args(&[
"-i",
format!("{}", input_address).as_str(),
"-y",
"c:a",
"aac",
"-b:a",
"160000",
"-ac",
"2",
"s",
"854x480",
"-c:v",
"libx264",
"-b:v",
"800000",
"-hls_time",
"10",
"-hls_list_size",
"10",
"-start_number",
"1",
output_file,
])
.spawn()
.ok()
.map(|child| child.id())
}
fn run_http(input_address: Uri, output_address: Uri) -> Option<u32> {
Command::new("ffmpeg")
.args(&[
"-i",
format!("{}", input_address).as_str(),
"-f",
"mpeg1video",
"-b",
"800k",
"-r",
"30",
format!("{}", output_address).as_str(),
])
.spawn()
.ok()
.map(|child| child.id())
}
fn run_http_server() {
println!("Trying to run http server");
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
pretty_env_logger::init();
let dispatch_websocket = |ws: warp::ws::Ws| {
// And then our closure will be called when it completes...
ws.on_upgrade(|websocket| {
// Just echo all messages back...
let (tx, rx) = websocket.split();
rx.forward(tx).map(|result| {
if let Err(e) = result {
eprintln!("websocket error: {:?}", e);
} else {
let info = result.unwrap();
println!("{:?}", info)
}
})
})
};
let videos_endpoint = warp::path("videos").and(warp::ws()).map(dispatch_websocket);
warp::serve(videos_endpoint)
.run(([127, 0, 0, 1], 3030))
.await;
})
}
fn print_usage(program: &str, opts: Options) |
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("o", "", "set output file name", "NAME");
opts.optopt("i", "", "set input file name", "NAME");
opts.optflag("h", "help", "print this help menu");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => {
panic!(f.to_string())
}
};
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
if!matches.opt_str("o").is_some() ||!matches.opt_str("i").is_some() {
print_usage(&program, opts);
return;
}
let input = matches.opt_str("i").expect("Expected input file");
let output = matches.opt_str("o").expect("Expected output file");
let pos_uri_input = input.parse::<Uri>();
let pos_uri_output = output.parse::<Uri>();
let uri_input = match pos_uri_input {
Ok(v) => v,
Err(_) => {
print_usage(&program, opts);
return;
}
};
let uri_output = match pos_uri_output {
Ok(v) => v,
Err(_) => {
print_usage(&program, opts);
return;
}
};
thread::spawn(move || run_http_server());
thread::sleep(time::Duration::from_secs(5));
if let Some(return_id) = run_http(uri_input, uri_output) {
println!("Type of return value {}", return_id);
} else {
println!("Error t get id")
}
thread::sleep(time::Duration::from_secs(20));
}
| {
let brief = format!("Usage: {} FILE [options]", program);
print!("{}", opts.usage(&brief));
} | identifier_body |
main.rs | extern crate ffmpeg_next as ffmpeg;
extern crate pretty_env_logger;
use std::env;
use std::process::Command;
use std::thread;
use std::time;
use futures::{FutureExt, StreamExt};
use http::Uri;
use warp::Filter;
use getopts::Options;
//ffmpeg -i rtsp://192.xxx.xxx:5554 -y c:a aac -b:a 160000 -ac 2 s 854x480 -c:v libx264 -b:v 800000 -hls_time 10 -hls_list_size 10 -start_number 1 playlist.m3u8
fn run(input_address: Uri, output_file: &str) -> Option<u32> {
Command::new("ffmpeg")
.args(&[
"-i",
format!("{}", input_address).as_str(),
"-y",
"c:a",
"aac",
"-b:a",
"160000",
"-ac",
"2",
"s",
"854x480",
"-c:v",
"libx264",
"-b:v",
"800000",
"-hls_time",
"10",
"-hls_list_size",
"10",
"-start_number",
"1",
output_file,
])
.spawn()
.ok()
.map(|child| child.id())
}
fn run_http(input_address: Uri, output_address: Uri) -> Option<u32> {
Command::new("ffmpeg")
.args(&[
"-i",
format!("{}", input_address).as_str(),
"-f",
"mpeg1video",
"-b",
"800k",
"-r",
"30",
format!("{}", output_address).as_str(),
])
.spawn()
.ok()
.map(|child| child.id())
}
fn run_http_server() {
println!("Trying to run http server");
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
pretty_env_logger::init();
let dispatch_websocket = |ws: warp::ws::Ws| {
// And then our closure will be called when it completes...
ws.on_upgrade(|websocket| {
// Just echo all messages back...
let (tx, rx) = websocket.split();
rx.forward(tx).map(|result| {
if let Err(e) = result {
eprintln!("websocket error: {:?}", e);
} else {
let info = result.unwrap();
println!("{:?}", info)
}
})
})
};
let videos_endpoint = warp::path("videos").and(warp::ws()).map(dispatch_websocket);
warp::serve(videos_endpoint)
.run(([127, 0, 0, 1], 3030))
.await;
})
}
fn | (program: &str, opts: Options) {
let brief = format!("Usage: {} FILE [options]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("o", "", "set output file name", "NAME");
opts.optopt("i", "", "set input file name", "NAME");
opts.optflag("h", "help", "print this help menu");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => {
panic!(f.to_string())
}
};
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
if!matches.opt_str("o").is_some() ||!matches.opt_str("i").is_some() {
print_usage(&program, opts);
return;
}
let input = matches.opt_str("i").expect("Expected input file");
let output = matches.opt_str("o").expect("Expected output file");
let pos_uri_input = input.parse::<Uri>();
let pos_uri_output = output.parse::<Uri>();
let uri_input = match pos_uri_input {
Ok(v) => v,
Err(_) => {
print_usage(&program, opts);
return;
}
};
let uri_output = match pos_uri_output {
Ok(v) => v,
Err(_) => {
print_usage(&program, opts);
return;
}
};
thread::spawn(move || run_http_server());
thread::sleep(time::Duration::from_secs(5));
if let Some(return_id) = run_http(uri_input, uri_output) {
println!("Type of return value {}", return_id);
} else {
println!("Error t get id")
}
thread::sleep(time::Duration::from_secs(20));
}
| print_usage | identifier_name |
main.rs | extern crate ffmpeg_next as ffmpeg;
extern crate pretty_env_logger;
use std::env;
use std::process::Command;
use std::thread;
use std::time;
use futures::{FutureExt, StreamExt};
use http::Uri;
use warp::Filter;
use getopts::Options;
//ffmpeg -i rtsp://192.xxx.xxx:5554 -y c:a aac -b:a 160000 -ac 2 s 854x480 -c:v libx264 -b:v 800000 -hls_time 10 -hls_list_size 10 -start_number 1 playlist.m3u8
fn run(input_address: Uri, output_file: &str) -> Option<u32> {
Command::new("ffmpeg")
.args(&[
"-i",
format!("{}", input_address).as_str(),
"-y",
"c:a",
"aac",
"-b:a",
"160000",
"-ac",
"2",
"s",
"854x480",
"-c:v",
"libx264",
"-b:v",
"800000",
"-hls_time",
"10",
"-hls_list_size",
"10",
"-start_number",
"1",
output_file,
])
.spawn()
.ok()
.map(|child| child.id())
}
fn run_http(input_address: Uri, output_address: Uri) -> Option<u32> {
Command::new("ffmpeg")
.args(&[
"-i",
format!("{}", input_address).as_str(),
"-f",
"mpeg1video",
"-b",
"800k",
"-r",
"30",
format!("{}", output_address).as_str(),
])
.spawn()
.ok()
.map(|child| child.id())
}
fn run_http_server() {
println!("Trying to run http server");
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
pretty_env_logger::init();
let dispatch_websocket = |ws: warp::ws::Ws| {
// And then our closure will be called when it completes...
ws.on_upgrade(|websocket| {
// Just echo all messages back...
let (tx, rx) = websocket.split();
rx.forward(tx).map(|result| {
if let Err(e) = result {
eprintln!("websocket error: {:?}", e);
} else {
let info = result.unwrap();
println!("{:?}", info)
}
})
})
};
let videos_endpoint = warp::path("videos").and(warp::ws()).map(dispatch_websocket);
warp::serve(videos_endpoint)
.run(([127, 0, 0, 1], 3030))
.await;
})
}
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} FILE [options]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("o", "", "set output file name", "NAME");
opts.optopt("i", "", "set input file name", "NAME");
opts.optflag("h", "help", "print this help menu");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => |
};
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
if!matches.opt_str("o").is_some() ||!matches.opt_str("i").is_some() {
print_usage(&program, opts);
return;
}
let input = matches.opt_str("i").expect("Expected input file");
let output = matches.opt_str("o").expect("Expected output file");
let pos_uri_input = input.parse::<Uri>();
let pos_uri_output = output.parse::<Uri>();
let uri_input = match pos_uri_input {
Ok(v) => v,
Err(_) => {
print_usage(&program, opts);
return;
}
};
let uri_output = match pos_uri_output {
Ok(v) => v,
Err(_) => {
print_usage(&program, opts);
return;
}
};
thread::spawn(move || run_http_server());
thread::sleep(time::Duration::from_secs(5));
if let Some(return_id) = run_http(uri_input, uri_output) {
println!("Type of return value {}", return_id);
} else {
println!("Error t get id")
}
thread::sleep(time::Duration::from_secs(20));
}
| {
panic!(f.to_string())
} | conditional_block |
upload_latest.rs | use crate::{api_client::{self,
Client},
common::ui::{Status,
UIWriter,
UI},
error::{Error,
Result},
PRODUCT,
VERSION};
use habitat_core::{crypto::keys::{Key,
KeyCache,
PublicOriginSigningKey,
SecretOriginSigningKey},
origin::Origin};
use reqwest::StatusCode;
pub async fn start(ui: &mut UI,
bldr_url: &str,
token: &str,
origin: &Origin,
with_secret: bool,
key_cache: &KeyCache)
-> Result<()> | {
Ok(()) => ui.status(Status::Uploaded, public_key.named_revision())?,
Err(api_client::Error::APIError(StatusCode::CONFLICT, _)) => {
ui.status(Status::Using,
format!("public key revision {} which already exists in the depot",
public_key.named_revision()))?;
}
Err(err) => return Err(Error::from(err)),
}
ui.end(format!("Upload of public origin key {} complete.",
public_key.named_revision()))?;
if with_secret {
// get matching secret key
let secret_key: SecretOriginSigningKey =
key_cache.secret_signing_key(public_key.named_revision())?;
let secret_keyfile = key_cache.path_in_cache(&secret_key);
ui.status(Status::Uploading, secret_keyfile.display())?;
match api_client.put_origin_secret_key(secret_key.named_revision().name(),
secret_key.named_revision().revision(),
&secret_keyfile,
token,
ui.progress())
.await
{
Ok(()) => {
ui.status(Status::Uploaded, secret_key.named_revision())?;
ui.end(format!("Upload of secret origin key {} complete.",
secret_key.named_revision()))?;
}
Err(e) => {
return Err(Error::APIClient(e));
}
}
}
Ok(())
}
| {
let api_client = Client::new(bldr_url, PRODUCT, VERSION, None)?;
ui.begin(format!("Uploading latest public origin key {}", &origin))?;
// Figure out the latest public key
let public_key: PublicOriginSigningKey = key_cache.latest_public_origin_signing_key(origin)?;
// The path to the key in the cache
let public_keyfile = key_cache.path_in_cache(&public_key);
ui.status(Status::Uploading, public_keyfile.display())?;
// TODO (CM): Really, we just need to pass the key itself; it's
// got all the information
match api_client.put_origin_key(public_key.named_revision().name(),
public_key.named_revision().revision(),
&public_keyfile,
token,
ui.progress())
.await | identifier_body |
upload_latest.rs | use crate::{api_client::{self,
Client},
common::ui::{Status,
UIWriter,
UI},
error::{Error,
Result},
PRODUCT,
VERSION};
use habitat_core::{crypto::keys::{Key,
KeyCache,
PublicOriginSigningKey,
SecretOriginSigningKey},
origin::Origin};
use reqwest::StatusCode;
pub async fn | (ui: &mut UI,
bldr_url: &str,
token: &str,
origin: &Origin,
with_secret: bool,
key_cache: &KeyCache)
-> Result<()> {
let api_client = Client::new(bldr_url, PRODUCT, VERSION, None)?;
ui.begin(format!("Uploading latest public origin key {}", &origin))?;
// Figure out the latest public key
let public_key: PublicOriginSigningKey = key_cache.latest_public_origin_signing_key(origin)?;
// The path to the key in the cache
let public_keyfile = key_cache.path_in_cache(&public_key);
ui.status(Status::Uploading, public_keyfile.display())?;
// TODO (CM): Really, we just need to pass the key itself; it's
// got all the information
match api_client.put_origin_key(public_key.named_revision().name(),
public_key.named_revision().revision(),
&public_keyfile,
token,
ui.progress())
.await
{
Ok(()) => ui.status(Status::Uploaded, public_key.named_revision())?,
Err(api_client::Error::APIError(StatusCode::CONFLICT, _)) => {
ui.status(Status::Using,
format!("public key revision {} which already exists in the depot",
public_key.named_revision()))?;
}
Err(err) => return Err(Error::from(err)),
}
ui.end(format!("Upload of public origin key {} complete.",
public_key.named_revision()))?;
if with_secret {
// get matching secret key
let secret_key: SecretOriginSigningKey =
key_cache.secret_signing_key(public_key.named_revision())?;
let secret_keyfile = key_cache.path_in_cache(&secret_key);
ui.status(Status::Uploading, secret_keyfile.display())?;
match api_client.put_origin_secret_key(secret_key.named_revision().name(),
secret_key.named_revision().revision(),
&secret_keyfile,
token,
ui.progress())
.await
{
Ok(()) => {
ui.status(Status::Uploaded, secret_key.named_revision())?;
ui.end(format!("Upload of secret origin key {} complete.",
secret_key.named_revision()))?;
}
Err(e) => {
return Err(Error::APIClient(e));
}
}
}
Ok(())
}
| start | identifier_name |
upload_latest.rs | use crate::{api_client::{self,
Client},
common::ui::{Status,
UIWriter,
UI},
error::{Error,
Result}, | PRODUCT,
VERSION};
use habitat_core::{crypto::keys::{Key,
KeyCache,
PublicOriginSigningKey,
SecretOriginSigningKey},
origin::Origin};
use reqwest::StatusCode;
pub async fn start(ui: &mut UI,
bldr_url: &str,
token: &str,
origin: &Origin,
with_secret: bool,
key_cache: &KeyCache)
-> Result<()> {
let api_client = Client::new(bldr_url, PRODUCT, VERSION, None)?;
ui.begin(format!("Uploading latest public origin key {}", &origin))?;
// Figure out the latest public key
let public_key: PublicOriginSigningKey = key_cache.latest_public_origin_signing_key(origin)?;
// The path to the key in the cache
let public_keyfile = key_cache.path_in_cache(&public_key);
ui.status(Status::Uploading, public_keyfile.display())?;
// TODO (CM): Really, we just need to pass the key itself; it's
// got all the information
match api_client.put_origin_key(public_key.named_revision().name(),
public_key.named_revision().revision(),
&public_keyfile,
token,
ui.progress())
.await
{
Ok(()) => ui.status(Status::Uploaded, public_key.named_revision())?,
Err(api_client::Error::APIError(StatusCode::CONFLICT, _)) => {
ui.status(Status::Using,
format!("public key revision {} which already exists in the depot",
public_key.named_revision()))?;
}
Err(err) => return Err(Error::from(err)),
}
ui.end(format!("Upload of public origin key {} complete.",
public_key.named_revision()))?;
if with_secret {
// get matching secret key
let secret_key: SecretOriginSigningKey =
key_cache.secret_signing_key(public_key.named_revision())?;
let secret_keyfile = key_cache.path_in_cache(&secret_key);
ui.status(Status::Uploading, secret_keyfile.display())?;
match api_client.put_origin_secret_key(secret_key.named_revision().name(),
secret_key.named_revision().revision(),
&secret_keyfile,
token,
ui.progress())
.await
{
Ok(()) => {
ui.status(Status::Uploaded, secret_key.named_revision())?;
ui.end(format!("Upload of secret origin key {} complete.",
secret_key.named_revision()))?;
}
Err(e) => {
return Err(Error::APIClient(e));
}
}
}
Ok(())
} | random_line_split |
|
mod.rs | pub mod buffers;
pub mod cursor;
pub mod position;
pub mod movement;
pub mod insert;
use gfx::Screen;
use config::Players;
use px8::PX8Config;
use px8::editor::State;
use self::buffers::BufferManager;
use self::cursor::Cursor;
use px8::editor::text::buffers::TextBuffer;
use px8::editor::text::buffers::SplitBuffer;
use px8::editor::text::buffers::Buffer;
use std::sync::{Arc, Mutex};
use std::cmp::{max, min};
use std::collections::HashMap;
use time;
pub struct TextEditor {
pub buffers: BufferManager,
}
impl TextEditor {
pub fn new(state: Arc<Mutex<State>>) -> TextEditor {
TextEditor {
buffers: BufferManager::new(),
}
}
pub fn init(&mut self, config: Arc<Mutex<PX8Config>>, screen: &mut Screen, filename: String, code: String) {
info!("[GFX_EDITOR] Init");
info!("[GFX_EDITOR] {:?}", self.pos());
let mut new_buffer: Buffer = SplitBuffer::from_str(&code).into();
new_buffer.title = Some(filename);
let new_buffer_index = self.buffers.new_buffer(new_buffer);
self.buffers.switch_to(new_buffer_index);
self.hint();
}
pub fn update(&mut self, players: Arc<Mutex<Players>>) -> bool {
true
}
/// Hint the buffer about the cursor position.
pub fn hint(&mut self) {
let x = self.cursor().x;
let y = self.cursor().y;
self.buffers.current_buffer_mut().focus_hint_y(y);
self.buffers.current_buffer_mut().focus_hint_x(x);
}
pub fn draw(&mut self, players: Arc<Mutex<Players>>, screen: &mut Screen) {
let (scroll_x, scroll_y) = {
let current_buffer = self.buffers.current_buffer_info();
(current_buffer.scroll_x, current_buffer.scroll_y)
};
let (pos_x, pos_y) = self.pos();
let w = screen.width;
screen.rect(4 * (pos_x - scroll_x) as i32,
(8 * (pos_y - scroll_y) as i32) + 8,
4 * (pos_x - scroll_x) as i32 + 4,
(8 * (pos_y - scroll_y) as i32) + 8 + 8,
8);
for (y, row) in self.buffers
.current_buffer()
.lines()
.enumerate() {
for (x, c) in row.chars().enumerate() {
let c = if c == '\t' | else { c };
let pos_char_x = 4 * (x - scroll_x) as i32;
let pos_char_y = 8 * (y - scroll_y) as i32;
//info!("OFF C {:?} X {:?} {:?}", c, pos_char_x, pos_char_y);
screen.print_char(c,
pos_char_x,
pos_char_y + 8,
7);
}
}
}
}
| { ' ' } | conditional_block |
mod.rs | pub mod buffers;
pub mod cursor;
pub mod position;
pub mod movement;
pub mod insert;
use gfx::Screen;
use config::Players;
use px8::PX8Config;
use px8::editor::State;
use self::buffers::BufferManager;
use self::cursor::Cursor;
use px8::editor::text::buffers::TextBuffer;
use px8::editor::text::buffers::SplitBuffer;
use px8::editor::text::buffers::Buffer;
use std::sync::{Arc, Mutex};
use std::cmp::{max, min};
use std::collections::HashMap;
use time;
pub struct TextEditor {
pub buffers: BufferManager,
}
impl TextEditor {
pub fn new(state: Arc<Mutex<State>>) -> TextEditor {
TextEditor {
buffers: BufferManager::new(),
}
}
pub fn init(&mut self, config: Arc<Mutex<PX8Config>>, screen: &mut Screen, filename: String, code: String) {
info!("[GFX_EDITOR] Init");
info!("[GFX_EDITOR] {:?}", self.pos());
let mut new_buffer: Buffer = SplitBuffer::from_str(&code).into();
new_buffer.title = Some(filename);
let new_buffer_index = self.buffers.new_buffer(new_buffer);
self.buffers.switch_to(new_buffer_index);
self.hint();
}
pub fn update(&mut self, players: Arc<Mutex<Players>>) -> bool {
true
}
/// Hint the buffer about the cursor position.
pub fn hint(&mut self) { | let y = self.cursor().y;
self.buffers.current_buffer_mut().focus_hint_y(y);
self.buffers.current_buffer_mut().focus_hint_x(x);
}
pub fn draw(&mut self, players: Arc<Mutex<Players>>, screen: &mut Screen) {
let (scroll_x, scroll_y) = {
let current_buffer = self.buffers.current_buffer_info();
(current_buffer.scroll_x, current_buffer.scroll_y)
};
let (pos_x, pos_y) = self.pos();
let w = screen.width;
screen.rect(4 * (pos_x - scroll_x) as i32,
(8 * (pos_y - scroll_y) as i32) + 8,
4 * (pos_x - scroll_x) as i32 + 4,
(8 * (pos_y - scroll_y) as i32) + 8 + 8,
8);
for (y, row) in self.buffers
.current_buffer()
.lines()
.enumerate() {
for (x, c) in row.chars().enumerate() {
let c = if c == '\t' {'' } else { c };
let pos_char_x = 4 * (x - scroll_x) as i32;
let pos_char_y = 8 * (y - scroll_y) as i32;
//info!("OFF C {:?} X {:?} {:?}", c, pos_char_x, pos_char_y);
screen.print_char(c,
pos_char_x,
pos_char_y + 8,
7);
}
}
}
} |
let x = self.cursor().x; | random_line_split |
mod.rs | pub mod buffers;
pub mod cursor;
pub mod position;
pub mod movement;
pub mod insert;
use gfx::Screen;
use config::Players;
use px8::PX8Config;
use px8::editor::State;
use self::buffers::BufferManager;
use self::cursor::Cursor;
use px8::editor::text::buffers::TextBuffer;
use px8::editor::text::buffers::SplitBuffer;
use px8::editor::text::buffers::Buffer;
use std::sync::{Arc, Mutex};
use std::cmp::{max, min};
use std::collections::HashMap;
use time;
pub struct TextEditor {
pub buffers: BufferManager,
}
impl TextEditor {
pub fn new(state: Arc<Mutex<State>>) -> TextEditor {
TextEditor {
buffers: BufferManager::new(),
}
}
pub fn | (&mut self, config: Arc<Mutex<PX8Config>>, screen: &mut Screen, filename: String, code: String) {
info!("[GFX_EDITOR] Init");
info!("[GFX_EDITOR] {:?}", self.pos());
let mut new_buffer: Buffer = SplitBuffer::from_str(&code).into();
new_buffer.title = Some(filename);
let new_buffer_index = self.buffers.new_buffer(new_buffer);
self.buffers.switch_to(new_buffer_index);
self.hint();
}
pub fn update(&mut self, players: Arc<Mutex<Players>>) -> bool {
true
}
/// Hint the buffer about the cursor position.
pub fn hint(&mut self) {
let x = self.cursor().x;
let y = self.cursor().y;
self.buffers.current_buffer_mut().focus_hint_y(y);
self.buffers.current_buffer_mut().focus_hint_x(x);
}
pub fn draw(&mut self, players: Arc<Mutex<Players>>, screen: &mut Screen) {
let (scroll_x, scroll_y) = {
let current_buffer = self.buffers.current_buffer_info();
(current_buffer.scroll_x, current_buffer.scroll_y)
};
let (pos_x, pos_y) = self.pos();
let w = screen.width;
screen.rect(4 * (pos_x - scroll_x) as i32,
(8 * (pos_y - scroll_y) as i32) + 8,
4 * (pos_x - scroll_x) as i32 + 4,
(8 * (pos_y - scroll_y) as i32) + 8 + 8,
8);
for (y, row) in self.buffers
.current_buffer()
.lines()
.enumerate() {
for (x, c) in row.chars().enumerate() {
let c = if c == '\t' {'' } else { c };
let pos_char_x = 4 * (x - scroll_x) as i32;
let pos_char_y = 8 * (y - scroll_y) as i32;
//info!("OFF C {:?} X {:?} {:?}", c, pos_char_x, pos_char_y);
screen.print_char(c,
pos_char_x,
pos_char_y + 8,
7);
}
}
}
}
| init | identifier_name |
macros.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.
//! Standard library macros
//!
//! This modules contains a set of macros which are exported from the standard
//! library. Each macro is available for use when linking against the standard
//! library.
#![experimental]
#![macro_escape]
/// The entry point for panic of Rust tasks.
///
/// This macro is used to inject panic into a Rust task, causing the task to
/// unwind and panic entirely. Each task's panic can be reaped as the
/// `Box<Any>` type, and the single-argument form of the `panic!` macro will be
/// the value which is transmitted.
///
/// The multi-argument form of this macro panics with a string and has the
/// `format!` syntax for building a string.
///
/// # Example
///
/// ```should_fail
/// # #![allow(unreachable_code)]
/// panic!();
/// panic!("this is a terrible mistake!");
/// panic!(4i); // panic with the value of 4 to be collected elsewhere
/// panic!("this is a {} {message}", "fancy", message = "message");
/// ```
#[macro_export]
macro_rules! panic(
() => ({
panic!("explicit panic")
});
($msg:expr) => ({
// static requires less code at runtime, more constant data
static _FILE_LINE: (&'static str, uint) = (file!(), line!());
::std::rt::begin_unwind($msg, &_FILE_LINE)
});
($fmt:expr, $($arg:tt)*) => ({
// a closure can't have return type!, so we need a full
// function to pass to format_args!, *and* we need the
// file and line numbers right here; so an inner bare fn
// is our only choice.
//
// LLVM doesn't tend to inline this, presumably because begin_unwind_fmt
// is #[cold] and #[inline(never)] and because this is flagged as cold
// as returning!. We really do want this to be inlined, however,
// because it's just a tiny wrapper. Small wins (156K to 149K in size)
// were seen when forcing this to be inlined, and that number just goes
// up with the number of calls to panic!()
//
// The leading _'s are to avoid dead code warnings if this is
// used inside a dead function. Just `#[allow(dead_code)]` is
// insufficient, since the user may have
// `#[forbid(dead_code)]` and which cannot be overridden.
#[inline(always)]
fn _run_fmt(fmt: &::std::fmt::Arguments) ->! {
static _FILE_LINE: (&'static str, uint) = (file!(), line!());
::std::rt::begin_unwind_fmt(fmt, &_FILE_LINE)
}
format_args!(_run_fmt, $fmt, $($arg)*)
});
)
/// Ensure that a boolean expression is `true` at runtime.
///
/// This will invoke the `panic!` macro if the provided expression cannot be
/// evaluated to `true` at runtime.
///
/// # Example
///
/// ```
/// // the panic message for these assertions is the stringified value of the
/// // expression given.
/// assert!(true);
/// # fn some_computation() -> bool { true }
/// assert!(some_computation());
///
/// // assert with a custom message
/// # let x = true;
/// assert!(x, "x wasn't true!");
/// # let a = 3i; let b = 27i;
/// assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
#[macro_export]
macro_rules! assert(
($cond:expr) => (
if!$cond {
panic!(concat!("assertion failed: ", stringify!($cond)))
}
);
($cond:expr, $($arg:expr),+) => (
if!$cond {
panic!($($arg),+)
}
); |
/// Asserts that two expressions are equal to each other, testing equality in
/// both directions.
///
/// On panic, this macro will print the values of the expressions.
///
/// # Example
///
/// ```
/// let a = 3i;
/// let b = 1i + 2i;
/// assert_eq!(a, b);
/// ```
#[macro_export]
macro_rules! assert_eq(
($given:expr, $expected:expr) => ({
match (&($given), &($expected)) {
(given_val, expected_val) => {
// check both directions of equality....
if!((*given_val == *expected_val) &&
(*expected_val == *given_val)) {
panic!("assertion failed: `(left == right) && (right == left)` \
(left: `{}`, right: `{}`)", *given_val, *expected_val)
}
}
}
})
)
/// Ensure that a boolean expression is `true` at runtime.
///
/// This will invoke the `panic!` macro if the provided expression cannot be
/// evaluated to `true` at runtime.
///
/// Unlike `assert!`, `debug_assert!` statements can be disabled by passing
/// `--cfg ndebug` to the compiler. This makes `debug_assert!` useful for
/// checks that are too expensive to be present in a release build but may be
/// helpful during development.
///
/// # Example
///
/// ```
/// // the panic message for these assertions is the stringified value of the
/// // expression given.
/// debug_assert!(true);
/// # fn some_expensive_computation() -> bool { true }
/// debug_assert!(some_expensive_computation());
///
/// // assert with a custom message
/// # let x = true;
/// debug_assert!(x, "x wasn't true!");
/// # let a = 3i; let b = 27i;
/// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
#[macro_export]
macro_rules! debug_assert(
($($arg:tt)*) => (if cfg!(not(ndebug)) { assert!($($arg)*); })
)
/// Asserts that two expressions are equal to each other, testing equality in
/// both directions.
///
/// On panic, this macro will print the values of the expressions.
///
/// Unlike `assert_eq!`, `debug_assert_eq!` statements can be disabled by
/// passing `--cfg ndebug` to the compiler. This makes `debug_assert_eq!`
/// useful for checks that are too expensive to be present in a release build
/// but may be helpful during development.
///
/// # Example
///
/// ```
/// let a = 3i;
/// let b = 1i + 2i;
/// debug_assert_eq!(a, b);
/// ```
#[macro_export]
macro_rules! debug_assert_eq(
($($arg:tt)*) => (if cfg!(not(ndebug)) { assert_eq!($($arg)*); })
)
/// A utility macro for indicating unreachable code. It will panic if
/// executed. This is occasionally useful to put after loops that never
/// terminate normally, but instead directly return from a function.
///
/// # Example
///
/// ```{.rust}
/// struct Item { weight: uint }
///
/// fn choose_weighted_item(v: &[Item]) -> Item {
/// assert!(!v.is_empty());
/// let mut so_far = 0u;
/// for item in v.iter() {
/// so_far += item.weight;
/// if so_far > 100 {
/// return *item;
/// }
/// }
/// // The above loop always returns, so we must hint to the
/// // type checker that it isn't possible to get down here
/// unreachable!();
/// }
/// ```
#[macro_export]
macro_rules! unreachable(
() => ({
panic!("internal error: entered unreachable code")
});
($msg:expr) => ({
unreachable!("{}", $msg)
});
($fmt:expr, $($arg:tt)*) => ({
panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
});
)
/// A standardised placeholder for marking unfinished code. It panics with the
/// message `"not yet implemented"` when executed.
#[macro_export]
macro_rules! unimplemented(
() => (panic!("not yet implemented"))
)
/// Use the syntax described in `std::fmt` to create a value of type `String`.
/// See `std::fmt` for more information.
///
/// # Example
///
/// ```
/// format!("test");
/// format!("hello {}", "world!");
/// format!("x = {}, y = {y}", 10i, y = 30i);
/// ```
#[macro_export]
macro_rules! format(
($($arg:tt)*) => (
format_args!(::std::fmt::format, $($arg)*)
)
)
/// Use the `format!` syntax to write data into a buffer of type `&mut Writer`.
/// See `std::fmt` for more information.
///
/// # Example
///
/// ```
/// # #![allow(unused_must_use)]
/// use std::io::MemWriter;
///
/// let mut w = MemWriter::new();
/// write!(&mut w, "test");
/// write!(&mut w, "formatted {}", "arguments");
/// ```
#[macro_export]
macro_rules! write(
($dst:expr, $($arg:tt)*) => ({
format_args_method!($dst, write_fmt, $($arg)*)
})
)
/// Equivalent to the `write!` macro, except that a newline is appended after
/// the message is written.
#[macro_export]
macro_rules! writeln(
($dst:expr, $fmt:expr $($arg:tt)*) => (
write!($dst, concat!($fmt, "\n") $($arg)*)
)
)
/// Equivalent to the `println!` macro except that a newline is not printed at
/// the end of the message.
#[macro_export]
macro_rules! print(
($($arg:tt)*) => (format_args!(::std::io::stdio::print_args, $($arg)*))
)
/// Macro for printing to a task's stdout handle.
///
/// Each task can override its stdout handle via `std::io::stdio::set_stdout`.
/// The syntax of this macro is the same as that used for `format!`. For more
/// information, see `std::fmt` and `std::io::stdio`.
///
/// # Example
///
/// ```
/// println!("hello there!");
/// println!("format {} arguments", "some");
/// ```
#[macro_export]
macro_rules! println(
($($arg:tt)*) => (format_args!(::std::io::stdio::println_args, $($arg)*))
)
/// Declare a task-local key with a specific type.
///
/// # Example
///
/// ```
/// local_data_key!(my_integer: int)
///
/// my_integer.replace(Some(2));
/// println!("{}", my_integer.get().map(|a| *a));
/// ```
#[macro_export]
macro_rules! local_data_key(
($name:ident: $ty:ty) => (
#[allow(non_upper_case_globals)]
static $name: ::std::local_data::Key<$ty> = &::std::local_data::KeyValueKey;
);
(pub $name:ident: $ty:ty) => (
#[allow(non_upper_case_globals)]
pub static $name: ::std::local_data::Key<$ty> = &::std::local_data::KeyValueKey;
);
)
/// Helper macro for unwrapping `Result` values while returning early with an
/// error if the value of the expression is `Err`. For more information, see
/// `std::io`.
#[macro_export]
macro_rules! try (
($expr:expr) => ({
match $expr {
Ok(val) => val,
Err(err) => return Err(::std::error::FromError::from_error(err))
}
})
)
/// Create a `std::vec::Vec` containing the arguments.
#[macro_export]
macro_rules! vec[
($($x:expr),*) => ({
use std::slice::BoxedSlicePrelude;
let xs: ::std::boxed::Box<[_]> = box [$($x),*];
xs.into_vec()
});
($($x:expr,)*) => (vec![$($x),*])
]
/// A macro to select an event from a number of receivers.
///
/// This macro is used to wait for the first event to occur on a number of
/// receivers. It places no restrictions on the types of receivers given to
/// this macro, this can be viewed as a heterogeneous select.
///
/// # Example
///
/// ```
/// let (tx1, rx1) = channel();
/// let (tx2, rx2) = channel();
/// # fn long_running_task() {}
/// # fn calculate_the_answer() -> int { 42i }
///
/// spawn(proc() { long_running_task(); tx1.send(()) });
/// spawn(proc() { tx2.send(calculate_the_answer()) });
///
/// select! (
/// () = rx1.recv() => println!("the long running task finished first"),
/// answer = rx2.recv() => {
/// println!("the answer was: {}", answer);
/// }
/// )
/// ```
///
/// For more information about select, see the `std::comm::Select` structure.
#[macro_export]
#[experimental]
macro_rules! select {
(
$($name:pat = $rx:ident.$meth:ident() => $code:expr),+
) => ({
use std::comm::Select;
let sel = Select::new();
$( let mut $rx = sel.handle(&$rx); )+
unsafe {
$( $rx.add(); )+
}
let ret = sel.wait();
$( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
{ unreachable!() }
})
}
// When testing the standard library, we link to the liblog crate to get the
// logging macros. In doing so, the liblog crate was linked against the real
// version of libstd, and uses a different std::fmt module than the test crate
// uses. To get around this difference, we redefine the log!() macro here to be
// just a dumb version of what it should be.
#[cfg(test)]
macro_rules! log (
($lvl:expr, $($args:tt)*) => (
if log_enabled!($lvl) { println!($($args)*) }
)
)
/// Built-in macros to the compiler itself.
///
/// These macros do not have any corresponding definition with a `macro_rules!`
/// macro, but are documented here. Their implementations can be found hardcoded
/// into libsyntax itself.
#[cfg(dox)]
pub mod builtin {
/// The core macro for formatted string creation & output.
///
/// This macro takes as its first argument a callable expression which will
/// receive as its first argument a value of type `&fmt::Arguments`. This
/// value can be passed to the functions in `std::fmt` for performing useful
/// functions. All other formatting macros (`format!`, `write!`,
/// `println!`, etc) are proxied through this one.
///
/// For more information, see the documentation in `std::fmt`.
///
/// # Example
///
/// ```rust
/// use std::fmt;
///
/// let s = format_args!(fmt::format, "hello {}", "world");
/// assert_eq!(s, format!("hello {}", "world"));
///
/// format_args!(|args| {
/// // pass `args` to another function, etc.
/// }, "hello {}", "world");
/// ```
#[macro_export]
macro_rules! format_args( ($closure:expr, $fmt:expr $($args:tt)*) => ({
/* compiler built-in */
}) )
/// Inspect an environment variable at compile time.
///
/// This macro will expand to the value of the named environment variable at
/// compile time, yielding an expression of type `&'static str`.
///
/// If the environment variable is not defined, then a compilation error
/// will be emitted. To not emit a compile error, use the `option_env!`
/// macro instead.
///
/// # Example
///
/// ```rust
/// let path: &'static str = env!("PATH");
/// println!("the $PATH variable at the time of compiling was: {}", path);
/// ```
#[macro_export]
macro_rules! env( ($name:expr) => ({ /* compiler built-in */ }) )
/// Optionally inspect an environment variable at compile time.
///
/// If the named environment variable is present at compile time, this will
/// expand into an expression of type `Option<&'static str>` whose value is
/// `Some` of the value of the environment variable. If the environment
/// variable is not present, then this will expand to `None`.
///
/// A compile time error is never emitted when using this macro regardless
/// of whether the environment variable is present or not.
///
/// # Example
///
/// ```rust
/// let key: Option<&'static str> = option_env!("SECRET_KEY");
/// println!("the secret key might be: {}", key);
/// ```
#[macro_export]
macro_rules! option_env( ($name:expr) => ({ /* compiler built-in */ }) )
/// Concatenate literals into a static byte slice.
///
/// This macro takes any number of comma-separated literal expressions,
/// yielding an expression of type `&'static [u8]` which is the
/// concatenation (left to right) of all the literals in their byte format.
///
/// This extension currently only supports string literals, character
/// literals, and integers less than 256. The byte slice returned is the
/// utf8-encoding of strings and characters.
///
/// # Example
///
/// ```
/// let rust = bytes!("r", 'u', "st", 255);
/// assert_eq!(rust[1], b'u');
/// assert_eq!(rust[4], 255);
/// ```
#[macro_export]
macro_rules! bytes( ($($e:expr),*) => ({ /* compiler built-in */ }) )
/// Concatenate identifiers into one identifier.
///
/// This macro takes any number of comma-separated identifiers, and
/// concatenates them all into one, yielding an expression which is a new
/// identifier. Note that hygiene makes it such that this macro cannot
/// capture local variables, and macros are only allowed in item,
/// statement or expression position, meaning this macro may be difficult to
/// use in some situations.
///
/// # Example
///
/// ```
/// #![feature(concat_idents)]
///
/// # fn main() {
/// fn foobar() -> int { 23 }
///
/// let f = concat_idents!(foo, bar);
/// println!("{}", f());
/// # }
/// ```
#[macro_export]
macro_rules! concat_idents( ($($e:ident),*) => ({ /* compiler built-in */ }) )
/// Concatenates literals into a static string slice.
///
/// This macro takes any number of comma-separated literals, yielding an
/// expression of type `&'static str` which represents all of the literals
/// concatenated left-to-right.
///
/// Integer and floating point literals are stringified in order to be
/// concatenated.
///
/// # Example
///
/// ```
/// let s = concat!("test", 10i, 'b', true);
/// assert_eq!(s, "test10btrue");
/// ```
#[macro_export]
macro_rules! concat( ($($e:expr),*) => ({ /* compiler built-in */ }) )
/// A macro which expands to the line number on which it was invoked.
///
/// The expanded expression has type `uint`, and the returned line is not
/// the invocation of the `line!()` macro itself, but rather the first macro
/// invocation leading up to the invocation of the `line!()` macro.
///
/// # Example
///
/// ```
/// let current_line = line!();
/// println!("defined on line: {}", current_line);
/// ```
#[macro_export]
macro_rules! line( () => ({ /* compiler built-in */ }) )
/// A macro which expands to the column number on which it was invoked.
///
/// The expanded expression has type `uint`, and the returned column is not
/// the invocation of the `col!()` macro itself, but rather the first macro
/// invocation leading up to the invocation of the `col!()` macro.
///
/// # Example
///
/// ```
/// let current_col = col!();
/// println!("defined on column: {}", current_col);
/// ```
#[macro_export]
macro_rules! col( () => ({ /* compiler built-in */ }) )
/// A macro which expands to the file name from which it was invoked.
///
/// The expanded expression has type `&'static str`, and the returned file
/// is not the invocation of the `file!()` macro itself, but rather the
/// first macro invocation leading up to the invocation of the `file!()`
/// macro.
///
/// # Example
///
/// ```
/// let this_file = file!();
/// println!("defined in file: {}", this_file);
/// ```
#[macro_export]
macro_rules! file( () => ({ /* compiler built-in */ }) )
/// A macro which stringifies its argument.
///
/// This macro will yield an expression of type `&'static str` which is the
/// stringification of all the tokens passed to the macro. No restrictions
/// are placed on the syntax of the macro invocation itself.
///
/// # Example
///
/// ```
/// let one_plus_one = stringify!(1 + 1);
/// assert_eq!(one_plus_one, "1 + 1");
/// ```
#[macro_export]
macro_rules! stringify( ($t:tt) => ({ /* compiler built-in */ }) )
/// Includes a utf8-encoded file as a string.
///
/// This macro will yield an expression of type `&'static str` which is the
/// contents of the filename specified. The file is located relative to the
/// current file (similarly to how modules are found),
///
/// # Example
///
/// ```rust,ignore
/// let secret_key = include_str!("secret-key.ascii");
/// ```
#[macro_export]
macro_rules! include_str( ($file:expr) => ({ /* compiler built-in */ }) )
/// Includes a file as a byte slice.
///
/// This macro will yield an expression of type `&'static [u8]` which is
/// the contents of the filename specified. The file is located relative to
/// the current file (similarly to how modules are found),
///
/// # Example
///
/// ```rust,ignore
/// let secret_key = include_bin!("secret-key.bin");
/// ```
#[macro_export]
macro_rules! include_bin( ($file:expr) => ({ /* compiler built-in */ }) )
/// Expands to a string that represents the current module path.
///
/// The current module path can be thought of as the hierarchy of modules
/// leading back up to the crate root. The first component of the path
/// returned is the name of the crate currently being compiled.
///
/// # Example
///
/// ```rust
/// mod test {
/// pub fn foo() {
/// assert!(module_path!().ends_with("test"));
/// }
/// }
///
/// test::foo();
/// ```
#[macro_export]
macro_rules! module_path( () => ({ /* compiler built-in */ }) )
/// Boolean evaluation of configuration flags.
///
/// In addition to the `#[cfg]` attribute, this macro is provided to allow
/// boolean expression evaluation of configuration flags. This frequently
/// leads to less duplicated code.
///
/// The syntax given to this macro is the same syntax as the `cfg`
/// attribute.
///
/// # Example
///
/// ```rust
/// let my_directory = if cfg!(windows) {
/// "windows-specific-directory"
/// } else {
/// "unix-directory"
/// };
/// ```
#[macro_export]
macro_rules! cfg( ($cfg:tt) => ({ /* compiler built-in */ }) )
} | ) | random_line_split |
issue-3753.rs | // run-pass
// Issue #3656
// Issue Name: pub method preceded by attribute can't be parsed
// Abstract: Visibility parsing failed when compiler parsing
use std::f64;
#[derive(Copy, Clone)]
pub struct Point {
x: f64,
y: f64
}
#[derive(Copy, Clone)]
pub enum | {
Circle(Point, f64),
Rectangle(Point, Point)
}
impl Shape {
pub fn area(&self, sh: Shape) -> f64 {
match sh {
Shape::Circle(_, size) => f64::consts::PI * size * size,
Shape::Rectangle(Point {x, y}, Point {x: x2, y: y2}) => (x2 - x) * (y2 - y)
}
}
}
pub fn main(){
let s = Shape::Circle(Point { x: 1.0, y: 2.0 }, 3.0);
println!("{}", s.area(s));
}
| Shape | identifier_name |
issue-3753.rs | // run-pass
// Issue #3656
// Issue Name: pub method preceded by attribute can't be parsed
// Abstract: Visibility parsing failed when compiler parsing
use std::f64;
#[derive(Copy, Clone)] | pub struct Point {
x: f64,
y: f64
}
#[derive(Copy, Clone)]
pub enum Shape {
Circle(Point, f64),
Rectangle(Point, Point)
}
impl Shape {
pub fn area(&self, sh: Shape) -> f64 {
match sh {
Shape::Circle(_, size) => f64::consts::PI * size * size,
Shape::Rectangle(Point {x, y}, Point {x: x2, y: y2}) => (x2 - x) * (y2 - y)
}
}
}
pub fn main(){
let s = Shape::Circle(Point { x: 1.0, y: 2.0 }, 3.0);
println!("{}", s.area(s));
} | random_line_split |
|
rustbox.rs | extern crate gag;
extern crate libc;
extern crate num;
extern crate time;
extern crate termbox_sys as termbox;
#[macro_use] extern crate bitflags;
pub use self::style::{Style, RB_BOLD, RB_UNDERLINE, RB_REVERSE, RB_NORMAL};
use std::error::Error;
use std::fmt;
use std::io;
use std::char;
use std::default::Default;
use std::marker::PhantomData;
use num::FromPrimitive;
use termbox::RawEvent;
use libc::c_int;
use gag::Hold;
use time::Duration;
pub mod keyboard;
pub mod mouse;
pub use self::running::running;
pub use keyboard::Key;
pub use mouse::Mouse;
#[derive(Clone, Copy, Debug)]
pub enum Event {
KeyEventRaw(u8, u16, u32),
KeyEvent(Key),
ResizeEvent(i32, i32),
MouseEvent(Mouse, i32, i32),
NoEvent
}
#[derive(Clone, Copy, Debug)]
pub enum InputMode {
Current = 0x00,
/// When ESC sequence is in the buffer and it doesn't match any known
/// ESC sequence => ESC means TB_KEY_ESC
Esc = 0x01,
/// When ESC sequence is in the buffer and it doesn't match any known
/// sequence => ESC enables TB_MOD_ALT modifier for the next keyboard event.
Alt = 0x02,
/// Same as `Esc` but enables mouse events
EscMouse = 0x05,
/// Same as `Alt` but enables mouse events
AltMouse = 0x06
}
#[derive(Clone, Copy, PartialEq)]
#[repr(C,u16)]
pub enum Color {
Default = 0x00,
Black = 0x01,
Red = 0x02,
Green = 0x03,
Yellow = 0x04,
Blue = 0x05,
Magenta = 0x06,
Cyan = 0x07,
White = 0x08,
}
mod style {
bitflags! {
#[repr(C)]
flags Style: u16 {
const TB_NORMAL_COLOR = 0x000F,
const RB_BOLD = 0x0100,
const RB_UNDERLINE = 0x0200,
const RB_REVERSE = 0x0400,
const RB_NORMAL = 0x0000,
const TB_ATTRIB = RB_BOLD.bits | RB_UNDERLINE.bits | RB_REVERSE.bits,
}
}
impl Style {
pub fn from_color(color: super::Color) -> Style {
Style { bits: color as u16 & TB_NORMAL_COLOR.bits }
}
}
}
const NIL_RAW_EVENT: RawEvent = RawEvent { etype: 0, emod: 0, key: 0, ch: 0, w: 0, h: 0, x: 0, y: 0 };
#[derive(Debug)]
pub enum EventError {
TermboxError,
Unknown(isize),
}
impl fmt::Display for EventError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", self.description())
}
}
impl Error for EventError {
fn description(&self) -> &str {
match *self {
EventError::TermboxError => "Error in Termbox",
// I don't know how to format this without lifetime error.
// EventError::Unknown(n) => &format!("There was an unknown error. Error code: {}", n),
EventError::Unknown(_) => "Unknown error in Termbox",
}
}
}
impl FromPrimitive for EventError {
fn from_i64(n: i64) -> Option<EventError> {
match n {
-1 => Some(EventError::TermboxError),
n => Some(EventError::Unknown(n as isize)),
}
}
fn from_u64(n: u64) -> Option<EventError> {
Some(EventError::Unknown(n as isize))
}
}
pub type EventResult = Result<Event, EventError>;
/// Unpack a RawEvent to an Event
///
/// if the `raw` parameter is true, then the Event variant will be the raw
/// representation of the event.
/// for instance KeyEventRaw instead of KeyEvent
///
/// This is useful if you want to interpret the raw event data yourself, rather
/// than having rustbox translate it to its own representation.
fn unpack_event(ev_type: c_int, ev: &RawEvent, raw: bool) -> EventResult {
match ev_type {
0 => Ok(Event::NoEvent),
1 => Ok(
if raw {
Event::KeyEventRaw(ev.emod, ev.key, ev.ch)
} else {
let k = match ev.key {
0 => char::from_u32(ev.ch).map(|c| Key::Char(c)),
a => Key::from_code(a),
};
if let Some(key) = k {
Event::KeyEvent(key)
}
else {
Event::KeyEvent(Key::Unknown(ev.key))
}
}),
2 => Ok(Event::ResizeEvent(ev.w, ev.h)),
3 => {
let mouse = Mouse::from_code(ev.key).unwrap_or(Mouse::Left);
Ok(Event::MouseEvent(mouse, ev.x, ev.y))
},
// `unwrap` is safe here because FromPrimitive for EventError only returns `Some`.
n => Err(FromPrimitive::from_isize(n as isize).unwrap()),
}
}
#[derive(Debug)]
pub enum InitError {
BufferStderrFailed(io::Error),
AlreadyOpen,
UnsupportedTerminal,
FailedToOpenTTy,
PipeTrapError,
Unknown(isize),
}
impl fmt::Display for InitError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", self.description())
}
}
impl Error for InitError {
fn description(&self) -> &str {
match *self {
InitError::BufferStderrFailed(_) => "Could not redirect stderr",
InitError::AlreadyOpen => "RustBox is already open",
InitError::UnsupportedTerminal => "Unsupported terminal",
InitError::FailedToOpenTTy => "Failed to open TTY",
InitError::PipeTrapError => "Pipe trap error",
InitError::Unknown(_) => "Unknown error from Termbox",
}
}
fn cause(&self) -> Option<&Error> {
match *self {
InitError::BufferStderrFailed(ref e) => Some(e),
_ => None
}
}
}
impl FromPrimitive for InitError {
fn from_i64(n: i64) -> Option<InitError> {
match n {
-1 => Some(InitError::UnsupportedTerminal),
-2 => Some(InitError::FailedToOpenTTy),
-3 => Some(InitError::PipeTrapError),
n => Some(InitError::Unknown(n as isize)),
}
}
fn from_u64(n: u64) -> Option<InitError> {
Some(InitError::Unknown(n as isize))
}
}
#[allow(missing_copy_implementations)]
pub struct RustBox {
// We only bother to redirect stderr for the moment, since it's used for panic!
_stderr: Option<Hold>,
// RAII lock.
//
// Note that running *MUST* be the last field in the destructor, since destructors run in
// top-down order. Otherwise it will not properly protect the above fields.
_running: running::RunningGuard,
// Termbox is not thread safe. See #39.
_phantom: PhantomData<*mut ()>,
}
#[derive(Clone, Copy,Debug)]
pub struct InitOptions {
/// Use this option to initialize with a specific input mode
///
/// See InputMode enum for details on the variants.
pub input_mode: InputMode,
/// Use this option to automatically buffer stderr while RustBox is running. It will be
/// written when RustBox exits.
///
/// This option uses a nonblocking OS pipe to buffer stderr output. This means that if the
/// pipe fills up, subsequent writes will fail until RustBox exits. If this is a concern for
/// your program, don't use RustBox's default pipe-based redirection; instead, redirect stderr
/// to a log file or another process that is capable of handling it better.
pub buffer_stderr: bool,
}
impl Default for InitOptions {
fn default() -> Self {
InitOptions {
input_mode: InputMode::Current,
buffer_stderr: false,
}
}
}
mod running {
use std::sync::atomic::{self, AtomicBool};
// The state of the RustBox is protected by the lock. Yay, global state!
static RUSTBOX_RUNNING: AtomicBool = atomic::ATOMIC_BOOL_INIT;
/// true iff RustBox is currently running. Beware of races here--don't rely on this for anything
/// critical unless you happen to know that RustBox cannot change state when it is called (a good
/// usecase would be checking to see if it's worth risking double printing backtraces to avoid
/// having them swallowed up by RustBox).
pub fn running() -> bool {
RUSTBOX_RUNNING.load(atomic::Ordering::SeqCst)
}
// Internal RAII guard used to ensure we release the running lock whenever we acquire it.
#[allow(missing_copy_implementations)]
pub struct RunningGuard(());
pub fn run() -> Option<RunningGuard> {
// Ensure that we are not already running and simultaneously set RUSTBOX_RUNNING using an
// atomic swap. This ensures that contending threads don't trample each other.
if RUSTBOX_RUNNING.swap(true, atomic::Ordering::SeqCst) {
// The Rustbox was already running.
None
} else {
// The RustBox was not already running, and now we have the lock.
Some(RunningGuard(()))
}
}
impl Drop for RunningGuard {
fn drop(&mut self) {
// Indicate that we're free now. We could probably get away with lower atomicity here,
// but there's no reason to take that chance.
RUSTBOX_RUNNING.store(false, atomic::Ordering::SeqCst);
}
}
}
impl RustBox {
/// Initialize rustbox.
///
/// For the default options, you can use:
///
/// ```
/// use rustbox::RustBox;
/// use std::default::Default;
/// let rb = RustBox::init(Default::default());
/// ```
///
/// Otherwise, you can specify:
///
/// ```
/// use rustbox::{RustBox, InitOptions};
/// use std::default::Default;
/// let rb = RustBox::init(InitOptions { input_mode: rustbox::InputMode::Esc,..Default::default() });
/// ```
pub fn init(opts: InitOptions) -> Result<RustBox, InitError> {
let running = match running::run() {
Some(r) => r,
None => return Err(InitError::AlreadyOpen),
};
let stderr = if opts.buffer_stderr {
Some(try!(Hold::stderr().map_err(|e| InitError::BufferStderrFailed(e))))
} else {
None
};
// Create the RustBox.
let rb = unsafe { match termbox::tb_init() {
0 => RustBox {
_stderr: stderr,
_running: running,
_phantom: PhantomData,
},
res => {
return Err(FromPrimitive::from_isize(res as isize).unwrap())
}
}};
match opts.input_mode {
InputMode::Current => (),
_ => rb.set_input_mode(opts.input_mode),
}
Ok(rb)
}
pub fn width(&self) -> usize {
unsafe { termbox::tb_width() as usize }
}
pub fn height(&self) -> usize {
unsafe { termbox::tb_height() as usize }
}
pub fn clear(&self) {
unsafe { termbox::tb_clear() }
}
pub fn present(&self) |
pub fn set_cursor(&self, x: isize, y: isize) {
unsafe { termbox::tb_set_cursor(x as c_int, y as c_int) }
}
pub unsafe fn change_cell(&self, x: usize, y: usize, ch: u32, fg: u16, bg: u16) {
termbox::tb_change_cell(x as c_int, y as c_int, ch, fg, bg)
}
pub fn print(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, s: &str) {
let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB);
let bg = Style::from_color(bg);
for (i, ch) in s.chars().enumerate() {
unsafe {
self.change_cell(x+i, y, ch as u32, fg.bits(), bg.bits());
}
}
}
pub fn print_char(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, ch: char) {
let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB);
let bg = Style::from_color(bg);
unsafe {
self.change_cell(x, y, ch as u32, fg.bits(), bg.bits());
}
}
pub fn poll_event(&self, raw: bool) -> EventResult {
let mut ev = NIL_RAW_EVENT;
let rc = unsafe {
termbox::tb_poll_event(&mut ev)
};
unpack_event(rc, &ev, raw)
}
pub fn peek_event(&self, timeout: Duration, raw: bool) -> EventResult {
let mut ev = NIL_RAW_EVENT;
let rc = unsafe {
termbox::tb_peek_event(&mut ev, timeout.num_milliseconds() as c_int)
};
unpack_event(rc, &ev, raw)
}
pub fn set_input_mode(&self, mode: InputMode) {
unsafe {
termbox::tb_select_input_mode(mode as c_int);
}
}
}
impl Drop for RustBox {
fn drop(&mut self) {
// Since only one instance of the RustBox is ever accessible, we should not
// need to do this atomically.
// Note: we should definitely have RUSTBOX_RUNNING = true here.
unsafe {
termbox::tb_shutdown();
}
}
}
| {
unsafe { termbox::tb_present() }
} | identifier_body |
rustbox.rs | extern crate gag;
extern crate libc;
extern crate num;
extern crate time;
extern crate termbox_sys as termbox;
#[macro_use] extern crate bitflags;
pub use self::style::{Style, RB_BOLD, RB_UNDERLINE, RB_REVERSE, RB_NORMAL};
use std::error::Error;
use std::fmt;
use std::io;
use std::char;
use std::default::Default;
use std::marker::PhantomData;
use num::FromPrimitive;
use termbox::RawEvent;
use libc::c_int;
use gag::Hold;
use time::Duration;
pub mod keyboard;
pub mod mouse;
pub use self::running::running;
pub use keyboard::Key;
pub use mouse::Mouse;
#[derive(Clone, Copy, Debug)]
pub enum Event {
KeyEventRaw(u8, u16, u32),
KeyEvent(Key),
ResizeEvent(i32, i32),
MouseEvent(Mouse, i32, i32),
NoEvent
}
#[derive(Clone, Copy, Debug)]
pub enum InputMode {
Current = 0x00,
/// When ESC sequence is in the buffer and it doesn't match any known
/// ESC sequence => ESC means TB_KEY_ESC
Esc = 0x01,
/// When ESC sequence is in the buffer and it doesn't match any known
/// sequence => ESC enables TB_MOD_ALT modifier for the next keyboard event.
Alt = 0x02,
/// Same as `Esc` but enables mouse events
EscMouse = 0x05,
/// Same as `Alt` but enables mouse events
AltMouse = 0x06
}
#[derive(Clone, Copy, PartialEq)]
#[repr(C,u16)]
pub enum Color {
Default = 0x00,
Black = 0x01,
Red = 0x02,
Green = 0x03,
Yellow = 0x04,
Blue = 0x05,
Magenta = 0x06,
Cyan = 0x07,
White = 0x08,
}
mod style {
bitflags! {
#[repr(C)]
flags Style: u16 {
const TB_NORMAL_COLOR = 0x000F,
const RB_BOLD = 0x0100,
const RB_UNDERLINE = 0x0200,
const RB_REVERSE = 0x0400,
const RB_NORMAL = 0x0000,
const TB_ATTRIB = RB_BOLD.bits | RB_UNDERLINE.bits | RB_REVERSE.bits,
}
}
impl Style {
pub fn from_color(color: super::Color) -> Style {
Style { bits: color as u16 & TB_NORMAL_COLOR.bits }
}
}
}
const NIL_RAW_EVENT: RawEvent = RawEvent { etype: 0, emod: 0, key: 0, ch: 0, w: 0, h: 0, x: 0, y: 0 };
#[derive(Debug)]
pub enum EventError {
TermboxError,
Unknown(isize),
}
impl fmt::Display for EventError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", self.description())
}
}
impl Error for EventError {
fn description(&self) -> &str {
match *self {
EventError::TermboxError => "Error in Termbox",
// I don't know how to format this without lifetime error.
// EventError::Unknown(n) => &format!("There was an unknown error. Error code: {}", n),
EventError::Unknown(_) => "Unknown error in Termbox",
}
}
}
impl FromPrimitive for EventError {
fn from_i64(n: i64) -> Option<EventError> {
match n {
-1 => Some(EventError::TermboxError),
n => Some(EventError::Unknown(n as isize)),
}
}
fn from_u64(n: u64) -> Option<EventError> {
Some(EventError::Unknown(n as isize))
}
}
pub type EventResult = Result<Event, EventError>;
/// Unpack a RawEvent to an Event
///
/// if the `raw` parameter is true, then the Event variant will be the raw
/// representation of the event.
/// for instance KeyEventRaw instead of KeyEvent
///
/// This is useful if you want to interpret the raw event data yourself, rather
/// than having rustbox translate it to its own representation.
fn unpack_event(ev_type: c_int, ev: &RawEvent, raw: bool) -> EventResult {
match ev_type {
0 => Ok(Event::NoEvent),
1 => Ok(
if raw {
Event::KeyEventRaw(ev.emod, ev.key, ev.ch)
} else {
let k = match ev.key {
0 => char::from_u32(ev.ch).map(|c| Key::Char(c)),
a => Key::from_code(a),
};
if let Some(key) = k {
Event::KeyEvent(key)
}
else {
Event::KeyEvent(Key::Unknown(ev.key))
}
}),
2 => Ok(Event::ResizeEvent(ev.w, ev.h)),
3 => {
let mouse = Mouse::from_code(ev.key).unwrap_or(Mouse::Left);
Ok(Event::MouseEvent(mouse, ev.x, ev.y))
},
// `unwrap` is safe here because FromPrimitive for EventError only returns `Some`.
n => Err(FromPrimitive::from_isize(n as isize).unwrap()),
}
}
#[derive(Debug)]
pub enum InitError {
BufferStderrFailed(io::Error),
AlreadyOpen,
UnsupportedTerminal,
FailedToOpenTTy,
PipeTrapError,
Unknown(isize),
}
impl fmt::Display for InitError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", self.description())
}
}
impl Error for InitError {
fn description(&self) -> &str {
match *self {
InitError::BufferStderrFailed(_) => "Could not redirect stderr",
InitError::AlreadyOpen => "RustBox is already open",
InitError::UnsupportedTerminal => "Unsupported terminal",
InitError::FailedToOpenTTy => "Failed to open TTY",
InitError::PipeTrapError => "Pipe trap error",
InitError::Unknown(_) => "Unknown error from Termbox",
}
}
fn cause(&self) -> Option<&Error> {
match *self {
InitError::BufferStderrFailed(ref e) => Some(e),
_ => None
}
}
}
impl FromPrimitive for InitError {
fn from_i64(n: i64) -> Option<InitError> {
match n {
-1 => Some(InitError::UnsupportedTerminal),
-2 => Some(InitError::FailedToOpenTTy),
-3 => Some(InitError::PipeTrapError),
n => Some(InitError::Unknown(n as isize)),
}
}
fn from_u64(n: u64) -> Option<InitError> {
Some(InitError::Unknown(n as isize))
}
}
#[allow(missing_copy_implementations)]
pub struct RustBox {
// We only bother to redirect stderr for the moment, since it's used for panic!
_stderr: Option<Hold>,
// RAII lock.
//
// Note that running *MUST* be the last field in the destructor, since destructors run in
// top-down order. Otherwise it will not properly protect the above fields.
_running: running::RunningGuard,
// Termbox is not thread safe. See #39.
_phantom: PhantomData<*mut ()>,
}
#[derive(Clone, Copy,Debug)]
pub struct InitOptions {
/// Use this option to initialize with a specific input mode
///
/// See InputMode enum for details on the variants.
pub input_mode: InputMode,
/// Use this option to automatically buffer stderr while RustBox is running. It will be
/// written when RustBox exits.
///
/// This option uses a nonblocking OS pipe to buffer stderr output. This means that if the
/// pipe fills up, subsequent writes will fail until RustBox exits. If this is a concern for
/// your program, don't use RustBox's default pipe-based redirection; instead, redirect stderr
/// to a log file or another process that is capable of handling it better.
pub buffer_stderr: bool,
}
impl Default for InitOptions {
fn default() -> Self {
InitOptions {
input_mode: InputMode::Current,
buffer_stderr: false,
}
}
}
mod running {
use std::sync::atomic::{self, AtomicBool};
// The state of the RustBox is protected by the lock. Yay, global state!
static RUSTBOX_RUNNING: AtomicBool = atomic::ATOMIC_BOOL_INIT;
/// true iff RustBox is currently running. Beware of races here--don't rely on this for anything
/// critical unless you happen to know that RustBox cannot change state when it is called (a good
/// usecase would be checking to see if it's worth risking double printing backtraces to avoid
/// having them swallowed up by RustBox).
pub fn running() -> bool {
RUSTBOX_RUNNING.load(atomic::Ordering::SeqCst)
}
// Internal RAII guard used to ensure we release the running lock whenever we acquire it.
#[allow(missing_copy_implementations)]
pub struct RunningGuard(());
pub fn run() -> Option<RunningGuard> {
// Ensure that we are not already running and simultaneously set RUSTBOX_RUNNING using an
// atomic swap. This ensures that contending threads don't trample each other.
if RUSTBOX_RUNNING.swap(true, atomic::Ordering::SeqCst) {
// The Rustbox was already running.
None
} else {
// The RustBox was not already running, and now we have the lock.
Some(RunningGuard(()))
}
}
impl Drop for RunningGuard {
fn drop(&mut self) {
// Indicate that we're free now. We could probably get away with lower atomicity here,
// but there's no reason to take that chance.
RUSTBOX_RUNNING.store(false, atomic::Ordering::SeqCst);
}
}
}
impl RustBox {
/// Initialize rustbox.
///
/// For the default options, you can use:
///
/// ```
/// use rustbox::RustBox;
/// use std::default::Default;
/// let rb = RustBox::init(Default::default());
/// ```
///
/// Otherwise, you can specify:
///
/// ```
/// use rustbox::{RustBox, InitOptions};
/// use std::default::Default;
/// let rb = RustBox::init(InitOptions { input_mode: rustbox::InputMode::Esc,..Default::default() });
/// ```
pub fn init(opts: InitOptions) -> Result<RustBox, InitError> {
let running = match running::run() {
Some(r) => r,
None => return Err(InitError::AlreadyOpen),
};
let stderr = if opts.buffer_stderr {
Some(try!(Hold::stderr().map_err(|e| InitError::BufferStderrFailed(e))))
} else {
None
};
// Create the RustBox.
let rb = unsafe { match termbox::tb_init() {
0 => RustBox {
_stderr: stderr,
_running: running,
_phantom: PhantomData,
},
res => {
return Err(FromPrimitive::from_isize(res as isize).unwrap())
}
}};
match opts.input_mode {
InputMode::Current => (),
_ => rb.set_input_mode(opts.input_mode),
}
Ok(rb)
}
pub fn width(&self) -> usize {
unsafe { termbox::tb_width() as usize }
}
pub fn height(&self) -> usize {
unsafe { termbox::tb_height() as usize }
}
pub fn clear(&self) {
unsafe { termbox::tb_clear() }
}
pub fn present(&self) {
unsafe { termbox::tb_present() }
}
pub fn set_cursor(&self, x: isize, y: isize) {
unsafe { termbox::tb_set_cursor(x as c_int, y as c_int) }
}
pub unsafe fn change_cell(&self, x: usize, y: usize, ch: u32, fg: u16, bg: u16) {
termbox::tb_change_cell(x as c_int, y as c_int, ch, fg, bg)
}
pub fn print(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, s: &str) {
let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB);
let bg = Style::from_color(bg);
for (i, ch) in s.chars().enumerate() {
unsafe {
self.change_cell(x+i, y, ch as u32, fg.bits(), bg.bits());
}
}
}
pub fn print_char(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, ch: char) {
let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB);
let bg = Style::from_color(bg);
unsafe {
self.change_cell(x, y, ch as u32, fg.bits(), bg.bits());
}
}
pub fn poll_event(&self, raw: bool) -> EventResult {
let mut ev = NIL_RAW_EVENT;
let rc = unsafe {
termbox::tb_poll_event(&mut ev)
};
unpack_event(rc, &ev, raw)
}
pub fn peek_event(&self, timeout: Duration, raw: bool) -> EventResult {
let mut ev = NIL_RAW_EVENT;
let rc = unsafe {
termbox::tb_peek_event(&mut ev, timeout.num_milliseconds() as c_int)
};
unpack_event(rc, &ev, raw)
}
pub fn set_input_mode(&self, mode: InputMode) {
unsafe {
termbox::tb_select_input_mode(mode as c_int);
}
}
}
impl Drop for RustBox {
fn | (&mut self) {
// Since only one instance of the RustBox is ever accessible, we should not
// need to do this atomically.
// Note: we should definitely have RUSTBOX_RUNNING = true here.
unsafe {
termbox::tb_shutdown();
}
}
}
| drop | identifier_name |
rustbox.rs | extern crate gag;
extern crate libc;
extern crate num;
extern crate time;
extern crate termbox_sys as termbox;
#[macro_use] extern crate bitflags;
pub use self::style::{Style, RB_BOLD, RB_UNDERLINE, RB_REVERSE, RB_NORMAL};
use std::error::Error;
use std::fmt;
use std::io;
use std::char;
use std::default::Default;
use std::marker::PhantomData;
use num::FromPrimitive;
use termbox::RawEvent;
use libc::c_int;
use gag::Hold;
use time::Duration;
pub mod keyboard;
pub mod mouse;
pub use self::running::running;
pub use keyboard::Key;
pub use mouse::Mouse;
#[derive(Clone, Copy, Debug)]
pub enum Event {
KeyEventRaw(u8, u16, u32),
KeyEvent(Key),
ResizeEvent(i32, i32),
MouseEvent(Mouse, i32, i32),
NoEvent
}
#[derive(Clone, Copy, Debug)]
pub enum InputMode {
Current = 0x00,
/// When ESC sequence is in the buffer and it doesn't match any known
/// ESC sequence => ESC means TB_KEY_ESC
Esc = 0x01,
/// When ESC sequence is in the buffer and it doesn't match any known
/// sequence => ESC enables TB_MOD_ALT modifier for the next keyboard event.
Alt = 0x02,
/// Same as `Esc` but enables mouse events
EscMouse = 0x05,
/// Same as `Alt` but enables mouse events
AltMouse = 0x06
}
#[derive(Clone, Copy, PartialEq)]
#[repr(C,u16)]
pub enum Color {
Default = 0x00,
Black = 0x01,
Red = 0x02,
Green = 0x03,
Yellow = 0x04,
Blue = 0x05,
Magenta = 0x06,
Cyan = 0x07,
White = 0x08,
}
mod style {
bitflags! {
#[repr(C)]
flags Style: u16 {
const TB_NORMAL_COLOR = 0x000F,
const RB_BOLD = 0x0100,
const RB_UNDERLINE = 0x0200,
const RB_REVERSE = 0x0400,
const RB_NORMAL = 0x0000,
const TB_ATTRIB = RB_BOLD.bits | RB_UNDERLINE.bits | RB_REVERSE.bits,
}
}
impl Style {
pub fn from_color(color: super::Color) -> Style {
Style { bits: color as u16 & TB_NORMAL_COLOR.bits }
}
}
}
const NIL_RAW_EVENT: RawEvent = RawEvent { etype: 0, emod: 0, key: 0, ch: 0, w: 0, h: 0, x: 0, y: 0 };
#[derive(Debug)]
pub enum EventError {
TermboxError,
Unknown(isize),
}
impl fmt::Display for EventError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", self.description())
}
}
impl Error for EventError {
fn description(&self) -> &str {
match *self {
EventError::TermboxError => "Error in Termbox",
// I don't know how to format this without lifetime error.
// EventError::Unknown(n) => &format!("There was an unknown error. Error code: {}", n),
EventError::Unknown(_) => "Unknown error in Termbox",
}
}
}
impl FromPrimitive for EventError {
fn from_i64(n: i64) -> Option<EventError> {
match n {
-1 => Some(EventError::TermboxError),
n => Some(EventError::Unknown(n as isize)),
}
}
fn from_u64(n: u64) -> Option<EventError> {
Some(EventError::Unknown(n as isize))
}
}
pub type EventResult = Result<Event, EventError>;
/// Unpack a RawEvent to an Event
///
/// if the `raw` parameter is true, then the Event variant will be the raw
/// representation of the event.
/// for instance KeyEventRaw instead of KeyEvent
///
/// This is useful if you want to interpret the raw event data yourself, rather
/// than having rustbox translate it to its own representation.
fn unpack_event(ev_type: c_int, ev: &RawEvent, raw: bool) -> EventResult {
match ev_type {
0 => Ok(Event::NoEvent),
1 => Ok(
if raw {
Event::KeyEventRaw(ev.emod, ev.key, ev.ch)
} else {
let k = match ev.key {
0 => char::from_u32(ev.ch).map(|c| Key::Char(c)),
a => Key::from_code(a),
};
if let Some(key) = k {
Event::KeyEvent(key)
}
else {
Event::KeyEvent(Key::Unknown(ev.key))
}
}),
2 => Ok(Event::ResizeEvent(ev.w, ev.h)),
3 => {
let mouse = Mouse::from_code(ev.key).unwrap_or(Mouse::Left);
Ok(Event::MouseEvent(mouse, ev.x, ev.y))
},
// `unwrap` is safe here because FromPrimitive for EventError only returns `Some`.
n => Err(FromPrimitive::from_isize(n as isize).unwrap()),
}
}
#[derive(Debug)]
pub enum InitError {
BufferStderrFailed(io::Error),
AlreadyOpen,
UnsupportedTerminal,
FailedToOpenTTy,
PipeTrapError,
Unknown(isize),
}
impl fmt::Display for InitError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", self.description())
} | impl Error for InitError {
fn description(&self) -> &str {
match *self {
InitError::BufferStderrFailed(_) => "Could not redirect stderr",
InitError::AlreadyOpen => "RustBox is already open",
InitError::UnsupportedTerminal => "Unsupported terminal",
InitError::FailedToOpenTTy => "Failed to open TTY",
InitError::PipeTrapError => "Pipe trap error",
InitError::Unknown(_) => "Unknown error from Termbox",
}
}
fn cause(&self) -> Option<&Error> {
match *self {
InitError::BufferStderrFailed(ref e) => Some(e),
_ => None
}
}
}
impl FromPrimitive for InitError {
fn from_i64(n: i64) -> Option<InitError> {
match n {
-1 => Some(InitError::UnsupportedTerminal),
-2 => Some(InitError::FailedToOpenTTy),
-3 => Some(InitError::PipeTrapError),
n => Some(InitError::Unknown(n as isize)),
}
}
fn from_u64(n: u64) -> Option<InitError> {
Some(InitError::Unknown(n as isize))
}
}
#[allow(missing_copy_implementations)]
pub struct RustBox {
// We only bother to redirect stderr for the moment, since it's used for panic!
_stderr: Option<Hold>,
// RAII lock.
//
// Note that running *MUST* be the last field in the destructor, since destructors run in
// top-down order. Otherwise it will not properly protect the above fields.
_running: running::RunningGuard,
// Termbox is not thread safe. See #39.
_phantom: PhantomData<*mut ()>,
}
#[derive(Clone, Copy,Debug)]
pub struct InitOptions {
/// Use this option to initialize with a specific input mode
///
/// See InputMode enum for details on the variants.
pub input_mode: InputMode,
/// Use this option to automatically buffer stderr while RustBox is running. It will be
/// written when RustBox exits.
///
/// This option uses a nonblocking OS pipe to buffer stderr output. This means that if the
/// pipe fills up, subsequent writes will fail until RustBox exits. If this is a concern for
/// your program, don't use RustBox's default pipe-based redirection; instead, redirect stderr
/// to a log file or another process that is capable of handling it better.
pub buffer_stderr: bool,
}
impl Default for InitOptions {
fn default() -> Self {
InitOptions {
input_mode: InputMode::Current,
buffer_stderr: false,
}
}
}
mod running {
use std::sync::atomic::{self, AtomicBool};
// The state of the RustBox is protected by the lock. Yay, global state!
static RUSTBOX_RUNNING: AtomicBool = atomic::ATOMIC_BOOL_INIT;
/// true iff RustBox is currently running. Beware of races here--don't rely on this for anything
/// critical unless you happen to know that RustBox cannot change state when it is called (a good
/// usecase would be checking to see if it's worth risking double printing backtraces to avoid
/// having them swallowed up by RustBox).
pub fn running() -> bool {
RUSTBOX_RUNNING.load(atomic::Ordering::SeqCst)
}
// Internal RAII guard used to ensure we release the running lock whenever we acquire it.
#[allow(missing_copy_implementations)]
pub struct RunningGuard(());
pub fn run() -> Option<RunningGuard> {
// Ensure that we are not already running and simultaneously set RUSTBOX_RUNNING using an
// atomic swap. This ensures that contending threads don't trample each other.
if RUSTBOX_RUNNING.swap(true, atomic::Ordering::SeqCst) {
// The Rustbox was already running.
None
} else {
// The RustBox was not already running, and now we have the lock.
Some(RunningGuard(()))
}
}
impl Drop for RunningGuard {
fn drop(&mut self) {
// Indicate that we're free now. We could probably get away with lower atomicity here,
// but there's no reason to take that chance.
RUSTBOX_RUNNING.store(false, atomic::Ordering::SeqCst);
}
}
}
impl RustBox {
/// Initialize rustbox.
///
/// For the default options, you can use:
///
/// ```
/// use rustbox::RustBox;
/// use std::default::Default;
/// let rb = RustBox::init(Default::default());
/// ```
///
/// Otherwise, you can specify:
///
/// ```
/// use rustbox::{RustBox, InitOptions};
/// use std::default::Default;
/// let rb = RustBox::init(InitOptions { input_mode: rustbox::InputMode::Esc,..Default::default() });
/// ```
pub fn init(opts: InitOptions) -> Result<RustBox, InitError> {
let running = match running::run() {
Some(r) => r,
None => return Err(InitError::AlreadyOpen),
};
let stderr = if opts.buffer_stderr {
Some(try!(Hold::stderr().map_err(|e| InitError::BufferStderrFailed(e))))
} else {
None
};
// Create the RustBox.
let rb = unsafe { match termbox::tb_init() {
0 => RustBox {
_stderr: stderr,
_running: running,
_phantom: PhantomData,
},
res => {
return Err(FromPrimitive::from_isize(res as isize).unwrap())
}
}};
match opts.input_mode {
InputMode::Current => (),
_ => rb.set_input_mode(opts.input_mode),
}
Ok(rb)
}
pub fn width(&self) -> usize {
unsafe { termbox::tb_width() as usize }
}
pub fn height(&self) -> usize {
unsafe { termbox::tb_height() as usize }
}
pub fn clear(&self) {
unsafe { termbox::tb_clear() }
}
pub fn present(&self) {
unsafe { termbox::tb_present() }
}
pub fn set_cursor(&self, x: isize, y: isize) {
unsafe { termbox::tb_set_cursor(x as c_int, y as c_int) }
}
pub unsafe fn change_cell(&self, x: usize, y: usize, ch: u32, fg: u16, bg: u16) {
termbox::tb_change_cell(x as c_int, y as c_int, ch, fg, bg)
}
pub fn print(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, s: &str) {
let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB);
let bg = Style::from_color(bg);
for (i, ch) in s.chars().enumerate() {
unsafe {
self.change_cell(x+i, y, ch as u32, fg.bits(), bg.bits());
}
}
}
pub fn print_char(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, ch: char) {
let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB);
let bg = Style::from_color(bg);
unsafe {
self.change_cell(x, y, ch as u32, fg.bits(), bg.bits());
}
}
pub fn poll_event(&self, raw: bool) -> EventResult {
let mut ev = NIL_RAW_EVENT;
let rc = unsafe {
termbox::tb_poll_event(&mut ev)
};
unpack_event(rc, &ev, raw)
}
pub fn peek_event(&self, timeout: Duration, raw: bool) -> EventResult {
let mut ev = NIL_RAW_EVENT;
let rc = unsafe {
termbox::tb_peek_event(&mut ev, timeout.num_milliseconds() as c_int)
};
unpack_event(rc, &ev, raw)
}
pub fn set_input_mode(&self, mode: InputMode) {
unsafe {
termbox::tb_select_input_mode(mode as c_int);
}
}
}
impl Drop for RustBox {
fn drop(&mut self) {
// Since only one instance of the RustBox is ever accessible, we should not
// need to do this atomically.
// Note: we should definitely have RUSTBOX_RUNNING = true here.
unsafe {
termbox::tb_shutdown();
}
}
} | }
| random_line_split |
color.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use azure::AzFloat;
use azure::azure_hl::Color as AzColor;
| r: (r as AzFloat) / (255.0 as AzFloat),
g: (g as AzFloat) / (255.0 as AzFloat),
b: (b as AzFloat) / (255.0 as AzFloat),
a: 1.0 as AzFloat
}
}
#[inline]
pub fn rgba(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
} | pub type Color = AzColor;
#[inline]
pub fn rgb(r: u8, g: u8, b: u8) -> AzColor {
AzColor { | random_line_split |
color.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use azure::AzFloat;
use azure::azure_hl::Color as AzColor;
pub type Color = AzColor;
#[inline]
pub fn rgb(r: u8, g: u8, b: u8) -> AzColor |
#[inline]
pub fn rgba(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
}
| {
AzColor {
r: (r as AzFloat) / (255.0 as AzFloat),
g: (g as AzFloat) / (255.0 as AzFloat),
b: (b as AzFloat) / (255.0 as AzFloat),
a: 1.0 as AzFloat
}
} | identifier_body |
color.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use azure::AzFloat;
use azure::azure_hl::Color as AzColor;
pub type Color = AzColor;
#[inline]
pub fn rgb(r: u8, g: u8, b: u8) -> AzColor {
AzColor {
r: (r as AzFloat) / (255.0 as AzFloat),
g: (g as AzFloat) / (255.0 as AzFloat),
b: (b as AzFloat) / (255.0 as AzFloat),
a: 1.0 as AzFloat
}
}
#[inline]
pub fn | (r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
}
| rgba | identifier_name |
export-glob-imports-target.rs | // xfail-fast
// 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.
// Test that a glob-export functions as an import
// when referenced within its own local scope.
// Modified to not use export since it's going away. --pcw | use foo::bar::*;
pub mod bar {
pub static a : int = 10;
}
pub fn zum() {
let _b = a;
}
}
pub fn main() { } |
mod foo { | random_line_split |
export-glob-imports-target.rs | // xfail-fast
// 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.
// Test that a glob-export functions as an import
// when referenced within its own local scope.
// Modified to not use export since it's going away. --pcw
mod foo {
use foo::bar::*;
pub mod bar {
pub static a : int = 10;
}
pub fn zum() {
let _b = a;
}
}
pub fn main() | { } | identifier_body |
|
export-glob-imports-target.rs | // xfail-fast
// 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.
// Test that a glob-export functions as an import
// when referenced within its own local scope.
// Modified to not use export since it's going away. --pcw
mod foo {
use foo::bar::*;
pub mod bar {
pub static a : int = 10;
}
pub fn zum() {
let _b = a;
}
}
pub fn | () { }
| main | identifier_name |
mod.rs | use std::ops::{Deref, DerefMut};
use std::io::Read;
use rocket::outcome::Outcome;
use rocket::request::Request;
use rocket::data::{self, Data, FromData};
use rocket::response::{self, Responder, content};
use rocket::http::Status;
use serde::{Serialize, Deserialize};
use serde_json;
pub use serde_json::Value;
pub use serde_json::error::Error as SerdeError;
/// The JSON type: implements `FromData` and `Responder`, allowing you to easily
/// consume and respond with JSON.
///
/// If you're receiving JSON data, simple add a `data` parameter to your route
/// arguments and ensure the type o the parameter is a `JSON<T>`, where `T` is
/// some type you'd like to parse from JSON. `T` must implement `Deserialize`
/// from [Serde](https://github.com/serde-rs/json). The data is parsed from the
/// HTTP request body.
///
/// ```rust,ignore
/// #[post("/users/", format = "application/json", data = "")]
/// fn new_user(user: JSON<User>) {
/// ...
/// }
/// ```
/// You don't _need_ to use `format = "application/json"`, but it _may_ be what
/// you want. Using `format = application/json` means that any request that
/// doesn't specify "application/json" as its first `Content-Type:` header
/// parameter will not be routed to this handler.
///
/// If you're responding with JSON data, return a `JSON<T>` type, where `T`
/// implements `Serialize` from [Serde](https://github.com/serde-rs/json). The
/// content type of the response is set to `application/json` automatically.
///
/// ```rust,ignore
/// #[get("/users/<id>")]
/// fn user(id: usize) -> JSON<User> {
/// let user_from_id = User::from(id);
/// ...
/// JSON(user_from_id)
/// }
/// ```
///
#[derive(Debug)]
pub struct JSON<T>(pub T);
impl<T> JSON<T> {
/// Consumes the JSON wrapper and returns the wrapped item.
///
/// # Example | /// # use rocket_contrib::JSON;
/// let string = "Hello".to_string();
/// let my_json = JSON(string);
/// assert_eq!(my_json.into_inner(), "Hello".to_string());
/// ```
pub fn into_inner(self) -> T {
self.0
}
}
/// Maximum size of JSON is 1MB.
/// TODO: Determine this size from some configuration parameter.
const MAX_SIZE: u64 = 1048576;
impl<T: Deserialize> FromData for JSON<T> {
type Error = SerdeError;
fn from_data(request: &Request, data: Data) -> data::Outcome<Self, SerdeError> {
if!request.content_type().map_or(false, |ct| ct.is_json()) {
error_!("Content-Type is not JSON.");
return Outcome::Forward(data);
}
let reader = data.open().take(MAX_SIZE);
match serde_json::from_reader(reader).map(|val| JSON(val)) {
Ok(value) => Outcome::Success(value),
Err(e) => {
error_!("Couldn't parse JSON body: {:?}", e);
Outcome::Failure((Status::BadRequest, e))
}
}
}
}
// Serializes the wrapped value into JSON. Returns a response with Content-Type
// JSON and a fixed-size body with the serialization. If serialization fails, an
// `Err` of `Status::InternalServerError` is returned.
impl<T: Serialize> Responder<'static> for JSON<T> {
fn respond(self) -> response::Result<'static> {
serde_json::to_string(&self.0).map(|string| {
content::JSON(string).respond().unwrap()
}).map_err(|e| {
error_!("JSON failed to serialize: {:?}", e);
Status::InternalServerError
})
}
}
impl<T> Deref for JSON<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
&self.0
}
}
impl<T> DerefMut for JSON<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
&mut self.0
}
}
/// A macro to create ad-hoc JSON serializable values using JSON syntax.
///
/// # Usage
///
/// To import the macro, add the `#[macro_use]` attribute to the `extern crate
/// rocket_contrib` invocation:
///
/// ```rust,ignore
/// #[macro_use] extern crate rocket_contrib;
/// ```
///
/// The return type of a macro invocation is
/// [Value](/rocket_contrib/enum.Value.html). A value created with this macro
/// can be returned from a handler as follows:
///
/// ```rust,ignore
/// use rocket_contrib::{JSON, Value};
///
/// #[get("/json")]
/// fn get_json() -> JSON<Value> {
/// JSON(json!({
/// "key": "value",
/// "array": [1, 2, 3, 4]
/// }))
/// }
/// ```
///
/// # Examples
///
/// Create a simple JSON object with two keys: `"username"` and `"id"`:
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate rocket_contrib;
/// # fn main() {
/// let value = json!({
/// "username": "mjordan",
/// "id": 23
/// });
/// # }
/// ```
///
/// Create a more complex object with a nested object and array:
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate rocket_contrib;
/// # fn main() {
/// let value = json!({
/// "code": 200,
/// "success": true,
/// "payload": {
/// "features": ["serde", "json"],
/// "ids": [12, 121],
/// },
/// });
/// # }
/// ```
///
/// Variables or expressions can be interpolated into the JSON literal. Any type
/// interpolated into an array element or object value must implement Serde's
/// `Serialize` trait, while any type interpolated into a object key must
/// implement `Into<String>`.
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate rocket_contrib;
/// # fn main() {
/// let code = 200;
/// let features = vec!["serde", "json"];
///
/// let value = json!({
/// "code": code,
/// "success": code == 200,
/// "payload": {
/// features[0]: features[1]
/// }
/// });
/// # }
/// ```
///
/// Trailing commas are allowed inside both arrays and objects.
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate rocket_contrib;
/// # fn main() {
/// let value = json!([
/// "notice",
/// "the",
/// "trailing",
/// "comma -->",
/// ]);
/// # }
/// ```
#[macro_export]
macro_rules! json {
($($json:tt)+) => {
json_internal!($($json)+)
};
} | /// ```rust | random_line_split |
mod.rs | use std::ops::{Deref, DerefMut};
use std::io::Read;
use rocket::outcome::Outcome;
use rocket::request::Request;
use rocket::data::{self, Data, FromData};
use rocket::response::{self, Responder, content};
use rocket::http::Status;
use serde::{Serialize, Deserialize};
use serde_json;
pub use serde_json::Value;
pub use serde_json::error::Error as SerdeError;
/// The JSON type: implements `FromData` and `Responder`, allowing you to easily
/// consume and respond with JSON.
///
/// If you're receiving JSON data, simple add a `data` parameter to your route
/// arguments and ensure the type o the parameter is a `JSON<T>`, where `T` is
/// some type you'd like to parse from JSON. `T` must implement `Deserialize`
/// from [Serde](https://github.com/serde-rs/json). The data is parsed from the
/// HTTP request body.
///
/// ```rust,ignore
/// #[post("/users/", format = "application/json", data = "")]
/// fn new_user(user: JSON<User>) {
/// ...
/// }
/// ```
/// You don't _need_ to use `format = "application/json"`, but it _may_ be what
/// you want. Using `format = application/json` means that any request that
/// doesn't specify "application/json" as its first `Content-Type:` header
/// parameter will not be routed to this handler.
///
/// If you're responding with JSON data, return a `JSON<T>` type, where `T`
/// implements `Serialize` from [Serde](https://github.com/serde-rs/json). The
/// content type of the response is set to `application/json` automatically.
///
/// ```rust,ignore
/// #[get("/users/<id>")]
/// fn user(id: usize) -> JSON<User> {
/// let user_from_id = User::from(id);
/// ...
/// JSON(user_from_id)
/// }
/// ```
///
#[derive(Debug)]
pub struct JSON<T>(pub T);
impl<T> JSON<T> {
/// Consumes the JSON wrapper and returns the wrapped item.
///
/// # Example
/// ```rust
/// # use rocket_contrib::JSON;
/// let string = "Hello".to_string();
/// let my_json = JSON(string);
/// assert_eq!(my_json.into_inner(), "Hello".to_string());
/// ```
pub fn into_inner(self) -> T |
}
/// Maximum size of JSON is 1MB.
/// TODO: Determine this size from some configuration parameter.
const MAX_SIZE: u64 = 1048576;
impl<T: Deserialize> FromData for JSON<T> {
type Error = SerdeError;
fn from_data(request: &Request, data: Data) -> data::Outcome<Self, SerdeError> {
if!request.content_type().map_or(false, |ct| ct.is_json()) {
error_!("Content-Type is not JSON.");
return Outcome::Forward(data);
}
let reader = data.open().take(MAX_SIZE);
match serde_json::from_reader(reader).map(|val| JSON(val)) {
Ok(value) => Outcome::Success(value),
Err(e) => {
error_!("Couldn't parse JSON body: {:?}", e);
Outcome::Failure((Status::BadRequest, e))
}
}
}
}
// Serializes the wrapped value into JSON. Returns a response with Content-Type
// JSON and a fixed-size body with the serialization. If serialization fails, an
// `Err` of `Status::InternalServerError` is returned.
impl<T: Serialize> Responder<'static> for JSON<T> {
fn respond(self) -> response::Result<'static> {
serde_json::to_string(&self.0).map(|string| {
content::JSON(string).respond().unwrap()
}).map_err(|e| {
error_!("JSON failed to serialize: {:?}", e);
Status::InternalServerError
})
}
}
impl<T> Deref for JSON<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
&self.0
}
}
impl<T> DerefMut for JSON<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
&mut self.0
}
}
/// A macro to create ad-hoc JSON serializable values using JSON syntax.
///
/// # Usage
///
/// To import the macro, add the `#[macro_use]` attribute to the `extern crate
/// rocket_contrib` invocation:
///
/// ```rust,ignore
/// #[macro_use] extern crate rocket_contrib;
/// ```
///
/// The return type of a macro invocation is
/// [Value](/rocket_contrib/enum.Value.html). A value created with this macro
/// can be returned from a handler as follows:
///
/// ```rust,ignore
/// use rocket_contrib::{JSON, Value};
///
/// #[get("/json")]
/// fn get_json() -> JSON<Value> {
/// JSON(json!({
/// "key": "value",
/// "array": [1, 2, 3, 4]
/// }))
/// }
/// ```
///
/// # Examples
///
/// Create a simple JSON object with two keys: `"username"` and `"id"`:
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate rocket_contrib;
/// # fn main() {
/// let value = json!({
/// "username": "mjordan",
/// "id": 23
/// });
/// # }
/// ```
///
/// Create a more complex object with a nested object and array:
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate rocket_contrib;
/// # fn main() {
/// let value = json!({
/// "code": 200,
/// "success": true,
/// "payload": {
/// "features": ["serde", "json"],
/// "ids": [12, 121],
/// },
/// });
/// # }
/// ```
///
/// Variables or expressions can be interpolated into the JSON literal. Any type
/// interpolated into an array element or object value must implement Serde's
/// `Serialize` trait, while any type interpolated into a object key must
/// implement `Into<String>`.
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate rocket_contrib;
/// # fn main() {
/// let code = 200;
/// let features = vec!["serde", "json"];
///
/// let value = json!({
/// "code": code,
/// "success": code == 200,
/// "payload": {
/// features[0]: features[1]
/// }
/// });
/// # }
/// ```
///
/// Trailing commas are allowed inside both arrays and objects.
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate rocket_contrib;
/// # fn main() {
/// let value = json!([
/// "notice",
/// "the",
/// "trailing",
/// "comma -->",
/// ]);
/// # }
/// ```
#[macro_export]
macro_rules! json {
($($json:tt)+) => {
json_internal!($($json)+)
};
}
| {
self.0
} | identifier_body |
mod.rs | use std::ops::{Deref, DerefMut};
use std::io::Read;
use rocket::outcome::Outcome;
use rocket::request::Request;
use rocket::data::{self, Data, FromData};
use rocket::response::{self, Responder, content};
use rocket::http::Status;
use serde::{Serialize, Deserialize};
use serde_json;
pub use serde_json::Value;
pub use serde_json::error::Error as SerdeError;
/// The JSON type: implements `FromData` and `Responder`, allowing you to easily
/// consume and respond with JSON.
///
/// If you're receiving JSON data, simple add a `data` parameter to your route
/// arguments and ensure the type o the parameter is a `JSON<T>`, where `T` is
/// some type you'd like to parse from JSON. `T` must implement `Deserialize`
/// from [Serde](https://github.com/serde-rs/json). The data is parsed from the
/// HTTP request body.
///
/// ```rust,ignore
/// #[post("/users/", format = "application/json", data = "")]
/// fn new_user(user: JSON<User>) {
/// ...
/// }
/// ```
/// You don't _need_ to use `format = "application/json"`, but it _may_ be what
/// you want. Using `format = application/json` means that any request that
/// doesn't specify "application/json" as its first `Content-Type:` header
/// parameter will not be routed to this handler.
///
/// If you're responding with JSON data, return a `JSON<T>` type, where `T`
/// implements `Serialize` from [Serde](https://github.com/serde-rs/json). The
/// content type of the response is set to `application/json` automatically.
///
/// ```rust,ignore
/// #[get("/users/<id>")]
/// fn user(id: usize) -> JSON<User> {
/// let user_from_id = User::from(id);
/// ...
/// JSON(user_from_id)
/// }
/// ```
///
#[derive(Debug)]
pub struct JSON<T>(pub T);
impl<T> JSON<T> {
/// Consumes the JSON wrapper and returns the wrapped item.
///
/// # Example
/// ```rust
/// # use rocket_contrib::JSON;
/// let string = "Hello".to_string();
/// let my_json = JSON(string);
/// assert_eq!(my_json.into_inner(), "Hello".to_string());
/// ```
pub fn | (self) -> T {
self.0
}
}
/// Maximum size of JSON is 1MB.
/// TODO: Determine this size from some configuration parameter.
const MAX_SIZE: u64 = 1048576;
impl<T: Deserialize> FromData for JSON<T> {
type Error = SerdeError;
fn from_data(request: &Request, data: Data) -> data::Outcome<Self, SerdeError> {
if!request.content_type().map_or(false, |ct| ct.is_json()) {
error_!("Content-Type is not JSON.");
return Outcome::Forward(data);
}
let reader = data.open().take(MAX_SIZE);
match serde_json::from_reader(reader).map(|val| JSON(val)) {
Ok(value) => Outcome::Success(value),
Err(e) => {
error_!("Couldn't parse JSON body: {:?}", e);
Outcome::Failure((Status::BadRequest, e))
}
}
}
}
// Serializes the wrapped value into JSON. Returns a response with Content-Type
// JSON and a fixed-size body with the serialization. If serialization fails, an
// `Err` of `Status::InternalServerError` is returned.
impl<T: Serialize> Responder<'static> for JSON<T> {
fn respond(self) -> response::Result<'static> {
serde_json::to_string(&self.0).map(|string| {
content::JSON(string).respond().unwrap()
}).map_err(|e| {
error_!("JSON failed to serialize: {:?}", e);
Status::InternalServerError
})
}
}
impl<T> Deref for JSON<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
&self.0
}
}
impl<T> DerefMut for JSON<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
&mut self.0
}
}
/// A macro to create ad-hoc JSON serializable values using JSON syntax.
///
/// # Usage
///
/// To import the macro, add the `#[macro_use]` attribute to the `extern crate
/// rocket_contrib` invocation:
///
/// ```rust,ignore
/// #[macro_use] extern crate rocket_contrib;
/// ```
///
/// The return type of a macro invocation is
/// [Value](/rocket_contrib/enum.Value.html). A value created with this macro
/// can be returned from a handler as follows:
///
/// ```rust,ignore
/// use rocket_contrib::{JSON, Value};
///
/// #[get("/json")]
/// fn get_json() -> JSON<Value> {
/// JSON(json!({
/// "key": "value",
/// "array": [1, 2, 3, 4]
/// }))
/// }
/// ```
///
/// # Examples
///
/// Create a simple JSON object with two keys: `"username"` and `"id"`:
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate rocket_contrib;
/// # fn main() {
/// let value = json!({
/// "username": "mjordan",
/// "id": 23
/// });
/// # }
/// ```
///
/// Create a more complex object with a nested object and array:
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate rocket_contrib;
/// # fn main() {
/// let value = json!({
/// "code": 200,
/// "success": true,
/// "payload": {
/// "features": ["serde", "json"],
/// "ids": [12, 121],
/// },
/// });
/// # }
/// ```
///
/// Variables or expressions can be interpolated into the JSON literal. Any type
/// interpolated into an array element or object value must implement Serde's
/// `Serialize` trait, while any type interpolated into a object key must
/// implement `Into<String>`.
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate rocket_contrib;
/// # fn main() {
/// let code = 200;
/// let features = vec!["serde", "json"];
///
/// let value = json!({
/// "code": code,
/// "success": code == 200,
/// "payload": {
/// features[0]: features[1]
/// }
/// });
/// # }
/// ```
///
/// Trailing commas are allowed inside both arrays and objects.
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate rocket_contrib;
/// # fn main() {
/// let value = json!([
/// "notice",
/// "the",
/// "trailing",
/// "comma -->",
/// ]);
/// # }
/// ```
#[macro_export]
macro_rules! json {
($($json:tt)+) => {
json_internal!($($json)+)
};
}
| into_inner | identifier_name |
archive_ro.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A wrapper around LLVM's archive (.a) code
use libc;
use ArchiveRef;
use std::ffi::CString;
use std::slice;
use std::path::Path;
pub struct ArchiveRO {
ptr: ArchiveRef,
}
impl ArchiveRO {
/// Opens a static archive for read-only purposes. This is more optimized
/// than the `open` method because it uses LLVM's internal `Archive` class
/// rather than shelling out to `ar` for everything.
///
/// If this archive is used with a mutable method, then an error will be
/// raised.
pub fn open(dst: &Path) -> Option<ArchiveRO> {
return unsafe {
let s = path2cstr(dst);
let ar = ::LLVMRustOpenArchive(s.as_ptr());
if ar.is_null() {
None
} else {
Some(ArchiveRO { ptr: ar })
}
};
#[cfg(unix)]
fn path2cstr(p: &Path) -> CString {
use std::os::unix::prelude::*;
use std::ffi::OsStr;
let p: &OsStr = p.as_ref();
CString::new(p.as_bytes()).unwrap()
}
#[cfg(windows)]
fn path2cstr(p: &Path) -> CString {
CString::new(p.to_str().unwrap()).unwrap()
}
}
/// Reads a file in the archive
pub fn read<'a>(&'a self, file: &str) -> Option<&'a [u8]> {
unsafe {
let mut size = 0 as libc::size_t;
let file = CString::new(file).unwrap();
let ptr = ::LLVMRustArchiveReadSection(self.ptr, file.as_ptr(),
&mut size);
if ptr.is_null() | else {
Some(slice::from_raw_parts(ptr as *const u8, size as usize))
}
}
}
}
impl Drop for ArchiveRO {
fn drop(&mut self) {
unsafe {
::LLVMRustDestroyArchive(self.ptr);
}
}
}
| {
None
} | conditional_block |
archive_ro.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A wrapper around LLVM's archive (.a) code
use libc;
use ArchiveRef;
use std::ffi::CString;
use std::slice;
use std::path::Path;
pub struct ArchiveRO {
ptr: ArchiveRef,
}
impl ArchiveRO {
/// Opens a static archive for read-only purposes. This is more optimized
/// than the `open` method because it uses LLVM's internal `Archive` class
/// rather than shelling out to `ar` for everything.
///
/// If this archive is used with a mutable method, then an error will be
/// raised.
pub fn open(dst: &Path) -> Option<ArchiveRO> {
return unsafe {
let s = path2cstr(dst);
let ar = ::LLVMRustOpenArchive(s.as_ptr());
if ar.is_null() {
None
} else {
Some(ArchiveRO { ptr: ar })
}
};
#[cfg(unix)]
fn path2cstr(p: &Path) -> CString {
use std::os::unix::prelude::*;
use std::ffi::OsStr;
let p: &OsStr = p.as_ref();
CString::new(p.as_bytes()).unwrap()
} | }
/// Reads a file in the archive
pub fn read<'a>(&'a self, file: &str) -> Option<&'a [u8]> {
unsafe {
let mut size = 0 as libc::size_t;
let file = CString::new(file).unwrap();
let ptr = ::LLVMRustArchiveReadSection(self.ptr, file.as_ptr(),
&mut size);
if ptr.is_null() {
None
} else {
Some(slice::from_raw_parts(ptr as *const u8, size as usize))
}
}
}
}
impl Drop for ArchiveRO {
fn drop(&mut self) {
unsafe {
::LLVMRustDestroyArchive(self.ptr);
}
}
} | #[cfg(windows)]
fn path2cstr(p: &Path) -> CString {
CString::new(p.to_str().unwrap()).unwrap()
} | random_line_split |
archive_ro.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A wrapper around LLVM's archive (.a) code
use libc;
use ArchiveRef;
use std::ffi::CString;
use std::slice;
use std::path::Path;
pub struct ArchiveRO {
ptr: ArchiveRef,
}
impl ArchiveRO {
/// Opens a static archive for read-only purposes. This is more optimized
/// than the `open` method because it uses LLVM's internal `Archive` class
/// rather than shelling out to `ar` for everything.
///
/// If this archive is used with a mutable method, then an error will be
/// raised.
pub fn open(dst: &Path) -> Option<ArchiveRO> {
return unsafe {
let s = path2cstr(dst);
let ar = ::LLVMRustOpenArchive(s.as_ptr());
if ar.is_null() {
None
} else {
Some(ArchiveRO { ptr: ar })
}
};
#[cfg(unix)]
fn path2cstr(p: &Path) -> CString {
use std::os::unix::prelude::*;
use std::ffi::OsStr;
let p: &OsStr = p.as_ref();
CString::new(p.as_bytes()).unwrap()
}
#[cfg(windows)]
fn | (p: &Path) -> CString {
CString::new(p.to_str().unwrap()).unwrap()
}
}
/// Reads a file in the archive
pub fn read<'a>(&'a self, file: &str) -> Option<&'a [u8]> {
unsafe {
let mut size = 0 as libc::size_t;
let file = CString::new(file).unwrap();
let ptr = ::LLVMRustArchiveReadSection(self.ptr, file.as_ptr(),
&mut size);
if ptr.is_null() {
None
} else {
Some(slice::from_raw_parts(ptr as *const u8, size as usize))
}
}
}
}
impl Drop for ArchiveRO {
fn drop(&mut self) {
unsafe {
::LLVMRustDestroyArchive(self.ptr);
}
}
}
| path2cstr | identifier_name |
archive_ro.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A wrapper around LLVM's archive (.a) code
use libc;
use ArchiveRef;
use std::ffi::CString;
use std::slice;
use std::path::Path;
pub struct ArchiveRO {
ptr: ArchiveRef,
}
impl ArchiveRO {
/// Opens a static archive for read-only purposes. This is more optimized
/// than the `open` method because it uses LLVM's internal `Archive` class
/// rather than shelling out to `ar` for everything.
///
/// If this archive is used with a mutable method, then an error will be
/// raised.
pub fn open(dst: &Path) -> Option<ArchiveRO> {
return unsafe {
let s = path2cstr(dst);
let ar = ::LLVMRustOpenArchive(s.as_ptr());
if ar.is_null() {
None
} else {
Some(ArchiveRO { ptr: ar })
}
};
#[cfg(unix)]
fn path2cstr(p: &Path) -> CString {
use std::os::unix::prelude::*;
use std::ffi::OsStr;
let p: &OsStr = p.as_ref();
CString::new(p.as_bytes()).unwrap()
}
#[cfg(windows)]
fn path2cstr(p: &Path) -> CString |
}
/// Reads a file in the archive
pub fn read<'a>(&'a self, file: &str) -> Option<&'a [u8]> {
unsafe {
let mut size = 0 as libc::size_t;
let file = CString::new(file).unwrap();
let ptr = ::LLVMRustArchiveReadSection(self.ptr, file.as_ptr(),
&mut size);
if ptr.is_null() {
None
} else {
Some(slice::from_raw_parts(ptr as *const u8, size as usize))
}
}
}
}
impl Drop for ArchiveRO {
fn drop(&mut self) {
unsafe {
::LLVMRustDestroyArchive(self.ptr);
}
}
}
| {
CString::new(p.to_str().unwrap()).unwrap()
} | identifier_body |
plane.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <[email protected]> |
// | |
// | This file is part of System Syzygy. |
// | |
// | System Syzygy 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. |
// | |
// | System Syzygy 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 details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use num_integer::div_floor;
use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use crate::gui::{
Action, Align, Canvas, Element, Event, Font, Point, Rect, Resources,
Sprite,
};
use crate::save::plane::{PlaneGrid, PlaneObj};
use crate::save::Direction;
// ========================================================================= //
pub enum PlaneCmd {
Changed,
PushUndo(Vec<(Point, Point)>),
}
// ========================================================================= //
const TILE_USIZE: u32 = 24;
const TILE_ISIZE: i32 = TILE_USIZE as i32;
pub struct PlaneGridView {
left: i32,
top: i32,
obj_sprites: Vec<Sprite>,
pipe_sprites: Vec<Sprite>,
drag_from: Option<Point>,
changes: Vec<(Point, Point)>,
font: Rc<Font>,
letters: HashMap<Point, char>,
}
impl PlaneGridView {
pub fn new(
resources: &mut Resources,
left: i32,
top: i32,
) -> PlaneGridView {
PlaneGridView {
left,
top,
obj_sprites: resources.get_sprites("plane/objects"),
pipe_sprites: resources.get_sprites("plane/pipes"),
drag_from: None,
changes: Vec::new(),
font: resources.get_font("roman"),
letters: HashMap::new(),
}
}
pub fn cancel_drag_and_clear_changes(&mut self) {
self.drag_from = None;
self.changes.clear();
}
pub fn cancel_drag_and_undo_changes(&mut self, grid: &mut PlaneGrid) {
self.drag_from = None;
for &(coords1, coords2) in self.changes.iter().rev() {
grid.toggle_pipe(coords1, coords2);
}
self.changes.clear();
}
pub fn add_letter(&mut self, coords: Point, letter: char) {
self.letters.insert(coords, letter);
}
fn rect(&self, grid: &PlaneGrid) -> Rect {
Rect::new(
self.left,
self.top,
grid.num_cols() * TILE_USIZE,
grid.num_rows() * TILE_USIZE,
)
}
fn pt_to_coords(&self, grid: &PlaneGrid, pt: Point) -> Option<Point> {
let col = div_floor(pt.x() - self.left, TILE_ISIZE);
let row = div_floor(pt.y() - self.top, TILE_ISIZE);
let coords = Point::new(col, row);
if grid.contains_coords(coords) {
Some(coords)
} else {
None
}
}
fn | (
&self,
grid: &PlaneGrid,
pos: Point,
dir: Direction,
canvas: &mut Canvas,
) {
let obj = grid.objects().get(&pos).cloned();
let sprite_index = match (dir, obj) {
(Direction::West, Some(PlaneObj::Cross)) => 10,
(Direction::West, Some(obj)) if obj.is_node() => 13,
(Direction::West, _) => 0,
(Direction::East, Some(PlaneObj::Cross)) => 11,
(Direction::East, Some(obj)) if obj.is_node() => 15,
(Direction::East, _) => 2,
(Direction::South, Some(obj)) if obj.is_node() => 14,
(Direction::South, _) => 1,
(Direction::North, Some(obj)) if obj.is_node() => 16,
(Direction::North, _) => 3,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, pos * TILE_ISIZE);
}
}
impl Element<PlaneGrid, PlaneCmd> for PlaneGridView {
fn draw(&self, grid: &PlaneGrid, canvas: &mut Canvas) {
let mut canvas = canvas.subcanvas(self.rect(grid));
canvas.clear((64, 64, 64));
for row in 0..(grid.num_rows() as i32) {
for col in 0..(grid.num_cols() as i32) {
let coords = Point::new(col, row);
if let Some(&obj) = grid.objects().get(&coords) {
let sprite_index = match obj {
PlaneObj::Wall => 0,
PlaneObj::Cross => 1,
PlaneObj::PurpleNode => 2,
PlaneObj::RedNode => 3,
PlaneObj::GreenNode => 4,
PlaneObj::BlueNode => 5,
PlaneObj::GrayNode => 6,
};
let sprite = &self.obj_sprites[sprite_index];
canvas.draw_sprite(sprite, coords * TILE_ISIZE);
} else {
let pt = coords * TILE_ISIZE;
let rect = Rect::new(
pt.x() + 1,
pt.y() + 1,
TILE_USIZE - 2,
TILE_USIZE - 2,
);
canvas.draw_rect((72, 72, 72), rect);
}
}
}
for pipe in grid.pipes() {
debug_assert!(pipe.len() >= 2);
let mut start = pipe[0];
let mut next = pipe[1];
let mut dir = Direction::from_delta(next - start);
self.draw_pipe_tip(grid, start, dir, &mut canvas);
for index in 2..pipe.len() {
start = next;
next = pipe[index];
let prev_dir = dir;
dir = Direction::from_delta(next - start);
let sprite_index = match (prev_dir, dir) {
(Direction::East, Direction::North) => 6,
(Direction::East, Direction::South) => 7,
(Direction::West, Direction::North) => 5,
(Direction::West, Direction::South) => 4,
(Direction::East, _) | (Direction::West, _) => {
let obj = grid.objects().get(&start).cloned();
if obj == Some(PlaneObj::Cross) {
12
} else {
8
}
}
(Direction::North, Direction::East) => 4,
(Direction::North, Direction::West) => 7,
(Direction::South, Direction::East) => 5,
(Direction::South, Direction::West) => 6,
(Direction::North, _) | (Direction::South, _) => 9,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, start * TILE_ISIZE);
}
dir = Direction::from_delta(start - next);
self.draw_pipe_tip(grid, next, dir, &mut canvas);
}
for (&coords, &letter) in self.letters.iter() {
let pt = Point::new(
coords.x() * TILE_ISIZE + TILE_ISIZE / 2,
coords.y() * TILE_ISIZE + TILE_ISIZE / 2 + 4,
);
canvas.draw_char(&self.font, Align::Center, pt, letter);
}
}
fn handle_event(
&mut self,
event: &Event,
grid: &mut PlaneGrid,
) -> Action<PlaneCmd> {
match event {
&Event::MouseDown(pt) if self.rect(grid).contains_point(pt) => {
self.drag_from = self.pt_to_coords(grid, pt);
Action::ignore().and_stop()
}
&Event::MouseDrag(pt) => {
if let Some(coords1) = self.drag_from {
if let Some(coords2) = self.pt_to_coords(grid, pt) {
self.drag_from = Some(coords2);
if grid.toggle_pipe(coords1, coords2) {
self.changes.push((coords1, coords2));
return Action::redraw()
.and_return(PlaneCmd::Changed);
}
}
}
Action::ignore()
}
&Event::MouseUp => {
self.drag_from = None;
if self.changes.is_empty() {
Action::ignore()
} else {
let vec = mem::replace(&mut self.changes, Vec::new());
Action::redraw().and_return(PlaneCmd::PushUndo(vec))
}
}
_ => Action::ignore(),
}
}
}
// ========================================================================= //
| draw_pipe_tip | identifier_name |
plane.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <[email protected]> |
// | |
// | This file is part of System Syzygy. |
// | |
// | System Syzygy 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. |
// | |
// | System Syzygy 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 details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use num_integer::div_floor;
use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use crate::gui::{
Action, Align, Canvas, Element, Event, Font, Point, Rect, Resources,
Sprite,
};
use crate::save::plane::{PlaneGrid, PlaneObj};
use crate::save::Direction;
// ========================================================================= //
pub enum PlaneCmd {
Changed,
PushUndo(Vec<(Point, Point)>),
}
// ========================================================================= //
const TILE_USIZE: u32 = 24;
const TILE_ISIZE: i32 = TILE_USIZE as i32;
pub struct PlaneGridView {
left: i32,
top: i32,
obj_sprites: Vec<Sprite>,
pipe_sprites: Vec<Sprite>,
drag_from: Option<Point>,
changes: Vec<(Point, Point)>,
font: Rc<Font>,
letters: HashMap<Point, char>,
}
impl PlaneGridView {
pub fn new(
resources: &mut Resources,
left: i32,
top: i32,
) -> PlaneGridView {
PlaneGridView {
left,
top,
obj_sprites: resources.get_sprites("plane/objects"),
pipe_sprites: resources.get_sprites("plane/pipes"),
drag_from: None,
changes: Vec::new(),
font: resources.get_font("roman"),
letters: HashMap::new(),
}
}
pub fn cancel_drag_and_clear_changes(&mut self) {
self.drag_from = None;
self.changes.clear();
}
pub fn cancel_drag_and_undo_changes(&mut self, grid: &mut PlaneGrid) {
self.drag_from = None;
for &(coords1, coords2) in self.changes.iter().rev() {
grid.toggle_pipe(coords1, coords2);
}
self.changes.clear();
}
pub fn add_letter(&mut self, coords: Point, letter: char) {
self.letters.insert(coords, letter);
}
fn rect(&self, grid: &PlaneGrid) -> Rect {
Rect::new(
self.left,
self.top,
grid.num_cols() * TILE_USIZE,
grid.num_rows() * TILE_USIZE,
)
}
fn pt_to_coords(&self, grid: &PlaneGrid, pt: Point) -> Option<Point> {
let col = div_floor(pt.x() - self.left, TILE_ISIZE);
let row = div_floor(pt.y() - self.top, TILE_ISIZE);
let coords = Point::new(col, row);
if grid.contains_coords(coords) {
Some(coords)
} else {
None
}
}
fn draw_pipe_tip(
&self,
grid: &PlaneGrid,
pos: Point,
dir: Direction,
canvas: &mut Canvas,
) {
let obj = grid.objects().get(&pos).cloned();
let sprite_index = match (dir, obj) {
(Direction::West, Some(PlaneObj::Cross)) => 10,
(Direction::West, Some(obj)) if obj.is_node() => 13,
(Direction::West, _) => 0,
(Direction::East, Some(PlaneObj::Cross)) => 11,
(Direction::East, Some(obj)) if obj.is_node() => 15,
(Direction::East, _) => 2,
(Direction::South, Some(obj)) if obj.is_node() => 14,
(Direction::South, _) => 1,
(Direction::North, Some(obj)) if obj.is_node() => 16,
(Direction::North, _) => 3,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, pos * TILE_ISIZE);
}
}
impl Element<PlaneGrid, PlaneCmd> for PlaneGridView {
fn draw(&self, grid: &PlaneGrid, canvas: &mut Canvas) {
let mut canvas = canvas.subcanvas(self.rect(grid));
canvas.clear((64, 64, 64));
for row in 0..(grid.num_rows() as i32) {
for col in 0..(grid.num_cols() as i32) {
let coords = Point::new(col, row);
if let Some(&obj) = grid.objects().get(&coords) {
let sprite_index = match obj {
PlaneObj::Wall => 0,
PlaneObj::Cross => 1,
PlaneObj::PurpleNode => 2,
PlaneObj::RedNode => 3,
PlaneObj::GreenNode => 4,
PlaneObj::BlueNode => 5,
PlaneObj::GrayNode => 6,
};
let sprite = &self.obj_sprites[sprite_index];
canvas.draw_sprite(sprite, coords * TILE_ISIZE);
} else {
let pt = coords * TILE_ISIZE;
let rect = Rect::new(
pt.x() + 1,
pt.y() + 1,
TILE_USIZE - 2,
TILE_USIZE - 2,
);
canvas.draw_rect((72, 72, 72), rect);
}
}
}
for pipe in grid.pipes() {
debug_assert!(pipe.len() >= 2);
let mut start = pipe[0];
let mut next = pipe[1];
let mut dir = Direction::from_delta(next - start);
self.draw_pipe_tip(grid, start, dir, &mut canvas);
for index in 2..pipe.len() {
start = next;
next = pipe[index];
let prev_dir = dir;
dir = Direction::from_delta(next - start);
let sprite_index = match (prev_dir, dir) {
(Direction::East, Direction::North) => 6,
(Direction::East, Direction::South) => 7,
(Direction::West, Direction::North) => 5,
(Direction::West, Direction::South) => 4,
(Direction::East, _) | (Direction::West, _) => {
let obj = grid.objects().get(&start).cloned();
if obj == Some(PlaneObj::Cross) {
12
} else |
}
(Direction::North, Direction::East) => 4,
(Direction::North, Direction::West) => 7,
(Direction::South, Direction::East) => 5,
(Direction::South, Direction::West) => 6,
(Direction::North, _) | (Direction::South, _) => 9,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, start * TILE_ISIZE);
}
dir = Direction::from_delta(start - next);
self.draw_pipe_tip(grid, next, dir, &mut canvas);
}
for (&coords, &letter) in self.letters.iter() {
let pt = Point::new(
coords.x() * TILE_ISIZE + TILE_ISIZE / 2,
coords.y() * TILE_ISIZE + TILE_ISIZE / 2 + 4,
);
canvas.draw_char(&self.font, Align::Center, pt, letter);
}
}
fn handle_event(
&mut self,
event: &Event,
grid: &mut PlaneGrid,
) -> Action<PlaneCmd> {
match event {
&Event::MouseDown(pt) if self.rect(grid).contains_point(pt) => {
self.drag_from = self.pt_to_coords(grid, pt);
Action::ignore().and_stop()
}
&Event::MouseDrag(pt) => {
if let Some(coords1) = self.drag_from {
if let Some(coords2) = self.pt_to_coords(grid, pt) {
self.drag_from = Some(coords2);
if grid.toggle_pipe(coords1, coords2) {
self.changes.push((coords1, coords2));
return Action::redraw()
.and_return(PlaneCmd::Changed);
}
}
}
Action::ignore()
}
&Event::MouseUp => {
self.drag_from = None;
if self.changes.is_empty() {
Action::ignore()
} else {
let vec = mem::replace(&mut self.changes, Vec::new());
Action::redraw().and_return(PlaneCmd::PushUndo(vec))
}
}
_ => Action::ignore(),
}
}
}
// ========================================================================= //
| {
8
} | conditional_block |
plane.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <[email protected]> |
// | |
// | This file is part of System Syzygy. |
// | |
// | System Syzygy 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. |
// | |
// | System Syzygy 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 details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use num_integer::div_floor;
use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use crate::gui::{
Action, Align, Canvas, Element, Event, Font, Point, Rect, Resources,
Sprite,
};
use crate::save::plane::{PlaneGrid, PlaneObj};
use crate::save::Direction;
// ========================================================================= //
pub enum PlaneCmd {
Changed,
PushUndo(Vec<(Point, Point)>),
}
// ========================================================================= //
const TILE_USIZE: u32 = 24;
const TILE_ISIZE: i32 = TILE_USIZE as i32;
pub struct PlaneGridView {
left: i32,
top: i32,
obj_sprites: Vec<Sprite>,
pipe_sprites: Vec<Sprite>,
drag_from: Option<Point>,
changes: Vec<(Point, Point)>,
font: Rc<Font>,
letters: HashMap<Point, char>,
}
impl PlaneGridView {
pub fn new(
resources: &mut Resources,
left: i32,
top: i32,
) -> PlaneGridView |
pub fn cancel_drag_and_clear_changes(&mut self) {
self.drag_from = None;
self.changes.clear();
}
pub fn cancel_drag_and_undo_changes(&mut self, grid: &mut PlaneGrid) {
self.drag_from = None;
for &(coords1, coords2) in self.changes.iter().rev() {
grid.toggle_pipe(coords1, coords2);
}
self.changes.clear();
}
pub fn add_letter(&mut self, coords: Point, letter: char) {
self.letters.insert(coords, letter);
}
fn rect(&self, grid: &PlaneGrid) -> Rect {
Rect::new(
self.left,
self.top,
grid.num_cols() * TILE_USIZE,
grid.num_rows() * TILE_USIZE,
)
}
fn pt_to_coords(&self, grid: &PlaneGrid, pt: Point) -> Option<Point> {
let col = div_floor(pt.x() - self.left, TILE_ISIZE);
let row = div_floor(pt.y() - self.top, TILE_ISIZE);
let coords = Point::new(col, row);
if grid.contains_coords(coords) {
Some(coords)
} else {
None
}
}
fn draw_pipe_tip(
&self,
grid: &PlaneGrid,
pos: Point,
dir: Direction,
canvas: &mut Canvas,
) {
let obj = grid.objects().get(&pos).cloned();
let sprite_index = match (dir, obj) {
(Direction::West, Some(PlaneObj::Cross)) => 10,
(Direction::West, Some(obj)) if obj.is_node() => 13,
(Direction::West, _) => 0,
(Direction::East, Some(PlaneObj::Cross)) => 11,
(Direction::East, Some(obj)) if obj.is_node() => 15,
(Direction::East, _) => 2,
(Direction::South, Some(obj)) if obj.is_node() => 14,
(Direction::South, _) => 1,
(Direction::North, Some(obj)) if obj.is_node() => 16,
(Direction::North, _) => 3,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, pos * TILE_ISIZE);
}
}
impl Element<PlaneGrid, PlaneCmd> for PlaneGridView {
fn draw(&self, grid: &PlaneGrid, canvas: &mut Canvas) {
let mut canvas = canvas.subcanvas(self.rect(grid));
canvas.clear((64, 64, 64));
for row in 0..(grid.num_rows() as i32) {
for col in 0..(grid.num_cols() as i32) {
let coords = Point::new(col, row);
if let Some(&obj) = grid.objects().get(&coords) {
let sprite_index = match obj {
PlaneObj::Wall => 0,
PlaneObj::Cross => 1,
PlaneObj::PurpleNode => 2,
PlaneObj::RedNode => 3,
PlaneObj::GreenNode => 4,
PlaneObj::BlueNode => 5,
PlaneObj::GrayNode => 6,
};
let sprite = &self.obj_sprites[sprite_index];
canvas.draw_sprite(sprite, coords * TILE_ISIZE);
} else {
let pt = coords * TILE_ISIZE;
let rect = Rect::new(
pt.x() + 1,
pt.y() + 1,
TILE_USIZE - 2,
TILE_USIZE - 2,
);
canvas.draw_rect((72, 72, 72), rect);
}
}
}
for pipe in grid.pipes() {
debug_assert!(pipe.len() >= 2);
let mut start = pipe[0];
let mut next = pipe[1];
let mut dir = Direction::from_delta(next - start);
self.draw_pipe_tip(grid, start, dir, &mut canvas);
for index in 2..pipe.len() {
start = next;
next = pipe[index];
let prev_dir = dir;
dir = Direction::from_delta(next - start);
let sprite_index = match (prev_dir, dir) {
(Direction::East, Direction::North) => 6,
(Direction::East, Direction::South) => 7,
(Direction::West, Direction::North) => 5,
(Direction::West, Direction::South) => 4,
(Direction::East, _) | (Direction::West, _) => {
let obj = grid.objects().get(&start).cloned();
if obj == Some(PlaneObj::Cross) {
12
} else {
8
}
}
(Direction::North, Direction::East) => 4,
(Direction::North, Direction::West) => 7,
(Direction::South, Direction::East) => 5,
(Direction::South, Direction::West) => 6,
(Direction::North, _) | (Direction::South, _) => 9,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, start * TILE_ISIZE);
}
dir = Direction::from_delta(start - next);
self.draw_pipe_tip(grid, next, dir, &mut canvas);
}
for (&coords, &letter) in self.letters.iter() {
let pt = Point::new(
coords.x() * TILE_ISIZE + TILE_ISIZE / 2,
coords.y() * TILE_ISIZE + TILE_ISIZE / 2 + 4,
);
canvas.draw_char(&self.font, Align::Center, pt, letter);
}
}
fn handle_event(
&mut self,
event: &Event,
grid: &mut PlaneGrid,
) -> Action<PlaneCmd> {
match event {
&Event::MouseDown(pt) if self.rect(grid).contains_point(pt) => {
self.drag_from = self.pt_to_coords(grid, pt);
Action::ignore().and_stop()
}
&Event::MouseDrag(pt) => {
if let Some(coords1) = self.drag_from {
if let Some(coords2) = self.pt_to_coords(grid, pt) {
self.drag_from = Some(coords2);
if grid.toggle_pipe(coords1, coords2) {
self.changes.push((coords1, coords2));
return Action::redraw()
.and_return(PlaneCmd::Changed);
}
}
}
Action::ignore()
}
&Event::MouseUp => {
self.drag_from = None;
if self.changes.is_empty() {
Action::ignore()
} else {
let vec = mem::replace(&mut self.changes, Vec::new());
Action::redraw().and_return(PlaneCmd::PushUndo(vec))
}
}
_ => Action::ignore(),
}
}
}
// ========================================================================= //
| {
PlaneGridView {
left,
top,
obj_sprites: resources.get_sprites("plane/objects"),
pipe_sprites: resources.get_sprites("plane/pipes"),
drag_from: None,
changes: Vec::new(),
font: resources.get_font("roman"),
letters: HashMap::new(),
}
} | identifier_body |
plane.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <[email protected]> |
// | |
// | This file is part of System Syzygy. |
// | |
// | System Syzygy 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. |
// | |
// | System Syzygy 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 details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use num_integer::div_floor;
use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use crate::gui::{
Action, Align, Canvas, Element, Event, Font, Point, Rect, Resources,
Sprite,
};
use crate::save::plane::{PlaneGrid, PlaneObj};
use crate::save::Direction;
// ========================================================================= //
pub enum PlaneCmd {
Changed,
PushUndo(Vec<(Point, Point)>),
}
// ========================================================================= //
const TILE_USIZE: u32 = 24;
const TILE_ISIZE: i32 = TILE_USIZE as i32;
pub struct PlaneGridView {
left: i32,
top: i32,
obj_sprites: Vec<Sprite>,
pipe_sprites: Vec<Sprite>,
drag_from: Option<Point>,
changes: Vec<(Point, Point)>,
font: Rc<Font>,
letters: HashMap<Point, char>,
}
impl PlaneGridView {
pub fn new(
resources: &mut Resources,
left: i32,
top: i32,
) -> PlaneGridView {
PlaneGridView {
left,
top,
obj_sprites: resources.get_sprites("plane/objects"),
pipe_sprites: resources.get_sprites("plane/pipes"),
drag_from: None,
changes: Vec::new(),
font: resources.get_font("roman"),
letters: HashMap::new(),
}
}
pub fn cancel_drag_and_clear_changes(&mut self) {
self.drag_from = None;
self.changes.clear();
}
pub fn cancel_drag_and_undo_changes(&mut self, grid: &mut PlaneGrid) {
self.drag_from = None;
for &(coords1, coords2) in self.changes.iter().rev() {
grid.toggle_pipe(coords1, coords2);
}
self.changes.clear();
}
pub fn add_letter(&mut self, coords: Point, letter: char) {
self.letters.insert(coords, letter);
}
fn rect(&self, grid: &PlaneGrid) -> Rect {
Rect::new(
self.left,
self.top,
grid.num_cols() * TILE_USIZE,
grid.num_rows() * TILE_USIZE,
)
}
fn pt_to_coords(&self, grid: &PlaneGrid, pt: Point) -> Option<Point> {
let col = div_floor(pt.x() - self.left, TILE_ISIZE);
let row = div_floor(pt.y() - self.top, TILE_ISIZE);
let coords = Point::new(col, row);
if grid.contains_coords(coords) {
Some(coords)
} else {
None
}
}
fn draw_pipe_tip(
&self,
grid: &PlaneGrid,
pos: Point,
dir: Direction,
canvas: &mut Canvas,
) {
let obj = grid.objects().get(&pos).cloned();
let sprite_index = match (dir, obj) {
(Direction::West, Some(PlaneObj::Cross)) => 10,
(Direction::West, Some(obj)) if obj.is_node() => 13,
(Direction::West, _) => 0,
(Direction::East, Some(PlaneObj::Cross)) => 11,
(Direction::East, Some(obj)) if obj.is_node() => 15,
(Direction::East, _) => 2,
(Direction::South, Some(obj)) if obj.is_node() => 14,
(Direction::South, _) => 1,
(Direction::North, Some(obj)) if obj.is_node() => 16,
(Direction::North, _) => 3,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, pos * TILE_ISIZE);
}
}
impl Element<PlaneGrid, PlaneCmd> for PlaneGridView {
fn draw(&self, grid: &PlaneGrid, canvas: &mut Canvas) {
let mut canvas = canvas.subcanvas(self.rect(grid));
canvas.clear((64, 64, 64));
for row in 0..(grid.num_rows() as i32) {
for col in 0..(grid.num_cols() as i32) {
let coords = Point::new(col, row);
if let Some(&obj) = grid.objects().get(&coords) {
let sprite_index = match obj {
PlaneObj::Wall => 0,
PlaneObj::Cross => 1,
PlaneObj::PurpleNode => 2,
PlaneObj::RedNode => 3,
PlaneObj::GreenNode => 4,
PlaneObj::BlueNode => 5,
PlaneObj::GrayNode => 6,
};
let sprite = &self.obj_sprites[sprite_index];
canvas.draw_sprite(sprite, coords * TILE_ISIZE);
} else {
let pt = coords * TILE_ISIZE;
let rect = Rect::new(
pt.x() + 1,
pt.y() + 1,
TILE_USIZE - 2,
TILE_USIZE - 2,
);
canvas.draw_rect((72, 72, 72), rect);
}
}
}
for pipe in grid.pipes() {
debug_assert!(pipe.len() >= 2);
let mut start = pipe[0];
let mut next = pipe[1];
let mut dir = Direction::from_delta(next - start);
self.draw_pipe_tip(grid, start, dir, &mut canvas);
for index in 2..pipe.len() {
start = next;
next = pipe[index];
let prev_dir = dir;
dir = Direction::from_delta(next - start);
let sprite_index = match (prev_dir, dir) {
(Direction::East, Direction::North) => 6,
(Direction::East, Direction::South) => 7,
(Direction::West, Direction::North) => 5,
(Direction::West, Direction::South) => 4,
(Direction::East, _) | (Direction::West, _) => {
let obj = grid.objects().get(&start).cloned();
if obj == Some(PlaneObj::Cross) {
12
} else {
8
}
}
(Direction::North, Direction::East) => 4, | (Direction::North, Direction::West) => 7,
(Direction::South, Direction::East) => 5,
(Direction::South, Direction::West) => 6,
(Direction::North, _) | (Direction::South, _) => 9,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, start * TILE_ISIZE);
}
dir = Direction::from_delta(start - next);
self.draw_pipe_tip(grid, next, dir, &mut canvas);
}
for (&coords, &letter) in self.letters.iter() {
let pt = Point::new(
coords.x() * TILE_ISIZE + TILE_ISIZE / 2,
coords.y() * TILE_ISIZE + TILE_ISIZE / 2 + 4,
);
canvas.draw_char(&self.font, Align::Center, pt, letter);
}
}
fn handle_event(
&mut self,
event: &Event,
grid: &mut PlaneGrid,
) -> Action<PlaneCmd> {
match event {
&Event::MouseDown(pt) if self.rect(grid).contains_point(pt) => {
self.drag_from = self.pt_to_coords(grid, pt);
Action::ignore().and_stop()
}
&Event::MouseDrag(pt) => {
if let Some(coords1) = self.drag_from {
if let Some(coords2) = self.pt_to_coords(grid, pt) {
self.drag_from = Some(coords2);
if grid.toggle_pipe(coords1, coords2) {
self.changes.push((coords1, coords2));
return Action::redraw()
.and_return(PlaneCmd::Changed);
}
}
}
Action::ignore()
}
&Event::MouseUp => {
self.drag_from = None;
if self.changes.is_empty() {
Action::ignore()
} else {
let vec = mem::replace(&mut self.changes, Vec::new());
Action::redraw().and_return(PlaneCmd::PushUndo(vec))
}
}
_ => Action::ignore(),
}
}
}
// ========================================================================= // | random_line_split |
|
lib.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! A collection associating pair of keys (row and column) with a single value.
use std::hash::Hash;
use std::collections::HashMap;
use std::collections::hash_map::Keys;
/// Structure to hold double-indexed values
///
/// You can obviously use `HashMap<(Row,Col), Val>`, but this structure gives
/// you better access to all `Columns` in Specific `Row`. Namely you can get sub-hashmap
/// `HashMap<Col, Val>` for specific `Row`
#[derive(Default, Debug, PartialEq)]
pub struct Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
map: HashMap<Row, HashMap<Col, Val>>,
}
impl<Row, Col, Val> Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
/// Creates new Table
pub fn new() -> Self {
Table {
map: HashMap::new(),
}
}
/// Returns keys iterator for this Table.
pub fn keys(&self) -> Keys<Row, HashMap<Col, Val>> {
self.map.keys()
}
/// Removes all elements from this Table
pub fn clear(&mut self) {
self.map.clear();
}
/// Returns length of the Table (number of (row, col, val) tuples)
pub fn len(&self) -> usize {
self.map.values().fold(0, |acc, v| acc + v.len())
}
/// Check if there is any element in this Table
pub fn is_empty(&self) -> bool {
self.map.is_empty() || self.map.values().all(|v| v.is_empty())
}
/// Get mutable reference for single Table row.
pub fn row_mut(&mut self, row: &Row) -> Option<&mut HashMap<Col, Val>> {
self.map.get_mut(row)
}
/// Checks if row is defined for that table (note that even if defined it might be empty)
pub fn has_row(&self, row: &Row) -> bool {
self.map.contains_key(row)
}
/// Get immutable reference for single row in this Table
pub fn row(&self, row: &Row) -> Option<&HashMap<Col, Val>> {
self.map.get(row)
}
/// Get element in cell described by `(row, col)`
pub fn | (&self, row: &Row, col: &Col) -> Option<&Val> {
self.map.get(row).and_then(|r| r.get(col))
}
/// Remove value from specific cell
///
/// It will remove the row if it's the last value in it
pub fn remove(&mut self, row: &Row, col: &Col) -> Option<Val> {
let (val, is_empty) = {
let row_map = self.map.get_mut(row);
if let None = row_map {
return None;
}
let mut row_map = row_map.unwrap();
let val = row_map.remove(col);
(val, row_map.is_empty())
};
// Clean row
if is_empty {
self.map.remove(row);
}
val
}
/// Remove given row from Table if there are no values defined in it
///
/// When using `#row_mut` it may happen that all values from some row are drained.
/// Table however will not be aware that row is empty.
/// You can use this method to explicitly remove row entry from the Table.
pub fn clear_if_empty(&mut self, row: &Row) {
let is_empty = self.map.get(row).map_or(false, |m| m.is_empty());
if is_empty {
self.map.remove(row);
}
}
/// Inserts new value to specified cell
///
/// Returns previous value (if any)
pub fn insert(&mut self, row: Row, col: Col, val: Val) -> Option<Val> {
self.map.entry(row).or_insert_with(HashMap::new).insert(col, val)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn should_create_empty_table() {
// when
let table : Table<usize, usize, bool> = Table::new();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
}
#[test]
fn should_insert_elements_and_return_previous_if_any() {
// given
let mut table = Table::new();
// when
let r1 = table.insert(5, 4, true);
let r2 = table.insert(10, 4, true);
let r3 = table.insert(10, 10, true);
let r4 = table.insert(10, 10, false);
// then
assert!(r1.is_none());
assert!(r2.is_none());
assert!(r3.is_none());
assert!(r4.is_some());
assert!(!table.is_empty());
assert_eq!(r4.unwrap(), true);
assert_eq!(table.len(), 3);
}
#[test]
fn should_remove_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(!table.is_empty());
assert_eq!(table.len(), 1);
// when
let r = table.remove(&5, &4);
// then
assert!(table.is_empty());
assert_eq!(table.len(),0);
assert_eq!(r.unwrap(), true);
}
#[test]
fn should_return_none_if_trying_to_remove_non_existing_element() {
// given
let mut table : Table<usize, usize, usize> = Table::new();
assert!(table.is_empty());
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_none());
}
#[test]
fn should_clear_row_if_removing_last_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(table.has_row(&5));
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_some());
assert!(!table.has_row(&5));
}
#[test]
fn should_return_element_given_row_and_col() {
// given
let mut table = Table::new();
table.insert(1551, 1234, 123);
// when
let r1 = table.get(&1551, &1234);
let r2 = table.get(&5, &4);
// then
assert!(r1.is_some());
assert!(r2.is_none());
assert_eq!(r1.unwrap(), &123);
}
#[test]
fn should_clear_table() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
assert_eq!(table.len(), 3);
// when
table.clear();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
assert_eq!(table.has_row(&1), false);
assert_eq!(table.has_row(&2), false);
}
#[test]
fn should_return_mutable_row() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
// when
{
let mut row = table.row_mut(&1).unwrap();
row.remove(&1);
row.remove(&2);
}
assert!(table.has_row(&1));
table.clear_if_empty(&1);
// then
assert!(!table.has_row(&1));
assert_eq!(table.len(), 1);
}
}
| get | identifier_name |
lib.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! A collection associating pair of keys (row and column) with a single value.
use std::hash::Hash;
use std::collections::HashMap;
use std::collections::hash_map::Keys;
/// Structure to hold double-indexed values
///
/// You can obviously use `HashMap<(Row,Col), Val>`, but this structure gives
/// you better access to all `Columns` in Specific `Row`. Namely you can get sub-hashmap
/// `HashMap<Col, Val>` for specific `Row`
#[derive(Default, Debug, PartialEq)]
pub struct Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
map: HashMap<Row, HashMap<Col, Val>>,
}
impl<Row, Col, Val> Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
/// Creates new Table
pub fn new() -> Self {
Table {
map: HashMap::new(),
}
}
/// Returns keys iterator for this Table.
pub fn keys(&self) -> Keys<Row, HashMap<Col, Val>> {
self.map.keys()
}
/// Removes all elements from this Table
pub fn clear(&mut self) {
self.map.clear();
}
/// Returns length of the Table (number of (row, col, val) tuples)
pub fn len(&self) -> usize {
self.map.values().fold(0, |acc, v| acc + v.len())
}
/// Check if there is any element in this Table
pub fn is_empty(&self) -> bool {
self.map.is_empty() || self.map.values().all(|v| v.is_empty())
}
/// Get mutable reference for single Table row.
pub fn row_mut(&mut self, row: &Row) -> Option<&mut HashMap<Col, Val>> {
self.map.get_mut(row)
}
/// Checks if row is defined for that table (note that even if defined it might be empty)
pub fn has_row(&self, row: &Row) -> bool |
/// Get immutable reference for single row in this Table
pub fn row(&self, row: &Row) -> Option<&HashMap<Col, Val>> {
self.map.get(row)
}
/// Get element in cell described by `(row, col)`
pub fn get(&self, row: &Row, col: &Col) -> Option<&Val> {
self.map.get(row).and_then(|r| r.get(col))
}
/// Remove value from specific cell
///
/// It will remove the row if it's the last value in it
pub fn remove(&mut self, row: &Row, col: &Col) -> Option<Val> {
let (val, is_empty) = {
let row_map = self.map.get_mut(row);
if let None = row_map {
return None;
}
let mut row_map = row_map.unwrap();
let val = row_map.remove(col);
(val, row_map.is_empty())
};
// Clean row
if is_empty {
self.map.remove(row);
}
val
}
/// Remove given row from Table if there are no values defined in it
///
/// When using `#row_mut` it may happen that all values from some row are drained.
/// Table however will not be aware that row is empty.
/// You can use this method to explicitly remove row entry from the Table.
pub fn clear_if_empty(&mut self, row: &Row) {
let is_empty = self.map.get(row).map_or(false, |m| m.is_empty());
if is_empty {
self.map.remove(row);
}
}
/// Inserts new value to specified cell
///
/// Returns previous value (if any)
pub fn insert(&mut self, row: Row, col: Col, val: Val) -> Option<Val> {
self.map.entry(row).or_insert_with(HashMap::new).insert(col, val)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn should_create_empty_table() {
// when
let table : Table<usize, usize, bool> = Table::new();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
}
#[test]
fn should_insert_elements_and_return_previous_if_any() {
// given
let mut table = Table::new();
// when
let r1 = table.insert(5, 4, true);
let r2 = table.insert(10, 4, true);
let r3 = table.insert(10, 10, true);
let r4 = table.insert(10, 10, false);
// then
assert!(r1.is_none());
assert!(r2.is_none());
assert!(r3.is_none());
assert!(r4.is_some());
assert!(!table.is_empty());
assert_eq!(r4.unwrap(), true);
assert_eq!(table.len(), 3);
}
#[test]
fn should_remove_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(!table.is_empty());
assert_eq!(table.len(), 1);
// when
let r = table.remove(&5, &4);
// then
assert!(table.is_empty());
assert_eq!(table.len(),0);
assert_eq!(r.unwrap(), true);
}
#[test]
fn should_return_none_if_trying_to_remove_non_existing_element() {
// given
let mut table : Table<usize, usize, usize> = Table::new();
assert!(table.is_empty());
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_none());
}
#[test]
fn should_clear_row_if_removing_last_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(table.has_row(&5));
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_some());
assert!(!table.has_row(&5));
}
#[test]
fn should_return_element_given_row_and_col() {
// given
let mut table = Table::new();
table.insert(1551, 1234, 123);
// when
let r1 = table.get(&1551, &1234);
let r2 = table.get(&5, &4);
// then
assert!(r1.is_some());
assert!(r2.is_none());
assert_eq!(r1.unwrap(), &123);
}
#[test]
fn should_clear_table() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
assert_eq!(table.len(), 3);
// when
table.clear();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
assert_eq!(table.has_row(&1), false);
assert_eq!(table.has_row(&2), false);
}
#[test]
fn should_return_mutable_row() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
// when
{
let mut row = table.row_mut(&1).unwrap();
row.remove(&1);
row.remove(&2);
}
assert!(table.has_row(&1));
table.clear_if_empty(&1);
// then
assert!(!table.has_row(&1));
assert_eq!(table.len(), 1);
}
}
| {
self.map.contains_key(row)
} | identifier_body |
lib.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! A collection associating pair of keys (row and column) with a single value.
use std::hash::Hash;
use std::collections::HashMap;
use std::collections::hash_map::Keys;
/// Structure to hold double-indexed values
///
/// You can obviously use `HashMap<(Row,Col), Val>`, but this structure gives
/// you better access to all `Columns` in Specific `Row`. Namely you can get sub-hashmap
/// `HashMap<Col, Val>` for specific `Row`
#[derive(Default, Debug, PartialEq)]
pub struct Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
map: HashMap<Row, HashMap<Col, Val>>,
}
impl<Row, Col, Val> Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
/// Creates new Table
pub fn new() -> Self {
Table {
map: HashMap::new(),
}
}
/// Returns keys iterator for this Table.
pub fn keys(&self) -> Keys<Row, HashMap<Col, Val>> {
self.map.keys()
}
/// Removes all elements from this Table
pub fn clear(&mut self) {
self.map.clear();
}
/// Returns length of the Table (number of (row, col, val) tuples)
pub fn len(&self) -> usize {
self.map.values().fold(0, |acc, v| acc + v.len())
}
/// Check if there is any element in this Table
pub fn is_empty(&self) -> bool {
self.map.is_empty() || self.map.values().all(|v| v.is_empty())
}
/// Get mutable reference for single Table row.
pub fn row_mut(&mut self, row: &Row) -> Option<&mut HashMap<Col, Val>> {
self.map.get_mut(row)
}
/// Checks if row is defined for that table (note that even if defined it might be empty)
pub fn has_row(&self, row: &Row) -> bool {
self.map.contains_key(row)
}
/// Get immutable reference for single row in this Table
pub fn row(&self, row: &Row) -> Option<&HashMap<Col, Val>> {
self.map.get(row)
}
/// Get element in cell described by `(row, col)`
pub fn get(&self, row: &Row, col: &Col) -> Option<&Val> {
self.map.get(row).and_then(|r| r.get(col))
}
/// Remove value from specific cell
///
/// It will remove the row if it's the last value in it
pub fn remove(&mut self, row: &Row, col: &Col) -> Option<Val> {
let (val, is_empty) = {
let row_map = self.map.get_mut(row);
if let None = row_map {
return None;
}
let mut row_map = row_map.unwrap();
let val = row_map.remove(col);
(val, row_map.is_empty())
};
// Clean row
if is_empty {
self.map.remove(row);
}
val
}
/// Remove given row from Table if there are no values defined in it
///
/// When using `#row_mut` it may happen that all values from some row are drained.
/// Table however will not be aware that row is empty.
/// You can use this method to explicitly remove row entry from the Table.
pub fn clear_if_empty(&mut self, row: &Row) {
let is_empty = self.map.get(row).map_or(false, |m| m.is_empty());
if is_empty {
self.map.remove(row);
}
}
/// Inserts new value to specified cell
///
/// Returns previous value (if any)
pub fn insert(&mut self, row: Row, col: Col, val: Val) -> Option<Val> {
self.map.entry(row).or_insert_with(HashMap::new).insert(col, val)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn should_create_empty_table() {
// when
let table : Table<usize, usize, bool> = Table::new();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
}
#[test]
fn should_insert_elements_and_return_previous_if_any() {
// given
let mut table = Table::new();
// when
let r1 = table.insert(5, 4, true);
let r2 = table.insert(10, 4, true);
let r3 = table.insert(10, 10, true);
let r4 = table.insert(10, 10, false);
// then
assert!(r1.is_none());
assert!(r2.is_none());
assert!(r3.is_none());
assert!(r4.is_some());
assert!(!table.is_empty());
assert_eq!(r4.unwrap(), true);
assert_eq!(table.len(), 3);
}
#[test]
fn should_remove_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(!table.is_empty());
assert_eq!(table.len(), 1);
// when
let r = table.remove(&5, &4);
// then
assert!(table.is_empty());
assert_eq!(table.len(),0);
assert_eq!(r.unwrap(), true);
}
#[test]
fn should_return_none_if_trying_to_remove_non_existing_element() {
// given
let mut table : Table<usize, usize, usize> = Table::new();
assert!(table.is_empty());
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_none());
}
#[test]
fn should_clear_row_if_removing_last_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(table.has_row(&5));
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_some());
assert!(!table.has_row(&5));
}
#[test]
fn should_return_element_given_row_and_col() {
// given
let mut table = Table::new();
table.insert(1551, 1234, 123);
// when
let r1 = table.get(&1551, &1234);
let r2 = table.get(&5, &4);
// then
assert!(r1.is_some());
assert!(r2.is_none());
assert_eq!(r1.unwrap(), &123);
}
#[test]
fn should_clear_table() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
assert_eq!(table.len(), 3);
// when
table.clear();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
assert_eq!(table.has_row(&1), false);
assert_eq!(table.has_row(&2), false);
}
#[test]
fn should_return_mutable_row() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
// when
{
let mut row = table.row_mut(&1).unwrap();
row.remove(&1);
row.remove(&2);
}
assert!(table.has_row(&1)); | // then
assert!(!table.has_row(&1));
assert_eq!(table.len(), 1);
}
} | table.clear_if_empty(&1);
| random_line_split |
lib.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! A collection associating pair of keys (row and column) with a single value.
use std::hash::Hash;
use std::collections::HashMap;
use std::collections::hash_map::Keys;
/// Structure to hold double-indexed values
///
/// You can obviously use `HashMap<(Row,Col), Val>`, but this structure gives
/// you better access to all `Columns` in Specific `Row`. Namely you can get sub-hashmap
/// `HashMap<Col, Val>` for specific `Row`
#[derive(Default, Debug, PartialEq)]
pub struct Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
map: HashMap<Row, HashMap<Col, Val>>,
}
impl<Row, Col, Val> Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
/// Creates new Table
pub fn new() -> Self {
Table {
map: HashMap::new(),
}
}
/// Returns keys iterator for this Table.
pub fn keys(&self) -> Keys<Row, HashMap<Col, Val>> {
self.map.keys()
}
/// Removes all elements from this Table
pub fn clear(&mut self) {
self.map.clear();
}
/// Returns length of the Table (number of (row, col, val) tuples)
pub fn len(&self) -> usize {
self.map.values().fold(0, |acc, v| acc + v.len())
}
/// Check if there is any element in this Table
pub fn is_empty(&self) -> bool {
self.map.is_empty() || self.map.values().all(|v| v.is_empty())
}
/// Get mutable reference for single Table row.
pub fn row_mut(&mut self, row: &Row) -> Option<&mut HashMap<Col, Val>> {
self.map.get_mut(row)
}
/// Checks if row is defined for that table (note that even if defined it might be empty)
pub fn has_row(&self, row: &Row) -> bool {
self.map.contains_key(row)
}
/// Get immutable reference for single row in this Table
pub fn row(&self, row: &Row) -> Option<&HashMap<Col, Val>> {
self.map.get(row)
}
/// Get element in cell described by `(row, col)`
pub fn get(&self, row: &Row, col: &Col) -> Option<&Val> {
self.map.get(row).and_then(|r| r.get(col))
}
/// Remove value from specific cell
///
/// It will remove the row if it's the last value in it
pub fn remove(&mut self, row: &Row, col: &Col) -> Option<Val> {
let (val, is_empty) = {
let row_map = self.map.get_mut(row);
if let None = row_map {
return None;
}
let mut row_map = row_map.unwrap();
let val = row_map.remove(col);
(val, row_map.is_empty())
};
// Clean row
if is_empty |
val
}
/// Remove given row from Table if there are no values defined in it
///
/// When using `#row_mut` it may happen that all values from some row are drained.
/// Table however will not be aware that row is empty.
/// You can use this method to explicitly remove row entry from the Table.
pub fn clear_if_empty(&mut self, row: &Row) {
let is_empty = self.map.get(row).map_or(false, |m| m.is_empty());
if is_empty {
self.map.remove(row);
}
}
/// Inserts new value to specified cell
///
/// Returns previous value (if any)
pub fn insert(&mut self, row: Row, col: Col, val: Val) -> Option<Val> {
self.map.entry(row).or_insert_with(HashMap::new).insert(col, val)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn should_create_empty_table() {
// when
let table : Table<usize, usize, bool> = Table::new();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
}
#[test]
fn should_insert_elements_and_return_previous_if_any() {
// given
let mut table = Table::new();
// when
let r1 = table.insert(5, 4, true);
let r2 = table.insert(10, 4, true);
let r3 = table.insert(10, 10, true);
let r4 = table.insert(10, 10, false);
// then
assert!(r1.is_none());
assert!(r2.is_none());
assert!(r3.is_none());
assert!(r4.is_some());
assert!(!table.is_empty());
assert_eq!(r4.unwrap(), true);
assert_eq!(table.len(), 3);
}
#[test]
fn should_remove_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(!table.is_empty());
assert_eq!(table.len(), 1);
// when
let r = table.remove(&5, &4);
// then
assert!(table.is_empty());
assert_eq!(table.len(),0);
assert_eq!(r.unwrap(), true);
}
#[test]
fn should_return_none_if_trying_to_remove_non_existing_element() {
// given
let mut table : Table<usize, usize, usize> = Table::new();
assert!(table.is_empty());
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_none());
}
#[test]
fn should_clear_row_if_removing_last_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(table.has_row(&5));
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_some());
assert!(!table.has_row(&5));
}
#[test]
fn should_return_element_given_row_and_col() {
// given
let mut table = Table::new();
table.insert(1551, 1234, 123);
// when
let r1 = table.get(&1551, &1234);
let r2 = table.get(&5, &4);
// then
assert!(r1.is_some());
assert!(r2.is_none());
assert_eq!(r1.unwrap(), &123);
}
#[test]
fn should_clear_table() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
assert_eq!(table.len(), 3);
// when
table.clear();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
assert_eq!(table.has_row(&1), false);
assert_eq!(table.has_row(&2), false);
}
#[test]
fn should_return_mutable_row() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
// when
{
let mut row = table.row_mut(&1).unwrap();
row.remove(&1);
row.remove(&2);
}
assert!(table.has_row(&1));
table.clear_if_empty(&1);
// then
assert!(!table.has_row(&1));
assert_eq!(table.len(), 1);
}
}
| {
self.map.remove(row);
} | conditional_block |
paged_results.rs | use super::{ControlParser, MakeCritical, RawControl};
use bytes::BytesMut;
use lber::common::TagClass;
use lber::IResult;
use lber::parse::{parse_uint, parse_tag};
use lber::structures::{ASNTag, Integer, OctetString, Sequence, Tag};
use lber::universal::Types;
use lber::write;
/// Paged Results control ([RFC 2696](https://tools.ietf.org/html/rfc2696)).
///
/// This struct can be used both for requests and responses, although `size`
/// means different things in each case.
#[derive(Clone, Debug)]
pub struct PagedResults {
/// For requests, desired page size. For responses, a server's estimate
/// of the result set size, if non-zero.
pub size: i32,
/// Paging cookie.
pub cookie: Vec<u8>,
}
pub const PAGED_RESULTS_OID: &'static str = "1.2.840.113556.1.4.319";
impl MakeCritical for PagedResults { }
impl From<PagedResults> for RawControl {
fn from(pr: PagedResults) -> RawControl | val: Some(Vec::from(&buf[..])),
}
}
}
impl ControlParser for PagedResults {
fn parse(val: &[u8]) -> PagedResults {
let mut pr_comps = match parse_tag(val) {
IResult::Done(_, tag) => tag,
_ => panic!("failed to parse paged results value components"),
}.expect_constructed().expect("paged results components").into_iter();
let size = match parse_uint(pr_comps.next().expect("element")
.match_class(TagClass::Universal)
.and_then(|t| t.match_id(Types::Integer as u64))
.and_then(|t| t.expect_primitive()).expect("paged results size")
.as_slice()) {
IResult::Done(_, size) => size as i32,
_ => panic!("failed to parse size"),
};
let cookie = pr_comps.next().expect("element").expect_primitive().expect("octet string");
PagedResults { size: size, cookie: cookie }
}
}
| {
let cookie_len = pr.cookie.len();
let cval = Tag::Sequence(Sequence {
inner: vec![
Tag::Integer(Integer {
inner: pr.size as i64,
.. Default::default()
}),
Tag::OctetString(OctetString {
inner: pr.cookie,
.. Default::default()
}),
],
.. Default::default()
}).into_structure();
let mut buf = BytesMut::with_capacity(cookie_len + 16);
write::encode_into(&mut buf, cval).expect("encoded");
RawControl {
ctype: PAGED_RESULTS_OID.to_owned(),
crit: false, | identifier_body |
paged_results.rs | use super::{ControlParser, MakeCritical, RawControl};
use bytes::BytesMut;
use lber::common::TagClass;
use lber::IResult;
use lber::parse::{parse_uint, parse_tag};
use lber::structures::{ASNTag, Integer, OctetString, Sequence, Tag};
use lber::universal::Types;
use lber::write;
/// Paged Results control ([RFC 2696](https://tools.ietf.org/html/rfc2696)).
///
/// This struct can be used both for requests and responses, although `size`
/// means different things in each case.
#[derive(Clone, Debug)]
pub struct PagedResults {
/// For requests, desired page size. For responses, a server's estimate
/// of the result set size, if non-zero.
pub size: i32,
/// Paging cookie.
pub cookie: Vec<u8>,
}
pub const PAGED_RESULTS_OID: &'static str = "1.2.840.113556.1.4.319";
| impl From<PagedResults> for RawControl {
fn from(pr: PagedResults) -> RawControl {
let cookie_len = pr.cookie.len();
let cval = Tag::Sequence(Sequence {
inner: vec![
Tag::Integer(Integer {
inner: pr.size as i64,
.. Default::default()
}),
Tag::OctetString(OctetString {
inner: pr.cookie,
.. Default::default()
}),
],
.. Default::default()
}).into_structure();
let mut buf = BytesMut::with_capacity(cookie_len + 16);
write::encode_into(&mut buf, cval).expect("encoded");
RawControl {
ctype: PAGED_RESULTS_OID.to_owned(),
crit: false,
val: Some(Vec::from(&buf[..])),
}
}
}
impl ControlParser for PagedResults {
fn parse(val: &[u8]) -> PagedResults {
let mut pr_comps = match parse_tag(val) {
IResult::Done(_, tag) => tag,
_ => panic!("failed to parse paged results value components"),
}.expect_constructed().expect("paged results components").into_iter();
let size = match parse_uint(pr_comps.next().expect("element")
.match_class(TagClass::Universal)
.and_then(|t| t.match_id(Types::Integer as u64))
.and_then(|t| t.expect_primitive()).expect("paged results size")
.as_slice()) {
IResult::Done(_, size) => size as i32,
_ => panic!("failed to parse size"),
};
let cookie = pr_comps.next().expect("element").expect_primitive().expect("octet string");
PagedResults { size: size, cookie: cookie }
}
} | impl MakeCritical for PagedResults { }
| random_line_split |
paged_results.rs | use super::{ControlParser, MakeCritical, RawControl};
use bytes::BytesMut;
use lber::common::TagClass;
use lber::IResult;
use lber::parse::{parse_uint, parse_tag};
use lber::structures::{ASNTag, Integer, OctetString, Sequence, Tag};
use lber::universal::Types;
use lber::write;
/// Paged Results control ([RFC 2696](https://tools.ietf.org/html/rfc2696)).
///
/// This struct can be used both for requests and responses, although `size`
/// means different things in each case.
#[derive(Clone, Debug)]
pub struct | {
/// For requests, desired page size. For responses, a server's estimate
/// of the result set size, if non-zero.
pub size: i32,
/// Paging cookie.
pub cookie: Vec<u8>,
}
pub const PAGED_RESULTS_OID: &'static str = "1.2.840.113556.1.4.319";
impl MakeCritical for PagedResults { }
impl From<PagedResults> for RawControl {
fn from(pr: PagedResults) -> RawControl {
let cookie_len = pr.cookie.len();
let cval = Tag::Sequence(Sequence {
inner: vec![
Tag::Integer(Integer {
inner: pr.size as i64,
.. Default::default()
}),
Tag::OctetString(OctetString {
inner: pr.cookie,
.. Default::default()
}),
],
.. Default::default()
}).into_structure();
let mut buf = BytesMut::with_capacity(cookie_len + 16);
write::encode_into(&mut buf, cval).expect("encoded");
RawControl {
ctype: PAGED_RESULTS_OID.to_owned(),
crit: false,
val: Some(Vec::from(&buf[..])),
}
}
}
impl ControlParser for PagedResults {
fn parse(val: &[u8]) -> PagedResults {
let mut pr_comps = match parse_tag(val) {
IResult::Done(_, tag) => tag,
_ => panic!("failed to parse paged results value components"),
}.expect_constructed().expect("paged results components").into_iter();
let size = match parse_uint(pr_comps.next().expect("element")
.match_class(TagClass::Universal)
.and_then(|t| t.match_id(Types::Integer as u64))
.and_then(|t| t.expect_primitive()).expect("paged results size")
.as_slice()) {
IResult::Done(_, size) => size as i32,
_ => panic!("failed to parse size"),
};
let cookie = pr_comps.next().expect("element").expect_primitive().expect("octet string");
PagedResults { size: size, cookie: cookie }
}
}
| PagedResults | identifier_name |
history.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use abomonation_derive::Abomonation;
use anyhow::Error;
use filenodes::{FilenodeInfo, FilenodeInfoCached};
#[derive(Abomonation, Clone)]
pub struct FilenodeHistoryCached {
// TODO: We could store this more efficiently by deduplicating filenode IDs.
history: Vec<FilenodeInfoCached>,
}
impl FilenodeHistoryCached {
pub fn into_filenode_info(self) -> Result<Vec<FilenodeInfo>, Error> {
self.history.into_iter().map(|c| c.try_into()).collect()
}
| let history = filenodes.into_iter().map(|f| f.into()).collect::<Vec<_>>();
Self { history }
}
} | pub fn from_filenodes(filenodes: Vec<FilenodeInfo>) -> Self { | random_line_split |
history.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use abomonation_derive::Abomonation;
use anyhow::Error;
use filenodes::{FilenodeInfo, FilenodeInfoCached};
#[derive(Abomonation, Clone)]
pub struct FilenodeHistoryCached {
// TODO: We could store this more efficiently by deduplicating filenode IDs.
history: Vec<FilenodeInfoCached>,
}
impl FilenodeHistoryCached {
pub fn | (self) -> Result<Vec<FilenodeInfo>, Error> {
self.history.into_iter().map(|c| c.try_into()).collect()
}
pub fn from_filenodes(filenodes: Vec<FilenodeInfo>) -> Self {
let history = filenodes.into_iter().map(|f| f.into()).collect::<Vec<_>>();
Self { history }
}
}
| into_filenode_info | identifier_name |
read_all.rs | use std::borrow::Cow;
use std::convert::TryInto;
use raw::client_messages;
use raw::client_messages::mod_ReadAllEventsCompleted::ReadAllResult;
use LogPosition;
/// Successful response to `Message::ReadAllEvents`.
#[derive(Debug, Clone, PartialEq)]
pub struct ReadAllCompleted<'a> {
/// Position of the commit of the current prepare
pub commit_position: LogPosition,
/// Position of the current prepare
pub prepare_position: LogPosition,
/// The read events, with position metadata
pub events: Vec<ResolvedEvent<'a>>,
/// For paging: next commit position
pub next_commit_position: Option<LogPosition>,
/// For paging: next prepare position
pub next_prepare_position: Option<LogPosition>,
}
/// Read event in `ReadAllSuccess` response
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedEvent<'a> {
/// The read event
pub event: client_messages::EventRecord<'a>,
/// Possible linking event
pub link: Option<client_messages::EventRecord<'a>>,
/// Position where this events transaction is commited
pub commit_position: LogPosition, | impl<'a> From<client_messages::ResolvedEvent<'a>> for ResolvedEvent<'a> {
fn from(e: client_messages::ResolvedEvent<'a>) -> ResolvedEvent<'a> {
ResolvedEvent {
event: e.event.into(),
link: e.link.into(),
commit_position: e.commit_position.try_into().unwrap(),
prepare_position: e.prepare_position.try_into().unwrap()
}
}
}
/// Failure cases of wire enum `ReadAllResult`.
#[derive(Debug, Clone, PartialEq)]
pub enum ReadAllError<'a> {
/// Unknown when this happens,
NotModified,
/// Other error
Error(Option<Cow<'a, str>>),
/// Access was denied (no credentials provided or insufficient permissions)
AccessDenied
}
impl<'a> From<(ReadAllResult, Option<Cow<'a, str>>)> for ReadAllError<'a> {
fn from((r, msg): (ReadAllResult, Option<Cow<'a, str>>)) -> ReadAllError<'a> {
use self::ReadAllResult::*;
match r {
Success => unreachable!(),
NotModified => ReadAllError::NotModified,
Error => ReadAllError::Error(msg),
AccessDenied => ReadAllError::AccessDenied,
}
}
} | /// Position where this event is stored
pub prepare_position: LogPosition,
}
| random_line_split |
read_all.rs | use std::borrow::Cow;
use std::convert::TryInto;
use raw::client_messages;
use raw::client_messages::mod_ReadAllEventsCompleted::ReadAllResult;
use LogPosition;
/// Successful response to `Message::ReadAllEvents`.
#[derive(Debug, Clone, PartialEq)]
pub struct ReadAllCompleted<'a> {
/// Position of the commit of the current prepare
pub commit_position: LogPosition,
/// Position of the current prepare
pub prepare_position: LogPosition,
/// The read events, with position metadata
pub events: Vec<ResolvedEvent<'a>>,
/// For paging: next commit position
pub next_commit_position: Option<LogPosition>,
/// For paging: next prepare position
pub next_prepare_position: Option<LogPosition>,
}
/// Read event in `ReadAllSuccess` response
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedEvent<'a> {
/// The read event
pub event: client_messages::EventRecord<'a>,
/// Possible linking event
pub link: Option<client_messages::EventRecord<'a>>,
/// Position where this events transaction is commited
pub commit_position: LogPosition,
/// Position where this event is stored
pub prepare_position: LogPosition,
}
impl<'a> From<client_messages::ResolvedEvent<'a>> for ResolvedEvent<'a> {
fn from(e: client_messages::ResolvedEvent<'a>) -> ResolvedEvent<'a> {
ResolvedEvent {
event: e.event.into(),
link: e.link.into(),
commit_position: e.commit_position.try_into().unwrap(),
prepare_position: e.prepare_position.try_into().unwrap()
}
}
}
/// Failure cases of wire enum `ReadAllResult`.
#[derive(Debug, Clone, PartialEq)]
pub enum | <'a> {
/// Unknown when this happens,
NotModified,
/// Other error
Error(Option<Cow<'a, str>>),
/// Access was denied (no credentials provided or insufficient permissions)
AccessDenied
}
impl<'a> From<(ReadAllResult, Option<Cow<'a, str>>)> for ReadAllError<'a> {
fn from((r, msg): (ReadAllResult, Option<Cow<'a, str>>)) -> ReadAllError<'a> {
use self::ReadAllResult::*;
match r {
Success => unreachable!(),
NotModified => ReadAllError::NotModified,
Error => ReadAllError::Error(msg),
AccessDenied => ReadAllError::AccessDenied,
}
}
}
| ReadAllError | identifier_name |
tex2.rs |
use std::io::{self, Write};
use image;
use image::GenericImage;
use nom::{le_u8, le_u32};
use byteorder::{LittleEndian, WriteBytesExt};
named!(pub tex2_header<(u32, u32, u8)>,
do_parse!(
tag!("\x11\x40") >> //.@, the magic number for the format
height: le_u32 >>
width: le_u32 >>
mipmaps: le_u8 >>
(height, width, mipmaps)
)
);
named!(pub tex2_pixel<(u8, u8, u8, u8)>,
tuple!(
le_u8,
le_u8,
le_u8,
le_u8
)
);
named!(pub tex2_image<DDTex2Image>,
do_parse!(
header: tex2_header >>
pixels: count!(tex2_pixel, calc_offset(header.0, header.1, (header.2 as u32)+1) as usize) >>
(DDTex2Image {
mipmap_levels: header.2,
mipmap_current: 0,
height: header.0,
width: header.1,
pixels: pixels
})
)
);
pub struct DDTex2Image {
pub mipmap_levels: u8,
mipmap_current: u8,
pub height: u32,
pub width: u32,
pub pixels: Vec<(u8, u8, u8, u8)>
}
impl DDTex2Image {
pub fn new(width: u32, height: u32) -> Self {
DDTex2Image {
mipmap_levels: 0,
mipmap_current: 0,
height: height,
width: width,
pixels: vec![(0, 0, 0, 0); (height*width) as usize]
}
}
pub fn save(&self, mut dst: &mut Write) -> io::Result<()> {
dst.write_u8(0x11)?;
dst.write_u8(0x40)?;
dst.write_u32::<LittleEndian>(self.height)?;
dst.write_u32::<LittleEndian>(self.width)?;
dst.write_u8(self.mipmap_levels)?;
for pixel in self.pixels.iter() {
dst.write_u8(pixel.0)?;
dst.write_u8(pixel.1)?;
dst.write_u8(pixel.2)?;
dst.write_u8(pixel.3)?;
}
Ok(())
}
pub fn set_mipmap(&mut self, new: u8) {
if new!= 0 && (!self.height.is_power_of_two() ||!self.width.is_power_of_two()) {
panic!("DDTex2Image {}x{}: can't do mipmap levels on non-power-of-two!", self.width, self.height);
}
self.mipmap_current = new;
}
pub fn cur_width(&self) -> u32 {
self.width >> self.mipmap_current
}
pub fn cur_height(&self) -> u32 {
self.height >> self.mipmap_current
}
pub fn | (&self, x: u32, y: u32) -> usize {
(calc_offset(self.height, self.width, (self.mipmap_current) as u32)
+ ((self.cur_width()*y) + x)) as usize
}
pub fn pixel(&self, x: u32, y: u32) -> (u8, u8, u8, u8) {
match self.pixels.get(self.pos(x, y)) {
Some(p) => *p,
None => (0xFF, 0xFF, 0xFF, 0xFF)
}
}
}
#[allow(unused_variables)]
impl GenericImage for DDTex2Image {
type Pixel = image::Rgba<u8>;
fn dimensions(&self) -> (u32, u32) {
(self.cur_width(), self.cur_height())
}
fn bounds(&self) -> (u32, u32, u32, u32) {
(0, 0, self.cur_width(), self.cur_height())
}
fn get_pixel(&self, x: u32, y: u32) -> Self::Pixel {
let p = self.pixel(x, y);
image::Rgba([p.0, p.1, p.2, p.3])
}
fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut Self::Pixel {
unimplemented!()
}
fn put_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
let pos = self.pos(x, y);
self.pixels[pos] = (pixel[0], pixel[1], pixel[2], pixel[3]);
}
fn blend_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
unimplemented!()
}
}
//12:36:48 AM <ubsan> zekesonxx: lemme think about it
//12:36:51 AM <ubsan> I have an idea
//12:37:24 AM <zekesonxx> ubsan: shoot
//12:37:42 AM <ubsan> zekesonxx: alright, so the function definition would be something like
//12:37:57 AM <ubsan> fn foo(x: usize, y: usize, n: u32) -> usize {
//12:39:51 AM <ubsan> let (x, y) = (x.trailing_zeroes(), y.trailing_zeroes()); (0..n).fold(1, |acc, n| acc += 1 << (x - n) * 1 << (y - n))
//12:39:55 AM <ubsan> something like this ^?
//12:52:55 AM <zekesonxx> ubsan: little bit of reworking needed but looks good. Thanks for the help.
//12:53:01 AM <ubsan> zekesonxx: yep!
//12:53:10 AM * ubsan has done some assembly in the past :P
fn calc_offset(height: u32, width: u32, cur_mip: u32) -> u32 {
let (x, y) = (height.trailing_zeros(), width.trailing_zeros());
(0..cur_mip).fold(0u32, |acc, n| acc + (1 << (x - n) * 1 << (y - n)))
} | pos | identifier_name |
tex2.rs |
use std::io::{self, Write};
use image;
use image::GenericImage;
use nom::{le_u8, le_u32};
use byteorder::{LittleEndian, WriteBytesExt};
named!(pub tex2_header<(u32, u32, u8)>,
do_parse!(
tag!("\x11\x40") >> //.@, the magic number for the format
height: le_u32 >>
width: le_u32 >>
mipmaps: le_u8 >>
(height, width, mipmaps)
)
);
named!(pub tex2_pixel<(u8, u8, u8, u8)>,
tuple!(
le_u8,
le_u8,
le_u8,
le_u8
)
);
named!(pub tex2_image<DDTex2Image>,
do_parse!(
header: tex2_header >>
pixels: count!(tex2_pixel, calc_offset(header.0, header.1, (header.2 as u32)+1) as usize) >>
(DDTex2Image {
mipmap_levels: header.2,
mipmap_current: 0,
height: header.0,
width: header.1,
pixels: pixels
})
)
);
pub struct DDTex2Image {
pub mipmap_levels: u8,
mipmap_current: u8,
pub height: u32,
pub width: u32,
pub pixels: Vec<(u8, u8, u8, u8)>
}
impl DDTex2Image {
pub fn new(width: u32, height: u32) -> Self {
DDTex2Image {
mipmap_levels: 0,
mipmap_current: 0,
height: height,
width: width,
pixels: vec![(0, 0, 0, 0); (height*width) as usize]
}
}
pub fn save(&self, mut dst: &mut Write) -> io::Result<()> {
dst.write_u8(0x11)?;
dst.write_u8(0x40)?;
dst.write_u32::<LittleEndian>(self.height)?;
dst.write_u32::<LittleEndian>(self.width)?;
dst.write_u8(self.mipmap_levels)?;
for pixel in self.pixels.iter() {
dst.write_u8(pixel.0)?;
dst.write_u8(pixel.1)?;
dst.write_u8(pixel.2)?;
dst.write_u8(pixel.3)?;
}
Ok(())
}
pub fn set_mipmap(&mut self, new: u8) {
if new!= 0 && (!self.height.is_power_of_two() ||!self.width.is_power_of_two()) {
panic!("DDTex2Image {}x{}: can't do mipmap levels on non-power-of-two!", self.width, self.height);
}
self.mipmap_current = new;
}
pub fn cur_width(&self) -> u32 {
self.width >> self.mipmap_current
}
pub fn cur_height(&self) -> u32 {
self.height >> self.mipmap_current
}
pub fn pos(&self, x: u32, y: u32) -> usize {
(calc_offset(self.height, self.width, (self.mipmap_current) as u32)
+ ((self.cur_width()*y) + x)) as usize
}
pub fn pixel(&self, x: u32, y: u32) -> (u8, u8, u8, u8) {
match self.pixels.get(self.pos(x, y)) {
Some(p) => *p,
None => (0xFF, 0xFF, 0xFF, 0xFF)
}
}
}
#[allow(unused_variables)]
impl GenericImage for DDTex2Image {
type Pixel = image::Rgba<u8>;
fn dimensions(&self) -> (u32, u32) {
(self.cur_width(), self.cur_height())
}
fn bounds(&self) -> (u32, u32, u32, u32) {
(0, 0, self.cur_width(), self.cur_height())
}
fn get_pixel(&self, x: u32, y: u32) -> Self::Pixel {
let p = self.pixel(x, y);
image::Rgba([p.0, p.1, p.2, p.3])
}
fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut Self::Pixel {
unimplemented!()
}
fn put_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) |
fn blend_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
unimplemented!()
}
}
//12:36:48 AM <ubsan> zekesonxx: lemme think about it
//12:36:51 AM <ubsan> I have an idea
//12:37:24 AM <zekesonxx> ubsan: shoot
//12:37:42 AM <ubsan> zekesonxx: alright, so the function definition would be something like
//12:37:57 AM <ubsan> fn foo(x: usize, y: usize, n: u32) -> usize {
//12:39:51 AM <ubsan> let (x, y) = (x.trailing_zeroes(), y.trailing_zeroes()); (0..n).fold(1, |acc, n| acc += 1 << (x - n) * 1 << (y - n))
//12:39:55 AM <ubsan> something like this ^?
//12:52:55 AM <zekesonxx> ubsan: little bit of reworking needed but looks good. Thanks for the help.
//12:53:01 AM <ubsan> zekesonxx: yep!
//12:53:10 AM * ubsan has done some assembly in the past :P
fn calc_offset(height: u32, width: u32, cur_mip: u32) -> u32 {
let (x, y) = (height.trailing_zeros(), width.trailing_zeros());
(0..cur_mip).fold(0u32, |acc, n| acc + (1 << (x - n) * 1 << (y - n)))
} | {
let pos = self.pos(x, y);
self.pixels[pos] = (pixel[0], pixel[1], pixel[2], pixel[3]);
} | identifier_body |
tex2.rs | use std::io::{self, Write};
use image;
use image::GenericImage;
use nom::{le_u8, le_u32};
use byteorder::{LittleEndian, WriteBytesExt};
named!(pub tex2_header<(u32, u32, u8)>,
do_parse!(
tag!("\x11\x40") >> //.@, the magic number for the format
height: le_u32 >>
width: le_u32 >>
mipmaps: le_u8 >>
(height, width, mipmaps)
)
);
named!(pub tex2_pixel<(u8, u8, u8, u8)>,
tuple!(
le_u8,
le_u8,
le_u8,
le_u8
)
);
named!(pub tex2_image<DDTex2Image>,
do_parse!(
header: tex2_header >>
pixels: count!(tex2_pixel, calc_offset(header.0, header.1, (header.2 as u32)+1) as usize) >>
(DDTex2Image {
mipmap_levels: header.2,
mipmap_current: 0,
height: header.0,
width: header.1,
pixels: pixels
})
)
);
pub struct DDTex2Image {
pub mipmap_levels: u8,
mipmap_current: u8,
pub height: u32,
pub width: u32,
pub pixels: Vec<(u8, u8, u8, u8)>
}
impl DDTex2Image {
pub fn new(width: u32, height: u32) -> Self {
DDTex2Image {
mipmap_levels: 0,
mipmap_current: 0,
height: height,
width: width,
pixels: vec![(0, 0, 0, 0); (height*width) as usize]
}
}
pub fn save(&self, mut dst: &mut Write) -> io::Result<()> {
dst.write_u8(0x11)?;
dst.write_u8(0x40)?;
dst.write_u32::<LittleEndian>(self.height)?;
dst.write_u32::<LittleEndian>(self.width)?;
dst.write_u8(self.mipmap_levels)?;
for pixel in self.pixels.iter() {
dst.write_u8(pixel.0)?;
dst.write_u8(pixel.1)?;
dst.write_u8(pixel.2)?;
dst.write_u8(pixel.3)?;
}
Ok(())
}
pub fn set_mipmap(&mut self, new: u8) {
if new!= 0 && (!self.height.is_power_of_two() ||!self.width.is_power_of_two()) {
panic!("DDTex2Image {}x{}: can't do mipmap levels on non-power-of-two!", self.width, self.height);
}
self.mipmap_current = new;
}
pub fn cur_width(&self) -> u32 {
self.width >> self.mipmap_current
}
pub fn cur_height(&self) -> u32 {
self.height >> self.mipmap_current
}
pub fn pos(&self, x: u32, y: u32) -> usize {
(calc_offset(self.height, self.width, (self.mipmap_current) as u32)
+ ((self.cur_width()*y) + x)) as usize
}
pub fn pixel(&self, x: u32, y: u32) -> (u8, u8, u8, u8) {
match self.pixels.get(self.pos(x, y)) {
Some(p) => *p,
None => (0xFF, 0xFF, 0xFF, 0xFF)
}
}
}
#[allow(unused_variables)]
impl GenericImage for DDTex2Image {
type Pixel = image::Rgba<u8>;
fn dimensions(&self) -> (u32, u32) { | }
fn get_pixel(&self, x: u32, y: u32) -> Self::Pixel {
let p = self.pixel(x, y);
image::Rgba([p.0, p.1, p.2, p.3])
}
fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut Self::Pixel {
unimplemented!()
}
fn put_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
let pos = self.pos(x, y);
self.pixels[pos] = (pixel[0], pixel[1], pixel[2], pixel[3]);
}
fn blend_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
unimplemented!()
}
}
//12:36:48 AM <ubsan> zekesonxx: lemme think about it
//12:36:51 AM <ubsan> I have an idea
//12:37:24 AM <zekesonxx> ubsan: shoot
//12:37:42 AM <ubsan> zekesonxx: alright, so the function definition would be something like
//12:37:57 AM <ubsan> fn foo(x: usize, y: usize, n: u32) -> usize {
//12:39:51 AM <ubsan> let (x, y) = (x.trailing_zeroes(), y.trailing_zeroes()); (0..n).fold(1, |acc, n| acc += 1 << (x - n) * 1 << (y - n))
//12:39:55 AM <ubsan> something like this ^?
//12:52:55 AM <zekesonxx> ubsan: little bit of reworking needed but looks good. Thanks for the help.
//12:53:01 AM <ubsan> zekesonxx: yep!
//12:53:10 AM * ubsan has done some assembly in the past :P
fn calc_offset(height: u32, width: u32, cur_mip: u32) -> u32 {
let (x, y) = (height.trailing_zeros(), width.trailing_zeros());
(0..cur_mip).fold(0u32, |acc, n| acc + (1 << (x - n) * 1 << (y - n)))
} | (self.cur_width(), self.cur_height())
}
fn bounds(&self) -> (u32, u32, u32, u32) {
(0, 0, self.cur_width(), self.cur_height()) | random_line_split |
messageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEventBinding;
use dom::bindings::codegen::Bindings::MessageEventBinding::MessageEventMethods;
use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::event::Event;
use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use js::jsapi::{HandleValue, Heap, JSContext};
use js::jsval::JSVal;
use servo_atoms::Atom;
#[dom_struct]
pub struct MessageEvent {
event: Event,
data: Heap<JSVal>,
origin: DOMString,
lastEventId: DOMString,
}
impl MessageEvent {
pub fn new_uninitialized(global: &GlobalScope) -> Root<MessageEvent> {
MessageEvent::new_initialized(global,
HandleValue::undefined(),
DOMString::new(),
DOMString::new())
}
pub fn new_initialized(global: &GlobalScope,
data: HandleValue,
origin: DOMString,
lastEventId: DOMString) -> Root<MessageEvent> {
let ev = box MessageEvent {
event: Event::new_inherited(),
data: Heap::new(data.get()),
origin: origin,
lastEventId: lastEventId,
};
reflect_dom_object(ev, global, MessageEventBinding::Wrap)
}
pub fn new(global: &GlobalScope, type_: Atom,
bubbles: bool, cancelable: bool,
data: HandleValue, origin: DOMString, lastEventId: DOMString)
-> Root<MessageEvent> {
let ev = MessageEvent::new_initialized(global, data, origin, lastEventId);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles, cancelable);
}
ev
}
pub fn Constructor(global: &GlobalScope,
type_: DOMString,
init: &MessageEventBinding::MessageEventInit)
-> Fallible<Root<MessageEvent>> {
// Dictionaries need to be rooted
// https://github.com/servo/servo/issues/6381
rooted!(in(global.get_cx()) let data = init.data);
let ev = MessageEvent::new(global,
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
data.handle(),
init.origin.clone(),
init.lastEventId.clone());
Ok(ev)
}
}
impl MessageEvent {
pub fn dispatch_jsval(target: &EventTarget,
scope: &GlobalScope,
message: HandleValue) {
let messageevent = MessageEvent::new(
scope, | false,
false,
message,
DOMString::new(),
DOMString::new());
messageevent.upcast::<Event>().fire(target);
}
}
impl MessageEventMethods for MessageEvent {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-messageevent-data
unsafe fn Data(&self, _cx: *mut JSContext) -> JSVal {
self.data.get()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-origin
fn Origin(&self) -> DOMString {
self.origin.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid
fn LastEventId(&self) -> DOMString {
self.lastEventId.clone()
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
} | atom!("message"), | random_line_split |
messageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEventBinding;
use dom::bindings::codegen::Bindings::MessageEventBinding::MessageEventMethods;
use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::event::Event;
use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use js::jsapi::{HandleValue, Heap, JSContext};
use js::jsval::JSVal;
use servo_atoms::Atom;
#[dom_struct]
pub struct MessageEvent {
event: Event,
data: Heap<JSVal>,
origin: DOMString,
lastEventId: DOMString,
}
impl MessageEvent {
pub fn new_uninitialized(global: &GlobalScope) -> Root<MessageEvent> {
MessageEvent::new_initialized(global,
HandleValue::undefined(),
DOMString::new(),
DOMString::new())
}
pub fn | (global: &GlobalScope,
data: HandleValue,
origin: DOMString,
lastEventId: DOMString) -> Root<MessageEvent> {
let ev = box MessageEvent {
event: Event::new_inherited(),
data: Heap::new(data.get()),
origin: origin,
lastEventId: lastEventId,
};
reflect_dom_object(ev, global, MessageEventBinding::Wrap)
}
pub fn new(global: &GlobalScope, type_: Atom,
bubbles: bool, cancelable: bool,
data: HandleValue, origin: DOMString, lastEventId: DOMString)
-> Root<MessageEvent> {
let ev = MessageEvent::new_initialized(global, data, origin, lastEventId);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles, cancelable);
}
ev
}
pub fn Constructor(global: &GlobalScope,
type_: DOMString,
init: &MessageEventBinding::MessageEventInit)
-> Fallible<Root<MessageEvent>> {
// Dictionaries need to be rooted
// https://github.com/servo/servo/issues/6381
rooted!(in(global.get_cx()) let data = init.data);
let ev = MessageEvent::new(global,
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
data.handle(),
init.origin.clone(),
init.lastEventId.clone());
Ok(ev)
}
}
impl MessageEvent {
pub fn dispatch_jsval(target: &EventTarget,
scope: &GlobalScope,
message: HandleValue) {
let messageevent = MessageEvent::new(
scope,
atom!("message"),
false,
false,
message,
DOMString::new(),
DOMString::new());
messageevent.upcast::<Event>().fire(target);
}
}
impl MessageEventMethods for MessageEvent {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-messageevent-data
unsafe fn Data(&self, _cx: *mut JSContext) -> JSVal {
self.data.get()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-origin
fn Origin(&self) -> DOMString {
self.origin.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid
fn LastEventId(&self) -> DOMString {
self.lastEventId.clone()
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| new_initialized | identifier_name |
messageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEventBinding;
use dom::bindings::codegen::Bindings::MessageEventBinding::MessageEventMethods;
use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::event::Event;
use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use js::jsapi::{HandleValue, Heap, JSContext};
use js::jsval::JSVal;
use servo_atoms::Atom;
#[dom_struct]
pub struct MessageEvent {
event: Event,
data: Heap<JSVal>,
origin: DOMString,
lastEventId: DOMString,
}
impl MessageEvent {
pub fn new_uninitialized(global: &GlobalScope) -> Root<MessageEvent> {
MessageEvent::new_initialized(global,
HandleValue::undefined(),
DOMString::new(),
DOMString::new())
}
pub fn new_initialized(global: &GlobalScope,
data: HandleValue,
origin: DOMString,
lastEventId: DOMString) -> Root<MessageEvent> {
let ev = box MessageEvent {
event: Event::new_inherited(),
data: Heap::new(data.get()),
origin: origin,
lastEventId: lastEventId,
};
reflect_dom_object(ev, global, MessageEventBinding::Wrap)
}
pub fn new(global: &GlobalScope, type_: Atom,
bubbles: bool, cancelable: bool,
data: HandleValue, origin: DOMString, lastEventId: DOMString)
-> Root<MessageEvent> {
let ev = MessageEvent::new_initialized(global, data, origin, lastEventId);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles, cancelable);
}
ev
}
pub fn Constructor(global: &GlobalScope,
type_: DOMString,
init: &MessageEventBinding::MessageEventInit)
-> Fallible<Root<MessageEvent>> {
// Dictionaries need to be rooted
// https://github.com/servo/servo/issues/6381
rooted!(in(global.get_cx()) let data = init.data);
let ev = MessageEvent::new(global,
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
data.handle(),
init.origin.clone(),
init.lastEventId.clone());
Ok(ev)
}
}
impl MessageEvent {
pub fn dispatch_jsval(target: &EventTarget,
scope: &GlobalScope,
message: HandleValue) {
let messageevent = MessageEvent::new(
scope,
atom!("message"),
false,
false,
message,
DOMString::new(),
DOMString::new());
messageevent.upcast::<Event>().fire(target);
}
}
impl MessageEventMethods for MessageEvent {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-messageevent-data
unsafe fn Data(&self, _cx: *mut JSContext) -> JSVal {
self.data.get()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-origin
fn Origin(&self) -> DOMString {
self.origin.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid
fn LastEventId(&self) -> DOMString |
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| {
self.lastEventId.clone()
} | identifier_body |
buffer.rs | use crate::parsing::ParsingContext;
use amq_protocol::frame::{BackToTheBuffer, GenError, GenResult, WriteContext};
use futures_lite::io::{AsyncRead, AsyncWrite};
use std::{
cmp,
io::{self, IoSlice, IoSliceMut},
pin::Pin,
task::{Context, Poll},
};
#[derive(Debug, PartialEq, Clone)]
pub(crate) struct Buffer {
memory: Vec<u8>,
capacity: usize,
position: usize,
end: usize,
available_data: usize,
}
pub(crate) struct Checkpoint {
end: usize,
backwards: bool,
}
impl Buffer {
pub(crate) fn with_capacity(capacity: usize) -> Buffer {
Buffer {
memory: vec![0; capacity],
capacity,
position: 0,
end: 0,
available_data: 0,
}
}
pub(crate) fn checkpoint(&self) -> Checkpoint {
Checkpoint {
end: self.end,
backwards: true,
}
}
pub(crate) fn rollback(&mut self, checkpoint: Checkpoint) {
if checkpoint.end == self.end {
return;
}
if checkpoint.backwards {
if self.end > checkpoint.end {
self.available_data -= self.end - checkpoint.end;
} else {
self.available_data -= self.end + (self.capacity - checkpoint.end);
}
} else if self.end > checkpoint.end {
self.available_data += (self.capacity - self.end) + checkpoint.end;
} else {
self.available_data += checkpoint.end - self.end;
}
self.end = checkpoint.end;
}
pub(crate) fn grow(&mut self, new_size: usize) -> bool {
if self.capacity >= new_size {
return false;
}
let old_capacity = self.capacity;
let growth = new_size - old_capacity;
self.memory.resize(new_size, 0);
self.capacity = new_size;
if self.end <= self.position && self.available_data > 0 {
// We have data and the "tail" was at the beginning of the buffer.
// We need to move it in the new end.
let (old, new) = self.memory.split_at_mut(old_capacity);
if self.end < growth {
// There is enough room in the new end for this whole "tail".
new[..].copy_from_slice(&old[..self.end]);
self.end += old_capacity;
} else {
// Fill the new end with as much data as we can.
// We also update the end pointer to the future right location.
// We still have [growth..old_end] to move into [..new_end]
new[..].copy_from_slice(&old[..growth]);
self.end -= growth;
if self.end < growth {
// Less than half the data is yet to be moved, we can split + copy.
let (start, data) = self.memory.split_at_mut(growth);
start[..].copy_from_slice(&data[..self.end])
} else {
// Not enough room to split + copy, we copy each byte one at a time.
for i in 0..=self.end {
self.memory[i] = self.memory[i + growth];
}
}
}
}
true
}
pub(crate) fn available_data(&self) -> usize {
self.available_data
}
pub(crate) fn available_space(&self) -> usize {
self.capacity - self.available_data
}
pub(crate) fn consume(&mut self, count: usize) -> usize {
let cnt = cmp::min(count, self.available_data());
self.position += cnt;
self.position %= self.capacity;
self.available_data -= cnt;
cnt
}
pub(crate) fn fill(&mut self, count: usize) -> usize {
let cnt = cmp::min(count, self.available_space());
self.end += cnt;
self.end %= self.capacity;
self.available_data += cnt;
cnt
}
pub(crate) fn poll_write_to<T: AsyncWrite>(
&self,
cx: &mut Context<'_>,
writer: Pin<&mut T>,
) -> Poll<io::Result<usize>> {
if self.available_data() == 0 {
Poll::Ready(Ok(0))
} else if self.end > self.position {
writer.poll_write(cx, &self.memory[self.position..self.end])
} else {
writer.poll_write_vectored(
cx,
&[
IoSlice::new(&self.memory[self.position..]),
IoSlice::new(&self.memory[..self.end]),
],
)
}
}
pub(crate) fn poll_read_from<T: AsyncRead>(
&mut self,
cx: &mut Context<'_>,
reader: Pin<&mut T>,
) -> Poll<io::Result<usize>> {
if self.available_space() == 0 {
Poll::Ready(Ok(0))
} else if self.end >= self.position {
let (start, end) = self.memory.split_at_mut(self.end);
reader.poll_read_vectored(
cx,
&mut [
IoSliceMut::new(&mut end[..]),
IoSliceMut::new(&mut start[..self.position]),
][..],
)
} else {
reader.poll_read(cx, &mut self.memory[self.end..self.position])
}
}
pub(crate) fn offset(&self, buf: ParsingContext<'_>) -> usize {
let data = &self.memory[self.position..self.position];
let dataptr = data.as_ptr() as usize;
let bufptr = buf.as_ptr() as usize;
if dataptr < bufptr {
bufptr - dataptr
} else {
let start = &self.memory[..0];
let startptr = start.as_ptr() as usize;
bufptr + self.capacity - self.position - startptr
}
}
pub(crate) fn parsing_context(&self) -> ParsingContext<'_> {
if self.available_data() == 0 {
self.memory[self.end..self.end].into()
} else if self.end > self.position {
self.memory[self.position..self.end].into()
} else {
[&self.memory[self.position..], &self.memory[..self.end]].into()
}
}
}
impl io::Write for &mut Buffer {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
let amt = if self.available_space() == 0 {
0
} else if self.end >= self.position {
let mut space = &mut self.memory[self.end..];
let mut amt = space.write(data)?;
if amt == self.capacity - self.end {
let mut space = &mut self.memory[..self.position];
amt += space.write(&data[amt..])?;
}
amt
} else | ;
self.fill(amt);
Ok(amt)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl BackToTheBuffer for &mut Buffer {
fn reserve_write_use<
Tmp,
Gen: Fn(WriteContext<Self>) -> Result<(WriteContext<Self>, Tmp), GenError>,
Before: Fn(WriteContext<Self>, Tmp) -> GenResult<Self>,
>(
s: WriteContext<Self>,
reserved: usize,
gen: &Gen,
before: &Before,
) -> Result<WriteContext<Self>, GenError> {
if s.write.available_space() < reserved {
return Err(GenError::BufferTooSmall(
reserved - s.write.available_space(),
));
}
let start = s.write.checkpoint();
s.write.fill(reserved);
gen(s).and_then(|(s, tmp)| {
let mut end = s.write.checkpoint();
end.backwards = false;
s.write.rollback(start);
before(s, tmp).map(|s| {
s.write.rollback(end);
s
})
})
}
}
| {
let mut space = &mut self.memory[self.end..self.position];
space.write(data)?
} | conditional_block |
buffer.rs | use crate::parsing::ParsingContext;
use amq_protocol::frame::{BackToTheBuffer, GenError, GenResult, WriteContext};
use futures_lite::io::{AsyncRead, AsyncWrite};
use std::{
cmp,
io::{self, IoSlice, IoSliceMut},
pin::Pin,
task::{Context, Poll},
};
#[derive(Debug, PartialEq, Clone)]
pub(crate) struct Buffer {
memory: Vec<u8>,
capacity: usize,
position: usize,
end: usize,
available_data: usize,
}
pub(crate) struct Checkpoint {
end: usize,
backwards: bool,
}
impl Buffer {
pub(crate) fn with_capacity(capacity: usize) -> Buffer {
Buffer {
memory: vec![0; capacity],
capacity,
position: 0,
end: 0,
available_data: 0,
}
}
pub(crate) fn checkpoint(&self) -> Checkpoint {
Checkpoint {
end: self.end,
backwards: true,
}
}
pub(crate) fn rollback(&mut self, checkpoint: Checkpoint) {
if checkpoint.end == self.end {
return;
}
if checkpoint.backwards {
if self.end > checkpoint.end {
self.available_data -= self.end - checkpoint.end;
} else {
self.available_data -= self.end + (self.capacity - checkpoint.end);
}
} else if self.end > checkpoint.end {
self.available_data += (self.capacity - self.end) + checkpoint.end;
} else {
self.available_data += checkpoint.end - self.end;
}
self.end = checkpoint.end;
}
pub(crate) fn grow(&mut self, new_size: usize) -> bool {
if self.capacity >= new_size {
return false;
}
let old_capacity = self.capacity;
let growth = new_size - old_capacity;
self.memory.resize(new_size, 0);
self.capacity = new_size;
if self.end <= self.position && self.available_data > 0 {
// We have data and the "tail" was at the beginning of the buffer.
// We need to move it in the new end.
let (old, new) = self.memory.split_at_mut(old_capacity);
if self.end < growth {
// There is enough room in the new end for this whole "tail".
new[..].copy_from_slice(&old[..self.end]);
self.end += old_capacity;
} else {
// Fill the new end with as much data as we can.
// We also update the end pointer to the future right location.
// We still have [growth..old_end] to move into [..new_end]
new[..].copy_from_slice(&old[..growth]);
self.end -= growth;
if self.end < growth {
// Less than half the data is yet to be moved, we can split + copy.
let (start, data) = self.memory.split_at_mut(growth);
start[..].copy_from_slice(&data[..self.end])
} else {
// Not enough room to split + copy, we copy each byte one at a time.
for i in 0..=self.end {
self.memory[i] = self.memory[i + growth];
}
}
}
}
true
}
pub(crate) fn available_data(&self) -> usize {
self.available_data
}
pub(crate) fn available_space(&self) -> usize {
self.capacity - self.available_data
}
pub(crate) fn consume(&mut self, count: usize) -> usize {
let cnt = cmp::min(count, self.available_data());
self.position += cnt;
self.position %= self.capacity;
self.available_data -= cnt;
cnt
}
pub(crate) fn fill(&mut self, count: usize) -> usize {
let cnt = cmp::min(count, self.available_space());
self.end += cnt;
self.end %= self.capacity;
self.available_data += cnt;
cnt
}
pub(crate) fn poll_write_to<T: AsyncWrite>(
&self,
cx: &mut Context<'_>,
writer: Pin<&mut T>,
) -> Poll<io::Result<usize>> {
if self.available_data() == 0 {
Poll::Ready(Ok(0))
} else if self.end > self.position {
writer.poll_write(cx, &self.memory[self.position..self.end])
} else {
writer.poll_write_vectored(
cx,
&[
IoSlice::new(&self.memory[self.position..]),
IoSlice::new(&self.memory[..self.end]),
],
)
}
}
pub(crate) fn poll_read_from<T: AsyncRead>(
&mut self,
cx: &mut Context<'_>,
reader: Pin<&mut T>,
) -> Poll<io::Result<usize>> {
if self.available_space() == 0 {
Poll::Ready(Ok(0))
} else if self.end >= self.position {
let (start, end) = self.memory.split_at_mut(self.end);
reader.poll_read_vectored(
cx,
&mut [
IoSliceMut::new(&mut end[..]),
IoSliceMut::new(&mut start[..self.position]),
][..],
)
} else {
reader.poll_read(cx, &mut self.memory[self.end..self.position])
}
}
pub(crate) fn offset(&self, buf: ParsingContext<'_>) -> usize {
let data = &self.memory[self.position..self.position];
let dataptr = data.as_ptr() as usize;
let bufptr = buf.as_ptr() as usize;
if dataptr < bufptr {
bufptr - dataptr
} else {
let start = &self.memory[..0];
let startptr = start.as_ptr() as usize;
bufptr + self.capacity - self.position - startptr
}
}
pub(crate) fn parsing_context(&self) -> ParsingContext<'_> {
if self.available_data() == 0 {
self.memory[self.end..self.end].into()
} else if self.end > self.position {
self.memory[self.position..self.end].into()
} else {
[&self.memory[self.position..], &self.memory[..self.end]].into()
}
}
}
impl io::Write for &mut Buffer {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
let amt = if self.available_space() == 0 {
0
} else if self.end >= self.position {
let mut space = &mut self.memory[self.end..];
let mut amt = space.write(data)?;
if amt == self.capacity - self.end {
let mut space = &mut self.memory[..self.position];
amt += space.write(&data[amt..])?;
}
amt
} else {
let mut space = &mut self.memory[self.end..self.position];
space.write(data)?
};
self.fill(amt);
Ok(amt)
}
fn flush(&mut self) -> io::Result<()> {
Ok(()) | fn reserve_write_use<
Tmp,
Gen: Fn(WriteContext<Self>) -> Result<(WriteContext<Self>, Tmp), GenError>,
Before: Fn(WriteContext<Self>, Tmp) -> GenResult<Self>,
>(
s: WriteContext<Self>,
reserved: usize,
gen: &Gen,
before: &Before,
) -> Result<WriteContext<Self>, GenError> {
if s.write.available_space() < reserved {
return Err(GenError::BufferTooSmall(
reserved - s.write.available_space(),
));
}
let start = s.write.checkpoint();
s.write.fill(reserved);
gen(s).and_then(|(s, tmp)| {
let mut end = s.write.checkpoint();
end.backwards = false;
s.write.rollback(start);
before(s, tmp).map(|s| {
s.write.rollback(end);
s
})
})
}
} | }
}
impl BackToTheBuffer for &mut Buffer { | random_line_split |
buffer.rs | use crate::parsing::ParsingContext;
use amq_protocol::frame::{BackToTheBuffer, GenError, GenResult, WriteContext};
use futures_lite::io::{AsyncRead, AsyncWrite};
use std::{
cmp,
io::{self, IoSlice, IoSliceMut},
pin::Pin,
task::{Context, Poll},
};
#[derive(Debug, PartialEq, Clone)]
pub(crate) struct Buffer {
memory: Vec<u8>,
capacity: usize,
position: usize,
end: usize,
available_data: usize,
}
pub(crate) struct Checkpoint {
end: usize,
backwards: bool,
}
impl Buffer {
pub(crate) fn with_capacity(capacity: usize) -> Buffer {
Buffer {
memory: vec![0; capacity],
capacity,
position: 0,
end: 0,
available_data: 0,
}
}
pub(crate) fn checkpoint(&self) -> Checkpoint {
Checkpoint {
end: self.end,
backwards: true,
}
}
pub(crate) fn rollback(&mut self, checkpoint: Checkpoint) {
if checkpoint.end == self.end {
return;
}
if checkpoint.backwards {
if self.end > checkpoint.end {
self.available_data -= self.end - checkpoint.end;
} else {
self.available_data -= self.end + (self.capacity - checkpoint.end);
}
} else if self.end > checkpoint.end {
self.available_data += (self.capacity - self.end) + checkpoint.end;
} else {
self.available_data += checkpoint.end - self.end;
}
self.end = checkpoint.end;
}
pub(crate) fn | (&mut self, new_size: usize) -> bool {
if self.capacity >= new_size {
return false;
}
let old_capacity = self.capacity;
let growth = new_size - old_capacity;
self.memory.resize(new_size, 0);
self.capacity = new_size;
if self.end <= self.position && self.available_data > 0 {
// We have data and the "tail" was at the beginning of the buffer.
// We need to move it in the new end.
let (old, new) = self.memory.split_at_mut(old_capacity);
if self.end < growth {
// There is enough room in the new end for this whole "tail".
new[..].copy_from_slice(&old[..self.end]);
self.end += old_capacity;
} else {
// Fill the new end with as much data as we can.
// We also update the end pointer to the future right location.
// We still have [growth..old_end] to move into [..new_end]
new[..].copy_from_slice(&old[..growth]);
self.end -= growth;
if self.end < growth {
// Less than half the data is yet to be moved, we can split + copy.
let (start, data) = self.memory.split_at_mut(growth);
start[..].copy_from_slice(&data[..self.end])
} else {
// Not enough room to split + copy, we copy each byte one at a time.
for i in 0..=self.end {
self.memory[i] = self.memory[i + growth];
}
}
}
}
true
}
pub(crate) fn available_data(&self) -> usize {
self.available_data
}
pub(crate) fn available_space(&self) -> usize {
self.capacity - self.available_data
}
pub(crate) fn consume(&mut self, count: usize) -> usize {
let cnt = cmp::min(count, self.available_data());
self.position += cnt;
self.position %= self.capacity;
self.available_data -= cnt;
cnt
}
pub(crate) fn fill(&mut self, count: usize) -> usize {
let cnt = cmp::min(count, self.available_space());
self.end += cnt;
self.end %= self.capacity;
self.available_data += cnt;
cnt
}
pub(crate) fn poll_write_to<T: AsyncWrite>(
&self,
cx: &mut Context<'_>,
writer: Pin<&mut T>,
) -> Poll<io::Result<usize>> {
if self.available_data() == 0 {
Poll::Ready(Ok(0))
} else if self.end > self.position {
writer.poll_write(cx, &self.memory[self.position..self.end])
} else {
writer.poll_write_vectored(
cx,
&[
IoSlice::new(&self.memory[self.position..]),
IoSlice::new(&self.memory[..self.end]),
],
)
}
}
pub(crate) fn poll_read_from<T: AsyncRead>(
&mut self,
cx: &mut Context<'_>,
reader: Pin<&mut T>,
) -> Poll<io::Result<usize>> {
if self.available_space() == 0 {
Poll::Ready(Ok(0))
} else if self.end >= self.position {
let (start, end) = self.memory.split_at_mut(self.end);
reader.poll_read_vectored(
cx,
&mut [
IoSliceMut::new(&mut end[..]),
IoSliceMut::new(&mut start[..self.position]),
][..],
)
} else {
reader.poll_read(cx, &mut self.memory[self.end..self.position])
}
}
pub(crate) fn offset(&self, buf: ParsingContext<'_>) -> usize {
let data = &self.memory[self.position..self.position];
let dataptr = data.as_ptr() as usize;
let bufptr = buf.as_ptr() as usize;
if dataptr < bufptr {
bufptr - dataptr
} else {
let start = &self.memory[..0];
let startptr = start.as_ptr() as usize;
bufptr + self.capacity - self.position - startptr
}
}
pub(crate) fn parsing_context(&self) -> ParsingContext<'_> {
if self.available_data() == 0 {
self.memory[self.end..self.end].into()
} else if self.end > self.position {
self.memory[self.position..self.end].into()
} else {
[&self.memory[self.position..], &self.memory[..self.end]].into()
}
}
}
impl io::Write for &mut Buffer {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
let amt = if self.available_space() == 0 {
0
} else if self.end >= self.position {
let mut space = &mut self.memory[self.end..];
let mut amt = space.write(data)?;
if amt == self.capacity - self.end {
let mut space = &mut self.memory[..self.position];
amt += space.write(&data[amt..])?;
}
amt
} else {
let mut space = &mut self.memory[self.end..self.position];
space.write(data)?
};
self.fill(amt);
Ok(amt)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl BackToTheBuffer for &mut Buffer {
fn reserve_write_use<
Tmp,
Gen: Fn(WriteContext<Self>) -> Result<(WriteContext<Self>, Tmp), GenError>,
Before: Fn(WriteContext<Self>, Tmp) -> GenResult<Self>,
>(
s: WriteContext<Self>,
reserved: usize,
gen: &Gen,
before: &Before,
) -> Result<WriteContext<Self>, GenError> {
if s.write.available_space() < reserved {
return Err(GenError::BufferTooSmall(
reserved - s.write.available_space(),
));
}
let start = s.write.checkpoint();
s.write.fill(reserved);
gen(s).and_then(|(s, tmp)| {
let mut end = s.write.checkpoint();
end.backwards = false;
s.write.rollback(start);
before(s, tmp).map(|s| {
s.write.rollback(end);
s
})
})
}
}
| grow | identifier_name |
buffer.rs | use crate::parsing::ParsingContext;
use amq_protocol::frame::{BackToTheBuffer, GenError, GenResult, WriteContext};
use futures_lite::io::{AsyncRead, AsyncWrite};
use std::{
cmp,
io::{self, IoSlice, IoSliceMut},
pin::Pin,
task::{Context, Poll},
};
#[derive(Debug, PartialEq, Clone)]
pub(crate) struct Buffer {
memory: Vec<u8>,
capacity: usize,
position: usize,
end: usize,
available_data: usize,
}
pub(crate) struct Checkpoint {
end: usize,
backwards: bool,
}
impl Buffer {
pub(crate) fn with_capacity(capacity: usize) -> Buffer {
Buffer {
memory: vec![0; capacity],
capacity,
position: 0,
end: 0,
available_data: 0,
}
}
pub(crate) fn checkpoint(&self) -> Checkpoint {
Checkpoint {
end: self.end,
backwards: true,
}
}
pub(crate) fn rollback(&mut self, checkpoint: Checkpoint) {
if checkpoint.end == self.end {
return;
}
if checkpoint.backwards {
if self.end > checkpoint.end {
self.available_data -= self.end - checkpoint.end;
} else {
self.available_data -= self.end + (self.capacity - checkpoint.end);
}
} else if self.end > checkpoint.end {
self.available_data += (self.capacity - self.end) + checkpoint.end;
} else {
self.available_data += checkpoint.end - self.end;
}
self.end = checkpoint.end;
}
pub(crate) fn grow(&mut self, new_size: usize) -> bool {
if self.capacity >= new_size {
return false;
}
let old_capacity = self.capacity;
let growth = new_size - old_capacity;
self.memory.resize(new_size, 0);
self.capacity = new_size;
if self.end <= self.position && self.available_data > 0 {
// We have data and the "tail" was at the beginning of the buffer.
// We need to move it in the new end.
let (old, new) = self.memory.split_at_mut(old_capacity);
if self.end < growth {
// There is enough room in the new end for this whole "tail".
new[..].copy_from_slice(&old[..self.end]);
self.end += old_capacity;
} else {
// Fill the new end with as much data as we can.
// We also update the end pointer to the future right location.
// We still have [growth..old_end] to move into [..new_end]
new[..].copy_from_slice(&old[..growth]);
self.end -= growth;
if self.end < growth {
// Less than half the data is yet to be moved, we can split + copy.
let (start, data) = self.memory.split_at_mut(growth);
start[..].copy_from_slice(&data[..self.end])
} else {
// Not enough room to split + copy, we copy each byte one at a time.
for i in 0..=self.end {
self.memory[i] = self.memory[i + growth];
}
}
}
}
true
}
pub(crate) fn available_data(&self) -> usize {
self.available_data
}
pub(crate) fn available_space(&self) -> usize {
self.capacity - self.available_data
}
pub(crate) fn consume(&mut self, count: usize) -> usize {
let cnt = cmp::min(count, self.available_data());
self.position += cnt;
self.position %= self.capacity;
self.available_data -= cnt;
cnt
}
pub(crate) fn fill(&mut self, count: usize) -> usize |
pub(crate) fn poll_write_to<T: AsyncWrite>(
&self,
cx: &mut Context<'_>,
writer: Pin<&mut T>,
) -> Poll<io::Result<usize>> {
if self.available_data() == 0 {
Poll::Ready(Ok(0))
} else if self.end > self.position {
writer.poll_write(cx, &self.memory[self.position..self.end])
} else {
writer.poll_write_vectored(
cx,
&[
IoSlice::new(&self.memory[self.position..]),
IoSlice::new(&self.memory[..self.end]),
],
)
}
}
pub(crate) fn poll_read_from<T: AsyncRead>(
&mut self,
cx: &mut Context<'_>,
reader: Pin<&mut T>,
) -> Poll<io::Result<usize>> {
if self.available_space() == 0 {
Poll::Ready(Ok(0))
} else if self.end >= self.position {
let (start, end) = self.memory.split_at_mut(self.end);
reader.poll_read_vectored(
cx,
&mut [
IoSliceMut::new(&mut end[..]),
IoSliceMut::new(&mut start[..self.position]),
][..],
)
} else {
reader.poll_read(cx, &mut self.memory[self.end..self.position])
}
}
pub(crate) fn offset(&self, buf: ParsingContext<'_>) -> usize {
let data = &self.memory[self.position..self.position];
let dataptr = data.as_ptr() as usize;
let bufptr = buf.as_ptr() as usize;
if dataptr < bufptr {
bufptr - dataptr
} else {
let start = &self.memory[..0];
let startptr = start.as_ptr() as usize;
bufptr + self.capacity - self.position - startptr
}
}
pub(crate) fn parsing_context(&self) -> ParsingContext<'_> {
if self.available_data() == 0 {
self.memory[self.end..self.end].into()
} else if self.end > self.position {
self.memory[self.position..self.end].into()
} else {
[&self.memory[self.position..], &self.memory[..self.end]].into()
}
}
}
impl io::Write for &mut Buffer {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
let amt = if self.available_space() == 0 {
0
} else if self.end >= self.position {
let mut space = &mut self.memory[self.end..];
let mut amt = space.write(data)?;
if amt == self.capacity - self.end {
let mut space = &mut self.memory[..self.position];
amt += space.write(&data[amt..])?;
}
amt
} else {
let mut space = &mut self.memory[self.end..self.position];
space.write(data)?
};
self.fill(amt);
Ok(amt)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl BackToTheBuffer for &mut Buffer {
fn reserve_write_use<
Tmp,
Gen: Fn(WriteContext<Self>) -> Result<(WriteContext<Self>, Tmp), GenError>,
Before: Fn(WriteContext<Self>, Tmp) -> GenResult<Self>,
>(
s: WriteContext<Self>,
reserved: usize,
gen: &Gen,
before: &Before,
) -> Result<WriteContext<Self>, GenError> {
if s.write.available_space() < reserved {
return Err(GenError::BufferTooSmall(
reserved - s.write.available_space(),
));
}
let start = s.write.checkpoint();
s.write.fill(reserved);
gen(s).and_then(|(s, tmp)| {
let mut end = s.write.checkpoint();
end.backwards = false;
s.write.rollback(start);
before(s, tmp).map(|s| {
s.write.rollback(end);
s
})
})
}
}
| {
let cnt = cmp::min(count, self.available_space());
self.end += cnt;
self.end %= self.capacity;
self.available_data += cnt;
cnt
} | identifier_body |
scalar.rs | use std::cmp;
use std::fmt;
use std::ops;
use num;
use math::common::LinearInterpolate;
pub type IntScalar = i32;
#[cfg(not(feature = "float64"))]
pub type FloatScalar = f32;
#[cfg(feature = "float64")]
pub type FloatScalar = f64;
pub trait BaseNum where
Self: Copy + Clone + fmt::Debug + cmp::PartialOrd,
Self: num::Num + num::NumCast + num::ToPrimitive,
Self: ops::AddAssign + ops::SubAssign + ops::MulAssign + ops::DivAssign {}
pub trait BaseFloat: BaseNum + num::Float + num::Signed {}
pub trait BaseInt: BaseNum {}
impl BaseNum for i8 {}
impl BaseNum for i16 {}
impl BaseNum for i32 {}
impl BaseNum for i64 {}
impl BaseNum for isize {}
impl BaseNum for u8 {}
impl BaseNum for u16 {}
impl BaseNum for u32 {}
impl BaseNum for u64 {}
impl BaseNum for usize {}
impl BaseNum for f32 {}
impl BaseNum for f64 {}
impl BaseInt for i8 {}
impl BaseInt for i16 {}
impl BaseInt for i32 {}
impl BaseInt for i64 {}
impl BaseInt for isize {}
impl BaseInt for u8 {}
impl BaseInt for u16 {}
impl BaseInt for u32 {}
impl BaseInt for u64 {}
impl BaseInt for usize {}
impl BaseFloat for f32 {}
impl BaseFloat for f64 {}
pub fn partial_min<T: cmp::PartialOrd>(a: T, b: T) -> T |
pub fn partial_max<T: cmp::PartialOrd>(a: T, b: T) -> T {
if a > b {
a
} else {
b
}
}
impl LinearInterpolate for f32 {
type Scalar = f32;
}
impl LinearInterpolate for f64 {
type Scalar = f64;
} | {
if a < b {
a
} else {
b
}
} | identifier_body |
scalar.rs | use std::cmp;
use std::fmt;
use std::ops;
use num;
use math::common::LinearInterpolate;
pub type IntScalar = i32;
#[cfg(not(feature = "float64"))]
pub type FloatScalar = f32;
#[cfg(feature = "float64")]
pub type FloatScalar = f64;
pub trait BaseNum where
Self: Copy + Clone + fmt::Debug + cmp::PartialOrd,
Self: num::Num + num::NumCast + num::ToPrimitive,
Self: ops::AddAssign + ops::SubAssign + ops::MulAssign + ops::DivAssign {}
pub trait BaseFloat: BaseNum + num::Float + num::Signed {}
pub trait BaseInt: BaseNum {}
impl BaseNum for i8 {}
impl BaseNum for i16 {}
impl BaseNum for i32 {}
impl BaseNum for i64 {}
impl BaseNum for isize {}
impl BaseNum for u8 {}
impl BaseNum for u16 {}
impl BaseNum for u32 {}
impl BaseNum for u64 {}
impl BaseNum for usize {}
impl BaseNum for f32 {}
impl BaseNum for f64 {}
impl BaseInt for i8 {}
impl BaseInt for i16 {}
impl BaseInt for i32 {}
impl BaseInt for i64 {}
impl BaseInt for isize {}
impl BaseInt for u8 {}
impl BaseInt for u16 {}
impl BaseInt for u32 {}
impl BaseInt for u64 {}
impl BaseInt for usize {}
impl BaseFloat for f32 {}
impl BaseFloat for f64 {}
pub fn partial_min<T: cmp::PartialOrd>(a: T, b: T) -> T {
if a < b {
a
} else {
b
}
} | if a > b {
a
} else {
b
}
}
impl LinearInterpolate for f32 {
type Scalar = f32;
}
impl LinearInterpolate for f64 {
type Scalar = f64;
} |
pub fn partial_max<T: cmp::PartialOrd>(a: T, b: T) -> T { | random_line_split |
scalar.rs | use std::cmp;
use std::fmt;
use std::ops;
use num;
use math::common::LinearInterpolate;
pub type IntScalar = i32;
#[cfg(not(feature = "float64"))]
pub type FloatScalar = f32;
#[cfg(feature = "float64")]
pub type FloatScalar = f64;
pub trait BaseNum where
Self: Copy + Clone + fmt::Debug + cmp::PartialOrd,
Self: num::Num + num::NumCast + num::ToPrimitive,
Self: ops::AddAssign + ops::SubAssign + ops::MulAssign + ops::DivAssign {}
pub trait BaseFloat: BaseNum + num::Float + num::Signed {}
pub trait BaseInt: BaseNum {}
impl BaseNum for i8 {}
impl BaseNum for i16 {}
impl BaseNum for i32 {}
impl BaseNum for i64 {}
impl BaseNum for isize {}
impl BaseNum for u8 {}
impl BaseNum for u16 {}
impl BaseNum for u32 {}
impl BaseNum for u64 {}
impl BaseNum for usize {}
impl BaseNum for f32 {}
impl BaseNum for f64 {}
impl BaseInt for i8 {}
impl BaseInt for i16 {}
impl BaseInt for i32 {}
impl BaseInt for i64 {}
impl BaseInt for isize {}
impl BaseInt for u8 {}
impl BaseInt for u16 {}
impl BaseInt for u32 {}
impl BaseInt for u64 {}
impl BaseInt for usize {}
impl BaseFloat for f32 {}
impl BaseFloat for f64 {}
pub fn partial_min<T: cmp::PartialOrd>(a: T, b: T) -> T {
if a < b {
a
} else |
}
pub fn partial_max<T: cmp::PartialOrd>(a: T, b: T) -> T {
if a > b {
a
} else {
b
}
}
impl LinearInterpolate for f32 {
type Scalar = f32;
}
impl LinearInterpolate for f64 {
type Scalar = f64;
} | {
b
} | conditional_block |
scalar.rs | use std::cmp;
use std::fmt;
use std::ops;
use num;
use math::common::LinearInterpolate;
pub type IntScalar = i32;
#[cfg(not(feature = "float64"))]
pub type FloatScalar = f32;
#[cfg(feature = "float64")]
pub type FloatScalar = f64;
pub trait BaseNum where
Self: Copy + Clone + fmt::Debug + cmp::PartialOrd,
Self: num::Num + num::NumCast + num::ToPrimitive,
Self: ops::AddAssign + ops::SubAssign + ops::MulAssign + ops::DivAssign {}
pub trait BaseFloat: BaseNum + num::Float + num::Signed {}
pub trait BaseInt: BaseNum {}
impl BaseNum for i8 {}
impl BaseNum for i16 {}
impl BaseNum for i32 {}
impl BaseNum for i64 {}
impl BaseNum for isize {}
impl BaseNum for u8 {}
impl BaseNum for u16 {}
impl BaseNum for u32 {}
impl BaseNum for u64 {}
impl BaseNum for usize {}
impl BaseNum for f32 {}
impl BaseNum for f64 {}
impl BaseInt for i8 {}
impl BaseInt for i16 {}
impl BaseInt for i32 {}
impl BaseInt for i64 {}
impl BaseInt for isize {}
impl BaseInt for u8 {}
impl BaseInt for u16 {}
impl BaseInt for u32 {}
impl BaseInt for u64 {}
impl BaseInt for usize {}
impl BaseFloat for f32 {}
impl BaseFloat for f64 {}
pub fn | <T: cmp::PartialOrd>(a: T, b: T) -> T {
if a < b {
a
} else {
b
}
}
pub fn partial_max<T: cmp::PartialOrd>(a: T, b: T) -> T {
if a > b {
a
} else {
b
}
}
impl LinearInterpolate for f32 {
type Scalar = f32;
}
impl LinearInterpolate for f64 {
type Scalar = f64;
} | partial_min | identifier_name |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn | () {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
//println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("You guessed: {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
| main | identifier_name |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
//println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue, | println!("You guessed: {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
} | };
| random_line_split |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() | println!("You guessed: {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
| {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
//println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
| identifier_body |
problem3.rs | /* Run tests with;
*
* rustc --test problem3.rs ;./problem3
*
*/
fn prime_factors(mut n: i64) -> Vec<i64> {
let mut divisor = 2;
let mut factors: Vec<i64> = Vec::new();
while divisor <= (n as f64).sqrt() as i64 {
if n%divisor == 0 | else {
divisor += 1;
}
}
factors.push(n);
return factors;
}
pub fn main() {
let factors = prime_factors(600851475143);
let largest_prime_factor = factors.last().unwrap();
println!("largest prime factor == {}", largest_prime_factor);
}
#[cfg(test)]
mod test {
use super::prime_factors;
#[test]
fn correct_answer() {
let factors = prime_factors(600851475143);
let expected_answer = 6857;
let computed_answer = *factors.last().unwrap();
assert_eq!(computed_answer, expected_answer);
}
}
| {
factors.push(divisor);
n = n / divisor;
divisor = 2;
} | conditional_block |
problem3.rs | /* Run tests with;
*
* rustc --test problem3.rs ;./problem3
*
*/
fn prime_factors(mut n: i64) -> Vec<i64> {
let mut divisor = 2; | n = n / divisor;
divisor = 2;
} else {
divisor += 1;
}
}
factors.push(n);
return factors;
}
pub fn main() {
let factors = prime_factors(600851475143);
let largest_prime_factor = factors.last().unwrap();
println!("largest prime factor == {}", largest_prime_factor);
}
#[cfg(test)]
mod test {
use super::prime_factors;
#[test]
fn correct_answer() {
let factors = prime_factors(600851475143);
let expected_answer = 6857;
let computed_answer = *factors.last().unwrap();
assert_eq!(computed_answer, expected_answer);
}
} | let mut factors: Vec<i64> = Vec::new();
while divisor <= (n as f64).sqrt() as i64 {
if n%divisor == 0 {
factors.push(divisor); | random_line_split |
problem3.rs | /* Run tests with;
*
* rustc --test problem3.rs ;./problem3
*
*/
fn prime_factors(mut n: i64) -> Vec<i64> {
let mut divisor = 2;
let mut factors: Vec<i64> = Vec::new();
while divisor <= (n as f64).sqrt() as i64 {
if n%divisor == 0 {
factors.push(divisor);
n = n / divisor;
divisor = 2;
} else {
divisor += 1;
}
}
factors.push(n);
return factors;
}
pub fn main() |
#[cfg(test)]
mod test {
use super::prime_factors;
#[test]
fn correct_answer() {
let factors = prime_factors(600851475143);
let expected_answer = 6857;
let computed_answer = *factors.last().unwrap();
assert_eq!(computed_answer, expected_answer);
}
}
| {
let factors = prime_factors(600851475143);
let largest_prime_factor = factors.last().unwrap();
println!("largest prime factor == {}", largest_prime_factor);
} | identifier_body |
problem3.rs | /* Run tests with;
*
* rustc --test problem3.rs ;./problem3
*
*/
fn prime_factors(mut n: i64) -> Vec<i64> {
let mut divisor = 2;
let mut factors: Vec<i64> = Vec::new();
while divisor <= (n as f64).sqrt() as i64 {
if n%divisor == 0 {
factors.push(divisor);
n = n / divisor;
divisor = 2;
} else {
divisor += 1;
}
}
factors.push(n);
return factors;
}
pub fn | () {
let factors = prime_factors(600851475143);
let largest_prime_factor = factors.last().unwrap();
println!("largest prime factor == {}", largest_prime_factor);
}
#[cfg(test)]
mod test {
use super::prime_factors;
#[test]
fn correct_answer() {
let factors = prime_factors(600851475143);
let expected_answer = 6857;
let computed_answer = *factors.last().unwrap();
assert_eq!(computed_answer, expected_answer);
}
}
| main | identifier_name |
issue-52742.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.
#![feature(nll)]
#![feature(in_band_lifetimes)]
struct Foo<'a, 'b> {
x: &'a u32,
y: &'b u32,
}
struct Bar<'b> { | impl Foo<'_, '_> {
fn take_bar(&mut self, b: Bar<'_>) {
self.y = b.z
//~^ ERROR unsatisfied lifetime constraints
}
}
fn main() { } | z: &'b u32
}
| random_line_split |
issue-52742.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.
#![feature(nll)]
#![feature(in_band_lifetimes)]
struct | <'a, 'b> {
x: &'a u32,
y: &'b u32,
}
struct Bar<'b> {
z: &'b u32
}
impl Foo<'_, '_> {
fn take_bar(&mut self, b: Bar<'_>) {
self.y = b.z
//~^ ERROR unsatisfied lifetime constraints
}
}
fn main() { }
| Foo | identifier_name |
issue-52742.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.
#![feature(nll)]
#![feature(in_band_lifetimes)]
struct Foo<'a, 'b> {
x: &'a u32,
y: &'b u32,
}
struct Bar<'b> {
z: &'b u32
}
impl Foo<'_, '_> {
fn take_bar(&mut self, b: Bar<'_>) |
}
fn main() { }
| {
self.y = b.z
//~^ ERROR unsatisfied lifetime constraints
} | identifier_body |
loader.rs | One of the immediate problems with linking the same library together twice
//! in the same problem is dealing with duplicate symbols. The primary way to
//! deal with this in rustc is to add hashes to the end of each symbol.
//!
//! In order to force hashes to change between versions of a library, if
//! desired, the compiler exposes an option `-C metadata=foo`, which is used to
//! initially seed each symbol hash. The string `foo` is prepended to each
//! string-to-hash to ensure that symbols change over time.
//!
//! ## Loading transitive dependencies
//!
//! Dealing with same-named-but-distinct crates is not just a local problem, but
//! one that also needs to be dealt with for transitive dependencies. Note that
//! in the letter above `--extern` flags only apply to the *local* set of
//! dependencies, not the upstream transitive dependencies. Consider this
//! dependency graph:
//!
//! ```notrust
//! A.1 A.2
//! | |
//! | |
//! B C
//! \ /
//! \ /
//! D
//! ```
//!
//! In this scenario, when we compile `D`, we need to be able to distinctly
//! resolve `A.1` and `A.2`, but an `--extern` flag cannot apply to these
//! transitive dependencies.
//!
//! Note that the key idea here is that `B` and `C` are both *already compiled*.
//! That is, they have already resolved their dependencies. Due to unrelated
//! technical reasons, when a library is compiled, it is only compatible with
//! the *exact same* version of the upstream libraries it was compiled against.
//! We use the "Strict Version Hash" to identify the exact copy of an upstream
//! library.
//!
//! With this knowledge, we know that `B` and `C` will depend on `A` with
//! different SVH values, so we crawl the normal `-L` paths looking for
//! `liba*.rlib` and filter based on the contained SVH.
//!
//! In the end, this ends up not needing `--extern` to specify upstream
//! transitive dependencies.
//!
//! # Wrapping up
//!
//! That's the general overview of loading crates in the compiler, but it's by
//! no means all of the necessary details. Take a look at the rest of
//! metadata::loader or metadata::creader for all the juicy details!
use back::archive::{METADATA_FILENAME};
use back::svh::Svh;
use driver::session::Session;
use llvm;
use llvm::{False, ObjectFile, mk_section_iter};
use llvm::archive_ro::ArchiveRO;
use metadata::cstore::{MetadataBlob, MetadataVec, MetadataArchive};
use metadata::decoder;
use metadata::encoder;
use metadata::filesearch::{FileSearch, FileMatches, FileDoesntMatch};
use syntax::codemap::Span;
use syntax::diagnostic::SpanHandler;
use util::fs;
use std::c_str::ToCStr;
use std::cmp;
use std::collections::hash_map::{Occupied, Vacant};
use std::collections::{HashMap, HashSet};
use std::io::fs::PathExtensions;
use std::io;
use std::ptr;
use std::slice;
use std::string;
use std::time::Duration;
use flate;
pub struct CrateMismatch {
path: Path,
got: String,
}
pub struct Context<'a> {
pub sess: &'a Session,
pub span: Span,
pub ident: &'a str,
pub crate_name: &'a str,
pub hash: Option<&'a Svh>,
pub triple: &'a str,
pub filesearch: FileSearch<'a>,
pub root: &'a Option<CratePaths>,
pub rejected_via_hash: Vec<CrateMismatch>,
pub rejected_via_triple: Vec<CrateMismatch>,
pub should_match_name: bool,
}
pub struct Library {
pub dylib: Option<Path>,
pub rlib: Option<Path>,
pub metadata: MetadataBlob,
}
pub struct ArchiveMetadata {
_archive: ArchiveRO,
// points into self._archive
data: *const [u8],
}
pub struct CratePaths {
pub ident: String,
pub dylib: Option<Path>,
pub rlib: Option<Path>
}
impl CratePaths {
fn paths(&self) -> Vec<Path> {
match (&self.dylib, &self.rlib) {
(&None, &None) => vec!(),
(&Some(ref p), &None) |
(&None, &Some(ref p)) => vec!(p.clone()),
(&Some(ref p1), &Some(ref p2)) => vec!(p1.clone(), p2.clone()),
}
}
}
impl<'a> Context<'a> {
pub fn maybe_load_library_crate(&mut self) -> Option<Library> {
self.find_library_crate()
}
pub fn load_library_crate(&mut self) -> Library {
match self.find_library_crate() {
Some(t) => t,
None => {
self.report_load_errs();
unreachable!()
}
}
}
pub fn report_load_errs(&mut self) {
let message = if self.rejected_via_hash.len() > 0 {
format!("found possibly newer version of crate `{}`",
self.ident)
} else if self.rejected_via_triple.len() > 0 {
format!("found incorrect triple for crate `{}`", self.ident)
} else {
format!("can't find crate for `{}`", self.ident)
};
let message = match self.root {
&None => message,
&Some(ref r) => format!("{} which `{}` depends on",
message, r.ident)
};
self.sess.span_err(self.span, message.as_slice());
let mismatches = self.rejected_via_triple.iter();
if self.rejected_via_triple.len() > 0 {
self.sess.span_note(self.span,
format!("expected triple of {}",
self.triple).as_slice());
for (i, &CrateMismatch{ ref path, ref got }) in mismatches.enumerate() {
self.sess.fileline_note(self.span,
format!("crate `{}` path {}{}, triple {}: {}",
self.ident, "#", i+1, got, path.display()).as_slice());
}
}
if self.rejected_via_hash.len() > 0 {
self.sess.span_note(self.span, "perhaps this crate needs \
to be recompiled?");
let mismatches = self.rejected_via_hash.iter();
for (i, &CrateMismatch{ ref path,.. }) in mismatches.enumerate() {
self.sess.fileline_note(self.span,
format!("crate `{}` path {}{}: {}",
self.ident, "#", i+1, path.display()).as_slice());
}
match self.root {
&None => {}
&Some(ref r) => {
for (i, path) in r.paths().iter().enumerate() {
self.sess.fileline_note(self.span,
format!("crate `{}` path #{}: {}",
r.ident, i+1, path.display()).as_slice());
}
}
}
}
self.sess.abort_if_errors();
}
fn find_library_crate(&mut self) -> Option<Library> {
// If an SVH is specified, then this is a transitive dependency that
// must be loaded via -L plus some filtering.
if self.hash.is_none() {
self.should_match_name = false;
match self.find_commandline_library() {
Some(l) => return Some(l),
None => {}
}
self.should_match_name = true;
}
let dypair = self.dylibname();
// want: crate_name.dir_part() + prefix + crate_name.file_part + "-"
let dylib_prefix = format!("{}{}", dypair.ref0(), self.crate_name);
let rlib_prefix = format!("lib{}", self.crate_name);
let mut candidates = HashMap::new();
// First, find all possible candidate rlibs and dylibs purely based on
// the name of the files themselves. We're trying to match against an
// exact crate name and a possibly an exact hash.
//
// During this step, we can filter all found libraries based on the
// name and id found in the crate id (we ignore the path portion for
// filename matching), as well as the exact hash (if specified). If we
// end up having many candidates, we must look at the metadata to
// perform exact matches against hashes/crate ids. Note that opening up
// the metadata is where we do an exact match against the full contents
// of the crate id (path/name/id).
//
// The goal of this step is to look at as little metadata as possible.
self.filesearch.search(|path| {
let file = match path.filename_str() {
None => return FileDoesntMatch,
Some(file) => file,
};
let (hash, rlib) = if file.starts_with(rlib_prefix.as_slice()) &&
file.ends_with(".rlib") {
(file.slice(rlib_prefix.len(), file.len() - ".rlib".len()),
true)
} else if file.starts_with(dylib_prefix.as_slice()) &&
file.ends_with(dypair.ref1().as_slice()) {
(file.slice(dylib_prefix.len(), file.len() - dypair.ref1().len()),
false)
} else {
return FileDoesntMatch
};
info!("lib candidate: {}", path.display());
let slot = match candidates.entry(hash.to_string()) {
Occupied(entry) => entry.into_mut(),
Vacant(entry) => entry.set((HashSet::new(), HashSet::new())),
};
let (ref mut rlibs, ref mut dylibs) = *slot;
if rlib {
rlibs.insert(fs::realpath(path).unwrap());
} else {
dylibs.insert(fs::realpath(path).unwrap());
}
FileMatches
});
// We have now collected all known libraries into a set of candidates
// keyed of the filename hash listed. For each filename, we also have a
// list of rlibs/dylibs that apply. Here, we map each of these lists
// (per hash), to a Library candidate for returning.
//
// A Library candidate is created if the metadata for the set of
// libraries corresponds to the crate id and hash criteria that this
// search is being performed for.
let mut libraries = Vec::new();
for (_hash, (rlibs, dylibs)) in candidates.into_iter() {
let mut metadata = None;
let rlib = self.extract_one(rlibs, "rlib", &mut metadata);
let dylib = self.extract_one(dylibs, "dylib", &mut metadata);
match metadata {
Some(metadata) => {
libraries.push(Library {
dylib: dylib,
rlib: rlib,
metadata: metadata,
})
}
None => {}
}
}
// Having now translated all relevant found hashes into libraries, see
// what we've got and figure out if we found multiple candidates for
// libraries or not.
match libraries.len() {
0 => None,
1 => Some(libraries.into_iter().next().unwrap()),
_ => {
self.sess.span_err(self.span,
format!("multiple matching crates for `{}`",
self.crate_name).as_slice());
self.sess.note("candidates:");
for lib in libraries.iter() {
match lib.dylib {
Some(ref p) => {
self.sess.note(format!("path: {}",
p.display()).as_slice());
}
None => {}
}
match lib.rlib {
Some(ref p) => {
self.sess.note(format!("path: {}",
p.display()).as_slice());
}
None => {}
}
let data = lib.metadata.as_slice();
let name = decoder::get_crate_name(data);
note_crate_name(self.sess.diagnostic(), name.as_slice());
}
None
}
}
}
// Attempts to extract *one* library from the set `m`. If the set has no
// elements, `None` is returned. If the set has more than one element, then
// the errors and notes are emitted about the set of libraries.
//
// With only one library in the set, this function will extract it, and then
// read the metadata from it if `*slot` is `None`. If the metadata couldn't
// be read, it is assumed that the file isn't a valid rust library (no
// errors are emitted).
fn extract_one(&mut self, m: HashSet<Path>, flavor: &str,
slot: &mut Option<MetadataBlob>) -> Option<Path> {
let mut ret = None::<Path>;
let mut error = 0u;
if slot.is_some() {
// FIXME(#10786): for an optimization, we only read one of the
// library's metadata sections. In theory we should
// read both, but reading dylib metadata is quite
// slow.
if m.len() == 0 {
return None
} else if m.len() == 1 {
return Some(m.into_iter().next().unwrap())
}
}
for lib in m.into_iter() {
info!("{} reading metadata from: {}", flavor, lib.display());
let metadata = match get_metadata_section(self.sess.target.target.options.is_like_osx,
&lib) {
Ok(blob) => {
if self.crate_matches(blob.as_slice(), &lib) {
blob
} else {
info!("metadata mismatch");
continue
}
}
Err(_) => {
info!("no metadata found");
continue
}
};
if ret.is_some() {
self.sess.span_err(self.span,
format!("multiple {} candidates for `{}` \
found",
flavor,
self.crate_name).as_slice());
self.sess.span_note(self.span,
format!(r"candidate #1: {}",
ret.as_ref().unwrap()
.display()).as_slice());
error = 1;
ret = None;
}
if error > 0 {
error += 1;
self.sess.span_note(self.span,
format!(r"candidate #{}: {}", error,
lib.display()).as_slice());
continue
}
*slot = Some(metadata);
ret = Some(lib);
}
return if error > 0 {None} else {ret}
}
fn crate_matches(&mut self, crate_data: &[u8], libpath: &Path) -> bool {
if self.should_match_name {
match decoder::maybe_get_crate_name(crate_data) {
Some(ref name) if self.crate_name == name.as_slice() => {}
_ => { info!("Rejecting via crate name"); return false }
}
}
let hash = match decoder::maybe_get_crate_hash(crate_data) {
Some(hash) => hash, None => {
info!("Rejecting via lack of crate hash");
return false;
}
};
let triple = match decoder::get_crate_triple(crate_data) {
None => |
Some(t) => t,
};
if triple.as_slice()!= self.triple {
info!("Rejecting via crate triple: expected {} got {}", self.triple, triple);
self.rejected_via_triple.push(CrateMismatch {
path: libpath.clone(),
got: triple.to_string()
});
return false;
}
match self.hash {
None => true,
Some(myhash) => {
if *myhash!= hash {
info!("Rejecting via hash: expected {} got {}", *myhash, hash);
self.rejected_via_hash.push(CrateMismatch {
path: libpath.clone(),
got: myhash.as_str().to_string()
});
false
} else {
true
}
}
}
}
// Returns the corresponding (prefix, suffix) that files need to have for
// dynamic libraries
fn dylibname(&self) -> (String, String) {
let t = &self.sess.target.target;
(t.options.dll_prefix.clone(), t.options.dll_suffix.clone())
}
fn find_commandline_library(&mut self) -> Option<Library> {
let locs = match self.sess.opts.externs.find_equiv(self.crate_name) {
Some(s) => s,
None => return None,
};
// First, filter out all libraries that look suspicious. We only accept
// files which actually exist that have the correct naming scheme for
// rlibs/dylibs.
let sess = self.sess;
| { debug!("triple not present"); return false } | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.